content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/parallels/catkin_ws/install/include".split(';') if "/home/parallels/catkin_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "cv_bridge;image_geometry;image_transport;camera_info_manager... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/parallels/catkin_ws/install/include'.split(';') if '/home/parallels/catkin_ws/install/include' != '' else []
project_catkin_depends = 'cv_bridge;image_geometry;image_transport;camera_info_manager;pcl_ros;roscpp;tf;visualization_msgs;std_msgs;tf2;messag... |
self.description = "Fileconflict file -> dir on package replacement (FS#24904)"
lp = pmpkg("dummy")
lp.files = ["dir/filepath",
"dir/file"]
self.addpkg2db("local", lp)
p1 = pmpkg("replace")
p1.provides = ["dummy"]
p1.replaces = ["dummy"]
p1.files = ["dir/filepath/",
"dir/filepath/file",
... | self.description = 'Fileconflict file -> dir on package replacement (FS#24904)'
lp = pmpkg('dummy')
lp.files = ['dir/filepath', 'dir/file']
self.addpkg2db('local', lp)
p1 = pmpkg('replace')
p1.provides = ['dummy']
p1.replaces = ['dummy']
p1.files = ['dir/filepath/', 'dir/filepath/file', 'dir/file', 'dir/file2']
self.ad... |
def find_lowest(lst):
# Return the lowest positive
# number in a list.
def lowest(first, rest):
# Base case
if len(rest) == 0:
return first
if first > rest[0] or first < 0:
return lowest(rest[0], rest[1:])
else:
return lowest(first, rest)
return lowest(lst[0], lst[1:])
a = [16,... | def find_lowest(lst):
def lowest(first, rest):
if len(rest) == 0:
return first
if first > rest[0] or first < 0:
return lowest(rest[0], rest[1:])
else:
return lowest(first, rest)
return lowest(lst[0], lst[1:])
a = [16, -6, 1, 6, 6]
print(find_lowest(a)... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"get_installed_dependencies": "00_checker.ipynb",
"check_new_version": "00_checker.ipynb"}
modules = ["checker.py"]
doc_url = "https://muellerzr.github.io/dependency_checker/"
git_url = "https://g... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'get_installed_dependencies': '00_checker.ipynb', 'check_new_version': '00_checker.ipynb'}
modules = ['checker.py']
doc_url = 'https://muellerzr.github.io/dependency_checker/'
git_url = 'https://github.com/muellerzr/dependency_checker/tree/master/'
... |
num = 600851475143
p = int(num**0.5) + 1
factors = []
def addToFactors(x):
for f in factors:
if not x % f:
return
factors.append(x)
for i in range(2, p):
if not num % i: addToFactors(i)
print(max(factors))
| num = 600851475143
p = int(num ** 0.5) + 1
factors = []
def add_to_factors(x):
for f in factors:
if not x % f:
return
factors.append(x)
for i in range(2, p):
if not num % i:
add_to_factors(i)
print(max(factors)) |
# https://codeforces.com/problemset/problem/230/B
n = int(input())
numbers = [int(x) for x in input().split()]
counter = 0
for number in numbers:
if number == 1 or number == 2:
print('NO')
continue
for x in range(2, number):
if counter > 1:
break
if number % x == 0... | n = int(input())
numbers = [int(x) for x in input().split()]
counter = 0
for number in numbers:
if number == 1 or number == 2:
print('NO')
continue
for x in range(2, number):
if counter > 1:
break
if number % x == 0:
counter += 1
if counter == 1:
... |
# Default dt for the imaging
DEF_DT = 0.2
# Parameters for cropping around bouts:
PRE_INT_BT_S = 2 # before
POST_INT_BT_S = 6 # after
| def_dt = 0.2
pre_int_bt_s = 2
post_int_bt_s = 6 |
first_sequence = list(map(int, input().split()))
second_sequence = list(map(int, input().split()))
line = input()
while not line == 'nexus':
first_pair, second_pair = line.split('|')
first_list_index1, second_list_index1 = list(map(int, first_pair.split(':')))
first_list_index2, second_list_index2 = list(... | first_sequence = list(map(int, input().split()))
second_sequence = list(map(int, input().split()))
line = input()
while not line == 'nexus':
(first_pair, second_pair) = line.split('|')
(first_list_index1, second_list_index1) = list(map(int, first_pair.split(':')))
(first_list_index2, second_list_index2) = l... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
node_list = []
sentinel = head = ListNode(0, None)
... | class Solution:
def merge_k_lists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
node_list = []
sentinel = head = list_node(0, None)
for item in lists:
while item:
node_list.append(item.val)
item = item.next
for item in sort... |
# https://leetcode.com/problems/fair-candy-swap/discuss/161269/C%2B%2BJavaPython-Straight-Forward
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
diff = (sum(A) - sum(B)) // 2
B = set(B)
A = set(A)
for b in B:
if b + diff in A:
... | class Solution:
def fair_candy_swap(self, A: List[int], B: List[int]) -> List[int]:
diff = (sum(A) - sum(B)) // 2
b = set(B)
a = set(A)
for b in B:
if b + diff in A:
return [b + diff, b] |
# create node class
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
# create stack
class Stack:
def __init__(self):
self.top = None
def isEmpty(self):
if self.top == None:
return True
else:
... | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
if self.top == None:
return True
else:
return False
def peek(self):
... |
# -*- coding: utf-8 -*-
class Hero(object):
def __init__(self, forename, surname, hero):
self.forename = forename
self.surname = surname
self.heroname = hero
| class Hero(object):
def __init__(self, forename, surname, hero):
self.forename = forename
self.surname = surname
self.heroname = hero |
class Ball:
def __init__(self):
self.x, self.y = 320, 240
self.speed_x = -10
self.speed_y = 10
self.size = 8
def movement(self, player1, player2):
self.x += self.speed_x
self.y += self.speed_y
if self.y <= 0:
self.speed_y *= -1
elif s... | class Ball:
def __init__(self):
(self.x, self.y) = (320, 240)
self.speed_x = -10
self.speed_y = 10
self.size = 8
def movement(self, player1, player2):
self.x += self.speed_x
self.y += self.speed_y
if self.y <= 0:
self.speed_y *= -1
el... |
def fizzbuzz(n):
if n%3 == 0 and n%5 != 0:
resultado = "Fizz"
elif n%5 == 0 and n%3 != 0:
resultado = "Buzz"
elif n%3 == 0 and n%5 == 0:
resultado = "FizzBuzz"
else:
resultado = n
return resultado
| def fizzbuzz(n):
if n % 3 == 0 and n % 5 != 0:
resultado = 'Fizz'
elif n % 5 == 0 and n % 3 != 0:
resultado = 'Buzz'
elif n % 3 == 0 and n % 5 == 0:
resultado = 'FizzBuzz'
else:
resultado = n
return resultado |
{
"includes": [
"ext/snowcrash/common.gypi"
],
"targets" : [
# LIBSOS
{
'target_name': 'libsos',
'type': 'static_library',
'direct_dependent_settings' : {
'include_dirs': [ 'ext/sos/src' ],
},
'sources': [
'ext/sos/src/sos.cc',
'ext/sos/src/sos.h',... | {'includes': ['ext/snowcrash/common.gypi'], 'targets': [{'target_name': 'libsos', 'type': 'static_library', 'direct_dependent_settings': {'include_dirs': ['ext/sos/src']}, 'sources': ['ext/sos/src/sos.cc', 'ext/sos/src/sos.h', 'ext/sos/src/sosJSON.h', 'ext/sos/src/sosYAML.h']}, {'target_name': 'libdrafter', 'type': '<(... |
# Config key of the MYSQL tag in config.ini
MSSQL_TAG = "MSSQL"
HOST_CONFIG = "host"
DATABASE_CONFIG = "database"
USER_CONFIG = "user"
PASSWORD_CONFIG = "password"
TABLE_CONFIG = "table"
DRIVER_CONFIG = "driver"
INSTANCE_NAME_FIELD_CONFIG = "instance_name_column"
TIMESTAMP_FIELD_CONFIG = "timestamp_column"
TIMESTAMP_FO... | mssql_tag = 'MSSQL'
host_config = 'host'
database_config = 'database'
user_config = 'user'
password_config = 'password'
table_config = 'table'
driver_config = 'driver'
instance_name_field_config = 'instance_name_column'
timestamp_field_config = 'timestamp_column'
timestamp_format_config = 'timestamp_format'
if_tag = 'I... |
print("hello, what is your name?")
name = input()
print("hi " + name)
| print('hello, what is your name?')
name = input()
print('hi ' + name) |
#Python 3.X solution for Easy Challenge #0007
#GitHub: https://github.com/Ashkore
#https://www.reddit.com/user/Ashkoree/
alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
morase = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..... | alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
morase = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '.--', '-..-', '-.--'... |
# Write a function or lambda using the implementation of fold below that will
# return the product of the elements of a list.
def or_else(lhs, rhs):
if lhs != None:
return lhs
else:
return rhs
def fold(function, arguments, initializer, accumulator = None):
if len(arguments) == 0:
return accumulator
else:
r... | def or_else(lhs, rhs):
if lhs != None:
return lhs
else:
return rhs
def fold(function, arguments, initializer, accumulator=None):
if len(arguments) == 0:
return accumulator
else:
return fold(function, arguments[1:], initializer, function(or_else(accumulator, initializer),... |
def solution(A):
nums = {}
for num in A:
nums[num] = 1
for num in nums:
if num + 1 in nums or num - 1 in nums:
return True
return False
def solution(N):
num = N
numStr = str(N)
if num < 0:
length = len(numStr) - 1
while length > 0:
if ... | def solution(A):
nums = {}
for num in A:
nums[num] = 1
for num in nums:
if num + 1 in nums or num - 1 in nums:
return True
return False
def solution(N):
num = N
num_str = str(N)
if num < 0:
length = len(numStr) - 1
while length > 0:
if... |
test = { 'name': 'q1_1',
'points': 1,
'suites': [ { 'cases': [{'code': ">>> unemployment.select('Date', 'NEI', 'NEI-PTER').take(0).column(0).item(0) == '1994-01-01'\nTrue", 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
't... | test = {'name': 'q1_1', 'points': 1, 'suites': [{'cases': [{'code': ">>> unemployment.select('Date', 'NEI', 'NEI-PTER').take(0).column(0).item(0) == '1994-01-01'\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
command = input()
numbers_sequence = [int(x) for x in input().split()]
odd_numbers = []
even_numbers = []
for number in numbers_sequence:
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
if command == 'Odd':
print(sum(odd_numbers) * len(numbers_sequence))
e... | command = input()
numbers_sequence = [int(x) for x in input().split()]
odd_numbers = []
even_numbers = []
for number in numbers_sequence:
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
if command == 'Odd':
print(sum(odd_numbers) * len(numbers_sequence))
elif... |
def sainte_claire1(general, dev, msg) :
code = 2
prio = 500
prio += adjust_prio(general, dev, msg)
keys=list();
keys.append('Sainte Claire')
if ( not contains(dev, keys) ) : return (0, 0, 0, '', '')
if ( dev['Sainte Claire']['count'] < 3) :
return (0, 0, 0, '', '')
title = "RU @ Sainte Claire?"
body = "... | def sainte_claire1(general, dev, msg):
code = 2
prio = 500
prio += adjust_prio(general, dev, msg)
keys = list()
keys.append('Sainte Claire')
if not contains(dev, keys):
return (0, 0, 0, '', '')
if dev['Sainte Claire']['count'] < 3:
return (0, 0, 0, '', '')
title = 'RU @ S... |
# General
TEMP_FILES_PATH = '/tmp/temp_files_parkun'
PERSONAL_FOLDER = 'broadcaster'
BOLD = 'bold'
ITALIC = 'italic'
MONO = 'mono'
STRIKE = 'strike'
POST_URL = 'post_url'
# Twitter
TWITTER_ENABLED = False
CONSUMER_KEY = 'consumer_key'
CONSUMER_SECRET = 'consumer_secret'
ACCESS_TOKEN = 'access_token'
ACCESS_TOKEN_SEC... | temp_files_path = '/tmp/temp_files_parkun'
personal_folder = 'broadcaster'
bold = 'bold'
italic = 'italic'
mono = 'mono'
strike = 'strike'
post_url = 'post_url'
twitter_enabled = False
consumer_key = 'consumer_key'
consumer_secret = 'consumer_secret'
access_token = 'access_token'
access_token_secret = 'access_token_sec... |
'''
Author : MiKueen
Level : Easy
Problem Statement : Convert Binary Number in a Linked List to Integer
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the... | """
Author : MiKueen
Level : Easy
Problem Statement : Convert Binary Number in a Linked List to Integer
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the... |
def computepay(h,r):
return 42.37
hrs = input("Enter Hours : ")
h = float(hrs)
rate = input("Enter rate per hour : ")
r = float(rate)
if h > 40:
gross = (40*r)+(h-40)*(r*1.5)
print(gross)
else:
gross=h*r
print(gross)
| def computepay(h, r):
return 42.37
hrs = input('Enter Hours : ')
h = float(hrs)
rate = input('Enter rate per hour : ')
r = float(rate)
if h > 40:
gross = 40 * r + (h - 40) * (r * 1.5)
print(gross)
else:
gross = h * r
print(gross) |
for t in range(int(input())):
p, q = map(int, input().split())
q = q + 1
hori = [0 for _ in range(q)]
vert = [0 for _ in range(q)]
for _ in range(p):
x, y, d = input().split()
x = int(x)
y = int(y)
if d == 'N':
vert[y + 1] += 1
if d == 'S':
vert[y] -= 1
vert[0] += 1
... | for t in range(int(input())):
(p, q) = map(int, input().split())
q = q + 1
hori = [0 for _ in range(q)]
vert = [0 for _ in range(q)]
for _ in range(p):
(x, y, d) = input().split()
x = int(x)
y = int(y)
if d == 'N':
vert[y + 1] += 1
if d == 'S':
... |
matrix = [sublist.split() for sublist in input().split("|")][::-1]
print(' '.join([str(number) for sublist in matrix for number in sublist]))
| matrix = [sublist.split() for sublist in input().split('|')][::-1]
print(' '.join([str(number) for sublist in matrix for number in sublist])) |
LOGIN_URL = "/login"
XPATH_EMAIL_INPUT = "//form//input[contains(@placeholder,'Email')]"
XPATH_PASSWORD_INPUT = "//form//input[contains(@placeholder,'Password')]"
XPATH_SUBMIT = "//form//button[contains(@type,'submit')]"
| login_url = '/login'
xpath_email_input = "//form//input[contains(@placeholder,'Email')]"
xpath_password_input = "//form//input[contains(@placeholder,'Password')]"
xpath_submit = "//form//button[contains(@type,'submit')]" |
dataset=["gossipcop_fake" "gossipcop_real" "politifact_fake" "politifact_real" "Aminer"]
methods=["proposed" "HITS" "CoHITS" "BGRM" "BiRank"]
| dataset = ['gossipcop_fakegossipcop_realpolitifact_fakepolitifact_realAminer']
methods = ['proposedHITSCoHITSBGRMBiRank'] |
'''
https://docs.python.org/3/reference/datamodel.html#object.__getitem__
'''
class XXX(object):
def __init__(self):
self.data = {int(i): str(i) for i in range(3)}
def __len__(self):
return len(self.data)
def __getitem__(self, index):
if index >= len(self): raise IndexError
r... | """
https://docs.python.org/3/reference/datamodel.html#object.__getitem__
"""
class Xxx(object):
def __init__(self):
self.data = {int(i): str(i) for i in range(3)}
def __len__(self):
return len(self.data)
def __getitem__(self, index):
if index >= len(self):
raise Inde... |
def search(list, key):
pos = -1
for i in range(0,len(list)):
if list[i] == key:
pos = i + 1
break
if pos != -1:
print("\n\nThe value {} is found to be at {} position!".format(key,pos))
else:
print("\n\nThe value {} cannot be found!".format(key))
print("\nEnter the elements of ... | def search(list, key):
pos = -1
for i in range(0, len(list)):
if list[i] == key:
pos = i + 1
break
if pos != -1:
print('\n\nThe value {} is found to be at {} position!'.format(key, pos))
else:
print('\n\nThe value {} cannot be found!'.format(key))
print('\... |
def diagonalDifference(arr, n):
mtotal = 0
stotal = 0
for i in range(n):
mtotal += arr[i][i]
stotal += arr[n - 1 - i][i]
return abs(mtotal - stotal)
n = int(input())
arr = [
list(map(int, input().split())) for _ in range(n)
]
print(diagonalDifference(arr, n))
| def diagonal_difference(arr, n):
mtotal = 0
stotal = 0
for i in range(n):
mtotal += arr[i][i]
stotal += arr[n - 1 - i][i]
return abs(mtotal - stotal)
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]
print(diagonal_difference(arr, n)) |
first_name = "Hannah"
last_name = "Louisa"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.upper()}")
message = f"Howdy, {full_name.title()}"
print(message)
| first_name = 'Hannah'
last_name = 'Louisa'
full_name = f'{first_name} {last_name}'
print(full_name)
print(f'Hello, {full_name.upper()}')
message = f'Howdy, {full_name.title()}'
print(message) |
#
# PySNMP MIB module DOCS-MCAST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-MCAST-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:38:33 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... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
def square(x):
return x*x
print(type(square))
print(id(square))
print(str(square)) | def square(x):
return x * x
print(type(square))
print(id(square))
print(str(square)) |
#
# PySNMP MIB module CISCO-VOICE-ATM-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-ATM-DIAL-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:19:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
def quote(msg: str):
return msg.replace("`", "")
def cleanup_code(content):
if content.startswith("```") and content.endswith("```"):
output = content[3:-3].rstrip("\n").lstrip("\n")
return output
return content.strip("` \n") | def quote(msg: str):
return msg.replace('`', '')
def cleanup_code(content):
if content.startswith('```') and content.endswith('```'):
output = content[3:-3].rstrip('\n').lstrip('\n')
return output
return content.strip('` \n') |
# Joe defined a dictionary listing his favorite artists, their albums,
# and the song from each of the albums. It looks as follows:
#tracks = {"Woodkid": {"The Golden Age": "Run Boy Run",
# "On the Other Side": "Samara"},
# "Cure": {"Disintegration": "Lovesong",
# "Wish":... | def tracklist(**tracks):
for (key, value) in tracks.items():
print(key)
for (k, v) in value.items():
print(f'ALBUM: {k} TRACK: {v}')
def tracklist(**artists):
for (artist, album) in artists.items():
print(artist)
print('\n'.join((f'ALBUM: {album_name} TRACK: {track}'... |
# Challenge Link - https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
# My Results - https://app.codility.com/demo/results/trainingFGAZZW-5XB/
def solution(A, K):
# write your code in Python 3.6
if not A:
return []
idx = [i for i in range(0, len(A))]
while K:
idx = [... | def solution(A, K):
if not A:
return []
idx = [i for i in range(0, len(A))]
while K:
idx = [i + 1 for i in idx]
max_index = idx.index(max(idx))
idx[max_index] = 0
k = K - 1
new_list = [0] * len(A)
for (n, index) in zip(A, idx):
new_list[index] = n
... |
class Account:
resource = 'accounts'
def __init__(self, requestor):
self.requestor = requestor
def retrieve(self):
return self.requestor.request('GET', '{}'.format(self.resource))
| class Account:
resource = 'accounts'
def __init__(self, requestor):
self.requestor = requestor
def retrieve(self):
return self.requestor.request('GET', '{}'.format(self.resource)) |
_base_ = 'resnet50_head1_4xb64-steplr1e-1-20e_in1k-10pct.py'
# optimizer
optimizer = dict(lr=0.01)
| _base_ = 'resnet50_head1_4xb64-steplr1e-1-20e_in1k-10pct.py'
optimizer = dict(lr=0.01) |
# -*- coding: utf-8 -*-
def search(key, arr):
return list(filter(lambda n: n[0] == key, arr))
def main():
arr = [[100, 2], [300, 3], [500, 4], [800, 5], [200, 6]]
inp_id = 200
ret = search(inp_id, arr)
print(ret)
if len(ret) > 0:
print("ok")
else:
print("Error")
if __name... | def search(key, arr):
return list(filter(lambda n: n[0] == key, arr))
def main():
arr = [[100, 2], [300, 3], [500, 4], [800, 5], [200, 6]]
inp_id = 200
ret = search(inp_id, arr)
print(ret)
if len(ret) > 0:
print('ok')
else:
print('Error')
if __name__ == '__main__':
main(... |
file = open("BoyNames.txt", "r")
data = file.read()
boys_names = data.split('\n')
file = open("GirlNames.txt", "r")
data = file.read()
girls_names = data.split('\n')
file.close()
choice = input("Enter 'boy', 'girl', or 'both':")
if choice == "boy":
name = input("Enter a boy's name:")
if name in boys_names:
print... | file = open('BoyNames.txt', 'r')
data = file.read()
boys_names = data.split('\n')
file = open('GirlNames.txt', 'r')
data = file.read()
girls_names = data.split('\n')
file.close()
choice = input("Enter 'boy', 'girl', or 'both':")
if choice == 'boy':
name = input("Enter a boy's name:")
if name in boys_names:
... |
a = int(input())
for _ in range(a):
x = input()
y = x[::-1]
counter = 0
while x != y or not counter:
x = str(int(x) + int(y))
y = x[::-1]
counter += 1
print(counter, x)
| a = int(input())
for _ in range(a):
x = input()
y = x[::-1]
counter = 0
while x != y or not counter:
x = str(int(x) + int(y))
y = x[::-1]
counter += 1
print(counter, x) |
# Input.
s = '367436765224262147416876392821832169781285655941123648172835986213848397566284241467793119283183835972359686446876651595915734132336167171121577524691918457577129283476247264385162111539468922414495231484194262592917889386218863347344978231632813893898536759322467341535638612338949526576258684154323161554... | s = '367436765224262147416876392821832169781285655941123648172835986213848397566284241467793119283183835972359686446876651595915734132336167171121577524691918457577129283476247264385162111539468922414495231484194262592917889386218863347344978231632813893898536759322467341535638612338949526576258684154323161554872428137... |
try:
a = int(input("Primeiro numero: "))
b = int(input("Segundo numero: "))
r = a / b
except Exception as erro:
print("Problema encontrado foi {}".format(erro.__class__))
else:
print("O resultado e {:.1f}".format(r))
finally:
print("Volte Sempre! Muito Obrigado :)")
| try:
a = int(input('Primeiro numero: '))
b = int(input('Segundo numero: '))
r = a / b
except Exception as erro:
print('Problema encontrado foi {}'.format(erro.__class__))
else:
print('O resultado e {:.1f}'.format(r))
finally:
print('Volte Sempre! Muito Obrigado :)') |
# Isaac Roberts
# Imports
# Functions
# Main execution of the program.
def main():
# Open provided CSV file
f = open("Python/airport-project/Airports.txt", 'r')
# Define list to store seperated CSV file in.
airports_list = []
# Loop through file and split each line into seperate lists.
for ... | def main():
f = open('Python/airport-project/Airports.txt', 'r')
airports_list = []
for i in f:
split_line = i.split(',')
del split_line[-1]
airports_list.append(split_line)
menu(airports_list)
def exit_program():
exit()
def menu(airports_list):
while True:
choi... |
class settings:
def init():
global baseURL
global password
global username
global usertestingpassword
global usertestingemail
global twilliotemplate | class Settings:
def init():
global baseURL
global password
global username
global usertestingpassword
global usertestingemail
global twilliotemplate |
#
# PySNMP MIB module NETONIX-SWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETONIX-SWITCH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:19:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
###checks to see which elements in array1, a1, are substrings of elements in array2, a2###
###returns sorted array of these elements###
def in_array(a1, a2):
inArray = set()
for i in a1:
for x in a2:
if i in x:
inArray.add(i)
return sorted(inArray)
| def in_array(a1, a2):
in_array = set()
for i in a1:
for x in a2:
if i in x:
inArray.add(i)
return sorted(inArray) |
AI_TYPE_TO_ROLE = {"redis_ycsb": ("ycsb", "redis"), "hadoop": ("hadoopmaster", "hadoopslave"),
"linpack": ("linpack",), "wrk": ("wrk", "apache"), "filebench": ("filebench",),
"sysbench": ("sysbench", "mysql"),
#"unixbench": ("unixbench",), "netperf": ("netclient"... | ai_type_to_role = {'redis_ycsb': ('ycsb', 'redis'), 'hadoop': ('hadoopmaster', 'hadoopslave'), 'linpack': ('linpack',), 'wrk': ('wrk', 'apache'), 'filebench': ('filebench',), 'sysbench': ('sysbench', 'mysql'), 'multichase': ('multichase',), 'oldisim': ('oldisimdriver', 'oldisimlb', 'oldisimroot', 'oldisimleaf'), 'open_... |
def permutation(input_list):
if len(input_list) == 0:
return []
elif len(input_list) == 1:
return [input_list]
else:
result = []
for i in range(len(input_list)):
element = input_list[i]
other_elements = input_list[:i] + input_list[i + 1:]
f... | def permutation(input_list):
if len(input_list) == 0:
return []
elif len(input_list) == 1:
return [input_list]
else:
result = []
for i in range(len(input_list)):
element = input_list[i]
other_elements = input_list[:i] + input_list[i + 1:]
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
REAL_FLAG = "oren_ctf_spectre!"
FAKE_FLAG = "oren_ctf_z3r0d4y!"
license = [chr(ord(c1) ^ ord(c2)) for c1,c2 in zip(REAL_FLAG, FAKE_FLAG)]
with open('license.bin', 'wb') as licensefile:
for byte in license:
licensefile.writ... | def main():
real_flag = 'oren_ctf_spectre!'
fake_flag = 'oren_ctf_z3r0d4y!'
license = [chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(REAL_FLAG, FAKE_FLAG)]
with open('license.bin', 'wb') as licensefile:
for byte in license:
licensefile.write(bytes(byte, 'utf-8'))
if __name__ == '__main_... |
class OUTGOING:
TOKEN = 'token'
TEAM_ID = 'team_id'
TEAM_DOMAIN = 'team_domain'
CHANNEL_ID = 'channel_id'
CHANNEL_NAME = 'channel_name'
TIMESTAMP = 'timestamp'
USER_ID = 'user_id'
USER_NAME = 'user_name'
TEXT = 'text'
TRIGGER_WORD = 'trigger_word'
class INCOMING:
USER_NAME ... | class Outgoing:
token = 'token'
team_id = 'team_id'
team_domain = 'team_domain'
channel_id = 'channel_id'
channel_name = 'channel_name'
timestamp = 'timestamp'
user_id = 'user_id'
user_name = 'user_name'
text = 'text'
trigger_word = 'trigger_word'
class Incoming:
user_name =... |
ODL_IP = "127.0.0.1"
ODL_PORT = "8181"
ODL_USER = "admin"
ODL_PASS = "admin"
| odl_ip = '127.0.0.1'
odl_port = '8181'
odl_user = 'admin'
odl_pass = 'admin' |
def arithmetic_arranger(problems, solutions = False):
if len(problems) > 5:
return 'Error: Too many problems.'
problem_list = []
for prob in problems:
output = ''
arr = prob.split(' ')
if arr[1] != '+' or arr[1] != '+':
return "Error: Operator must be '+' or '-'."
if arr[0].isdig... | def arithmetic_arranger(problems, solutions=False):
if len(problems) > 5:
return 'Error: Too many problems.'
problem_list = []
for prob in problems:
output = ''
arr = prob.split(' ')
if arr[1] != '+' or arr[1] != '+':
return "Error: Operator must be '+' or '-'."
... |
_, ax = plt.subplots(figsize=(8, 8))
ax = sns.kdeplot(
data=X_train_scaled,
x="Culmen Length (mm)",
y="Culmen Depth (mm)",
levels=10,
fill=True,
cmap=plt.cm.viridis,
ax=ax,
)
_ = ax.axis("square")
| (_, ax) = plt.subplots(figsize=(8, 8))
ax = sns.kdeplot(data=X_train_scaled, x='Culmen Length (mm)', y='Culmen Depth (mm)', levels=10, fill=True, cmap=plt.cm.viridis, ax=ax)
_ = ax.axis('square') |
def doiList():
return [
"10.1016/j.jksuci.2019.05.004", # ScienceDirect good example
"10.1016/j.eswa.2019.04.070"
]
| def doi_list():
return ['10.1016/j.jksuci.2019.05.004', '10.1016/j.eswa.2019.04.070'] |
class IPGroup():
def __init__(self, key, packet_count, total_packet_size, process_number):
self.packet_count = packet_count
self.total_packet_size = total_packet_size
self.process_number = process_number
self.groupname = key
@property
def averagePacketSize(self):
ret... | class Ipgroup:
def __init__(self, key, packet_count, total_packet_size, process_number):
self.packet_count = packet_count
self.total_packet_size = total_packet_size
self.process_number = process_number
self.groupname = key
@property
def average_packet_size(self):
re... |
# Specifies the login method to use -- whether the user logs in by entering
# his username, e-mail address, or either one of both. Possible values
# are 'username' | 'email' | 'username_email'
# ACCOUNT_AUTHENTICATION_METHOD
# The URL to redirect to after a successful e-mail confirmation, in case no
# user is logged i... | account_email_required = True
account_email_verification = 'optional'
account_unique_email = True
account_username_required = True
account_password_min_length = 6
socialaccount_providers = {'google': {'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'}}, 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['e... |
'''
A Popular Strategy Using Autocorrelation
One puzzling anomaly with stocks is that investors tend to overreact to news. Following large jumps, either up or down, stock prices tend to reverse. This is described as mean reversion in stock prices: prices tend to bounce back, or revert, towards previous levels after la... | """
A Popular Strategy Using Autocorrelation
One puzzling anomaly with stocks is that investors tend to overreact to news. Following large jumps, either up or down, stock prices tend to reverse. This is described as mean reversion in stock prices: prices tend to bounce back, or revert, towards previous levels after la... |
# Colors
blue = '#377EB8'
red = '#E41A1C'
green = '#4DAF4A'
| blue = '#377EB8'
red = '#E41A1C'
green = '#4DAF4A' |
class ConfigClass:
def __init__(self):
# link to a zip file in google drive with your pretrained model
self._model_url = "https://drive.google.com/file/d/14VduVhV12k1mgLJMJ0WMhtRlFqwqMKtN/view?usp=sharing"
# False/True flag indicating whether the testing system will download
# ... | class Configclass:
def __init__(self):
self._model_url = 'https://drive.google.com/file/d/14VduVhV12k1mgLJMJ0WMhtRlFqwqMKtN/view?usp=sharing'
self._download_model = True
self.corpusPath = ''
self.savedFileMainFolder = ''
self.saveFilesWithStem = self.savedFileMainFolder + '/... |
'''4. Write a Python program to add two positive integers without using the '+' operator.
Note: Use bit wise operations to add two numbers.'''
num1 = 4
num2 = 34
num3 = num1.__add__(num2)
print(num3) | """4. Write a Python program to add two positive integers without using the '+' operator.
Note: Use bit wise operations to add two numbers."""
num1 = 4
num2 = 34
num3 = num1.__add__(num2)
print(num3) |
__copyright__ = "Copyright 2019, RISE Research Institutes of Sweden"
__author__ = "Naveed Anwar Bhatti and Martina Brachmann"
def maprange(a, b, s):
'''
Maps an input value to an ouput value depending on a sensors' and actuators's range
Parameters
----------
a : tupel (float, float)
the s... | __copyright__ = 'Copyright 2019, RISE Research Institutes of Sweden'
__author__ = 'Naveed Anwar Bhatti and Martina Brachmann'
def maprange(a, b, s):
"""
Maps an input value to an ouput value depending on a sensors' and actuators's range
Parameters
----------
a : tupel (float, float)
the se... |
class Card:
def __init__(self,rank,suit): # instance recevies two parameters rank and suit
self.rank = rank
self.suit = suit
self.rank_list = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] # a list contains all ranks
self.suit_list = ['H', 'C', 'D', 'S'] # a list c... | class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.rank_list = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
self.suit_list = ['H', 'C', 'D', 'S']
assert self.rank.upper() in self.rank_list, 'Invalid Rank'
assert se... |
n = 1
while True:
num = int(input(f"Enter value{n}: "))
if num == -99:
break
n += 1
print(f"You entered {n-1} numbers.") | n = 1
while True:
num = int(input(f'Enter value{n}: '))
if num == -99:
break
n += 1
print(f'You entered {n - 1} numbers.') |
while True:
n = int(input())
if n == -1:
break
last_elapsed = 0
distance = 0
for _ in range(n):
s, t = map(int, input().split())
_t = t - last_elapsed
distance += s * _t
last_elapsed = t
print(distance, "miles")
| while True:
n = int(input())
if n == -1:
break
last_elapsed = 0
distance = 0
for _ in range(n):
(s, t) = map(int, input().split())
_t = t - last_elapsed
distance += s * _t
last_elapsed = t
print(distance, 'miles') |
POSTGRES_DATA_TYPES = {
"int2": "smallint",
"integer": "integer",
"uuid": "uuid",
"string": "varchar",
"timestamp": "timestamp",
}
| postgres_data_types = {'int2': 'smallint', 'integer': 'integer', 'uuid': 'uuid', 'string': 'varchar', 'timestamp': 'timestamp'} |
def rotLeft(a, d):
for x in range(d):
temp = a[0]
a.pop(0)
a.append(temp)
return a
no_of_inputs = 5
no_of_rotation = 4
my_str = "1 2 3 4 5"
my_arr = [s for s in my_str.strip().split()]
print(rotLeft(my_arr, no_of_rotation))
| def rot_left(a, d):
for x in range(d):
temp = a[0]
a.pop(0)
a.append(temp)
return a
no_of_inputs = 5
no_of_rotation = 4
my_str = '1 2 3 4 5'
my_arr = [s for s in my_str.strip().split()]
print(rot_left(my_arr, no_of_rotation)) |
# We have tossed a coin a 6 times and saved the results in a list
# called heads_or_tails. The values are integers: 1 stands for a
# head, while 0 denotes a tail.
# Add some code to find out whether the list has any heads. Do
# not print the variable check, just store the result in it.
# Fingers crossed
check = any(h... | check = any(heads_or_tails) |
A, B, C = list(map(int, input().split()))
if C <= B:
print('-1')
else:
print(int(A / (C-B) + 1))
| (a, b, c) = list(map(int, input().split()))
if C <= B:
print('-1')
else:
print(int(A / (C - B) + 1)) |
'''
Intuition
----
Intuition is an engine, some building bricks and a set of tools meant to let
you efficiently and intuitively make your own automated quantitative trading
system. It is designed to let traders, developers and scientists explore,
improve and deploy market technical hacks.
:copyright (c)... | """
Intuition
----
Intuition is an engine, some building bricks and a set of tools meant to let
you efficiently and intuitively make your own automated quantitative trading
system. It is designed to let traders, developers and scientists explore,
improve and deploy market technical hacks.
:copyright (c)... |
#assignment2 homework1
student1=input("Enter student name1:")
student2=input("Enter student name2:")
student3=input("Enter student name3:")
print("Student1 Name is:"+student1+"\n"+"Student2 Name is:"+student2+"\n"+"Student3 Name is:"+student3)
#assignment2 homework2
def function1():
print("Function1 output:",ag... | student1 = input('Enter student name1:')
student2 = input('Enter student name2:')
student3 = input('Enter student name3:')
print('Student1 Name is:' + student1 + '\n' + 'Student2 Name is:' + student2 + '\n' + 'Student3 Name is:' + student3)
def function1():
print('Function1 output:', age)
def function2():
age... |
class LimitedStack:
def __init__ (self,max_size=200):
self.stack = []
self.max_size = max_size
def add (self,item=None):
self.stack.append(item)
if len(self.stack) > self.max_size:
self.stack = self.stack[1:]
def get (self):
... | class Limitedstack:
def __init__(self, max_size=200):
self.stack = []
self.max_size = max_size
def add(self, item=None):
self.stack.append(item)
if len(self.stack) > self.max_size:
self.stack = self.stack[1:]
def get(self):
if self.stack:
re... |
class Config(object):
env = 'default'
backbone = 'resnet18'
classify = 'softmax'
num_classes = 5000
metric = 'arc_margin'
easy_margin = False
use_se = False
loss = 'focal_loss'
display = False
finetune = False
meta_train = '/preprocessed/train_meta.csv'
train_root = '/p... | class Config(object):
env = 'default'
backbone = 'resnet18'
classify = 'softmax'
num_classes = 5000
metric = 'arc_margin'
easy_margin = False
use_se = False
loss = 'focal_loss'
display = False
finetune = False
meta_train = '/preprocessed/train_meta.csv'
train_root = '/pre... |
#
# PySNMP MIB module ENTERASYS-POWER-ETHERNET-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-POWER-ETHERNET-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
# vim: fdm=indent
'''
author: Fabio Zanini
date: 31/08/15
content: Module that contains fast conversion factories between private and
anonymyzed versions of data.
Such a module is useful during research development, when consensus
on anonymized patient/sample names has ... | """
author: Fabio Zanini
date: 31/08/15
content: Module that contains fast conversion factories between private and
anonymyzed versions of data.
Such a module is useful during research development, when consensus
on anonymized patient/sample names has not been reached y... |
def get_index(word):
while True:
try:
pos = int(input("Enter an index: "))
if pos == -1:
return pos
elif pos >= len(word):
print("invalid index")
elif pos <= -1:
print("invalid index")
els... | def get_index(word):
while True:
try:
pos = int(input('Enter an index: '))
if pos == -1:
return pos
elif pos >= len(word):
print('invalid index')
elif pos <= -1:
print('invalid index')
else:
... |
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x) | x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x) |
# package information.
INFO = dict(
name = "latexutils",
description = "Utils for making Latex documents",
author = "Daisuke Kataoka",
author_email = "daisuke.1221.canoe@gmail.com",
url = "https://github.com/dai39suke/latexutils",
classifiers = [
"Programming Language :: Python :: 3.... | info = dict(name='latexutils', description='Utils for making Latex documents', author='Daisuke Kataoka', author_email='daisuke.1221.canoe@gmail.com', url='https://github.com/dai39suke/latexutils', classifiers=['Programming Language :: Python :: 3.6']) |
## (y - y1) / (x - x1) = (y2 - y1) / (x2 - x1)
y = lambda x, x1, x2, y1, y2: y1 + (y2-y1) / (x2-x1) * (x-x1)
def interpolation(xp, X, Y):
if xp < X[0]:
print("Given x-value is out of range")
return None
for i, Xi in enumerate(X):
if xp < Xi:
return y(xp, X[i-1], X[i], Y[i-1... | y = lambda x, x1, x2, y1, y2: y1 + (y2 - y1) / (x2 - x1) * (x - x1)
def interpolation(xp, X, Y):
if xp < X[0]:
print('Given x-value is out of range')
return None
for (i, xi) in enumerate(X):
if xp < Xi:
return y(xp, X[i - 1], X[i], Y[i - 1], Y[i])
else:
print('Gi... |
'''
Let us say your expense for every month are listed below,
January - 2200
February - 2350
March - 2600
April - 2130
May - 2190
Create a list to store these monthly expenses and using that find out,
1. In Feb, how many dollars you spent extra compare to January?
2. Find out your total expense in first quarter (first... | """
Let us say your expense for every month are listed below,
January - 2200
February - 2350
March - 2600
April - 2130
May - 2190
Create a list to store these monthly expenses and using that find out,
1. In Feb, how many dollars you spent extra compare to January?
2. Find out your total expense in first quarter (first... |
class Solution:
def shortestWordDistance(self, words: 'List[str]', word1: 'str', word2: 'str') -> 'int':
i1 = i2 = -1
ans = math.inf
equal = word1 == word2
for i, word in enumerate(words):
if word == word1:
i1 = i
if word == word2:
... | class Solution:
def shortest_word_distance(self, words: 'List[str]', word1: 'str', word2: 'str') -> 'int':
i1 = i2 = -1
ans = math.inf
equal = word1 == word2
for (i, word) in enumerate(words):
if word == word1:
i1 = i
if word == word2:
... |
f = open("HaltestellenVVS_simplified_utf8.csv", "r")
r = open("HaltestellenVVS_simplified_utf8_stationID.csv", "w")
r.write(f.readline())
lines = f.readlines()
for line in lines:
stationID = line.split(",")[0]
newStationID = int(stationID)+5000000
outLine = str(newStationID) + line[len(stationID):]
r.write(outL... | f = open('HaltestellenVVS_simplified_utf8.csv', 'r')
r = open('HaltestellenVVS_simplified_utf8_stationID.csv', 'w')
r.write(f.readline())
lines = f.readlines()
for line in lines:
station_id = line.split(',')[0]
new_station_id = int(stationID) + 5000000
out_line = str(newStationID) + line[len(stationID):]
... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
vals = []
if not roo... | class Solution:
def level_order(self, root):
vals = []
if not root:
return vals
cache = [root]
while len(cache) > 0:
tmp = []
level = []
for node in cache:
level.append(node.val)
if node.left:
... |
def quicksorted(L):
#base case
if len(L) < 2:
return L[:]
# Divide!
pivot = L[-1]
LT = [e for e in L if e < pivot]
ET = [e for e in L if e == pivot]
GT = [e for e in L if e > pivot]
# Conquer
A = quicksorted(LT)
B = quicksorted(GT)
# Combine
return A + ET + B
... | def quicksorted(L):
if len(L) < 2:
return L[:]
pivot = L[-1]
lt = [e for e in L if e < pivot]
et = [e for e in L if e == pivot]
gt = [e for e in L if e > pivot]
a = quicksorted(LT)
b = quicksorted(GT)
return A + ET + B
def quicksort(L, left=0, right=None):
if right is None:
... |
# Parsed from https://www.ibm.com/docs/en/spectrum-lsf/10.1.0?topic=options-o
bjobs_fields = [
{"name": "jobid", "width": 7, "aliases": "id", "unit": None},
{"name": "jobindex", "width": 8, "aliases": None, "unit": None},
{"name": "stat", "width": 5, "aliases": None, "unit": None},
{"name": "user", "wid... | bjobs_fields = [{'name': 'jobid', 'width': 7, 'aliases': 'id', 'unit': None}, {'name': 'jobindex', 'width': 8, 'aliases': None, 'unit': None}, {'name': 'stat', 'width': 5, 'aliases': None, 'unit': None}, {'name': 'user', 'width': 7, 'aliases': None, 'unit': None}, {'name': 'user_group', 'width': 15, 'aliases': 'ugroup'... |
# from ncats.translator.module.disease.gene import disease_associated_genes
@given('a disease term {disease_identifier} for disease label {disease_label} in Translator Modules')
def step_impl(context, disease_identifier, disease_label):
context.disease = {"disease_identifier":disease_identifier, "disease_label":di... | @given('a disease term {disease_identifier} for disease label {disease_label} in Translator Modules')
def step_impl(context, disease_identifier, disease_label):
context.disease = {'disease_identifier': disease_identifier, 'disease_label': disease_label}
@when('we run the disease associated genes Translator Module'... |
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
count=0
for i in range(N):
count+=min(A[i],B[i])
if A[i]<B[i]:
if A[i+1]<B[i]-A[i]:
count+=A[i+1]
A[i+1]=0
else:
count+=B[i]-A[i]
A[i+1]-=B[i]-A[i]
print(count) | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
count = 0
for i in range(N):
count += min(A[i], B[i])
if A[i] < B[i]:
if A[i + 1] < B[i] - A[i]:
count += A[i + 1]
A[i + 1] = 0
else:
count += B[i] - A[i]
A[i ... |
def ground_ship(weight):
flat = 20
if weight <= 2:
return weight*1.5 + flat
elif weight > 2 and weight <= 6:
return weight*3.0 + flat
elif weight > 6 and weight <= 10:
return weight*4.0 + flat
else:
return weight*4.75 + flat
cost = ground_ship(8.4)
print(cost)
def drone_ship(weight):
flat ... | def ground_ship(weight):
flat = 20
if weight <= 2:
return weight * 1.5 + flat
elif weight > 2 and weight <= 6:
return weight * 3.0 + flat
elif weight > 6 and weight <= 10:
return weight * 4.0 + flat
else:
return weight * 4.75 + flat
cost = ground_ship(8.4)
print(cost)... |
# Copyright 2018 ZTE Corporation.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | grant_data = {'vnfInstanceId': '1', 'vnfLcmOpOccId': '2', 'vnfdId': '3', 'flavourId': '4', 'operation': 'INSTANTIATE', 'isAutomaticInvocation': True, 'instantiationLevelId': '5', 'addResources': [{'id': '1', 'type': 'COMPUTE', 'vduId': '2', 'resourceTemplateId': '3', 'resourceTemplate': {'vimConnectionId': '4', 'resour... |
def my_func():
print("Foo")
my_other_func = lambda: print("Bar")
my_arr = [my_func, my_other_func]
for i in range (0, 2):
my_arr[i]()
# Bots Position
BOT_POS = [(5401, 1530),(3686, 1857),(3733, 2626),(2325, 1814),
(1718, 1282),(1288, 2418),(1249, 506),(2513,1286)
]
prin... | def my_func():
print('Foo')
my_other_func = lambda : print('Bar')
my_arr = [my_func, my_other_func]
for i in range(0, 2):
my_arr[i]()
bot_pos = [(5401, 1530), (3686, 1857), (3733, 2626), (2325, 1814), (1718, 1282), (1288, 2418), (1249, 506), (2513, 1286)]
print('\n')
for (x, y) in BOT_POS:
print(x, y) |
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1 or len(s) <= 2:
return s
# compute the length of the zigzag
zigzagLen = 2*nRows - 2;
lens = len(s)
res = ''
for i in range(nRows):
idx = i
while idx... | class Solution:
def convert(self, s, nRows):
if nRows == 1 or len(s) <= 2:
return s
zigzag_len = 2 * nRows - 2
lens = len(s)
res = ''
for i in range(nRows):
idx = i
while idx < lens:
res = res + s[idx]
if i ... |
amountNumbers = int(input())
arrNumbers = set(map(int, input().split()))
amountCommands = int(input())
for i in range(amountCommands):
command = input().split()
if command[0] == "pop":
arrNumbers.pop()
elif command[0] == "remove":
if int(command[1]) in arrNumbers:
arrNumbers.r... | amount_numbers = int(input())
arr_numbers = set(map(int, input().split()))
amount_commands = int(input())
for i in range(amountCommands):
command = input().split()
if command[0] == 'pop':
arrNumbers.pop()
elif command[0] == 'remove':
if int(command[1]) in arrNumbers:
arrNumbers.r... |
# 238. Product of Array Except Self
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
cur, n = 1, len(nums)
out = [1]*n
for i in range(1, n):
cur *= nums[i-1]
out[i] = cur
cur = 1
for i in range(n-2, -1, -1):
... | class Solution:
def product_except_self(self, nums: List[int]) -> List[int]:
(cur, n) = (1, len(nums))
out = [1] * n
for i in range(1, n):
cur *= nums[i - 1]
out[i] = cur
cur = 1
for i in range(n - 2, -1, -1):
cur *= nums[i + 1]
... |
try:
myfile1=open("E:\\python_progs\\demochange\\mydir2\\pic1.jpg","rb")
myfile2=open("E:\\python_progs\\demochange\\mydir2\\newpic1.jpg","wb")
bytes=myfile1.read()
myfile2.write(bytes)
print("A new Image is available having name as: newpic1.jpg")
finally:
myfile1.close()
myfile2.close()
| try:
myfile1 = open('E:\\python_progs\\demochange\\mydir2\\pic1.jpg', 'rb')
myfile2 = open('E:\\python_progs\\demochange\\mydir2\\newpic1.jpg', 'wb')
bytes = myfile1.read()
myfile2.write(bytes)
print('A new Image is available having name as: newpic1.jpg')
finally:
myfile1.close()
myfile2.clo... |
expected_output = {
'power-usage-information': {
'power-usage-item': [
{
'name': 'PSM 0',
'state': 'Online',
'dc-input-detail2': {
'dc-input-status':
'OK (INP0 feed expected, INP0 feed connected)'
... | expected_output = {'power-usage-information': {'power-usage-item': [{'name': 'PSM 0', 'state': 'Online', 'dc-input-detail2': {'dc-input-status': 'OK (INP0 feed expected, INP0 feed connected)'}, 'pem-capacity-detail': {'capacity-actual': '2100', 'capacity-max': '2500'}, 'dc-output-detail2': {'str-dc-power': '489.25', 's... |
def list3(str):
result = 0
for i in str:
if i == 'a':
result += 1
return result
def main():
print(list3(['Hello', 'world', 'a']))
print(list3(['a', 'a']))
print(list3(['Computational', 'thinking']))
print(list3(['a', 'A', 'A']))
if __name__ == '__main__':
main()
| def list3(str):
result = 0
for i in str:
if i == 'a':
result += 1
return result
def main():
print(list3(['Hello', 'world', 'a']))
print(list3(['a', 'a']))
print(list3(['Computational', 'thinking']))
print(list3(['a', 'A', 'A']))
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.