common_id
stringlengths
5
5
image
stringlengths
18
18
code
stringlengths
55
1.44k
10912
Test/png/10912.png
# Write a python function to count the occurrence of a given character in a string. def count(s, c): res = 0 for i in range(len(s)): if s[i] == c: res = res + 1 return res
10174
Test/png/10174.png
def width(self): if len(self.coords) <= 1: return 0 return np.max(self.xx) - np.min(self.xx)
10623
Test/png/10623.png
def die(msg, code=-1): sys.stderr.write(msg + "\n") sys.exit(code)
10953
Test/png/10953.png
# Write a function to find the maximum sum of bi-tonic sub-sequence for the given array. def max_sum(arr, n): MSIBS = arr[:] for i in range(n): for j in range(0, i): if arr[i] > arr[j] and MSIBS[i] < MSIBS[j] + arr[i]: MSIBS[i] = MSIBS[j] + arr[i] MSDBS = arr[:] for i in range(1, n + 1): for j in range(1, i): if arr[-i] > arr[-j] and MSDBS[-i] < MSDBS[-j] + arr[-i]: MSDBS[-i] = MSDBS[-j] + arr[-i] max_sum = float("-Inf") for i, j, k in zip(MSIBS, MSDBS, arr): max_sum = max(max_sum, i + j - k) return max_sum
10801
Test/png/10801.png
# Write a function to calculate the value of 'a' to the power 'b'. def power(a, b): if b == 0: return 1 elif a == 0: return 0 elif b == 1: return a else: return a * power(a, b - 1)
10678
Test/png/10678.png
def is_redirecting(path): candidate = unipath(path, '.cpenv') return os.path.exists(candidate) and os.path.isfile(candidate)
10542
Test/png/10542.png
def param_particle_rad(self, ind): ind = self._vps(listify(ind)) return [self._i2p(i, 'a') for i in ind]
10141
Test/png/10141.png
def _append_html(self, html, before_prompt=False): self._append_custom(self._insert_html, html, before_prompt)
10227
Test/png/10227.png
def put(self, state_id): self._states.append(state_id) self._lock.notify_all() return state_id
10838
Test/png/10838.png
# Write a function to find the item with maximum frequency in a given list. from collections import defaultdict def max_occurrences(nums): dict = defaultdict(int) for i in nums: dict[i] += 1 result = max(dict.items(), key=lambda x: x[1]) return result
10405
Test/png/10405.png
def top(self): o = self.get_ordering_queryset().aggregate(Min('order')).get('order__min') self.to(o)
10494
Test/png/10494.png
def value_to_string(self, obj): value = self.value_from_object(obj) return b64encode(self._dump(value)).decode('ascii')
10383
Test/png/10383.png
def get_mappings(cls, index_name, doc_type): return cache.get(cls.get_cache_item_name(index_name, doc_type), {})
10284
Test/png/10284.png
def add_dividers(row, divider, padding): div = ''.join([padding * ' ', divider, padding * ' ']) return div.join(row)
10177
Test/png/10177.png
def word_to_id(self, word): if word in self._vocab: return self._vocab[word] else: return self._unk_id
10519
Test/png/10519.png
def publish(self, event_type, events): assert event_type in self.events current_queues.queues['stats-{}'.format(event_type)].publish(events)
10723
Test/png/10723.png
# Write a function to split a string at lowercase letters. import re def split_lowerstring(text): return re.findall("[a-z][^a-z]*", text)
10132
Test/png/10132.png
def init_session(self): default_secure(self.config) self.session = Session(config=self.config, username=u'kernel')
11251
Test/png/11251.png
# Write a function to add two numbers and print number of digits of sum. def count_digits(num1, num2): number = num1 + num2 count = 0 while number > 0: number = number // 10 count = count + 1 return count
11059
Test/png/11059.png
# Write a python function to find the first element occurring k times in a given array. def first_Element(arr, n, k): count_map = {} for i in range(0, n): if arr[i] in count_map.keys(): count_map[arr[i]] += 1 else: count_map[arr[i]] = 1 i += 1 for i in range(0, n): if count_map[arr[i]] == k: return arr[i] i += 1 return -1
10142
Test/png/10142.png
def file_read(filename): fobj = open(filename, 'r') source = fobj.read() fobj.close() return source
10873
Test/png/10873.png
# Write a python function to count characters at same position in a given string (lower and uppercase characters) as in english alphabet. def count_char_position(str1): count_chars = 0 for i in range(len(str1)): if (i == ord(str1[i]) - ord("A")) or (i == ord(str1[i]) - ord("a")): count_chars += 1 return count_chars
11076
Test/png/11076.png
# Write a function to repeat the given tuple n times. def repeat_tuples(test_tup, N): res = (test_tup,) * N return res
10340
Test/png/10340.png
def warn(txt): print("%s# %s%s%s" % (PR_WARN_CC, get_time_stamp(), txt, PR_NC)) sys.stdout.flush()
10700
Test/png/10700.png
def _addRoute(self, f, matcher): self._routes.append((f.func_name, f, matcher))
10758
Test/png/10758.png
# Write a function to find the list with minimum length using lambda function. def min_length_list(input_list): min_length = min(len(x) for x in input_list) min_list = min(input_list, key=lambda i: len(i)) return (min_length, min_list)
10423
Test/png/10423.png
def nodes_by_category(self, category): return [n for n in self.nodes if n.category == category]
10733
Test/png/10733.png
# Write a python function to find the product of non-repeated elements in a given array. def find_Product(arr, n): arr.sort() prod = 1 for i in range(0, n, 1): if arr[i - 1] != arr[i]: prod = prod * arr[i] return prod
10512
Test/png/10512.png
def rename(self, name): self._impl.system.rename_model(new_name=name, old_name=self.name)
10182
Test/png/10182.png
def addValuesToField(self, i, numValues): assert (len(self.fields) > i) values = [self.addValueToField(i) for n in range(numValues)] return values
10463
Test/png/10463.png
def _dump_to_file(self, file): xmltodict.unparse(self.object(), file, pretty=True)
10397
Test/png/10397.png
def has_delete_permission(self, request): return request.user.is_authenticated and request.user.is_active and request.user.is_superuser
11126
Test/png/11126.png
# Write a python function to find the sublist having maximum length. def Find_Max(lst): maxList = max((x) for x in lst) return maxList
10907
Test/png/10907.png
# Write a python function to find highest power of 2 less than or equal to given number. def highest_Power_of_2(n): res = 0 for i in range(n, 0, -1): if (i & (i - 1)) == 0: res = i break return res
10118
Test/png/10118.png
def loop_gtk(kernel): from .gui.gtkembed import GTKEmbed gtk_kernel = GTKEmbed(kernel) gtk_kernel.start()
10973
Test/png/10973.png
# Write a function to split a list for every nth element. def list_split(S, step): return [S[i::step] for i in range(step)]
10410
Test/png/10410.png
def _deactivate(self): self.cache.remove_fetcher(self) if self.active: self._deactivated()
10747
Test/png/10747.png
# Write a function to check if the letters of a given string can be rearranged so that two characters that are adjacent to each other are different. import heapq from collections import Counter def rearange_string(S): ctr = Counter(S) heap = [(-value, key) for key, value in ctr.items()] heapq.heapify(heap) if (-heap[0][0]) * 2 > len(S) + 1: return "" ans = [] while len(heap) >= 2: nct1, char1 = heapq.heappop(heap) nct2, char2 = heapq.heappop(heap) ans.extend([char1, char2]) if nct1 + 1: heapq.heappush(heap, (nct1 + 1, char1)) if nct2 + 1: heapq.heappush(heap, (nct2 + 1, char2)) return "".join(ans) + (heap[0][1] if heap else "")
10318
Test/png/10318.png
def set(self, ring, angle, color): pixel = self.angleToPixel(angle, ring) self._set_base(pixel, color)
10437
Test/png/10437.png
def round_any(x, accuracy, f=np.round): if not hasattr(x, 'dtype'): x = np.asarray(x) return f(x / accuracy) * accuracy
10108
Test/png/10108.png
def find_args(self): return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \ self.program + self.program_args
10759
Test/png/10759.png
# Write a function to print check if the triangle is equilateral or not. def check_equilateral(x, y, z): if x == y == z: return True else: return False
10312
Test/png/10312.png
def geo(lat, lon, radius, unit='km'): return GeoValue(lat, lon, radius, unit)
10558
Test/png/10558.png
def dump_set(self, obj, class_name=set_class_name): return {"$" + class_name: [self._json_convert(item) for item in obj]}
10545
Test/png/10545.png
def reset(self, **kwargs): self.aug_state.reset() super(LMAugmentedState, self).reset(**kwargs)
10226
Test/png/10226.png
def parse_num(source, start, charset): while start < len(source) and source[start] in charset: start += 1 return start
10137
Test/png/10137.png
def register_checker(self, checker): if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
11172
Test/png/11172.png
# Write a function to check if all values are same in a dictionary. def check_value(dict, n): result = all(x == n for x in dict.values()) return result
10638
Test/png/10638.png
def init_async(self, loop): super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
10253
Test/png/10253.png
def include(f): fl = open(f, 'r') data = fl.read() fl.close() return raw(data)
10888
Test/png/10888.png
# Write a function to calculate distance between two points using latitude and longitude. from math import radians, sin, cos, acos def distance_lat_long(slat, slon, elat, elon): dist = 6371.01 * acos( sin(slat) * sin(elat) + cos(slat) * cos(elat) * cos(slon - elon) ) return dist
10955
Test/png/10955.png
# Write a function to find the longest palindromic subsequence in the given string. def lps(str): n = len(str) L = [[0 for x in range(n)] for x in range(n)] for i in range(n): L[i][i] = 1 for cl in range(2, n + 1): for i in range(n - cl + 1): j = i + cl - 1 if str[i] == str[j] and cl == 2: L[i][j] = 2 elif str[i] == str[j]: L[i][j] = L[i + 1][j - 1] + 2 else: L[i][j] = max(L[i][j - 1], L[i + 1][j]) return L[0][n - 1]
11100
Test/png/11100.png
# Write a function to find the maximum sum possible by using the given equation f(n) = max( (f(n/2) + f(n/3) + f(n/4) + f(n/5)), n). def get_max_sum(n): res = list() res.append(0) res.append(1) i = 2 while i < n + 1: res.append( max( i, (res[int(i / 2)] + res[int(i / 3)] + res[int(i / 4)] + res[int(i / 5)]), ) ) i = i + 1 return res[n]
10634
Test/png/10634.png
def angle_rates(self): return [self.ode_obj.getAngleRate(i) for i in range(self.ADOF)]
10194
Test/png/10194.png
def timetz(self): "Return the time part, with same tzinfo." return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo)
10695
Test/png/10695.png
def sigma_prime(self): return _np.sqrt(self.emit/self.beta(self.E))
10293
Test/png/10293.png
def centerdc_2_twosided(data): N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
10651
Test/png/10651.png
def _get_new_connection(self): pool = getRedisPool(self.mdl.REDIS_CONNECTION_PARAMS) return redis.Redis(connection_pool=pool)
10781
Test/png/10781.png
# Write a function to split the given string with multiple delimiters by using regex. import re def multiple_split(text): return re.split("; |, |\*|\n", text)
11090
Test/png/11090.png
# Write a function to find the number of rotations in a circularly sorted array. def find_rotation_count(A): (left, right) = (0, len(A) - 1) while left <= right: if A[left] <= A[right]: return left mid = (left + right) // 2 next = (mid + 1) % len(A) prev = (mid - 1 + len(A)) % len(A) if A[mid] <= A[next] and A[mid] <= A[prev]: return mid elif A[mid] <= A[right]: right = mid - 1 elif A[mid] >= A[left]: left = mid + 1 return -1
10784
Test/png/10784.png
# Write a python function to count the number of squares in a rectangle. def count_Squares(m, n): if n < m: temp = m m = n n = temp return m * (m + 1) * (2 * m + 1) / 6 + (n - m) * m * (m + 1) / 2
10377
Test/png/10377.png
def toggle_pause(self): self.controller.playing = not self.controller.playing self.music.toggle_pause()
10105
Test/png/10105.png
def select_left(self): r, c = self._index self._select_index(r, c-1)
10267
Test/png/10267.png
def execute(self, task, script, **kwargs): locals().update(kwargs) exec(script)
10287
Test/png/10287.png
def markdown(tag): return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))
10849
Test/png/10849.png
# Write a function to sort a list of elements using pancake sort. def pancake_sort(nums): arr_len = len(nums) while arr_len > 1: mi = nums.index(max(nums[0:arr_len])) nums = nums[mi::-1] + nums[mi + 1 : len(nums)] nums = nums[arr_len - 1 :: -1] + nums[arr_len : len(nums)] arr_len -= 1 return nums
10822
Test/png/10822.png
# Write a function to assign frequency to each tuple in the given tuple list. from collections import Counter def assign_freq(test_list): res = [(*key, val) for key, val in Counter(test_list).items()] return str(res)
10843
Test/png/10843.png
# Write a function to find the nth hexagonal number. def hexagonal_num(n): return n * (2 * n - 1)
10301
Test/png/10301.png
def leave(self, room): self.socket.rooms.remove(self._get_room_name(room))
10589
Test/png/10589.png
def present_results(self, query_text, n=10): "Get results for the query and present them." self.present(self.query(query_text, n))
11144
Test/png/11144.png
# Write a python function to print negative numbers in a list. def neg_nos(list1): for num in list1: if num < 0: return num
11129
Test/png/11129.png
# Write a function to concatenate each element of tuple by the delimiter. def concatenate_tuple(test_tup): delim = "-" res = "".join([str(ele) + delim for ele in test_tup]) res = res[: len(res) - len(delim)] return str(res)
10657
Test/png/10657.png
def log_update(entity, update): p = {'on': entity, 'update': update} _log(TYPE_CODES.UPDATE, p)
10344
Test/png/10344.png
def start(self): self.__thread = Threads(target=self.run, args=(True, True, False)) self.__thread.setDaemon(True) self.__thread.start()
10234
Test/png/10234.png
def LT(self, a, b): return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)
11227
Test/png/11227.png
# Write a function to calculate volume of a tetrahedron. import math def volume_tetrahedron(num): volume = num**3 / (6 * math.sqrt(2)) return round(volume, 2)
10741
Test/png/10741.png
# Write a python function to convert a decimal number to binary number. def decimal_To_Binary(N): B_Number = 0 cnt = 0 while N != 0: rem = N % 2 c = pow(10, cnt) B_Number += rem * c N //= 2 cnt += 1 return B_Number
10671
Test/png/10671.png
def fmt(a, b): return 100 * np.min([a, b], axis=0).sum() / np.max([a, b], axis=0).sum()
10258
Test/png/10258.png
def mh_digest(data): num_perm = 512 m = MinHash(num_perm) for d in data: m.update(d.encode('utf8')) return m
11015
Test/png/11015.png
# Write a function to get a colon of a tuple. from copy import deepcopy def colon_tuplex(tuplex, m, n): tuplex_colon = deepcopy(tuplex) tuplex_colon[m].append(n) return tuplex_colon
10175
Test/png/10175.png
def log_if(level, msg, condition, *args): if condition: vlog(level, msg, *args)
10246
Test/png/10246.png
def t_tabbedheredoc(self, t): r'<<-\S+\r?\n' t.lexer.is_tabbed = True self._init_heredoc(t) t.lexer.begin('tabbedheredoc')
10752
Test/png/10752.png
# Write a function that matches a word at the beginning of a string. import re def text_match_string(text): patterns = "^\w+" if re.search(patterns, text): return "Found a match!" else: return "Not matched!"
10969
Test/png/10969.png
# Write a function to perform mathematical division operation across the given tuples. def division_elements(test_tup1, test_tup2): res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) return res
10941
Test/png/10941.png
# Write a function to find the lateral surface area of a cylinder. def lateralsuface_cylinder(r, h): lateralsurface = 2 * 3.1415 * r * h return lateralsurface
10929
Test/png/10929.png
# Write a python function to find the first even number in a given list of numbers. def first_even(nums): first_even = next((el for el in nums if el % 2 == 0), -1) return first_even
11191
Test/png/11191.png
# Write a python function to find the first natural number whose factorial is divisible by x. def first_Factorial_Divisible_Number(x): i = 1 fact = 1 for i in range(1, x): fact = fact * i if fact % x == 0: break return i
10667
Test/png/10667.png
def mfbe(a, b): return 2 * bias(a, b) / (a.mean() + b.mean())
10323
Test/png/10323.png
def fillRGB(self, r, g, b, start=0, end=-1): self.fill((r, g, b), start, end)
10505
Test/png/10505.png
def sync_update_info(self, *_): loop = asyncio.get_event_loop() task = loop.create_task(self.update_info()) loop.run_until_complete(task)
10381
Test/png/10381.png
def add_data_dir(self, directory): dirs = list(self.DATA_DIRS) dirs.append(directory) self.DATA_DIRS = dirs
11212
Test/png/11212.png
# Write a python function to find the cube sum of first n natural numbers. def sum_Of_Series(n): sum = 0 for i in range(1, n + 1): sum += i * i * i return sum
10128
Test/png/10128.png
def configure(self, options, conf): self.conf = conf if not options.capture: self.enabled = False
10981
Test/png/10981.png
# Write a function to substract the contents of one tuple with corresponding index of other tuple. def substract_elements(test_tup1, test_tup2): res = tuple(map(lambda i, j: i - j, test_tup1, test_tup2)) return res
10977
Test/png/10977.png
# Write a function to find the ascii value of a character. def ascii_value(k): ch = k return ord(ch)
10881
Test/png/10881.png
# Write a function to remove everything except alphanumeric characters from a string. import re def remove_splchar(text): pattern = re.compile("[\W_]+") return pattern.sub("", text)
11242
Test/png/11242.png
# Write a function to search a literals string in a string and also find the location within the original string where the pattern occurs. import re def search_literal(pattern, text): match = re.search(pattern, text) s = match.start() e = match.end() return (s, e)
11233
Test/png/11233.png
# Write a python function to check whether two given lines are parallel or not. def parallel_lines(line1, line2): return line1[0] / line1[1] == line2[0] / line2[1]
10560
Test/png/10560.png
def dump_nparray(self, obj, class_name=numpy_ndarray_class_name): return {"$" + class_name: self._json_convert(obj.tolist())}
10306
Test/png/10306.png
def add(self, requester: int, track: dict): self.queue.append(AudioTrack().build(track, requester))