content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def solution():
T = int(input())
for t in range(1, T+1):
p = solve(t)
print('Case #%d: %d' % (t, p))
def isAllOne(i, n):
while n:
if n%i != 1:
return False
n //= i
return True
def solve(t):
n = int(input())
# (p^x-1)/(p-1) = n
# x>4, p<10^5
min... | def solution():
t = int(input())
for t in range(1, T + 1):
p = solve(t)
print('Case #%d: %d' % (t, p))
def is_all_one(i, n):
while n:
if n % i != 1:
return False
n //= i
return True
def solve(t):
n = int(input())
min_n = min(n, 10 ** 5)
for i in ... |
def _print_param_tuning_results(mod=None, mod_type=None, X=None) -> None:
"""
Utility function for printing results of paramter tuning
Args:
mod ([type], optional): Model object. Defaults to None.
X ([type], optional): Pandas data with feature columns for training. Defaults to None.
"""... | def _print_param_tuning_results(mod=None, mod_type=None, X=None) -> None:
"""
Utility function for printing results of paramter tuning
Args:
mod ([type], optional): Model object. Defaults to None.
X ([type], optional): Pandas data with feature columns for training. Defaults to None.
"""... |
# Python - 3.6.0
def tail_swap(strings):
s1, s2 = strings
a, b = s1.split(':')
c, d = s2.split(':')
return [f'{a}:{d}', f'{c}:{b}']
| def tail_swap(strings):
(s1, s2) = strings
(a, b) = s1.split(':')
(c, d) = s2.split(':')
return [f'{a}:{d}', f'{c}:{b}'] |
cad = {}
apv = []
cad['nome'] = str(input('Nome do Jogador: '))
n = int(input(f'Quantas partidas {cad["nome"]} jogou? '))
for c in range (0,n):
apv.append(int(input(f'Quantos gols na partida {c+1}? ')))
cad['gols'] = apv[:]
cad['total'] = sum(apv)
print('-=-'*30)
for k, v in cad.items():
print(f'O campo {k} te... | cad = {}
apv = []
cad['nome'] = str(input('Nome do Jogador: '))
n = int(input(f"Quantas partidas {cad['nome']} jogou? "))
for c in range(0, n):
apv.append(int(input(f'Quantos gols na partida {c + 1}? ')))
cad['gols'] = apv[:]
cad['total'] = sum(apv)
print('-=-' * 30)
for (k, v) in cad.items():
print(f'O campo {... |
class TupleWithCallback(tuple):
def __new__(cls, *args, onDone=None):
t = tuple.__new__(cls, args)
if onDone is not None:
t.onDone = onDone
return t
| class Tuplewithcallback(tuple):
def __new__(cls, *args, onDone=None):
t = tuple.__new__(cls, args)
if onDone is not None:
t.onDone = onDone
return t |
WHITE, BLACK, NONE = "W", "B", " "
class Board:
def __init__(self, board):
self.board = [list(row) for row in board]
def territory(self, x, y):
if x < 0 or x >= len(self.board[0]) or y < 0 or y >= len(self.board):
raise ValueError(r".+")
if self.board[y][x] != NONE:
... | (white, black, none) = ('W', 'B', ' ')
class Board:
def __init__(self, board):
self.board = [list(row) for row in board]
def territory(self, x, y):
if x < 0 or x >= len(self.board[0]) or y < 0 or (y >= len(self.board)):
raise value_error('.+')
if self.board[y][x] != NONE:
... |
"""An implementation of the Euclidean algorithm
Adapted from https://github.com/j2kun/finite-fields
"""
def gcd(a, b):
"""General implementation of Euclidean algorithm.
A general Euclidean algorithm for any number type with a divmod and a
valuation abs() whose minimum value is zero. Note that this implement... | """An implementation of the Euclidean algorithm
Adapted from https://github.com/j2kun/finite-fields
"""
def gcd(a, b):
"""General implementation of Euclidean algorithm.
A general Euclidean algorithm for any number type with a divmod and a
valuation abs() whose minimum value is zero. Note that this implemen... |
"""Module version and author info."""
__title__ = "termania"
__description__ = "A Python interface for the Termania.net dictionary API"
__url__ = "https://github.com/techouse/termania-api"
__version__ = "1.0.2"
__author__ = "Klemen Tusar"
__author_email__ = "techouse@gmail.com"
__license__ = "MIT"
| """Module version and author info."""
__title__ = 'termania'
__description__ = 'A Python interface for the Termania.net dictionary API'
__url__ = 'https://github.com/techouse/termania-api'
__version__ = '1.0.2'
__author__ = 'Klemen Tusar'
__author_email__ = 'techouse@gmail.com'
__license__ = 'MIT' |
# Enter species name and filters
sp="Macaca_mulatta"
GQ_lim="60"
DP_min="0.5*mean_dp"
DP_max="2*mean_dp"
AB_max="0.7"
AB_min="0.3"
| sp = 'Macaca_mulatta'
gq_lim = '60'
dp_min = '0.5*mean_dp'
dp_max = '2*mean_dp'
ab_max = '0.7'
ab_min = '0.3' |
expected_chiral_data = [(True, 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... | expected_chiral_data = [(True, 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... |
def title(txt):
tam = len(txt)+4
print('-'*tam)
print(f' {txt}')
print('-'*tam)
while True:
title("SYSTEM HELPER PYHELP")
Helper = input("CAN I HELP YOU? TYPE A FUNCTION (FOR FINISH(END)): ")
if 'end' in Helper:
break
help(Helper)
title("THANKS! SEE YOU SOON!")
| def title(txt):
tam = len(txt) + 4
print('-' * tam)
print(f' {txt}')
print('-' * tam)
while True:
title('SYSTEM HELPER PYHELP')
helper = input('CAN I HELP YOU? TYPE A FUNCTION (FOR FINISH(END)): ')
if 'end' in Helper:
break
help(Helper)
title('THANKS! SEE YOU SOON!') |
def validate_input(msg, allowed):
i = ""
while i not in allowed:
i = input(msg)
return i
def format_choices(choices):
return " | ".join(choices)
| def validate_input(msg, allowed):
i = ''
while i not in allowed:
i = input(msg)
return i
def format_choices(choices):
return ' | '.join(choices) |
length = 5
width = 16.5
height = 12.5
volume = length * width * height
area = 2*length*width + 2*length*height + 2*width*height
print('volume =', volume)
print('area =', area)
| length = 5
width = 16.5
height = 12.5
volume = length * width * height
area = 2 * length * width + 2 * length * height + 2 * width * height
print('volume =', volume)
print('area =', area) |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 14:37:28 2019
@author: hu
"""
| """
Created on Mon Jun 24 14:37:28 2019
@author: hu
""" |
""" Version file for intelmq-manager
SPDX-FileCopyrightText: 2020-2021 Intelmq Team <intelmq-team@cert.at>
SPDX-License-Identifier: AGPL-3.0-or-later
"""
__version_info__ = (3, 1, 0, 'alpha1')
__version__ = '.'.join(map(str, __version_info__))
| """ Version file for intelmq-manager
SPDX-FileCopyrightText: 2020-2021 Intelmq Team <intelmq-team@cert.at>
SPDX-License-Identifier: AGPL-3.0-or-later
"""
__version_info__ = (3, 1, 0, 'alpha1')
__version__ = '.'.join(map(str, __version_info__)) |
class PlotDesigner:
def __init__(self) -> None:
"""Initialises the PlotDesigner Class.
Attributes
----------
figsize : tuple
Figsize in inches for the plot.
title_fontsize : str, int
Matplotlib command for the title fontsize.
text_fontsize :... | class Plotdesigner:
def __init__(self) -> None:
"""Initialises the PlotDesigner Class.
Attributes
----------
figsize : tuple
Figsize in inches for the plot.
title_fontsize : str, int
Matplotlib command for the title fontsize.
text_fontsize : ... |
#
# PySNMP MIB module EQLREPLPARTNER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQLREPLPARTNER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | """Errors used in the Python datastore API."""
class Error(Exception):
"""Base datastore error type.
"""
class Badvalueerror(Error):
"""Raised by Entity.__setitem__(), Query.__setitem__(), Get(), and others
when a property value or filter value is invalid.
"""
class Badpropertyerror(Error):
"""Rais... |
dictionary = {'A':'Alfa', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', "H":"Hotel", 'I':'India', 'J':'Juliett', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey',... | dictionary = {'A': 'Alfa', 'B': 'Bravo', 'C': 'Charlie', 'D': 'Delta', 'E': 'Echo', 'F': 'Foxtrot', 'G': 'Golf', 'H': 'Hotel', 'I': 'India', 'J': 'Juliett', 'K': 'Kilo', 'L': 'Lima', 'M': 'Mike', 'N': 'November', 'O': 'Oscar', 'P': 'Papa', 'Q': 'Quebec', 'R': 'Romeo', 'S': 'Sierra', 'T': 'Tango', 'U': 'Uniform', 'V': '... |
# Given
# a
# binary
# tree,
# return the
# postorder
# traversal
# of
# its
# nodes
# ' values.
#
# For
# example:
# Given
# binary
# tree[1, null, 2, 3],
#
# 1
# \
# 2
# /
# 3
#
# return [3, 2, 1].
#
# Note: Recursive
# solution is trivial, could
# you
# do
# it
# iteratively?
# Definition for a binary tree node.
cl... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def postorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
self.iterative(root, res)... |
# Rewrite your pay computation with time-and-a-half for over-
# time and create a function called compute_pay which takes two parameters
# (hours and rate).
user_hours = input('Enter your hours worked: ')
user_hours = float(user_hours)
user_pay = input('Enter the rate per hour: ')
user_pay = float(user_pay)
def c... | user_hours = input('Enter your hours worked: ')
user_hours = float(user_hours)
user_pay = input('Enter the rate per hour: ')
user_pay = float(user_pay)
def compute_pay(hours, rate):
if user_hours > 40:
over_time = user_hours - 40
total_pay = over_time * (user_pay * 1.5) + 40 * user_pay
retu... |
'''write a function that shutters a word as if someone is struggling to read it. The first two letters are repeated twice with an ellipsis ... , and then the word is pronounced with a question mark?
Input Format
a string
Constraints
no
Output Format
xx... xx... ~~~~~~~?
Sample Input 0
incredible
Sample Output 0... | """write a function that shutters a word as if someone is struggling to read it. The first two letters are repeated twice with an ellipsis ... , and then the word is pronounced with a question mark?
Input Format
a string
Constraints
no
Output Format
xx... xx... ~~~~~~~?
Sample Input 0
incredible
Sample Output 0... |
class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
m, n = len(matrix), len(matrix[0])
for row in matrix:
for i in range(n - 1):
row[i + 1] += row[i]
res = 0
for i in range(n):
for j in range(i, n):
... | class Solution:
def num_submatrix_sum_target(self, matrix: List[List[int]], target: int) -> int:
(m, n) = (len(matrix), len(matrix[0]))
for row in matrix:
for i in range(n - 1):
row[i + 1] += row[i]
res = 0
for i in range(n):
for j in range(i,... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
"//haskell:private/dependencies.bzl",
"gather_dep_info",
)
load(
"//haskell:private/expansions.bzl",
"expand_make_variables",
"haskell_library_extra_label_attrs",
)
load(
"//haskell:private/mode.bzl",
"is_profiling_enabled",
)
load("//haske... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//haskell:private/dependencies.bzl', 'gather_dep_info')
load('//haskell:private/expansions.bzl', 'expand_make_variables', 'haskell_library_extra_label_attrs')
load('//haskell:private/mode.bzl', 'is_profiling_enabled')
load('//haskell:private/pkg_id.bzl', 'pkg_id')
loa... |
class Worker:
""" An abstraction of a worker. """
def __init__(self, worker_id: str):
""" Create a worker instance.
Args:
worker_id: the id that uniquely identifies the user.
"""
self._worker_id = worker_id
self._cycles = {}
def register_cycle(se... | class Worker:
""" An abstraction of a worker. """
def __init__(self, worker_id: str):
""" Create a worker instance.
Args:
worker_id: the id that uniquely identifies the user.
"""
self._worker_id = worker_id
self._cycles = {}
def register_cycle(se... |
weth_abi = [
{
"constant": True,
"inputs": [],
"name": "name",
"outputs": [{"name": "tokenName", "type": "string"}],
"payable": False,
"stateMutability": "view",
"type": "function",
},
{
"constant": False,
"inputs": [
{"name... | weth_abi = [{'constant': True, 'inputs': [], 'name': 'name', 'outputs': [{'name': 'tokenName', 'type': 'string'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': False, 'inputs': [{'name': 'spender', 'type': 'address'}, {'name': 'value', 'type': 'uint256'}], 'name': 'approve', 'outputs':... |
class PerceptionActionCycle:
def __init__(self, initial_camera_position, initial_gameloop):
self.initial_camera_position = initial_camera_position
self.initial_gameloop = initial_gameloop
self.final_camera_position = None
self.final_gameloop = None
self.actions = []
s... | class Perceptionactioncycle:
def __init__(self, initial_camera_position, initial_gameloop):
self.initial_camera_position = initial_camera_position
self.initial_gameloop = initial_gameloop
self.final_camera_position = None
self.final_gameloop = None
self.actions = []
... |
"""
Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
... | """
Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
... |
class Person(object):
'''
Test class to show the functionality of model creation in the flask api.abs
It contains:
* first name = First name of a person
* last name = Last name of a person
'''
def __init__(self, first_name, last_name):
self.first_name - first_name
self.last =... | class Person(object):
"""
Test class to show the functionality of model creation in the flask api.abs
It contains:
* first name = First name of a person
* last name = Last name of a person
"""
def __init__(self, first_name, last_name):
self.first_name - first_name
self.last ... |
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY
short_version = '1.6.0'
version = '1.6.0'
full_version = '1.6.0'
git_revision = 'Unknown'
release = True
if not release:
version = full_version
| short_version = '1.6.0'
version = '1.6.0'
full_version = '1.6.0'
git_revision = 'Unknown'
release = True
if not release:
version = full_version |
class WrongPassword(Exception):
pass
class WrongEmail(Exception):
pass
class RequestedApproval(Exception):
pass
class UserBlocked(Exception):
pass
class DisabledInviting(Exception):
pass
class UnexpectedException(Exception):
pass
class NoDialogflowCredentialsFileFound(Exception):
... | class Wrongpassword(Exception):
pass
class Wrongemail(Exception):
pass
class Requestedapproval(Exception):
pass
class Userblocked(Exception):
pass
class Disabledinviting(Exception):
pass
class Unexpectedexception(Exception):
pass
class Nodialogflowcredentialsfilefound(Exception):
pass |
# temp = 19
# is_raining = False
# if temp > 15:
# print("take a hat")
# print("don't take a coat")
# else:
# print("don't take a hat")
# print("take a coat")
# if is_raining==True:
# print("take an umbrella")
# else:
# print("don't take an umbrella")
temp = int(input("\nwhat i... | temp = int(input('\nwhat is the tempreture ? '))
is_raining = input('\nis it raining ? ')
if temp > 15:
print('\ntake a hat')
print("don't take a coat")
else:
print("\ndon't take a hat")
print('take a coat')
if is_raining == 'yes':
print('take an umbrella')
else:
print("don't take an umbrella") |
class CableTrayType(MEPCurveType,IDisposable):
""" This class represents a cable tray type in Autodesk Revit. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def IsValidBendMu... | class Cabletraytype(MEPCurveType, IDisposable):
""" This class represents a cable tray type in Autodesk Revit. """
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_bounding_box(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
... |
"""GO-DAG constants."""
__copyright__ = "Copyright (C) 2010-2019, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
# pylint: disable=too-few-public-methods
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
NAMESPACE2NS = {
'biological_process' : '... | """GO-DAG constants."""
__copyright__ = 'Copyright (C) 2010-2019, DV Klopfenstein, H Tang, All rights reserved.'
__author__ = 'DV Klopfenstein'
class Consts(object):
"""Constants commonly used in GO-DAG operations."""
namespace2_ns = {'biological_process': 'BP', 'molecular_function': 'MF', 'cellular_component'... |
# https://www.educative.io/courses/grokking-the-coding-interview/7XMlMEQPnnQ
def get_sum_between_ptr(sum_array, i, j):
if i == 0:
return sum_array[j]
else:
return sum_array[j] - sum_array[i - 1]
def get_smallest_subarray_size(size, ptr1, ptr2):
if size > (ptr2 - ptr1 + 1):
return... | def get_sum_between_ptr(sum_array, i, j):
if i == 0:
return sum_array[j]
else:
return sum_array[j] - sum_array[i - 1]
def get_smallest_subarray_size(size, ptr1, ptr2):
if size > ptr2 - ptr1 + 1:
return ptr2 - ptr1 + 1
else:
return size
def smallest_subarray_with_given_s... |
# Find the next greater and next smaller number with same number of set bits
# Ex. num = 6 bin = 110
def next_greater(num):
res = num
if num != 0:
# Find the right most 1 position
# Ex. right_one = 2 bin = 10
right_one = num & -num
# get the left pattern to merge
# Ex. ... | def next_greater(num):
res = num
if num != 0:
right_one = num & -num
left_pattern = num + right_one
right_pattern = (num ^ left_pattern) >> right_one + 1
res = left_pattern | right_pattern
return res
def next_smaller(num):
return ~next_greater(~num)
print(next_greater(6)... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Space: O(h), where h is the tree height
class Solution:
def __init__(self):
self.prev = TreeNode(float("-inf"))
self.first = None
self.s... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.prev = tree_node(float('-inf'))
self.first = None
self.second = None
def recover_tree(self, root: TreeNode) -> None:
"""... |
m = 1000000007
N, *c = map(int, open(0).read().split())
fac = [1] * (N + 1)
for i in range(N):
fac[i + 1] = fac[i] * (i + 1)
fac[i + 1] %= m
x = fac[N - 1] * (pow(10, N, m) - 1) * pow(9, -1, m) % m
frac = 0
denom = 1
for i in range(9):
if c[i] == 0:
continue
frac += c[i] * (i + 1) * x
fra... | m = 1000000007
(n, *c) = map(int, open(0).read().split())
fac = [1] * (N + 1)
for i in range(N):
fac[i + 1] = fac[i] * (i + 1)
fac[i + 1] %= m
x = fac[N - 1] * (pow(10, N, m) - 1) * pow(9, -1, m) % m
frac = 0
denom = 1
for i in range(9):
if c[i] == 0:
continue
frac += c[i] * (i + 1) * x
frac... |
# Copyright 2017, Ansible by Red Hat.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | version = '3.3.0'
cur_api_version = 'v2'
launch_type_choices = ['manual', 'relaunch', 'relaunch', 'callback', 'scheduled', 'dependency', 'workflow', 'sync', 'scm']
status_choices = ['new', 'pending', 'waiting', 'running', 'successful', 'failed', 'error', 'canceled']
inventory_source_choices = ['', 'file', 'scm', 'ec2',... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
bar=input()
bar = bar.replace('()','/')
raiser=0
ans=0
for i in bar:
if(i=='/'):
ans=ans+raiser
elif(i=='('):
raiser=raiser+1
else:
raiser=raiser-1
ans=ans+1
print(ans)
| bar = input()
bar = bar.replace('()', '/')
raiser = 0
ans = 0
for i in bar:
if i == '/':
ans = ans + raiser
elif i == '(':
raiser = raiser + 1
else:
raiser = raiser - 1
ans = ans + 1
print(ans) |
def extremize(y,level=0.1):
y[y<level]=0
y[y>=level]=1
return y
| def extremize(y, level=0.1):
y[y < level] = 0
y[y >= level] = 1
return y |
""" Variables starts with letter and
can contain only letter and
numbers (plus '_')
"""
# Set variables
message = "what's up Pantelis?"
n = 17
pi = 3.14
# Reference variables
print(message)
print(n)
print(pi)
x = 5
print("initial x = ", x)
x = 10
print("now x = ",x)
xyz = 0
XYZ = 1
print("xyz = ",xyz," ", "X... | """ Variables starts with letter and
can contain only letter and
numbers (plus '_')
"""
message = "what's up Pantelis?"
n = 17
pi = 3.14
print(message)
print(n)
print(pi)
x = 5
print('initial x = ', x)
x = 10
print('now x = ', x)
xyz = 0
xyz = 1
print('xyz = ', xyz, ' ', 'XYZ = ', XYZ) |
class DynamicSystem:
def __init__(self, b, sigma, v, min_hamil_deriv_X, dg, initX, n_timesteps=100, T=1, lp=None, lm=None):
"""
All functions take input t, x, y, z, r
v can be None
"""
self.b = b
self.sigma = sigma
self.v = v
self.min_hamil_deriv_X = m... | class Dynamicsystem:
def __init__(self, b, sigma, v, min_hamil_deriv_X, dg, initX, n_timesteps=100, T=1, lp=None, lm=None):
"""
All functions take input t, x, y, z, r
v can be None
"""
self.b = b
self.sigma = sigma
self.v = v
self.min_hamil_deriv_X = ... |
#!/usr/bin/env python3
COLLATZ_SIZE = 5000000 + 5
collatz = [0] * COLLATZ_SIZE
answers = [0] * COLLATZ_SIZE
for k in range(23):
collatz[2 ** k] = k
def calculate_collatz(N):
global collatz;
steps = 0
n = N
# Answers for n < N have been calculated already.
while (n >= N):
steps += 1
... | collatz_size = 5000000 + 5
collatz = [0] * COLLATZ_SIZE
answers = [0] * COLLATZ_SIZE
for k in range(23):
collatz[2 ** k] = k
def calculate_collatz(N):
global collatz
steps = 0
n = N
while n >= N:
steps += 1
n = n // 2 if n % 2 == 0 else 3 * n + 1
collatz[N] = collatz[n] + steps
... |
class Solution:
def numSubarraysWithSum(self, A, S):
"""
:type A: List[int]
:type S: int
:rtype: int
"""
acc_dic = collections.Counter()
acc_dic[0] += 1
res, acc = 0, 0
for num in A:
acc += num
res += acc_dic[acc - S]
... | class Solution:
def num_subarrays_with_sum(self, A, S):
"""
:type A: List[int]
:type S: int
:rtype: int
"""
acc_dic = collections.Counter()
acc_dic[0] += 1
(res, acc) = (0, 0)
for num in A:
acc += num
res += acc_dic[acc... |
__author__ = 'Comma'
END = -1
MAIN_PANEL = 1
POST_START = 10
POST_SELECT_FIELD = 11
POST_FILL_VALUE = 12
POST_BEFORE_SUBMIT = 13
POST_SUBMIT = 14
UPDATE_START = 15
UPDATE_SELECT_TICKET = 16
UPDATE_SELECT_FIELD = 17
UPDATE_FILL_VALUE = 18
UPDATE_BEFORE_SUBMIT = 19
UPDATE_SUBMIT = 20
SEARCH_START = 21
SEARCH_SELECT_F... | __author__ = 'Comma'
end = -1
main_panel = 1
post_start = 10
post_select_field = 11
post_fill_value = 12
post_before_submit = 13
post_submit = 14
update_start = 15
update_select_ticket = 16
update_select_field = 17
update_fill_value = 18
update_before_submit = 19
update_submit = 20
search_start = 21
search_select_field... |
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licen... | """
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
'''
Created on 1.12.2016
@author: Darren
'''
'''
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up:
Could you do it using only constant space complexity?
'''
| """
Created on 1.12.2016
@author: Darren
"""
'\nGiven an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.\n\nYou may assume each number in the sequence is unique.\n\nFollow up:\nCould you do it using only constant space complexity?\n' |
# flake8: noqa
# lambda function atau dikenal juga dengan anonymous function
# adalah function yang bisa menerima multiple arguments
# tapi hanya bisa melakukan 1 expression
# seperti contoh pada lambda luas_persegi dibawah
# hanya input s, dan satu expresi yaitu, s * s
luas_persegi = lambda s: s ** 2
print(luas_per... | luas_persegi = lambda s: s ** 2
print(luas_persegi(4))
luas_segitiga = lambda a, t: a * t / 2
print(luas_segitiga(2, 3))
infinite = lambda *input: sum(input)
print(infinite(1, 2, 3))
print(infinite(1, 2, 3, 4))
key_inf = lambda **kwargs: sum(kwargs.values())
print(key_inf(satu=1, dua=2, tiga=3))
print(key_inf(seven=7, ... |
load(
"//tensorflow:tensorflow.bzl",
"tf_binary_additional_srcs",
)
# Generate Java wrapper classes for all registered core operations and package
# them into a single source archive (.srcjar).
#
# For example:
# tf_java_op_gen_srcjar("gen_sources", ":gen_tool", "my.package")
#
# will create a genrule named "... | load('//tensorflow:tensorflow.bzl', 'tf_binary_additional_srcs')
def tf_java_op_gen_srcjar(name, gen_tool, base_package, api_def_srcs=[], out_dir='ops/', out_src_dir='src/main/java/', visibility=['//tensorflow/java:__pkg__']):
gen_cmds = ['rm -rf $(@D)']
srcs = api_def_srcs[:]
if not api_def_srcs:
... |
class Foo:
def __init__(self):
self.name = 'Foo name'
class Bar:
def __init__(self):
self.last_name = 'Bar name'
class DataAdapter:
def __init__(self, source, target):
self.source = type(source)
self.target = type(target)
def do(self, source, target=None):
... | class Foo:
def __init__(self):
self.name = 'Foo name'
class Bar:
def __init__(self):
self.last_name = 'Bar name'
class Dataadapter:
def __init__(self, source, target):
self.source = type(source)
self.target = type(target)
def do(self, source, target=None):
i... |
# for loop
for x in range(1, 20):
print(x)
# WHILE
age = 5
while age < 10:
print(age)
age += 1
| for x in range(1, 20):
print(x)
age = 5
while age < 10:
print(age)
age += 1 |
# exceptions.py - Python exceptions for everything at "text_formatter"
#
# This file contains many, many exceptions (subclasses of the
# standard "Exception") and related functions.
class InvalidString(Exception):
"""
This exception must be raised when a string
argument is not what we expected.
"""
... | class Invalidstring(Exception):
"""
This exception must be raised when a string
argument is not what we expected.
"""
pass
class Invalidbytes(Exception):
"""
The same function than InvalidString,
but applied to bytestrings.
"""
pass |
{ # pylint: disable=C8101,C8103
'name': 'Odoo Next - Eletronic documents',
'description': 'Enable Eletronic Documents',
'version': '14.0.1.0.0',
'category': 'Localization',
'author': 'Trustcode',
'license': 'OEEL-1',
'website': 'http://www.odoo-next.com,br',
'contributors': [
'D... | {'name': 'Odoo Next - Eletronic documents', 'description': 'Enable Eletronic Documents', 'version': '14.0.1.0.0', 'category': 'Localization', 'author': 'Trustcode', 'license': 'OEEL-1', 'website': 'http://www.odoo-next.com,br', 'contributors': ['Danimar Ribeiro <danimaribeiro@gmail.com>'], 'depends': ['l10n_br_account'... |
class Action:
def __init__(self, name, parameter, precondition, effects):
self.name = name
self.parameter = parameter
self.precondition = precondition
self.effects = effects
def update_params(self, param_type, param_mapping, p_objects):
self.parameter = param_type
... | class Action:
def __init__(self, name, parameter, precondition, effects):
self.name = name
self.parameter = parameter
self.precondition = precondition
self.effects = effects
def update_params(self, param_type, param_mapping, p_objects):
self.parameter = param_type
... |
INVALID_DATE = "Invalid date format provided. Please YYYY/MM/dd date format"
COIN_UNAVAILABLE = "Coin with given id does not exist"
COIN_ID_NOT_PROVIDED = "A coin_id must be provided"
QUERY_DATE_NOT_PROVIDED = "A query date must be provided"
CURRENCY_CODE_NOT_PROVIDED = "A currency code must be provided"
FUTURE_DATE_NO... | invalid_date = 'Invalid date format provided. Please YYYY/MM/dd date format'
coin_unavailable = 'Coin with given id does not exist'
coin_id_not_provided = 'A coin_id must be provided'
query_date_not_provided = 'A query date must be provided'
currency_code_not_provided = 'A currency code must be provided'
future_date_no... |
"""
Reserved token names
Copyright (c)
See LICENSE for details.
<jtm@robot.is>
"""
tokens = {
'@media': 'css_media',
'@page': 'css_page',
'@import': 'css_import',
'@charset': 'css_charset',
'@font-face': 'css_font_face',
'@namespace': 'css_namespace',
'@keyframes': 'css_key... | """
Reserved token names
Copyright (c)
See LICENSE for details.
<jtm@robot.is>
"""
tokens = {'@media': 'css_media', '@page': 'css_page', '@import': 'css_import', '@charset': 'css_charset', '@font-face': 'css_font_face', '@namespace': 'css_namespace', '@keyframes': 'css_keyframes', '@-moz-keyframes': 'c... |
"""
Deja Vu
You aren't paying attention and you accidentally type a bunch of random letters on your keyboard. You want to know if you ever typed the same letter twice, or if they are all unique letters.
Task:
If you are given a string of random letters, your task is to evaluate whether any letter is repeated in the s... | """
Deja Vu
You aren't paying attention and you accidentally type a bunch of random letters on your keyboard. You want to know if you ever typed the same letter twice, or if they are all unique letters.
Task:
If you are given a string of random letters, your task is to evaluate whether any letter is repeated in the s... |
class Sources:
'''
Sources class that defines source objects
'''
def __init__(self,id,name,author,description,url,category,urlToImage,title):
'''
Function that initiates the sources class
'''
self.id = id
self.name = name
self.author = author
self.... | class Sources:
"""
Sources class that defines source objects
"""
def __init__(self, id, name, author, description, url, category, urlToImage, title):
"""
Function that initiates the sources class
"""
self.id = id
self.name = name
self.author = author
... |
n=int(input())
prices=input().split(" ")
temp_buy_date=0
buy_price=(1<<31)-1
buy_date=0
profit=0
for i in range(n) :
p=int(prices[i])
if p<buy_price :
buy_price=p
temp_buy_date=i+1
elif p-buy_price>profit :
buy_date=temp_buy_date
profit=p-buy_price
print(str(profit)+"\n"+str(buy_date))
| n = int(input())
prices = input().split(' ')
temp_buy_date = 0
buy_price = (1 << 31) - 1
buy_date = 0
profit = 0
for i in range(n):
p = int(prices[i])
if p < buy_price:
buy_price = p
temp_buy_date = i + 1
elif p - buy_price > profit:
buy_date = temp_buy_date
profit = p - buy_... |
tokens = [
('{', 'LKEY'),
('}', 'RKEY'),
('[', 'LBRACKETS'),
(']', 'RBRACKETS'),
('(', 'LPARENTHESES'),
(')', 'RPARENTHESES'),
('+', 'PLUS'),
('-', 'MINUS'),
('/', 'DIVISION'),
('%', 'MODULO'),
('~', 'NOT'),
('=', 'EQUALS'),
('<', 'LT'),
('>', 'GT'),
('<=', 'L... | tokens = [('{', 'LKEY'), ('}', 'RKEY'), ('[', 'LBRACKETS'), (']', 'RBRACKETS'), ('(', 'LPARENTHESES'), (')', 'RPARENTHESES'), ('+', 'PLUS'), ('-', 'MINUS'), ('/', 'DIVISION'), ('%', 'MODULO'), ('~', 'NOT'), ('=', 'EQUALS'), ('<', 'LT'), ('>', 'GT'), ('<=', 'LTE'), ('>=', 'GTE'), ('==', 'DOUBLEEQUAL'), ('&', 'AND'), ('|... |
# coding: utf-8
REDIS_URL = 'redis://redis:6379/0'
REDIS_CONF = {
'url': REDIS_URL,
'socket_timeout': 0.5,
}
WEBHOOK_TYPES = ['jira', 'jenkins']
LOG_DIR = '/var/log'
HOST = '120.78.197.57'
| redis_url = 'redis://redis:6379/0'
redis_conf = {'url': REDIS_URL, 'socket_timeout': 0.5}
webhook_types = ['jira', 'jenkins']
log_dir = '/var/log'
host = '120.78.197.57' |
class Point:
def __init__(self, value):
self.value = value
self.mark = False
def __str__(self):
return f"value: {self.value}, marked: {self.mark}"
def get_value(self):
return self.value
def get_mark(self):
return self.mark
def mark_point(self):
se... | class Point:
def __init__(self, value):
self.value = value
self.mark = False
def __str__(self):
return f'value: {self.value}, marked: {self.mark}'
def get_value(self):
return self.value
def get_mark(self):
return self.mark
def mark_point(self):
se... |
def cnn(x_train, y_train, x_test, y_test, batch_size, nb_classes, epochs, input_shape):
"""
CNN Architecture for classifying the speech
"""
return 0
if __name__ == '__main__':
# CNN Parameters
batch_size = 32
nb_classes = 2
epochs = 7
print("Processing...")
# TODO: Normalize d... | def cnn(x_train, y_train, x_test, y_test, batch_size, nb_classes, epochs, input_shape):
"""
CNN Architecture for classifying the speech
"""
return 0
if __name__ == '__main__':
batch_size = 32
nb_classes = 2
epochs = 7
print('Processing...')
print('Fitting model...')
print('Evalua... |
def _impl(ctx):
in_file = ctx.file.src
basename = ctx.attr.src.label.name
out_file = ctx.actions.declare_file("%s.gz" % basename)
cmd = "gzip --no-name -c '%s' > '%s'" % (in_file.path, out_file.path)
ctx.actions.run_shell(
outputs = [out_file],
inputs = [in_file],
command ... | def _impl(ctx):
in_file = ctx.file.src
basename = ctx.attr.src.label.name
out_file = ctx.actions.declare_file('%s.gz' % basename)
cmd = "gzip --no-name -c '%s' > '%s'" % (in_file.path, out_file.path)
ctx.actions.run_shell(outputs=[out_file], inputs=[in_file], command=cmd)
return [default_info(fi... |
# inserts "\t* " before each line in the selection
text = bg.components.fldDocument.getStringSelection()
unorderedList = ""
for i in text.splitlines(1):
unorderedList += "\t* " + i
bg.components.fldDocument.replaceSelection(unorderedList)
| text = bg.components.fldDocument.getStringSelection()
unordered_list = ''
for i in text.splitlines(1):
unordered_list += '\t* ' + i
bg.components.fldDocument.replaceSelection(unorderedList) |
class Solution:
def freqAlphabets(self, s: str) -> str:
chars = string.ascii_lowercase
m = dict(zip('123456789', chars[:9]))
m.update(dict(zip(['{}#'.format(val) for val in range(10, 27)], chars[9:])))
n = len(s)
ans = []
i = 0
while i < n:
if i + ... | class Solution:
def freq_alphabets(self, s: str) -> str:
chars = string.ascii_lowercase
m = dict(zip('123456789', chars[:9]))
m.update(dict(zip(['{}#'.format(val) for val in range(10, 27)], chars[9:])))
n = len(s)
ans = []
i = 0
while i < n:
if i ... |
# settings.py
def get_defaults():
return {
'aleph': {
'queue_topic': 'ALEPH-QUEUE',
'host': '127.0.0.1',
'port': 8080
},
'p2p': {
'port': 4025,
'http_port': 4024,
'host': '0.0.0.0',
'key': None,
'... | def get_defaults():
return {'aleph': {'queue_topic': 'ALEPH-QUEUE', 'host': '127.0.0.1', 'port': 8080}, 'p2p': {'port': 4025, 'http_port': 4024, 'host': '0.0.0.0', 'key': None, 'reconnect_delay': 60, 'clients': ['http'], 'peers': ['/ip4/51.159.57.71/tcp/4025/p2p/QmZkurbY2G2hWay59yiTgQNaQxHSNzKZFt2jbnwJhQcKgV', '/ip... |
def table(df, text, software, flow=False):
try:
html = """
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
... | def table(df, text, software, flow=False):
try:
html = '\n <!doctype html>\n <html lang="en">\n <head>\n <!-- Required meta tags -->\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">\n\n ... |
class Console:
def __init__(self, text=None):
if text is None:
text = ""
self.text = "\n"
self.add(text)
def get(self):
return self.text
def add(self, maybe_text):
try:
self.text += " " + maybe_text + "\n"
except TypeError:
... | class Console:
def __init__(self, text=None):
if text is None:
text = ''
self.text = '\n'
self.add(text)
def get(self):
return self.text
def add(self, maybe_text):
try:
self.text += ' ' + maybe_text + '\n'
except TypeError:
... |
# Keywords
KW_START = 'KW_START'
KW_STOP = 'KW_STOP'
KW_VAR = 'KW_VAR'
KW_AS = 'KW_AS'
KW_INT = 'KW_INTEGER'
KW_FLOAT = 'KW_FLOATING'
KW_STRING = 'KW_STRING'
KW_BOOLEAN = 'KW_BOOLEAN'
KW_OUTPUT = 'KW_OUTPUT'
KW_INPUT = 'KW_INPUT'
KW_CHAR = 'KW_CHAR'
# LANGUAGE SPECIFICS
NEWLINE = 'NL' # Value is (#)
CONCATENATOR = '... | kw_start = 'KW_START'
kw_stop = 'KW_STOP'
kw_var = 'KW_VAR'
kw_as = 'KW_AS'
kw_int = 'KW_INTEGER'
kw_float = 'KW_FLOATING'
kw_string = 'KW_STRING'
kw_boolean = 'KW_BOOLEAN'
kw_output = 'KW_OUTPUT'
kw_input = 'KW_INPUT'
kw_char = 'KW_CHAR'
newline = 'NL'
concatenator = 'CON'
comment_init = 'COMI'
escape_open = 'ESCO'
es... |
class FinderError(Exception):
pass
class MultipleMatchesError(FinderError):
pass
class NoMatchesError(FinderError):
pass
class Finder(object):
def __init__(self, root, item_finder_factory):
self._root = root
self.item_finder_factory = item_finder_factory
def find(self, matcher... | class Findererror(Exception):
pass
class Multiplematcheserror(FinderError):
pass
class Nomatcheserror(FinderError):
pass
class Finder(object):
def __init__(self, root, item_finder_factory):
self._root = root
self.item_finder_factory = item_finder_factory
def find(self, matcher_s... |
tableau20 = [
'steelblue', # 0
'lightsteelblue', # 1
'darkorange', # 2
'peachpuff', # 3
'green', # 4
'lightgreen', # 5
'crimson', # 6
'lightcoral', # 7
'mediumpurple', # 8
'thistle', # 9
'saddlebrown', # 10
'rosybrown', # 11
'orchid', # 12
'lightpink'... | tableau20 = ['steelblue', 'lightsteelblue', 'darkorange', 'peachpuff', 'green', 'lightgreen', 'crimson', 'lightcoral', 'mediumpurple', 'thistle', 'saddlebrown', 'rosybrown', 'orchid', 'lightpink', 'gray', 'lightgray', 'olive', 'palegoldenrod', 'mediumturquoise', 'paleturquoise']
tableau10 = ['blue', 'darkorange', 'gree... |
'''
Author: ZHAO Zinan
Created: 09. April 2019
237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list,
given only access to that node.
Note:
The linked list will have at least two elements.
All of the nodes' values will be unique.
The given node ... | """
Author: ZHAO Zinan
Created: 09. April 2019
237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list,
given only access to that node.
Note:
The linked list will have at least two elements.
All of the nodes' values will be unique.
The given node will not be t... |
"""
imbalanceddl
=====
Available Subpackage
-------------------
dataset
defines Imbalance dataset class
net
defines backbone and model
loss
defines loss
strategy
Implementation of different deep imbalance learning algorithms
"""
__all__ = ["strategy", "dataset", "net", "loss"]
| """
imbalanceddl
=====
Available Subpackage
-------------------
dataset
defines Imbalance dataset class
net
defines backbone and model
loss
defines loss
strategy
Implementation of different deep imbalance learning algorithms
"""
__all__ = ['strategy', 'dataset', 'net', 'loss'] |
#!/usr/bin/env python3
N = int(input())
P = [int(_) for _ in input().split()]
count = 0
flag = False
for i, v in enumerate(P):
ii = i + 1
if v == ii:
if flag:
flag = False
else:
count += 1
flag = True
elif flag:
flag = False
print(count)
| n = int(input())
p = [int(_) for _ in input().split()]
count = 0
flag = False
for (i, v) in enumerate(P):
ii = i + 1
if v == ii:
if flag:
flag = False
else:
count += 1
flag = True
elif flag:
flag = False
print(count) |
# ------------------------------
# 506. Relative Ranks
#
# Description:
# Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
# Example 1:
# Input: [5, 4, 3, 2, 1]
# Output: ["Gold Medal", "... | class Solution(object):
def find_relative_ranks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
res = []
sort_nums = sorted(nums, reverse=True)
for i in nums:
idx = sortNums.index(i)
if idx == 0:
res.append... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
Entry... | """
Entrypoint for Hummingbird modules.
"""
__version__ = '0.4.2'
__author__ = 'Microsoft'
__producer__ = 'hummingbird'
__producer_version__ = __version__
__domain__ = 'microsoft.gsl'
__model_version__ = 0 |
"""build-magic
* Macro - A command to be executed by a CommandRunner.
* MacroFactory - Generates Macro objects based on the provided commands.
* CommandRunner - An abstract class for defining methods for executing commands.
"""
__version__ = '0.4.1rc0'
__all__ = [
'cli',
'core',
'macro',
... | """build-magic
* Macro - A command to be executed by a CommandRunner.
* MacroFactory - Generates Macro objects based on the provided commands.
* CommandRunner - An abstract class for defining methods for executing commands.
"""
__version__ = '0.4.1rc0'
__all__ = ['cli', 'core', 'macro', 'output', 'runner',... |
"""Module used to hold potential errors present on the client code."""
class BaseIIC2343Error(Exception):
"""
A base error class to be able to handle every error thrown by the
library at the same time.
"""
class CannotOpenPortError(BaseIIC2343Error):
"""Error for when a port cannot be opened."""... | """Module used to hold potential errors present on the client code."""
class Baseiic2343Error(Exception):
"""
A base error class to be able to handle every error thrown by the
library at the same time.
"""
class Cannotopenporterror(BaseIIC2343Error):
"""Error for when a port cannot be opened."""
... |
#!/usr/bin/env python
oracle_home = '/usr/local/ohs'
domain_name = 'base_domain'
domain_home = oracle_home + '/user_projects/domains/' + domain_name
node_manager_name = 'localmachine'
component_name = 'ohs1'
component_admin_listen_address = '127.0.0.1'
component_admin_listen_port = '9999'
component_listen_address = ''... | oracle_home = '/usr/local/ohs'
domain_name = 'base_domain'
domain_home = oracle_home + '/user_projects/domains/' + domain_name
node_manager_name = 'localmachine'
component_name = 'ohs1'
component_admin_listen_address = '127.0.0.1'
component_admin_listen_port = '9999'
component_listen_address = ''
component_listen_port ... |
# Copyright (c) 2020 Rocky Bernstein
def testtrue(self, lhs: str, n: int, rule, ast, tokens, first: int, last: int) -> bool:
# FIXME: make this work for all versions
if self.version != 3.7:
return False
if rule == ("testtrue", ("expr", "POP_JUMP_IF_TRUE")):
pjit = tokens[min(last - 1, n -... | def testtrue(self, lhs: str, n: int, rule, ast, tokens, first: int, last: int) -> bool:
if self.version != 3.7:
return False
if rule == ('testtrue', ('expr', 'POP_JUMP_IF_TRUE')):
pjit = tokens[min(last - 1, n - 2)]
if pjit == 'POP_JUMP_IF_TRUE_BACK':
assert_next = tokens[min... |
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
return self.lengthOfLongestSubstringKDistinct(s, 2)
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:... | class Solution(object):
def length_of_longest_substring_two_distinct(self, s):
"""
:type s: str
:rtype: int
"""
return self.lengthOfLongestSubstringKDistinct(s, 2)
def length_of_longest_substring_k_distinct(self, s, k):
"""
:type s: str
:type k: ... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
print(['black','grimy'][0--int(input())//2%2]) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
print(['black', 'grimy'][0 - -int(input()) // 2 % 2]) |
# -*- coding: utf-8 -*-
class Solution:
def reverseString(self, s):
return s[::-1]
if __name__ == '__main__':
solution = Solution()
assert 'olleh' == solution.reverseString('hello')
assert 'amanaP :lanac a ,nalp a ,nam A' == solution.\
reverseString('A man, a plan, a canal: Panama')... | class Solution:
def reverse_string(self, s):
return s[::-1]
if __name__ == '__main__':
solution = solution()
assert 'olleh' == solution.reverseString('hello')
assert 'amanaP :lanac a ,nalp a ,nam A' == solution.reverseString('A man, a plan, a canal: Panama') |
# taken from https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
rainbow = [
(230, 25, 75),
(60, 180, 75),
(255, 225, 25),
(0, 130, 200),
(245, 130, 48),
(145, 30, 180),
(70, 240, 240),
(240, 50, 230),
(210, 245, 60),
(250, 190, 190),
(0, 128, 128),
(230, 190,... | rainbow = [(230, 25, 75), (60, 180, 75), (255, 225, 25), (0, 130, 200), (245, 130, 48), (145, 30, 180), (70, 240, 240), (240, 50, 230), (210, 245, 60), (250, 190, 190), (0, 128, 128), (230, 190, 255), (170, 110, 40), (255, 250, 200), (128, 0, 0), (170, 255, 195), (128, 128, 0), (255, 215, 180), (0, 0, 128), (128, 128, ... |
# Ex050.2
"""Develop a program that reads six integers and shows the sum only of those that are even,
If the value entered is odd, disregard it"""
sum = 0
for value in range(1, 7):
number = int(input('Type a value: '))
if number % 2 == 0:
sum += number
print(f'The sum between 6 numbers informed is {sum... | """Develop a program that reads six integers and shows the sum only of those that are even,
If the value entered is odd, disregard it"""
sum = 0
for value in range(1, 7):
number = int(input('Type a value: '))
if number % 2 == 0:
sum += number
print(f'The sum between 6 numbers informed is {sum}') |
sample_rate = 44100
window_size = 2048 # 1024 # 2048
overlap = 672 # 256 # 672 # So that there are 320 frames in an audio clip
seq_len = 320 # 573 # 320
mel_bins = 64
labels = ['airport', 'bus', 'metro', 'metro_station', 'park', 'public_square',
'shopping_mall', 'street_pedestrian', 'street_traffic', 'tra... | sample_rate = 44100
window_size = 2048
overlap = 672
seq_len = 320
mel_bins = 64
labels = ['airport', 'bus', 'metro', 'metro_station', 'park', 'public_square', 'shopping_mall', 'street_pedestrian', 'street_traffic', 'tram']
lb_to_ix = {lb: ix for (ix, lb) in enumerate(labels)}
ix_to_lb = {ix: lb for (ix, lb) in enumera... |
# Algorithms for computer algebra, Geddes
# a, b in R, R es D.F.U.
# return gcd(a, b)
def primitive_euclidean(a, b, R):
c = R.primitive_part(a)
d = R.primitive_part(b)
while d != R.zero():
r = primitive_reminder(c, d, R)
c = d
d = R.primitive_part(r)
F = R.get_domain()
gamma... | def primitive_euclidean(a, b, R):
c = R.primitive_part(a)
d = R.primitive_part(b)
while d != R.zero():
r = primitive_reminder(c, d, R)
c = d
d = R.primitive_part(r)
f = R.get_domain()
gamma = F.gcd(R.cont(a), R.cont(b))
g = R.mul(gamma, c)
return g
def primitive_remi... |
a = float(input("Enter The Base : "))
b = float(input("Enter The Hight : "))
Area = 0.5 * a * b
print("Triangle Area is:",Area)
| a = float(input('Enter The Base : '))
b = float(input('Enter The Hight : '))
area = 0.5 * a * b
print('Triangle Area is:', Area) |
def test_publish(judge_command):
judge_command(
"publish foo bar", {"command": "publish", "channel": "foo", "message": "bar"}
)
def test_subscribe(judge_command):
judge_command("subscribe foo bar", {"command": "subscribe", "channel": "bar"})
def test_pubsub(judge_command):
judge_command(
... | def test_publish(judge_command):
judge_command('publish foo bar', {'command': 'publish', 'channel': 'foo', 'message': 'bar'})
def test_subscribe(judge_command):
judge_command('subscribe foo bar', {'command': 'subscribe', 'channel': 'bar'})
def test_pubsub(judge_command):
judge_command('PUBSUB NUMSUB foo b... |
def check_hashtarget(bible_hash, target):
""" tests if the biblepay hash is valid for the hashtarget, means that is it lower.
True = is lower and all is fine """
rs = False
try:
rs = int(bible_hash, 16) < int(target, 16)
except:
pass
return rs
def validate_bi... | def check_hashtarget(bible_hash, target):
""" tests if the biblepay hash is valid for the hashtarget, means that is it lower.
True = is lower and all is fine """
rs = False
try:
rs = int(bible_hash, 16) < int(target, 16)
except:
pass
return rs
def validate_bibleplay_address_... |
def reverse_string(x):
# Reversing a string
output = ""
for c in x:
output = c + output
return output
print(reverse_string("hello"))
def reverse_string_2(x):
output = [None] * len(x)
idx = len(x)-1
for c in x:
output[idx] = c
idx -= 1
return ''.join(output)
pri... | def reverse_string(x):
output = ''
for c in x:
output = c + output
return output
print(reverse_string('hello'))
def reverse_string_2(x):
output = [None] * len(x)
idx = len(x) - 1
for c in x:
output[idx] = c
idx -= 1
return ''.join(output)
print(reverse_string_2('hell... |
class Integer:
def __init__(self, value):
self.value = value
@classmethod
def from_float(cls, value):
if isinstance(value, float):
return cls(int(value))
return 'value is not a float'
@classmethod
def from_roman(cls, value):
roman = {'I': 1, 'V': 5, 'X':... | class Integer:
def __init__(self, value):
self.value = value
@classmethod
def from_float(cls, value):
if isinstance(value, float):
return cls(int(value))
return 'value is not a float'
@classmethod
def from_roman(cls, value):
roman = {'I': 1, 'V': 5, 'X'... |
file = open("4_dna_sequences.txt")
all_lines = file.readlines()
for line in all_lines:
print("> " + line[:5] + '\n' + line[8:].replace('"', "").replace("-", "").upper())
file.close()
| file = open('4_dna_sequences.txt')
all_lines = file.readlines()
for line in all_lines:
print('> ' + line[:5] + '\n' + line[8:].replace('"', '').replace('-', '').upper())
file.close() |
def invert_dictionary(d):
""" (dict) -> dict
Precondition: Values of d are immutable
Return a new dictionary where the keys in the new dictionary are
the values from d, and the values are lists of the keys
that are associated with those values from d.
>>> invert_dictionary({"cherry": "red", "... | def invert_dictionary(d):
""" (dict) -> dict
Precondition: Values of d are immutable
Return a new dictionary where the keys in the new dictionary are
the values from d, and the values are lists of the keys
that are associated with those values from d.
>>> invert_dictionary({"cherry": "red", "... |
N, M, A, B = map(int, input().split())
t = N
for i in range(M):
if t <= A:
t += B
c = int(input())
t -= c
if t < 0:
print(i + 1)
break
else:
print('complete')
| (n, m, a, b) = map(int, input().split())
t = N
for i in range(M):
if t <= A:
t += B
c = int(input())
t -= c
if t < 0:
print(i + 1)
break
else:
print('complete') |
def handle_num(num: str):
s = ''
for c in num:
if c != ' ':
s += c
if s[:1] == '0':
s = '0o'+s[1:]
return int(s, 8)
return int(s)
def handle_article(path_from, path_to):
with open(path_from, 'r') as f_in:
with open(path_to, 'w') as f_out:
for ... | def handle_num(num: str):
s = ''
for c in num:
if c != ' ':
s += c
if s[:1] == '0':
s = '0o' + s[1:]
return int(s, 8)
return int(s)
def handle_article(path_from, path_to):
with open(path_from, 'r') as f_in:
with open(path_to, 'w') as f_out:
fo... |
def search1(pat: str, txt: str):
M = len(pat)
N = len(txt)
for i in range(N - M + 1):
j = 0
while j < M:
if txt[i + j] == pat[j]: # index should be i + j for txt
j += 1
else:
break
if j == M:
return i
return N
... | def search1(pat: str, txt: str):
m = len(pat)
n = len(txt)
for i in range(N - M + 1):
j = 0
while j < M:
if txt[i + j] == pat[j]:
j += 1
else:
break
if j == M:
return i
return N
def search2(pat: str, txt: str):
... |
class PdfPageContainer:
def __init__(self):
self.triples = []
self.shapes = []
| class Pdfpagecontainer:
def __init__(self):
self.triples = []
self.shapes = [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.