content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# GET /app/hello_world
print("hello world!")
| print('hello world!') |
# Time: O(n + w^2), n = w * l,
# n is the length of S,
# w is the number of word,
# l is the average length of word
# Space: O(n)
# A sentence S is given, composed of words separated by spaces.
# Each word consists of lowercase and uppercase letters only.
#
# W... | class Solution(object):
def to_goat_latin(self, S):
"""
:type S: str
:rtype: str
"""
def convert(S):
vowel = set('aeiouAEIOU')
for (i, word) in enumerate(S.split(), 1):
if word[0] not in vowel:
word = word[1:] + wo... |
class Solution(object):
def combinationSum(self, candidates, target):
return self.helper(candidates, target, [], set())
def helper(self, arr, target, comb, result):
for num in arr:
if target - num == 0:
result.add(tuple(sorted(comb[:] + [num])))
elif ... | class Solution(object):
def combination_sum(self, candidates, target):
return self.helper(candidates, target, [], set())
def helper(self, arr, target, comb, result):
for num in arr:
if target - num == 0:
result.add(tuple(sorted(comb[:] + [num])))
elif ta... |
# Consider a list (list = []).
# You can perform the following commands:
# insert i e: Insert integer 'e' at position 'i'.
# print: Print the list.
# remove e: Delete the first occurrence of integer .
# append e: Insert integer at the end of the list.
# sort: Sort the list.
# pop: Pop the last... | if __name__ == '__main__':
n = int(input())
my_list = []
for _ in range(0, N):
command = input()
command_parts = command.split()
key_word = command_parts[0]
if key_word == 'insert':
index = int(command_parts[1])
value = int(command_parts[2])
... |
n = int(input())
arr = input().split()
for i in range(0,len(arr)):
arr[i] = int(arr[i])
count = 0
Max = max(arr)
for i in range(0,len(arr)):
if(arr[i]==Max):
count +=1
print(str(count))
| n = int(input())
arr = input().split()
for i in range(0, len(arr)):
arr[i] = int(arr[i])
count = 0
max = max(arr)
for i in range(0, len(arr)):
if arr[i] == Max:
count += 1
print(str(count)) |
def alphabet_position(character):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
lower = character.lower()
return alphabet.index(lower)
def rotate_string_13(text):
rotated = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in text:
rotated_idx = (alphabet_position(char) + 13) % 26
... | def alphabet_position(character):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
lower = character.lower()
return alphabet.index(lower)
def rotate_string_13(text):
rotated = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in text:
rotated_idx = (alphabet_position(char) + 13) % 26
i... |
description = 'Additional rotation table'
group = 'optional'
tango_base = 'tango://motorbox05.stressi.frm2.tum.de:10000/box/'
devices = dict(
addphi_m = device('nicos.devices.entangle.Motor',
tangodevice = tango_base + 'channel4/motor',
fmtstr = '%.2f',
visibility = (),
speed = 4,... | description = 'Additional rotation table'
group = 'optional'
tango_base = 'tango://motorbox05.stressi.frm2.tum.de:10000/box/'
devices = dict(addphi_m=device('nicos.devices.entangle.Motor', tangodevice=tango_base + 'channel4/motor', fmtstr='%.2f', visibility=(), speed=4), addphi=device('nicos.devices.generic.Axis', desc... |
NEW2OLD = {'AD': 'ADCY8', 'DP': 'DPYS', 'GA': 'GARL1', 'HA9': 'HOXA9',
'GR': 'GRM6', 'H12': 'HOXD12', 'HD9': 'HOXD9', 'PR': 'PRAC',
'PT': 'PTGDR', 'SA': 'SALL3', 'SI': 'SIX6', 'SL': 'SLC6A2',
'TL': 'TLX3', 'TR': 'TRIM58', 'ZF': 'ZFP41'}
OLD2NEW = {NEW2OLD[i]: i for i in NEW2OLD.keys() i... | new2_old = {'AD': 'ADCY8', 'DP': 'DPYS', 'GA': 'GARL1', 'HA9': 'HOXA9', 'GR': 'GRM6', 'H12': 'HOXD12', 'HD9': 'HOXD9', 'PR': 'PRAC', 'PT': 'PTGDR', 'SA': 'SALL3', 'SI': 'SIX6', 'SL': 'SLC6A2', 'TL': 'TLX3', 'TR': 'TRIM58', 'ZF': 'ZFP41'}
old2_new = {NEW2OLD[i]: i for i in NEW2OLD.keys() if NEW2OLD[i] is not None}
def ... |
# Single Responsibility Principle (SRP) or Separation Of Concerns (SOC)
class Journal():
def __init__(self):
self.entries = []
self.count = 0
def add_entry(self, text):
self.count += 1
self.entries.append(f'{self.count}: {text}')
def remove_entry(self, index):
... | class Journal:
def __init__(self):
self.entries = []
self.count = 0
def add_entry(self, text):
self.count += 1
self.entries.append(f'{self.count}: {text}')
def remove_entry(self, index):
self.count -= 1
self.entries.pop(index)
def __str__(self):
... |
# why=None
# what=why
# while what is why:
# try:
# what=int (input ("what? " ) )
# except ValueError :
# print( "no.")
# def abc(z):
# if(z<=1):return False
# for(x)in(range(2 ,int(z**.5)+1)) :
# if z % x==0:
# return False
# return True
# for who in rang... | """This program will check all integers up to a specified limit for primality"""
max_number = None
while max_number is None:
try:
max_number = int(input('Up to which number would you like to check? '))
except ValueError:
print('Please enter an integer.')
def is_prime(n):
"""Checks if the ar... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# Copyright (c) 2012 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.
{
'variables': {
'chromium_code': 1,
# Override to dynamically link the cras (ChromeOS audio) library.
'use_cras%': 0,
# Option e.g. fo... | {'variables': {'chromium_code': 1, 'use_cras%': 0, 'linux_link_pulseaudio%': 0, 'conditions': [['OS == "android" or OS == "ios"', {'media_use_ffmpeg%': 0, 'media_use_libvpx%': 0}, {'media_use_ffmpeg%': 1, 'media_use_libvpx%': 1}], ['OS=="win" or OS=="mac" or (OS=="linux" and use_x11==1)', {'screen_capture_supported%': ... |
def replaceSlice(string, l_index, r_index, replaceable):
string = string[0:l_index] + string[r_index - 1:]
string = string[0:l_index] + replaceable + string[r_index:]
return string
def correctSpaces(expression):
return expression.replace(" ", "")
def replaceAlternateOperationSigns(expression):
r... | def replace_slice(string, l_index, r_index, replaceable):
string = string[0:l_index] + string[r_index - 1:]
string = string[0:l_index] + replaceable + string[r_index:]
return string
def correct_spaces(expression):
return expression.replace(' ', '')
def replace_alternate_operation_signs(expression):
... |
def changeFeather(value):
for s in nuke.selectedNodes():
selNode = nuke.selectedNode()
if s.Class() == "Roto" or s.Class() == "RotoPaint":
for item in s['curves'].rootLayer:
attr = item.getAttributes()
attr.set('ff',value)
feather_value = 0
changeFeathe... | def change_feather(value):
for s in nuke.selectedNodes():
sel_node = nuke.selectedNode()
if s.Class() == 'Roto' or s.Class() == 'RotoPaint':
for item in s['curves'].rootLayer:
attr = item.getAttributes()
attr.set('ff', value)
feather_value = 0
change_feath... |
def mongoify(doc):
if 'id' in doc:
doc['_id'] = doc['id']
del doc['id']
return doc
def demongoify(doc):
if "_id" in doc:
doc['id'] = doc['_id']
del doc['_id']
return doc
| def mongoify(doc):
if 'id' in doc:
doc['_id'] = doc['id']
del doc['id']
return doc
def demongoify(doc):
if '_id' in doc:
doc['id'] = doc['_id']
del doc['_id']
return doc |
def main() -> None:
# fermat's little theorem
n, k, m = map(int, input().split())
# m^(k^n)
MOD = 998_244_353
m %= MOD
print(pow(m, pow(k, n, MOD - 1), MOD))
if __name__ == "__main__":
main()
| def main() -> None:
(n, k, m) = map(int, input().split())
mod = 998244353
m %= MOD
print(pow(m, pow(k, n, MOD - 1), MOD))
if __name__ == '__main__':
main() |
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
try:
idx = word.index(ch) + 1
except Exception:
return word
return ''.join(word[:idx][::-1] + word[idx:]) | class Solution:
def reverse_prefix(self, word: str, ch: str) -> str:
try:
idx = word.index(ch) + 1
except Exception:
return word
return ''.join(word[:idx][::-1] + word[idx:]) |
# -*- coding: utf-8 -*-
"""Top-level package for Crime_term_project."""
__author__ = """Catalina Cardelle"""
__email__ = 'cardelle.c@husky.neu.edu'
__version__ = '0.1.0'
| """Top-level package for Crime_term_project."""
__author__ = 'Catalina Cardelle'
__email__ = 'cardelle.c@husky.neu.edu'
__version__ = '0.1.0' |
rest_days = int(input())
year_in_days = 365
work_days = year_in_days - rest_days
play_time = (work_days * 63 + rest_days * 127)
if play_time <= 30000:
play_time1 = 30000 - play_time
else:
play_time1 = play_time - 30000
hours = play_time1 // 60
minutes = play_time1 % 60
if play_time > 30000:
print(f"Tom w... | rest_days = int(input())
year_in_days = 365
work_days = year_in_days - rest_days
play_time = work_days * 63 + rest_days * 127
if play_time <= 30000:
play_time1 = 30000 - play_time
else:
play_time1 = play_time - 30000
hours = play_time1 // 60
minutes = play_time1 % 60
if play_time > 30000:
print(f'Tom will r... |
# -*- coding: utf-8 -*-
__author__ = 'guti'
'''
Default configurations for the Web application.
'''
configs = {
'db': {
'host': '127.0.0.1',
'port': 5432,
'user': 'test_usr',
'password': 'test_pw',
'database': 'test_db'
},
'session': {
'secret': '0IH9c71HS86... | __author__ = 'guti'
'\nDefault configurations for the Web application.\n'
configs = {'db': {'host': '127.0.0.1', 'port': 5432, 'user': 'test_usr', 'password': 'test_pw', 'database': 'test_db'}, 'session': {'secret': '0IH9c71HS86KSnqmQFAbBiwnEUqMYEo9vAQFb+DA9Ns='}} |
class UnetOptions:
def __init__(self):
self.in_channels=1
self.n_classes=2
self.depth=5
self.wf=6
self.padding=False
self.up_mode='upconv'
self.batch_norm=True
self.non_neg = True
self.pose_predict_mode = False
self.pretrained_mode =... | class Unetoptions:
def __init__(self):
self.in_channels = 1
self.n_classes = 2
self.depth = 5
self.wf = 6
self.padding = False
self.up_mode = 'upconv'
self.batch_norm = True
self.non_neg = True
self.pose_predict_mode = False
self.pretr... |
# Python - 2.7.6
def find_next_square(sq):
num = int(sq ** 0.5)
return (num + 1) ** 2 if (num ** 2) == sq else -1
| def find_next_square(sq):
num = int(sq ** 0.5)
return (num + 1) ** 2 if num ** 2 == sq else -1 |
# value of A represent its position in C
# value of C represent its position in B
def count_sort(A, k):
B = [0 for i in range(len(A))]
C = [0 for i in range(k)]
# count the frequency of each elements in A and save them in the coresponding position in B
for i in range(0, len(A)):
C[A[i] - 1] +=... | def count_sort(A, k):
b = [0 for i in range(len(A))]
c = [0 for i in range(k)]
for i in range(0, len(A)):
C[A[i] - 1] += 1
for i in range(1, k, 1):
C[i] = C[i - 1] + C[i]
for i in range(len(A) - 1, -1, -1):
B[C[A[i] - 1] - 1] = A[i]
C[A[i] - 1] -= 1
return B
b = c... |
class Params:
# -------------------------------
# GENERAL
# -------------------------------
gpu_ewc = '4' # GPU number
gpu_rewc = '3' # GPU number
data_size = 224 # Data size
batch_size = 32 # Batch size
nb_cl = 50 # Classes ... | class Params:
gpu_ewc = '4'
gpu_rewc = '3'
data_size = 224
batch_size = 32
nb_cl = 50
nb_groups = 4
nb_val = 0
epochs = 50
num_samples = 5
lr_init = 0.001
lr_strat = [40, 80]
lr_factor = 5.0
wght_decay = 1e-05
ratio = 100.0
eval_single = True
save_path = '... |
place_needed = int(input().split()[1])
scores = [j for j in reversed(sorted([int(i) for i in input().split() if int(i) > 0]))]
try:
score_needed = scores[place_needed - 1]
except IndexError:
score_needed = 0
amount = 0
for i in scores:
if i >= score_needed:
amount += 1
print(amount)
| place_needed = int(input().split()[1])
scores = [j for j in reversed(sorted([int(i) for i in input().split() if int(i) > 0]))]
try:
score_needed = scores[place_needed - 1]
except IndexError:
score_needed = 0
amount = 0
for i in scores:
if i >= score_needed:
amount += 1
print(amount) |
# List aa images with query stringa available
def list_all_images_subparser(subparser):
list_all_images = subparser.add_parser(
'list-all-images',
description=('***List all'
... | def list_all_images_subparser(subparser):
list_all_images = subparser.add_parser('list-all-images', description='***List all images of producers/consumers account', help='List all images of producers/consumers account')
group_key = list_all_images.add_mutually_exclusive_group(required=True)
group_key.add_ar... |
# No good name, sorry, lol :)
def combinations(list, k):
return 0
print( combinations([1, 2, 3, 4], 3) ) | def combinations(list, k):
return 0
print(combinations([1, 2, 3, 4], 3)) |
#Find the difference between the sum of the squares of the first one hundred natural numbers
# and the square of the sum.
#Generating a list with natural numbers 1-100.
nums = list(range(101))
#print(nums)
#Find the square of the sum (1+...+100).
# The following is old code: (that does work.)
#LIST = nums
... | nums = list(range(101))
list = list(range(101))
def tri_num(n):
n = int(n)
sum = n * (n + 1)
sum = sum / 2
sum = int(sum)
return sum
a = tri_num(100)
print(a)
print(a * a)
def tri_num_sqrd(n):
n = int(n)
sum = n * (n + 1) * (2 * n + 1)
sum = sum / 6
sum = int(sum)
return sum
b ... |
class Message:
# type id_message id_device timestamp
type = 'default'
id = 0
source_id = 0
source_timestamp = 0
payload = bytearray(0)
def __init__(self, type, id, source_id, source_timestamp, payload):
self.type = type
self.id = id
self.source_id = source_id
... | class Message:
type = 'default'
id = 0
source_id = 0
source_timestamp = 0
payload = bytearray(0)
def __init__(self, type, id, source_id, source_timestamp, payload):
self.type = type
self.id = id
self.source_id = source_id
self.source_timestamp
self.payloa... |
class Solution:
def cloneTree(self, root: 'Node') -> 'Node':
"""Tree.
"""
if not root:
return None
croot = Node(root.val)
m = {root: croot}
nodes = deque([root])
cnodes = deque([croot])
while nodes:
n = nodes.popleft()
... | class Solution:
def clone_tree(self, root: 'Node') -> 'Node':
"""Tree.
"""
if not root:
return None
croot = node(root.val)
m = {root: croot}
nodes = deque([root])
cnodes = deque([croot])
while nodes:
n = nodes.popleft()
... |
# Copyright (C) 2020 Square, 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... | def metadata(group_id, artifact_id, version, target, license, github_slug, developers=[], description=None, name=None):
""" Generates a known struct which can be consumed to generate release packaging. """
if not developers:
fail('Must specify at least one developer.')
return struct(name=name if nam... |
{
'targets': [
{
'target_name': 'xwalk_extensions_unittest',
'type': 'executable',
'dependencies': [
'../../base/base.gyp:base',
'../../base/base.gyp:run_all_unittests',
'../../testing/gtest.gyp:gtest',
'extensions.gyp:xwalk_extensions',
],
'sources': ... | {'targets': [{'target_name': 'xwalk_extensions_unittest', 'type': 'executable', 'dependencies': ['../../base/base.gyp:base', '../../base/base.gyp:run_all_unittests', '../../testing/gtest.gyp:gtest', 'extensions.gyp:xwalk_extensions'], 'sources': ['browser/xwalk_extension_function_handler_unittest.cc', 'common/xwalk_ext... |
def preprocess(df, standardize = False):
"""Splits the data into training and validation sets.
arguments:
df: the dataframe of training and test data you want to split.
standardize: if True returns standardized data.
"""
#split the data
train, test = train_test_split(df, train_size=0... | def preprocess(df, standardize=False):
"""Splits the data into training and validation sets.
arguments:
df: the dataframe of training and test data you want to split.
standardize: if True returns standardized data.
"""
(train, test) = train_test_split(df, train_size=0.8, random_state=42)... |
class Solution:
@staticmethod
def naive(n,edges):
adj = {i:[] for i in range(n)}
for u,v in edges:
adj[u].append(v)
adj[v].append(u)
# no cycle, only one fully connected tree
visited = set()
def dfs(i,fro):
if i in visited:
... | class Solution:
@staticmethod
def naive(n, edges):
adj = {i: [] for i in range(n)}
for (u, v) in edges:
adj[u].append(v)
adj[v].append(u)
visited = set()
def dfs(i, fro):
if i in visited:
return False
visited.add(i... |
def factorial(n):
"""
Computes the factorial of n.
"""
if n < 0:
raise ValueError('received negative input')
result = 1
for i in range(1, n + 1):
result *= i
return result
| def factorial(n):
"""
Computes the factorial of n.
"""
if n < 0:
raise value_error('received negative input')
result = 1
for i in range(1, n + 1):
result *= i
return result |
class CardSelectionConfigController(object):
cs = None
controller = None
pos = None
def __init__(self, cs, controller, pos=-1):
self.cs = cs
self.controller = controller
self.pos = pos
def save(self):
if self.pos < 0:
self.controller.add_cs(self.cs)
... | class Cardselectionconfigcontroller(object):
cs = None
controller = None
pos = None
def __init__(self, cs, controller, pos=-1):
self.cs = cs
self.controller = controller
self.pos = pos
def save(self):
if self.pos < 0:
self.controller.add_cs(self.cs)
... |
"""
With / As Keywords
"""
# print("Normal Write Start")
# my_write = open("textfile.txt", "w")
# my_write.write("Trying to write to the file")
# my_write.close()
#
#
# print("Normal Read Start")
# my_read = open("textfile.txt", "r")
# print(str(my_read.read()))
print("With As Write Start")
with open("withas.txt", "w"... | """
With / As Keywords
"""
print('With As Write Start')
with open('withas.txt', 'w') as with_as_write:
with_as_write.write('This is an example of with as write/read')
print()
print('With As Read Start')
with open('withas.txt', 'r') as with_as_read:
print(str(with_as_read.read())) |
""" A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone.
The frog can jump on a stone, but it must not jump into the water.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units.
Note that the frog can o... | """ A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone.
The frog can jump on a stone, but it must not jump into the water.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units.
Note that the frog can o... |
"""The longest common subsequence problem is the problem of finding the longest subsequence common to all sequences
in a set of sequences. It differs from the longest common substring problem: unlike substrings, subsequences are not
required to occupy consecutive positions within the original sequences. """
"""For bet... | """The longest common subsequence problem is the problem of finding the longest subsequence common to all sequences
in a set of sequences. It differs from the longest common substring problem: unlike substrings, subsequences are not
required to occupy consecutive positions within the original sequences. """
'For better... |
"""Re-exports shell rule."""
load("@bazel_skylib//lib:shell.bzl", _shell = "shell")
shell = _shell
| """Re-exports shell rule."""
load('@bazel_skylib//lib:shell.bzl', _shell='shell')
shell = _shell |
T = int(input())
for _ in range(T):
n = int(input())
s = [int(s_arr) for s_arr in input().split(' ')]
misere, count = 0, 0
for i in range(n):
misere ^= s[i]
if s[i] <= 1:
count += 1
print ("Second" if (count == n and misere == 1) or (count < n and misere == 0) el... | t = int(input())
for _ in range(T):
n = int(input())
s = [int(s_arr) for s_arr in input().split(' ')]
(misere, count) = (0, 0)
for i in range(n):
misere ^= s[i]
if s[i] <= 1:
count += 1
print('Second' if count == n and misere == 1 or (count < n and misere == 0) else 'Firs... |
# tests transition from small to large int representation by multiplication
for rhs in range(2, 11):
lhs = 1
for k in range(100):
res = lhs * rhs
print(lhs, '*', rhs, '=', res)
lhs = res
# below tests pos/neg combinations that overflow small int
# 31-bit overflow
i = 1 << 20
print(i * ... | for rhs in range(2, 11):
lhs = 1
for k in range(100):
res = lhs * rhs
print(lhs, '*', rhs, '=', res)
lhs = res
i = 1 << 20
print(i * i)
print(i * -i)
print(-i * i)
print(-i * -i)
i = 1 << 40
print(i * i)
print(i * -i)
print(-i * i)
print(-i * -i) |
class Reference():
metadata = {}
def __init__(self, metadata: dict, figures: list):
self.metadata.update(metadata)
for fig in figures:
setattr(self, fig.name, fig)
class Figure():
"""
This is the base class for figure data.
"""
def __init__(self, name: str, l... | class Reference:
metadata = {}
def __init__(self, metadata: dict, figures: list):
self.metadata.update(metadata)
for fig in figures:
setattr(self, fig.name, fig)
class Figure:
"""
This is the base class for figure data.
"""
def __init__(self, name: str, lines: list... |
class Solution:
def findComplement(self, num: int) -> int:
r = '{:08b}'.format(num).lstrip('0')
r2 = ''
for i in r:
if i == '0':
r2 += '1'
else:
r2 += '0'
r3 = int(r2, 2)
return r3
if __name__ == '__main__':
s = So... | class Solution:
def find_complement(self, num: int) -> int:
r = '{:08b}'.format(num).lstrip('0')
r2 = ''
for i in r:
if i == '0':
r2 += '1'
else:
r2 += '0'
r3 = int(r2, 2)
return r3
if __name__ == '__main__':
s = so... |
__copyright__ = """
Copyright 2021 Amazon.com, Inc. or its affiliates.
Copyright 2021 Netflix Inc.
Copyright 2021 Google LLC
"""
__license__ = """
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 cop... | __copyright__ = '\n Copyright 2021 Amazon.com, Inc. or its affiliates.\n Copyright 2021 Netflix Inc.\n Copyright 2021 Google LLC\n'
__license__ = '\n Licensed under the Apache License, Version 2.0 (the "License");\n you may not use this file except in compliance with the License.\n You may obtain a co... |
def filter_museums(request):
sub = {'nature': 1,
'memorial': 2,
'art': 3,
'gallery': 4,
'history': 5}
categories = [sub[i] for i in sub if request.GET.get(i) != 'false']
return categories
| def filter_museums(request):
sub = {'nature': 1, 'memorial': 2, 'art': 3, 'gallery': 4, 'history': 5}
categories = [sub[i] for i in sub if request.GET.get(i) != 'false']
return categories |
for i in range(1, 70, 2):
s= str(i+1)
print("printf \"26\\n30\\n" + s + "\\n\" > tile.sizes")
print("./polycc --tile --parallel NusValidation.cpp")
print("gcc -o nus" + s + " -O2 NusValidation.cpp.pluto.c -fopenmp -lm")
print("cp nus" + s + " exp")
print("./exp/nus" + s)
| for i in range(1, 70, 2):
s = str(i + 1)
print('printf "26\\n30\\n' + s + '\\n" > tile.sizes')
print('./polycc --tile --parallel NusValidation.cpp')
print('gcc -o nus' + s + ' -O2 NusValidation.cpp.pluto.c -fopenmp -lm')
print('cp nus' + s + ' exp')
print('./exp/nus' + s) |
# Puzzle Input
with open('Day05_Input.txt') as puzzle_input:
seats = puzzle_input.read().split('\n')
# Converts a list containing a binary number to a decimal number
def bin_to_decimal(bin_num):
dec_num = 0
bin_len = len(bin_num)
for pos, bit in enumerate(bin_num):
if bit == 1:
dec... | with open('Day05_Input.txt') as puzzle_input:
seats = puzzle_input.read().split('\n')
def bin_to_decimal(bin_num):
dec_num = 0
bin_len = len(bin_num)
for (pos, bit) in enumerate(bin_num):
if bit == 1:
dec_num += 2 ** (bin_len - pos - 1)
return dec_num
seat_id = []
for s in seats... |
# All traversals in one: Pre, post and inorder
# Time complexity: O(3n)
# Space complexity: O(4n), 4 stacks are being used
class Node():
def __init__(self, key):
self.left = None
self.value = key
self.right = None
def traversal(node):
if node is None:
return []
... | class Node:
def __init__(self, key):
self.left = None
self.value = key
self.right = None
def traversal(node):
if node is None:
return []
stack = [[node, 1]]
preorder = []
inorder = []
postorder = []
while len(stack) != 0:
curr = stack[-1][0]
... |
file = open("/disk/lulu/database/TSGene/pro/TSG.genepos.qukong.txt")
#f = open("out.txt", "w")
for line in file:
# print line,
list = line.strip().split("\t")
# print list
if list[4] == "-":
line1 = line.strip().replace("-", "")
print (line1)
# print >> f, "%s" % line1
... | file = open('/disk/lulu/database/TSGene/pro/TSG.genepos.qukong.txt')
for line in file:
list = line.strip().split('\t')
if list[4] == '-':
line1 = line.strip().replace('-', '')
print(line1)
else:
print(list[0], '\t', list[1], '\t', list[2], '\t', list[3], '\t', list[5], '\t', list[6],... |
# -*- coding: utf-8 -*-
class EndOfStream(Exception):
pass
class InvalidSyntaxError(Exception):
pass
class InvalidCommandFormat(InvalidSyntaxError):
pass
class TokenNotFound(InvalidSyntaxError):
pass
class DeprecatedSyntax(InvalidSyntaxError):
pass
class RenderingError(Exception):
pa... | class Endofstream(Exception):
pass
class Invalidsyntaxerror(Exception):
pass
class Invalidcommandformat(InvalidSyntaxError):
pass
class Tokennotfound(InvalidSyntaxError):
pass
class Deprecatedsyntax(InvalidSyntaxError):
pass
class Renderingerror(Exception):
pass
class Apertureselectionerro... |
src = []
include_tmp = []
if aos_global_config.compiler == 'armcc':
src = Split('''
compilers/armlibc/armcc_libc.c
''')
include_tmp = Split('''
compilers/armlibc
''')
elif aos_global_config.compiler == 'rvct':
src = Split('''
compilers/armlibc/armcc_libc.c
''')
... | src = []
include_tmp = []
if aos_global_config.compiler == 'armcc':
src = split('\n compilers/armlibc/armcc_libc.c\n ')
include_tmp = split('\n compilers/armlibc\n ')
elif aos_global_config.compiler == 'rvct':
src = split('\n compilers/armlibc/armcc_libc.c\n ')
include_tmp ... |
#
# PySNMP MIB module CISCO-PRIVATE-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-PRIVATE-VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
"""
File contains the groovy scripts used by Nexus 3 script api as objects
that may be used in the nexus3 state module.
I put these here as it made it easy to sync the groovy with the module itself
"""
create_blobstore = """
import groovy.json.JsonSlurper
parsed_args = new JsonSlurper().parseText(args)
existingBlob... | """
File contains the groovy scripts used by Nexus 3 script api as objects
that may be used in the nexus3 state module.
I put these here as it made it easy to sync the groovy with the module itself
"""
create_blobstore = '\nimport groovy.json.JsonSlurper\n\nparsed_args = new JsonSlurper().parseText(args)\n\nexistingBl... |
def compose_maxmin(R, S):
"""
X = {1: 0, 2: 0.2, 3: 0.4}
Y = {1: 0, 2: 0.2}
Relation (X*Y) = {(1, 1): 0, (1, 2): 0, (2, 1): 0, (2, 2): 0.04, (3, 1): 0, (3, 2): 0.08}
:param R: a dictionary like above example that
:param S: a dictionary like above example
:return: RoS a composition of R to S
... | def compose_maxmin(R, S):
"""
X = {1: 0, 2: 0.2, 3: 0.4}
Y = {1: 0, 2: 0.2}
Relation (X*Y) = {(1, 1): 0, (1, 2): 0, (2, 1): 0, (2, 2): 0.04, (3, 1): 0, (3, 2): 0.08}
:param R: a dictionary like above example that
:param S: a dictionary like above example
:return: RoS a composition of R to S
... |
class Solution:
def rangeSumBST(self, root, L, R):
def dfs(node):
if node:
if L <= node.val <= R:
self.ans = self.ans + node.val
if L < node.val:
dfs(node.left)
if R > node.val:
dfs(node.r... | class Solution:
def range_sum_bst(self, root, L, R):
def dfs(node):
if node:
if L <= node.val <= R:
self.ans = self.ans + node.val
if L < node.val:
dfs(node.left)
if R > node.val:
dfs(no... |
"""
This problem was asked by Google.
Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don't intersect, return 0.
For example, given the following rectangles:
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
}
and
{
"top_left": (0, 5),
"dimension... | """
This problem was asked by Google.
Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don't intersect, return 0.
For example, given the following rectangles:
{
"top_left": (1, 4),
"dimensions": (3, 3) # width, height
}
and
{
"top_left": (0, 5),
"dimension... |
class DataGridViewRowErrorTextNeededEventArgs(EventArgs):
""" Provides data for the System.Windows.Forms.DataGridView.RowErrorTextNeeded event of a System.Windows.Forms.DataGridView control. """
ErrorText=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the error text for the ... | class Datagridviewrowerrortextneededeventargs(EventArgs):
""" Provides data for the System.Windows.Forms.DataGridView.RowErrorTextNeeded event of a System.Windows.Forms.DataGridView control. """
error_text = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the error tex... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
class Types:
BIT = -7
TINYINT = -6
SMALLINT = 5
INTEGER = 4
BIGINT = -5
FLOAT = 6
REAL = 7
DOUBLE = 8
NUMERIC = 2
DECIMAL = 3
CHAR = 1
VARCHAR = 12
LONGVARCHAR = -1
DATE = 91
TIME =... | class Types:
bit = -7
tinyint = -6
smallint = 5
integer = 4
bigint = -5
float = 6
real = 7
double = 8
numeric = 2
decimal = 3
char = 1
varchar = 12
longvarchar = -1
date = 91
time = 92
timestamp = 93
binary = -2
varbinary = -3
longvarbinary = -... |
class Count(object):
version=1.5
def add(self,x,y):
return x+y
def sub(self,x,y):
return x-y
if __name__ == '__main__':
c=Count()
print(c.add(1,2))
print(c.sub(10,5)) | class Count(object):
version = 1.5
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
if __name__ == '__main__':
c = count()
print(c.add(1, 2))
print(c.sub(10, 5)) |
expected_output = {
"sensor_list": {
"Environmental Monitoring": {
"sensor": {
"PEM Iout": {"location": "P1", "reading": "0 A", "state": "Normal"},
"PEM Vin": {"location": "P1", "reading": "104 V AC", "state": "Normal"},
"PEM Vout": {"location": "P... | expected_output = {'sensor_list': {'Environmental Monitoring': {'sensor': {'PEM Iout': {'location': 'P1', 'reading': '0 A', 'state': 'Normal'}, 'PEM Vin': {'location': 'P1', 'reading': '104 V AC', 'state': 'Normal'}, 'PEM Vout': {'location': 'P1', 'reading': '0 V DC', 'state': 'Normal'}, 'Temp: Asic1': {'location': '0'... |
"""
Here we put all the device configuration that we emulate.
"""
# possible kik versions to emulate
kik_version_11_info = {"kik_version": "11.1.1.12218", "classes_dex_sha1_digest": "aCDhFLsmALSyhwi007tvowZkUd0="}
kik_version_13_info = {"kik_version": "13.4.0.9614", "classes_dex_sha1_digest": "ETo70PFW30/jeFMKKY+CNanX... | """
Here we put all the device configuration that we emulate.
"""
kik_version_11_info = {'kik_version': '11.1.1.12218', 'classes_dex_sha1_digest': 'aCDhFLsmALSyhwi007tvowZkUd0='}
kik_version_13_info = {'kik_version': '13.4.0.9614', 'classes_dex_sha1_digest': 'ETo70PFW30/jeFMKKY+CNanX2Fg='}
kik_version_14_info = {'kik_v... |
"""Created by sgoswami on 8/8/17."""
"""Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the
nodes of the first two lists."""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = No... | """Created by sgoswami on 8/8/17."""
'Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the \nnodes of the first two lists.'
class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def merg... |
class AST:
def __init__(self, **fields):
for k, v in fields.items():
setattr(self, k, v)
class mod(AST): pass
class Module(mod):
_fields = ('body',)
class Interactive(mod):
_fields = ('body',)
class Expression(mod):
_fields = ('body',)
class Suite(mod):
_fields = ('body',)
cla... | class Ast:
def __init__(self, **fields):
for (k, v) in fields.items():
setattr(self, k, v)
class Mod(AST):
pass
class Module(mod):
_fields = ('body',)
class Interactive(mod):
_fields = ('body',)
class Expression(mod):
_fields = ('body',)
class Suite(mod):
_fields = ('bo... |
# Approach 1 - Backtracking
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(remain, comb, next_start):
if remain == 0:
results.append(comb.copy())
return
elif remain < 0:
... | class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(remain, comb, next_start):
if remain == 0:
results.append(comb.copy())
return
elif remain < 0:
return
for i in... |
#Find the Prime Numbers in a given range with total count.
#(so basically prime number is a number which is only divisible by '1' & itself)
#examples : 2, 3, 5, 7, 11, 13,...
def error():
try:
#Finds the Prime Numbers in a given range:
ip = int(input("Enter the range to find Prime Nu... | def error():
try:
ip = int(input('Enter the range to find Prime Numbers: '))
if ip <= 0:
print('Wrong Input')
print('Input must be a positive value')
print('Start again..')
error()
print('Prime Numbers: ')
for num in range(1, ip + 1):
... |
# encoding: utf-8
# module Revit.Filter calls itself Filter
# from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class FilterRule(object):
""" Revit Filter Rule """
@staticmethod
def ByRuleType(type, v... | class Filterrule(object):
""" Revit Filter Rule """
@staticmethod
def by_rule_type(type, value, parameter):
"""
ByRuleType(type: str,value: object,parameter: Parameter) -> FilterRule
Create a new Filter Rule
type: Filter Rule Type
value: Value to check
parameter: Parameter... |
class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
res = [(r0, c0)]
step = 1
while len(res) < R * C:
# right
for j in range(step):
c0 += 1
if self._in_grid(c0, r0, C, R):
... | class Solution:
def spiral_matrix_iii(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
res = [(r0, c0)]
step = 1
while len(res) < R * C:
for j in range(step):
c0 += 1
if self._in_grid(c0, r0, C, R):
res.append((r0, c... |
# Copyright 2016 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.
class PixelTestPage(object):
"""A wrapper class mimicking the functionality of the PixelTestsStorySet
from the old-style GPU tests.
"""
def __init__(... | class Pixeltestpage(object):
"""A wrapper class mimicking the functionality of the PixelTestsStorySet
from the old-style GPU tests.
"""
def __init__(self, url, name, test_rect, revision, expected_colors=None, tolerance=2, browser_args=None):
super(PixelTestPage, self).__init__()
self.url = ... |
def get_sql():
limit = 6
sql = f"SELEct speed from world where animal='dolphin' limit {limit}"
return sql
def get_query_template():
limit = 6
query_template = (
f"SELEct speed from world where animal='dolphin' group by family limit {limit}"
)
return query_template
def get_query()... | def get_sql():
limit = 6
sql = f"SELEct speed from world where animal='dolphin' limit {limit}"
return sql
def get_query_template():
limit = 6
query_template = f"SELEct speed from world where animal='dolphin' group by family limit {limit}"
return query_template
def get_query():
limit = 99
... |
postponed = 'POSTPONED'
scheduled = 'SCHEDULED'
awarded = 'AWARDED'
suspended = 'SUSPENDED'
inPlay = 'IN_PLAY'
canceled = 'CANCELED'
paused = 'PAUSED'
finished = 'FINISHED'
matchToBePlayedList = [scheduled, suspended, paused, inPlay] | postponed = 'POSTPONED'
scheduled = 'SCHEDULED'
awarded = 'AWARDED'
suspended = 'SUSPENDED'
in_play = 'IN_PLAY'
canceled = 'CANCELED'
paused = 'PAUSED'
finished = 'FINISHED'
match_to_be_played_list = [scheduled, suspended, paused, inPlay] |
class ActionException(Exception):
pass
class PingTimeout(Exception):
pass
class MeruException(Exception):
pass
| class Actionexception(Exception):
pass
class Pingtimeout(Exception):
pass
class Meruexception(Exception):
pass |
class Table(object):
def __init__(self, name, columns):
self.name = name
self.columns = columns
| class Table(object):
def __init__(self, name, columns):
self.name = name
self.columns = columns |
def test_add_group(app, xlsx_groups):
old_list = app.group.get_group_list()
app.group.add_new_group(xlsx_groups)
new_list = app.group.get_group_list()
old_list.append(xlsx_groups)
assert sorted(old_list) == sorted(new_list)
| def test_add_group(app, xlsx_groups):
old_list = app.group.get_group_list()
app.group.add_new_group(xlsx_groups)
new_list = app.group.get_group_list()
old_list.append(xlsx_groups)
assert sorted(old_list) == sorted(new_list) |
'''
Created on 18 Sep 2017
@author: ywz
'''
| """
Created on 18 Sep 2017
@author: ywz
""" |
a = 3
b = 4.0
c = a + b
d = a - b
e = a / b
tup = (a, b, c, d, e)
tup
| a = 3
b = 4.0
c = a + b
d = a - b
e = a / b
tup = (a, b, c, d, e)
tup |
#!/usr/bin/env python
NAME = 'Newdefend (NewDefend)'
def is_waf(self):
# Newdefend reveals itself within the server headers without any mal requests
if self.matchheader(('Server', 'Newdefend')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
re... | name = 'Newdefend (NewDefend)'
def is_waf(self):
if self.matchheader(('Server', 'Newdefend')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, page) = r
if any((i in page for i in (b'http://www.newdefend.com/feedback', b'/nd-... |
# Example: Send Picture Message
id = api.send_message(
from_ = '+1234567980',
to = '+1234567981',
media = ['http://host/path/to/file']
)
| id = api.send_message(from_='+1234567980', to='+1234567981', media=['http://host/path/to/file']) |
def lps(string, result=[]):
if len(string) > 0:
end = 0
for i in range(1, len(string)):
if string[i] == string[0] and i > end:
end = i
if not result:
result.append(string[0: end + 1])
elif len(string[0: end+1]) > len(result[0]):
re... | def lps(string, result=[]):
if len(string) > 0:
end = 0
for i in range(1, len(string)):
if string[i] == string[0] and i > end:
end = i
if not result:
result.append(string[0:end + 1])
elif len(string[0:end + 1]) > len(result[0]):
res... |
class ModesOfPaymentService(object):
"""
:class:`fortnox.ModesOfPaymentService` is used by :class:`fortnox.Client` to make
actions related to ModesOfPayment resource.
Normally you won't instantiate this class directly.
"""
"""
Allowed attributes for ModesOfPayment to send to Fortnox backen... | class Modesofpaymentservice(object):
"""
:class:`fortnox.ModesOfPaymentService` is used by :class:`fortnox.Client` to make
actions related to ModesOfPayment resource.
Normally you won't instantiate this class directly.
"""
'\n Allowed attributes for ModesOfPayment to send to Fortnox backend ... |
# Exercise 66 - Translator
d = dict(weather = "clima", earth = "terra", rain = "chuva")
def vocabulary(word):
return d[word] if word in d else ''
word = input('Enter word: ')
print(vocabulary(word)) | d = dict(weather='clima', earth='terra', rain='chuva')
def vocabulary(word):
return d[word] if word in d else ''
word = input('Enter word: ')
print(vocabulary(word)) |
class BoardAlreadyExistsException(Exception):
"""
Exception used for when the Tensorboard class cannot delete a folder
that already exists. This exception should not be use for anything else.
"""
def __init__(self, name):
super().__init__(f'Tensorboard: {name} already exists') | class Boardalreadyexistsexception(Exception):
"""
Exception used for when the Tensorboard class cannot delete a folder
that already exists. This exception should not be use for anything else.
"""
def __init__(self, name):
super().__init__(f'Tensorboard: {name} already exists') |
def bytes2human(n):
# http://code.activestate.com/recipes/578019
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
... | def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for (i, s) in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return '... |
#!/usr/bin/env python
NAME = 'Radware AppWall'
def is_waf(self):
if self.matchheader(('X-SL-CompState', '.')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, responsebody = r
# Most reliable fingerprint is this on block page... | name = 'Radware AppWall'
def is_waf(self):
if self.matchheader(('X-SL-CompState', '.')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, responsebody) = r
if all((i in responsebody for i in (b'because we have detected unautho... |
class RoutingPath:
"""Holds a list of locations and optimizes for `in` comparisons
"""
def __init__(self, path):
self._values = tuple(path)
self._set = frozenset(path)
def __len__(self):
return len(self._values)
def __getitem__(self, key):
return self._values[key]
... | class Routingpath:
"""Holds a list of locations and optimizes for `in` comparisons
"""
def __init__(self, path):
self._values = tuple(path)
self._set = frozenset(path)
def __len__(self):
return len(self._values)
def __getitem__(self, key):
return self._values[key]
... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return 1
i = 1
l = len(nums)
cur = 0
while i < l:
if nums[c... | class Solution(object):
def remove_duplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return 1
i = 1
l = len(nums)
cur = 0
while i < l:
if nums... |
def domainchanger(email,newdom,olddom = "1"):
email = email.split("@")
if newdom != email[1]:
newemail = email[0] + "@"+ newdom
return f"Changed: {newemail}"
else:
newemail = email[0] + "@"+ email[1]
return f"Unchanged: {newemail}"
email = input("Enter your email: ")
newdom... | def domainchanger(email, newdom, olddom='1'):
email = email.split('@')
if newdom != email[1]:
newemail = email[0] + '@' + newdom
return f'Changed: {newemail}'
else:
newemail = email[0] + '@' + email[1]
return f'Unchanged: {newemail}'
email = input('Enter your email: ')
newdom... |
# -*- coding: utf-8 -*-
def extract_id(object_or_id):
"""Return an id given either an object with an id or an id."""
try:
id = object_or_id.id
except AttributeError:
id = object_or_id
return id
def extract_ids(objects_or_ids):
"""Return a list of ids given either objects with ids o... | def extract_id(object_or_id):
"""Return an id given either an object with an id or an id."""
try:
id = object_or_id.id
except AttributeError:
id = object_or_id
return id
def extract_ids(objects_or_ids):
"""Return a list of ids given either objects with ids or a list of ids."""
t... |
"""Params for ADDA."""
# params for dataset and data loader
data_root = "data"
usps_data = data_root + '/USPS'
mnistm_data = data_root + '/MNIST_M'
svhn_data = data_root + '/SVHN'
dataset_mean_value = 0.5
dataset_std_value = 0.5
dataset_mean = (dataset_mean_value, dataset_mean_value, dataset_mean_value)
dataset_std = ... | """Params for ADDA."""
data_root = 'data'
usps_data = data_root + '/USPS'
mnistm_data = data_root + '/MNIST_M'
svhn_data = data_root + '/SVHN'
dataset_mean_value = 0.5
dataset_std_value = 0.5
dataset_mean = (dataset_mean_value, dataset_mean_value, dataset_mean_value)
dataset_std = (dataset_std_value, dataset_std_value,... |
#!/usr/bin/env python
""" This simple Python script can be run to generate
ztriangle_code_*.h, ztriangle_table.*, and ztriangle_*.cxx, which
are a poor man's form of generated code to cover the explosion of
different rendering options while scanning out triangles.
Each different combination of options is compiled to a... | """ This simple Python script can be run to generate
ztriangle_code_*.h, ztriangle_table.*, and ztriangle_*.cxx, which
are a poor man's form of generated code to cover the explosion of
different rendering options while scanning out triangles.
Each different combination of options is compiled to a different
inner-loop ... |
class Vector:
def __init__(self, length=3, vec=None):
self._vec = []
if isinstance(vec, list):
self._vec = vec.copy()
else:
if isinstance(length, (int, float)):
for i in range(int(length)):
self._vec.append(0)
self._length =... | class Vector:
def __init__(self, length=3, vec=None):
self._vec = []
if isinstance(vec, list):
self._vec = vec.copy()
elif isinstance(length, (int, float)):
for i in range(int(length)):
self._vec.append(0)
self._length = len(self._vec)
de... |
# -*- coding: utf-8 -*-
"""
pip_services3_mongodb.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mongodb module initialization
:copyright: Conceptual Vision Consulting LLC 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
__all__ = [ ]
| """
pip_services3_mongodb.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mongodb module initialization
:copyright: Conceptual Vision Consulting LLC 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
__all__ = [] |
'''
This file contains config values (like the port numbers) used by our library
'''
#:port to use for socket communications
PORT = 1001
#:ip address of group to use for multicast communications
MULTICAST_GROUP_IP = '224.15.35.42'
#:port to use for multicast communications
MULTICAST_PORT = 10000
#:the default timeout f... | """
This file contains config values (like the port numbers) used by our library
"""
port = 1001
multicast_group_ip = '224.15.35.42'
multicast_port = 10000
default_timeout = 10
max_connect_requests = 5
network_chunk_size = 8192 |
food_items = [
"ham",
#"spam",
"eggs",
"nuts"
]
for food in food_items:
if food == "spam":
print ("No spam please")
break
print ("Great - ", food)
#else:
# print ("I am glad - There was no spam")
print ("Finally I have finished") | food_items = ['ham', 'eggs', 'nuts']
for food in food_items:
if food == 'spam':
print('No spam please')
break
print('Great - ', food)
print('Finally I have finished') |
# https://leetcode.com/problems/sum-of-two-integers/
class Solution:
def getSum(self, a: int, b: int) -> int:
result = sum([a, b])
return result
a = 1
b = 2
s = Solution()
result = s.getSum(a, b) | class Solution:
def get_sum(self, a: int, b: int) -> int:
result = sum([a, b])
return result
a = 1
b = 2
s = solution()
result = s.getSum(a, b) |
class HttpHeaders:
X_CORRELATION_ID = "X-Correlation-ID"
CONTENT_TYPE = "Content-Type"
ACCEPT = 'Accept'
| class Httpheaders:
x_correlation_id = 'X-Correlation-ID'
content_type = 'Content-Type'
accept = 'Accept' |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-repodb'
ES_DOC_TYPE = 'chemical'
API_PREFIX = 'repodb'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-repodb'
es_doc_type = 'chemical'
api_prefix = 'repodb'
api_version = '' |
def check_types(value, *types, var_name="value"):
"""
Check value by types compliance.
:param value: object.
Value to check.
:param types: tuple.
Types list to compare.
:param var_name: str, optional (default="value").
Name of the variable for exception message.
"""
... | def check_types(value, *types, var_name='value'):
"""
Check value by types compliance.
:param value: object.
Value to check.
:param types: tuple.
Types list to compare.
:param var_name: str, optional (default="value").
Name of the variable for exception message.
"""
... |
def match(text, pattern, base=10):
text_len = len(text)
pattern_len = len(pattern)
text_hash = _get_hash(text[:pattern_len], base)
pattern_hash = _get_hash(pattern, base)
matches = []
for i in xrange(text_len - pattern_len + 1):
if pattern_hash == text_hash:
# If the hashe... | def match(text, pattern, base=10):
text_len = len(text)
pattern_len = len(pattern)
text_hash = _get_hash(text[:pattern_len], base)
pattern_hash = _get_hash(pattern, base)
matches = []
for i in xrange(text_len - pattern_len + 1):
if pattern_hash == text_hash:
if pattern == tex... |
"""
A collection of useful classes and functions
"""
__all__ = ['add', 'MixedSpam']
def add(a, b):
"""
Add two numbers
"""
return a + b
class MixedSpam(object):
"""
Special spam
"""
def eat(self, time):
"""
Eat special spam in the required time.
"""
... | """
A collection of useful classes and functions
"""
__all__ = ['add', 'MixedSpam']
def add(a, b):
"""
Add two numbers
"""
return a + b
class Mixedspam(object):
"""
Special spam
"""
def eat(self, time):
"""
Eat special spam in the required time.
"""
pas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.