content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
About this package
"""
__version__ = '0.1.0'
__description__ = 'Python3 client code for ec_golanggrpc'
__author__ = 'Paul Hewlett'
__author_email__ = 'phewlett76@gmail.com'
__license__ = 'MIT'
| """
About this package
"""
__version__ = '0.1.0'
__description__ = 'Python3 client code for ec_golanggrpc'
__author__ = 'Paul Hewlett'
__author_email__ = 'phewlett76@gmail.com'
__license__ = 'MIT' |
class CrawlerCodeDTO(object):
"""
Object that contains grouped all data of the code
"""
def __init__(self, id, libs, comments, variable_names, function_names, class_name, lines_number, code):
self.id = id
self.libs = libs if len(libs) > 0 else []
self.comments = comments if ... | class Crawlercodedto(object):
"""
Object that contains grouped all data of the code
"""
def __init__(self, id, libs, comments, variable_names, function_names, class_name, lines_number, code):
self.id = id
self.libs = libs if len(libs) > 0 else []
self.comments = comments if ... |
def cls_with_meta(mc, attrs):
class _x_(object):
__metaclass__ = mc
for k, v in attrs.items():
setattr(_x_, k, v)
return _x_
| def cls_with_meta(mc, attrs):
class _X_(object):
__metaclass__ = mc
for (k, v) in attrs.items():
setattr(_x_, k, v)
return _x_ |
num = int(input('Digite um valor para saber seu fatorial: '))
d = num
for c in range(num-1,1,-1):
num += (num * c) - num
print('Calculando {}! = {}.'.format(d, num)) | num = int(input('Digite um valor para saber seu fatorial: '))
d = num
for c in range(num - 1, 1, -1):
num += num * c - num
print('Calculando {}! = {}.'.format(d, num)) |
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
head = ListNode(0, head)
p1, prev, p2 = head, head, head.next
while p2:
if p2.val < x:
if p1 == prev:
prev, p2 = p2, p2.next
else:
... | class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
head = list_node(0, head)
(p1, prev, p2) = (head, head, head.next)
while p2:
if p2.val < x:
if p1 == prev:
(prev, p2) = (p2, p2.next)
else:
... |
#
# PySNMP MIB module BLUECOAT-HOST-RESOURCES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-HOST-RESOURCES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:39:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) ... |
t = {}
t["0"] = ["-113", "Marginal"]
t["1"] = ["-111", "Marginal"]
t["2"] = ["-109", "Marginal"]
t["3"] = ["-107", "Marginal"]
t["4"] = ["-105", "Marginal"]
t["5"] = ["-103", "Marginal"]
t["6"] = ["-101", "Marginal"]
t["7"] = ["-99", "Marginal"]
t["8"] = ["-97", "Marginal"]
t["9"] = ["-95", "Marginal"]
t["10"] = ["-93"... | t = {}
t['0'] = ['-113', 'Marginal']
t['1'] = ['-111', 'Marginal']
t['2'] = ['-109', 'Marginal']
t['3'] = ['-107', 'Marginal']
t['4'] = ['-105', 'Marginal']
t['5'] = ['-103', 'Marginal']
t['6'] = ['-101', 'Marginal']
t['7'] = ['-99', 'Marginal']
t['8'] = ['-97', 'Marginal']
t['9'] = ['-95', 'Marginal']
t['10'] = ['-93'... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | """Precision calculation function of Ubuntu data"""
def get_p_at_n_in_m(data, n, m, ind):
"""Former n recall rate"""
pos_score = data[ind][0]
curr = data[ind:ind + m]
curr = sorted(curr, key=lambda x: x[0], reverse=True)
if curr[n - 1][0] <= pos_score:
return 1
return 0
def evaluate(fi... |
class Solution:
def longestWPI(self, hours: List[int]) -> int:
acc = 0
seen = {0 : -1}
mx_len = 0
for i, h in enumerate(hours):
if h > 8:
acc += 1
else:
acc -= 1
if acc > 0:
mx_len = i + 1
... | class Solution:
def longest_wpi(self, hours: List[int]) -> int:
acc = 0
seen = {0: -1}
mx_len = 0
for (i, h) in enumerate(hours):
if h > 8:
acc += 1
else:
acc -= 1
if acc > 0:
mx_len = i + 1
... |
#log in process
def login():
Username = input("Enter Username : ")
if Username == 'betterllama' or NewUsername:
Password = input("Enter Password : ")
else:
print("Username Incorrect")
if Password == 'omoshi' or NewPassword:
print("Welcome, " + Username)
else:
print("Password is incorrect")
#sign up + log... | def login():
username = input('Enter Username : ')
if Username == 'betterllama' or NewUsername:
password = input('Enter Password : ')
else:
print('Username Incorrect')
if Password == 'omoshi' or NewPassword:
print('Welcome, ' + Username)
else:
print('Password is incor... |
# -*- coding: utf8 -*-
def js_test():
pass | def js_test():
pass |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# This example will open a file and read it line by line, process each line,
# and write the processed line to standard out.
# -----------------------------------------------------------------------------
# Open a fil... | outfile = open('jenny.txt', 'w')
num = 867
num2 = 5309
txt = 'Jenny'
txt2 = 'Tommy Tutone'
list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls']
outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2))
outfile.write('and was covered by:\n')
for l in list:
outfile.write('%s\n' % l)
outfile.cl... |
"""
107. Word Break
https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160
DFS on dictionary
"""
class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def wordBreak(self, s, dict):
return self.dfs(s, dict, 0)... | """
107. Word Break
https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160
DFS on dictionary
"""
class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def word_break(self, s, dict):
return self.dfs(s, dict, 0)
... |
# A binary search template
"""
left, right = 0, len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
""" | """
left, right = 0, len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
""" |
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
if x < -(2 ** 31) or x > (2 ** 31) - 1:
return 0
newNumber = 0
tempNumber = abs(x)
while tempNumber > 0:
newNumber = (newNumber * 10) + tempNumber % 10
te... | class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
if x < -2 ** 31 or x > 2 ** 31 - 1:
return 0
new_number = 0
temp_number = abs(x)
while tempNumber > 0:
new_number = newNumber * 10 + tempNumber % 10
temp_num... |
good = 0
good_2 = 0
with open("day2.txt") as f:
for line in f.readlines():
parts = line.strip().split()
print(parts)
cmin, cmax = [int(i) for i in parts[0].split('-')]
letter = parts[1][0]
pwd = parts[2]
print(cmin, cmax, letter, pwd)
count = pwd.count(letter... | good = 0
good_2 = 0
with open('day2.txt') as f:
for line in f.readlines():
parts = line.strip().split()
print(parts)
(cmin, cmax) = [int(i) for i in parts[0].split('-')]
letter = parts[1][0]
pwd = parts[2]
print(cmin, cmax, letter, pwd)
count = pwd.count(lette... |
description = 'PUMA multianalyzer device'
group = 'lowlevel'
includes = ['aliases']
level = False
devices = dict(
man = device('nicos_mlz.puma.devices.PumaMultiAnalyzer',
description = 'PUMA multi analyzer',
translations = ['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8',
... | description = 'PUMA multianalyzer device'
group = 'lowlevel'
includes = ['aliases']
level = False
devices = dict(man=device('nicos_mlz.puma.devices.PumaMultiAnalyzer', description='PUMA multi analyzer', translations=['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8', 'ta9', 'ta10', 'ta11'], rotations=['ra1', 'ra2'... |
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return None
result = ''
maxPal = 0
record = [[0] * len(s) for i in range(len(s))]
for j in range(len(s)):
for i in range(j+1):
record[i][j] = ((s[i] == s[j]) and (j-i... | class Solution:
def longest_palindrome(self, s: str) -> str:
if not s:
return None
result = ''
max_pal = 0
record = [[0] * len(s) for i in range(len(s))]
for j in range(len(s)):
for i in range(j + 1):
record[i][j] = s[i] == s[j] and (j... |
"""
entrada
nombre-->str-->n
horas_trabajadas-->int-->ht
precio_hora_normal-->int-->phn
horas _extras-->int-->hx
#hijos-->int-->hi
salidas
asignaciones-->str-->asi
deducciones-->str-->dd
sueldo_neto-->str-->sn
"""
n=str(input("escriba el nombre del trabador "))
ht=int(input("digite la cantidad de horas trabajadas "))
p... | """
entrada
nombre-->str-->n
horas_trabajadas-->int-->ht
precio_hora_normal-->int-->phn
horas _extras-->int-->hx
#hijos-->int-->hi
salidas
asignaciones-->str-->asi
deducciones-->str-->dd
sueldo_neto-->str-->sn
"""
n = str(input('escriba el nombre del trabador '))
ht = int(input('digite la cantidad de horas trabajadas '... |
__author__ = 'Liu'
def quadrado_menores(n):
return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
assert [1] == quadrado_menores(1)
assert [1, 4] == quadrado_menores(4)
assert [1, 4, 9] == quadrado_menores(9)
assert [1, 4, 9] == quadrado_menores(11)
def soma_quadrados(n):
if n > 0:
menores = quadrad... | __author__ = 'Liu'
def quadrado_menores(n):
return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
assert [1] == quadrado_menores(1)
assert [1, 4] == quadrado_menores(4)
assert [1, 4, 9] == quadrado_menores(9)
assert [1, 4, 9] == quadrado_menores(11)
def soma_quadrados(n):
if n > 0:
menores = quadrad... |
try:
pass
except ImportError:
pass
if False:
pass
class GraphQLSchema(object):
"""Schema Definition
A Schema is created by supplying the root types of each type of operation, query and mutation (optional).
A schema definition is then supplied to the validator and executor.
Example:
MyAppSchema =... | try:
pass
except ImportError:
pass
if False:
pass
class Graphqlschema(object):
"""Schema Definition
A Schema is created by supplying the root types of each type of operation, query and mutation (optional).
A schema definition is then supplied to the validator and executor.
Example:
... |
a = 1
if a == 1:
print("ok")
else:
print("no")
py_builtins = 1
if py_builtins == 1:
print("ok")
else:
print("no")
for py_builtins in range(5):
a += py_builtins
print(a)
| a = 1
if a == 1:
print('ok')
else:
print('no')
py_builtins = 1
if py_builtins == 1:
print('ok')
else:
print('no')
for py_builtins in range(5):
a += py_builtins
print(a) |
""" html head """
def get_head(content):
""" xxx """
return_data = '<head>'+ content +'</head>'
return return_data
| """ html head """
def get_head(content):
""" xxx """
return_data = '<head>' + content + '</head>'
return return_data |
"""Exceptions for ReSpecTh Parser.
.. moduleauthor:: Kyle Niemeyer <kyle.niemeyer@gmail.com>
"""
class ParseError(Exception):
"""Base class for errors."""
pass
class KeywordError(ParseError):
"""Raised for errors in keyword parsing."""
def __init__(self, *keywords):
self.keywords = keywords... | """Exceptions for ReSpecTh Parser.
.. moduleauthor:: Kyle Niemeyer <kyle.niemeyer@gmail.com>
"""
class Parseerror(Exception):
"""Base class for errors."""
pass
class Keyworderror(ParseError):
"""Raised for errors in keyword parsing."""
def __init__(self, *keywords):
self.keywords = keywords
... |
"""
digit factorial chains
"""
factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
def next_number(n):
factorial_sum = 0
while n != 0:
factorial_sum += factorial[n % 10]
n //= 10
return factorial_sum
def chain_len(n):
chain = []
while not chain.__contains__(n):
cha... | """
digit factorial chains
"""
factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
def next_number(n):
factorial_sum = 0
while n != 0:
factorial_sum += factorial[n % 10]
n //= 10
return factorial_sum
def chain_len(n):
chain = []
while not chain.__contains__(n):
chai... |
flag = [""] * 36
flag[0] = chr(0x46)
flag[1] = chr(0x4c)
flag[2] = chr(0x41)
flag[3] = chr(0x47)
flag[4] = chr(0x7b)
flag[5] = chr(0x35)
flag[6] = chr(0x69)
flag[7] = chr(0x6d)
flag[8] = chr(0x70)
flag[9] = chr(0x31)
flag[10] = chr(0x65)
flag[11] = chr(0x5f)
flag[12] = chr(0x52)
flag[13] = chr(0x65)
flag[14] = chr(0x7... | flag = [''] * 36
flag[0] = chr(70)
flag[1] = chr(76)
flag[2] = chr(65)
flag[3] = chr(71)
flag[4] = chr(123)
flag[5] = chr(53)
flag[6] = chr(105)
flag[7] = chr(109)
flag[8] = chr(112)
flag[9] = chr(49)
flag[10] = chr(101)
flag[11] = chr(95)
flag[12] = chr(82)
flag[13] = chr(101)
flag[14] = chr(118)
flag[15] = chr(101)
f... |
def code_function():
#function begin############################################
global code
code="""
class {0}_scoreboard extends uvm_scoreboard;
//---------------------------------------
// declaring pkt_qu to store the pkt's recived from monitor
//---------------------------------------
... | def code_function():
global code
code = '\nclass {0}_scoreboard extends uvm_scoreboard;\n \n //---------------------------------------\n // declaring pkt_qu to store the pkt\'s recived from monitor\n //---------------------------------------\n {0}_seq_item pkt_qu[$];\n \n //------------------------------... |
uno= Board('/dev/cu.wchusbserial1420')
led= Led(13)
led.setColor([0.84, 0.34, 0.67])
ledController= ExdTextInputBox(target= led, value="period", size="sm")
APP.STACK.add_widget(ledController)
| uno = board('/dev/cu.wchusbserial1420')
led = led(13)
led.setColor([0.84, 0.34, 0.67])
led_controller = exd_text_input_box(target=led, value='period', size='sm')
APP.STACK.add_widget(ledController) |
a, b = map(int, input().split())
if a + b == 15:
print('+')
elif a*b == 15:
print('*')
else:
print('x')
| (a, b) = map(int, input().split())
if a + b == 15:
print('+')
elif a * b == 15:
print('*')
else:
print('x') |
class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
n = len(stoneValue)
dp = [[0] * n for _ in range(n)]
mx = [[0] * n for _ in range(n)]
for i in range(n):
mx[i][i] = stoneValue[i]
for j in range(1, n):
mid = j
s = stoneVal... | class Solution:
def stone_game_v(self, stoneValue: List[int]) -> int:
n = len(stoneValue)
dp = [[0] * n for _ in range(n)]
mx = [[0] * n for _ in range(n)]
for i in range(n):
mx[i][i] = stoneValue[i]
for j in range(1, n):
mid = j
s = stone... |
# %% [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/)
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
r = self.sumOfLeftLeaves(root.right)
if (p := root.left) and not p.left and not p.right:
return ro... | class Solution:
def sum_of_left_leaves(self, root: TreeNode) -> int:
if not root:
return 0
r = self.sumOfLeftLeaves(root.right)
if (p := root.left) and (not p.left) and (not p.right):
return root.left.val + r
return self.sumOfLeftLeaves(root.left) + r |
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix: return 0
row, col = len(matrix), len(matrix[0])
dp = [0] * col
ret = 0
for i in range(row):
for j in range(col):
if matrix[i][j] == '1':
... | class Solution:
def maximal_rectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
(row, col) = (len(matrix), len(matrix[0]))
dp = [0] * col
ret = 0
for i in range(row):
for j in range(col):
if matrix[i][j] == '1':
... |
database_name = "Health_Service"
user_name = "postgres"
password = "zhangheng"
port = "5432"
| database_name = 'Health_Service'
user_name = 'postgres'
password = 'zhangheng'
port = '5432' |
""" Problem Set 5 - Problem 1 - Build the Shift Dictionary and Apply Shift
The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action).
In the next two questions, you will fill in the methods of the Mess... | """ Problem Set 5 - Problem 1 - Build the Shift Dictionary and Apply Shift
The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action).
In the next two questions, you will fill in the methods of the Mess... |
#Exercise 3.2: Rewrite your pay program using try and except so
# that yourprogram handles non-numeric input gracefully by
# printing a messageand exiting the program. The following
# shows two executions of the program:
# Enter Hours: 20
# Enter Rate: nine
# Error, please enter numeric input
# Enter Hours: forty
... | hrs = input('Enter Hours: ')
try:
h = float(hrs)
rph = input('Enter Rate: ')
try:
r = float(rph)
if h <= 40:
pay = h * r
else:
overhours = h - 40
norm_pay = 40 * r
over_pay = overhours * r * 1.5
pay = norm_pay + over_pay
... |
_base_ = [
'../_base_/models/mask_rcnn_r50_fpn_icdar2021.py',
'../_base_/datasets/icdar2021_instance_isolated.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# data = dict(
# samples_per_gpu=1,
# workers_per_gpu=2)
# optimizer = dict(type='SGD', lr=0.01, momentum=0.9, w... | _base_ = ['../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'] |
"""
Define custom exceptions
"""
__all__ = (
'Track17Exception',
'InvalidCarrierCode',
'DateProcessingError'
)
class Track17Exception(Exception):
def __init__(self, message: str, code: int = None):
self.message = message
self.code = code
super().__init__()
def __str__(sel... | """
Define custom exceptions
"""
__all__ = ('Track17Exception', 'InvalidCarrierCode', 'DateProcessingError')
class Track17Exception(Exception):
def __init__(self, message: str, code: int=None):
self.message = message
self.code = code
super().__init__()
def __str__(self) -> str:
... |
"""
Ryan Kirkbride - Noodling around:
https://www.youtube.com/watch?v=CXrkq7u69vU
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed together (ctrl+enter)
- If you want to fast-forward through the son... | """
Ryan Kirkbride - Noodling around:
https://www.youtube.com/watch?v=CXrkq7u69vU
How to:
- Run the statements line by line (alt+enter),
go to the next one whenever you feel like
- The "#### > run block <" blocks should be
executed together (ctrl+enter)
- If you want to fast-forward through the son... |
HASS_EVENT_RECEIVE = 'HASS_EVENT_RECEIVE' # hass.bus --> hauto.bus
HASS_STATE_CHANGED = 'HASS_STATE_CHANGE' # aka hass.EVENT_STATE_CHANGED
HASS_ENTITY_CREATE = 'HASS_ENTITY_CREATE' # hass entity is newly created
HASS_ENTITY_CHANGE = 'HASS_ENTITY_CHANGE' # hass entity's state changes
HASS_ENTITY_UPDATE = 'HASS_ENT... | hass_event_receive = 'HASS_EVENT_RECEIVE'
hass_state_changed = 'HASS_STATE_CHANGE'
hass_entity_create = 'HASS_ENTITY_CREATE'
hass_entity_change = 'HASS_ENTITY_CHANGE'
hass_entity_update = 'HASS_ENTITY_UPDATE'
hass_entity_remove = 'HASS_ENTITY_REMOVE' |
N, L = map(int, input().split())
amida = []
for _ in range(L+1):
tmp = list(input())
amida.append(tmp)
idx = amida[L].index('o')
for i in reversed(range(L)):
if idx != N*2-2 and amida[i][idx+1] == '-':
idx += 2
elif idx != 0 and amida[i][idx-1] == '-':
idx -= 2
print(idx//2+1)
| (n, l) = map(int, input().split())
amida = []
for _ in range(L + 1):
tmp = list(input())
amida.append(tmp)
idx = amida[L].index('o')
for i in reversed(range(L)):
if idx != N * 2 - 2 and amida[i][idx + 1] == '-':
idx += 2
elif idx != 0 and amida[i][idx - 1] == '-':
idx -= 2
print(idx // 2... |
# LSM6DSO 3D accelerometer and 3D gyroscope seneor micropython drive
# ver: 1.0
# License: MIT
# Author: shaoziyang (shaoziyang@micropython.org.cn)
# v1.0 2019.7
LSM6DSO_CTRL1_XL = const(0x10)
LSM6DSO_CTRL2_G = const(0x11)
LSM6DSO_CTRL3_C = const(0x12)
LSM6DSO_CTRL6_C = const(0x15)
LSM6DSO_CTRL8_XL = const(0x17)
LSM6D... | lsm6_dso_ctrl1_xl = const(16)
lsm6_dso_ctrl2_g = const(17)
lsm6_dso_ctrl3_c = const(18)
lsm6_dso_ctrl6_c = const(21)
lsm6_dso_ctrl8_xl = const(23)
lsm6_dso_status = const(30)
lsm6_dso_out_temp_l = const(32)
lsm6_dso_outx_l_g = const(34)
lsm6_dso_outy_l_g = const(36)
lsm6_dso_outz_l_g = const(38)
lsm6_dso_outx_l_a = con... |
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l=0
r=len(nums)-1
while l<r:
mid=l+(r-l)//2
if nums[mid]<nums[mid+1]:
l=mid+1
else:
r=mid
return l
| class Solution:
def find_peak_element(self, nums: List[int]) -> int:
l = 0
r = len(nums) - 1
while l < r:
mid = l + (r - l) // 2
if nums[mid] < nums[mid + 1]:
l = mid + 1
else:
r = mid
return l |
# Refers to `_RAND_INCREASING_TRANSFORMS` in pytorch-image-models
rand_increasing_policies = [
dict(type='AutoContrast'),
dict(type='Equalize'),
dict(type='Invert'),
dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)),
dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, ... | rand_increasing_policies = [dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='S... |
def tickets(people):
twenty_fives = 0
fifties = 0
for p in people:
if p == 25:
twenty_fives += 1
if p == 50:
if twenty_fives == 0:
return 'NO'
twenty_fives -= 1
fifties += 1
if p == 100:
if fifties >= 1 and t... | def tickets(people):
twenty_fives = 0
fifties = 0
for p in people:
if p == 25:
twenty_fives += 1
if p == 50:
if twenty_fives == 0:
return 'NO'
twenty_fives -= 1
fifties += 1
if p == 100:
if fifties >= 1 and t... |
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# Disable DYNAMICBASE for these tests because it implies/doesn't imply
# FIXED in certain cases so it complicates the test for FIXED.
{... | {'targets': [{'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['he... |
# Python program to Find Numbers divisible by Another number
def main():
x=int(input("Enter the number"))
y=int(input("Enter the limit value"))
print("The Numbers divisible by",x,"is")
for i in range(1,y+1):
if i%x==0:
print(i)
if __name__=='__main__':
main()
| def main():
x = int(input('Enter the number'))
y = int(input('Enter the limit value'))
print('The Numbers divisible by', x, 'is')
for i in range(1, y + 1):
if i % x == 0:
print(i)
if __name__ == '__main__':
main() |
class multi():
def insert(self,num):
for i in range(1, 11):
print(num, "X", i, "=", num * i)
d=multi()
d.insert(num=int(input('Enter the number')))
| class Multi:
def insert(self, num):
for i in range(1, 11):
print(num, 'X', i, '=', num * i)
d = multi()
d.insert(num=int(input('Enter the number'))) |
a = 67
b = 1006
c = 1002
"""if (a>=b and a>=c):
print(a)
elif (b>=c and b>=a) :
print(b)
elif (b>=a and b>=b) :
print(c)"""
max=a
if a>=b:
if b>=c:
max =a
else:
if a>=c:
max =a
else:
max = c
else:
if a>=c:
max =b
else:
if b>=c:
... | a = 67
b = 1006
c = 1002
'if (a>=b and a>=c):\n print(a)\nelif (b>=c and b>=a) :\n print(b)\nelif (b>=a and b>=b) :\n print(c)'
max = a
if a >= b:
if b >= c:
max = a
elif a >= c:
max = a
else:
max = c
elif a >= c:
max = b
elif b >= c:
max = a
else:
max = c
print(... |
"""
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to
ask during an in... | """
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to
ask during an in... |
for value in range(10):
print(value)
print('All Done!')
| for value in range(10):
print(value)
print('All Done!') |
"""""
Datos de Entrada
N Enteros Positivos = n = int
K Enteros Positivos = k = int
Datos de Salida
Siempre que k sea menor a n
Cuando N = K
"""""
n=int(input("Escriba el primer digito "))
k=int(input("Escriba el primer digito "))
while True:
n=0
if(k<n):
n=n-1
print(n)
elif(n==k):
... | """""
Datos de Entrada
N Enteros Positivos = n = int
K Enteros Positivos = k = int
Datos de Salida
Siempre que k sea menor a n
Cuando N = K
"""
n = int(input('Escriba el primer digito '))
k = int(input('Escriba el primer digito '))
while True:
n = 0
if k < n:
n = n - 1
print(n)
elif n =... |
def shift_letter(char, shifts):
if not isinstance(char, chr):
raise ValueError('char should be typeof chr')
if char == '' or char is None:
raise ValueError('char should be typeof chr')
if ord(char.upper()) < 65 or ord(char.upper()) > 90:
raise ValueError('char should be only a-z Lati... | def shift_letter(char, shifts):
if not isinstance(char, chr):
raise value_error('char should be typeof chr')
if char == '' or char is None:
raise value_error('char should be typeof chr')
if ord(char.upper()) < 65 or ord(char.upper()) > 90:
raise value_error('char should be only a-z L... |
i = 1
while i < 20:
print(i)
i += 1
i = 1
while i < 100:
print(i)
i += 1
i = 50
while i < 60:
print(i)
i += 1
i = 5
while i < 60:
print(i)
i += 1
i = 1
while i < 6:
print(i)
if (i == 3):
break
i += 1
k = 1
while k < 20:
print(k)
... | i = 1
while i < 20:
print(i)
i += 1
i = 1
while i < 100:
print(i)
i += 1
i = 50
while i < 60:
print(i)
i += 1
i = 5
while i < 60:
print(i)
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
k = 1
while k < 20:
print(k)
if k == 20 or k =... |
def count_words(message):
#return len(message.split())
# words = []
count = 0
activeWord = False
for c in message:
if c.isspace():
activeWord = False
else:
if not activeWord:
# words.append([])
count += 1
activeW... | def count_words(message):
count = 0
active_word = False
for c in message:
if c.isspace():
active_word = False
elif not activeWord:
count += 1
active_word = True
return count
def main():
message = 'What is your name?'
print(message)
print(c... |
class BufferFullException(Exception):
def __init__(self, msg):
self.msg = msg
class BufferEmptyException(Exception):
def __init__(self, msg):
self.msg = msg
class CircularBuffer:
def __init__(self, capacity):
self.list_circulator = list()
self.list_circulator.append(','.jo... | class Bufferfullexception(Exception):
def __init__(self, msg):
self.msg = msg
class Bufferemptyexception(Exception):
def __init__(self, msg):
self.msg = msg
class Circularbuffer:
def __init__(self, capacity):
self.list_circulator = list()
self.list_circulator.append(','.... |
DOMAIN = "microsoft_todo"
CONF_CLIENT_ID = "client_id"
CONF_CLIENT_SECRET = "client_secret"
AUTH_CALLBACK_PATH = "/api/microsoft-todo"
AUTHORIZATION_BASE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
SCOPE = ["Tasks.ReadW... | domain = 'microsoft_todo'
conf_client_id = 'client_id'
conf_client_secret = 'client_secret'
auth_callback_path = '/api/microsoft-todo'
authorization_base_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
scope = ['Tasks.ReadWr... |
input = """
c | d.
a | b :- c.
a :- b.
b :- a.
"""
output = """
{d}
{c, a, b}
"""
| input = '\nc | d.\na | b :- c.\na :- b.\nb :- a.\n'
output = '\n{d}\n{c, a, b}\n' |
def parse_response_from_json(r):
response = ''
try:
response = r.json()['response']
except Exception as ex:
response = str(ex)
return response
| def parse_response_from_json(r):
response = ''
try:
response = r.json()['response']
except Exception as ex:
response = str(ex)
return response |
# [Commerci Republic] Delfino Deleter 2
sm.setSpeakerID(9390256) # Leon Daniella
sm.sendNext("I was so much faster than you! But you're the sidekick for a reason.")
sm.sendNext("C'mon! We can't let them get their buddies. We have to finish this now! I'll be waiting for you at #m865020200#") # Canal 3
sm.sendNext("Wh... | sm.setSpeakerID(9390256)
sm.sendNext("I was so much faster than you! But you're the sidekick for a reason.")
sm.sendNext("C'mon! We can't let them get their buddies. We have to finish this now! I'll be waiting for you at #m865020200#")
sm.sendNext('What are you waiting for, my loyal sidekick?')
sm.setPlayerAsSpeaker()
... |
ans=0
n=200
def f(n):
fac=[0]*(n+10)
fac[0]=1
for i in range(1,n+5):
fac[i]=i*fac[i-1]
return fac
def c(n,m):
return fac[n]//fac[n-m]//fac[m]
def solve(i,asn,b,other):
res=0
if i>b:
if other>b+1:
return 0
else:
t=fac[b+1]//fac[b+1-other]
for j in asn:
if j:
t//=fac[j]
return t
for j i... | ans = 0
n = 200
def f(n):
fac = [0] * (n + 10)
fac[0] = 1
for i in range(1, n + 5):
fac[i] = i * fac[i - 1]
return fac
def c(n, m):
return fac[n] // fac[n - m] // fac[m]
def solve(i, asn, b, other):
res = 0
if i > b:
if other > b + 1:
return 0
else:
... |
a='ala ma kota'
print(a)
a=u'ala ma kota'
print(a)
a='ala'+'ma'+'kota'
print(a)
print(len(a))
if(a[:1]=='a'):
print(a[-4])
else:
print('No nie za brdzo')
print('{0}, {1}, {2}'.format(*'abc'))
a = 'Psa'
print('%s ma %s' % (a,a))
| a = 'ala ma kota'
print(a)
a = u'ala ma kota'
print(a)
a = 'ala' + 'ma' + 'kota'
print(a)
print(len(a))
if a[:1] == 'a':
print(a[-4])
else:
print('No nie za brdzo')
print('{0}, {1}, {2}'.format(*'abc'))
a = 'Psa'
print('%s ma %s' % (a, a)) |
class ElectricMotor:
"""A class used to model an electric motor
Assumptions:
- linear magnetic circuit (not considering flux dispersions and metal saturation when high currents are applied)
- only viscous friction is assumed to be present (not considering Coulomb frictions)
- stator is ... | class Electricmotor:
"""A class used to model an electric motor
Assumptions:
- linear magnetic circuit (not considering flux dispersions and metal saturation when high currents are applied)
- only viscous friction is assumed to be present (not considering Coulomb frictions)
- stator is ... |
scan_utility_version = '1.0.11'
detect_jar = "/tmp/synopsys-detect.jar"
# workflow_script = "/Users/mbrad/working/blackduck-scan-action/blackduck-rapid-scan-to-github.py"
# detect_jar = "./synopsys-detect.jar"
# workflow_script = "/Users/jcroall/PycharmProjects/blackduck-scan-action/blackduck-rapid-scan-to-github.py"
d... | scan_utility_version = '1.0.11'
detect_jar = '/tmp/synopsys-detect.jar'
debug = 0
bd = None
args = None
scm_provider = None
pkg_files = ['pom.xml', 'package.json', 'npm-shrinkwrap.json', 'package-lock.json', 'Cargo.toml', 'Cargo.lock', 'conanfile.txt', 'environment.yml', 'pubspec.yml', 'pubspec.lock', 'gogradle.lock', ... |
"""
230. Kth Smallest Element in a BST
"""
# 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 kthSmallest(self, root: TreeNode, k: int) -> int:
A = []
... | """
230. Kth Smallest Element in a BST
"""
class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
a = []
res = self.inorder(root, A)
... |
def collateFunction(self, batch):
"""
Custom collate function to adjust a variable number of low-res images.
Args:
batch: list of imageset
Returns:
padded_lr_batch: tensor (B, min_L, W, H), low resolution images
alpha_batch: tensor (B, min_L), low resolution indicator (0 if pa... | def collate_function(self, batch):
"""
Custom collate function to adjust a variable number of low-res images.
Args:
batch: list of imageset
Returns:
padded_lr_batch: tensor (B, min_L, W, H), low resolution images
alpha_batch: tensor (B, min_L), low resolution indicator (0 if padd... |
destination = input()
current_money = 0
while destination != 'End':
vacation_money = float(input())
while current_money < vacation_money:
work_money = float(input())
current_money += work_money
print(f'Going to {destination}!')
current_money = 0
destination = input() | destination = input()
current_money = 0
while destination != 'End':
vacation_money = float(input())
while current_money < vacation_money:
work_money = float(input())
current_money += work_money
print(f'Going to {destination}!')
current_money = 0
destination = input() |
"""Internal exception classes."""
class UnsatisfiableConstraint(Exception):
"""Raise when a specified constraint cannot be satisfied."""
pass
class UnsatisfiableType(UnsatisfiableConstraint):
"""Raised when a type constraint cannot be satisfied."""
pass
class TreeConstructionError(Exception):
... | """Internal exception classes."""
class Unsatisfiableconstraint(Exception):
"""Raise when a specified constraint cannot be satisfied."""
pass
class Unsatisfiabletype(UnsatisfiableConstraint):
"""Raised when a type constraint cannot be satisfied."""
pass
class Treeconstructionerror(Exception):
"""... |
class Book:
def __init__(self, title, bookType):
self.title = title
self.bookType = bookType
| class Book:
def __init__(self, title, bookType):
self.title = title
self.bookType = bookType |
XK_Aogonek = 0x1a1
XK_breve = 0x1a2
XK_Lstroke = 0x1a3
XK_Lcaron = 0x1a5
XK_Sacute = 0x1a6
XK_Scaron = 0x1a9
XK_Scedilla = 0x1aa
XK_Tcaron = 0x1ab
XK_Zacute = 0x1ac
XK_Zcaron = 0x1ae
XK_Zabovedot = 0x1af
XK_aogonek = 0x1b1
XK_ogonek = 0x1b2
XK_lstroke = 0x1b3
XK_lcaron = 0x1b5
XK_sacute = 0x1b6
XK_caron... | xk__aogonek = 417
xk_breve = 418
xk__lstroke = 419
xk__lcaron = 421
xk__sacute = 422
xk__scaron = 425
xk__scedilla = 426
xk__tcaron = 427
xk__zacute = 428
xk__zcaron = 430
xk__zabovedot = 431
xk_aogonek = 433
xk_ogonek = 434
xk_lstroke = 435
xk_lcaron = 437
xk_sacute = 438
xk_caron = 439
xk_scaron = 441
xk_scedilla = 4... |
load(
"//scala:scala.bzl",
"scala_library",
)
load(
"//scala:scala_cross_version.bzl",
_default_scala_version = "default_scala_version",
_extract_major_version = "extract_major_version",
_scala_mvn_artifact = "scala_mvn_artifact",
)
load(
"@io_bazel_rules_scala//scala:scala_maven_import_exte... | load('//scala:scala.bzl', 'scala_library')
load('//scala:scala_cross_version.bzl', _default_scala_version='default_scala_version', _extract_major_version='extract_major_version', _scala_mvn_artifact='scala_mvn_artifact')
load('@io_bazel_rules_scala//scala:scala_maven_import_external.bzl', _scala_maven_import_external='... |
def EDFB(U):
if U>1:
return False
else:
return True
def SC_EDF(tasks):
U=0
for itask in tasks:
U+=(itask['execution']+itask['sslength'])/itask['period']
return EDFB(U) | def edfb(U):
if U > 1:
return False
else:
return True
def sc_edf(tasks):
u = 0
for itask in tasks:
u += (itask['execution'] + itask['sslength']) / itask['period']
return edfb(U) |
"""
Write a Python function that takes a number as an input from the
user and computes its factorial.
Written by Sudipto Ghosh for the University of Delhi
"""
def factorial(n):
"""
Calculates factorial of a number
Arguments:
n {integer} -- input
Returns:
factorial {integer}
"""
... | """
Write a Python function that takes a number as an input from the
user and computes its factorial.
Written by Sudipto Ghosh for the University of Delhi
"""
def factorial(n):
"""
Calculates factorial of a number
Arguments:
n {integer} -- input
Returns:
factorial {integer}
"""
... |
#buffer = [0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]
#buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
#buffer = [0xB5, 0x62, 0x06, 0x3B,... | buffer = [181, 98, 5, 1, 2, 0, 6, 0]
ca = 0
cb = 0
for x in range(2, len(buffer)):
ca = 255 & ca + buffer[x]
cb = 255 & cb + ca
print(hex(ca))
print(hex(cb)) |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: he... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: hea... |
ifXTable = '.1.3.6.1.2.1.31.1.1.1'
ifName = ifXTable + '.1'
ifInMulticastPkts = ifXTable + '.2'
ifHCInOctets = ifXTable + '.6'
ifHCInUcastPkts = ifXTable + '.7'
ifHCInMulticastPkts = ifXTable + '.8'
ifHCInBroadcastPkts = ifXTable + '.9'
ifHCOutOctets = ifXTable + '.10'
ifHCOutUcastPkts = ifXTable + '.11'
ifHCOutMultica... | if_x_table = '.1.3.6.1.2.1.31.1.1.1'
if_name = ifXTable + '.1'
if_in_multicast_pkts = ifXTable + '.2'
if_hc_in_octets = ifXTable + '.6'
if_hc_in_ucast_pkts = ifXTable + '.7'
if_hc_in_multicast_pkts = ifXTable + '.8'
if_hc_in_broadcast_pkts = ifXTable + '.9'
if_hc_out_octets = ifXTable + '.10'
if_hc_out_ucast_pkts = ifX... |
# from django.views.generic.base import View
# from rest_framework.views import APIView
# from django.conf import settings
#!/usr/bin/env python
# def func():
# fun_list = []
# for i in range(4):
# def foo(x, i=i):
# return x*i
# fun_list.append(foo)
# return fun_list
#
#
# for... | class Singletool(object):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def addxnum(self, *args):
my_sum = 0
for value in args:
my_sum += value
return my... |
# modifying a list in a function
# Start with some designs that need to be printed.
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
# Simulate printing each design, until none are left.
# Move each design to completed_models after printing.
while unprinted_designs:
curren... | unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f'Printing model: {current_design}')
completed_models.append(current_design)
print('\nThe following models have been printed:')
for completed_mode... |
def foo():
x = 1
def bar():
nonlocal x
baz()
print(x)
def baz():
nonlocal x
x = 2
bar()
foo() | def foo():
x = 1
def bar():
nonlocal x
baz()
print(x)
def baz():
nonlocal x
x = 2
bar()
foo() |
"""Constants for the onboarding component."""
DOMAIN = "onboarding"
STEP_USER = "user"
STEP_CORE_CONFIG = "core_config"
STEP_INTEGRATION = "integration"
STEP_ANALYTICS = "analytics"
STEP_MOB_INTEGRATION = "mob_integration"
STEPS = [
STEP_USER,
STEP_CORE_CONFIG,
STEP_ANALYTICS,
STEP_INTEGRATION,
STE... | """Constants for the onboarding component."""
domain = 'onboarding'
step_user = 'user'
step_core_config = 'core_config'
step_integration = 'integration'
step_analytics = 'analytics'
step_mob_integration = 'mob_integration'
steps = [STEP_USER, STEP_CORE_CONFIG, STEP_ANALYTICS, STEP_INTEGRATION, STEP_MOB_INTEGRATION]
def... |
class MovieData:
def __init__(self,movie_name,imdb_id,plot,review,facts_table,comments,spans,labels,chat,chat_id):
self.movie_name=movie_name
self.imdb_id=imdb_id
self.plot=plot
self.review=review
self.facts_table=facts_table
self.comments=comments
s... | class Moviedata:
def __init__(self, movie_name, imdb_id, plot, review, facts_table, comments, spans, labels, chat, chat_id):
self.movie_name = movie_name
self.imdb_id = imdb_id
self.plot = plot
self.review = review
self.facts_table = facts_table
self.comments = comme... |
# Tests:
# ifstmt ::= testexpr _ifstmts_jump
# _ifstmts_jump ::= c_stmts_opt JUMP_FORWARD COME_FROM
if True:
b = False
| if True:
b = False |
class Solution:
def checkEqualTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return False
seen = set()
def dfs(root: Optional[TreeNode]) -> int:
if not root:
return 0
sum = root.val + dfs(root.left) + dfs(root.right)
seen.add(sum)
return sum
sum = ... | class Solution:
def check_equal_tree(self, root: Optional[TreeNode]) -> bool:
if not root:
return False
seen = set()
def dfs(root: Optional[TreeNode]) -> int:
if not root:
return 0
sum = root.val + dfs(root.left) + dfs(root.right)
... |
# color references:
# http://rebrickable.com/colors
# http://www.bricklink.com/catalogColors.asp
rebrickable_color_to_bricklink = {
# Solid Colors
15: (1, 'White'),
503: (49, 'Very Light Gray'),
151: (99, 'Very Light Bluish Gray'),
71: (86, 'Light Bluish Gray'),
7: (9, 'Light Gray'),
8: (10, 'Dark Gray'),
... | rebrickable_color_to_bricklink = {15: (1, 'White'), 503: (49, 'Very Light Gray'), 151: (99, 'Very Light Bluish Gray'), 71: (86, 'Light Bluish Gray'), 7: (9, 'Light Gray'), 8: (10, 'Dark Gray'), 72: (85, 'Dark Bluish Gray'), 0: (11, 'Black'), 320: (59, 'Dark Red'), 4: (5, 'Red'), 216: (27, 'Rust'), 12: (25, 'Salmon'), 1... |
"""
Root-level catalog interface
"""
class ValidationError(Exception):
pass
class PrivateArchive(Exception):
pass
class EntityNotFound(Exception):
pass
class NoAccessToEntity(Exception):
"""
Used when the actual entity is not accessible, i.e. when a ref cannot dereference itself
"""
p... | """
Root-level catalog interface
"""
class Validationerror(Exception):
pass
class Privatearchive(Exception):
pass
class Entitynotfound(Exception):
pass
class Noaccesstoentity(Exception):
"""
Used when the actual entity is not accessible, i.e. when a ref cannot dereference itself
"""
pass... |
def get_gender(sex='unknown'):
if sex == 'm':
sex = 'male'
elif sex == 'f':
sex = 'female'
print(sex)
get_gender('m')
get_gender('f')
get_gender()
| def get_gender(sex='unknown'):
if sex == 'm':
sex = 'male'
elif sex == 'f':
sex = 'female'
print(sex)
get_gender('m')
get_gender('f')
get_gender() |
description = 'Example Sans2D Pixel Detector Setup with Instrument View'
group = 'basic'
sysconfig = dict(
instrument = 'sans2d',
)
devices = dict(
sans2d = device('nicos_demo.mantid.devices.instrument.ViewableInstrument',
description = 'instrument object',
responsible = 'R. Esponsible <r.esp... | description = 'Example Sans2D Pixel Detector Setup with Instrument View'
group = 'basic'
sysconfig = dict(instrument='sans2d')
devices = dict(sans2d=device('nicos_demo.mantid.devices.instrument.ViewableInstrument', description='instrument object', responsible='R. Esponsible <r.esponsible@stfc.ac.uk>', instrument='sans2... |
class Student:
def __init__(self,name="",roll=2):
print("para init called")
self.name=name
self.roll_no=roll
def hello(self):
print("Hello this is: ",self.name)
print("Your roll no. is: ",self.roll_no)
| class Student:
def __init__(self, name='', roll=2):
print('para init called')
self.name = name
self.roll_no = roll
def hello(self):
print('Hello this is: ', self.name)
print('Your roll no. is: ', self.roll_no) |
description = 'pressure filter readout'
group = 'lowlevel'
devices = dict(
# p_in_filter = device('nicos_mlz.sans1.devices.wut.WutValue',
# hostname = 'sans1wut-p-diff-fak40.sans1.frm2',
# port = '1',
# description = 'pressure in front of filter',
# fmtstr = '%.2F',
# logle... | description = 'pressure filter readout'
group = 'lowlevel'
devices = dict() |
#Python doesn't support Generics
#you can do it like this in java or C++ or
#any other Object Oriented language which supports Generics
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
di... | class Advancedarithmetic(object):
def divisor_sum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisor_sum(self, n):
divisor = []
for i in range(n):
x = len([i for i in range(1, n + 1) if n % i])
divisor.append(x)
res = sum(di... |
class Solution:
def solve(self, nums, k):
history = [nums[:]]
seen = {tuple(nums)}
before_cycle = []
cycle = []
while True:
nums2 = [0]*8
for i in range(1,7):
l = (nums[i-1] if i-1 >= 0 else 0) + (nums[i+1] if i+1 < 8 else 0)
... | class Solution:
def solve(self, nums, k):
history = [nums[:]]
seen = {tuple(nums)}
before_cycle = []
cycle = []
while True:
nums2 = [0] * 8
for i in range(1, 7):
l = (nums[i - 1] if i - 1 >= 0 else 0) + (nums[i + 1] if i + 1 < 8 else 0... |
expected_output = {
"Tunnel10": {
"bandwidth": 100,
"counters": {
"in_abort": 0,
"in_broadcast_pkts": 0,
"in_crc_errors": 0,
"in_errors": 0,
"in_frame": 0,
"in_giants": 0,
"in_ignored": 0,
"in_multicast_p... | expected_output = {'Tunnel10': {'bandwidth': 100, 'counters': {'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_errors': 0, 'in_frame': 0, 'in_giants': 0, 'in_ignored': 0, 'in_multicast_pkts': 0, 'in_no_buffer': 0, 'in_octets': 0, 'in_overrun': 0, 'in_pkts': 0, 'in_runts': 0, 'in_throttles': 0, 'last_clea... |
input = open('input.txt');
length = int(input.readline());
tokens = input.readline().split(' ');
input.close();
output = open('output.txt' , 'w');
i = 0;
while i < length:
j = 0;
while (int(tokens[i]) >= int(tokens[j])) & (j < i):
j += 1;
if j < i:
shelf = tokens[i];
k = i;
w... | input = open('input.txt')
length = int(input.readline())
tokens = input.readline().split(' ')
input.close()
output = open('output.txt', 'w')
i = 0
while i < length:
j = 0
while (int(tokens[i]) >= int(tokens[j])) & (j < i):
j += 1
if j < i:
shelf = tokens[i]
k = i
while k > j:... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
expected_output = {
"ospf-database-information": {
"ospf-area-header": {"ospf-area": "192.168.76.0"},
"ospf-database": {
"@heading": "Type ID Adv Rtr Seq Age Opt Cksum Len",
"advertising-router": "192.168.219.235",
"age": "173... | expected_output = {'ospf-database-information': {'ospf-area-header': {'ospf-area': '192.168.76.0'}, 'ospf-database': {'@heading': 'Type ID Adv Rtr Seq Age Opt Cksum Len', 'advertising-router': '192.168.219.235', 'age': '1730', 'checksum': '0x1b56', 'lsa-id': '10.69.197.1', 'lsa-len... |
# 1.Why carry is a&b:
# If a and b are both 1 at the same digit, it creates one carry.
# Because you can only use 0 and 1 in binary, if you add 1+1 together, it will roll that over to the next digit, and the value will be 0 at this digit.
# if they are both 0 or only one is 1, it doesn't... | class Solution(object):
def get_sum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
infinity = 4294967295
while b & INFINITY != 0:
carry = (a & b) << 1
a = a ^ b
b = carry
return a & INFINITY if b > INFIN... |
while True:
h = int(input())
if h == 0:
break
arr = list()
arr.append(h)
while h != 1:
if h%2 == 0:
h = int((0.5)*h)
arr.append(h)
else:
h = 3 * h + 1
arr.append(h)
# print(arr)
print(max(arr)) | while True:
h = int(input())
if h == 0:
break
arr = list()
arr.append(h)
while h != 1:
if h % 2 == 0:
h = int(0.5 * h)
arr.append(h)
else:
h = 3 * h + 1
arr.append(h)
print(max(arr)) |
def read_input():
row, col = [int(x) for x in input().split()]
arr = [list(input()) for _ in range(row)]
return arr
def print_output(obj):
for i in obj:
print(''.join(i))
def test_pos(obj, grid, row, col):
for i in range(len(obj)):
for j in range(len(obj[0])):
if grid... | def read_input():
(row, col) = [int(x) for x in input().split()]
arr = [list(input()) for _ in range(row)]
return arr
def print_output(obj):
for i in obj:
print(''.join(i))
def test_pos(obj, grid, row, col):
for i in range(len(obj)):
for j in range(len(obj[0])):
if grid... |
# import pytest
class TestSingletonMeta:
def test___call__(self): # synced
assert True
class TestSingleton:
pass
| class Testsingletonmeta:
def test___call__(self):
assert True
class Testsingleton:
pass |
i = 0
result = 0
while i <= 100:
if i % 2 == 0:
result += i
i += 1
print(result)
j = 0
result2 = 0
while j <= 100:
result2 += j
j += 2
print(result2) | i = 0
result = 0
while i <= 100:
if i % 2 == 0:
result += i
i += 1
print(result)
j = 0
result2 = 0
while j <= 100:
result2 += j
j += 2
print(result2) |
# test for PR#112 -- functions should not have __module__ attributes
def f():
pass
if hasattr(f, '__module__'):
print('functions should not have __module__ attributes')
# but make sure classes still do have __module__ attributes
class F:
pass
if not hasattr(F, '__module__'):
print('classes should st... | def f():
pass
if hasattr(f, '__module__'):
print('functions should not have __module__ attributes')
class F:
pass
if not hasattr(F, '__module__'):
print('classes should still have __module__ attributes') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.