content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
with open('src/base.rs', 'r') as f:
code = f.read()
for size in ['8', '16', '32', '64', 'size', '128']:
utype = 'u%s' % size
itype = 'i%s' % size
with open(f'src/{utype}_func.rs','w') as f:
f.write(code.replace('u8', utype))
with open(f'src/{itype}_func.rs','w') as f:
f.write(code.r... | with open('src/base.rs', 'r') as f:
code = f.read()
for size in ['8', '16', '32', '64', 'size', '128']:
utype = 'u%s' % size
itype = 'i%s' % size
with open(f'src/{utype}_func.rs', 'w') as f:
f.write(code.replace('u8', utype))
with open(f'src/{itype}_func.rs', 'w') as f:
f.write(code.... |
# In fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "",
# the number 0, and the value None. And of course the value False evaluates to False.
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
# One more value, or object in this case, evaluates to Fal... | bool(False)
bool(None)
bool(0)
bool('')
bool(())
bool([])
bool({})
class Myclass:
def __len__(self):
return 0
my_obj = my_class()
print(bool(myObj)) |
#
# PySNMP MIB module IRM-OIDS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IRM-OIDS
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 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... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
# Write a program to display "Hello" if a number entered by user is a multiple of five ,
# otherwise print "Bye".
print("Program displayed - 'Hello' If user Entered Number multiple of 5 Other-wise displayed bye")
num = int(input("Enter the Number : "))
if(num%5==0):
print("Hello")
else:
print("Bye")
# For ... | print("Program displayed - 'Hello' If user Entered Number multiple of 5 Other-wise displayed bye")
num = int(input('Enter the Number : '))
if num % 5 == 0:
print('Hello')
else:
print('Bye')
input('Press Enter to close program') |
# adaptive thresholding method
def adaptive_thresholding(img):
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
adaptive_threshed = cv2.adaptiveThreshold(img_grey, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 1)
cv2.imshow("adaptive", adaptive_threshed)
return adaptive_threshed
# Nor... | def adaptive_thresholding(img):
img_grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
adaptive_threshed = cv2.adaptiveThreshold(img_grey, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 1)
cv2.imshow('adaptive', adaptive_threshed)
return adaptive_threshed
def normalize(img):
normalize_im... |
"""Constants for broadlink platform."""
CONF_PACKET = 'packet'
DOMAIN = 'broadlink'
SERVICE_LEARN = 'learn'
SERVICE_SEND = 'send'
| """Constants for broadlink platform."""
conf_packet = 'packet'
domain = 'broadlink'
service_learn = 'learn'
service_send = 'send' |
n = (3, 6, 3)
transformers = [
lambda _: _.transpose(),
lambda _: _.rename_axis(
mapper='variable',
axis='index',
),
lambda _: _.rename_axis(
mapper='id',
axis='columns',
),
]
| n = (3, 6, 3)
transformers = [lambda _: _.transpose(), lambda _: _.rename_axis(mapper='variable', axis='index'), lambda _: _.rename_axis(mapper='id', axis='columns')] |
#!/usr/bin/python3
__doc__ = '''
abcdefg
'''
| __doc__ = '\n abcdefg\n' |
## Part 1: Standalone Functions
### Mean
def mean(input_list):
return sum(input_list) / len(input_list)
# Provided test, you should add more.
numbers = [5, 10, 15]
m = mean(numbers)
print(m) # 10
### Median
def median(input_list):
n = len(input_list)
sorted_list = sorted(input_list)
# No elements,... | def mean(input_list):
return sum(input_list) / len(input_list)
numbers = [5, 10, 15]
m = mean(numbers)
print(m)
def median(input_list):
n = len(input_list)
sorted_list = sorted(input_list)
if n == 0:
return None
elif n % 2 == 0:
a = sorted_list[n // 2]
b = sorted_list[n // 2... |
# DP, recurrsive and memorization
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
mem = [[0 for _ in range(n)] for _ in range(m)]
for i in range(n):
mem[0][i] = 1
for j in range(m):
... | class Solution(object):
def unique_paths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
mem = [[0 for _ in range(n)] for _ in range(m)]
for i in range(n):
mem[0][i] = 1
for j in range(m):
mem[j][0] = 1
def ... |
# 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 u... | """Constants."""
glove_npz_sha1 = {'glove.42B.300d': ('glove.42B.300d.npz', '7deee8f4860744db53ed9e50892effe9883e6d89'), 'glove.6B.100d': ('glove.6B.100d.npz', '01f80f202fcabcc3e0804898349087bfc191dd1c'), 'glove.6B.200d': ('glove.6B.200d.npz', '5e6e2bdab346c257f88d80d215d518e680d86e32'), 'glove.6B.300d': ('glove.6B.300... |
class Image:
"""
A representation of graphical content.
:param path: Path to the image. Allowed values can be local file
(relative or absolute path) or URL (HTTP or HTTPS). Relative paths
will be interpreted relative to the application module directory.
"""
def __init__(self, path):... | class Image:
"""
A representation of graphical content.
:param path: Path to the image. Allowed values can be local file
(relative or absolute path) or URL (HTTP or HTTPS). Relative paths
will be interpreted relative to the application module directory.
"""
def __init__(self, path)... |
# VS Code Python Tutorial
# https://code.visualstudio.com/docs/python/python-tutorial
msg = "Hello World"
print(msg)
| msg = 'Hello World'
print(msg) |
# -*- coding: utf-8 -*-
# This file is part of Shuup Admin Channel
#
# Copyright (c) 2019, Christian Hess. All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#: Set the channel layer to use when sending messages
#: Keep Non... | shuup_admin_channel_layer = None
shuup_admin_channel_order_received_enabled = True
shuup_admin_channel_settings_provider = 'shuup_admin_channel.resources:DefaultSettingsProvider' |
# this is a base class
class WindSensor(object):
def __init__(self):
return
def read(self):
return 0
| class Windsensor(object):
def __init__(self):
return
def read(self):
return 0 |
def euc_2d(n1, n2):
"""
The euclidean distance for 2D cartesian nodes
:param n1: first node
:type n1: Node
:param n2: second node
:type n2: Node
:return: the euclidean distance between first node and second node in 2D space
:rtype: float
"""
return ((n1.x - n2.x)**2 + (n1.y - n2... | def euc_2d(n1, n2):
"""
The euclidean distance for 2D cartesian nodes
:param n1: first node
:type n1: Node
:param n2: second node
:type n2: Node
:return: the euclidean distance between first node and second node in 2D space
:rtype: float
"""
return ((n1.x - n2.x) ** 2 + (n1.y - ... |
"""
This is my sixth prime number project,
it is the fastest function I have created untill now,
and it is also very optimised that can find lots of
prime numbers in short period of time.
It will find all prime numbers between 2 and 'End'.
1. At first we create an Prime array of [2, 3]
2. Then until we reach the En... | """
This is my sixth prime number project,
it is the fastest function I have created untill now,
and it is also very optimised that can find lots of
prime numbers in short period of time.
It will find all prime numbers between 2 and 'End'.
1. At first we create an Prime array of [2, 3]
2. Then until we reach the End... |
def read_in():
data = []
while value := input():
level = 0
res = []
for s in value:
if s == '[':
level += 1
elif s == ']':
level -= 1
elif s != ',':
res.append((int(s), level))
data.append(res)
... | def read_in():
data = []
while (value := input()):
level = 0
res = []
for s in value:
if s == '[':
level += 1
elif s == ']':
level -= 1
elif s != ',':
res.append((int(s), level))
data.append(res)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Permute vector to minimize scalar product
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
def min_scalar_prod(x, y):
"""Permute vector to minimize scalar product
:param x:
:param y: x, y are vectors of same size
:returns: min sum x[i] * y[si... | """Permute vector to minimize scalar product
jill-jenn vie et christoph durr - 2014-2018
"""
def min_scalar_prod(x, y):
"""Permute vector to minimize scalar product
:param x:
:param y: x, y are vectors of same size
:returns: min sum x[i] * y[sigma[i]] over all permutations sigma
:complexity: O(n l... |
class Node(object):
def __init__(self, v):
self.next = None
self.v = v
class LinkedList(object):
def __init__(self):
self.root = None
self.n = 0
def put(self, v):
node = Node(v)
node.next = self.root
self.root = node
self.n += 1
def __l... | class Node(object):
def __init__(self, v):
self.next = None
self.v = v
class Linkedlist(object):
def __init__(self):
self.root = None
self.n = 0
def put(self, v):
node = node(v)
node.next = self.root
self.root = node
self.n += 1
def __... |
class Solution:
def XXX(self, head: ListNode) -> ListNode:
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
| class Solution:
def xxx(self, head: ListNode) -> ListNode:
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head |
# https://leetcode.com/problems/letter-case-permutation/
# By Jiapeng
# Runtime: 64 ms, faster than 61.44% of Python3 online submissions for Letter Case Permutation.
# Memory Usage: 14.4 MB, less than 50.53% of Python3 online submissions for Letter Case Permutation.
class Solution:
def letterCasePermutation(self,... | class Solution:
def letter_case_permutation(self, S: str) -> List[str]:
ans = []
if S:
self.dfs(0, S, ans, '', 0)
return ans
def dfs(self, d, S, ans, cur, starter):
if d == len(S):
ans.append(cur)
return
for i in range(starter, len(S)... |
file_path_pharma_class = '/home/kevinxin/drug/drugcentral/2018.6/pharma_class.csv'
#df_drugcentral_pharma_class = pd.read_csv(file_path_pharma_class, sep=",", names=['_id', 'struc_id', 'role', 'description', 'code', 'source'])
file_path_faers = '/home/kevinxin/drug/drugcentral/2018.6/faers.csv'
#df_drugcentral_faers =... | file_path_pharma_class = '/home/kevinxin/drug/drugcentral/2018.6/pharma_class.csv'
file_path_faers = '/home/kevinxin/drug/drugcentral/2018.6/faers.csv'
file_path_act = '/home/kevinxin/drug/drugcentral/2018.6/act_table_full.csv'
file_path_omop = '/home/kevinxin/drug/drugcentral/2018.6/omop_relationship.csv'
file_path_ap... |
#!/usr/bin/env python
class Cow(object):
pass
class Fox(object):
def get_noise(self):
return "Ring-ding-ding-ding-dingeringeding"
def ask(obj):
print('What goes "{}?"'.format(obj.get_noise()))
ask(Fox())
ask(Cow())
| class Cow(object):
pass
class Fox(object):
def get_noise(self):
return 'Ring-ding-ding-ding-dingeringeding'
def ask(obj):
print('What goes "{}?"'.format(obj.get_noise()))
ask(fox())
ask(cow()) |
class Tank:
"""My Aquarium.
Fish and shrimps can live in it.
The aquarium can be a freshwater or saltwater aquarium.
We can adjust PH and temperature up or down.
"""
def __init__(self, *, aquarium_type="freshwater", ph=7, temperature=30):
"""Initialize."""
self.aquarium_type =... | class Tank:
"""My Aquarium.
Fish and shrimps can live in it.
The aquarium can be a freshwater or saltwater aquarium.
We can adjust PH and temperature up or down.
"""
def __init__(self, *, aquarium_type='freshwater', ph=7, temperature=30):
"""Initialize."""
self.aquarium_type =... |
# Find minimum swaps to satisfy a[i]%3 = i%3 property in a a given array
a = [0, 1, 3, 2, 1]
a_i = []
diff = 0 # difference in a,a_i values
n = len(a)
# hashmaps containing mod 3 values and indices 0(n)
index_hm, value_hm = dict(), dict()
for i in range(0, n):
# modded value hashmap
try:
value_hm[a[i] ... | a = [0, 1, 3, 2, 1]
a_i = []
diff = 0
n = len(a)
(index_hm, value_hm) = (dict(), dict())
for i in range(0, n):
try:
value_hm[a[i] % 3] += 1
except:
value_hm[a[i] % 3] = 1
a[i] %= 3
try:
index_hm[i % 3] += 1
except:
index_hm[i % 3] = 1
a_i.append(i % 3)
if a[i]... |
########################
## GENERAL PARAMETERS ##
########################
DATA_PATH = "data/"
DATA_SETTINGS = "data_settings.py"
DATA_EXT = ".shelf"
MODEL_PATH = "models/"
MODEL_SETTINGS = "model_settings.py"
MODEL_SETTINGS_LOADER = "model_settings_loader.py"
SIMULATION_SETTINGS = "simulation_settings.py"
RESULTS_... | data_path = 'data/'
data_settings = 'data_settings.py'
data_ext = '.shelf'
model_path = 'models/'
model_settings = 'model_settings.py'
model_settings_loader = 'model_settings_loader.py'
simulation_settings = 'simulation_settings.py'
results_path = 'results/'
results_ext = '.shelf' |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class Policy(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is ... | class Policy(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'policyScope... |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LnkdList:
def __init__(self):
self.head = None
l1 = LnkdList()
l1.head = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
l1.head.next = e2
# Link second Node to third node
e2.next ... | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Lnkdlist:
def __init__(self):
self.head = None
l1 = lnkd_list()
l1.head = node('Mon')
e2 = node('Tue')
e3 = node('Wed')
l1.head.next = e2
e2.next = e3 |
class Credentials:
"""
Class that creates new instance for credentials
"""
credentials_list=[]#an empty credentials list
def __init__(self,account,username,password):
"""
new application and credentials are being generated
"""
self.account=account
se... | class Credentials:
"""
Class that creates new instance for credentials
"""
credentials_list = []
def __init__(self, account, username, password):
"""
new application and credentials are being generated
"""
self.account = account
self.username = username
... |
# from resources.session import UserInfo
def router(api) -> None:
# api.add_resource(UserInfo, "/userinfo")
pass
| def router(api) -> None:
pass |
#Load the data
DATA_DIR = "ml-25/"
rating = pd.read_csv(DATA_DIR + "ratings.csv")
nb_entries = rating.shape[0]
print("Number of entries : %d " %nb_entries)
#Load the movies files in order to create the id_to_title dictionary and complete the rating dataframe
movies = pd.read_csv(DATA_DIR + "movies.csv")
id_to_title = ... | data_dir = 'ml-25/'
rating = pd.read_csv(DATA_DIR + 'ratings.csv')
nb_entries = rating.shape[0]
print('Number of entries : %d ' % nb_entries)
movies = pd.read_csv(DATA_DIR + 'movies.csv')
id_to_title = dict(movies[['movieId', 'title']].values)
rating['movie'] = [id_to_title[x] for x in rating['movieId'].values]
rating.... |
# -*- coding: utf-8 -*-
BOT_NAME = 'scouter'
SPIDER_MODULES = ['scouter.spiders']
NEWSPIDER_MODULE = 'scouter.spiders'
ROBOTSTXT_OBEY = False
CONCURRENT_REQUESTS = 16
DOWNLOAD_DELAY = 2
RANDOMIZE_DOWNLOAD_DELAY = True
COOKIES_ENABLED = False
MONGO_URI = 'mongodb://scouter:1A2B3C4D_@127.0.0.1:27017'
MONGO_DATABASE... | bot_name = 'scouter'
spider_modules = ['scouter.spiders']
newspider_module = 'scouter.spiders'
robotstxt_obey = False
concurrent_requests = 16
download_delay = 2
randomize_download_delay = True
cookies_enabled = False
mongo_uri = 'mongodb://scouter:1A2B3C4D_@127.0.0.1:27017'
mongo_database = 'scouter'
downloader_middle... |
# Interface which returns final rel scores after aggregation of different module scores
class Aggregator:
"""
Basic Interface for Aggregators of different relation linking module scores
"""
def __init__(self):
pass
def aggregate(self, scores_dict, params=None):
"""
Takes in ... | class Aggregator:
"""
Basic Interface for Aggregators of different relation linking module scores
"""
def __init__(self):
pass
def aggregate(self, scores_dict, params=None):
"""
Takes in scores_dict (dict of dicts) corresponding to different modules
and returns a si... |
class FileMetadataError(Exception):
"""Base file metadata driver exception."""
class FileMetadataDriverError(FileMetadataError):
"""Exception raised when a driver encounters an unexpected error."""
| class Filemetadataerror(Exception):
"""Base file metadata driver exception."""
class Filemetadatadrivererror(FileMetadataError):
"""Exception raised when a driver encounters an unexpected error.""" |
#
# PySNMP MIB module IPSEC-SPD-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/IPSEC-SPD-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:18:27 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
# Query to get water leak calls and daily precipitation
query = """
SELECT hpd311calls.*, weather.prcp
FROM hpd311calls
JOIN weather
ON hpd311calls.created_date = weather.date
WHERE hpd311calls.complaint_type = 'WATER LEAK';
"""
# Load query results into the leak_calls data frame
leak_calls = pd.read_sql(que... | query = "\nSELECT hpd311calls.*, weather.prcp\n FROM hpd311calls\n JOIN weather\n ON hpd311calls.created_date = weather.date\n WHERE hpd311calls.complaint_type = 'WATER LEAK';\n"
leak_calls = pd.read_sql(query, engine)
print(leak_calls.head())
"\n<script.py> output:\n unique_key created_date agency complaint... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def cats(number=100):
return "\U0001F431 " * number
def green_circle(number=1):
return "\U0001F7E2 " * number
def blue_circle(number=1):
return "\U0001F535 " * number
def red_circle(number=1):
return "\U0001F534 " * number
def yellow_circle(number=1):
... | def cats(number=100):
return '🐱 ' * number
def green_circle(number=1):
return '🟢 ' * number
def blue_circle(number=1):
return '🔵 ' * number
def red_circle(number=1):
return '🔴 ' * number
def yellow_circle(number=1):
return '🟡 ' * number
def graph(number=1):
return '📈 ' * number
def b... |
class Solution(object):
def subsets(self, nums):
res = []
def children(j, tmp):
res.append(tmp)
for i in range(j, len(nums)):
children(i + 1, tmp + [nums[i]])
children(0, [])
return res
class Solution:
def subsets(self, nums: [int]) -> [[i... | class Solution(object):
def subsets(self, nums):
res = []
def children(j, tmp):
res.append(tmp)
for i in range(j, len(nums)):
children(i + 1, tmp + [nums[i]])
children(0, [])
return res
class Solution:
def subsets(self, nums: [int]) -> ... |
# Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
celsius = float(input('Enter celsius temperature: '));
fahrenheit = (celsius * 9/5) + 32;
print('Fahrenheit:',fahrenheit); | celsius = float(input('Enter celsius temperature: '))
fahrenheit = celsius * 9 / 5 + 32
print('Fahrenheit:', fahrenheit) |
# -*- coding: utf-8 -*-
X = int(input())
Y = int(input())
start, end = min(X, Y), max(X, Y)
for i in range(start + 1, end):
if ((i % 5) in [2, 3]):
print(i) | x = int(input())
y = int(input())
(start, end) = (min(X, Y), max(X, Y))
for i in range(start + 1, end):
if i % 5 in [2, 3]:
print(i) |
keys = {
'MONGO_DBNAME' : 'your_database_name',
'MONGO_URI' : 'your_mongo_uri_name'
}
| keys = {'MONGO_DBNAME': 'your_database_name', 'MONGO_URI': 'your_mongo_uri_name'} |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'System and method are not included'},
{'abbr': 1, 'code': 1, 'title': 'System and method are included'},
{'abbr': 2,
'code': 2,
'title': 'System, method, reference date, climate date (from) and climate '
... | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'System and method are not included'}, {'abbr': 1, 'code': 1, 'title': 'System and method are included'}, {'abbr': 2, 'code': 2, 'title': 'System, method, reference date, climate date (from) and climate date (to) are included'}, {'abbr': 3, 'code': 3, 'title': 'A... |
def get_alignment(pairs, s1, s2):
if len(pairs) == 0: return s1, s2
m, n = len(s1), len(s2)
c1, c2 = [], []
ipairs, jpairs = zip(*sorted(pairs))
i,j = 1,1
while i <= m or j <= n:
iIsNotGap = j in jpairs or j > n
jIsNotGap = i in ipairs or i > m
if not(iIsNotGap or jIs... | def get_alignment(pairs, s1, s2):
if len(pairs) == 0:
return (s1, s2)
(m, n) = (len(s1), len(s2))
(c1, c2) = ([], [])
(ipairs, jpairs) = zip(*sorted(pairs))
(i, j) = (1, 1)
while i <= m or j <= n:
i_is_not_gap = j in jpairs or j > n
j_is_not_gap = i in ipairs or i > m
... |
def isPalindrome(string):
i, j = 0, len(string) - 1
while i < j:
if string[i] != string[j]:
return False
i += 1
j -= 1
return True
| def is_palindrome(string):
(i, j) = (0, len(string) - 1)
while i < j:
if string[i] != string[j]:
return False
i += 1
j -= 1
return True |
class Solution:
"""
@param nums: an integer array
@return: the maximum product
"""
def maximumProduct(self, nums):
# Write your code here
nums=sorted(nums)
a = nums[-1]*nums[-2]*nums[-3]
b = nums[0]*nums[1]*nums[-1]
if a>b:
return a
else:
... | class Solution:
"""
@param nums: an integer array
@return: the maximum product
"""
def maximum_product(self, nums):
nums = sorted(nums)
a = nums[-1] * nums[-2] * nums[-3]
b = nums[0] * nums[1] * nums[-1]
if a > b:
return a
else:
return... |
TORTOISE_ORM = {
"connections": {"default": "postgres://blog:blog@localhost:5432/blog"},
"apps": {
"models": {
"models": ["src.app.user.models", "aerich.models"],
"default_connection": "default",
},
},
}
| tortoise_orm = {'connections': {'default': 'postgres://blog:blog@localhost:5432/blog'}, 'apps': {'models': {'models': ['src.app.user.models', 'aerich.models'], 'default_connection': 'default'}}} |
class BaseView:
def prepare_image(self): raise NotImplementedError
def show_image(self): raise NotImplementedError
def show_centered_string(self, text, font, y = None): raise NotImplementedError
def show_welcome(self): raise NotImplementedError
| class Baseview:
def prepare_image(self):
raise NotImplementedError
def show_image(self):
raise NotImplementedError
def show_centered_string(self, text, font, y=None):
raise NotImplementedError
def show_welcome(self):
raise NotImplementedError |
class PIWebAsyncException(Exception):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class APIException(PIWebAsyncException):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class SerializationError(APIException):
def __init__(self, *args: ... | class Piwebasyncexception(Exception):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class Apiexception(PIWebAsyncException):
def __init__(self, *args: object) -> None:
super().__init__(*args)
class Serializationerror(APIException):
def __init__(self, *args: object) ... |
def index():
db.entidad.id.readable = False
create = editable = deletable = auth.has_membership('editor_economia')
grid = SQLFORM.grid(db.entidad, create=create, editable=editable, deletable=deletable)
return locals() | def index():
db.entidad.id.readable = False
create = editable = deletable = auth.has_membership('editor_economia')
grid = SQLFORM.grid(db.entidad, create=create, editable=editable, deletable=deletable)
return locals() |
class Note:
def __init__(self, name, note):
if type(name) is not str:
raise TypeError('Name must be a string')
if name is None:
raise TypeError('Name cannot be None')
if name == '':
raise ValueError('Name cannot be empty')
if type(note) is not floa... | class Note:
def __init__(self, name, note):
if type(name) is not str:
raise type_error('Name must be a string')
if name is None:
raise type_error('Name cannot be None')
if name == '':
raise value_error('Name cannot be empty')
if type(note) is not ... |
def main():
red = pygame.Rect(700,300,space_w,space_h)
yellow = pygame.Rect(100,300,space_w,space_h)
RED_bullets =[]
YELLOW_BULLETS = []
red_health = 20
yellow_health = 20
Clock = pygame.time.Clock()
run = True
while run:
Clock.tick(fps)
for event i... | def main():
red = pygame.Rect(700, 300, space_w, space_h)
yellow = pygame.Rect(100, 300, space_w, space_h)
red_bullets = []
yellow_bullets = []
red_health = 20
yellow_health = 20
clock = pygame.time.Clock()
run = True
while run:
Clock.tick(fps)
for event in pygame.eve... |
def iprint(text):
print ("INFO: " + str(text))
def dprint(desc, content):
print ("-" * 20 + desc + "-" * 20)
print (content)
print ("-" * 40) | def iprint(text):
print('INFO: ' + str(text))
def dprint(desc, content):
print('-' * 20 + desc + '-' * 20)
print(content)
print('-' * 40) |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['theme']
# Cell
def theme():
"""Niklas Morberg's personal theme for Altair"""
return {
"config": {
"axis": {
"labelFontSize": 12,
"labelColor": "#666",
... | __all__ = ['theme']
def theme():
"""Niklas Morberg's personal theme for Altair"""
return {'config': {'axis': {'labelFontSize': 12, 'labelColor': '#666', 'titleFontSize': 14, 'titleFontWeight': 'normal', 'titleColor': '#666'}, 'axisX': {'grid': False, 'gridWidth': 0.4}, 'axisY': {'gridDash': [3], 'gridWidth': 0... |
s3gis_tests = load_module("tests.unit_tests.modules.s3.s3gis")
def test_OpenStreetMap():
s3gis_tests.layer_test(
db,
db.gis_layer_openstreetmap,
dict(
enabled = True,
name = "test OSM layer",
url1 = "http://otile1.example.com/tiles/1.0.0/osm/",
... | s3gis_tests = load_module('tests.unit_tests.modules.s3.s3gis')
def test__open_street_map():
s3gis_tests.layer_test(db, db.gis_layer_openstreetmap, dict(enabled=True, name='test OSM layer', url1='http://otile1.example.com/tiles/1.0.0/osm/', url2='http://otile2.example.com/tiles/1.0.0/osm/', url3='http://otile3.exam... |
__author__ = 'felix.shaw@tgac.ac.uk - 29/07/2016'
class CopoRuntimeError(RuntimeError):
def __init__(self, message, errors=dict()):
# Call the base class constructor with the parameters it needs
super(CopoRuntimeError, self).__init__(message)
self.errors = errors
| __author__ = 'felix.shaw@tgac.ac.uk - 29/07/2016'
class Coporuntimeerror(RuntimeError):
def __init__(self, message, errors=dict()):
super(CopoRuntimeError, self).__init__(message)
self.errors = errors |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __about__.py
"""PyEMD metadata"""
__title__ = 'pyemd'
__version__ = '0.5.1'
__description__ = ("A Python wrapper for Ofir Pele and Michael Werman's "
"implementation of the Earth Mover's Distance.")
__author__ = 'Will Mayner'
__author_email__ = 'wmay... | """PyEMD metadata"""
__title__ = 'pyemd'
__version__ = '0.5.1'
__description__ = "A Python wrapper for Ofir Pele and Michael Werman's implementation of the Earth Mover's Distance."
__author__ = 'Will Mayner'
__author_email__ = 'wmayner@gmail.com'
__author_website__ = 'http://willmayner.com'
__license__ = 'MIT'
__copyri... |
#
# ktool | kswift
# demangle.py
#
#
#
# This file is part of ktool. ktool is free software that
# is made available under the MIT license. Consult the
# file "LICENSE" that is distributed together with this file
# for the exact licensing terms.
#
# Copyright (c) kat 2022.
#
def demangle(name):
... | def demangle(name):
"""
Very basic, very sloppy bare minimum POC for swift classname demangling
:param name:
:return:
"""
project = ''
typename = ''
stage = 0
skip = False
for c in name:
if c.isdigit():
if skip:
continue
else:
... |
class Solution(object):
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
if __name__ == "__main__":
s = Solution()
assert s.toLowerCase("Hello") == "hello"
assert s.toLowerCase("here") == "here"
assert s.toLowerCase("LOVELY")... | class Solution(object):
def to_lower_case(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
if __name__ == '__main__':
s = solution()
assert s.toLowerCase('Hello') == 'hello'
assert s.toLowerCase('here') == 'here'
assert s.toLowerCase('LOVELY'... |
"""
File: class_reviews.py
Name: DiCheng
-------------------------------
At the beginning of this program, the user is asked to input
the class name (either SC001 or SC101).
Attention: your program should be case-insensitive.
If the user input -1 for class name, your program would output
the maximum, minimum, and avera... | """
File: class_reviews.py
Name: DiCheng
-------------------------------
At the beginning of this program, the user is asked to input
the class name (either SC001 or SC101).
Attention: your program should be case-insensitive.
If the user input -1 for class name, your program would output
the maximum, minimum, and avera... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'npapi',
'type': 'none',
'direct_dependent_settings': {
'include_dirs': [
# Som... | {'targets': [{'target_name': 'npapi', 'type': 'none', 'direct_dependent_settings': {'include_dirs': ['.', 'bindings']}, 'sources': ['bindings/npapi.h', 'bindings/npapi_extensions.h', 'bindings/npruntime.h'], 'conditions': [['OS=="linux" or OS=="freebsd"', {'sources': ['bindings/npapi_x11.h']}]]}]} |
# encoding: utf-8
# module cv2.motempl
# from /home/davtoh/anaconda3/envs/rrtools/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so
# by generator 1.144
# no doc
# no imports
# Variables with simple values
__loader__ = None
__spec__ = None
# functions
# real signature unknown; restored from __doc__
... | __loader__ = None
__spec__ = None
def calc_global_orientation(orientation, mask, mhi, timestamp, duration):
""" calcGlobalOrientation(orientation, mask, mhi, timestamp, duration) -> retval """
pass
def calc_motion_gradient(mhi, delta1, delta2, mask=None, orientation=None, apertureSize=None):
""" calcMotio... |
hands = {'Aces', 'Kings', 'Queens', 'Jacks', 'Tens', 'Nines', 'Full House', 'Five of a Kind', 'Straight Flush', 'Royal Flush'}
# State
player_combos = dict() # dictionary of dictionaries: player => scores per combo
# setup the new game
while True:
name = input('Enter name of next player (or return if finished): ... | hands = {'Aces', 'Kings', 'Queens', 'Jacks', 'Tens', 'Nines', 'Full House', 'Five of a Kind', 'Straight Flush', 'Royal Flush'}
player_combos = dict()
while True:
name = input('Enter name of next player (or return if finished): ')
if not name:
break
player_combos[name] = {hand: False for hand in hand... |
"""
1339. Maximum Product of Splitted Binary Tree
Medium
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return ... | """
1339. Maximum Product of Splitted Binary Tree
Medium
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return ... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class NodeWrapperCustom(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and th... | class Nodewrappercustom(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'... |
class Solution:
# Loop and Divide (Accepted), O(log n) time, O(1) space
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
while n != 1:
n /= 3
if n != int(n):
return False
return True
# Two conditions (Top Voted), O(... | class Solution:
def is_power_of_three(self, n: int) -> bool:
if n < 1:
return False
while n != 1:
n /= 3
if n != int(n):
return False
return True
def is_power_of_three(self, n: int) -> bool:
return n > 0 == 3 ** 19 % n |
t = int(input())
for i in range(t):
s = list(map(str, input().rstrip()))
answer = ''
if s.count('x') >= 8:
answer = 'NO'
else:
answer = 'YES'
print('#{} {}'.format(i+1, answer))
| t = int(input())
for i in range(t):
s = list(map(str, input().rstrip()))
answer = ''
if s.count('x') >= 8:
answer = 'NO'
else:
answer = 'YES'
print('#{} {}'.format(i + 1, answer)) |
#!/usr/bin/env python3
def has_module(module):
try:
__import__(module)
return True
except ImportError:
pass
| def has_module(module):
try:
__import__(module)
return True
except ImportError:
pass |
def main():
lenght = int(input('Lenght: '))
array = [None] * lenght
for i in range(lenght):
array[i] = int(input('Item {}: '.format(i)))
print('Source array: ', array)
for i in range(lenght):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
... | def main():
lenght = int(input('Lenght: '))
array = [None] * lenght
for i in range(lenght):
array[i] = int(input('Item {}: '.format(i)))
print('Source array: ', array)
for i in range(lenght):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
array[... |
#Enter a number using custom input
a = int(input("Enter a nmber: "))
# if number is divisible by both 3 and 5 it returns fizzbuzz
if (a%5 == 0 and a%3 == 0):
print("FizzBuzz")
# if number is divisible by 3 it returns fizz
elif(a%3 == 0 ):
print("Fizz")
# if number is divisible by 5 it returns buzz
elif (a%5 ... | a = int(input('Enter a nmber: '))
if a % 5 == 0 and a % 3 == 0:
print('FizzBuzz')
elif a % 3 == 0:
print('Fizz')
elif a % 5 == 0:
print('Buzz')
else:
print(a) |
# Copyright 2020 BlueCat Networks. All rights reserved.
# Default Configuration ID
DEFAULT_CONFIG_NAME = 'Default'
# Default View ID
DEFAULT_VIEW_NAME = 'test1'
DEFAULT_VIEW_ID = 100910
| default_config_name = 'Default'
default_view_name = 'test1'
default_view_id = 100910 |
"""
The Program receives from the USER a MONTH and a DAY of the year
and returns (displaying it) the corresponding season, knowing that:
- March 20 -> first day of Spring
- June 21 -> first day of Summer
- September 22 -> first day of Fall (or Autumn)
- December 21 -> first day of Winter
"""
# START Definition of FUNC... | """
The Program receives from the USER a MONTH and a DAY of the year
and returns (displaying it) the corresponding season, knowing that:
- March 20 -> first day of Spring
- June 21 -> first day of Summer
- September 22 -> first day of Fall (or Autumn)
- December 21 -> first day of Winter
"""
def valida_month(stringInp... |
"""
You are given a list of integers List[] of size N.
Your task is find a position p(0<=p<=N-1) in the List[], such that the addition
of all integers to the left of p should be exactly equal to addition of all the
integers to the right of p.
If all the integers are at one end of p ,assume the sum of other end is 0.
If... | """
You are given a list of integers List[] of size N.
Your task is find a position p(0<=p<=N-1) in the List[], such that the addition
of all integers to the left of p should be exactly equal to addition of all the
integers to the right of p.
If all the integers are at one end of p ,assume the sum of other end is 0.
If... |
class BaseShoulderTap:
def __init__(self, payload, payloadId, imsi):
'''Creates a representation of a Shoulder-Tap.
Parameters
----------
payload : bytes
The payload contained by the shoulder-tap.
payloadId : int or str
The ID of the shoulder-tap, as p... | class Baseshouldertap:
def __init__(self, payload, payloadId, imsi):
"""Creates a representation of a Shoulder-Tap.
Parameters
----------
payload : bytes
The payload contained by the shoulder-tap.
payloadId : int or str
The ID of the shoulder-tap, as ... |
#!/usr/bin/python3
def main():
n = 42
s = 'This is a {} \nstring!'.format(n)
i = r'This is a {} \nstring!'.format(n) # Raw string
y = '''multiple line of strings
this is a string'''
print(s)
print(i)
print(y)
if __name__ == "__main__" : main() | def main():
n = 42
s = 'This is a {} \nstring!'.format(n)
i = 'This is a {} \\nstring!'.format(n)
y = 'multiple line of strings\nthis is a string'
print(s)
print(i)
print(y)
if __name__ == '__main__':
main() |
class Employee:
"""Common base class for all employees"""
empCount =0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
... | class Employee:
"""Common base class for all employees"""
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def display_count(self):
print('Total Employee %d' % Employee.empCount)
def display_employee(self)... |
#
# class CSS(object):
# """
# This class helps with some html css parameters.
# """
# @staticmethod
# def basic():
# """
# Returns a simple css.
# """
# basic = """
# body {
# background-color: white;
# }
#
# h1 {
# color: black;
# text-align: center;
# }
#
# p {
# font-family: verd... | class Cssstripedtable(object):
@staticmethod
def get(self, color='#dddddd'):
"""
A simple table css that alternates the color of every other row by
a use defined color (the default is gray).
"""
css = '\n\t\ttable {\n\t\t\tfont-family: arial, sans-serif;\n\t\t\tborder-collapse: collapse;\... |
# this is our descriptor object
class Bar():
def __init__(self):
self.value = 'casa'
def __get__(self):
print ("returned from descriptor object")
return self.value
def __set__(self, value):
print ("set in descriptor object")
self.value = value
def __delete... | class Bar:
def __init__(self):
self.value = 'casa'
def __get__(self):
print('returned from descriptor object')
return self.value
def __set__(self, value):
print('set in descriptor object')
self.value = value
def __delete__(self):
print('deleted in desc... |
"""
LeetCode Problem: 10. Regular Expression Matching
Link: https://leetcode.com/problems/regular-expression-matching/
Language: Python
Written by: Mostofa Adib Shakib
"""
# Time Complexity: O(m*n)
# Space Complexity: O(m*n)
# m = length of the pattern string
# n = length of the text string
class Solution:
def is... | """
LeetCode Problem: 10. Regular Expression Matching
Link: https://leetcode.com/problems/regular-expression-matching/
Language: Python
Written by: Mostofa Adib Shakib
"""
class Solution:
def is_match(self, s: str, p: str) -> bool:
n = len(s)
m = len(p)
dp = [[False for i in range(m + 1)] ... |
secret_key = b""
app_id = 0
client_secret = ""
bot_token = ""
| secret_key = b''
app_id = 0
client_secret = ''
bot_token = '' |
for _ in range(int(input())):
n,m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
distinct_color = {}
f, ans = 0, 0
for i in range(n):
# if(a[i] >= a[i + 1]):
for j in range(i - 1, -1,-1):
if(a[j] > a[i]):break
else: a[j] = 0
# print(a)
f... | for _ in range(int(input())):
(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
distinct_color = {}
(f, ans) = (0, 0)
for i in range(n):
for j in range(i - 1, -1, -1):
if a[j] > a[i]:
break
... |
_MODEL_DICT = {}
def register_model(name):
def decorator(cls):
_MODEL_DICT[name] = cls
return cls
return decorator
def get_model(cfg):
return _MODEL_DICT[cfg.type](cfg)
| _model_dict = {}
def register_model(name):
def decorator(cls):
_MODEL_DICT[name] = cls
return cls
return decorator
def get_model(cfg):
return _MODEL_DICT[cfg.type](cfg) |
marks=int(input("Enter your marks out of 100:"))
if marks>90:
print("Grade A")
elif marks>80:
print("Grade B")
elif marks>60:
print("Grade C")
elif marks>=0:
print("Grade D")
else :
print("You entered incorrect marks")
| marks = int(input('Enter your marks out of 100:'))
if marks > 90:
print('Grade A')
elif marks > 80:
print('Grade B')
elif marks > 60:
print('Grade C')
elif marks >= 0:
print('Grade D')
else:
print('You entered incorrect marks') |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
result = []
def inorder(node):
if node:
i... | class Solution:
def balance_bst(self, root: TreeNode) -> TreeNode:
result = []
def inorder(node):
if node:
if node.left != None:
inorder(node.left)
result.append(int(node.val))
if node.right != None:
... |
clist = ["orange", "apple apple", "banana anything banana", "mangao"]
cstr = " ".join([c for c in clist])
mlist = list(set([m for m in cstr.split()]))
print(mlist)
clst = []
for m in mlist:
if m != "anything":
clst.append(cstr.replace("anything", m))
print(clst)
| clist = ['orange', 'apple apple', 'banana anything banana', 'mangao']
cstr = ' '.join([c for c in clist])
mlist = list(set([m for m in cstr.split()]))
print(mlist)
clst = []
for m in mlist:
if m != 'anything':
clst.append(cstr.replace('anything', m))
print(clst) |
state2constituency_mapper = {2004: {'ANDHRA PRADESH': ['Srikakulam',
'Parvathipuram',
'Bobbili',
'Visakhapatnam',
... | state2constituency_mapper = {2004: {'ANDHRA PRADESH': ['Srikakulam', 'Parvathipuram', 'Bobbili', 'Visakhapatnam', 'Bhadrachalam', 'Anakapalli', 'Kakinada', 'Rajahmundry', 'Amalapuram', 'Narasapur', 'Eluru', 'Machilipatnam', 'Vijayawada', 'Tenali', 'Guntur', 'Bapatla', 'Narasaraopet', 'Ongole', 'Nellore', 'Tirupathi', '... |
# Task
goodFood = []
goodFood.append("burgers")
print(goodFood)
# Task
prerequisites = ["COP 2271c", "Introduction to Computation and Programming", 3, "Dr. Anderson" , 2015]
prerequisites.pop(4)
print(prerequisites)
# Task
prerequisites.remove("Dr. Anderson")
print(prerequisites)
prerequisites.remove(3)
print(prerequ... | good_food = []
goodFood.append('burgers')
print(goodFood)
prerequisites = ['COP 2271c', 'Introduction to Computation and Programming', 3, 'Dr. Anderson', 2015]
prerequisites.pop(4)
print(prerequisites)
prerequisites.remove('Dr. Anderson')
print(prerequisites)
prerequisites.remove(3)
print(prerequisites)
prerequisites.i... |
__all__ = ['splitter_streams']
# goes into each unit in from units list and unfixes all the stream fractions associate with that unit
#for optimization. eventually may want to optimize particular streams if more than 2 coming out of unit.
def splitter_streams(m=None, from_units=None):
for unit in from_units:
... | __all__ = ['splitter_streams']
def splitter_streams(m=None, from_units=None):
for unit in from_units:
for key in m.fs.arc_dict:
if m.fs.arc_dict[key][0] == unit:
splitter_name = m.fs.arc_dict[key][2]
for outlet_i in getattr(m.fs, splitter_name).outlet_list:
... |
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
alist = []
result = [];
if not nums:
return result
self.helper(nums, alist, result)
return result
def helper(self, nums, a... | class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
alist = []
result = []
if not nums:
return result
self.helper(nums, alist, result)
return result
def helper(self, nums, ali... |
# config.py
def can_build(env, platform):
return not env['production']
def configure(env):
pass
| def can_build(env, platform):
return not env['production']
def configure(env):
pass |
def aumentar(n, taxa=10):
a = n + (n * taxa / 100)
return a
def diminuir(n, taxa=10):
a = n - (n * taxa / 100)
return a
def dobro(n):
return float(n * 2)
def metade(n):
return n / 2
| def aumentar(n, taxa=10):
a = n + n * taxa / 100
return a
def diminuir(n, taxa=10):
a = n - n * taxa / 100
return a
def dobro(n):
return float(n * 2)
def metade(n):
return n / 2 |
#
# PySNMP MIB module BROCADE-PRODUCTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BROCADE-PRODUCTS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:41:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) ... |
def includeme(config):
config.add_route('index.dashboard', '/dashboard')
config.add_route('index.dashboard.api', '/api/dashboard/')
config.add_route('index.versions', '/versions')
config.add_route('index.json_body', '/json-body')
| def includeme(config):
config.add_route('index.dashboard', '/dashboard')
config.add_route('index.dashboard.api', '/api/dashboard/')
config.add_route('index.versions', '/versions')
config.add_route('index.json_body', '/json-body') |
_base_ = [
'../../../_base_/models/slowonly_r50.py',
'../../../_base_/default_runtime.py'
]
ann_type = 'tanz_base' # * change accordingly
videos_per_gpu_train = 8 if ann_type == 'tanz_base' else 4
workers_per_gpu_train = 1 # Normally it was 4, but it creates a bottleneck in CPU usage. Check SlowTraining&High... | _base_ = ['../../../_base_/models/slowonly_r50.py', '../../../_base_/default_runtime.py']
ann_type = 'tanz_base'
videos_per_gpu_train = 8 if ann_type == 'tanz_base' else 4
workers_per_gpu_train = 1
num_classes = 9 if ann_type == 'tanz_base' else 42
model = dict(backbone=dict(pretrained=None), cls_head=dict(num_classes=... |
Suffixes={1000:['KB','MB','TB','PB','EB','ZB','YB'],
1024:['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']}
def approximate_size(size,a_kilobyte_is_1024_byte=True):
if size < 0:
raise ValueError('Number is non-negitive')
multiple = 1024 if a_kilobyte_is_1024_byte else 1000
for suffix in Suffixes[m... | suffixes = {1000: ['KB', 'MB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_byte=True):
if size < 0:
raise value_error('Number is non-negitive')
multiple = 1024 if a_kilobyte_is_1024_byte else 1000
for s... |
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
n = len(intervals)
if n == 0:
return [newInterval]
i = 0
while i < n and newInterval[0] > intervals[i][0]:
i += 1
if i == n: # edge case 1: insert ... | class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
n = len(intervals)
if n == 0:
return [newInterval]
i = 0
while i < n and newInterval[0] > intervals[i][0]:
i += 1
if i == n:
result = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
connectives = [
"but", "because", "although", "though", "despite", "necessarily",
"therefore", "thus", "nevertheless", "consequently", "alternatively",
"resulting", "unless"
# omitted "if"/"then" because they're ubiquitous outside conditionals
# omitted... | connectives = ['but', 'because', 'although', 'though', 'despite', 'necessarily', 'therefore', 'thus', 'nevertheless', 'consequently', 'alternatively', 'resulting', 'unless']
connective_non_adv = ['so', 'yet']
connective_with_comma = ['first', 'second', 'third', 'however', 'finally']
def logical_connectives_pct(taggedT... |
class SymbTable:
def __init__(self, debug=True):
self.symbTable = dict()
self.symbTable[0] = dict({'global': dict({'scope_type': 'global', 'parent': None, 'scope_vars': dict()})})
'''
Structure of SymbTable:
top level key : Level - Basically represent nesting level (... | class Symbtable:
def __init__(self, debug=True):
self.symbTable = dict()
self.symbTable[0] = dict({'global': dict({'scope_type': 'global', 'parent': None, 'scope_vars': dict()})})
'\n Structure of SymbTable:\n top level key : Level - Basically represent nesting level (... |
"""
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, s... | """
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, s... |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
prin... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.