text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_nums(arr):
""" Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. e.g. -... | def digits_sum(n):
neg = 1
if n < 0: n, neg = -1 * n, -1
n = [int(i) for i in str(n)]
n[0] = n[0] * neg
return sum(n)
return len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr])))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_one_ball(arr):
"""We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The numbers in the array will be randomly ordered. Your task is to... | if len(arr)==0:
return True
sorted_array=sorted(arr)
my_arr=[]
min_value=min(arr)
min_index=arr.index(min_value)
my_arr=arr[min_index:]+arr[0:min_index]
for i in range(len(arr)):
if my_arr[i]!=sorted_array[i]:
return False
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exchange(lst1, lst2):
"""In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform ... | odd = 0
even = 0
for i in lst1:
if i%2 == 1:
odd += 1
for i in lst2:
if i%2 == 0:
even += 1
if even >= odd:
return "YES"
return "NO"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram(test):
"""Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and contai... | dict1={}
list1=test.split(" ")
t=0
for i in list1:
if(list1.count(i)>t) and i!='':
t=list1.count(i)
if t>0:
for i in list1:
if(list1.count(i)==t):
dict1[i]=t
return dict1
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reverse_delete(s,c):
"""Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check... | s = ''.join([char for char in s if char not in c])
return (s,s[::-1] == s)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def odd_count(lst):
"""Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number o... | res = []
for arr in lst:
n = sum(int(d)%2==1 for d in arr)
res.append("the number of odd elements " + str(n) + "n the str"+ str(n) +"ng "+ str(n) +" of the "+ str(n) +"nput.")
return res
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minSubArraySum(nums):
""" Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2,... | max_sum = 0
s = 0
for num in nums:
s += -num
if (s < 0):
s = 0
max_sum = max(s, max_sum)
if max_sum == 0:
max_sum = max(-i for i in nums)
min_sum = -max_sum
return min_sum
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_fill(grid, capacity):
import math
""" You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents... | return sum([math.ceil(sum(arr)/capacity) for arr in grid])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_array(arr):
""" In this Kata, you have to sort an array of non-negative integers according to number of ones in their binary representation in ascend... | return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1'))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_words(s, n):
"""Given a string s and a natural number n, you have been tasked to implement a function that returns a list of all words from string ... | result = []
for word in s.split():
n_consonants = 0
for i in range(0, len(word)):
if word[i].lower() not in ["a","e","i","o","u"]:
n_consonants += 1
if n_consonants == n:
result.append(word)
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_closest_vowel(word):
"""You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the wor... | if len(word) < 3:
return ""
vowels = {"a", "e", "i", "o", "u", "A", "E", 'O', 'U', 'I'}
for i in range(len(word)-2, 0, -1):
if word[i] in vowels:
if (word[i+1] not in vowels) and (word[i-1] not in vowels):
return word[i]
return ""
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum(arr, k):
""" Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. 1. The l... | if k == 0:
return []
arr.sort()
ans = arr[-k:]
return ans
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solution(lst):
"""Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples """ | return sum([x for idx, x in enumerate(lst) if idx%2==0 and x%2==1])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_elements(arr, k):
""" Given a non-empty array of integers arr and an integer k, return the sum of the elements with at most two digits from the first ... | return sum(elem for elem in arr[:k] if len(str(elem)) <= 2)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_odd_collatz(n):
""" Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence. The Collatz conjecture is a conject... | if n%2==0:
odd_collatz = []
else:
odd_collatz = [n]
while n > 1:
if n % 2 == 0:
n = n/2
else:
n = n*3 + 1
if n%2 == 1:
odd_collatz.append(int(n))
return sorted(odd_collatz)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_date(date):
"""You have to write a function which validates a given date string and returns True if the date is valid otherwise False. 1. The date s... | try:
date = date.strip()
month, day, year = date.split('-')
month, day, year = int(month), int(day), int(year)
if month < 1 or month > 12:
return False
if month in [1,3,5,7,8,10,12] and day < 1 or day > 31:
return False
if month in [4,6,9,11] a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(interval1, interval2):
"""You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, ... | def is_prime(num):
if num == 1 or num == 0:
return False
if num == 2:
return True
for i in range(2, num):
if num%i == 0:
return False
return True
l = max(interval1[0], interval2[0])
r = min(interval1[1], interval2[1])
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prod_signs(arr):
""" You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of eac... | if not arr: return None
prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr)))
return prod * sum([abs(i) for i in arr])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minPath(grid, k):
""" Given a grid with N rows and N columns (N >= 2) and a positive integer k, inclusive appears exactly once on the cells of the grid. Y... | n = len(grid)
val = n * n + 1
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
temp = []
if i != 0:
temp.append(grid[i - 1][j])
if j != 0:
temp.append(grid[i][j - 1])
if i !... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tri(n):
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tri... | if n == 0:
return [1]
my_tri = [1, 3]
for i in range(2, n + 1):
if i % 2 == 0:
my_tri.append(i / 2 + 1)
else:
my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2)
return my_tri
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def digits(n):
"""Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. digits(1) == 1 digits(4) == 0 digits(235)... | product = 1
odd_count = 0
for digit in str(n):
int_digit = int(digit)
if int_digit%2 == 1:
product= product*int_digit
odd_count+=1
if odd_count ==0:
return 0
else:
return product
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sum_squares(lst):
"""You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to ... | import math
squared = 0
for i in lst:
squared += math.ceil(i)**2
return squared
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_arrange(arr):
"""Create a function which returns the largest index of an element which is not greater than or equal to the element immediately precedi... | ind=-1
i=1
while i<len(arr):
if arr[i]<arr[i-1]:
ind=i
i+=1
return ind
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_one(a, b):
""" Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given v... | temp_a, temp_b = a, b
if isinstance(temp_a, str): temp_a = temp_a.replace(',','.')
if isinstance(temp_b, str): temp_b = temp_b.replace(',','.')
if float(temp_a) == float(temp_b): return None
return a if float(temp_a) > float(temp_b) else b
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_equal_to_sum_even(n):
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers Example is_equal_to_sum_even(... | return n%2 == 0 and n >= 8
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def special_factorial(n):
""" where n > 0 288 The function will receive an integer as input and should return the special factorial of this integer. """ | fact_i = 1
special_fact = 1
for i in range(1, n+1):
fact_i *= i
special_fact *= fact_i
return special_fact
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_spaces(text):
""" Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all... | new_text = ""
i = 0
start, end = 0, 0
while i < len(text):
if text[i] == " ":
end += 1
else:
if end - start > 2:
new_text += "-"+text[i]
elif end - start > 0:
new_text += "_"*(end - start)+text[i]
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_name_check(file_name):
"""Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and r... | suf = ['txt', 'exe', 'dll']
lst = file_name.split(sep='.')
if len(lst) != 2:
return 'No'
if not lst[1] in suf:
return 'No'
if len(lst[0]) == 0:
return 'No'
if not lst[0][0].isalpha():
return 'No'
t = len([x for x in lst[0] if x.isdigit()])
if t > 3:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sum_squares(lst):
"""" This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index... | result =[]
for i in range(len(lst)):
if i %3 == 0:
result.append(lst[i]**2)
elif i % 4 == 0 and i%3 != 0:
result.append(lst[i]**3)
else:
result.append(lst[i])
return sum(result)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def words_in_sentence(sentence):
""" You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to re... | new_lst = []
for word in sentence.split():
flg = 0
if len(word) == 1:
flg = 1
for i in range(2, len(word)):
if len(word)%i == 0:
flg = 1
if flg == 0 or len(word) == 2:
new_lst.append(word)
return " ".join(new_lst)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simplify(x, n):
"""Your task is to implement a function that will simplify the expression otherwise. Both x and n, are string representation of a fraction... | a, b = x.split("/")
c, d = n.split("/")
numerator = int(a) * int(c)
denom = int(b) * int(d)
if (numerator/denom == int(numerator/denom)):
return True
return False
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order_by_points(nums):
""" Write a function which sorts the given list of integers in ascending order according to the sum of their digits. order them bas... | def digits_sum(n):
neg = 1
if n < 0: n, neg = -1 * n, -1
n = [int(i) for i in str(n)]
n[0] = n[0] * neg
return sum(n)
return sorted(nums, key=digits_sum)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def specialFilter(nums):
"""Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 ... |
count = 0
for num in nums:
if num > 10:
odd_digits = (1, 3, 5, 7, 9)
number_as_string = str(num)
if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits:
count += 1
return count
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_max_triples(n):
""" You are given a positive integer n. You have to create an integer array a of length n. Return the number of triples (a[i], a[j], a... | A = [i*i - i + 1 for i in range(1,n+1)]
ans = []
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
if (A[i]+A[j]+A[k])%3 == 0:
ans += [(A[i],A[j],A[k])]
return len(ans)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_list_sum(lst):
"""Write a function that accepts a list of strings as a parameter, deletes the strings that have odd lengths from it, and returns th... | lst.sort()
new_lst = []
for i in lst:
if len(i)%2 == 0:
new_lst.append(i)
return sorted(new_lst, key=len)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def x_or_y(n, x, y):
"""A simple program which should return the value of x if n is a prime number and should return the value of y otherwise. for x_or_y(7, 3... | if n == 1:
return y
for i in range(2, n):
if n % i == 0:
return y
break
else:
return x
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(game,guess):
"""I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you ha... | return [abs(x-y) for x,y in zip(game,guess)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Strongest_Extension(class_name, extensions):
"""You will be given the name of a class (a string) and a list of extensions. The extensions are to be used t... | strong = extensions[0]
my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()])
for s in extensions:
val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()])
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cycpattern_check(a , b):
"""You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word """ | l = len(b)
pat = b + b
for i in range(len(a) - l + 1):
for j in range(l + 1):
if a[i:i+l] == pat[j:j+l]:
return True
return False
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def even_odd_count(num):
"""Given an integer. return a tuple that has the number of even and odd digits respectively. """ | even_count = 0
odd_count = 0
for i in str(abs(num)):
if int(i)%2==0:
even_count +=1
else:
odd_count +=1
return (even_count, odd_count)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def int_to_mini_roman(number):
""" Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. """ | num = [1, 4, 5, 9, 10, 40, 50, 90,
100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL",
"L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
res = ''
while number:
div = number // num[i]
number %= num[i]
while div:
res += sym[i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_max(words):
"""Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique char... | return sorted(words, key = lambda x: (-len(set(x)), x))[0]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eat(number, need, remaining):
""" You're a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to ... | if(need <= remaining):
return [ number + need , remaining-need ]
else:
return [ number + remaining , 0]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_algebra(operator, operand):
""" Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of in... | expression = str(operand[0])
for oprt, oprn in zip(operator, operand[1:]):
expression+= oprt + str(oprn)
return eval(expression)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(s):
"""You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string ... | flg = 0
idx = 0
new_str = list(s)
for i in s:
if i.isalpha():
new_str[idx] = i.swapcase()
flg = 1
idx += 1
s = ""
for i in new_str:
s += i
if flg == 0:
return s[len(s)::-1]
return s
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string_to_md5(text):
""" Given a string 'text', return its md5 hash equivalent string. If 'text' is an empty string, return None. """ | import hashlib
return hashlib.md5(text.encode('ascii')).hexdigest() if text else None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_integers(a, b):
""" Given two positive integers a and b, return the even digits between a and b, in ascending order. """ | lower = max(2, min(a, b))
upper = min(8, max(a, b))
return [i for i in range(lower, upper+1) if i % 2 == 0]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __multiscale_gc_lo2hi_run(self):
# , pyed):
""" Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed no... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self._msgc_lo2hi_resize_init()
self.__msgc_step0_init()
hard_constraints = self.__msgc_step12_low_resolution_segmentation()
# ===== high resolution data processing
seg = self.__msgc_step3_dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __multiscale_gc_hi2lo_run(self):
# , pyed):
""" Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed ... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self.__msgc_step0_init()
hard_constraints = self.__msgc_step12_low_resolution_segmentation()
# ===== high resolution data processing
seg = self.__msgc_step3_discontinuity_localization()
nlink... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __hi2lo_multiscale_indexes(self, mask, orig_shape):
# , zoom):
""" Function computes multiscale indexes of ndarray. mask: Says where is original resolution ... |
mask_orig = zoom_to_shape(mask, orig_shape, dtype=np.int8)
inds_small = np.arange(mask.size).reshape(mask.shape)
inds_small_in_orig = zoom_to_shape(inds_small, orig_shape, dtype=np.int8)
inds_orig = np.arange(np.prod(orig_shape)).reshape(orig_shape)
# inds_orig = inds_orig * ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interactivity(self, min_val=None, max_val=None, qt_app=None):
""" Interactive seed setting with 3d seed editor """ |
from .seed_editor_qt import QTSeedEditor
from PyQt4.QtGui import QApplication
if min_val is None:
min_val = np.min(self.img)
if max_val is None:
max_val = np.max(self.img)
window_c = (max_val + min_val) / 2 # .astype(np.int16)
window_w = max_v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, run_fit_model=True):
""" Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the mode... |
if run_fit_model:
self.fit_model(self.img, self.voxelsize, self.seeds)
self._start_time = time.time()
if self.segparams["method"].lower() in ("graphcut", "gc"):
self.__single_scale_gc_run()
elif self.segparams["method"].lower() in (
"multiscale_grap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __similarity_for_tlinks_obj_bgr( self, data, voxelsize, # voxels1, voxels2, # seeds, otherfeatures=None ):
""" Compute edge values for graph cut tlinks based... |
# self.fit_model(data, voxelsize, seeds)
# There is a need to have small vaues for good fit
# R(obj) = -ln( Pr (Ip | O) )
# R(bck) = -ln( Pr (Ip | B) )
# Boykov2001b
# ln is computed in likelihood
tdata1 = (-(self.mdl.likelihood_from_image(data, voxelsize, 1))) *... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ssgc_prepare_data_and_run_computation( self, # voxels1, voxels2, hard_constraints=True, area_weight=1, ):
""" Setting of data. You need set seeds if you wan... |
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
# import pdb; pdb.set_trace() # BREAKPOINT
unariesalt = self.__create_tlinks(
self.img,
self.voxelsize,
# voxels1, voxels2,
self.seeds,
area_weight,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seed_zoom(seeds, zoom):
""" Smart zoom for sparse matrix. If there is resize to bigger resolution thin line of label could be lost. This function prefers lab... |
# import scipy
# loseeds=seeds
labels = np.unique(seeds)
# remove first label - 0
labels = np.delete(labels, 0)
# @TODO smart interpolation for seeds in one block
# loseeds = scipy.ndimage.interpolation.zoom(
# seeds, zoom, order=0)
loshape = np.ceil(np.array(seeds... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zoom_to_shape(data, shape, dtype=None):
""" Zoom data to specific shape. """ |
import scipy
import scipy.ndimage
zoomd = np.array(shape) / np.array(data.shape, dtype=np.double)
import warnings
datares = scipy.ndimage.interpolation.zoom(data, zoomd, order=0, mode="reflect")
if datares.shape != shape:
logger.warning("Zoom with different output shape")
dataout... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crop(data, crinfo):
""" Crop the data. crop(data, crinfo) :param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]] """ |
crinfo = fix_crinfo(crinfo)
return data[
__int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]),
__int_or_none(crinfo[1][0]) : __int_or_none(crinfo[1][1]),
__int_or_none(crinfo[2][0]) : __int_or_none(crinfo[2][1]),
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combinecrinfo(crinfo1, crinfo2):
""" Combine two crinfos. First used is crinfo1, second used is crinfo2. """ |
crinfo1 = fix_crinfo(crinfo1)
crinfo2 = fix_crinfo(crinfo2)
crinfo = [
[crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]],
[crinfo1[1][0] + crinfo2[1][0], crinfo1[1][0] + crinfo2[1][1]],
[crinfo1[2][0] + crinfo2[2][0], crinfo1[2][0] + crinfo2[2][1]],
]
return c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crinfo_from_specific_data(data, margin=0):
""" Create crinfo of minimum orthogonal nonzero block in input data. :param data: input data :param margin: add ma... |
# hledáme automatický ořez, nonzero dá indexy
logger.debug("crinfo")
logger.debug(str(margin))
nzi = np.nonzero(data)
logger.debug(str(nzi))
if np.isscalar(margin):
margin = [margin] * 3
x1 = np.min(nzi[0]) - margin[0]
x2 = np.max(nzi[0]) + margin[0] + 1
y1 = np.min(nzi[1]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
""" Put some boundary to input image. :param data: input data :param crinfo:... |
if crinfo is None:
crinfo = list(zip([0] * data.ndim, orig_shape))
elif np.asarray(crinfo).size == data.ndim:
crinfo = list(zip(crinfo, np.asarray(crinfo) + data.shape))
crinfo = fix_crinfo(crinfo)
data_out = np.ones(orig_shape, dtype=data.dtype) * cval
# print 'uncrop ', crinfo
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_crinfo(crinfo, to="axis"):
""" Function recognize order of crinfo and convert it to proper format. """ |
crinfo = np.asarray(crinfo)
if crinfo.shape[0] == 2:
crinfo = crinfo.T
return crinfo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_grid_2d(shape, voxelsize):
""" Generate list of edges for a base grid. """ |
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
sh = copy.copy(list(shape))
sh[direction] += -1
nedges += nm.prod(sh)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_nodes(self, coors, node_low_or_high=None):
""" Add new nodes at the end of the list. """ |
last = self.lastnode
if type(coors) is nm.ndarray:
if len(coors.shape) == 1:
coors = coors.reshape((1, coors.size))
nadd = coors.shape[0]
idx = slice(last, last + nadd)
else:
nadd = 1
idx = self.lastnode
right_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mul_block(self, index, val):
"""Multiply values in block""" |
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_fv_by_seeds(fv, seeds=None, unique_cls=None):
""" Return features selected by seeds and unique_cls or selection from features and corresponding seed c... |
if seeds is not None:
if unique_cls is not None:
return select_from_fv_by_seeds(fv, seeds, unique_cls)
else:
raise AssertionError("Input unique_cls has to be not None if seeds is not None.")
else:
return fv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand(self, expression):
"""Expands logical constructions.""" |
self.logger.debug("expand : expression %s", str(expression))
if not is_string(expression):
return expression
result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression)
result = result.strip()
self.logger.debug('expand : %s - result : %s'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_gutter_client( alias='default', cache=CLIENT_CACHE, **kwargs ):
""" Creates gutter clients and memoizes them in a registry for future quick access. Args:... |
from gutter.client.models import Manager
if not alias:
return Manager(**kwargs)
elif alias not in cache:
cache[alias] = Manager(**kwargs)
return cache[alias] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _modulo(self, decimal_argument):
""" The mod operator is prone to floating point errors, so use decimal. 101.1 % 100 decimal_context.divmod(Decimal('100.1'),... |
_times, remainder = self._context.divmod(decimal_argument, 100)
# match the builtin % behavior by adding the N to the result if negative
return remainder if remainder >= 0 else remainder + 100 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enabled_for(self, inpt):
""" Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for th... |
signals.switch_checked.call(self)
signal_decorated = partial(self.__signal_and_return, inpt)
if self.state is self.states.GLOBAL:
return signal_decorated(True)
elif self.state is self.states.DISABLED:
return signal_decorated(False)
conditions_dict = Co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, inpt):
""" Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ... |
if inpt is Manager.NONE_INPUT:
return False
# Call (construct) the argument with the input object
argument_instance = self.argument(inpt)
if not argument_instance.applies:
return False
application = self.__apply(argument_instance, inpt)
if sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switches(self):
""" List of all switches currently registered. """ |
results = [
switch for name, switch in self.storage.iteritems()
if name.startswith(self.__joined_namespace)
]
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switch(self, name):
""" Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED... |
try:
switch = self.storage[self.__namespaced(name)]
except KeyError:
if not self.autocreate:
raise ValueError("No switch named '%s' registered in '%s'" % (name, self.namespace))
switch = self.__create_and_register_disabled_switch(name)
switc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(self, switch, signal=signals.switch_registered):
'''
Register a switch and persist it to the storage.
'''
if not switch.name:
raise ValueError('Switch name cannot be blank')
switch.manager = self
self.__persist(switch)
signal.call(switch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False):
"""Central interface to verify interactions. `verify` uses a fluent interface::... |
if isinstance(obj, str):
obj = get_obj(obj)
verification_fn = _get_wanted_verification(
times=times, atleast=atleast, atmost=atmost, between=between)
if inorder:
verification_fn = verification.InOrder(verification_fn)
# FIXME?: Catch error if obj is neither a Mock nor a known... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def when(obj, strict=None):
"""Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dumm... |
if isinstance(obj, str):
obj = get_obj(obj)
if strict is None:
strict = True
theMock = _get_mock(obj, strict=strict)
class When(object):
def __getattr__(self, method_name):
return invocation.StubbedInvocation(
theMock, method_name, strict=strict)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def when2(fn, *args, **kwargs):
"""Stub a function call with the given arguments Exposes a more pythonic interface than :func:`when`. See :func:`when` for more d... |
obj, name = get_obj_attr_tuple(fn)
theMock = _get_mock(obj, strict=True)
return invocation.StubbedInvocation(theMock, name)(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None):
"""Stub a function call, and set up an expected call count. Usage:: # Given `d... |
if strict is None:
strict = True
theMock = _get_mock(obj, strict=strict)
verification_fn = _get_wanted_verification(
times=times, atleast=atleast, atmost=atmost, between=between)
class Expect(object):
def __getattr__(self, method_name):
return invocation.StubbedInv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unstub(*objs):
"""Unstubs all stubbed methods and functions If you don't pass in any argument, *all* registered mocks and patched modules, classes etc. will ... |
if objs:
for obj in objs:
mock_registry.unstub(obj)
else:
mock_registry.unstub_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verifyZeroInteractions(*objs):
"""Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed ... |
for obj in objs:
theMock = _get_mock_or_raise(obj)
if len(theMock.invocations) > 0:
raise VerificationError(
"\nUnwanted interaction: %s" % theMock.invocations[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verifyNoUnwantedInteractions(*objs):
"""Verifies that expectations set via `expect` are met E.g.:: os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok... |
if objs:
theMocks = map(_get_mock_or_raise, objs)
else:
theMocks = mock_registry.get_registered_mocks()
for mock in theMocks:
for i in mock.stubbed_invocations:
i.verify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verifyStubbedInvocationsAreUsed(*objs):
"""Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is... |
if objs:
theMocks = map(_get_mock_or_raise, objs)
else:
theMocks = mock_registry.get_registered_mocks()
for mock in theMocks:
for i in mock.stubbed_invocations:
if not i.allow_zero_invocations and i.used < len(i.answers):
raise VerificationError("\nUnus... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_function_host(fn):
"""Destructure a given function into its host and its name. The 'host' of a function is a module, for methods it is usually its instan... |
obj = None
try:
name = fn.__name__
obj = fn.__self__
except AttributeError:
pass
if obj is None:
# Due to how python imports work, everything that is global on a module
# level must be regarded as not safe here. For now, we go for the extra
# mile, TBC,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_obj(path):
"""Return obj for given dotted path. Typical inputs for `path` are 'os' or 'os.path' in which case you get a module; or 'os.path.exists' in wh... |
# Since we usually pass in mocks here; duck typing is not appropriate
# (mocks respond to every attribute).
if not isinstance(path, str):
return path
if path.startswith('.'):
raise TypeError('relative imports are not supported')
parts = path.split('.')
head, tail = parts[0], p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spy(object):
"""Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afte... |
if inspect.isclass(object) or inspect.ismodule(object):
class_ = None
else:
class_ = object.__class__
class Spy(_Dummy):
if class_:
__class__ = class_
def __getattr__(self, method_name):
return RememberedProxyInvocation(theMock, method_name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so tha... |
if isinstance(fn, str):
answer = get_obj(fn)
else:
answer = fn
when2(fn, Ellipsis).thenAnswer(answer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def importPuppetClasses(self, smartProxyId):
""" Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETUR... |
return self.api.create('{}/{}/import_puppetclasses'
.format(self.objName, smartProxyId), '{}') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_templates(model):
""" Return a list of templates usable by a model. """ |
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_api_envs():
"""Get required API keys from environment variables.""" |
client_id = os.environ.get('CLIENT_ID')
user_id = os.environ.get('USER_ID')
if not client_id or not user_id:
raise ValueError('API keys are not found in the environment')
return client_id, user_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkAndCreate(self, key, payload, domainId):
""" Function checkAndCreate Check if a subnet exists and create it if not @param key: The targeted subnet @para... |
if key not in self:
self[key] = payload
oid = self[key]['id']
if not oid:
return False
#~ Ensure subnet contains the domain
subnetDomainIds = []
for domain in self[key]['domains']:
subnetDomainIds.append(domain['id'])
if domain... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeDomain(self, subnetId, domainId):
""" Function removeDomain Delete a domain from a subnet @param subnetId: The subnet Id @param domainId: The domainId ... |
subnetDomainIds = []
for domain in self[subnetId]['domains']:
subnetDomainIds.append(domain['id'])
subnetDomainIds.remove(domainId)
self[subnetId]["domain_ids"] = subnetDomainIds
return len(self[subnetId]["domains"]) is len(subnetDomainIds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exclusive(via=threading.Lock):
""" Mark a callable as exclusive :param via: factory for a Lock to guard the callable Guards the callable against being entere... |
def make_exclusive(fnc):
fnc_guard = via()
@functools.wraps(fnc)
def exclusive_call(*args, **kwargs):
if fnc_guard.acquire(blocking=False):
try:
return fnc(*args, **kwargs)
finally:
fnc_guard.release()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service(flavour):
r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method i... |
def service_unit_decorator(raw_cls):
__new__ = raw_cls.__new__
def __new_service__(cls, *args, **kwargs):
if __new__ is object.__new__:
self = __new__(cls)
else:
self = __new__(cls, *args, **kwargs)
service_unit = ServiceUnit(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, payload, *args, flavour: ModuleType, **kwargs):
""" Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are ... |
if args or kwargs:
payload = functools.partial(payload, *args, **kwargs)
return self._meta_runner.run_payload(payload, flavour=flavour) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adopt(self, payload, *args, flavour: ModuleType, **kwargs):
""" Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` are provided... |
if args or kwargs:
payload = functools.partial(payload, *args, **kwargs)
self._meta_runner.register_payload(payload, flavour=flavour) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accept(self):
""" Start accepting synchronous, asynchronous and service payloads Since services are globally defined, only one :py:class:`ServiceRunner` may ... |
if self._meta_runner:
raise RuntimeError('payloads scheduled for %s before being started' % self)
self._must_shutdown = False
self._logger.info('%s starting', self.__class__.__name__)
# force collecting objects so that defunct, migrated and overwritten services are destroyed... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self):
"""Shutdown the accept loop and stop running payloads""" |
self._must_shutdown = True
self._is_shutdown.wait()
self._meta_runner.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start_console(local_vars={}):
'''Starts a console; modified from code.interact'''
transforms.CONSOLE_ACTIVE = True
transforms.remove_not_allowed_in_console()
sys.ps1 = prompt
console = ExperimentalInteractiveConsole(locals=local_vars)
console.interact(banner=banner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push(self, line):
"""Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is ap... |
if transforms.FROM_EXPERIMENTAL.match(line):
transforms.add_transformers(line)
self.buffer.append("\n")
else:
self.buffer.append(line)
add_pass = False
if line.rstrip(' ').endswith(":"):
add_pass = True
source = "\n".join(self.buf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(obj, f, preserve=False):
"""Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optiona... |
if not f.write:
raise TypeError('You can only dump an object into a file object')
encoder = Encoder(f, preserve=preserve)
return encoder.write_dict(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dumps(obj, preserve=False):
"""Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline... |
f = StringIO()
dump(obj, f, preserve)
return f.getvalue() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.