content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# # config.py: configuration for semantic segmentation # (c) Neil Nie, 2017 # All Rights Reserved. # batch_size = 8 img_height = 512 img_width = 1024 display_height = 512 display_width = 1024 nb_classes = 34 learning_rate = 1e-4 nb_epoch = 10
batch_size = 8 img_height = 512 img_width = 1024 display_height = 512 display_width = 1024 nb_classes = 34 learning_rate = 0.0001 nb_epoch = 10
# # @lc app=leetcode id=485 lang=python3 # # [485] Max Consecutive Ones # # @lc code=start class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: res = 0 count = 0 for i in nums: if i == 0: count = 0 else: count += 1...
class Solution: def find_max_consecutive_ones(self, nums: List[int]) -> int: res = 0 count = 0 for i in nums: if i == 0: count = 0 else: count += 1 res = max(res, count) return res
''' module for calculating greatest common divisor (GCD) and lowest common multiple (LCM) ''' def gcd(x: int, y: int): ''' Calculating GCD of x and y using Euclid's algorithm ''' if (x > y): while (y != 0): x, y = y, x % y return x else: while (x != 0)...
""" module for calculating greatest common divisor (GCD) and lowest common multiple (LCM) """ def gcd(x: int, y: int): """ Calculating GCD of x and y using Euclid's algorithm """ if x > y: while y != 0: (x, y) = (y, x % y) return x else: while x != 0: ...
""" For a string and pattern, count for each pattern the number of times it appears in the string """ def check_pattern_count(string, pattern): pattern_count = 0 string_length, pattern_length = len(string), len(pattern) for i in range(0, string_length - pattern_length - 1): temp_pattern_extract = ...
""" For a string and pattern, count for each pattern the number of times it appears in the string """ def check_pattern_count(string, pattern): pattern_count = 0 (string_length, pattern_length) = (len(string), len(pattern)) for i in range(0, string_length - pattern_length - 1): temp_pattern_extract...
#!/bin/python3 #I think this needs to run in c def addTuple(t1, t2): return [t1i + t2i for t1i, t2i in zip(t1, t2)] def compareTuple(t1, t2): return all([t1i <= t2i for t1i, t2i in zip(t1, t2)]) def theHackathon(n, m, a, b, f, s, t): # Participant code here people = {} groups = {} max_de...
def add_tuple(t1, t2): return [t1i + t2i for (t1i, t2i) in zip(t1, t2)] def compare_tuple(t1, t2): return all([t1i <= t2i for (t1i, t2i) in zip(t1, t2)]) def the_hackathon(n, m, a, b, f, s, t): people = {} groups = {} max_dep = (f, s, t) for i in range(n): inputdata = input().split() ...
# https://www.geeksforgeeks.org/merge-sort/ # merge(arr,l,m,r) is a key process assuming that arr[l..m] and arr[m+1..r] are sorted and merges the sub-arrays into one # Recursive implementation # Space complexity is O(n)+O(logn) counting stack frames -> still O(n) in case of arrays def mergeSort(arr): # base cas...
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 l = arr[:mid] r = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: ...
# list of lists matrix = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] # get element from list of lists x = matrix[0][0] # slice a list of lists x = matrix[0][0:2] # update element in list matrix[0][0] = -1 # remove element in list matrix[0].remove(-1) # get number of lists x = len(matrix)
matrix = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] x = matrix[0][0] x = matrix[0][0:2] matrix[0][0] = -1 matrix[0].remove(-1) x = len(matrix)
# A little about strings # Often programmers face a problem that can be solved by # analogy. You are already familiar with the string data type, # Now you need to study the relevant section of the # documentation about strings to solve this problem. In the # documentation you will find the necessary similar examples. ...
print("It isn`t in the section 'C:\\some\\name_of_file'")
def stringfixer(sentence): sentence = sentence.split() symbollst = [".","!","?"] flag = False count = 0 final = "" for elm in sentence: if count ==0: elm = elm.capitalize() count += 1 if flag: elm = elm.capitalize() flag = False ...
def stringfixer(sentence): sentence = sentence.split() symbollst = ['.', '!', '?'] flag = False count = 0 final = '' for elm in sentence: if count == 0: elm = elm.capitalize() count += 1 if flag: elm = elm.capitalize() flag = False ...
class Node: """ this is the constructor. """ def __init__ (self, val = None, next = None): self.val = val self.next = next class LinkedList: """ stores reference to head node, and interacts with nodes, but is not a node. """ def __init__(self): self.head = None ...
class Node: """ this is the constructor. """ def __init__(self, val=None, next=None): self.val = val self.next = next class Linkedlist: """ stores reference to head node, and interacts with nodes, but is not a node. """ def __init__(self): self.head = None ...
test_json = [] test_json.append("""{"log":[ {"user_responses":[ {"description":"test autologging 2 "}, ]}, {"autogeneratated":[ {"status":""}, {"files":[ {"name":"./sample/interface_deck_2D_decomp/head/interface_deck_2D_decomp.cc","size":79168,"last_modified":1528904996}, {"name":"./s...
test_json = [] test_json.append('{"log":[\n{"user_responses":[\n {"description":"test autologging 2\n"},\n]},\n{"autogeneratated":[ {"status":""},\n {"files":[\n {"name":"./sample/interface_deck_2D_decomp/head/interface_deck_2D_decomp.cc","size":79168,"last_modified":1528904996},\n {"name...
def positive_or_negative(value): if value > 0: return "Positive!" elif value < 0: return "Negative!" else: return "It's zero!" number = int(input("Wprowadz liczbe: ")) print(positive_or_negative(number))
def positive_or_negative(value): if value > 0: return 'Positive!' elif value < 0: return 'Negative!' else: return "It's zero!" number = int(input('Wprowadz liczbe: ')) print(positive_or_negative(number))
"""Traffic generator package using scapy Scapy Documentation: http://www.secdev.org/projects/scapy/doc/ """
"""Traffic generator package using scapy Scapy Documentation: http://www.secdev.org/projects/scapy/doc/ """
""" Draw tree like structures using Space Colonization algorithm https://www.youtube.com/watch?v=kKT0v3qhIQY https://medium.com/@jason.webb/space-colonization-algorithm-in-javascript-6f683b743dc5 """ add_library('svg') leaf_prob = 0.01 # ratio of non-white pixels that are converted to leaves max_dist = 50 # max dist...
""" Draw tree like structures using Space Colonization algorithm https://www.youtube.com/watch?v=kKT0v3qhIQY https://medium.com/@jason.webb/space-colonization-algorithm-in-javascript-6f683b743dc5 """ add_library('svg') leaf_prob = 0.01 max_dist = 50 min_dist = 4 branch_len = 3 tree = None class Leaf: def __init_...
command = input().split("|") energy = 100 coins = 100 clear_event = True for current_command in command: current_command = current_command.split("-") event = current_command[0] number = int(current_command[1]) if event == "rest": needed_energy = 100 - energy gained_energy = min(numbe...
command = input().split('|') energy = 100 coins = 100 clear_event = True for current_command in command: current_command = current_command.split('-') event = current_command[0] number = int(current_command[1]) if event == 'rest': needed_energy = 100 - energy gained_energy = min(number, n...
class EventLogEntryCollection(object): """ Defines size and enumerators for a collection of System.Diagnostics.EventLogEntry instances. """ def ZZZ(self): """hardcoded/mock instance of the class""" return EventLogEntryCollection() instance=ZZZ() """hardcoded/returns an instance of the class""" def CopyT...
class Eventlogentrycollection(object): """ Defines size and enumerators for a collection of System.Diagnostics.EventLogEntry instances. """ def zzz(self): """hardcoded/mock instance of the class""" return event_log_entry_collection() instance = zzz() 'hardcoded/returns an instance of th...
def diff_tests(input_files): tests = [] updates = [] for input_file in input_files: genrule_name = "gen_{}.actual".format(input_file) actual_file = "{}.actual".format(input_file) native.genrule( name = genrule_name, srcs = [input_file], outs = [a...
def diff_tests(input_files): tests = [] updates = [] for input_file in input_files: genrule_name = 'gen_{}.actual'.format(input_file) actual_file = '{}.actual'.format(input_file) native.genrule(name=genrule_name, srcs=[input_file], outs=[actual_file], tools=['//main:as-tree'], cmd='$...
#----------------------------------------------------------------------------- # Name: Looping Structures - While (loopingWhile.py) # Purpose: To provide information about how while loops work as a looping # structure in Python # # Author: Mr. Seidel # Created: 17-Aug-2018 # Updated: 22-Aug...
count = 1 while count < 10: print(str(x + count)) count = count + 1 count = 275 while count > 250: count = count - 1 if count % 2 == 0: print(str(z) + ': This number is even') count = 1 while count == 1: print('Count is equal to the number 1') count = 1 while count < 10: print(str(2 * co...
print("Akshitha Sai"); print("AM.EN.U4CSE18122"); print("CSE"); print("marvel rocks");
print('Akshitha Sai') print('AM.EN.U4CSE18122') print('CSE') print('marvel rocks')
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { # GN version: //ios/net:ios_net_unittests 'target_name': 'ios_net_unittests',...
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'ios_net_unittests', 'type': '<(gtest_target_type)', 'dependencies': ['../../base/base.gyp:base', '../../base/base.gyp:run_all_unittests', '../../net/net.gyp:net_test_support', '../../testing/gtest.gyp:gtest', '../../url/url.gyp:url_lib', 'ios_net.gyp:ios_...
def test_password(con): """Called by GitHub Actions with auth method password. We just need to check that we can get a connection. """ pass
def test_password(con): """Called by GitHub Actions with auth method password. We just need to check that we can get a connection. """ pass
n = int(input("Enter N: ")) l = [] for i in range(0 , n): inp = int(input("Enter numbers: ")) l.append(inp) l.sort() a = 0 b = 0 for i in range(0 , n): if i % 2 != 0: a = a * 10 + l[i] else: b = b * 10 + l[i] c = a + b print(c)
n = int(input('Enter N: ')) l = [] for i in range(0, n): inp = int(input('Enter numbers: ')) l.append(inp) l.sort() a = 0 b = 0 for i in range(0, n): if i % 2 != 0: a = a * 10 + l[i] else: b = b * 10 + l[i] c = a + b print(c)
help = '''tdo -- A todo list tool for the terminal. Available commands: tdo Lists all undone tasks, sorted by category. tdo all Lists all tasks. tdo add "task" [list] Add a task to a certain list or the default list. tdo edit id Edit a task description. tdo done id ...
help = 'tdo -- A todo list tool for the terminal.\n\nAvailable commands:\ntdo Lists all undone tasks, sorted by category.\ntdo all Lists all tasks.\ntdo add "task" [list] Add a task to a certain list or the default list.\ntdo edit id Edit a task description.\ntdo done i...
game_list = { "games": [ "4story", "8bitmmo", "9dragons", "9lives-arena", "a-tale-in-the-desert", "a3", "a3-still-alive", "aberoth", "ace-online", "achaea", "ad2460", "adventure-land", "adventure-quest-3d", "adventurequest-worlds", ...
game_list = {'games': ['4story', '8bitmmo', '9dragons', '9lives-arena', 'a-tale-in-the-desert', 'a3', 'a3-still-alive', 'aberoth', 'ace-online', 'achaea', 'ad2460', 'adventure-land', 'adventure-quest-3d', 'adventurequest-worlds', 'aetolia-the-midnight-age', 'age-of-conan-unchained', 'age-of-the-four-clans', 'age-of-wus...
# For demonstration this will serve as the database of partners # For real implementation this will come from a database. # Both partnerId and key should be shared between services. partners = { 'abcd123' : { # this is partner ssoId (abcd123) 'name': 'Partner 1 inc.', 'shared_key' : '5f4dcc3b...
partners = {'abcd123': {'name': 'Partner 1 inc.', 'shared_key': '5f4dcc3b5aa765d61d8327deb882cf99', 'is_active': True}, 'abcd1234': {'name': 'Partner 2 inc.', 'shared_key': '482c811da5d5b4bc6d497ffa98491e38', 'is_active': False}}
#!/usr/bin/env python3 steps = 10 with open('input.txt', 'r') as f: lines = f.read().splitlines() initial_string = lines[0] mapping = {} for line in lines: if '->' in line: x,y=line.split(" -> ") replacement_text = x[0]+y mapping[x] = replacement_text for _ in range(1, steps+1): processed_string = '' fo...
steps = 10 with open('input.txt', 'r') as f: lines = f.read().splitlines() initial_string = lines[0] mapping = {} for line in lines: if '->' in line: (x, y) = line.split(' -> ') replacement_text = x[0] + y mapping[x] = replacement_text for _ in range(1, steps + 1): processed_stri...
#Occurance of a word in text file Text = open("abc.txt","r") d = dict() #Dictionary to store words(keys) and its iterations(values) # iterate through each line in txt file for line in Text: line = line.strip() #remove leading space and \n chrtr line = line.lower() #convert to lower case words = line.spl...
text = open('abc.txt', 'r') d = dict() for line in Text: line = line.strip() line = line.lower() words = line.split(' ') for word in words: if word in d: d[word] += 1 else: d[word] = 1 for key in list(d.keys()): print(key, ':', d[key])
# Easy horntail gem sm.spawnMob(8810102, 95, 260, False) sm.spawnMob(8810103, 95, 260, False) sm.spawnMob(8810104, 95, 260, False) sm.spawnMob(8810105, 95, 260, False) sm.spawnMob(8810106, 95, 260, False) sm.spawnMob(8810107, 95, 260, False) sm.spawnMob(8810108, 95, 260, False) sm.spawnMob(8810109, 95, 260, False) sm.s...
sm.spawnMob(8810102, 95, 260, False) sm.spawnMob(8810103, 95, 260, False) sm.spawnMob(8810104, 95, 260, False) sm.spawnMob(8810105, 95, 260, False) sm.spawnMob(8810106, 95, 260, False) sm.spawnMob(8810107, 95, 260, False) sm.spawnMob(8810108, 95, 260, False) sm.spawnMob(8810109, 95, 260, False) sm.spawnMob(8810118, 95,...
# file generated by setuptools_scm # don't change, don't track in version control version = "0.1.dev1+ga7b326d.d20210618" version_tuple = (0, 1, "dev1+ga7b326d", "d20210618")
version = '0.1.dev1+ga7b326d.d20210618' version_tuple = (0, 1, 'dev1+ga7b326d', 'd20210618')
""" Prepare arguments for goldclip pipeline """ def args_init(args=None, demx=False, trim=False, align=False, call_peak=False): """Inititate the arguments, assign the default values to arg """ if isinstance(args, dict): pass elif args is None: args = {} # init d...
""" Prepare arguments for goldclip pipeline """ def args_init(args=None, demx=False, trim=False, align=False, call_peak=False): """Inititate the arguments, assign the default values to arg """ if isinstance(args, dict): pass elif args is None: args = {} else: raise excep...
pattern_zero=[0.0, 0.024983563445, 0.048652202498, 0.051282051282, 0.07100591716, 0.076265614727, 0.092044707429, 0.09993425378, 0.102564102564, 0.111768573307, 0.122287968442, 0.127547666009, 0.130177514793, 0.143326758711, 0.147271531887, 0.151216305062, 0.153846153846, 0.163050624589, 0.173570019724, 0.177514792899,...
pattern_zero = [0.0, 0.024983563445, 0.048652202498, 0.051282051282, 0.07100591716, 0.076265614727, 0.092044707429, 0.09993425378, 0.102564102564, 0.111768573307, 0.122287968442, 0.127547666009, 0.130177514793, 0.143326758711, 0.147271531887, 0.151216305062, 0.153846153846, 0.163050624589, 0.173570019724, 0.17751479289...
class Solution: def findRepeatNumber(self, nums: List[int]) -> int: s = set() for _ in nums: if _ not in s: s.add(_) else: return _
class Solution: def find_repeat_number(self, nums: List[int]) -> int: s = set() for _ in nums: if _ not in s: s.add(_) else: return _
def dfs(vertex): global reachable_vertex global visited_vertex if visited_vertex[vertex] is True: return visited_vertex[vertex] = True reachable_vertex.append(vertex) for i in range(0, vertex_num): if adjacent_matrix[vertex][i] is True: dfs(i) vertex_num = int(inp...
def dfs(vertex): global reachable_vertex global visited_vertex if visited_vertex[vertex] is True: return visited_vertex[vertex] = True reachable_vertex.append(vertex) for i in range(0, vertex_num): if adjacent_matrix[vertex][i] is True: dfs(i) vertex_num = int(input()...
# 14.2.5 Python Implementation class Graph: """Representation of a simple graph using an adjacency map.""" #------------------------- nested Vertex class ------------------------- class Vertex: """Lightweight vertex structure for a graph.""" __slots__ = '_element' def __init__(sel...
class Graph: """Representation of a simple graph using an adjacency map.""" class Vertex: """Lightweight vertex structure for a graph.""" __slots__ = '_element' def __init__(self, x): """Do not call constructor directly. Use Graph's insert_vertex(x). ...
N, K=map(int, input().split()) arr=[] result=0 for i in range(N): arr.append(int(input())) for i in range(N-1, -1, -1): if K==0: break else: result+=K//arr[i] K=K%arr[i] print(result)
(n, k) = map(int, input().split()) arr = [] result = 0 for i in range(N): arr.append(int(input())) for i in range(N - 1, -1, -1): if K == 0: break else: result += K // arr[i] k = K % arr[i] print(result)
""" 413. Reverse Integer https://www.lintcode.com/problem/reverse-integer/description?_from=ladder&&fromId=37 """ class Solution: """ @param n: the integer to be reversed @return: the reversed integer """ def reverseInteger(self, n): # write your code here a = str(abs(n)) ...
""" 413. Reverse Integer https://www.lintcode.com/problem/reverse-integer/description?_from=ladder&&fromId=37 """ class Solution: """ @param n: the integer to be reversed @return: the reversed integer """ def reverse_integer(self, n): a = str(abs(n)) sign = n > 0 res = int(...
class Token: """Token representation class""" def __init__(self, token_type, lexeme, literal, line): self.type = token_type self.lexeme = lexeme self.literal = literal self.line = line def __str__(self): if self.lexeme: return self.lexeme else: ...
class Token: """Token representation class""" def __init__(self, token_type, lexeme, literal, line): self.type = token_type self.lexeme = lexeme self.literal = literal self.line = line def __str__(self): if self.lexeme: return self.lexeme else: ...
myl1 = [12,10,38,22] myl1.sort(reverse = True) print(myl1) myl1.sort(reverse = False) print(myl1)
myl1 = [12, 10, 38, 22] myl1.sort(reverse=True) print(myl1) myl1.sort(reverse=False) print(myl1)
"""Bundles all exceptions and warnings used in the package prodsim""" class InvalidValue(Exception): """ Raises when a value is not within the permissible range """ pass class InvalidType(Exception): """ Raises when a value has the wrong type """ pass class MissingParameter(Exception): """ Raised...
"""Bundles all exceptions and warnings used in the package prodsim""" class Invalidvalue(Exception): """ Raises when a value is not within the permissible range """ pass class Invalidtype(Exception): """ Raises when a value has the wrong type """ pass class Missingparameter(Exception): """ Raised...
def minSwap(arr, n, k) : # Find count of elements # which are less than # equals to k count = 0 for i in range(0, n) : if (arr[i] <= k) : count = count + 1 # Find unwanted elements # in current window of # size 'count' bad = ...
def min_swap(arr, n, k): count = 0 for i in range(0, n): if arr[i] <= k: count = count + 1 bad = 0 for i in range(0, count): if arr[i] > k: bad = bad + 1 ans = bad j = count for i in range(0, n): if j == n: break if arr[i] >...
#!/usr/bin/python # -*- coding: utf-8 -*- """CatSystem 2 PE executable information WARNING: This module is deprecated, and will be changed or removed, once it's made obsolete. """ __version__ = '0.0.1' __date__ = '2020-01-01' __author__ = 'Robert Jordan' #################################################...
"""CatSystem 2 PE executable information WARNING: This module is deprecated, and will be changed or removed, once it's made obsolete. """ __version__ = '0.0.1' __date__ = '2020-01-01' __author__ = 'Robert Jordan'
class CSVWriter: """Class that represents the structure of a CSV file writer Author: Luis Marques """ def __init__(self, filename: str, header: tuple, file_type: str = "w"): """Creates an instance of a CSV file writer Args: filename (str): string to define the name of the ...
class Csvwriter: """Class that represents the structure of a CSV file writer Author: Luis Marques """ def __init__(self, filename: str, header: tuple, file_type: str='w'): """Creates an instance of a CSV file writer Args: filename (str): string to define the name of the fi...
class Product: def __init__(self, name="", price=0.0, discountPercent=0): self.name = name self.price = price self.discountPercent = discountPercent def getDiscountAmount(self): return self.price * self.discountPercent / 100 def getDiscountPrice(self): return self.p...
class Product: def __init__(self, name='', price=0.0, discountPercent=0): self.name = name self.price = price self.discountPercent = discountPercent def get_discount_amount(self): return self.price * self.discountPercent / 100 def get_discount_price(self): return s...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: slow, fast = head, head tot = 0 while fast and fast.next: fast = ...
class Solution: def is_palindrome(self, head: ListNode) -> bool: (slow, fast) = (head, head) tot = 0 while fast and fast.next: fast = fast.next.next slow = slow.next if not fast: mid = slow else: mid = slow.next mid = s...
n = int(input()) count = 0 for i in range(n): one_word = list(input()) count_arr = [0 for _ in range(26)] pre = "" for c in one_word: idx = ord(c) - 97 cur = c if (count_arr[idx] == 0) or (pre == cur): count_arr[idx] += 1 pre = c if sum(count_arr) == len(o...
n = int(input()) count = 0 for i in range(n): one_word = list(input()) count_arr = [0 for _ in range(26)] pre = '' for c in one_word: idx = ord(c) - 97 cur = c if count_arr[idx] == 0 or pre == cur: count_arr[idx] += 1 pre = c if sum(count_arr) == len(one_w...
p=21888242871839275222246405745257275088696311157297823662689037894645226208583 print("over 253 bit") for i in range (10): print(i, (p * i) >> 253) def maxarg(x): return x // p print("maxarg") for i in range(16): print(i, maxarg(i << 253)) x=0x2c130429c1d4802eb8703197d038ebd5109f96aee333bd027963094f5bb33ad y =...
p = 21888242871839275222246405745257275088696311157297823662689037894645226208583 print('over 253 bit') for i in range(10): print(i, p * i >> 253) def maxarg(x): return x // p print('maxarg') for i in range(16): print(i, maxarg(i << 253)) x = 1245960260290650057564252865548478619374135861792959100192203205...
""" Configuration for development - change these with caution! """ REGION_DIMS = (512, 512) DEFAULT_FILTRATION_STATUS = None DEFAULT_FILTRATION_CACHE_FILEPATH = "filtration_cache.h5" DEFULAT_FILTRATION_CACHE_TITLE = "filtration_cache" DATASET_FILTRATION_PREPROCESSING_MULTIPROCESSING = False FILTRATION_CACHE_A...
""" Configuration for development - change these with caution! """ region_dims = (512, 512) default_filtration_status = None default_filtration_cache_filepath = 'filtration_cache.h5' defulat_filtration_cache_title = 'filtration_cache' dataset_filtration_preprocessing_multiprocessing = False filtration_cache_apply_f...
# This problem was recently asked by AirBNB: # You are given a singly linked list and an integer k. Return the linked list, removing the k-th last element from the list. # Try to do it in a single pass and using constant space. class Node: def __init__(self, val, next=None): self.val = val self.n...
class Node: def __init__(self, val, next=None): self.val = val self.next = next def __str__(self): current_node = self result = [] while current_node: result.append(current_node.val) current_node = current_node.next return str(result) de...
a=int(input()) if(a%2==0): if(a>=2 and a<5): print ("Not Weird") elif(a<=20): print("Weird") else: print("Not Weird") else: print("Weird")
a = int(input()) if a % 2 == 0: if a >= 2 and a < 5: print('Not Weird') elif a <= 20: print('Weird') else: print('Not Weird') else: print('Weird')
# test builtin object() # creation object() # printing print(repr(object())[:7])
object() print(repr(object())[:7])
class Solution: def findSpecialInteger(self, arr: List[int]) -> int: n = len(arr) // 4 c = 0 prev = -1 for e in arr: if e == prev: c += 1 else: c = 1 prev = e if c > n: return e
class Solution: def find_special_integer(self, arr: List[int]) -> int: n = len(arr) // 4 c = 0 prev = -1 for e in arr: if e == prev: c += 1 else: c = 1 prev = e if c > n: return e
# # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not u...
"""=============== Axon Exceptions =============== AxonException is the base class for all axon exceptions defined here. """ class Axonexception(Exception): """ Base class for axon exceptions. Any arguments listed are placed in self.args """ def __init__(self, *args): self.args = args clas...
''' Data list contains all users info. Each user's info must be a list. First Element: 0 (int) Second Element: name (str) Third Element: username (str) Fourth Element: toph link (str) Fifth Element: dimik link (str) Sixth Element: uri link (str) Note: If any user does not have an account leave ...
""" Data list contains all users info. Each user's info must be a list. First Element: 0 (int) Second Element: name (str) Third Element: username (str) Fourth Element: toph link (str) Fifth Element: dimik link (str) Sixth Element: uri link (str) Note: If any user does not have an account leave ...
students = [] references = [] benefits = [] MODE_SPECIFIC = '1. SPECIFIC' MODE_HOSTEL = '2. HOSTEL' MODE_MCDM = '3. MCDM' MODE_REMAIN = '4. REMAIN'
students = [] references = [] benefits = [] mode_specific = '1. SPECIFIC' mode_hostel = '2. HOSTEL' mode_mcdm = '3. MCDM' mode_remain = '4. REMAIN'
#!/usr/bin/python3 '''Day 6 of the 2017 advent of code''' def redistribute(memory): '''helper to redistribute the memory''' size = len(memory) max_index = 0 max_value = memory[0] #always assumed to be memory #find max and index of max for i in range(size): if memory[i] > max_value: ...
"""Day 6 of the 2017 advent of code""" def redistribute(memory): """helper to redistribute the memory""" size = len(memory) max_index = 0 max_value = memory[0] for i in range(size): if memory[i] > max_value: max_value = memory[i] max_index = i memory[max_index] =...
secret_password = "marty" def apasswordcheker(password_checkers): if password == "marty": print("You figured out the secret password") def password_check(passwd): SpecialSym =['$', '@', '#', '%'] val = True if len(passwd) < 6: print('length should be at least 6') ...
secret_password = 'marty' def apasswordcheker(password_checkers): if password == 'marty': print('You figured out the secret password') def password_check(passwd): special_sym = ['$', '@', '#', '%'] val = True if len(passwd) < 6: print('length should be at least 6') val = False ...
def levenshtein_dis(wordA, wordB): wordA = wordA.lower() # making the wordA lower case wordB = wordB.lower() # making the wordB lower case # get the length of the words and defining the variables length_A = len(wordA) length_B = len(wordB) max_len = 0 diff = 0 distances = [] dist...
def levenshtein_dis(wordA, wordB): word_a = wordA.lower() word_b = wordB.lower() length_a = len(wordA) length_b = len(wordB) max_len = 0 diff = 0 distances = [] distance = 0 if length_A > length_B: diff = length_A - length_B max_len = length_A elif length_A < leng...
# # PySNMP MIB module SHIVA-ETHER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SHIVA-ETHER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:54:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ...
def set_search_path(sender, **kwargs): conn = kwargs.get('connection') if conn is not None: cursor = conn.cursor() cursor.execute("SET search_path=saleor")
def set_search_path(sender, **kwargs): conn = kwargs.get('connection') if conn is not None: cursor = conn.cursor() cursor.execute('SET search_path=saleor')
def debug_report_progress(repo_ctx, msg): if repo_ctx.attr.debug: print(msg) repo_ctx.report_progress(msg) for i in range(25000000): x = 1
def debug_report_progress(repo_ctx, msg): if repo_ctx.attr.debug: print(msg) repo_ctx.report_progress(msg) for i in range(25000000): x = 1
# -*- coding: utf-8 -*- def get_normals(self, indices=[]): """Return the array of the normals coordinates. Parameters ---------- self : MeshVTK a MeshVTK object indices : list list of the points to extract (optional) Returns ------- normals: ndarray Normals co...
def get_normals(self, indices=[]): """Return the array of the normals coordinates. Parameters ---------- self : MeshVTK a MeshVTK object indices : list list of the points to extract (optional) Returns ------- normals: ndarray Normals coordinates """ surf...
""" Time Complexity: O(1) Space Complexity: O(1) """ for number in [2, 3, 5, 7, 11, 13, 19, 23, 29]: print(number)
""" Time Complexity: O(1) Space Complexity: O(1) """ for number in [2, 3, 5, 7, 11, 13, 19, 23, 29]: print(number)
def respond(code=200, payload={}, messages=[]): return { 'status': 'ok' if int(code/100) == 2 else 'error', 'code': code, 'messages': messages, 'payload': payload, }, code
def respond(code=200, payload={}, messages=[]): return ({'status': 'ok' if int(code / 100) == 2 else 'error', 'code': code, 'messages': messages, 'payload': payload}, code)
class Puzzle: def __init__(self, grid): self.grid = grid self.empty_cells = [] def check_full(self): """ Checks if grid is full. :return: True if full, otherwise False """ for row in range(0, 9): for col in range(0, 9): ...
class Puzzle: def __init__(self, grid): self.grid = grid self.empty_cells = [] def check_full(self): """ Checks if grid is full. :return: True if full, otherwise False """ for row in range(0, 9): for col in range(0, 9): if sel...
default_app_config = 'business.staff_accounts.apps.UserManagementConfig' """ This APP is for management of users Functions:- Adding staff Users and giving them initial details -Department -Staff Type -Departmental,General Managers have predefined roles depending on the departments they can...
default_app_config = 'business.staff_accounts.apps.UserManagementConfig' '\nThis APP is for management of users \nFunctions:-\n Adding staff Users and giving them initial details \n -Department\n -Staff Type\n -Departmental,General Managers have predefined roles depending on the departments they...
# finding least positive number # Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, # find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. # code contributed by devanshi katy...
def main_function(arr, size): for i in range(size): if abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0: arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] for i in range(size): if arr[i] > 0: return i + 1 return size + 1 def findpositive(arr, size): j = 0 for i...
def login_required(func): def not_logged_in(self, **kwargs): self.send_login_required({'signin_required': 'you need to sign in'}) return def check_user(self, **kwargs): user = self.connection.user if not user: return not_logged_in(self, **kwargs) return func(...
def login_required(func): def not_logged_in(self, **kwargs): self.send_login_required({'signin_required': 'you need to sign in'}) return def check_user(self, **kwargs): user = self.connection.user if not user: return not_logged_in(self, **kwargs) return func...
# C.O.R.S. cors_origins = [ "http://localhost", "http://localhost:8080", "http://localhost:3000", # Production Client on Vercel "https://twitter-clone.programmertutor.com", "https://www.twitter-clone.programmertutor.com", "https://twitter.dericfagnan.com", "https://www.twitter.dericfagna...
cors_origins = ['http://localhost', 'http://localhost:8080', 'http://localhost:3000', 'https://twitter-clone.programmertutor.com', 'https://www.twitter-clone.programmertutor.com', 'https://twitter.dericfagnan.com', 'https://www.twitter.dericfagnan.com', 'ws://localhost', 'wss://localhost', 'ws://localhost:8080', 'wss:/...
""" Created on Saturday, November 02, 2019 11:00:46 IST @author: Saurabh Ghanekar """ ip = input("Enter ip adddress: ") firstq1 = "" flag = 0 for i in range(len(ip)): if ip[i] == ".": firstqs = ip[:i + 1] break for i in range(len(ip)): if ip[i] == ".": firsths = ip[:i + 1] f...
""" Created on Saturday, November 02, 2019 11:00:46 IST @author: Saurabh Ghanekar """ ip = input('Enter ip adddress: ') firstq1 = '' flag = 0 for i in range(len(ip)): if ip[i] == '.': firstqs = ip[:i + 1] break for i in range(len(ip)): if ip[i] == '.': firsths = ip[:i + 1] flag ...
class Job: def __init__(self, title, link, date, job_id): ''' This class holds job information and attributes ''' self.title = title self.link = link self.date = date self.job_id = job_id self.applied = False self.old = False ...
class Job: def __init__(self, title, link, date, job_id): """ This class holds job information and attributes """ self.title = title self.link = link self.date = date self.job_id = job_id self.applied = False self.old = False self.new ...
{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f9af1484", "metadata": {}, "outputs": [], "source": [ "# ---------------------- STEP 2: Climate APP\n", "\n", "from flask import Flask, json, jsonify\n", "import datetime as dt\n", "\n", "import sqlalchemy\n...
{'cells': [{'cell_type': 'code', 'execution_count': null, 'id': 'f9af1484', 'metadata': {}, 'outputs': [], 'source': ['# ---------------------- STEP 2: Climate APP\n', '\n', 'from flask import Flask, json, jsonify\n', 'import datetime as dt\n', '\n', 'import sqlalchemy\n', 'from sqlalchemy.ext.automap import automap_ba...
# Add your import statements here # Add any utility functions here def rel_docs(query_id,qrels): j=[item['id'] for item in qrels if item['query_num']==str(query_id)] return j def rel_score_as_dict_for_query(query_id,qrels): docs_score_dict={int(item['id']):int(item['position']) for item in qrels if int(it...
def rel_docs(query_id, qrels): j = [item['id'] for item in qrels if item['query_num'] == str(query_id)] return j def rel_score_as_dict_for_query(query_id, qrels): docs_score_dict = {int(item['id']): int(item['position']) for item in qrels if int(item['query_num']) == int(query_id)} return docs_score_di...
class MockData: def __init__(self): self.data = [ 'ATGCAT', 'ATGGGT', 'ATGAAT', ] def get_row(self, i): return self.sequences[i]
class Mockdata: def __init__(self): self.data = ['ATGCAT', 'ATGGGT', 'ATGAAT'] def get_row(self, i): return self.sequences[i]
#!/usr/bin/env python # -*- coding: utf-8 -*- class PodiumUser(object): """ Object that represents a particular User. **Attributes:** **user_id** (int): User id **uri** (string): URI for the User. **username** (string): The User's username. **description** ...
class Podiumuser(object): """ Object that represents a particular User. **Attributes:** **user_id** (int): User id **uri** (string): URI for the User. **username** (string): The User's username. **description** (string): The User's description. **avatar_url** (st...
class Arc(object): """ Python representation of a constraint arc """ def __init__(self, left, right): """ Since the arc is a directed edge, the left and right components of the arc are initalized where the arc travels from left to right. """ self.left = left ...
class Arc(object): """ Python representation of a constraint arc """ def __init__(self, left, right): """ Since the arc is a directed edge, the left and right components of the arc are initalized where the arc travels from left to right. """ self.left = left ...
# # PySNMP MIB module ONEACCESS-DOT11-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-DOT11-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:25:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) ...
class Decipher: def __init__(self, data='', password=''): self.data = data self.password = password self.result = False def decipher_password(self): # For authentication(Deciphering your password).. helper = self.data.split('*/*/') count, separator, compare, help...
class Decipher: def __init__(self, data='', password=''): self.data = data self.password = password self.result = False def decipher_password(self): helper = self.data.split('*/*/') (count, separator, compare, helper_list) = (1, '', '', []) for i in helper[0]: ...
class Error(Exception): pass class ResourceNotFoundError(Error): pass class ResourceAlreadyExistsError(Error): pass class DatabaseCommitFailedError(Error): pass
class Error(Exception): pass class Resourcenotfounderror(Error): pass class Resourcealreadyexistserror(Error): pass class Databasecommitfailederror(Error): pass
N = int(input()) t = N % 360 if t == 90 or t == 270: print('Yes') else: print('No')
n = int(input()) t = N % 360 if t == 90 or t == 270: print('Yes') else: print('No')
#!/usr/bin/python3 # Demo of a dictionary comprehension d={i:chr(i) for i in range(ord('a'),ord('z')+1)} for k,v in d.items(): print(k,':',v)
d = {i: chr(i) for i in range(ord('a'), ord('z') + 1)} for (k, v) in d.items(): print(k, ':', v)
""" Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} """ n=int(input("Input a number ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d)
""" Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} """ n = int(input('Input a number ')) d = dict() for x in range(1, n + 1): d[x] = x * x print(d)
#!/usr/bin/python3 class GuiService(): def readSettingsFile(self,wert): settingsFile = open("Settings","r") file = settingsFile.read() fileList = file.split("\n") for element in fileList: if wert in element: x = element.split(":") return x...
class Guiservice: def read_settings_file(self, wert): settings_file = open('Settings', 'r') file = settingsFile.read() file_list = file.split('\n') for element in fileList: if wert in element: x = element.split(':') return x[1] def ge...
carbohydrate_min_length = 3 carbohydrate_chain_length_including_start_C = 3 def is_glycan(a_category): for _ in a_category["types"]: if "Glycan" in _: return True return False def add_carbohydrate_output(output, type_, mass, num_c_atoms, num_o_atoms, atom_list, full_atom_dic): output...
carbohydrate_min_length = 3 carbohydrate_chain_length_including_start_c = 3 def is_glycan(a_category): for _ in a_category['types']: if 'Glycan' in _: return True return False def add_carbohydrate_output(output, type_, mass, num_c_atoms, num_o_atoms, atom_list, full_atom_dic): output.a...
class MicroRaidenException(Exception): """Base exception for uRaiden""" pass class InvalidBalanceAmount(MicroRaidenException): """Raised if the payment contains lesser balance than the previous one.""" pass class InvalidBalanceProof(MicroRaidenException): """Balance proof data do not make sense....
class Microraidenexception(Exception): """Base exception for uRaiden""" pass class Invalidbalanceamount(MicroRaidenException): """Raised if the payment contains lesser balance than the previous one.""" pass class Invalidbalanceproof(MicroRaidenException): """Balance proof data do not make sense.""...
class Error(Exception): """Base class for other exceptions""" pass class TopicOrServiceNameDoesNotExistError(Error): """The topic or service name passed does not exist in the source destination dictionary.""" pass
class Error(Exception): """Base class for other exceptions""" pass class Topicorservicenamedoesnotexisterror(Error): """The topic or service name passed does not exist in the source destination dictionary.""" pass
n = int(input("Enter a number you want to check:")) def digisum(n): return sum([int(s) for s in str(n)]) def getfactors(n): k=2 result=[] while k ** 2 <= n: while n%k==0: result.append(k) n = n // k k = k +1 if n > 1: result.append(n) return resu...
n = int(input('Enter a number you want to check:')) def digisum(n): return sum([int(s) for s in str(n)]) def getfactors(n): k = 2 result = [] while k ** 2 <= n: while n % k == 0: result.append(k) n = n // k k = k + 1 if n > 1: result.append(n) re...
def obok(n, kost): szesc = [[[k * n**2 + j * n + i + 1 for i in range(n)] for j in range(n)] for k in range(n)] p = 0 r = 0 m = 0 for a in range(n): for b in range(n): for c in range(n): if szesc[a][b][c] == kost: p=a ...
def obok(n, kost): szesc = [[[k * n ** 2 + j * n + i + 1 for i in range(n)] for j in range(n)] for k in range(n)] p = 0 r = 0 m = 0 for a in range(n): for b in range(n): for c in range(n): if szesc[a][b][c] == kost: p = a r ...
def getAbsMax(list, roundTo=None): """ `list` - the list/array to find the absolute maximum `roundTo` - the number of digits to round the result to. returns the absolute maximum of a list. """ x = max(max(list), abs(min(list))) if roundTo: x = round(x, roundTo) return x
def get_abs_max(list, roundTo=None): """ `list` - the list/array to find the absolute maximum `roundTo` - the number of digits to round the result to. returns the absolute maximum of a list. """ x = max(max(list), abs(min(list))) if roundTo: x = round(x, roundTo) return x
######## ## ## Class to represent a bot in an IPD tournament ## ######## class BotPlayer(object): """ This class should be inherited from by bots who define their own getNextMove method. That is how bots have their own strategy. self.name is the name of the strategy employed self.description is an...
class Botplayer(object): """ This class should be inherited from by bots who define their own getNextMove method. That is how bots have their own strategy. self.name is the name of the strategy employed self.description is an explanation of the strategy self.tournament_id can be assigned upon be...
class OrderNotFound(Exception): def __init__(self, message='Order tidak ditemukan!'): self.message = message super().__init__(self.message) pass
class Ordernotfound(Exception): def __init__(self, message='Order tidak ditemukan!'): self.message = message super().__init__(self.message) pass
class Solution: def addDigits(self, num: int) -> int: while num > 9: num = sum(int(ch) for ch in str(num)) return num
class Solution: def add_digits(self, num: int) -> int: while num > 9: num = sum((int(ch) for ch in str(num))) return num
value = '' for i in range(1, 10001): value = value + str(i) + ' ' value = value.replace('0', ' ') values = value.split(' ') total = 0; for num in values: if num.lstrip().rstrip().strip() == '': continue total += int(num) print ('Total: ' + str(total))
value = '' for i in range(1, 10001): value = value + str(i) + ' ' value = value.replace('0', ' ') values = value.split(' ') total = 0 for num in values: if num.lstrip().rstrip().strip() == '': continue total += int(num) print('Total: ' + str(total))
class Stack: def __init__(self): self.data = [] def pop(self): if self.is_empty(): return None val = self.data[len(self.data)-1] self.data = self.data[:len(self.data)-1] return val def peek(self): if self.is_empty(): return None ...
class Stack: def __init__(self): self.data = [] def pop(self): if self.is_empty(): return None val = self.data[len(self.data) - 1] self.data = self.data[:len(self.data) - 1] return val def peek(self): if self.is_empty(): return None ...
"""The result library.""" class Result: """ Construct Result objects. Result is the basic answer for services that encapsulates the outcome of the service in a clear and consistent pattern across services. It was added after creating some services, so there are a few of them that do not make use ...
"""The result library.""" class Result: """ Construct Result objects. Result is the basic answer for services that encapsulates the outcome of the service in a clear and consistent pattern across services. It was added after creating some services, so there are a few of them that do not make use o...
class Solution: def shortestWordDistance(self, words, word1, word2): i1 = i2 = -1 res, same = float("inf"), word1 == word2 for i, w in enumerate(words): if w == word1: if same: i2 = i1 i1 = i if i2 >= 0: res = min(res, i1 - i2) ...
class Solution: def shortest_word_distance(self, words, word1, word2): i1 = i2 = -1 (res, same) = (float('inf'), word1 == word2) for (i, w) in enumerate(words): if w == word1: if same: i2 = i1 i1 = i if i2 >= 0:...
class LogSystem: def __init__(self): """Design. """ self.d = {} self.g = {'Year': 4, 'Month': 7, 'Day': 10, 'Hour': 13, 'Minute': 16, 'Second': 19} def put(self, id: int, timestamp: str) -> None: self.d[timestamp] = id def retrieve(self, start: str, end: s...
class Logsystem: def __init__(self): """Design. """ self.d = {} self.g = {'Year': 4, 'Month': 7, 'Day': 10, 'Hour': 13, 'Minute': 16, 'Second': 19} def put(self, id: int, timestamp: str) -> None: self.d[timestamp] = id def retrieve(self, start: str, end: str, granu...
if __name__ == '__main__': n = int(input()) arr = map(int, input().split(' ')) arr = sorted(list(arr)) arr.reverse() biggest = arr[0] for i in arr: if i != biggest: print(i) break
if __name__ == '__main__': n = int(input()) arr = map(int, input().split(' ')) arr = sorted(list(arr)) arr.reverse() biggest = arr[0] for i in arr: if i != biggest: print(i) break
class Test(): pass test = Test() print(test.__new__)
class Test: pass test = test() print(test.__new__)
i = input('carteira em reais: ') d = float(i)/3.27 print('carteira em dollar: ',d)
i = input('carteira em reais: ') d = float(i) / 3.27 print('carteira em dollar: ', d)
# GUI Application automation and testing library # Copyright (C) 2006 Mark Mc Mahon # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at you...
"""ComboBox dropped height Test **What is checked** It is ensured that the height of the list displayed when the combobox is dropped down is not less than the height of the reference. **How is it checked** The value for the dropped rectangle can be retrieved from windows. The height of this rectangle is calculated an...