content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
| print('Hai')
print('Hai')
print('Hai')
print('Hai')
print('Hai')
print('Hai')
print('Hai') |
COUNTRIES = {
'colombia': 31,
'argentina': 45,
'venezuela': 12,
'peru': 22,
'ecuador': 55,
'mexico': 143,
}
while True:
country = str(input('Ingresa el nombre del pais: ')).lower()
try:
print('El numero de habiantes en {} es de {} millones de habitantes'. format(country , COUNTRIES[country]))
except ... | countries = {'colombia': 31, 'argentina': 45, 'venezuela': 12, 'peru': 22, 'ecuador': 55, 'mexico': 143}
while True:
country = str(input('Ingresa el nombre del pais: ')).lower()
try:
print('El numero de habiantes en {} es de {} millones de habitantes'.format(country, COUNTRIES[country]))
except Key... |
#!/usr/bin/env python
# coding: utf-8
# # Pachyderm-Seldon Integration: Version Controlled Models
#
# [Pachyderm](https://pachyderm.io/) is a data science platform that combines Data Lineage with End-to-End Pipelines. [Seldon-Core](https://www.seldon.io/tech/products/core/) is an open-source platform for rapidly depl... | get_ipython().system('pachctl version --client-only')
get_ipython().system('kubectl get po -A')
get_ipython().system('kubectl create ns pachyderm')
get_ipython().system('pachctl deploy local --no-expose-docker-socket --no-dashboard --namespace pachyderm')
get_ipython().system('kubectl rollout status deployment -n pachy... |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
curr_dir, curr_pos = 0, (0, 0)
for instruction in instructions:
if instruction == "R":
curr_dir = (curr_dir + 1) % 4
elif instructio... | class Solution:
def is_robot_bounded(self, instructions: str) -> bool:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
(curr_dir, curr_pos) = (0, (0, 0))
for instruction in instructions:
if instruction == 'R':
curr_dir = (curr_dir + 1) % 4
elif instruction ... |
# Time: ctor: O(1)
# addText: O(l)
# deleteText: O(k)
# cursorLeft: O(k)
# cursorRight: O(k)
# Space: O(n)
# design, stack
class TextEditor(object):
def __init__(self):
self.__LAST_COUNT = 10
self.__left = []
self.__right = []
def addText(self... | class Texteditor(object):
def __init__(self):
self.__LAST_COUNT = 10
self.__left = []
self.__right = []
def add_text(self, text):
"""
:type text: str
:rtype: None
"""
for x in text:
self.__left.append(x)
def delete_text(self, k):... |
def distance(n, point1, point2):
point1_x, point1_y = point1
point2_x, point2_y = point2
if abs(point1_x) >= n or abs(point1_y) >= n or abs(point2_x) >= n or abs(point2_y) >= n:
raise ValueError("coords are not from given range")
dist_x = min(abs(point1_x - point2_x), point1_x + (n - point2_x)... | def distance(n, point1, point2):
(point1_x, point1_y) = point1
(point2_x, point2_y) = point2
if abs(point1_x) >= n or abs(point1_y) >= n or abs(point2_x) >= n or (abs(point2_y) >= n):
raise value_error('coords are not from given range')
dist_x = min(abs(point1_x - point2_x), point1_x + (n - poin... |
"""
https://leetcode.com/problems/lru-cache/
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or in... | """
https://leetcode.com/problems/lru-cache/
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or in... |
number = input("Input a number to invert its order:")
print("Printing using string: " + number[::-1])
inverted = 0
exponent = len(number)
number = int(number)
while number >= 1:
inverted += (number % 10) * (10 ** (exponent - 1))
exponent -= 1
number = number // 10 # the floor division // rounds t... | number = input('Input a number to invert its order:')
print('Printing using string: ' + number[::-1])
inverted = 0
exponent = len(number)
number = int(number)
while number >= 1:
inverted += number % 10 * 10 ** (exponent - 1)
exponent -= 1
number = number // 10
print('Printing using way faster and elegant ma... |
__version_tuple__ = (0, 6, 0, 'dev.1')
__version__ = '0.6.0-dev.1'
__version_tuple_js__ = (0, 6, 0, 'dev.1')
__version_js__ = '0.6.0-dev.1'
# kept for embedding in offline mode, we don't care about the patch version since it should be compatible
__version_threejs__ = '0.97'
| __version_tuple__ = (0, 6, 0, 'dev.1')
__version__ = '0.6.0-dev.1'
__version_tuple_js__ = (0, 6, 0, 'dev.1')
__version_js__ = '0.6.0-dev.1'
__version_threejs__ = '0.97' |
#===============================================================================
# Copyright 2022 Intel Corporation
#
# 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.a... | def _check_is_fitted(estimator, attributes=None, *, msg=None):
if msg is None:
msg = "This %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator."
if not hasattr(estimator, 'fit'):
raise type_error('%s is not an estimator instance.' % estimator)
... |
class BubbleSort:
name = 'Bubble sort'
history = []
focus = []
def reset(self):
self.history = []
self.focus = []
def sort(self, unsorted_list):
self.bubble_sort(unsorted_list)
return unsorted_list
# stable
# O(1) space complexity
# O(n2) comparisons... | class Bubblesort:
name = 'Bubble sort'
history = []
focus = []
def reset(self):
self.history = []
self.focus = []
def sort(self, unsorted_list):
self.bubble_sort(unsorted_list)
return unsorted_list
def bubble_sort(self, array):
for (index, _) in enumera... |
"""
Event Calendar Module.
The event calendar channel is how the Events cog shows upcoming events
to users. It is configured per server, with two types of events - member
events, and recurring events.
Member events are initiated by members and approved by moderators in
an approval channel, while recurring events, whi... | """
Event Calendar Module.
The event calendar channel is how the Events cog shows upcoming events
to users. It is configured per server, with two types of events - member
events, and recurring events.
Member events are initiated by members and approved by moderators in
an approval channel, while recurring events, whi... |
def hello() -> str:
"""
Used to test that the library is installed successfully.
Returns
----------
The string 'world'.
"""
return "world"
| def hello() -> str:
"""
Used to test that the library is installed successfully.
Returns
----------
The string 'world'.
"""
return 'world' |
{
'includes': [
'../defaults.gypi',
],
'targets': [
{
'target_name':
'DirectZobEngine',
'type':
'static_library',
'dependencies': [
'../dependencies/minifb/minifb.gyp:minifb',
'../dependencies/tinyxml... | {'includes': ['../defaults.gypi'], 'targets': [{'target_name': 'DirectZobEngine', 'type': 'static_library', 'dependencies': ['../dependencies/minifb/minifb.gyp:minifb', '../dependencies/tinyxml/tinyxml.gyp:tinyxml', '../dependencies/nanojpeg/nanojpeg.gyp:nanojpeg', '../dependencies/lodepng/lodepng.gyp:lodepng', '../dep... |
"""
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
"""
class Solution():
# @param A : tuple of integers
# @return an integer
def maximumGap(self, A):
n = len(A)
index = dict()
for i in range(n):
if A[i] in index:
... | """
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
"""
class Solution:
def maximum_gap(self, A):
n = len(A)
index = dict()
for i in range(n):
if A[i] in index:
index[A[i]].append[i]
else:
... |
fruits = ["apple","orange","pear"]
for fruit in fruits:
print(fruit)
print(fruits[0])
print(fruits[1])
print(fruits[2])
for v in range(10):
print(v)
for v in range(5,10):
print(v)
for v in range(len(fruits)):
print(v)
print(fruits[v])
print(len(fruits)) | fruits = ['apple', 'orange', 'pear']
for fruit in fruits:
print(fruit)
print(fruits[0])
print(fruits[1])
print(fruits[2])
for v in range(10):
print(v)
for v in range(5, 10):
print(v)
for v in range(len(fruits)):
print(v)
print(fruits[v])
print(len(fruits)) |
# r/GlobalOffensive/comments/cjhcpy/game_state_integration_a_very_large_and_indepth
# Game state integration round descriptor
class Round(dict):
# The phase of the current round. Value is freezetime during the initial
# freeze time as well as team timeouts, live when the round is live, and
# over when the... | class Round(dict):
@property
def phase(self):
return self.get('phase')
@property
def win_team(self):
return self.get('win_team')
@property
def bomb(self):
return self.get('bomb') |
#!/usr/bin/env python
__all__ = (
'Goat',
'_Velociraptor'
)
class Goat:
@property
def name(self):
return "George"
class _Velociraptor:
@property
def name(self):
return "Cuddles"
class SecretDuck:
@property
def name(self):
return "None of your business"
| __all__ = ('Goat', '_Velociraptor')
class Goat:
@property
def name(self):
return 'George'
class _Velociraptor:
@property
def name(self):
return 'Cuddles'
class Secretduck:
@property
def name(self):
return 'None of your business' |
#def basic(x, y):
# answer = x * y + 3
# # print(answer)
# # return f"{x} * {y} + 3 = {answer}"
# return answer
#
#
#print(basic(7, 10))
#grade = 25 + basic(7, 10)
#print(grade)
#
#
#def more_advanced(x, y, store_data=True, save_file="myanswer.txt"):
# ans = x ** (y-3)
# if store_data:
# with o... | def solar_args(*objects):
print(objects)
s = sum(objects)
print(s)
solar_args(4, 8, 15, 16, 23, 42)
def whiteboard(**kwargs):
print(kwargs)
for kw in kwargs.keys():
print(kw, kwargs[kw])
whiteboard(instructor='Sam', lunch='awesome', eod='6:30')
def full(x, y, *args, washer_cycle='normal', ... |
def LinearSearch(array, key):
for index, theValue in enumerate(array):
if(array[index] == key):
return index
return -1
def main():
theArray = [2, 5, 25, 6, 8, 9, 1, 0, 6, 8, 4, 5, 66, 548, 889]
print("The index of the 25 is: ", LinearSearch(theArray, 25))
print("The index of th... | def linear_search(array, key):
for (index, the_value) in enumerate(array):
if array[index] == key:
return index
return -1
def main():
the_array = [2, 5, 25, 6, 8, 9, 1, 0, 6, 8, 4, 5, 66, 548, 889]
print('The index of the 25 is: ', linear_search(theArray, 25))
print('The index o... |
[x**2 for x in range(1, 10)]
[x**2 for x in range(1, 10) if x % 2 == 0]
powers_of_2 = []
for x in range(1, 10):
powers_of_2.append(x**2)
powers_of_2 = []
for x in range(1, 10):
if x % 2 == 0:
powers_of_2.append(x**2)
[x*y for x in range(1, 10) if x % 2 == 1 for y in range(10) if y % 2 == 1]
... | [x ** 2 for x in range(1, 10)]
[x ** 2 for x in range(1, 10) if x % 2 == 0]
powers_of_2 = []
for x in range(1, 10):
powers_of_2.append(x ** 2)
powers_of_2 = []
for x in range(1, 10):
if x % 2 == 0:
powers_of_2.append(x ** 2)
[x * y for x in range(1, 10) if x % 2 == 1 for y in range(10) if y % 2 == 1] |
# Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
# Example 1:
# Input: A = "ab", B = "ba"
# Output: true
# Example 2:
# Input: A = "ab", B = "ab"
# Output: false
# Example 3:
# Input: A = "aa", B = "aa"
# Output: true
# Example 4:
#... | class Solution:
def buddy_strings(self, a, b):
c = {}
for i in range(len(a)):
if a[i] != b[i]:
c[i] = a[i]
if len(c) != 2:
return False
r = ''
for i in range(len(b)):
if i in c:
r += c[i]
con... |
S = [input() for _ in range(4)]
if sorted(S) == ['2B', '3B', 'H', 'HR']:
print('Yes')
else:
print('No')
| s = [input() for _ in range(4)]
if sorted(S) == ['2B', '3B', 'H', 'HR']:
print('Yes')
else:
print('No') |
# -*- coding: utf-8 -*-
DATABASE_TIMEZONE = 'UTC'
DEFAULT_TIMEZONE = 'Asia/Shanghai'
| database_timezone = 'UTC'
default_timezone = 'Asia/Shanghai' |
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/bihar_pnc.xml
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/bihar_del.xml
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/b... | pnc = 'http://bihar.commcarehq.org/pregnancy/pnc'
delivery = 'http://bihar.commcarehq.org/pregnancy/del'
registration = 'http://bihar.commcarehq.org/pregnancy/registration'
ebf = 'http://bihar.commcarehq.org/pregnancy/ebf'
cf = 'http://bihar.commcarehq.org/pregnancy/cf'
bp = 'http://bihar.commcarehq.org/pregnancy/bp'
n... |
class A:
def y(self):
pass
a = A()
a.y()
| class A:
def y(self):
pass
a = a()
a.y() |
a = int(input())
def match(p):
st = []
for c in p:
if c == '(':
st.append(c)
if c == ')':
if len(st) == 0:
print("NO")
return
else:
st.pop(0)
if len(st) == 0:
print("YES")
else:
print("NO... | a = int(input())
def match(p):
st = []
for c in p:
if c == '(':
st.append(c)
if c == ')':
if len(st) == 0:
print('NO')
return
else:
st.pop(0)
if len(st) == 0:
print('YES')
else:
print('NO... |
def moveZero(arr):
length = len(arr)
i = 0
k = 0
while k < length:
if arr[i] == 0:
temp = arr.pop(i)
arr.append(temp)
i -= 1
i += 1
k += 1
arr = [0, 1, 0, 3, 12, 0]
moveZero(arr)
print(arr) | def move_zero(arr):
length = len(arr)
i = 0
k = 0
while k < length:
if arr[i] == 0:
temp = arr.pop(i)
arr.append(temp)
i -= 1
i += 1
k += 1
arr = [0, 1, 0, 3, 12, 0]
move_zero(arr)
print(arr) |
#
# PySNMP MIB module Dell-rldot1q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-rldot1q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:57:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
# This Python file contains the constants used by any Python codes leveraged by the contact book application
# for ease of maintainability.
ROOT_DIR_CONTACTS_DICT_FILE = 'contact_book/src/contact_book/data/'
FILE_NAME_CONTACTS_DICT = 'contacts_dict.txt'
TEXT_FONT_AND_SIZE_FORMAT_WINDOW_FRAME = "*font"
TEXT_FONT_AND_S... | root_dir_contacts_dict_file = 'contact_book/src/contact_book/data/'
file_name_contacts_dict = 'contacts_dict.txt'
text_font_and_size_format_window_frame = '*font'
text_font_and_size_main_window_frame = 'Verdana 12'
dimensions_format_window_frame = '{}x{}'
height_main_window_frame = 260
width_main_window_frame = 575
wid... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
if root == None:
return 0
self.max_count = 0
self.caller(... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longest_univalue_path(self, root: TreeNode) -> int:
if root == None:
return 0
self.max_count = 0
self.caller(root, 0)
return self.max_... |
a = list(map(int, input().split()))
def kangaroo(x1, v1, x2, v2):
if x1>x2 and v1>v2:
return'NO'
elif x2>x1 and v2>v1:
return 'NO'
else:
result = 'NO'
for i in range(10000):
if x1+i*v1==x2+i*v2:
result = 'YES'
break
retu... | a = list(map(int, input().split()))
def kangaroo(x1, v1, x2, v2):
if x1 > x2 and v1 > v2:
return 'NO'
elif x2 > x1 and v2 > v1:
return 'NO'
else:
result = 'NO'
for i in range(10000):
if x1 + i * v1 == x2 + i * v2:
result = 'YES'
br... |
"""tnz utility functions
Usage: from . import _util.py
Copyright 2021 IBM Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
__author__ = "Neil Johnson"
_SESSION_PS_SIZES = {
"2": (24, 80),
"3": (32, 80),
"4": (43, 80),
"5": (27, 132),
"6": (24, 132),
"7": (36, 80),
"8": ... | """tnz utility functions
Usage: from . import _util.py
Copyright 2021 IBM Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
__author__ = 'Neil Johnson'
_session_ps_sizes = {'2': (24, 80), '3': (32, 80), '4': (43, 80), '5': (27, 132), '6': (24, 132), '7': (36, 80), '8': (36, 132), '9': (48, 80), '10':... |
def operator_insertor(n):
res=helper("123456789", 0, n)-1
return res if res!=float("inf") else None
def helper(s, index, n):
if index>=len(s):
return 0 if n==0 else float("inf")
res=float("inf")
cur=0
for i in range(index, len(s)):
cur=cur*10+int(s[i])
res=min(res, helper... | def operator_insertor(n):
res = helper('123456789', 0, n) - 1
return res if res != float('inf') else None
def helper(s, index, n):
if index >= len(s):
return 0 if n == 0 else float('inf')
res = float('inf')
cur = 0
for i in range(index, len(s)):
cur = cur * 10 + int(s[i])
... |
{
"targets": [
{
"target_name": "rdiff",
"sources": [
"rdiff.cc"
],
"link_settings": {
"libraries": [
"-lrsync",
"-lz"
]
},
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
}
]
} | {'targets': [{'target_name': 'rdiff', 'sources': ['rdiff.cc'], 'link_settings': {'libraries': ['-lrsync', '-lz']}, 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
class UniformResourceLocatable:
"""
Represents an object with a URL.
"""
__slots__ = ()
_fields = {
"resource_path": "resourcePath",
"url": "url",
}
@property
def resource_path(self):
"""
An HTTP path to the resource.
:type: :class:`str`
... | class Uniformresourcelocatable:
"""
Represents an object with a URL.
"""
__slots__ = ()
_fields = {'resource_path': 'resourcePath', 'url': 'url'}
@property
def resource_path(self):
"""
An HTTP path to the resource.
:type: :class:`str`
"""
return self... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
pre = -100000
cnt = 0
i = -1
j = 0
while j < len(nums):
if nums[j] != pre:
i += 1
nums[i] = nums[j]
cnt = 1
elif cnt < 2:
i += 1
nums[i] = nums[j]
cnt += 1
pre = nu... | class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
pre = -100000
cnt = 0
i = -1
j = 0
while j < len(nums):
if nums[j] != pre:
i += 1
nums[i] = nums[j]
cnt = 1
elif cnt < 2:
... |
class BaseArg:
@staticmethod
def read_argument(parser):
raise NotImplementedError()
@staticmethod
def add_argument(parser):
raise NotImplementedError()
| class Basearg:
@staticmethod
def read_argument(parser):
raise not_implemented_error()
@staticmethod
def add_argument(parser):
raise not_implemented_error() |
"""Constants for Gafaelfawr."""
ALGORITHM = "RS256"
"""JWT algorithm to use for all tokens."""
COOKIE_NAME = "gafaelfawr"
"""Name of the state cookie."""
HTTP_TIMEOUT = 20.0
"""Timeout (in seconds) for outbound HTTP requests to auth providers."""
MINIMUM_LIFETIME = 5 * 60
"""Minimum expiration lifetime for a token ... | """Constants for Gafaelfawr."""
algorithm = 'RS256'
'JWT algorithm to use for all tokens.'
cookie_name = 'gafaelfawr'
'Name of the state cookie.'
http_timeout = 20.0
'Timeout (in seconds) for outbound HTTP requests to auth providers.'
minimum_lifetime = 5 * 60
'Minimum expiration lifetime for a token in seconds.'
oidc_... |
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-DUPE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-DUPE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:15:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
"""
File contains all needed constants for net file reading
"""
EDGE_SECTION_HEADER = "$STRECKE"
EDGE_NAME_HEADER = "NR"
EDGE_FROM_NAME_HEADER = "VONKNOTNR"
EDGE_TO_NAME_HEADER = "NACHKNOTNR"
LINE_SECTION_HEADER = "$LINE"
LINE_NAME_HEADER = "NAME"
LINE_VSYSCODE_HEADER = "TSYSCODE"
LINE_VEHICLE_COMBINATION_NUMBER_HEADER... | """
File contains all needed constants for net file reading
"""
edge_section_header = '$STRECKE'
edge_name_header = 'NR'
edge_from_name_header = 'VONKNOTNR'
edge_to_name_header = 'NACHKNOTNR'
line_section_header = '$LINE'
line_name_header = 'NAME'
line_vsyscode_header = 'TSYSCODE'
line_vehicle_combination_number_header... |
"""
A group of code statements which can perform some specific task
Methods are reusable and can be called when needed in the code
"""
def sum_nums(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return n1 + n2
sum1 = sum_nums(2, 8)
sum2 = sum_nums(3, 3)
string_ad... | """
A group of code statements which can perform some specific task
Methods are reusable and can be called when needed in the code
"""
def sum_nums(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return n1 + n2
sum1 = sum_nums(2, 8)
sum2 = sum_nums(3, 3)
string_add = ... |
"""
public, protected, private
_ privado/protected (public _)
__ privado (_NOMECLASSE__nomeatributo)
"""
class BaseDeDados:
def __init__(self):
self.__dados = {}
@property
def dados(self):
return self.__dados
def inserir_clientes(self, id, nome):
if 'clientes' not in self.__d... | """
public, protected, private
_ privado/protected (public _)
__ privado (_NOMECLASSE__nomeatributo)
"""
class Basededados:
def __init__(self):
self.__dados = {}
@property
def dados(self):
return self.__dados
def inserir_clientes(self, id, nome):
if 'clientes' not in self.__d... |
{
'name': 'Base Kanban',
'category': 'Hidden',
'description': """
OpenERP Web kanban view.
========================
""",
'version': '2.0',
'depends': ['web'],
'js': [
'static/src/js/kanban.js'
],
'css': [
'static/src/css/kanban.css'
],
'qweb' : [
'static/... | {'name': 'Base Kanban', 'category': 'Hidden', 'description': '\nOpenERP Web kanban view.\n========================\n\n', 'version': '2.0', 'depends': ['web'], 'js': ['static/src/js/kanban.js'], 'css': ['static/src/css/kanban.css'], 'qweb': ['static/src/xml/*.xml'], 'auto_install': True} |
"""
Extract the dictionary definition: Takes the third element s3 returned by `split_entry()`
>>> from GDLC.GDLC import *
>>> dml = '''\
... <blockquote class="calibre27">
... <p class="ps">Definition here.</p>
... <p class="p">More details here.</p>
... <p class="p">Even more details here.</p>
... </blockquote... | """
Extract the dictionary definition: Takes the third element s3 returned by `split_entry()`
>>> from GDLC.GDLC import *
>>> dml = '''... <blockquote class="calibre27">
... <p class="ps">Definition here.</p>
... <p class="p">More details here.</p>
... <p class="p">Even more details here.</p>
... </blockquote>'... |
# Find the cube root of a perfect cube
n = int(input("Enter an integer: "))
ans = 0
while ans ** 3 < abs(n):
ans += 1
if ans ** 3 != abs(n):
print(n, "is not a perfect cube")
else:
if n < 0:
ans = -ans
print("Cube root of", n, "is", ans) | n = int(input('Enter an integer: '))
ans = 0
while ans ** 3 < abs(n):
ans += 1
if ans ** 3 != abs(n):
print(n, 'is not a perfect cube')
else:
if n < 0:
ans = -ans
print('Cube root of', n, 'is', ans) |
class Solution:
def replaceElements(self, arr: list[int]) -> list[int]:
largest_value = -1
for index, num in reversed(list(enumerate(arr))):
arr[index] = largest_value
largest_value = max(largest_value, num)
return arr
tests = [
(
([17, 18, 5, 4, 6, 1],... | class Solution:
def replace_elements(self, arr: list[int]) -> list[int]:
largest_value = -1
for (index, num) in reversed(list(enumerate(arr))):
arr[index] = largest_value
largest_value = max(largest_value, num)
return arr
tests = [(([17, 18, 5, 4, 6, 1],), [18, 6, 6,... |
# nlantau, 2020-11-09
def evens_and_odds(n):
return f"{n:b}" if n % 2 == 0 else f"{n:x}"
print(evens_and_odds(1))
print(evens_and_odds(2))
print(evens_and_odds(3))
print(evens_and_odds(13))
| def evens_and_odds(n):
return f'{n:b}' if n % 2 == 0 else f'{n:x}'
print(evens_and_odds(1))
print(evens_and_odds(2))
print(evens_and_odds(3))
print(evens_and_odds(13)) |
# -*- coding: utf-8 -*-
'''
Given n non-negative integers a1, a2, ..., an,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the ... | """
Given n non-negative integers a1, a2, ..., an,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the most water.
Note: You ma... |
a = 5
b = a
print(a,b)
a = 3
print(a,b)
| a = 5
b = a
print(a, b)
a = 3
print(a, b) |
# Activity Select
def printMaxActivity(s, f):
n = len(f)
print('The Following Activitices are selected.')
i = 0
print(i)
for j in range(n):
if (s[j] >= f[i]):
print(j)
i = j
s = [1, 3, 0, 5, 8, 5]
f = [2, 4, 6, 7, 9, 9]
printMaxActivity(s, f)
''... | def print_max_activity(s, f):
n = len(f)
print('The Following Activitices are selected.')
i = 0
print(i)
for j in range(n):
if s[j] >= f[i]:
print(j)
i = j
s = [1, 3, 0, 5, 8, 5]
f = [2, 4, 6, 7, 9, 9]
print_max_activity(s, f)
'\nOutput:\n>>>\nThe Following Activitice... |
# Roman Ramirez, rr8rk@virginia.edu
# Advent of Code 2021, Day 09: Smoke Basin
#%% LONG INPUT
my_input = []
with open('input.txt', 'r') as f:
for line in f:
my_input.append(line.strip('\n'))
#%% EXAMPLE INPUT
my_input = [
'2199943210',
'3987894921',
'9856789892',
'8767896789',
'989... | my_input = []
with open('input.txt', 'r') as f:
for line in f:
my_input.append(line.strip('\n'))
my_input = ['2199943210', '3987894921', '9856789892', '8767896789', '9899965678']
heights = [[int(s) for s in x] for x in my_input]
def is_low_point(x, y):
low_accum = True
val = heights[y][x]
if x ... |
#program that guess a number between 0 to 100
low=0
High=100
medium=(low+High) //2
state =True
print("please Enter a number between 0 to 100 ")
while state :
print("is your secret number:"+ str(medium))
guess=input("Enter h if indicates is high and enter 'l' is low ")
if guess=='c':
print("GAME OV... | low = 0
high = 100
medium = (low + High) // 2
state = True
print('please Enter a number between 0 to 100 ')
while state:
print('is your secret number:' + str(medium))
guess = input("Enter h if indicates is high and enter 'l' is low ")
if guess == 'c':
print('GAME OVER . Your secret number was Medium... |
def adiciona_item(nome, lista):
backup=[]
if len(lista)==0:
lista.append(nome)
return
else:
for i in range(len(lista)-1, -1, -1):
if nome<lista[i]:
if nome<lista[i] and i == 0:
backup.append(lista.pop())
lista.append... | def adiciona_item(nome, lista):
backup = []
if len(lista) == 0:
lista.append(nome)
return
else:
for i in range(len(lista) - 1, -1, -1):
if nome < lista[i]:
if nome < lista[i] and i == 0:
backup.append(lista.pop())
li... |
# Currency FX rate settings
BASE_URL = 'https://www.x-rates.com/calculator/?from={}&to={}&amount=1'
BASE_CURRENCY = 'JPY'
TO_CURRENCY_LIST = ['AUD', 'CNY', 'USD', 'GBP']
# Alert threshold for sending push notification
ALERT_THRESHOLD = [
{'fx_pair': 'JPY/AUD', 'buy-threshold': 0.0134, 'sell-threshold': 0.0137},
... | base_url = 'https://www.x-rates.com/calculator/?from={}&to={}&amount=1'
base_currency = 'JPY'
to_currency_list = ['AUD', 'CNY', 'USD', 'GBP']
alert_threshold = [{'fx_pair': 'JPY/AUD', 'buy-threshold': 0.0134, 'sell-threshold': 0.0137}, {'fx_pair': 'JPY/USD', 'buy-threshold': 0.009, 'sell-threshold': 0.01}, {'fx_pair': ... |
_base_ = [
'../_base_/models/resnet18.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024.py',
'../_base_/default_runtime.py'
]
actnn = True
data = dict(
samples_per_gpu=256, # 256*4 = 1024
workers_per_gpu=8,
)
log_config = dict(
interval=100,
hooks=[
... | _base_ = ['../_base_/models/resnet18.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py']
actnn = True
data = dict(samples_per_gpu=256, workers_per_gpu=8)
log_config = dict(interval=100, hooks=[dict(type='TextLoggerHook'), dict(type='WandbLoggerHook', ini... |
"""
.. _hosted_multi_images:
Multiple Container Images in a Single Workflow
----------------------------------------------
When working locally, it is typically preferable to install all requirements of your project locally (maybe in a single virtual environment). It gets complicated when you want to deploy your code... | """
.. _hosted_multi_images:
Multiple Container Images in a Single Workflow
----------------------------------------------
When working locally, it is typically preferable to install all requirements of your project locally (maybe in a single virtual environment). It gets complicated when you want to deploy your code... |
train_dataset_seed = 1234
test_dataset_seed = 4321
n_test_dataset = 100
is_subtype = mlprogram.languages.python.IsSubtype()
normalize_dataset = mlprogram.utils.transform.NormalizeGroundTruth(
normalize=mlprogram.functools.Sequence(
funcs=collections.OrderedDict(
items=[["parse", parser.parse], ... | train_dataset_seed = 1234
test_dataset_seed = 4321
n_test_dataset = 100
is_subtype = mlprogram.languages.python.IsSubtype()
normalize_dataset = mlprogram.utils.transform.NormalizeGroundTruth(normalize=mlprogram.functools.Sequence(funcs=collections.OrderedDict(items=[['parse', parser.parse], ['unparse', parser.unparse]]... |
def c3():
global x1
global y1
global x2
global y2
global x3
global y3
global x4
global y4
x1=float(input("What are your x1?"))
y1=float(input("What are your y1?"))
x2=float(input("What are your x2?"))
y2=float(input("What are your y2?"))
x3=float(input("What are your x3?"))
y3=float(input("W... | def c3():
global x1
global y1
global x2
global y2
global x3
global y3
global x4
global y4
x1 = float(input('What are your x1?'))
y1 = float(input('What are your y1?'))
x2 = float(input('What are your x2?'))
y2 = float(input('What are your y2?'))
x3 = float(input('What... |
SHOW_FILM_NAMES = True
# SHOW_FILM_NAMES = False
# UPDATE_TEXT_BOX_LOC = False
UPDATE_TEXT_BOX_LOC = True
SHORTEN_FILM_NAMES = True
# READ_PARTIAL_DB = True
READ_PARTIAL_DB = False
# HIGH_RES = False
HIGH_RES = True
EXPIRE_FILM_NAMES = True
# EXPIRE_FILM_NAMES = False
#SLIDING_WINDOW = False
SLIDING_WINDOW = True... | show_film_names = True
update_text_box_loc = True
shorten_film_names = True
read_partial_db = False
high_res = True
expire_film_names = True
sliding_window = True
window_width = 5
add_zoom_out = True
add_end_delay = True
w_high_res = 1920
h_high_res = 1080
font_size_h_res = 3
w_low_res = 1080
h_low_res = 720
font_size_... |
def monkey_trouble(a_smile, b_smile):
if a_smile is True and b_smile is True:
return True
elif a_smile is False and b_smile is False:
return True
else:
return False
| def monkey_trouble(a_smile, b_smile):
if a_smile is True and b_smile is True:
return True
elif a_smile is False and b_smile is False:
return True
else:
return False |
class Queue:
def __init__(self):
self.elements = []
def __str__(self):
return f"{[element for element in self.elements]}"
def __repr__(self):
return f"{[element for element in self.elements]}"
def enqueue(self, element):
self.elements.append(element)
def dequeue(s... | class Queue:
def __init__(self):
self.elements = []
def __str__(self):
return f'{[element for element in self.elements]}'
def __repr__(self):
return f'{[element for element in self.elements]}'
def enqueue(self, element):
self.elements.append(element)
def dequeue(... |
TEMP_ENV_VARS = {
'TELEGRAM_WEBHOOK_KEY': '',
}
ENV_VARS_TO_SUSPEND = [
] | temp_env_vars = {'TELEGRAM_WEBHOOK_KEY': ''}
env_vars_to_suspend = [] |
#
# PySNMP MIB module ALCATEL-IND1-TIMETRA-SERV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-TIMETRA-SERV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:19:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (t_filter_id,) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-FILTER-MIB', 'TFilterID')
(tmnx_sr_objs, timetra_srmib_modules, tmnx_sr_notify_prefix, tmnx_sr_confs) = mibBuilder.importSymbols('ALCATEL-IND1-TIMETRA-GLOBAL-MIB', 'tmnxSRObjs', 'timetraSRMIBModules', 'tmnxSRNotifyPrefix', 'tmnxSRConfs')
(t_scheduler_polic... |
spacy_model_names = {
"en": "en_core_web_md",
"fr": "fr_core_news_md",
"es": "es_core_news_md"
}
# 17 for English.
# 15 for French: replace "INTJ" (7 entries) or "SYM" with "X" (1296 entries).
# 16 for Spanish: Change "X" (1 entry) to "INTJ" (27 entries)
spacy_pos_dict = {
"en": ['ADJ', 'ADP', 'ADV',... | spacy_model_names = {'en': 'en_core_web_md', 'fr': 'fr_core_news_md', 'es': 'es_core_news_md'}
spacy_pos_dict = {'en': ['ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'INTJ', 'NOUN', 'NUM', 'PART', 'PRON', 'PROPN', 'PUNCT', 'SCONJ', 'SYM', 'VERB', 'X'], 'fr': ['ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'NOUN', 'NUM', 'PA... |
class GeneratorStatus(Enum, IComparable, IFormattable, IConvertible):
"""
Used by System.Windows.Controls.ItemContainerGenerator to indicate the status of its item generation.
enum GeneratorStatus,values: ContainersGenerated (2),Error (3),GeneratingContainers (1),NotStarted (0)
"""
def __eq__(s... | class Generatorstatus(Enum, IComparable, IFormattable, IConvertible):
"""
Used by System.Windows.Controls.ItemContainerGenerator to indicate the status of its item generation.
enum GeneratorStatus,values: ContainersGenerated (2),Error (3),GeneratingContainers (1),NotStarted (0)
"""
def __eq__(self, *arg... |
def reverse(value):
if not isinstance(value, str):
return None
result = ''
for i in reversed(range(len(value))):
result += value[i]
return result | def reverse(value):
if not isinstance(value, str):
return None
result = ''
for i in reversed(range(len(value))):
result += value[i]
return result |
# ADDITION (plus signal)
print (5 + 5)
# SUBTRACTION (minus signal)
print (85 - 72)
# MULTIPLICATION (times signal)
print (8 * 7)
# DIVISION (split signal)
print (56 / 12)
print(5 / 2) # Quotient, number of times a division is completed fully
print(5 // 2) # Always return an integer number
# REMAINDER
print(6... | print(5 + 5)
print(85 - 72)
print(8 * 7)
print(56 / 12)
print(5 / 2)
print(5 // 2)
print(6 % 2)
print(4 ** 4) |
class DataGridPreparingCellForEditEventArgs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.PreparingCellForEdit event.
DataGridPreparingCellForEditEventArgs(column: DataGridColumn,row: DataGridRow,editingEventArgs: RoutedEventArgs,editingElement: FrameworkElement)
"""
@staticmet... | class Datagridpreparingcellforediteventargs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.PreparingCellForEdit event.
DataGridPreparingCellForEditEventArgs(column: DataGridColumn,row: DataGridRow,editingEventArgs: RoutedEventArgs,editingElement: FrameworkElement)
"""
@staticmeth... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
##############################################################################
# Copyright 2020 AlexPDev
#
# 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 Lice... | """Module for stylesheets."""
stylesheet = '\n * {\n background-color: #19232D;\n color: #FFFFFF;\n padding: 0px;\n margin: 0px;\n border-width: 0px;\n border-style: solid;\n }\n QMenu,\n QTreeWidget,\n QTreeWidget::item,\n QTableWidget,\n QTableWidget::ite... |
fileObj = open("words.txt")
array = []
for word in fileObj:
array.append(word.rstrip())
fileObj.close()
final = "var words = ["
for element in array:
final += "\"" + element + "\","
final = final[:-1]
final += "]"
fileOut = open("output.js", "w")
fileOut.write(final)
fileOut.close()
| file_obj = open('words.txt')
array = []
for word in fileObj:
array.append(word.rstrip())
fileObj.close()
final = 'var words = ['
for element in array:
final += '"' + element + '",'
final = final[:-1]
final += ']'
file_out = open('output.js', 'w')
fileOut.write(final)
fileOut.close() |
IMPALA_RESERVED_WORDS = (
"abs",
"acos",
"add",
"aggregate",
"all",
"allocate",
"alter",
"analytic",
"and",
"anti",
"any",
"api_version",
"are",
"array",
"array_agg",
"array_max_cardinality",
"as",
"asc",
"asensitive",
"asin",
"asymmetr... | impala_reserved_words = ('abs', 'acos', 'add', 'aggregate', 'all', 'allocate', 'alter', 'analytic', 'and', 'anti', 'any', 'api_version', 'are', 'array', 'array_agg', 'array_max_cardinality', 'as', 'asc', 'asensitive', 'asin', 'asymmetric', 'at', 'atan', 'atomic', 'authorization', 'avg', 'avro', 'backup', 'begin', 'begi... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")
def deps(repo_mapping = {}):
rules_foreign_cc_dependencies()
maybe(
http_archive,
... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@rules_foreign_cc//foreign_cc:repositories.bzl', 'rules_foreign_cc_dependencies')
def deps(repo_mapping={}):
rules_foreign_cc_dependencies()
maybe(http_archive, name='openss... |
jInicial = 7
iInicial = 1
for i in range (1, 10, +2):
iDaConta = i - iInicial
j = iDaConta + jInicial
print("I={} J={}".format(i, j))
print("I={} J={}".format(i, j-1))
print("I={} J={}".format(i, j-2))
| j_inicial = 7
i_inicial = 1
for i in range(1, 10, +2):
i_da_conta = i - iInicial
j = iDaConta + jInicial
print('I={} J={}'.format(i, j))
print('I={} J={}'.format(i, j - 1))
print('I={} J={}'.format(i, j - 2)) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(nd):
if not nd: retur... | class Solution:
def is_balanced(self, root: Optional[TreeNode]) -> bool:
def height(nd):
if not nd:
return 0
hl = height(nd.left)
hr = height(nd.right)
dh = abs(hl - hr)
if hl < 0 or hr < 0 or dh > 1:
return -1
... |
# Runs to perform
control = True
saltproc = True
linear_generation = False
cycle_time_decay = True
linear_isotope = False
# Basic model using ln(1 / (1 - X)) WIP
efficiency_based = False
saltproc_efficiency_based = False
# Separate core piping is WIP
separate_core_piping = False
# Options
plotting = True
ov... | control = True
saltproc = True
linear_generation = False
cycle_time_decay = True
linear_isotope = False
efficiency_based = False
saltproc_efficiency_based = False
separate_core_piping = False
plotting = True
overlap = 0.5
width = 3
path_to_dump_files = 'ss-comparison'
base_material_path = './ss-data-test/ss-fuel_'
temp... |
def normalize_start_end(x, inds=20):
mi = x[:inds, :].mean(axis=0)
ma = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi)
def normalize_end_start(x, inds=20):
ma = x[:inds, :].mean(axis=0)
mi = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi)
| def normalize_start_end(x, inds=20):
mi = x[:inds, :].mean(axis=0)
ma = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi)
def normalize_end_start(x, inds=20):
ma = x[:inds, :].mean(axis=0)
mi = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi) |
class SetUnionRank:
def __init__(self, arr):
self.parents = arr
self.ranks = [0] * self.size
@property
def size(self):
return len(self.parents)
def find(self, i):
while i != self.parents[i - 1]:
i = self.parents[i - 1]
return i
def union(self, ... | class Setunionrank:
def __init__(self, arr):
self.parents = arr
self.ranks = [0] * self.size
@property
def size(self):
return len(self.parents)
def find(self, i):
while i != self.parents[i - 1]:
i = self.parents[i - 1]
return i
def union(self, ... |
# run with python 3
def binary_representation(number):
if number > 1:
binary_representation(number//2)
print(number%2, end="")
binary_representation(4)
print()
binary_representation(7)
print() | def binary_representation(number):
if number > 1:
binary_representation(number // 2)
print(number % 2, end='')
binary_representation(4)
print()
binary_representation(7)
print() |
# Copyright 2020 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | class Servicetypes:
agriculture = 'agriculture'
clock = 'clock'
cluster = 'cluster'
czml = 'czml'
data = 'data'
groundstation = 'groundstation'
iot = 'iot'
orbits = 'orbits'
rl = 'rl'
rl__training = 'rl_training'
logging = 'logging'
config = 'config'
template = 'templ... |
"""
for two input arrays, find the closest two elements
"""
def smallestDifference(arrayOne, arrayTwo):
# Write your code here.
smallest = float("inf")
res = []
for eleone in arrayOne:
for eletwo in arrayTwo:
if abs(eleone -eletwo) < smallest:
smallest = abs(eleone-eletwo)
res = [eleone, eletwo]
re... | """
for two input arrays, find the closest two elements
"""
def smallest_difference(arrayOne, arrayTwo):
smallest = float('inf')
res = []
for eleone in arrayOne:
for eletwo in arrayTwo:
if abs(eleone - eletwo) < smallest:
smallest = abs(eleone - eletwo)
r... |
d = {}
n = int(input())
cnt = 0
while True:
cnt +=1
N = "%04d" % n
middle = int(N[1:3])
square = middle * middle
n = square
try:
d[square] +=1
except:
d[square] = 1
else:
break
print(cnt) | d = {}
n = int(input())
cnt = 0
while True:
cnt += 1
n = '%04d' % n
middle = int(N[1:3])
square = middle * middle
n = square
try:
d[square] += 1
except:
d[square] = 1
else:
break
print(cnt) |
# Copyright (C) 2018 Intel Corporation
#
# 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 wri... | """ This module contains the parameters """
class Configconstants:
verbose = 2
min_data_points = 20
lower_util_bound = 0.5
step = 50
use_ratio = True
step_ratio = 0.3
rand_seed = 1
max_components = 10
outlier_span = 3
check_strict = False
check_chi_square_test = False
ch... |
'''
Microsoft has come to hire interns from your college. N students got shortlisted out of which few were males and a few females. All the students have been assigned talent levels. Smaller the talent level, lesser is your chance to be selected. Microsoft wants to create the result list where it wants the candidates ... | """
Microsoft has come to hire interns from your college. N students got shortlisted out of which few were males and a few females. All the students have been assigned talent levels. Smaller the talent level, lesser is your chance to be selected. Microsoft wants to create the result list where it wants the candidates ... |
"""Dummy objects."""
class DummyProgress(object):
def __enter__(self):
return self
def __exit__(self, *args):
pass
def update(self, value):
pass
def close(self):
pass
| """Dummy objects."""
class Dummyprogress(object):
def __enter__(self):
return self
def __exit__(self, *args):
pass
def update(self, value):
pass
def close(self):
pass |
# Find the last element of a list.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-1])
# Find the second to last element of a list.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-2])
# Find all elements from the third to last element of a list to the last one.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-3:])
# Find the k'th e... | inventors = [{'first': 'Albert', 'last': 'Einstein', 'year': 1879, 'passed': 1955}, {'first': 'Isaac', 'last': 'Newton', 'year': 1643, 'passed': 1727}, {'first': 'Galileo', 'last': 'Galilei', 'year': 1564, 'passed': 1642}, {'first': 'Marie', 'last': 'Curie', 'year': 1867, 'passed': 1934}, {'first': 'Johannes', 'last': ... |
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res=0
left=0
right = 0
while right<len(nums):
if nums[right]==1:
res=max(res,right-left+1)
else:
left=right+1
right+=1
return res... | class Solution:
def find_max_consecutive_ones(self, nums: List[int]) -> int:
res = 0
left = 0
right = 0
while right < len(nums):
if nums[right] == 1:
res = max(res, right - left + 1)
else:
left = right + 1
right += ... |
# -*- coding: utf-8 -*-
################################################################################
# Object Returned from vision
################################################################################
class RecognizedObject:
def __init__(self, category=None, posi... | class Recognizedobject:
def __init__(self, category=None, position=None, color=None):
self.category = category
self.position = position
self.color = color
def __str__(self):
pattern = "RecognizedObject('{}', '{}', '{}')"
return pattern.format(self.category, self.positio... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | def cli_billing_list_invoices(client, generate_url=False):
"""List all available invoices of the subscription"""
return client.list(expand='downloadUrl' if generate_url else None)
def cli_billing_get_invoice(client, name=None):
"""Retrieve invoice of specific name of the subscription"""
if name:
... |
class OSSecurityGroupsV2(object):
def on_get(self, req, resp, tenant_id, instance_id=None):
resp.body = {
'security_groups': [{
'description': 'default',
'id': 1,
'name': 'default',
'rules': {},
'tenant_id': tenant... | class Ossecuritygroupsv2(object):
def on_get(self, req, resp, tenant_id, instance_id=None):
resp.body = {'security_groups': [{'description': 'default', 'id': 1, 'name': 'default', 'rules': {}, 'tenant_id': tenant_id}]} |
#! /usr/bin/env python
# coding: utf-8
__author__ = 'ZhouHeng'
class IPManager(object):
def __init__(self):
self.ip_1a = 256
self.ip_2a = self.ip_1a * self.ip_1a
self.ip_3a = self.ip_1a * self.ip_2a
self.ip_4a = self.ip_1a * self.ip_3a
def ip_value_str(self, ip_str=None, ip_v... | __author__ = 'ZhouHeng'
class Ipmanager(object):
def __init__(self):
self.ip_1a = 256
self.ip_2a = self.ip_1a * self.ip_1a
self.ip_3a = self.ip_1a * self.ip_2a
self.ip_4a = self.ip_1a * self.ip_3a
def ip_value_str(self, ip_str=None, ip_value=None):
if ip_str is not Non... |
#string
s = "I am a string."
print(type(s)) #returns str
#Boolean ...these are specifically true or false. NO possibility you would have the wrong precision.
yes = True #Boolean True, "True" is a protected term in python
print(type(yes)) #boolean
no = False
print(type(no))
#List -- ordered and changeable ... | s = 'I am a string.'
print(type(s))
yes = True
print(type(yes))
no = False
print(type(no))
alpha_list = ['a', 'b', 'c']
print(type(alpha_list))
print(type(alpha_list[0]))
alpha_list.append('d')
print(alpha_list)
alpha_tuple = ('a', 'b', 'c')
print(type(alpha_tuple))
try:
alpha_tuple[2] = 'd'
except TypeError:
p... |
"""
Utilidades del front
"""
# Clase abstracta de la que heredaran mis fronts
class Board:
def init(self, data):
pass
def print_board(self, size):
pass
| """
Utilidades del front
"""
class Board:
def init(self, data):
pass
def print_board(self, size):
pass |
# coding: utf-8
s = input()
k = int(input())
w = [int(i) for i in input().split()]
li = []
for ch in s:
li.append(w[ord(ch)-ord('a')])
li.extend([max(w)]*k)
ans = 0
for i in range(0,len(li)):
ans += (i+1)*li[i]
print(ans)
| s = input()
k = int(input())
w = [int(i) for i in input().split()]
li = []
for ch in s:
li.append(w[ord(ch) - ord('a')])
li.extend([max(w)] * k)
ans = 0
for i in range(0, len(li)):
ans += (i + 1) * li[i]
print(ans) |
"""
International Morse Code defines a standard encoding where each letter is mapped to
a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c"
maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
'a':".-",
'b':... | """
International Morse Code defines a standard encoding where each letter is mapped to
a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c"
maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
'a':".-",
'b':... |
answer_filename='g0pA_taskb.txt'
n=3
answer_row = complete_df.loc[complete_df['File'] == answer_filename]
task = answer_row['Task'].values[0]
answer = answer_row['Text'].values[0]
source = complete_df.loc[(complete_df['Datatype'] == 'orig') &
(complete_df['Task'] == task... | answer_filename = 'g0pA_taskb.txt'
n = 3
answer_row = complete_df.loc[complete_df['File'] == answer_filename]
task = answer_row['Task'].values[0]
answer = answer_row['Text'].values[0]
source = complete_df.loc[(complete_df['Datatype'] == 'orig') & (complete_df['Task'] == task)]['Text'].values[0]
counts = count_vectorize... |
#!/usr/bin/python3.5
# Solves the magic hexagon problem for n = 3 by brute force
# https://en.wikipedia.org/wiki/Magic_hexagon
line_jumps = [3, 4, 5, 4, 3]
lines = [
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18],
[7, 3, 0],
[12, 8, 4, 1],
[16, 13, 9, 5, 2],
[17, 14, 10, 6],
[18,... | line_jumps = [3, 4, 5, 4, 3]
lines = [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18], [7, 3, 0], [12, 8, 4, 1], [16, 13, 9, 5, 2], [17, 14, 10, 6], [18, 15, 11]]
def print_board(board):
c = 0
s = ''
for jump in line_jumps:
for x in board[c:jump + c]:
s += str... |
class TransactionData():
def __init__(self):
self.data_frame = None
self.train_df = None
self.test_df = None
self.validation_df = None
self.train_indexes = {}
self.test_indexes = {}
self.validation_indexes = {}
self.all_indexes = {}
self.co... | class Transactiondata:
def __init__(self):
self.data_frame = None
self.train_df = None
self.test_df = None
self.validation_df = None
self.train_indexes = {}
self.test_indexes = {}
self.validation_indexes = {}
self.all_indexes = {}
self.columns... |
class Edge:
def __init__(self, start, end, cost, length, direction):
self.start = start
self.end = end
self.cost = cost
self.length = length
self.direction = direction
self.is_visited = False
self.length_by_cost = length/cost
# making global variables
def... | class Edge:
def __init__(self, start, end, cost, length, direction):
self.start = start
self.end = end
self.cost = cost
self.length = length
self.direction = direction
self.is_visited = False
self.length_by_cost = length / cost
def parse(file):
i = open(... |
def get_attribute(attributes, attribute_name, default_value=None):
attribute = next(item for item in attributes if item.Name == attribute_name)
if attribute:
return attribute.Value
if default_value:
return default_value
raise ValueError('Attribute {0} is missing'.format(attribute_name)... | def get_attribute(attributes, attribute_name, default_value=None):
attribute = next((item for item in attributes if item.Name == attribute_name))
if attribute:
return attribute.Value
if default_value:
return default_value
raise value_error('Attribute {0} is missing'.format(attribute_name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.