content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
fig, ax = plt.subplots()
im = ax.pcolor(grouped_pivot, cmap='RdBu')
#label names
row_labels = grouped_pivot.columns.levels[1]
col_labels = grouped_pivot.index
#move ticks and labels to the center
ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5,... | (fig, ax) = plt.subplots()
im = ax.pcolor(grouped_pivot, cmap='RdBu')
row_labels = grouped_pivot.columns.levels[1]
col_labels = grouped_pivot.index
ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5, minor=False)
ax.set_xticklabels(row_labels, minor... |
def sayhello(name):
return "Hello, " + name + ", nice to meet you!"
if __name__ == "__main__":
print(sayhello(input("What is your name? ")))
| def sayhello(name):
return 'Hello, ' + name + ', nice to meet you!'
if __name__ == '__main__':
print(sayhello(input('What is your name? '))) |
# using cube coordinates: https://www.redblobgames.com/grids/hexagons/
def update(tile, command):
x, y, z = tile
if command == 'w':
x -= 1
y += 1
elif command == 'e':
x += 1
y -= 1
elif command == 'nw':
y += 1
z -= 1
elif command == 'se':
y -= ... | def update(tile, command):
(x, y, z) = tile
if command == 'w':
x -= 1
y += 1
elif command == 'e':
x += 1
y -= 1
elif command == 'nw':
y += 1
z -= 1
elif command == 'se':
y -= 1
z += 1
elif command == 'ne':
x += 1
z -... |
# Demo Python For Loops - The range() Function
'''
The range() Function - Part 2
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
'''
# Using the start parameter:
for ... | """
The range() Function - Part 2
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
"""
for x in range(2, 7):
print(x) |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | def create__thrift_unicode_decode_error_from__unicode_decode_error(error, field_name):
if isinstance(error, ThriftUnicodeDecodeError):
error.field_names.append(field_name)
return error
return thrift_unicode_decode_error(error.encoding, error.object, error.start, error.end, error.reason, field_na... |
class Enactor:
def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location,
sftp_directory):
pass
def stop(self):
pass
def enact_light_plan(self, dev, BL_Quota, NL_Quota):
return True
def enact_socket_plan(self, dev... | class Enactor:
def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location, sftp_directory):
pass
def stop(self):
pass
def enact_light_plan(self, dev, BL_Quota, NL_Quota):
return True
def enact_socket_plan(self, dev, AC_total):
... |
class Solution:
def reverse(self, x: int):
flag = 0
minus = "-"
if x < 0:
flag = 1
x = x * -1
result= str(x)
result = ''.join(reversed(result))
x = int(result)
if flag == 1:
x = x * -1
if x > 2147... | class Solution:
def reverse(self, x: int):
flag = 0
minus = '-'
if x < 0:
flag = 1
x = x * -1
result = str(x)
result = ''.join(reversed(result))
x = int(result)
if flag == 1:
x = x * -1
if x > 2147483647 or x < -214... |
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1 = [int(x) for x in version1.split('.')]
v2 = [int(x) for x in version2.split('.')]
while v1 and v1[-1] == 0:
v1.pop()
while v2 and v2[-1] == 0:
v2.pop()
if v1 < v2:
... | class Solution:
def compare_version(self, version1: str, version2: str) -> int:
v1 = [int(x) for x in version1.split('.')]
v2 = [int(x) for x in version2.split('.')]
while v1 and v1[-1] == 0:
v1.pop()
while v2 and v2[-1] == 0:
v2.pop()
if v1 < v2:
... |
def star(N):
for i in range(0,N):
for j in range(0,i+1):
print("*",end = "")
print("\r")
if __name__ == '__main__':
N = int(input())
star(N)
| def star(N):
for i in range(0, N):
for j in range(0, i + 1):
print('*', end='')
print('\r')
if __name__ == '__main__':
n = int(input())
star(N) |
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return self.height(root) != -1
def height(self, root):
if not root:
return 0
lh = self.height(root.right)
if lh == -1:
return -1
rh = self.height(root.left)
if rh == -1:
... | class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.height(root) != -1
def height(self, root):
if not root:
return 0
lh = self.height(root.right)
if lh == -1:
return -1
rh = self.height(root.left)
if rh == -1:
... |
class Metrics:
listMetric = {}
def addMetric(self, metric):
self.listMetric[metric.getName()] = metric.getData()
def getMetrics(self):
return self.listMetric | class Metrics:
list_metric = {}
def add_metric(self, metric):
self.listMetric[metric.getName()] = metric.getData()
def get_metrics(self):
return self.listMetric |
# coding: utf-8
class Maxipago(object):
def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False):
self.maxid = maxid
self.api_key = api_key
self.api_version = api_version
self.sandbox = sandbox
def __getattr__(self, name):
try:
class_name ... | class Maxipago(object):
def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False):
self.maxid = maxid
self.api_key = api_key
self.api_version = api_version
self.sandbox = sandbox
def __getattr__(self, name):
try:
class_name = ''.join([n.title... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Defines different rounding options for binary search.'''
# todo: Confirm that `*_IF_BOTH` options are used are used in all places that
# currently ~use them.
class Rounding:
'''Base class for rounding options for binary sea... | """Defines different rounding options for binary search."""
class Rounding:
"""Base class for rounding options for binary search."""
class Both(Rounding):
"""
Get a tuple `(low, high)` of the 2 items that surround the specified value.
If there's an exact match, gives it twice in the tuple, i.e. `... |
expected_output = {
"interfaces": {
"GigabitEthernet1/0/1": {
"name": "foo bar",
"down_time": "00:00:00",
"up_time": "4d5h",
},
}
} | expected_output = {'interfaces': {'GigabitEthernet1/0/1': {'name': 'foo bar', 'down_time': '00:00:00', 'up_time': '4d5h'}}} |
data = [
[0, 'Does your animal fly?', 1, 2],
[1, 'Is your flying animal a bird?', 3, 4],
[2, 'Does your animal live underwater?', 7, 8],
[3, 'Is your bird native to Australia?', 5, 6],
[4, 'Is it a fruit bat?'],
[5, 'Is it a kookaburra?'],
[6, 'Is it a blue jay?'],
[7, 'Is your animal a ... | data = [[0, 'Does your animal fly?', 1, 2], [1, 'Is your flying animal a bird?', 3, 4], [2, 'Does your animal live underwater?', 7, 8], [3, 'Is your bird native to Australia?', 5, 6], [4, 'Is it a fruit bat?'], [5, 'Is it a kookaburra?'], [6, 'Is it a blue jay?'], [7, 'Is your animal a mammal?', 9, 10], [8, 'Is it a wo... |
def riverSizes(matrix):
# Write your code here.
if not matrix:
return []
sizes=[]
visited=[[False for values in row] for row in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if visited[i][j]:
continue
getSize(i,j,visited,matrix,sizes)
return sizes
def getSi... | def river_sizes(matrix):
if not matrix:
return []
sizes = []
visited = [[False for values in row] for row in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if visited[i][j]:
continue
get_size(i, j, visited, matrix, sizes)
... |
# G00364712 Robert Higgins - Exercise 2
# Collatz Conjecture https://en.wikipedia.org/wiki/Collatz_conjecture
nStr = input("Enter a positive integer:")
n = int(nStr)
while n > 1:
if n % 2 == 0:
n = n/2
print(int(n))
else:
n = (3*n) + 1
print(int(n))
# Output below for user inp... | n_str = input('Enter a positive integer:')
n = int(nStr)
while n > 1:
if n % 2 == 0:
n = n / 2
print(int(n))
else:
n = 3 * n + 1
print(int(n)) |
def functie(l,n):
for a in range(1,n+1):
l.append(a**n)
list=[]
n = int(input("n = "))
functie(list,n)
print(list)
| def functie(l, n):
for a in range(1, n + 1):
l.append(a ** n)
list = []
n = int(input('n = '))
functie(list, n)
print(list) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( A , arr_size , sum ) :
for i in range ( 0 , arr_size - 1 ) :
s = set ( )
curr_sum = sum - A [ i... | def f_gold(A, arr_size, sum):
for i in range(0, arr_size - 1):
s = set()
curr_sum = sum - A[i]
for j in range(i + 1, arr_size):
if curr_sum - A[j] in s:
print('Triplet is', A[i], ', ', A[j], ', ', curr_sum - A[j])
return True
s.add(A[j]... |
# ------- MAIN SETTINGS ----------- #
SQLITE_DB_PATH = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite'
JSON_DATA_FILENAME = 'pp.json'
MASTER_JSON_FILENAME = 'master.json'
STOP_COUNT = 2
# ------- STORAGE SETTINGS ----------- #
INPUT_STORE_DIRECTORY = u'/Users/sidhshar/Downloads/photodirip'
OUTPUT_STORE_DIRECTORY ... | sqlite_db_path = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite'
json_data_filename = 'pp.json'
master_json_filename = 'master.json'
stop_count = 2
input_store_directory = u'/Users/sidhshar/Downloads/photodirip'
output_store_directory = u'/Users/sidhshar/Downloads/photodirop'
type_jpg_family = ('jpg', 'jpeg')
type_video... |
def make_key(*args):
return "ti:" + ":".join(args)
def make_refset_key(pmid):
return make_key("article", pmid, "refset") | def make_key(*args):
return 'ti:' + ':'.join(args)
def make_refset_key(pmid):
return make_key('article', pmid, 'refset') |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Find an element in a sorted array that has been rotated a num... | class Array(object):
def search_sorted_array(self, array, val):
if array is None or val is None:
raise type_error('array or val cannot be None')
if not array:
return None
return self._search_sorted_array(array, val, start=0, end=len(array) - 1)
def _search_sorte... |
def iterable(source):
def callbag(start, sink):
if (start != 0):
return
for i in source:
sink(1, i)
return callbag | def iterable(source):
def callbag(start, sink):
if start != 0:
return
for i in source:
sink(1, i)
return callbag |
'''1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
Sample data:
/*
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70
*/ '''
X = [10, 20, 20, 20]
Y = [... | """1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
Sample data:
/*
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70
*/ """
x = [10, 20, 20, 20]
y = [... |
def request_numbers():
numbers = []
for n in range(3):
number = float(input("Number: "))
numbers.append(number)
return numbers
def main():
numbers = request_numbers()
ordered = list(sorted(numbers))
if numbers == ordered:
print("Aumentando")
elif numbers == ordered[... | def request_numbers():
numbers = []
for n in range(3):
number = float(input('Number: '))
numbers.append(number)
return numbers
def main():
numbers = request_numbers()
ordered = list(sorted(numbers))
if numbers == ordered:
print('Aumentando')
elif numbers == ordered[:... |
##
## Karkinos - b0bb
##
## https://twitter.com/0xb0bb
## https://github.com/0xb0bb/karkinos
##
MAJOR_VERSION = 0
MINOR_VERSION = 2
KARKINOS_VERSION = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION)
| major_version = 0
minor_version = 2
karkinos_version = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION) |
#!/usr/bin/env python3
if __name__ == '__main__':
numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8... | if __name__ == '__main__':
numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8, 8], [6], [2, 5, 4], [7... |
SEPN = f"\n{'=' * 40}"
SEP = f"{SEPN}\n"
QUERY_SPLIT_SIZE = 5000
SEQUENCE = 'sequence'
TABLE = 'table'
PRIMARY = 'primary'
UNIQUE = 'unique'
FOREIGN = 'foreign'
| sepn = f"\n{'=' * 40}"
sep = f'{SEPN}\n'
query_split_size = 5000
sequence = 'sequence'
table = 'table'
primary = 'primary'
unique = 'unique'
foreign = 'foreign' |
# Numbers in Python can be of two types: Integers and Floats
# They're very important as many ML algorithms can only deal
# with numbers and will ignore/crash on any other kind of input
# because they're based complex math algorithms
# Integers have unbound size in Python 3!
lucky_number = 13
universe_number = 42
# ... | lucky_number = 13
universe_number = 42
pi = 3.14
a_third = 0.333
times_two = lucky_number * 2
square = universe_number ** 2
mod = 3 % 2
radius = 50
area_of_circle = pi * radius ** 2
print(area_of_circle) |
# Runs all 1d datasets.
Experiment(description='Run all 1D datasets',
data_dir='../data/1d_data/',
max_depth=8,
random_order=False,
k=2,
debug=False,
local_computation=True,
n_rand=3,
sd=4,
max_jobs=500,
... | experiment(description='Run all 1D datasets', data_dir='../data/1d_data/', max_depth=8, random_order=False, k=2, debug=False, local_computation=True, n_rand=3, sd=4, max_jobs=500, verbose=True, make_predictions=False, skip_complete=True, results_dir='../results/Feb 10 1D results/', iters=200) |
# 1.2 Palindrome Tester
def is_palindrome(input_string):
length = len(input_string)
palindrome = True
for i in range(0, length // 2):
if input_string[i] != input_string[length - i - 1]:
palindrome = False
return palindrome
| def is_palindrome(input_string):
length = len(input_string)
palindrome = True
for i in range(0, length // 2):
if input_string[i] != input_string[length - i - 1]:
palindrome = False
return palindrome |
class Gurney:
def greeting(self):
print('welcome to Simple Calculator Alpha 0.1')
def main(self):
firstNumber = float(input('Enter your first number: '))
operator = float(input('enter your operator: '))
secondNumber = float(input('Enter your third number:'))
if (ope... | class Gurney:
def greeting(self):
print('welcome to Simple Calculator Alpha 0.1')
def main(self):
first_number = float(input('Enter your first number: '))
operator = float(input('enter your operator: '))
second_number = float(input('Enter your third number:'))
if operat... |
symbology = 'code93'
cases = [
('001.png', 'CODE93', dict(includetext=True)),
('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True)),
]
| symbology = 'code93'
cases = [('001.png', 'CODE93', dict(includetext=True)), ('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True))] |
class Solution:
def minimumDeletions(self, s: str) -> int:
n = len(s)
a = 0
res = 0
for i in range(n - 1, -1, -1):
if s[i] == 'a':
a += 1
elif s[i] == 'b':
if a > 0:
a -= 1
res += 1
... | class Solution:
def minimum_deletions(self, s: str) -> int:
n = len(s)
a = 0
res = 0
for i in range(n - 1, -1, -1):
if s[i] == 'a':
a += 1
elif s[i] == 'b':
if a > 0:
a -= 1
res += 1
... |
num1=100
num2=200
num3=300
a
b
c
1
2
3
ttttt
e
f
g
9
8
7
| num1 = 100
num2 = 200
num3 = 300
a
b
c
1
2
3
ttttt
e
f
g
9
8
7 |
#Find the Runner-Up Score!
if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
arr=sorted(arr)
a=arr[0]
b=arr[0]
for i in range(1,n):
if(arr[i]==a):
pass
elif(arr[i]>a):
a=arr[i]
b=arr[i-1]
print(b) | if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
arr = sorted(arr)
a = arr[0]
b = arr[0]
for i in range(1, n):
if arr[i] == a:
pass
elif arr[i] > a:
a = arr[i]
b = arr[i - 1]
print(b) |
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
| access_token = ''
access_token_secret = ''
consumer_key = ''
consumer_secret = '' |
SECRET_KEY = '\xa6\xbaG\x80\xc9-$s\xd5~\x031N\x8f\xd9/\x88\xd0\xba#B\x9c\xcd_'
DEBUG = False
DB_HOST = 'localhost'
DB_USER = 'grupo35'
DB_PASS = 'OTRiYWJhYjU3YWMy'
DB_NAME = 'grupo35'
SQLALCHEMY_DATABASE_URI = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35'
SQLALCHEMY_TRACK_MODIFICATIONS = False | secret_key = '¦ºG\x80É-$sÕ~\x031N\x8fÙ/\x88к#B\x9cÍ_'
debug = False
db_host = 'localhost'
db_user = 'grupo35'
db_pass = 'OTRiYWJhYjU3YWMy'
db_name = 'grupo35'
sqlalchemy_database_uri = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35'
sqlalchemy_track_modifications = False |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
out = []
self.traverse(root, out)
return out
... | class Solution:
def inorder_traversal(self, root: 'TreeNode') -> 'List[int]':
out = []
self.traverse(root, out)
return out
def traverse(self, root, out):
if root:
self.traverse(root.left, out)
out.append(root.val)
self.traverse(root.right, ou... |
# Created by MechAviv
# Quest ID :: 17620
# [Commerci Republic] Eye for an Eye
sm.setSpeakerID(9390217)
sm.sendNext("Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.")
sm.setSpeakerID(9390217)
sm.setPlayerAsSpeaker()
sm.sendSay("Can you introduce me to Gil... | sm.setSpeakerID(9390217)
sm.sendNext('Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.')
sm.setSpeakerID(9390217)
sm.setPlayerAsSpeaker()
sm.sendSay('Can you introduce me to Gilberto Daniella?')
sm.setSpeakerID(9390217)
sm.sendSay('I offer to make your wildes... |
#!/usr/bin/env python3
f = "day10.input.txt"
# f = "day10.ex.txt"
ns = open(f).read().strip().split("\n")
ns = [int(x) for x in ns]
ns.sort()
ns.insert(0, 0)
ns.append(max(ns) + 3)
def part1():
count1 = 0
count3 = 0
for i in range(len(ns) - 1):
diff = ns[i + 1] - ns[i]
if diff == 1:
count1 += 1... | f = 'day10.input.txt'
ns = open(f).read().strip().split('\n')
ns = [int(x) for x in ns]
ns.sort()
ns.insert(0, 0)
ns.append(max(ns) + 3)
def part1():
count1 = 0
count3 = 0
for i in range(len(ns) - 1):
diff = ns[i + 1] - ns[i]
if diff == 1:
count1 += 1
if diff == 3:
... |
def sub_dict(dic, *keys, **renames):
d1 = {k: v for k, v in dic.items() if k in keys}
d2 = {renames[k]: v for k, v in dic.items() if k in renames.keys()}
return d1 | d2
| def sub_dict(dic, *keys, **renames):
d1 = {k: v for (k, v) in dic.items() if k in keys}
d2 = {renames[k]: v for (k, v) in dic.items() if k in renames.keys()}
return d1 | d2 |
# TODO: Figure out if this is even being used...
class logging(object):
def __init__(self, arg):
super(logging, self).__init__()
self.arg = arg
| class Logging(object):
def __init__(self, arg):
super(logging, self).__init__()
self.arg = arg |
# https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python
def solution(args):
print(args)
i = j = 0
result = []
section = []
while i < len(args):
section.append(str(args[j]))
while j + 1 < len(args) and args[j] + 1 == args[j + 1]:
section.append(str(args... | def solution(args):
print(args)
i = j = 0
result = []
section = []
while i < len(args):
section.append(str(args[j]))
while j + 1 < len(args) and args[j] + 1 == args[j + 1]:
section.append(str(args[j + 1]))
j += 1
if len(section) > 2:
result... |
'''
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's n... | """
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's n... |
def is_a_leap_year(year):
if (year % 400 == 0):
return True
elif (year % 100 == 0):
return False
elif (year % 4 == 0):
return True
return False
def get_number_of_days(month, is_a_leap_year):
if (month == 4 or month == 6 or month == 9 or month == 11):
return 30
if... | def is_a_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
return False
def get_number_of_days(month, is_a_leap_year):
if month == 4 or month == 6 or month == 9 or (month == 11):
return 30
if month... |
class WordCount:
# @param {str} line a text, for example "Bye Bye see you next"
def mapper(self, _, line):
# Write your code here
# Please use 'yield key, value'
for word in line.split():
yield word, 1
# @param key is from mapper
# @param values is a set of value w... | class Wordcount:
def mapper(self, _, line):
for word in line.split():
yield (word, 1)
def reducer(self, key, values):
yield (key, sum(values)) |
CLIENT_ID = "affordability-c31256e5-39c4-4b20-905a-7500c583c591"
CLIENT_SECRET = "eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050"
API_BASE = "https://api.nordicapigateway.com/"
# If Python 2.x is used, only ASCII characters can be used in the values below.
SECRET_KEY = "0401" # for local session sto... | client_id = 'affordability-c31256e5-39c4-4b20-905a-7500c583c591'
client_secret = 'eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050'
api_base = 'https://api.nordicapigateway.com/'
secret_key = '0401'
userhash = 'test-user-id'
include_transaction_details = False |
MEDIA_INTENT = 'media'
FEELING_INTENTS = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep',
'smalltalk.appraisal.thank_you', 'smalltalk.user.good',
'smalltalk.user.happy', 'smalltalk.user.sad',
'smalltalk.appraisal.bad', 'smalltalk.agent.happy',
... | media_intent = 'media'
feeling_intents = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep', 'smalltalk.appraisal.thank_you', 'smalltalk.user.good', 'smalltalk.user.happy', 'smalltalk.user.sad', 'smalltalk.appraisal.bad', 'smalltalk.agent.happy', 'smalltalk.user.sick']
affirmation_intents = ['yes', 'correct', ... |
x1, v1, x2, v2 = map(int, input().strip().split(' '))
if v1 == v2:
print("NO")
else:
j = (x1 - x2) // (v2 - v1)
print("YES" if j > 0 and (x1+v1*j == x2+v2*j) else "NO")
| (x1, v1, x2, v2) = map(int, input().strip().split(' '))
if v1 == v2:
print('NO')
else:
j = (x1 - x2) // (v2 - v1)
print('YES' if j > 0 and x1 + v1 * j == x2 + v2 * j else 'NO') |
with open("meeting.in", "r") as inputFile:
numberOfFields, numberOfPaths = map(int, list(inputFile.readline().strip().split()))
paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()]
bessiepassable, elsiepassable = {str(i[0])+str(i[1]):i[2] for i in paths}, {str(i[0])+str(i[1]):i[3] f... | with open('meeting.in', 'r') as input_file:
(number_of_fields, number_of_paths) = map(int, list(inputFile.readline().strip().split()))
paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()]
(bessiepassable, elsiepassable) = ({str(i[0]) + str(i[1]): i[2] for i in paths}, {str(i[0]) + st... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
t = -1
for i in range(len(tokens)):
if tokens[i] == '+':
tokens[t - 1] += tokens[t]
t -= 1
elif tokens[i] == '-':
tokens[t - 1] -= tokens[t]
t... | class Solution:
def eval_rpn(self, tokens: List[str]) -> int:
t = -1
for i in range(len(tokens)):
if tokens[i] == '+':
tokens[t - 1] += tokens[t]
t -= 1
elif tokens[i] == '-':
tokens[t - 1] -= tokens[t]
t -= 1
... |
def rotate(A, B, C):
return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0])
def jarvismarch(A):
points_count = len(A)
processing_indexes = range(points_count)
# start point
for i in range(1, points_count):
if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]:
... | def rotate(A, B, C):
return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0])
def jarvismarch(A):
points_count = len(A)
processing_indexes = range(points_count)
for i in range(1, points_count):
if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]:
(processing_ind... |
class NodoAST:
def __init__(self, contenido):
self._contenido = contenido
self._hijos = []
def getContenido(self):
return self._contenido
def getHijos(self):
return self._hijos
def setHijo(self, hijo):
self._hijos.append(hijo) | class Nodoast:
def __init__(self, contenido):
self._contenido = contenido
self._hijos = []
def get_contenido(self):
return self._contenido
def get_hijos(self):
return self._hijos
def set_hijo(self, hijo):
self._hijos.append(hijo) |
#This program displays a date in the form
#(Month day, Year like March 12, 2014
#ALGORITHM in pseudocode
#1. get a date string in the form mm/dd/yyyy from the user
#2. use the split method to remove the seperator('/')
# and assign the results to a variable.
#3. determine the month the user entered
# if month is 0... | def main():
date_string = input('Enter a date in the form "mm/dd/yyyy": ')
date_list = get_date_list(date_string)
def get_date_list(date_string):
date_list = date_string.split('/')
mm = date_list[0]
if mm == '01':
mm = 'January'
elif mm == '02':
mm = 'February'
elif mm == '0... |
n1 = float(input('Valor do produto (R$): '))
n2 = float(input('Desconto em porcentagem (%): '))
d = n2/100
d1 = n1*d
nv = n1-d1
print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2,nv))
| n1 = float(input('Valor do produto (R$): '))
n2 = float(input('Desconto em porcentagem (%): '))
d = n2 / 100
d1 = n1 * d
nv = n1 - d1
print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2, nv)) |
mem_key_cache = 'cache'
mem_key_metadata = 'meta'
mem_key_sponsor = 'sponsor'
mem_key_total_open_source_spaces = 'oss'
mem_key_creeps_by_role = 'roles_alive'
mem_key_work_parts_by_role = 'roles_work'
mem_key_carry_parts_by_role = 'roles_carry'
mem_key_creeps_by_role_and_replacement_time = 'rt_map'
mem_key_prepping_defe... | mem_key_cache = 'cache'
mem_key_metadata = 'meta'
mem_key_sponsor = 'sponsor'
mem_key_total_open_source_spaces = 'oss'
mem_key_creeps_by_role = 'roles_alive'
mem_key_work_parts_by_role = 'roles_work'
mem_key_carry_parts_by_role = 'roles_carry'
mem_key_creeps_by_role_and_replacement_time = 'rt_map'
mem_key_prepping_defe... |
# -*- coding: utf-8 -*-
# Scrapy settings for watches project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topic... | bot_name = 'watches'
spider_modules = ['watches.spiders']
newspider_module = 'watches.spiders'
redirect_enabled = False
retry_times = 10
retry_http_codes = [500, 503, 504, 400, 403, 404, 408]
robotstxt_obey = False
download_delay = 0.2
cookies_enabled = False |
#!/usr/bin/env python
#######################################
# Installation module for eyewitness
#######################################
# AUTHOR OF MODULE NAME
AUTHOR="Kirk Hayes (l0gan)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update EyeWitness."
# INSTALL TYPE GIT, SVN, FILE DOWNLOAD
#... | author = 'Kirk Hayes (l0gan)'
description = 'This module will install/update EyeWitness.'
install_type = 'GIT'
repository_location = 'https://github.com/FortyNorthSecurity/EyeWitness'
install_location = 'eyewitness'
debian = 'git,python-setuptools,libffi-dev,libssl-dev'
after_commands = 'cd {INSTALL_LOCATION}Python/set... |
users = {'email1': 'password1'}
links = [ # fake array of posts
{
'author': 'users',
'date' : "04-08-2017",
'description': 'cool information site',
'link': 'https://www.wikipedia.org',
'tags': None
},
{
'author': 'user',
'date' : "06-08-2017",
... | users = {'email1': 'password1'}
links = [{'author': 'users', 'date': '04-08-2017', 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None}, {'author': 'user', 'date': '06-08-2017', 'description': "worst site I've ever used", 'link': 'www.facebook.org', 'tags': None}, {'author': 'user'... |
# OAuth app keys
DROPBOX_BUSINESS_FILEACCESS_KEY = None
DROPBOX_BUSINESS_FILEACCESS_SECRET = None
DROPBOX_BUSINESS_MANAGEMENT_KEY = None
DROPBOX_BUSINESS_MANAGEMENT_SECRET = None
DROPBOX_BUSINESS_AUTH_CSRF_TOKEN = 'dropboxbusiness-auth-csrf-token'
TEAM_FOLDER_NAME_FORMAT = '{title}_GRDM_{guid}' # available: {title} ... | dropbox_business_fileaccess_key = None
dropbox_business_fileaccess_secret = None
dropbox_business_management_key = None
dropbox_business_management_secret = None
dropbox_business_auth_csrf_token = 'dropboxbusiness-auth-csrf-token'
team_folder_name_format = '{title}_GRDM_{guid}'
group_name_format = 'GRDM_{guid}'
admin_g... |
colors = {
'default': (0, 'WHITE', 'BLACK', 'NORMAL'),
'title': (1, 'YELLOW', 'BLUE', 'BOLD'),
'status': (2, 'YELLOW', 'BLUE', 'BOLD'),
'error': (3, 'RED', 'BLACK', 'BOLD'),
'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD'),
}
| colors = {'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD')} |
#-----------------problem parameters-----------------------
depot = []
capacity = 120
time_dist_factor = 10 # time per job converted to distance
num_salesmen = 5
# ---------------------------------------------------------
population = 50
nodes = []
node_num = 0
gnd_truth_tsp = []
gnd_truth_dist_list... | depot = []
capacity = 120
time_dist_factor = 10
num_salesmen = 5
population = 50
nodes = []
node_num = 0
gnd_truth_tsp = []
gnd_truth_dist_list = []
gnd_truth_dist_from_depot = []
def print_error(msg):
print('ERROR: ' + msg)
exit() |
class MeuObjeto:
def __init__(self, id, nome, sobrenome):
self.id = id
self.nome = nome
self.sobrenome = sobrenome
| class Meuobjeto:
def __init__(self, id, nome, sobrenome):
self.id = id
self.nome = nome
self.sobrenome = sobrenome |
def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... | def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... |
fig, ax = plt.subplots()
ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue')
ax.set_xlabel('Zr [ppm]')
ax.set_ylabel('Likelihood of occurrence')
| (fig, ax) = plt.subplots()
ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue')
ax.set_xlabel('Zr [ppm]')
ax.set_ylabel('Likelihood of occurrence') |
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [can for can in heights if can > 161]
print(can_ride_coaster)
| heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [can for can in heights if can > 161]
print(can_ride_coaster) |
i = 1
while (i<=10):
print(i, end=" ")
i += 1
print()
| i = 1
while i <= 10:
print(i, end=' ')
i += 1
print() |
def my_function(*args, **kwargs):
for arg in args:
print('arg:', arg)
for key in kwargs.keys():
print('key:', key, 'has value: ', kwargs[key])
my_function('John', 'Denise', daughter='Phoebe', son='Adam')
print('-' * 50)
my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='Jame... | def my_function(*args, **kwargs):
for arg in args:
print('arg:', arg)
for key in kwargs.keys():
print('key:', key, 'has value: ', kwargs[key])
my_function('John', 'Denise', daughter='Phoebe', son='Adam')
print('-' * 50)
my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James'... |
class A:
def __init__(self):
print("A")
super().__init__()
class B1(A):
def __init__(self):
print("B1")
super().__init__()
class B2(A):
def __init__(self):
print("B2")
super().__init__()
class C(B1, A):
def __init__(self):
print("C")
sup... | class A:
def __init__(self):
print('A')
super().__init__()
class B1(A):
def __init__(self):
print('B1')
super().__init__()
class B2(A):
def __init__(self):
print('B2')
super().__init__()
class C(B1, A):
def __init__(self):
print('C')
... |
props.bf_Shank_Dia = 10.0
#props.bf_Pitch = 1.5 # Coarse
props.bf_Pitch = 1.25 # Fine
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 10.0
props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch)
props.bf_Hex_Head_Flat_Distance = 17.0
props.bf_Hex_Head_Height = 6.4
props.bf_Cap... | props.bf_Shank_Dia = 10.0
props.bf_Pitch = 1.25
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 10.0
props.bf_Minor_Dia = props.bf_Major_Dia - 1.082532 * props.bf_Pitch
props.bf_Hex_Head_Flat_Distance = 17.0
props.bf_Hex_Head_Height = 6.4
props.bf_Cap_Head_Dia = 16.0
props.bf_Cap_Head_Height... |
def dividedtimes(x):
if not isinstance(x, int):
raise TypeError('x must be integer.')
elif x <= 2:
raise ValueError('x must be greater than 2.')
counter = 0
while x >= 2:
x = x / 2
counter += 1
return counter
| def dividedtimes(x):
if not isinstance(x, int):
raise type_error('x must be integer.')
elif x <= 2:
raise value_error('x must be greater than 2.')
counter = 0
while x >= 2:
x = x / 2
counter += 1
return counter |
def bubbleSort(list):
for i in range(0,len(list)-1):
for j in range(0,len(list)-i-1):
if list[j] > list[j+1]:
print("\n%d > %d"%(list[j],list[j+1]))
(list[j], list[j+1]) = (list[j+1], list[j])
print("\nNext Pass\n")
print("\nThe elements are now sorted in ascending order:\n")
for i i... | def bubble_sort(list):
for i in range(0, len(list) - 1):
for j in range(0, len(list) - i - 1):
if list[j] > list[j + 1]:
print('\n%d > %d' % (list[j], list[j + 1]))
(list[j], list[j + 1]) = (list[j + 1], list[j])
print('\nNext Pass\n')
print('\nThe ele... |
# pylint: disable=missing-docstring,redefined-builtin,unsubscriptable-object
# pylint: disable=invalid-name,too-few-public-methods,attribute-defined-outside-init
class Repository:
def _transfer(self, bytes=-1):
self._bytesTransfered = 0
bufff = True
while bufff and (bytes < 0 or self._bytesT... | class Repository:
def _transfer(self, bytes=-1):
self._bytesTransfered = 0
bufff = True
while bufff and (bytes < 0 or self._bytesTransfered < bytes):
bufff = bufff[:bytes - self._bytesTransfered]
self._bytesTransfered += len(bufff) |
# Copyright 2016 Check Point Software Technologies LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | uri = 'https://te-api.checkpoint.com/tecloud/api/v1/file/'
token_uri = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external'
port = '18194'
remote_dir = 'tecloud/api/v1/file'
query = 'query'
upload = 'upload'
download = 'download'
query_selector = '%s%s' % (URI, QUERY)
upload_selector = '%s%s' % (URI, UPLOAD)
dow... |
g=[]
for a in range (1000):
if a%3==0 or a%5==0:
g.append(a)
print(sum(g))
| g = []
for a in range(1000):
if a % 3 == 0 or a % 5 == 0:
g.append(a)
print(sum(g)) |
#Strinping Names:
Person_name = " Chandler Bing "
print("Person Name with tab space :\t"+Person_name)
print("Person Name in new line :\n"+Person_name)
print("Person Name with space removed from left side :"+Person_name.lstrip())
print("Person Name with space removed from right side :"+Person_name.rstrip())
print("Pe... | person_name = ' Chandler Bing '
print('Person Name with tab space :\t' + Person_name)
print('Person Name in new line :\n' + Person_name)
print('Person Name with space removed from left side :' + Person_name.lstrip())
print('Person Name with space removed from right side :' + Person_name.rstrip())
print('Person Name wit... |
def divisibleSumPairs(n, k, ar):
count = 0
for i in range(len(ar)-1):
for j in range(i+1, len(ar)):
if (ar[i]+ar[j])%k == 0:
count += 1
return count
| def divisible_sum_pairs(n, k, ar):
count = 0
for i in range(len(ar) - 1):
for j in range(i + 1, len(ar)):
if (ar[i] + ar[j]) % k == 0:
count += 1
return count |
# Python3 Binary Tree to Doubly Linked List
# 10
# / \
# 12 15 ---> head ---> 25<->12<->30<->10<->36<->15
# / \ /
# 25 30 36
#
def tree2DLL(root, head):
if not root:
return
prev = None
tree2DLL(root.left)
if not prev:
head = prev
else:
root.left = prev
pr... | def tree2_dll(root, head):
if not root:
return
prev = None
tree2_dll(root.left)
if not prev:
head = prev
else:
root.left = prev
prev.right = root
prev = root |
class Synapse:
def __init__(self, label, input, weight, next_neurons):
self.label = label
self.input = input
self.weight = weight
self.next_neurons = next_neurons
| class Synapse:
def __init__(self, label, input, weight, next_neurons):
self.label = label
self.input = input
self.weight = weight
self.next_neurons = next_neurons |
'''
Created on 2020-09-10
@author: wf
'''
class Labels(object):
'''
NLTK labels
'''
default=['GPE','PERSON','ORGANIZATION']
geo=['GPE'] | """
Created on 2020-09-10
@author: wf
"""
class Labels(object):
"""
NLTK labels
"""
default = ['GPE', 'PERSON', 'ORGANIZATION']
geo = ['GPE'] |
'''
Substring Concatenation
Asked in: Facebook
https://www.interviewbit.com/problems/substring-concatenation/
You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any inter... | """
Substring Concatenation
Asked in: Facebook
https://www.interviewbit.com/problems/substring-concatenation/
You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any inter... |
def trunk_1(arr_1, size_1):
result_1 = []
while arr:
pop_data = [arr_1.pop(0) for _ in range(size_1)]
result_1.append(pop_data)
return result_1
def trunk_2(arr_2, size_2):
arrs = []
while len(arr_2) > size_2:
pice = arr_2[:size_2]
arrs.append(pice)
arr_2 = ... | def trunk_1(arr_1, size_1):
result_1 = []
while arr:
pop_data = [arr_1.pop(0) for _ in range(size_1)]
result_1.append(pop_data)
return result_1
def trunk_2(arr_2, size_2):
arrs = []
while len(arr_2) > size_2:
pice = arr_2[:size_2]
arrs.append(pice)
arr_2 = ar... |
#!/usr/bin/env python
if __name__ == "__main__":
print("Hello world from copied executable")
| if __name__ == '__main__':
print('Hello world from copied executable') |
data = open("day3.txt", "r").read().splitlines()
openSquare = data[0][0]
tree = data[0][6]
def howManyTrees(right, down):
position = right
iterator = down
trees = 0
openSquares = 0
for rowIterator in range(0, int((len(data))/down) - 1):
row = data[iterator]
res_row = row * 100
obstacle = res_... | data = open('day3.txt', 'r').read().splitlines()
open_square = data[0][0]
tree = data[0][6]
def how_many_trees(right, down):
position = right
iterator = down
trees = 0
open_squares = 0
for row_iterator in range(0, int(len(data) / down) - 1):
row = data[iterator]
res_row = row * 100
... |
n = int(input())
d = [[0,0,0] for i in range(n + 1)]
for i in range(1, n + 1):
(r, g, b) = [int(i) for i in input().split()]
d[i][0] = r + min(d[i - 1][1], d[i - 1][2])
d[i][1] = g + min(d[i - 1][0], d[i - 1][2])
d[i][2] = b + min(d[i - 1][0], d[i - 1][1])
print(min(d[n])) | n = int(input())
d = [[0, 0, 0] for i in range(n + 1)]
for i in range(1, n + 1):
(r, g, b) = [int(i) for i in input().split()]
d[i][0] = r + min(d[i - 1][1], d[i - 1][2])
d[i][1] = g + min(d[i - 1][0], d[i - 1][2])
d[i][2] = b + min(d[i - 1][0], d[i - 1][1])
print(min(d[n])) |
# Test passwords are randomly hashed
def test_passwords_hashed_randomly(test_app, test_database, add_user):
user_one = add_user(
"test_user_one", "test_user_one@mail.com", "test_password"
)
user_two = add_user(
"test_user_two", "test_user_two@mail.com", "test_password"
)
assert user... | def test_passwords_hashed_randomly(test_app, test_database, add_user):
user_one = add_user('test_user_one', 'test_user_one@mail.com', 'test_password')
user_two = add_user('test_user_two', 'test_user_two@mail.com', 'test_password')
assert user_one.password != user_two.password
assert user_one.password !=... |
# Defination for mathematical operation
def math(token_ip_stream,toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" :
... | def math(token_ip_stream, toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and (token_ip_stream[2][1] == '=') and (token_ip_stream[3][1] == toko[0][0]) and (token_ip_stream[5][1] == toko[1][0]) and (token_ip_stream[6][0] == 'STATEMENT_END'):
if token_ip_stream[4][1] == '+... |
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
# First way is brute force
def is_triplet(array):
# Base case, if array is under 3 elements, not possible
if len(array) < 3:
return False
# Iterate through first element... | def is_triplet(array):
if len(array) < 3:
return False
for i in range(len(array) - 2):
for j in range(i + 1, len(array) - 1):
for k in range(j, len(array)):
a = array[i] * array[i]
b = array[j] * array[j]
c = array[k] * array[k]
... |
climacell_yr_map = {
"6201": "48", # heavy freezing rain
"6001": "12", # freezing rain
"6200": "47", # light freezing rain
"6000": "47", # freeing drizzle
"7101": "48", # heavy ice pellets
"7000": "12", # ice pellets
"7102": "47", # light ice pellets
"5101": "50", # heavy snow
"5000... | climacell_yr_map = {'6201': '48', '6001': '12', '6200': '47', '6000': '47', '7101': '48', '7000': '12', '7102': '47', '5101': '50', '5000': '13', '5100': '49', '5001': '49', '8000': '11', '4201': '10', '4001': '09', '4200': '46', '4000': '46', '2100': '15', '2000': '15', '1001': '04', '1102': '03', '1101': '02', '1100'... |
# read answer, context, question
# generate vocabulary file for elmo batcher
pre = ['dev', 'train']
fs = ['answer', 'context', 'question']
result = set()
for p in pre:
for f in fs:
print ('Processing ' + p + '.' +f)
with open('../../data/' + p + '.' + f) as ff:
content = ff.readlines()
... | pre = ['dev', 'train']
fs = ['answer', 'context', 'question']
result = set()
for p in pre:
for f in fs:
print('Processing ' + p + '.' + f)
with open('../../data/' + p + '.' + f) as ff:
content = ff.readlines()
for line in content:
for token in line.split():
... |
'''
Insert 5 numbers in the right position without using .sort()
Then show the list orderned
'''
my_list = []
for c in range(0, 5):
num = int(input('Type a number: '))
if c == 0 or num > my_list[-1]:
my_list.append(num)
print('Add this number at the end.')
else:
pos = 0
while... | """
Insert 5 numbers in the right position without using .sort()
Then show the list orderned
"""
my_list = []
for c in range(0, 5):
num = int(input('Type a number: '))
if c == 0 or num > my_list[-1]:
my_list.append(num)
print('Add this number at the end.')
else:
pos = 0
while... |
# Wi-Fi Diagnostic Tree
print(' Please reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Make sure the cables between t... | print(' Please reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Make sure the cables between the router and modem are p... |
class Dictionary:
def __init__(self):
self.words = set()
def check(self, word):
return word.lower() in self.words
def load(self, dictionary):
file = open(dictionary, 'r')
for line in file:
self.words.add(line.rstrip('\n'))
file.close()
return True
def size(self):
return len(self.words)
def un... | class Dictionary:
def __init__(self):
self.words = set()
def check(self, word):
return word.lower() in self.words
def load(self, dictionary):
file = open(dictionary, 'r')
for line in file:
self.words.add(line.rstrip('\n'))
file.close()
return Tr... |
class Map:
def __init__(self, x, y):
self.wall = False
self.small_dot = False
self.big_dot = False
self.eaten = False
self.x = x
self.y = y
#--- drawing on map ---#
def draw_dot(self):
if self.small_dot:
if not self.eaten:
... | class Map:
def __init__(self, x, y):
self.wall = False
self.small_dot = False
self.big_dot = False
self.eaten = False
self.x = x
self.y = y
def draw_dot(self):
if self.small_dot:
if not self.eaten:
fill(255, 255, 0)
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = train # train, test, test_episodes, render
LOAD_MODEL_FROM = None
SAVE_MODELS_TO = models/debugging_wmg_dynamic_state_Collins2018_train10_test15.pth
# worker.py
ENV = Collins2018_Env
EN... | type_of_run = train
load_model_from = None
save_models_to = models / debugging_wmg_dynamic_state_Collins2018_train10_test15.pth
env = Collins2018_Env
env_random_seed = 2
agent_random_seed = 1
reporting_interval = 5000
total_steps = 10000000
anneal_lr = False
num_episodes_to_test = 5
agent_net = WMG_State_Network
v2 = F... |
class B:
pass
class A:
pass | class B:
pass
class A:
pass |
class Solution:
def maxScore(self, cards, k):
pre = [0]
for card in cards:
pre.append(pre[-1] + card)
ans = 0
n = len(pre)
for i in range(k + 1):
ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans)
return ans
| class Solution:
def max_score(self, cards, k):
pre = [0]
for card in cards:
pre.append(pre[-1] + card)
ans = 0
n = len(pre)
for i in range(k + 1):
ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans)
return ans |
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday):
#assert len(books) == len(L)
score = 0.
d = 0
for l in L:
d += L_signuptimes[l]
number_of_books = (D - d) * L_shipperday[l]
score += sum(books[l][:number_of_books])
return score
| def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday):
score = 0.0
d = 0
for l in L:
d += L_signuptimes[l]
number_of_books = (D - d) * L_shipperday[l]
score += sum(books[l][:number_of_books])
return score |
MESSAGE_PRIORITY = (
(-2, 'Stumm'),
(-1, 'Ruhig'),
(0, 'Normal'),
(1, 'Wichtig'),
(2, 'Emergency'),
) | message_priority = ((-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.