content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_orm_test',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'OPTIONS': {
'init_command': 'SET storage_engine=INNODB',
}
},
}
TEST_MODULE_PREFIX = 'm... | databases = {'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_orm_test', 'USER': 'root', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'OPTIONS': {'init_command': 'SET storage_engine=INNODB'}}}
test_module_prefix = 'mysql_'
secret_key = 'django_tests_secret_key' |
#
# Copyright (C) 2014-2015 Sebastian Deiss, all rights reserved.
#
# This file is a part of QR2Auth.
#
# QR2Auth is free software; you can redistribute it and/or modify it under the
# terms of the MIT licensee. For further information see LICENSE.txt in the
# parent folder.
#
# This module contains some helper functio... | def is_ascii(s):
"""
Check if a string contains only ASCII characters.
:param str s: The string to check
:return: Returns True if the string contains only ASCII characters
otherwise False
:rtype: bool
"""
return all((ord(c) < 128 for c in s))
def is_integer(s):
"""
Che... |
# -*- coding: utf-8 -*-
description = 'Eulerian cradle'
group = 'lowlevel'
includes = ['system', 'motorbus1', 'motorbus2', 'motorbus5']
excludes = ['euler']
devices = dict(
st_echi = device('nicos.devices.vendor.ipc.Motor',
bus = 'motorbus2',
addr = 61,
slope = 200,
unit = 'deg'... | description = 'Eulerian cradle'
group = 'lowlevel'
includes = ['system', 'motorbus1', 'motorbus2', 'motorbus5']
excludes = ['euler']
devices = dict(st_echi=device('nicos.devices.vendor.ipc.Motor', bus='motorbus2', addr=61, slope=200, unit='deg', abslimits=(-1000000, 1000000), zerosteps=500000, visibility=()), co_echi=d... |
# uke, I Am Your ...
# Luke Skywalker has family and friends. Help him remind them who is who. Given a string with a name, return the relation of that person to Luke.
# Person Relation
# Darth Vader father
# Leia sister
# Han brother in law
# R2D2 droid
def relation_to_luke(name):
d1 = {"Darth Vader": "father", "Lei... | def relation_to_luke(name):
d1 = {'Darth Vader': 'father', 'Leia': 'sister', 'Han': 'brother in law', 'R2D2': 'droid'}
return f'Luke, I am your {d1[name]}'
print(relation_to_luke('Darth Vader')) |
{
"targets": [
{
"target_name": "native_metrics",
"sources": [
"src/GcProfiler.cc",
"src/LoopProfiler.cc",
"src/LoopProfiler.hh",
"src/Metric.hh",
"src/ResourceProfiler.cc",
"src/ResourceProfiler.hh",
"src/native_metrics.cc"
],
"defines": [
"NOMINMAX"
],
"include_di... | {'targets': [{'target_name': 'native_metrics', 'sources': ['src/GcProfiler.cc', 'src/LoopProfiler.cc', 'src/LoopProfiler.hh', 'src/Metric.hh', 'src/ResourceProfiler.cc', 'src/ResourceProfiler.hh', 'src/native_metrics.cc'], 'defines': ['NOMINMAX'], 'include_dirs': ['src', '<!(node -e "require(\'nan\')")']}]} |
class Solution:
def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
dp = [[0]*n for _ in range(m)]
dp[i][j] = 1
total = 0
MOD = 1000000007
for _ in range(N):
temp = [[0]*n for _ in range(m)]
for r in range(m):
for c in r... | class Solution:
def find_paths(self, m: int, n: int, N: int, i: int, j: int) -> int:
dp = [[0] * n for _ in range(m)]
dp[i][j] = 1
total = 0
mod = 1000000007
for _ in range(N):
temp = [[0] * n for _ in range(m)]
for r in range(m):
for ... |
# dataset settings
data_root = 'data/jhmdb/JHMDB'
dataset_type_val = 'JHMDBDataset'
data_prefix_val = 'data/jhmdb/JHMDB/Frames'
anno_prefix_val = 'data/jhmdb/JHMDB/joint_positions'
ann_file_val = 'data/jhmdb/JHMDB/jhmdb_val_split_1_rawframes.txt'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.... | data_root = 'data/jhmdb/JHMDB'
dataset_type_val = 'JHMDBDataset'
data_prefix_val = 'data/jhmdb/JHMDB/Frames'
anno_prefix_val = 'data/jhmdb/JHMDB/joint_positions'
ann_file_val = 'data/jhmdb/JHMDB/jhmdb_val_split_1_rawframes.txt'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=Fals... |
#!/usr/bin/python3
if __name__ == "__main__":
# open text file to read
file = open('write_file.txt', 'r')
# read the second line from the file
file.seek(53)
data = file.read()
print(data)
file.close() | if __name__ == '__main__':
file = open('write_file.txt', 'r')
file.seek(53)
data = file.read()
print(data)
file.close() |
class Person:
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def greet(person):
if person.gender == 'M' and person.age < 18:
title = 'Master'
elif person.gender == 'M':
title = 'Mr.'
else:
title = 'Ms.'
return f"Hello {title} ... | class Person:
def __init__(self, n, a, g):
self.name = n
self.age = a
self.gender = g
def greet(person):
if person.gender == 'M' and person.age < 18:
title = 'Master'
elif person.gender == 'M':
title = 'Mr.'
else:
title = 'Ms.'
return f'Hello {title}... |
def solution(digits):
# return max(int(digits[a:a + 5]) for a in xrange(len(digits) - 4))
# code below only calls int once
return int(max(digits[a:a + 5] for a in xrange(len(digits) - 4)))
| def solution(digits):
return int(max((digits[a:a + 5] for a in xrange(len(digits) - 4)))) |
def calculate_area(l, w):
if (isinstance(l, str) or isinstance(w, str)):
raise ValueError
if l < 0 or w < 0:
raise ValueError
return l* w | def calculate_area(l, w):
if isinstance(l, str) or isinstance(w, str):
raise ValueError
if l < 0 or w < 0:
raise ValueError
return l * w |
#one line version of is_palindrome.py
def one_is_palindrome(string):
if string == string[::-1]: return True
else: return False
if __name__ == '__main__':
if one_is_palindrome("racecar") == True: print("true")
else: print("false") | def one_is_palindrome(string):
if string == string[::-1]:
return True
else:
return False
if __name__ == '__main__':
if one_is_palindrome('racecar') == True:
print('true')
else:
print('false') |
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Solution using for and append in a new list
evens = []
odds = []
for i in original_list:
if i % 2 == 0:
evens.append(i)
else:
odds.append(i)
# Solution using slicing
# evens = original_list[1::2]
# odds = original_list[::2]
# Solution using filter... | original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = []
odds = []
for i in original_list:
if i % 2 == 0:
evens.append(i)
else:
odds.append(i)
print(f'evens: {evens}')
print(f'odds: {odds}') |
alti=input("Enter the altitude:")
altitude=int(alti)
if altitude<=1000:
print("safe to land")
elif altitude > 1000 and altitude < 5000:
print("bring down to 1000")
elif altitude>5000:
print("turn around") | alti = input('Enter the altitude:')
altitude = int(alti)
if altitude <= 1000:
print('safe to land')
elif altitude > 1000 and altitude < 5000:
print('bring down to 1000')
elif altitude > 5000:
print('turn around') |
# numRows = 1, 2, 3, 4, 5, 6 ...
# Gap = 1, 2, 4, 6, 8, 10 ...
def convert(s: str, numRows: int) -> str:
if not s or len(s) == 0:
return ""
if numRows == 1:
return s
result = ""
gap = 2 * (numRows - 1)
for row in range(numRows):
start = 0
... | def convert(s: str, numRows: int) -> str:
if not s or len(s) == 0:
return ''
if numRows == 1:
return s
result = ''
gap = 2 * (numRows - 1)
for row in range(numRows):
start = 0
while start + row < len(s):
result += s[row + start]
if row != 0 and... |
_base_ = [
'../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py'
]
model = dict(
roi_head=dict(
_delete_=True,
type='KeypointCascadeRoIHead',
output_heatmaps=False,
keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4),
... | _base_ = ['../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py']
model = dict(roi_head=dict(_delete_=True, type='KeypointCascadeRoIHead', output_heatmaps=False, keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), num_keypoints=5, num_stages=3, stage_loss_weig... |
COLOR_SPACE = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF]
def _color_get_place(byte_1):
if byte_1 == 0xff:
return 5
for index, i in enumerate(COLOR_SPACE):
if i > byte_1:
return index - (1 if byte_1 - COLOR_SPACE[index - 1] <= i - byte_1 else 0)
def color(byte_3):
if byte_3%0xa0a0a ... | color_space = [0, 95, 135, 175, 215, 255]
def _color_get_place(byte_1):
if byte_1 == 255:
return 5
for (index, i) in enumerate(COLOR_SPACE):
if i > byte_1:
return index - (1 if byte_1 - COLOR_SPACE[index - 1] <= i - byte_1 else 0)
def color(byte_3):
if byte_3 % 657930 == 526344... |
# for loop in python
# here we iterate through the string we defined
for item in 'pooya':
print(item)
# iterate through the array
for index in ['pooya', 'amir', 'flix']:
print(index)
for indexer in [1,2,3,4,5,6]:
print(indexer)
# range start from 0 to range < desire number, here is ten
for i in range(10):
pr... | for item in 'pooya':
print(item)
for index in ['pooya', 'amir', 'flix']:
print(index)
for indexer in [1, 2, 3, 4, 5, 6]:
print(indexer)
for i in range(10):
print(i)
for j in range(2, 10, 2):
print(j)
prices = [6, 22, 33]
total = 0
for price in prices:
total += price
print(f'the Total is: {total}... |
#
# @lc app=leetcode id=81 lang=python3
#
# [81] Search in Rotated Sorted Array II
#
# https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/
#
# algorithms
# Medium (33.48%)
# Likes: 1879
# Dislikes: 551
# Total Accepted: 288.3K
# Total Submissions: 861.1K
# Testcase Example: '[2,5,6,0,0,1... | class Solution:
def search(self, nums: List[int], target: int) -> bool:
if not nums or len(nums) == 0:
return False
(left, right) = (0, len(nums) - 1)
while left + 1 < right:
mid = (left + right) // 2
if target == nums[mid]:
return True
... |
# Zigzag String
# https://www.interviewbit.com/problems/zigzag-string/
#
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P.......A........H.......N
# ..A..P....L....S....I...I....G
# ....Y.... | class Solution:
def convert(self, A, B):
res = [''] * B
if B == 1:
return A
(direction, i) = (True, 0)
for a in A:
res[i] += a
if direction and i == B - 1:
direction = False
elif not direction and i == 0:
... |
{
'name': 'Chapter 07, Recipe 5 code',
'summary': 'Write tests for your module using Python unit tests',
'depends': ['my_module'], # from Chapter 3
}
| {'name': 'Chapter 07, Recipe 5 code', 'summary': 'Write tests for your module using Python unit tests', 'depends': ['my_module']} |
# yapf:disable
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
])
# yapf:enable
checkpoint_config = dict(interval=50)
evaluation = dict(by_epoch=True, metric='accuracy', interval=5)
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflo... | log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
checkpoint_config = dict(interval=50)
evaluation = dict(by_epoch=True, metric='accuracy', interval=5)
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
pin_memory = True
use_infinite_sam... |
{
"targets": [{
"target_name": "fstream-addon",
"sources": [
"main.cc",
],
'include_dirs': [
"<!@(node -p \"require('node-addon-api').include\")"
],
'libraries': [],
'dependencies': [
"<!(node -p \"require('node-addon-api').... | {'targets': [{'target_name': 'fstream-addon', 'sources': ['main.cc'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': [], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'configurations': {'Release': {'msvs_settings': {'VCCLCompilerTool': {'RuntimeTypeInfo': 'true... |
# Source : https://leetcode.com/problems/maximum-ascending-subarray-sum/
# Author : foxfromworld
# Date : 24/10/2021
# Second attempt
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
ret, temp = 0, 0
for i in range(len(nums)):
if nums[i] <= nums[i-1]:
... | class Solution:
def max_ascending_sum(self, nums: List[int]) -> int:
(ret, temp) = (0, 0)
for i in range(len(nums)):
if nums[i] <= nums[i - 1]:
temp = 0
temp += nums[i]
ret = max(temp, ret)
return ret
class Solution:
def max_ascendin... |
# TODO: db_uri
# dialect+driver://username:password@host:port/database?charset=utf8
DB_URI = 'mysql+pymysql://root:root123@127.0.0.1:3300/flask_migrate_demo?charset=utf8'
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
| db_uri = 'mysql+pymysql://root:root123@127.0.0.1:3300/flask_migrate_demo?charset=utf8'
sqlalchemy_database_uri = DB_URI
sqlalchemy_track_modifications = False |
print("TEA5767 FM Radio project")
print("dipto@linuxcircle.com")
print("Excellent codes will be uploaded here!")
| print('TEA5767 FM Radio project')
print('dipto@linuxcircle.com')
print('Excellent codes will be uploaded here!') |
'''
Problem Statement : Even Fibonacci numbers
Link : https://projecteuler.net/problem=2
score : accepted
'''
n1 = 0
n2 = 1
term = 1
next_term = n1+n2
even_sum = 0
while next_term < 4000000:
next_term = n1+n2
if next_term%2==0:
even_sum += next_term
n1 = n2
n2 = next_term
term += 1
print(ev... | """
Problem Statement : Even Fibonacci numbers
Link : https://projecteuler.net/problem=2
score : accepted
"""
n1 = 0
n2 = 1
term = 1
next_term = n1 + n2
even_sum = 0
while next_term < 4000000:
next_term = n1 + n2
if next_term % 2 == 0:
even_sum += next_term
n1 = n2
n2 = next_term
term += 1
p... |
while True:
a,b=map(int,input().split())
if a==0 and b==0:
break
else:
print(a+b) | while True:
(a, b) = map(int, input().split())
if a == 0 and b == 0:
break
else:
print(a + b) |
#!/usr/bin/env python
class ThingToMakeDynamic():
pass
def __init__(self):
self.a = "a"
obj = ThingToMakeDynamic()
print("object created and only has {0} attribute".format(len(vars(obj))))
for key in vars(obj):
print(key, " -> ",getattr(obj,key))
print("check for 'a'")
print("a -> ",getattr... | class Thingtomakedynamic:
pass
def __init__(self):
self.a = 'a'
obj = thing_to_make_dynamic()
print('object created and only has {0} attribute'.format(len(vars(obj))))
for key in vars(obj):
print(key, ' -> ', getattr(obj, key))
print("check for 'a'")
print('a -> ', getattr(obj, 'a'))
print("check f... |
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
n = len(timeSeries)
if n == 0: return 0
total = sum(min(timeSeries[i + 1] - timeSeries[i], duration) for i in range(n - 1))
return total + duration
| class Solution:
def find_poisoned_duration(self, timeSeries: List[int], duration: int) -> int:
n = len(timeSeries)
if n == 0:
return 0
total = sum((min(timeSeries[i + 1] - timeSeries[i], duration) for i in range(n - 1)))
return total + duration |
def maximumStones(arr):
odd_sum = even_sum = 0
for i,a in enumerate(arr):
if i%2==0:
even_sum+=a
else:
odd_sum+=a
return 2*min(odd_sum, even_sum)
input()
arr=list(map(int, input().split()))
print(maximumStones(arr)) | def maximum_stones(arr):
odd_sum = even_sum = 0
for (i, a) in enumerate(arr):
if i % 2 == 0:
even_sum += a
else:
odd_sum += a
return 2 * min(odd_sum, even_sum)
input()
arr = list(map(int, input().split()))
print(maximum_stones(arr)) |
list = ['abc','uvw', 'xyz']
print(f"input is: {list}")
#By simple Method
element = []
def reverse_list(l):
for i in list:
element.append(i[::-1])
return element
print(f"By simple Method: {reverse_list(list)}")
#By comprehension Method
new_element = [i[::-1] for i in list]
print(f"By comprehension Meth... | list = ['abc', 'uvw', 'xyz']
print(f'input is: {list}')
element = []
def reverse_list(l):
for i in list:
element.append(i[::-1])
return element
print(f'By simple Method: {reverse_list(list)}')
new_element = [i[::-1] for i in list]
print(f'By comprehension Method: {new_element}') |
def makeAnagram(a, b):
buffer = [0] * 26
for char in a:
buffer[ord(char) - ord('a')] += 1
for char in b:
buffer[ord(char) - ord('a')] -= 1
return sum(map(abs, buffer)) | def make_anagram(a, b):
buffer = [0] * 26
for char in a:
buffer[ord(char) - ord('a')] += 1
for char in b:
buffer[ord(char) - ord('a')] -= 1
return sum(map(abs, buffer)) |
# -*- coding: utf-8 -*-
'''
Executors Directory
'''
FUNCTION_EXECUTORS = set(('direct_call.get', 'sudo.get'))
class ModuleExecutorBase(object):
'''
Base class for module executors.
Each executor implementation have to override this class and have corresponding get function that creates the
executor o... | """
Executors Directory
"""
function_executors = set(('direct_call.get', 'sudo.get'))
class Moduleexecutorbase(object):
"""
Base class for module executors.
Each executor implementation have to override this class and have corresponding get function that creates the
executor object.
"""
def __... |
def d(n: int):
result = n
for i in str(n):
result += int(i)
return result
table = [True for i in range(10001)]
for i in range(1, 10001):
result = d(i)
if 1 <= result <= 10000:
table[d(i)] = False
for i in range(1, 10001):
if table[i]:
print(i)
| def d(n: int):
result = n
for i in str(n):
result += int(i)
return result
table = [True for i in range(10001)]
for i in range(1, 10001):
result = d(i)
if 1 <= result <= 10000:
table[d(i)] = False
for i in range(1, 10001):
if table[i]:
print(i) |
def distance(base_strand, compare_strand):
count = 0
for base_char in range(0, len(base_strand)):
count = count + (base_strand[base_char] is not compare_strand[base_char])
#adds one to count if the characters are not equal
return count | def distance(base_strand, compare_strand):
count = 0
for base_char in range(0, len(base_strand)):
count = count + (base_strand[base_char] is not compare_strand[base_char])
return count |
g_api_key = "xxxxxx"
g_secret_key = "xxxxxx"
g_sub_uid = 123456
g_account_id = 123456
| g_api_key = 'xxxxxx'
g_secret_key = 'xxxxxx'
g_sub_uid = 123456
g_account_id = 123456 |
class BaseTimeInterval:
seconds = NotImplemented
multiplier = NotImplemented
def get_seconds(self):
return self.seconds
class NaiveTimeInterval(BaseTimeInterval):
def __init__(self, amount):
self.seconds = amount * self.multiplier
class Seconds(NaiveTimeInterval):
multiplier = ... | class Basetimeinterval:
seconds = NotImplemented
multiplier = NotImplemented
def get_seconds(self):
return self.seconds
class Naivetimeinterval(BaseTimeInterval):
def __init__(self, amount):
self.seconds = amount * self.multiplier
class Seconds(NaiveTimeInterval):
multiplier = 1
... |
description = 'Slits'
group = 'lowlevel'
tango_base = 'tango://motorbox03.spodi.frm2.tum.de:10000/box/'
devices = dict(
# Monochromator slit
slitm_u = device('nicos.devices.generic.Axis',
description = 'Monochromator slit upper blade',
motor = 'slitm_u_m',
coder = 'slitm_u_c',
... | description = 'Slits'
group = 'lowlevel'
tango_base = 'tango://motorbox03.spodi.frm2.tum.de:10000/box/'
devices = dict(slitm_u=device('nicos.devices.generic.Axis', description='Monochromator slit upper blade', motor='slitm_u_m', coder='slitm_u_c', precision=0.01, lowlevel=True), slitm_u_m=device('nicos.devices.tango.Mo... |
class Solution:
def mySqrt(self, x: int) -> int:
if x <= 1:return x
left, right = 1, x
while left<=right:
mid = left + (right-left)//2
if mid*mid>x:
right = mid-1
else:
left = mid+1
return left-1 | class Solution:
def my_sqrt(self, x: int) -> int:
if x <= 1:
return x
(left, right) = (1, x)
while left <= right:
mid = left + (right - left) // 2
if mid * mid > x:
right = mid - 1
else:
left = mid + 1
r... |
# Runtime: 28 ms, faster than 67.93% of Python3 online submissions for Unique Binary Search Trees.
# Memory Usage: 13.9 MB, less than 10.71% of Python3 online submissions for Unique Binary Search Trees.
class Solution:
def numTrees(self, n: int) -> int:
'''Recursion with memoization
Time: O(n^2)
... | class Solution:
def num_trees(self, n: int) -> int:
"""Recursion with memoization
Time: O(n^2)
Space: O(n)
"""
cache = {}
def num_trees(n):
if n == 0:
return 1
if n not in cache:
cache[n] = 0
fo... |
#!/usr/bin/env python3
def find_paths(connections, visited):
paths = 0
if visited[-1] == 'end':
print(f'Found path: {visited}')
return 1 # we found one path
for c in connections[visited[-1]]:
# once you leave the start cave, you can never return to it
if c == 'start':
... | def find_paths(connections, visited):
paths = 0
if visited[-1] == 'end':
print(f'Found path: {visited}')
return 1
for c in connections[visited[-1]]:
if c == 'start':
continue
if c.islower() and c in visited:
skip = False
for node in connect... |
def fromLines(laneLines):
state = 'NoLane'
if laneLines.left and laneLines.right:
state = 'Lane'
elif laneLines.left:
state = 'LeftOnly'
elif laneLines.right:
state = 'RightOnly'
return state
| def from_lines(laneLines):
state = 'NoLane'
if laneLines.left and laneLines.right:
state = 'Lane'
elif laneLines.left:
state = 'LeftOnly'
elif laneLines.right:
state = 'RightOnly'
return state |
#Create a Time class and initialize it with hours and minutes.
#1. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)
#2. Make a method displayTime which should print the time.
#3. Make a method DisplayMinute which should display the to... | class Time:
def __init__(self, hours: int, minutes: int):
self.hours = hours
self.minutes = minutes
def add_time(t1, t2):
t3 = time(0, 0)
if t1.minutes + t2.minutes > 60:
t3.hours = t3.hours + 1 + t1.hours + t2.hours
t3.minutes = t2.minutes + t1.minutes ... |
# dataset settings
dataset_type = 'VOC'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(typ... | dataset_type = 'VOC'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='RandomResizedCrop', size=224), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Normalize', **img_norm_cfg), dict(type... |
def main():
a = Trackable('1')
b = Trackable('2')
a = b # '1' object is no longer needed
b = Trackable('3') # '2' is referred by 'a' variable
del b # '3' object is no longer needed
a # '2' object will be freed when the function ends
if __name__ == '__main__':
main()
print('END')
| def main():
a = trackable('1')
b = trackable('2')
a = b
b = trackable('3')
del b
a
if __name__ == '__main__':
main()
print('END') |
(x1, y1) = map(int, input().split(" "))
(x2, y2) = map(int, input().split(" "))
(x3, y3) = map(int, input().split(" "))
(x4, y4) = map(int, input().split(" "))
#print(y1, y2, y3, y4, x1, x4, x2, x3)
if (y1 == y4 and y2 == y3 and x1 == x2 and x3 == x4):
print("yes")
else:
print("no")
| (x1, y1) = map(int, input().split(' '))
(x2, y2) = map(int, input().split(' '))
(x3, y3) = map(int, input().split(' '))
(x4, y4) = map(int, input().split(' '))
if y1 == y4 and y2 == y3 and (x1 == x2) and (x3 == x4):
print('yes')
else:
print('no') |
class PersonaHandler(object):
def __init__(self, owner):
self.owner = owner
| class Personahandler(object):
def __init__(self, owner):
self.owner = owner |
# -*- coding: utf-8 -*-
class Config(object):
def __init__(self, bigdata=False):
self.epochs = 100
self.lmbda = 0.01
self.decay = 0.96
if bigdata:
self.batch_size = 50
self.eta = 0.2
self.interval = 10
self.ftrain = 'bigdata/train.co... | class Config(object):
def __init__(self, bigdata=False):
self.epochs = 100
self.lmbda = 0.01
self.decay = 0.96
if bigdata:
self.batch_size = 50
self.eta = 0.2
self.interval = 10
self.ftrain = 'bigdata/train.conll'
self.fdev... |
n, m = map(int, input().split())
coins = list(map(int, input().split()))
dp = [1]+[0]*n
for i in range(m):
for j in range(coins[i], n+1):
dp[j] += dp[j-coins[i]]
print(dp[-1])
| (n, m) = map(int, input().split())
coins = list(map(int, input().split()))
dp = [1] + [0] * n
for i in range(m):
for j in range(coins[i], n + 1):
dp[j] += dp[j - coins[i]]
print(dp[-1]) |
def ps1a():
# retrive user input
annual_salary = int(input("Enter your annual salary: "))
portion_saved = float(
input("Enter the percent of your salary to save, as decimal: ")
)
total_cost = int(input("Enter the cost of your dream home:"))
# initialize some state variables
portion_... | def ps1a():
annual_salary = int(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percent of your salary to save, as decimal: '))
total_cost = int(input('Enter the cost of your dream home:'))
portion_down_payment = 0.25
current_savings = 0
r = 0.04
monthly_salary = ... |
x = 35e3
y = 12e4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
| x = 35000.0
y = 120000.0
z = -8.77e+101
print(type(x))
print(type(y))
print(type(z)) |
def myPrint(n):
for i in range(0,n):
print("moo"*n) #side effect
return ("moo"*n) #return value
# recursive function
def ask_recursively(question):
print(question)
reply = input("> ").lower()
if reply=="yes":
return True
if reply=="no":
return False
else:
print("please answer yes or no")
ask_recursi... | def my_print(n):
for i in range(0, n):
print('moo' * n)
return 'moo' * n
def ask_recursively(question):
print(question)
reply = input('> ').lower()
if reply == 'yes':
return True
if reply == 'no':
return False
else:
print('please answer yes or no')
as... |
def encode(json, schema):
payload = schema.Main()
payload.basics = schema.Basics()
payload.basics.name = json['basics']['name']
payload.basics.label = json['basics']['label']
payload.basics.picture = json['basics']['picture']
payload.basics.email = json['basics']['email']
payload.basics.pho... | def encode(json, schema):
payload = schema.Main()
payload.basics = schema.Basics()
payload.basics.name = json['basics']['name']
payload.basics.label = json['basics']['label']
payload.basics.picture = json['basics']['picture']
payload.basics.email = json['basics']['email']
payload.basics.phon... |
# This file was automatically generated on 2020-04-30T19:04:34.711463
# by script /code/nc/extract_nc/ansi_escape_code.py
# from ANSI escape codes
COLORS = {
'Black': (0, 0, 0),
'Red': (127, 0, 0),
'Green': (0, 147, 0),
'Yellow': (252, 127, 0),
'Blue': (0, 0, 127),
'Magenta': (156, 0, 156),
... | colors = {'Black': (0, 0, 0), 'Red': (127, 0, 0), 'Green': (0, 147, 0), 'Yellow': (252, 127, 0), 'Blue': (0, 0, 127), 'Magenta': (156, 0, 156), 'Cyan': (0, 147, 147), 'White': (210, 210, 210), 'Bright Black': (127, 127, 127), 'Bright Red': (255, 0, 0), 'Bright Green': (0, 252, 0), 'Bright Yellow': (255, 255, 0), 'Brigh... |
# import mongoengine
def global_init():
mongoengine.register_connection(alias='core', name='snake_bnb')
| def global_init():
mongoengine.register_connection(alias='core', name='snake_bnb') |
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# Revised BSD License, included in this distribution as LICENSE
PACKAGE_PREFIX = '_packages'
MATERIALIZED_DATA_PREFIX='_materialized_data'
| package_prefix = '_packages'
materialized_data_prefix = '_materialized_data' |
print("**Calcular Promedio Final")
#Datos de entrada
nota1=float(input("Ingrese nota 1:"))
nota2=float(input("Ingrese nota 2:"))
nota3=float(input("Ingrese nota 3:"))
nota4=float(input("Ingrese nota 4:"))
nota5=float(input("Ingrese nota 5:"))
nota6=float(input("Ingrese nota 6:"))
nota7=float(input("Ingrese nota 7:"))
#... | print('**Calcular Promedio Final')
nota1 = float(input('Ingrese nota 1:'))
nota2 = float(input('Ingrese nota 2:'))
nota3 = float(input('Ingrese nota 3:'))
nota4 = float(input('Ingrese nota 4:'))
nota5 = float(input('Ingrese nota 5:'))
nota6 = float(input('Ingrese nota 6:'))
nota7 = float(input('Ingrese nota 7:'))
prome... |
'''
even_odd_vending.py
Print whether the input is even or odd. If even, print the next 9 even numbers
If odd, print the next 9 odd numbers.
'''
def even_odd_vending(num):
if (num % 2) == 0:
print('Even')
else:
print('Odd')
count = 1
print(num)
while count <= 9:
num += 2
... | """
even_odd_vending.py
Print whether the input is even or odd. If even, print the next 9 even numbers
If odd, print the next 9 odd numbers.
"""
def even_odd_vending(num):
if num % 2 == 0:
print('Even')
else:
print('Odd')
count = 1
print(num)
while count <= 9:
num += 2
... |
def rename_groups(
adata, key_added, restrict_key, restrict_categories, restrict_indices, groups
):
key_added = restrict_key + '_R' if key_added is None else key_added
all_groups = adata.obs[restrict_key].astype('U')
prefix = '-'.join(restrict_categories) + ','
new_groups = [prefix + g for g in grou... | def rename_groups(adata, key_added, restrict_key, restrict_categories, restrict_indices, groups):
key_added = restrict_key + '_R' if key_added is None else key_added
all_groups = adata.obs[restrict_key].astype('U')
prefix = '-'.join(restrict_categories) + ','
new_groups = [prefix + g for g in groups.ast... |
flags = {
'AAA': {'undefined': ['OF', 'SF', 'ZF', 'PF'], 'defined': ['AF', 'CF'], 'setted': [], 'modified': ['OF', 'SF', 'ZF', 'AF', 'PF', 'CF'], 'tested': ['AF'], 'cleared': []} ,
'AAD': {'undefined': ['OF', 'AF', 'CF'], 'defined': ['SF', 'ZF', 'PF'], 'setted': [], 'modified': ['OF', 'SF', 'ZF', 'AF', 'PF', 'CF'], '... | flags = {'AAA': {'undefined': ['OF', 'SF', 'ZF', 'PF'], 'defined': ['AF', 'CF'], 'setted': [], 'modified': ['OF', 'SF', 'ZF', 'AF', 'PF', 'CF'], 'tested': ['AF'], 'cleared': []}, 'AAD': {'undefined': ['OF', 'AF', 'CF'], 'defined': ['SF', 'ZF', 'PF'], 'setted': [], 'modified': ['OF', 'SF', 'ZF', 'AF', 'PF', 'CF'], 'test... |
def add(x,y):
#add 2 numbers
return x + y
def subtract(x, y):
#subtract 2 numbers
return y - x
| def add(x, y):
return x + y
def subtract(x, y):
return y - x |
def similarity(a, b):
return a==b
| def similarity(a, b):
return a == b |
# Undirected Graph from demo represented as Adjacency List
graph = {
"a": [("b", 7), ("c", 9), ("f", 14)],
"b": [("a", 7), ("c", 10), ("d", 15)],
"c": [("a", 9), ("b", 10), ("d", 11), ("f", 2)],
"d": [("b", 15), ("c", 11), ("e", 6)],
"e": [("d", 6), ("f", 9)],
"f": [("a", 14), ("c", 2), ("e", 9... | graph = {'a': [('b', 7), ('c', 9), ('f', 14)], 'b': [('a', 7), ('c', 10), ('d', 15)], 'c': [('a', 9), ('b', 10), ('d', 11), ('f', 2)], 'd': [('b', 15), ('c', 11), ('e', 6)], 'e': [('d', 6), ('f', 9)], 'f': [('a', 14), ('c', 2), ('e', 9)]}
def find_vertices():
return graph.keys()
def find_edges():
edges = []
... |
def set_conditional_tape(self, awg_nr, tape_nr, tape):
'''
set the conditional tape content for an awg
@param awg : the awg of the dac, (0,1,2).
@param tape_nr : the number of the tape, integer ranging (0~6)
@param tape : the array of entries, with a maximum number of entries 512.
Every ent... | def set_conditional_tape(self, awg_nr, tape_nr, tape):
"""
set the conditional tape content for an awg
@param awg : the awg of the dac, (0,1,2).
@param tape_nr : the number of the tape, integer ranging (0~6)
@param tape : the array of entries, with a maximum number of entries 512.
Every ent... |
def bar(a, b):
pass
bar(1, 3)
bar(1, b=3)
bar(1, 2) | def bar(a, b):
pass
bar(1, 3)
bar(1, b=3)
bar(1, 2) |
for_sale_category = {
"antiques": "ata",
"appliances": "ppa",
"arts+crafts": "ara",
"atv/utv/sno": "sna",
"auto parts": "pta wta",
"baby+kids": "baa",
"barter": "bar",
"beauty+hlth": "haa",
"bikes": "bia bip",
"boats": "boo bpa",
"books": "bka",
"business": "bfa",
"ca... | for_sale_category = {'antiques': 'ata', 'appliances': 'ppa', 'arts+crafts': 'ara', 'atv/utv/sno': 'sna', 'auto parts': 'pta wta', 'baby+kids': 'baa', 'barter': 'bar', 'beauty+hlth': 'haa', 'bikes': 'bia bip', 'boats': 'boo bpa', 'books': 'bka', 'business': 'bfa', 'cars+trucks': 'cta', 'cds/dvd/vhs': 'ema', 'cell phones... |
#!/usr/bin/env python
#
# Licence statement goes here
#
tosca_ordered_fields = ['tosca_definitions_version', 'description', 'metadata', 'policy_types', 'topology_template']
| tosca_ordered_fields = ['tosca_definitions_version', 'description', 'metadata', 'policy_types', 'topology_template'] |
n=600851475143
for i in range(2,n):
if n%i==0:
n=int(n/i)
print(f'{i}, {n}')
if n==1:
break | n = 600851475143
for i in range(2, n):
if n % i == 0:
n = int(n / i)
print(f'{i}, {n}')
if n == 1:
break |
class UnoError(Exception):
def __init__(self,valor):
self.valorError = valor
def __str__(self):
print("no se puede dividir entre 1 el numero",self.valorError)
print("Hola")
e= 5
h=1
n=2
try:
print(0/n)
if(n==2):
raise UnoError(e) #Lanzar el error creado
except ... | class Unoerror(Exception):
def __init__(self, valor):
self.valorError = valor
def __str__(self):
print('no se puede dividir entre 1 el numero', self.valorError)
print('Hola')
e = 5
h = 1
n = 2
try:
print(0 / n)
if n == 2:
raise uno_error(e)
except UnoError:
print('Error cre... |
class A:
def __init__(self, a: int):
self.a = a
def __lt__(self, other):
return self.a < other.a
class B:
def __init__(self) -> None:
self.b = 1
def __gt__(self, other):
return self.b > other.b
def __lt__(self, other):
return self.b < other.b
a1: ... | class A:
def __init__(self, a: int):
self.a = a
def __lt__(self, other):
return self.a < other.a
class B:
def __init__(self) -> None:
self.b = 1
def __gt__(self, other):
return self.b > other.b
def __lt__(self, other):
return self.b < other.b
a1: A = a()... |
uctable = [ [ 225, 155, 174 ],
[ 225, 155, 175 ],
[ 225, 155, 176 ],
[ 226, 133, 160 ],
[ 226, 133, 161 ],
[ 226, 133, 162 ],
[ 226, 133, 163 ],
[ 226, 133, 164 ],
[ 226, 133, 165 ],
[ 226, 133, 166 ],
[ 226, 133, 167 ],
[ 226, 133, 168 ],
[ 226, 133, 169 ],
[ 226, 133, 170 ],
[ 226, 133, 17... | uctable = [[225, 155, 174], [225, 155, 175], [225, 155, 176], [226, 133, 160], [226, 133, 161], [226, 133, 162], [226, 133, 163], [226, 133, 164], [226, 133, 165], [226, 133, 166], [226, 133, 167], [226, 133, 168], [226, 133, 169], [226, 133, 170], [226, 133, 171], [226, 133, 172], [226, 133, 173], [226, 133, 174], [22... |
#! /usr/bin/env python3.4
def ask_ok(prompt,retries=4,complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries = retries -1
if retries <= 0:
... | def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries <= 0:
raise io_error('... |
# Author: Bradley Reeves <bradleyaaronreeves@gmail.com>
# Date: October 18, 2020
# About: Converts a Tanagra tree description from HTML
# to a usable format.
# chained dictionary class
# set a dict value given a key list
class Chain_Dict(dict):
def set_value(self, key_list, value):
... | class Chain_Dict(dict):
def set_value(self, key_list, value):
""" Parameters
----------
self: Chain Dict object
key_list: list of dict indexes
value: string to insert at key_list
Returns
-------
None
"""
t... |
#
# PySNMP MIB module CISCO-ATM2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
i = 0
while (i <= 100):
if((i % 2) == 1):
print(i)
i += 1
| i = 0
while i <= 100:
if i % 2 == 1:
print(i)
i += 1 |
def create_table(name: str, **collumns) -> str:
result: str = f"CREATE TABLE IF NOT EXISTS `{name}`("
for collumn, types in collumns.items():
result += f"{collumn} {types.upper()}, "
result = result[:-2] + ");"
return result
def insert(table: str, **collumns) -> str:
part1: str = f"INSERT ... | def create_table(name: str, **collumns) -> str:
result: str = f'CREATE TABLE IF NOT EXISTS `{name}`('
for (collumn, types) in collumns.items():
result += f'{collumn} {types.upper()}, '
result = result[:-2] + ');'
return result
def insert(table: str, **collumns) -> str:
part1: str = f'INSERT... |
def headleft():
i01.head.rothead.attach()
i01.head.rothead.moveTo(180)
sleep(1)
i01.detach()
| def headleft():
i01.head.rothead.attach()
i01.head.rothead.moveTo(180)
sleep(1)
i01.detach() |
db.define_table('page_visit_count',
Field('page_name'),
Field('counter', 'integer'),
)
db.define_table('page_visit_data',
Field('page_name'),
Field('last_visited','datetime'),
Field('args'),
Field('vars'),
) | db.define_table('page_visit_count', field('page_name'), field('counter', 'integer'))
db.define_table('page_visit_data', field('page_name'), field('last_visited', 'datetime'), field('args'), field('vars')) |
a = int(input())
b = int(input())
t = 0
v = 0
if b > a:
for x in range(a+1, b):
if x % 2 != 0:
t = t + x
print(t)
if a > b:
for x in range(b +1, a):
if x % 2 != 0:
v = v + x
print(v)
if a == b:
print(0)
| a = int(input())
b = int(input())
t = 0
v = 0
if b > a:
for x in range(a + 1, b):
if x % 2 != 0:
t = t + x
print(t)
if a > b:
for x in range(b + 1, a):
if x % 2 != 0:
v = v + x
print(v)
if a == b:
print(0) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def maxTree(node):
if node is None:
... | class Solution:
def is_balanced(self, root: TreeNode) -> bool:
def max_tree(node):
if node is None:
return 0
left = max_tree(node.left)
right = max_tree(node.right)
if abs(left - right) > 1 or left == -1 or right == -1:
return... |
class StratifiedThermalField:
def write(self, generator, case, staggering):
g = generator
g.w.build(
outputs=[case.path('0', theta) for theta in staggering.thetaOutputs()],
rule=staggering.stratifiedThetaRule,
implicit=case.polyMesh + case.systemFiles ... | class Stratifiedthermalfield:
def write(self, generator, case, staggering):
g = generator
g.w.build(outputs=[case.path('0', theta) for theta in staggering.thetaOutputs()], rule=staggering.stratifiedThetaRule, implicit=case.polyMesh + case.systemFiles + staggering.thetaInits(case) + [case.environmen... |
def matrix_to_str(matrix):
s = ''
for row in matrix:
for elem in row:
s += (str(elem) + ' ')
s += "\n"
return s
def get_spiral_matrix(n):
x, y, dx, dy, m = 0, 0, 0, 1, [[0] * n for _ in range(n)]
for i in range(n * n):
m[x][y] = str(i + 1)
if x + dx >= ... | def matrix_to_str(matrix):
s = ''
for row in matrix:
for elem in row:
s += str(elem) + ' '
s += '\n'
return s
def get_spiral_matrix(n):
(x, y, dx, dy, m) = (0, 0, 0, 1, [[0] * n for _ in range(n)])
for i in range(n * n):
m[x][y] = str(i + 1)
if x + dx >= ... |
# function without a name
x = 0
getx = lambda: x
def xman():
return x
| x = 0
getx = lambda : x
def xman():
return x |
# -*- coding: utf-8 -*-
__author__ = 'Alexander Filatov'
__email__ = 'alexander@kriegspiel.org'
__version__ = '1.0.0rc2'
| __author__ = 'Alexander Filatov'
__email__ = 'alexander@kriegspiel.org'
__version__ = '1.0.0rc2' |
class Seq2SeqLSTM():
def __init__(self, batch_size=64, epochs=10, latent_dim=256,lstm_dim=64,lr=0.001, Prints=False):
#epsilon: fuzzy factor.
self.batch_size = batch_size #maximal number of texts or text pairs in the single mini-batch (positive integer).
self.epochs ... | class Seq2Seqlstm:
def __init__(self, batch_size=64, epochs=10, latent_dim=256, lstm_dim=64, lr=0.001, Prints=False):
self.batch_size = batch_size
self.epochs = epochs
self.latent_dim = latent_dim
self.lstm_dim = lstm_dim
self.lr = lr
self.Prints = Prints
sel... |
def HammingDistance(Text,Text2):
#defines variables to be used
n = len(Text)
k = 1
j=0
#goes through both sequences and increments j by one every time there's a mismatch
for i in range(n):
MatchPattern1 = Text[i:i + k]
MatchPattern2 = Text2[i:i + k]
if MatchPattern1 != MatchP... | def hamming_distance(Text, Text2):
n = len(Text)
k = 1
j = 0
for i in range(n):
match_pattern1 = Text[i:i + k]
match_pattern2 = Text2[i:i + k]
if MatchPattern1 != MatchPattern2:
j = j + 1
return j
text = 'ATA'
text2 = 'AAT'
print(hamming_distance(Text, Text2)) |
class Test:
def wait(self):
self.test()
class SubTest:
def test(self):
pass
| class Test:
def wait(self):
self.test()
class Subtest:
def test(self):
pass |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task7_w1
def solution( i ):
return str(i)
if __name__ == "__main__":
print('----------start------------')
i = -4366
print(solution( i ))
print('------------end------------')
| def solution(i):
return str(i)
if __name__ == '__main__':
print('----------start------------')
i = -4366
print(solution(i))
print('------------end------------') |
class OriginChannels():
def __init__(self, fhdhr, origin):
self.fhdhr = fhdhr
self.origin = origin
def get_channels(self):
channel_list = []
return channel_list
def get_channel_stream(self, chandict):
streamurl = ""
return streamurl
| class Originchannels:
def __init__(self, fhdhr, origin):
self.fhdhr = fhdhr
self.origin = origin
def get_channels(self):
channel_list = []
return channel_list
def get_channel_stream(self, chandict):
streamurl = ''
return streamurl |
#!/usr/bin/env python
# coding=utf-8
class ConfigAbstract(object):
SQLALCHEMY_DATABASE = {
'ENGINE': 'postgresql',
'NAME': None,
'NAME_TESTING': None,
'USER': None,
'PASSWORD': None,
'HOST': 'localhost',
'PORT': None,
}
pass
| class Configabstract(object):
sqlalchemy_database = {'ENGINE': 'postgresql', 'NAME': None, 'NAME_TESTING': None, 'USER': None, 'PASSWORD': None, 'HOST': 'localhost', 'PORT': None}
pass |
#
# PySNMP MIB module CISCO-ERM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ERM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:40:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def Intensifiers(object):
object.tokens.Token.set_extension("is_INTENSADV1", getter = lambda token: token.text.lower() in ('absolutely', 'absurdly', 'resoundingly', 'amazingly', 'awfully', 'extremely', 'completely', 'highly', 'incredibly', 'perfectly', 'quite', 'reall... | def intensifiers(object):
object.tokens.Token.set_extension('is_INTENSADV1', getter=lambda token: token.text.lower() in ('absolutely', 'absurdly', 'resoundingly', 'amazingly', 'awfully', 'extremely', 'completely', 'highly', 'incredibly', 'perfectly', 'quite', 'really', 'strikingly', 'surprisingly', 'terribly', 'tot... |
def insertion_sort(array):
for i in range(1, len(array)):
temp = array[i]
j = i-1
while j >= 0 and temp < array[j]:
array[j+1] = array[j]
j = j-1
array[j+1] = temp
| def insertion_sort(array):
for i in range(1, len(array)):
temp = array[i]
j = i - 1
while j >= 0 and temp < array[j]:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = temp |
def merge_dict(d1, d2):
for k, v in d2.items():
d1[k] = v
return d1
def deep_merge_dict(d1, d2):
for k, v in d2.items():
v1 = d1.get(k)
v2 = d2.get(k)
new_v = deep_merge(v1, v2)
d1[k] = new_v
return d1
def deep_merge(v1, v2):
if isinstance(v1, list) and i... | def merge_dict(d1, d2):
for (k, v) in d2.items():
d1[k] = v
return d1
def deep_merge_dict(d1, d2):
for (k, v) in d2.items():
v1 = d1.get(k)
v2 = d2.get(k)
new_v = deep_merge(v1, v2)
d1[k] = new_v
return d1
def deep_merge(v1, v2):
if isinstance(v1, list) and ... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jun 4, 2015
# Question: 043-Multiply-Strings
# Link: https://leetcode.com/problems/multiply-strings/
# ==================================================================... | class Solution:
def multiply(self, num1, num2):
return str(int(num1) * int(num2)) |
def pascal(row: int, col: int):
if (row == 1):
return 1
if (col == 1 or row == col):
return 1
return pascal(row - 1, col - 1) + pascal(row - 1, col)
def pascal_row(n: int):
return list(map(lambda i: pascal(n, i), range(1, n+1)))
def test_pascal():
assert pascal_row(1) == [1]
... | def pascal(row: int, col: int):
if row == 1:
return 1
if col == 1 or row == col:
return 1
return pascal(row - 1, col - 1) + pascal(row - 1, col)
def pascal_row(n: int):
return list(map(lambda i: pascal(n, i), range(1, n + 1)))
def test_pascal():
assert pascal_row(1) == [1]
asse... |
{
"includes": [ "common.gypi" ],
"targets": [
{
"target_name": "sweepjs",
"sources": [ "sweepjs.cc" ],
"xcode_settings": {
"GCC_ENABLE_CPP_RTTI": "YES",
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"MACOSX_DEPLOYMENT_TARGET": "10... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'sweepjs', 'sources': ['sweepjs.cc'], 'xcode_settings': {'GCC_ENABLE_CPP_RTTI': 'YES', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'MACOSX_DEPLOYMENT_TARGET': '10.8', 'CLANG_CXX_LIBRARY': 'libc++', 'CLANG_CXX_LANGUAGE_STANDARD': 'c++11', 'GCC_VERSION': 'com.apple.compil... |
# defines maximum steps of programs
max_step = 16
# maximum number of parameters + program id
max_param = 7 + 1
# the id of stop sign
stop_id = 22
# number of effective parameters for each program
num_params = [0,
6, 6, 5, 5, 6,
5, 5, 5, 5, 6,
6, 6, 6, 6, 7,
6, 7... | max_step = 16
max_param = 7 + 1
stop_id = 22
num_params = [0, 6, 6, 5, 5, 6, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 6, 7, 6, 4, 2, 0]
max_for_step = 20
for_step = 3 |
playerGuess = input("What color is the alien(green/red/yellow)? ")
points = 0
if playerGuess == 'green':
points = 5
else:
points = 10
print(f"Your shoot a {playerGuess} alien and got {points} points") | player_guess = input('What color is the alien(green/red/yellow)? ')
points = 0
if playerGuess == 'green':
points = 5
else:
points = 10
print(f'Your shoot a {playerGuess} alien and got {points} points') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.