content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def convert_temp(unit_in, unit_out, temp):
"""Convert farenheit <-> celsius and return results.
- unit_in: either "f" or "c"
- unit_out: either "f" or "c"
- temp: temperature (in f or c, depending on unit_in)
Return results of conversion, if any.
If unit_in or unit_out are invalid, return "I... | def convert_temp(unit_in, unit_out, temp):
"""Convert farenheit <-> celsius and return results.
- unit_in: either "f" or "c"
- unit_out: either "f" or "c"
- temp: temperature (in f or c, depending on unit_in)
Return results of conversion, if any.
If unit_in or unit_out are invalid, return "I... |
class TemplatesAdminHook(object):
'''
Hook baseclass
'''
@classmethod
def pre_save(cls, request, form, template_path):
pass
@classmethod
def post_save(cls, request, form, template_path):
pass
@classmethod
def contribute_to_form(cls, form, template_path):
r... | class Templatesadminhook(object):
"""
Hook baseclass
"""
@classmethod
def pre_save(cls, request, form, template_path):
pass
@classmethod
def post_save(cls, request, form, template_path):
pass
@classmethod
def contribute_to_form(cls, form, template_path):
re... |
#!/usr/bin/env python
class SNVMixRecord(object):
def __init__(self, line):
"""
:param line: a line of SNVMix2 output
:type line: str
"""
data = line.strip().split()
location = data[0].split(':')
self.chromosome = location[0]
self.position = int(loca... | class Snvmixrecord(object):
def __init__(self, line):
"""
:param line: a line of SNVMix2 output
:type line: str
"""
data = line.strip().split()
location = data[0].split(':')
self.chromosome = location[0]
self.position = int(location[1])
self.r... |
'''
2
Check if a number is odd or even
'''
def odd_or_even_using_modulus(n):
if n%2 == 0:
return("Even")
else:
return("Odd")
def odd_or_even_using_bitwise_and(n):
if n&1 == 0:
return("Even")
else:
return("Odd")
if __name__ == "__main__":
n = int(input("Number? ... | """
2
Check if a number is odd or even
"""
def odd_or_even_using_modulus(n):
if n % 2 == 0:
return 'Even'
else:
return 'Odd'
def odd_or_even_using_bitwise_and(n):
if n & 1 == 0:
return 'Even'
else:
return 'Odd'
if __name__ == '__main__':
n = int(input('Number? '))
... |
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def recursion(startIdx, endIdx):
if startIdx >= endIdx: return True
curIdx = startIdx
while postorder[curIdx] < postorder[endIdx]:
curIdx += 1
rightStartIdx = curIdx
while postorder[curIdx] > postorder[e... | class Solution:
def verify_postorder(self, postorder: List[int]) -> bool:
def recursion(startIdx, endIdx):
if startIdx >= endIdx:
return True
cur_idx = startIdx
while postorder[curIdx] < postorder[endIdx]:
cur_idx += 1
right_s... |
"""
from : https://leetcode.com/problems/candy-crush/discuss/1028524/Python-Straightforward-and-Clean-with-Explanation
Don't be intimidated by how long or ugly the code looks. Sometimes I fall into that trap. It's simpler than it seems.
Also, I would love feedback if this is helpful, or if there are any mistakes!
A ke... | """
from : https://leetcode.com/problems/candy-crush/discuss/1028524/Python-Straightforward-and-Clean-with-Explanation
Don't be intimidated by how long or ugly the code looks. Sometimes I fall into that trap. It's simpler than it seems.
Also, I would love feedback if this is helpful, or if there are any mistakes!
A ke... |
# darwin64.py
# Mac OS X platform specific configuration
def config(env,args):
debug = args.get('debug',0)
if int(debug):
env.Append(CXXFLAGS = env.Split('-g -O0'))
else:
env.Append(CXXFLAGS = '-O')
env.Append(CPPDEFINES= 'NDEBUG')
env.Append(CPPDEFINES= 'WITH_DEBUG')
env... | def config(env, args):
debug = args.get('debug', 0)
if int(debug):
env.Append(CXXFLAGS=env.Split('-g -O0'))
else:
env.Append(CXXFLAGS='-O')
env.Append(CPPDEFINES='NDEBUG')
env.Append(CPPDEFINES='WITH_DEBUG')
env.Append(CXXFLAGS=env.Split('-Wall -fPIC'))
env.Append(CPPDEFI... |
class ProjectView(object):
def __init__(self, project_id, name, status, selected_cluster_id):
self.id = project_id
self.name = name
self.status = status
self.selected_cluster_id = selected_cluster_id
class ClusterView(object):
def __init__(self, cluster_id, anchor, selected=... | class Projectview(object):
def __init__(self, project_id, name, status, selected_cluster_id):
self.id = project_id
self.name = name
self.status = status
self.selected_cluster_id = selected_cluster_id
class Clusterview(object):
def __init__(self, cluster_id, anchor, selected=Fa... |
b2bi_strings = {
19: "g1VrCfVNFH+rV57qwbKeQla3oBPyyFjb4gEwtD6wgY2IlHxi8PIxjhilZLQd3c+N2dF9vKj79McEnR128FDVDU7ah4JipfLyAoRr8uy7R4FirnY8Xox1OSAS23Chz39lWmFFAq0lmg0C5s62acgk2ALzDECWwvguqPfmsc+Uv77MtWF1ubIFwQEGJhtOCKDKTim1gG6E+eYH0k1NmX5orDwhHmDzdJAt8AcmIJKPxlSSxdrfmp+4iNaFdUMDqOHw38QBUydx36LhOqhwgmsjRMjTjAnYP+ccxUxg2vtU... | b2bi_strings = {19: 'g1VrCfVNFH+rV57qwbKeQla3oBPyyFjb4gEwtD6wgY2IlHxi8PIxjhilZLQd3c+N2dF9vKj79McEnR128FDVDU7ah4JipfLyAoRr8uy7R4FirnY8Xox1OSAS23Chz39lWmFFAq0lmg0C5s62acgk2ALzDECWwvguqPfmsc+Uv77MtWF1ubIFwQEGJhtOCKDKTim1gG6E+eYH0k1NmX5orDwhHmDzdJAt8AcmIJKPxlSSxdrfmp+4iNaFdUMDqOHw38QBUydx36LhOqhwgmsjRMjTjAnYP+ccxUxg2vtUSok... |
"""Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the... | """Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the... |
class StringUtils(object):
@staticmethod
def get_first_row_which_starts_with(text, starts_with):
rows = str(text).split("\n")
for row in rows:
str_row = str(row)
if str_row.startswith(starts_with):
return str_row
@staticmethod
def get_value_afte... | class Stringutils(object):
@staticmethod
def get_first_row_which_starts_with(text, starts_with):
rows = str(text).split('\n')
for row in rows:
str_row = str(row)
if str_row.startswith(starts_with):
return str_row
@staticmethod
def get_value_after... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PinValidationError(Exception):
pass
class PinChangingError(Exception):
pass
class AccountWithoutBalanceError(Exception):
pass
class Account:
def __init__(self, id: str, pin: str, balance: float):
self.__id = id
self.__pin = pin
... | class Pinvalidationerror(Exception):
pass
class Pinchangingerror(Exception):
pass
class Accountwithoutbalanceerror(Exception):
pass
class Account:
def __init__(self, id: str, pin: str, balance: float):
self.__id = id
self.__pin = pin
self.__balance = balance
def id(self)... |
model_lib = {
'fasterrcnn_mobilenet_v3_large_320_fpn': {
'model_path': 'fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth',
'tx2_delay': 0.18,
'cloud_delay': 0.024,
'precision': None,
'service_type': 'object_detection'
},
'fasterrcnn_mobilenet_v3_large_fpn': {
... | model_lib = {'fasterrcnn_mobilenet_v3_large_320_fpn': {'model_path': 'fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth', 'tx2_delay': 0.18, 'cloud_delay': 0.024, 'precision': None, 'service_type': 'object_detection'}, 'fasterrcnn_mobilenet_v3_large_fpn': {'model_path': 'fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth'... |
#
# PySNMP MIB module RBN-BIND-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-BIND-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
"""Although you have to be careful using recursion it is one of those concepts you want to at least understand. It's also commonly used in coding interviews :)
In this beginner Bite we let you rewrite a simple countdown for loop using recursion. See countdown_for below, it produces the following output:
least unders... | """Although you have to be careful using recursion it is one of those concepts you want to at least understand. It's also commonly used in coding interviews :)
In this beginner Bite we let you rewrite a simple countdown for loop using recursion. See countdown_for below, it produces the following output:
least unders... |
text = "W. W. W. S. S. S. S. W. W. S. UNLOCK FRONT DOOR. S. WAIT. NO. LOOK AT WEATHER. WAIT. N. W. W. S. W. N. GET FOLDER AND MASK. MOVE BODY. LOOK IN WASTE BASKET. GET CARD AND OBJECT. S. E. N. E. E. E. E. N. W. DROP PEN AND NOTEBOOK. GET WET OVERCOAT. E. E. E. E. SHOW FOLDER TO ASTRONAUT. SHOW CARD TO ASTRONAUT. EXAM... | text = 'W. W. W. S. S. S. S. W. W. S. UNLOCK FRONT DOOR. S. WAIT. NO. LOOK AT WEATHER. WAIT. N. W. W. S. W. N. GET FOLDER AND MASK. MOVE BODY. LOOK IN WASTE BASKET. GET CARD AND OBJECT. S. E. N. E. E. E. E. N. W. DROP PEN AND NOTEBOOK. GET WET OVERCOAT. E. E. E. E. SHOW FOLDER TO ASTRONAUT. SHOW CARD TO ASTRONAUT. EXAM... |
API_TOKEN = "xxxxxxxxx"
DEFAULT_REPLY = "Sorry but I didn't understand you"
PLUGINS = [
'slackbot.plugins'
] | api_token = 'xxxxxxxxx'
default_reply = "Sorry but I didn't understand you"
plugins = ['slackbot.plugins'] |
'''
You've been using list comprehensions to build lists of values, sometimes using operations to create these values.
An interesting mechanism in list comprehensions is that you can also create lists with values that meet only a certain condition. One way of doing this is by using conditionals on iterator variables. ... | """
You've been using list comprehensions to build lists of values, sometimes using operations to create these values.
An interesting mechanism in list comprehensions is that you can also create lists with values that meet only a certain condition. One way of doing this is by using conditionals on iterator variables. ... |
print("\n")
name = input("What's your name? ")
age = input("How old are you? ")
city = input("Where do you live? ")
print("\n")
print("Hello,", name)
print("Your age is", age)
print("You live in", city)
print("\n") | print('\n')
name = input("What's your name? ")
age = input('How old are you? ')
city = input('Where do you live? ')
print('\n')
print('Hello,', name)
print('Your age is', age)
print('You live in', city)
print('\n') |
"""
logalyzer:
Parses your bloated HTTP access logs to extract the info you want
about hits from (hopefully) real people instead of just the endless
stream of hackers and bots that passes for web traffic
nowadays. Stores the info in a relational database where you can
access it using all the power of SQL.
"""
| """
logalyzer:
Parses your bloated HTTP access logs to extract the info you want
about hits from (hopefully) real people instead of just the endless
stream of hackers and bots that passes for web traffic
nowadays. Stores the info in a relational database where you can
access it using all the power of SQL.
""" |
#cerner_2tothe5th_2021
# Get all substrings of a given string using slicing of string
# initialize the string
input_string = "floccinaucinihilipilification"
# print the input string
print("The input string is : " + str(input_string))
# Get all substrings of the string
result = [input_string[i: j] for ... | input_string = 'floccinaucinihilipilification'
print('The input string is : ' + str(input_string))
result = [input_string[i:j] for i in range(len(input_string)) for j in range(i + 1, len(input_string) + 1)]
print('All substrings of the input string are : ' + str(result)) |
#Sasikala Varatharajan G00376470
#Program to find all divisors between the given two numbers
#In this program we are going to find the numbers divisble by 6 but not by 12
#Get two inputs from the user - As per the instructions it should use 1000 as int_From and 10000 as int_to.
#But I have given an option to the user... | int__from = int(input('Enter the Range of numbers starts with : '))
int__to = int(input('Enter the Range of numbers ends with : '))
print('Divisable by 6 but not by 12 between', int_From, 'and', int_To, 'are:')
for num in range(int_From, int_To + 1):
if num % 6 == 0 and num % 12 != 0:
print(num)
else:
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
_, maxSum = self.maxPa... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def max_path_sum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
(_, max_sum) = self.maxPathSumHelper(root)
retu... |
# Author: weiwei
class BaseEvaluator:
def __init__(self, result_dir):
self.result_dir = result_dir
def evaluate(self, output, batch):
raise NotImplementedError()
def summarize(self):
raise NotImplementedError()
| class Baseevaluator:
def __init__(self, result_dir):
self.result_dir = result_dir
def evaluate(self, output, batch):
raise not_implemented_error()
def summarize(self):
raise not_implemented_error() |
#
# PySNMP MIB module HP-ICF-RIP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-RIP
# Produced by pysmi-0.3.4 at Mon Apr 29 19:22:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ... |
{
'name': "MOBtexting SMS Gateway",
'version': '1.0',
'author': "MOBtexting",
'category': 'Tools',
'summary':'MOBtexting SMS Gateway',
'description':'You can use sms template to send SMS using MOBtexting Intergration.',
'website': "http://www.mobtexting.com",
'depends': ['base','web',],
... | {'name': 'MOBtexting SMS Gateway', 'version': '1.0', 'author': 'MOBtexting', 'category': 'Tools', 'summary': 'MOBtexting SMS Gateway', 'description': 'You can use sms template to send SMS using MOBtexting Intergration.', 'website': 'http://www.mobtexting.com', 'depends': ['base', 'web'], 'sequence': -80, 'data': ['view... |
"""
fake_libc.py
For PyPy.
"""
def regex_parse(regex_str):
return True
# This makes things fall through to the first case statement...
def fnmatch(s, to_match):
return True
| """
fake_libc.py
For PyPy.
"""
def regex_parse(regex_str):
return True
def fnmatch(s, to_match):
return True |
def quicksort (lst):
if lst == []:
return []
else:
smallsorted = quicksort([x for x in lst[1:] if x <= lst[0]])
bigsorted = quicksort([x for x in lst[1:] if x > lst[0]])
return smallsorted + [lst[0]] + bigsorted
| def quicksort(lst):
if lst == []:
return []
else:
smallsorted = quicksort([x for x in lst[1:] if x <= lst[0]])
bigsorted = quicksort([x for x in lst[1:] if x > lst[0]])
return smallsorted + [lst[0]] + bigsorted |
class Board():
def __init__(self):
self.grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0... | class Board:
def __init__(self):
self.grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]]
... |
aos_global_config.set('no_with_lwip', 1)
src = Split('''
soc/uart.c
main/arg_options.c
main/main.c
main/hw.c
main/wifi_port.c
main/ota_port.c
main/nand.c
main/vfs_trap.c
''')
global_cflags = Split('''
-m32
-std=gnu99
-Wall
-Wno-missing-field-initializers
-Wno-strict... | aos_global_config.set('no_with_lwip', 1)
src = split('\n soc/uart.c\n main/arg_options.c\n main/main.c\n main/hw.c\n main/wifi_port.c\n main/ota_port.c\n main/nand.c\n main/vfs_trap.c\n')
global_cflags = split('\n -m32\n -std=gnu99\n -Wall\n -Wno-missing-field-initializers\n -Wno-... |
myl1 = [1,2,3,4,5]
myl2 = myl1.copy()
print(id(myl1))
print(id(myl2))
print("Initially")
print(" myl1 is: ", myl1)
print(" myl2 is: ", myl2)
print("--------------------")
myl1[2] = 13
print("Modifying myl1")
print(" myl1 is: ", myl1)
print(" myl2 is: ", myl2)
print("--------------------")
myl2[3] = 14
print("Modifying ... | myl1 = [1, 2, 3, 4, 5]
myl2 = myl1.copy()
print(id(myl1))
print(id(myl2))
print('Initially')
print(' myl1 is: ', myl1)
print(' myl2 is: ', myl2)
print('--------------------')
myl1[2] = 13
print('Modifying myl1')
print(' myl1 is: ', myl1)
print(' myl2 is: ', myl2)
print('--------------------')
myl2[3] = 14
print('Modify... |
if __name__=="__main__":
t=int(input())
while(t>0):
(n, k) = map(int, input().split())
li=list(map(int, input().split()[:n]))
min = 99999999
for i in range(len(li)):
if li[i] < min:
min=li[i]
if k-min > 0:
print(k-min)
else:... | if __name__ == '__main__':
t = int(input())
while t > 0:
(n, k) = map(int, input().split())
li = list(map(int, input().split()[:n]))
min = 99999999
for i in range(len(li)):
if li[i] < min:
min = li[i]
if k - min > 0:
print(k - min)
... |
people = [
[['Kay', 'McNulty'], 'mcnulty@eniac.org'],
[['Betty', 'Jennings'], 'jennings@eniac.org'],
[['Marlyn', 'Wescoff'], 'mwescoff@eniac.org']
]
for [[first, last], email] in people:
print('{} {} <{}>'.format(first, last, email))
| people = [[['Kay', 'McNulty'], 'mcnulty@eniac.org'], [['Betty', 'Jennings'], 'jennings@eniac.org'], [['Marlyn', 'Wescoff'], 'mwescoff@eniac.org']]
for [[first, last], email] in people:
print('{} {} <{}>'.format(first, last, email)) |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Kaleb Roscco Horvath
#
# 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
# ... | """PyIface - Easy API for low-level wireless hardware system calls.
This package exports the following modules and subpackages:
Interface - the public bound object that binds together all private API methods.
Since version 1.2.beta, PyIface implements the Interface object. Older applicants
of PyIface are HIGHLY ENCO... |
# Helper function to get the turning performance with moving in upward right lane and
# turn left.
def UpLeftRightLane(line1, line2, flag, x, y):
laneWidth = abs(line2[0][0]-line2[0][1])
half = line2[0][0] + laneWidth/2 + 2
Rang1_1 = [[half-2, half],[ line2[1][0], line2[1][1] ]]
Rang1_2 = [[half, half... | def up_left_right_lane(line1, line2, flag, x, y):
lane_width = abs(line2[0][0] - line2[0][1])
half = line2[0][0] + laneWidth / 2 + 2
rang1_1 = [[half - 2, half], [line2[1][0], line2[1][1]]]
rang1_2 = [[half, half + 0.5], [line2[1][0], line2[1][1]]]
rang2_1 = [[half - 3, half - 2], [line2[1][0], line... |
a,b,c = input().split(" ")
A = int(a)
B = int(b)
C = int(c)
MAIORAB = (A + B + abs(A-B))/2
MAIOR = (MAIORAB + C + abs(MAIORAB - C))/2
print("%d eh o maior" %MAIOR)
| (a, b, c) = input().split(' ')
a = int(a)
b = int(b)
c = int(c)
maiorab = (A + B + abs(A - B)) / 2
maior = (MAIORAB + C + abs(MAIORAB - C)) / 2
print('%d eh o maior' % MAIOR) |
'''
Exercise 11 (0 points).
Implement a function to compute the Hessian of the log-likelihood. The signature of your function should be,
'''
def hess_log_likelihood(theta, y, X):
"""Returns the Hessian of the log-likelihood."""
z = X.dot(theta)
A = np.multiply(X, logistic(z))
B = np.multiply(X, logist... | """
Exercise 11 (0 points).
Implement a function to compute the Hessian of the log-likelihood. The signature of your function should be,
"""
def hess_log_likelihood(theta, y, X):
"""Returns the Hessian of the log-likelihood."""
z = X.dot(theta)
a = np.multiply(X, logistic(z))
b = np.multiply(X, logist... |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
Hivy
----
Hivy exposes a RESTful API to the Unide (unide.co) platform. Create, destroy
and configure collaborative development environments and services around it.
:copyright (c) 2014 Xavier Bruhier.
:license: Apache 2.0, see LICENSE for more details.
'''
__... | """
Hivy
----
Hivy exposes a RESTful API to the Unide (unide.co) platform. Create, destroy
and configure collaborative development environments and services around it.
:copyright (c) 2014 Xavier Bruhier.
:license: Apache 2.0, see LICENSE for more details.
"""
__project__ = 'hivy'
__author__ = 'Xavier Bruh... |
MEMORY_SIZE = 64 * 1024
WORD_LENGTH = 255
_IN = "IN" # constant to specify input ports
_OUT = "OUT" # constant to specify output ports
| memory_size = 64 * 1024
word_length = 255
_in = 'IN'
_out = 'OUT' |
inputFile = "day13/day13_1_input.txt"
# https://adventofcode.com/2021/day/13
def deleteAndAddKeys(paperDict, keysToPop, keysToAdd):
for key in keysToPop:
del paperDict[key]
for key in keysToAdd:
if key not in paperDict:
paperDict[key] = True
def foldYUp(paperDict, y):
keysT... | input_file = 'day13/day13_1_input.txt'
def delete_and_add_keys(paperDict, keysToPop, keysToAdd):
for key in keysToPop:
del paperDict[key]
for key in keysToAdd:
if key not in paperDict:
paperDict[key] = True
def fold_y_up(paperDict, y):
keys_to_pop = []
keys_to_add = []
... |
SPECIMEN_MAPPING = {
"output_name": "specimen",
"select": [
"specimen_id",
"external_sample_id",
"colony_id",
"strain_accession_id",
"genetic_background",
"strain_name",
"zygosity",
"production_center",
"phenotyping_center",
"projec... | specimen_mapping = {'output_name': 'specimen', 'select': ['specimen_id', 'external_sample_id', 'colony_id', 'strain_accession_id', 'genetic_background', 'strain_name', 'zygosity', 'production_center', 'phenotyping_center', 'project', 'litter_id', 'biological_sample_group', 'sex', 'pipeline_stable_id', 'developmental_st... |
class Node:
def __init__(self, data=None):
self.__data = data
self.__next = None
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
de... | class Node:
def __init__(self, data=None):
self.__data = data
self.__next = None
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
d... |
# Copyright (C) 2018-2021 Seoul National University
#
# 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... | """Crane, GPU Cluster Manager for DL training.
When a Job is submitted to the cluster, it goes into job queue (Queued)
When a Job is scheduled, it goes into running job pool (Running)
- At running state, each Job has ApplicationMaster(AM).
- AM receives MiniCluster.
- AM can create Tasks. A Task is a group of containe... |
def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=True,
feature_vec=True):
"""
Function accepts params and returns HOG features (optionally flattened) and an optional matrix for
visualization. Features will always be the first return (flatten... | def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=True, feature_vec=True):
"""
Function accepts params and returns HOG features (optionally flattened) and an optional matrix for
visualization. Features will always be the first return (flattened if feature_vector= True).
A visualizatio... |
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | class Communicationmetadata(object):
command = 'command'
task_name = 'task_name'
fl_ctx = 'fl_ctx'
event_type = 'event_type'
handle_conn = 'handle_conn'
exe_conn = 'exe_conn'
components = 'MPExecutor_components'
handlers = 'MPExecutor_handlers'
local_executor = 'local_executor'
r... |
def Part1():
File = open("Input.txt").read().split("\n")
Order = [3,1]
CurrentLocation = [0,0]
Trees = 0
while (CurrentLocation[1] < len(File)-1):
CurrentLocation[1] += Order[1]
CurrentLocation[0] += Order[0]
if File[CurrentLocation[1]][CurrentLocation[0] % 31] == "#":
... | def part1():
file = open('Input.txt').read().split('\n')
order = [3, 1]
current_location = [0, 0]
trees = 0
while CurrentLocation[1] < len(File) - 1:
CurrentLocation[1] += Order[1]
CurrentLocation[0] += Order[0]
if File[CurrentLocation[1]][CurrentLocation[0] % 31] == '#':
... |
lista=[[],[]]
for i in range(0,7):
numero=int(input('Digite um valor: '))
if numero%2==0:
lista[0].append(numero)
else:
lista[1].append(numero)
lista[0].sort()
lista[1].sort()
print(f'Os valores pares foram {lista[0]} e os impares foram {lista[1]}') | lista = [[], []]
for i in range(0, 7):
numero = int(input('Digite um valor: '))
if numero % 2 == 0:
lista[0].append(numero)
else:
lista[1].append(numero)
lista[0].sort()
lista[1].sort()
print(f'Os valores pares foram {lista[0]} e os impares foram {lista[1]}') |
class Build:
def __init__(self, **CONFIG):
self.CONFIG = CONFIG
try: self.builtup = CONFIG['STRING']
except KeyError: raise KeyError('Could not find configuration "STRING"')
def __call__(self):
return self.builtup
def reset(self):
self.builtup = self.CONFIG['STRING'... | class Build:
def __init__(self, **CONFIG):
self.CONFIG = CONFIG
try:
self.builtup = CONFIG['STRING']
except KeyError:
raise key_error('Could not find configuration "STRING"')
def __call__(self):
return self.builtup
def reset(self):
self.buil... |
class Check(object):
'''Base class for defining linting checks.'''
ID = None
def run(self, name, meta, source):
return True
| class Check(object):
"""Base class for defining linting checks."""
id = None
def run(self, name, meta, source):
return True |
# pylint: skip-file
# flake8: noqa
# noqa: E302,E301
# pylint: disable=too-many-instance-attributes
class RouteConfig(object):
''' Handle route options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
namespace,
kubeconfig,
... | class Routeconfig(object):
""" Handle route options """
def __init__(self, sname, namespace, kubeconfig, destcacert=None, cacert=None, cert=None, key=None, host=None, tls_termination=None, service_name=None, wildcard_policy=None, weight=None):
""" constructor for handling route options """
self... |
class Observer:
"""
Abstract class for implementation of observers used to monitor EvolutionEngine process.
"""
def trigger(self, event):
"""
This function is trigger by EvolutionEngine when particular event occurs.
:param event: Event
"""
raise NotImplementedErr... | class Observer:
"""
Abstract class for implementation of observers used to monitor EvolutionEngine process.
"""
def trigger(self, event):
"""
This function is trigger by EvolutionEngine when particular event occurs.
:param event: Event
"""
raise not_implemented_... |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# Solution 1:
# Time Complexity: O(n)
# Space Complexity: O(n)
# nums_sorted = sorted(nums)
# res = []
# for num in nums:
# res.append(nums_sorted.index(num))
# retu... | class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
res = []
for i in nums:
summ = 0
for j in nums:
if i > j:
summ += 1
res.append(summ)
return res |
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 2:
return len(s)
cur = 1
left = -1
max_length = 1
while cur < len(s):
rindex = cur - 1
while rindex >= 0:
... | class Solution:
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 2:
return len(s)
cur = 1
left = -1
max_length = 1
while cur < len(s):
rindex = cur - 1
while rindex >= 0... |
# jupyter_notebook_config.py in $JUPYTER_CONFIG_DIR
c = get_config()
# c.NotebookApp.allow_root = True
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888 # NOTE don't forget to open
c.NotebookApp.open_browser = False
c.NotebookApp.allow_remote_access = True
c.NotebookApp.password_required = False
c.NotebookApp.password... | c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.allow_remote_access = True
c.NotebookApp.password_required = False
c.NotebookApp.password = ''
c.NotebookApp.token = '' |
def to_separate_args(content: str, sep='|'):
return list(map(lambda s: s.strip(), content.split(sep)))
def prepare_bot_module(name: str):
if not name.startswith('cogs.'):
name = 'cogs.' + name
return name
| def to_separate_args(content: str, sep='|'):
return list(map(lambda s: s.strip(), content.split(sep)))
def prepare_bot_module(name: str):
if not name.startswith('cogs.'):
name = 'cogs.' + name
return name |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: system_certificate
short_description: Resource module for System Certificate
description:
- Manage operations upda... | documentation = "\n---\nmodule: system_certificate\nshort_description: Resource module for System Certificate\ndescription:\n- Manage operations update and delete of the resource System Certificate.\nversion_added: '1.0.0'\nextends_documentation_fragment:\n - cisco.ise.module\nauthor: Rafael Campos (@racampos)\noption... |
# Copyright (c) 2020 safexl
# A config file to capture Excel constants for later use
# these are also available from `win32com.client.constants`
# though not in a format that plays nicely with autocomplete in IDEs
# Can be accessed like - `safexl.xl_constants.xlToLeft`
# Constants
xlAll = -4104
xlAutomatic =... | xl_all = -4104
xl_automatic = -4105
xl_both = 1
xl_center = -4108
xl_checker = 9
xl_circle = 8
xl_corner = 2
xl_criss_cross = 16
xl_cross = 4
xl_diamond = 2
xl_distributed = -4117
xl_double_accounting = 5
xl_fixed_value = 1
xl_formats = -4122
xl_gray16 = 17
xl_gray8 = 18
xl_grid = 15
xl_high = -4127
xl_inside = 2
xl_ju... |
'''
Your function should take in a signle parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
print(word)
if len(word) < 2:
re... | """
Your function should take in a signle parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
"""
def count_th(word):
print(word)
if len(word) < 2:
retu... |
def triangle(rows):
spaces = rows
for i in range(0, rows*2, 2):
for j in range(0, spaces):
print(end = " ")
spaces -= 1
for j in range(0, i + 1):
print("$", end = "")
print()
triangle(5) | def triangle(rows):
spaces = rows
for i in range(0, rows * 2, 2):
for j in range(0, spaces):
print(end=' ')
spaces -= 1
for j in range(0, i + 1):
print('$', end='')
print()
triangle(5) |
# list examples
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[]
print(a)
a.extend('ab')
print(a)
a.extend([1,2,33])
print(a)
| a = ['spam', 'eggs', 100, 1234]
print(a[:2] + ['bacon', 2 * 2])
print(3 * a[:3] + ['Boo!'])
print(a[:])
a[2] = a[2] + 23
print(a)
a[0:2] = [1, 12]
print(a)
a[0:2] = []
print(a)
a[1:1] = ['bletch', 'xyzzy']
print(a)
a[:0] = a
print(a)
a[:] = []
print(a)
a.extend('ab')
print(a)
a.extend([1, 2, 33])
print(a) |
class Message_Template:
def __init__(
self,
chat_id,
text,
disable_web_page_preview=None,
reply_to_message_id=None,
reply_markup=None,
parse_mode=None,
disable_notification=None,
timeout=None
):
self.chat_id = chat_id
self.text = text
self.disable_web_page_preview = disable_web_page_pre... | class Message_Template:
def __init__(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None, timeout=None):
self.chat_id = chat_id
self.text = text
self.disable_web_page_preview = disable_web_page_preview
... |
# -*- coding: utf-8 -*-
"""
__init__.py
~~~~~~~~~~~~~~
Test package definition.
:copyright: (c) 2016 by fengweimin.
:date: 16/6/11
"""
| """
__init__.py
~~~~~~~~~~~~~~
Test package definition.
:copyright: (c) 2016 by fengweimin.
:date: 16/6/11
""" |
'''
Design Amazon / Flipkart (an online shopping platform)
Beyond the basic functionality (signup, login etc.), interviewers will be
looking for the following:
Discoverability:
How will the buyer discover a product?
How will the search surface results?
Cart & Checkout: Users expect the cart and checkou... | """
Design Amazon / Flipkart (an online shopping platform)
Beyond the basic functionality (signup, login etc.), interviewers will be
looking for the following:
Discoverability:
How will the buyer discover a product?
How will the search surface results?
Cart & Checkout: Users expect the cart and checkou... |
def list_open_ports():
pass
| def list_open_ports():
pass |
def swap_case(s):
str1 = ""
for i in range(len(s)):
if s[i].isupper():
str1 = str1+s[i].lower()
elif s[i].islower():
str1 = str1+s[i].upper()
else:
str1 = str1+s[i]
return str1
if __name__ == '__main__':
s = input()
result = ... | def swap_case(s):
str1 = ''
for i in range(len(s)):
if s[i].isupper():
str1 = str1 + s[i].lower()
elif s[i].islower():
str1 = str1 + s[i].upper()
else:
str1 = str1 + s[i]
return str1
if __name__ == '__main__':
s = input()
result = swap_case... |
# SPDX-FileCopyrightText: 2020 2019-2020 SAP SE
#
# SPDX-License-Identifier: Apache-2.0
API_FIELD_CLIENT_ID = 'clientId'
API_FIELD_CLIENT_LIMIT = 'limit'
API_FIELD_CLIENT_NAME = 'clientName'
API_FIELD_DOCUMENT_TYPE = 'documentType'
API_FIELD_ENRICHMENT = 'enrichment'
API_FIELD_EXTRACTED_HEADER_FIELDS = 'headerFields'
... | api_field_client_id = 'clientId'
api_field_client_limit = 'limit'
api_field_client_name = 'clientName'
api_field_document_type = 'documentType'
api_field_enrichment = 'enrichment'
api_field_extracted_header_fields = 'headerFields'
api_field_extracted_line_item_fields = 'lineItemFields'
api_field_extracted_values = 'ext... |
"""File with cops"""
class Cop:
cop_conf = dict()
DEFAULT_CONFIG = {
'enabled': True
}
def processable(self):
return self.cop_conf.get('enabled', True)
class ICop:
cop_conf = dict()
@classmethod
def name(self):
"""The Cop name"""
class ITokenCop(ICop):
de... | """File with cops"""
class Cop:
cop_conf = dict()
default_config = {'enabled': True}
def processable(self):
return self.cop_conf.get('enabled', True)
class Icop:
cop_conf = dict()
@classmethod
def name(self):
"""The Cop name"""
class Itokencop(ICop):
def process_tokens(... |
def selection_sort(arr):
comparisons = 1
for i in range(len(arr)):
comparisons += 1
min_idx = i
comparisons += 1
for j in range(i + 1, len(arr)):
comparisons += 2
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_... | def selection_sort(arr):
comparisons = 1
for i in range(len(arr)):
comparisons += 1
min_idx = i
comparisons += 1
for j in range(i + 1, len(arr)):
comparisons += 2
if arr[min_idx] > arr[j]:
min_idx = j
(arr[i], arr[min_idx]) = (arr[m... |
# fail-if: '-x' not in EXTRA_JIT_ARGS
def dec(f):
return f
@dec
def f():
pass
| def dec(f):
return f
@dec
def f():
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/)
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_de... | def my_decorator(func):
def wrapper():
print('Something is happening before the function is called.')
func()
print('Something is happening after the function is called.')
return wrapper
@my_decorator
def say_whee():
print('Whee!')
say_whee() |
class Scene:
def __init__(self):
"""
A scene has multiple SceneObject
"""
self.objects = []
class SceneObject:
def __init__(self, pos, color):
"""
Object that belongs to a scene
Args:
pos(ndarray): Position in 3D space
color(ndarr... | class Scene:
def __init__(self):
"""
A scene has multiple SceneObject
"""
self.objects = []
class Sceneobject:
def __init__(self, pos, color):
"""
Object that belongs to a scene
Args:
pos(ndarray): Position in 3D space
color(ndar... |
def register_init(func):
pass
def register_config(func):
pass
def register_read(func):
pass
def register_write(func):
pass
def info(msg):
print(msg)
| def register_init(func):
pass
def register_config(func):
pass
def register_read(func):
pass
def register_write(func):
pass
def info(msg):
print(msg) |
class Solution:
def solve(self, words):
minimum = sorted(words, key = len)[0]
LCP = ''
for i in range(len(minimum)):
matches = True
curChar = minimum[i]
for j in range(len(words)):
if words[j][i] != curChar:
matches ... | class Solution:
def solve(self, words):
minimum = sorted(words, key=len)[0]
lcp = ''
for i in range(len(minimum)):
matches = True
cur_char = minimum[i]
for j in range(len(words)):
if words[j][i] != curChar:
matches = Fa... |
# -*- coding: utf-8 -*-
operation = input()
total = 0
for i in range(144):
N = float(input())
line = (i // 12) + 1
if (i < (line * 12 - line)):
total += N
answer = total if (operation == 'S') else (total / 66)
print("%.1f" % answer) | operation = input()
total = 0
for i in range(144):
n = float(input())
line = i // 12 + 1
if i < line * 12 - line:
total += N
answer = total if operation == 'S' else total / 66
print('%.1f' % answer) |
# -*- coding: utf-8 -*-
'''
File name: code\onechild_numbers\sol_413.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #413 :: One-child Numbers
#
# For more information see:
# https://projecteuler.net/problem=413
# Problem Statement
'''
... | """
File name: code\\onechild_numbers\\sol_413.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
"""
'\nWe say that a d-digit positive number (no leading zeros) is a one-child number if exactly one of its sub-strings is divisible by d.\n\nFor example, 5671 is a 4-digit one-child num... |
# A DP program to solve edit distance problem
def editDistDP(x, y):
m = len(x);
n = len(y);
# Create an e-table to store results of subproblems
e = [[0 for j in range(n + 1)] for i in range(m + 1)]
# Fill in e[][] in bottom up manner
for i in range(m + 1):
for j in range(n + 1)... | def edit_dist_dp(x, y):
m = len(x)
n = len(y)
e = [[0 for j in range(n + 1)] for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
e[i][j] = j
elif j == 0:
e[i][j] = i
elif x[i - 1] == y[j - 1]:
... |
"""
Solver functions for Sudoku
"""
def print_sudoku(sudoku):
for i in range(len(sudoku)):
line = ""
if i == 3 or i == 6:
print("---------------------")
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += "| "
line += str(sudoku[... | """
Solver functions for Sudoku
"""
def print_sudoku(sudoku):
for i in range(len(sudoku)):
line = ''
if i == 3 or i == 6:
print('---------------------')
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += '| '
line += str(sudoku[... |
def sum(matriz):
sumValue = 0;
if len(matriz) > 0 and matriz[-1] <= 1000:
for item in matriz:
sumValue += item
return sumValue
print(sum([1, 2, 3]));
| def sum(matriz):
sum_value = 0
if len(matriz) > 0 and matriz[-1] <= 1000:
for item in matriz:
sum_value += item
return sumValue
print(sum([1, 2, 3])) |
# https://www.acmicpc.net/problem/11091
input = __import__('sys').stdin.readline
N = int(input())
for _ in range(N):
chars = [0 for _ in range(26)]
line = input().rstrip()
for char in line:
if 97 <= ord(char) < 123:
chars[ord(char) - 97] += 1
elif 65 <= ord(char) < 91:
... | input = __import__('sys').stdin.readline
n = int(input())
for _ in range(N):
chars = [0 for _ in range(26)]
line = input().rstrip()
for char in line:
if 97 <= ord(char) < 123:
chars[ord(char) - 97] += 1
elif 65 <= ord(char) < 91:
chars[ord(char) - 65] += 1
missing... |
def http(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_respon... | def http(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_respon... |
attendees = ["Ken", "Alena", "Treasure"]
attendees.append("Ashley")
attendees.extend(["James", "Guil"])
optional_attendees = ["Ben J.", "Dave"]
potential_attendees = attendees + optional_attendees
print("There are", len(potential_attendees), "attendees currently")
| attendees = ['Ken', 'Alena', 'Treasure']
attendees.append('Ashley')
attendees.extend(['James', 'Guil'])
optional_attendees = ['Ben J.', 'Dave']
potential_attendees = attendees + optional_attendees
print('There are', len(potential_attendees), 'attendees currently') |
## https://leetcode.com/problems/dota2-senate/
## go through the rounds of voting, where a vote is to ban another
## senator or, if all senators of the other party are banned, delcare
## victory.
## the optimal play for each senator is to ban the first member of
## the opposition party after them. fastest way to ha... | class Solution:
def predict_party_victory(self, senate: str) -> str:
bans_to_proc = 0
values = {'D': 1, 'R': -1}
while len(set(senate)) > 1:
next_senate = ''
for (ii, char) in enumerate(senate):
if bans_to_proc == 0:
next_senate +=... |
# init exercise 2 solution
# Using an approach similar to what was used in the Iris example
# we can identify appropriate boundaries for our meshgrid by
# referencing the actual wine data
x_1_wine = X_wine_train[predictors[0]]
x_2_wine = X_wine_train[predictors[1]]
x_1_min_wine, x_1_max_wine = x_1_wine.min() - 0.2, ... | x_1_wine = X_wine_train[predictors[0]]
x_2_wine = X_wine_train[predictors[1]]
(x_1_min_wine, x_1_max_wine) = (x_1_wine.min() - 0.2, x_1_wine.max() + 0.2)
(x_2_min_wine, x_2_max_wine) = (x_2_wine.min() - 0.2, x_2_wine.max() + 0.2)
(xx_1_wine, xx_2_wine) = np.meshgrid(np.arange(x_1_min_wine, x_1_max_wine, 0.003), np.aran... |
# addinterest1.py
def addInterest(balance, rate):
newBalance = balance * (1+rate)
balance = newBalance
def test():
amount = 1000
rate = 0.05
addInterest(amount, rate)
print(amount)
test()
| def add_interest(balance, rate):
new_balance = balance * (1 + rate)
balance = newBalance
def test():
amount = 1000
rate = 0.05
add_interest(amount, rate)
print(amount)
test() |
print ("How many students' test scores do you want to arrange?")
a = input()
if a == "2":
print ("Enter first student's name")
name1 = input()
print ("Enter his/her score")
score1 = input()
print ("Enter second student's name")
name2 = input()
print ("Enter his/her score")
scor... | print("How many students' test scores do you want to arrange?")
a = input()
if a == '2':
print("Enter first student's name")
name1 = input()
print('Enter his/her score')
score1 = input()
print("Enter second student's name")
name2 = input()
print('Enter his/her score')
score2 = input()
... |
def murmur3_32(data, seed=0):
"""MurmurHash3 was written by Austin Appleby, and is placed in the
public domain. The author hereby disclaims copyright to this source
code."""
c1 = 0xCC9E2D51
c2 = 0x1B873593
length = len(data)
h1 = seed
roundedEnd = length & 0xFFFFFFFC # round down to 4... | def murmur3_32(data, seed=0):
"""MurmurHash3 was written by Austin Appleby, and is placed in the
public domain. The author hereby disclaims copyright to this source
code."""
c1 = 3432918353
c2 = 461845907
length = len(data)
h1 = seed
rounded_end = length & 4294967292
for i in range(0... |
# .-. . .-. .-. . . .-. .-.
# `-. | | | | | | `-. |
# `-' `--`-' `-' `-' `-' '
__title__ = 'slocust'
__version__ = '0.18.5.17.1'
__description__ = 'Generate serveral Locust nodes on single server.'
__license__ = 'MIT'
__url__ = 'http://ityoung.gitee.io'
__author__ = 'Shin Yeung'
__author_email__ = 'ityoung@foxma... | __title__ = 'slocust'
__version__ = '0.18.5.17.1'
__description__ = 'Generate serveral Locust nodes on single server.'
__license__ = 'MIT'
__url__ = 'http://ityoung.gitee.io'
__author__ = 'Shin Yeung'
__author_email__ = 'ityoung@foxmail.com'
__copyright__ = 'Copyright 2018 Shin Yeung' |
def add(x, y):
return x+y
def product(z, y):
return z*y
| def add(x, y):
return x + y
def product(z, y):
return z * y |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
B.sort()
S = 0
for I in range(N... | """
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
A.sort()
B.sort()
s = 0
for i in range(N):
s += min(A[I], B[I])
print(S) |
# Project Euler Problem 21
# Created on: 2012-06-18
# Created by: William McDonald
# Returns a list of all primes under n using a sieve technique
def primes(n):
# 0 prime, 1 not.
primeSieve = ['0'] * (n / 2 - 1)
primeList = [2]
for i in range(3, n, 2):
if primeSieve[(i - 3) / 2] == '0... | def primes(n):
prime_sieve = ['0'] * (n / 2 - 1)
prime_list = [2]
for i in range(3, n, 2):
if primeSieve[(i - 3) / 2] == '0':
primeList.append(i)
for j in range((i - 3) / 2 + i, len(primeSieve), i):
primeSieve[j] = '1'
return primeList
def prime_d(n):
... |
#
# PySNMP MIB module ALTEON-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTEON-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:21:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (ip_cur_cfg_gw_index, altswitch_traps, slb_cur_cfg_virt_service_real_port, flt_cur_cfg_port_indx, slb_cur_cfg_real_server_ip_addr, slb_cur_cfg_real_server_index, flt_cur_cfg_indx, ip_cur_cfg_gw_addr, slb_cur_cfg_real_server_name) = mibBuilder.importSymbols('ALTEON-PRIVATE-MIBS', 'ipCurCfgGwIndex', 'altswitchTraps', 'sl... |
#!/usr/bin/env python -*- coding: utf-8 -*-
def per_section(it):
""" Read a file and yield sections using empty line as delimiter """
section = []
for line in it:
if line.strip():
section.append(line)
else:
yield ''.join(section)
section = []
# yield any remaining lines as a section t... | def per_section(it):
""" Read a file and yield sections using empty line as delimiter """
section = []
for line in it:
if line.strip():
section.append(line)
else:
yield ''.join(section)
section = []
if section:
yield ''.join(section) |
class InfluxDBClientError(Exception):
"""Raised when an error occurs in the request."""
def __init__(self, content, code=None):
"""Initialize the InfluxDBClientError handler."""
if isinstance(content, type(b'')):
content = content.decode('UTF-8', 'replace')
if code is not N... | class Influxdbclienterror(Exception):
"""Raised when an error occurs in the request."""
def __init__(self, content, code=None):
"""Initialize the InfluxDBClientError handler."""
if isinstance(content, type(b'')):
content = content.decode('UTF-8', 'replace')
if code is not No... |
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
d = defaultdict(set)
for a in allowed:
d[a[:2]].add(a[2])
return self._dfs(bottom, d, 0, "")
def _dfs(self, bottom, d, p, nxt):
if len(bottom) == 1:
return True
... | class Solution:
def pyramid_transition(self, bottom: str, allowed: List[str]) -> bool:
d = defaultdict(set)
for a in allowed:
d[a[:2]].add(a[2])
return self._dfs(bottom, d, 0, '')
def _dfs(self, bottom, d, p, nxt):
if len(bottom) == 1:
return True
... |
for i in range(10):
print(i)
print("YY")
| for i in range(10):
print(i)
print('YY') |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
# Copyright 2019 Google LLC
#
# 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, s... | """Create configuration to deploy GKE cluster."""
def generate_config(context):
"""Generate YAML resource configuration."""
name_prefix = context.env['deployment'] + '-' + context.env['name']
cluster_name = name_prefix
regular_type_name = name_prefix + '-type'
service_type_name = name_prefix + '-se... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/86563872
# https://blog.csdn.net/danspace1/article/details/88737508
# IDEA :
# TOTAL MOVES = abs(coins left need) + abs(coins right need)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
... | class Solution(object):
def distribute_coins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
def dfs(root):
if not root:
return 0
left = dfs(root.left)
right = dfs(root.right)
self.an... |
#
# PySNMP MIB module UX25-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UX25-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:30:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
"""
Device Message Queue defined in Thorlabs Kinesis v1.14.10
The device message queue allows the internal events raised by the device to be
monitored by the DLLs owner.
The device raises many different events, usually associated with a change of state.
These messages are temporarily stored in the DLL and can be a... | """
Device Message Queue defined in Thorlabs Kinesis v1.14.10
The device message queue allows the internal events raised by the device to be
monitored by the DLLs owner.
The device raises many different events, usually associated with a change of state.
These messages are temporarily stored in the DLL and can be a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.