content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
##Generalize orienteering contours=name ##maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm=number4 ##contours=vector ##min=string37 ##generalizecontours=output vector outputs_QGISFIELDCALCULATOR_1=processing.runalg('qgis:fieldcalculator', contours,'length',0,10.0,2.0,True,'round($length,2)'...
outputs_qgisfieldcalculator_1 = processing.runalg('qgis:fieldcalculator', contours, 'length', 0, 10.0, 2.0, True, 'round($length,2)', None) outputs_qgisextractbyattribute_1 = processing.runalg('qgis:extractbyattribute', outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'], 'length', 3, min, None) outputs_GRASS7V.GENERALIZE.SI...
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) # norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet18_v1c', backbone=dict( type='BiseNetV1', base_model='ResNetV1c', depth=18, out_indices=(0,...
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained='open-mmlab://resnet18_v1c', backbone=dict(type='BiseNetV1', base_model='ResNetV1c', depth=18, out_indices=(0, 1, 2), with_sp=False, norm_cfg=norm_cfg, align_corners=False), decode_head=dict(type='FCNHead', in_index=-1, in...
#For packaging ''' Users api handles JWT auth for users '''
""" Users api handles JWT auth for users """
def run(params={}): return { 'project_name': 'Core', 'bitcode': True, 'min_version': '9.0', 'enable_arc': True, 'enable_visibility': True, 'conan_profile': 'ezored_ios_framework_profile', 'archs': [ {'arch': 'armv7', 'conan_arch': 'armv7', 'platfor...
def run(params={}): return {'project_name': 'Core', 'bitcode': True, 'min_version': '9.0', 'enable_arc': True, 'enable_visibility': True, 'conan_profile': 'ezored_ios_framework_profile', 'archs': [{'arch': 'armv7', 'conan_arch': 'armv7', 'platform': 'OS'}, {'arch': 'armv7s', 'conan_arch': 'armv7s', 'platform': 'OS'...
#!/usr/bin/python # encoding: utf-8 """ custom_stopwords Purpose: Collect custom stopwords lists Author: datadonk23 (datadonk23@gmail.com) Date: 2018-05-01 """ arxiv_stopwords = ["arxiv", "astro-ph", "astro-ph.co", "astro-ph.ep", "astro-ph.ga", "astro-ph.he", "astro-ph.im", "astro-ph.sr", ...
""" custom_stopwords Purpose: Collect custom stopwords lists Author: datadonk23 (datadonk23@gmail.com) Date: 2018-05-01 """ arxiv_stopwords = ['arxiv', 'astro-ph', 'astro-ph.co', 'astro-ph.ep', 'astro-ph.ga', 'astro-ph.he', 'astro-ph.im', 'astro-ph.sr', 'cond-mat.dis-nn', 'cond-mat.mes-hall', 'cond-mat.mtrl-sci', 'con...
# Copyright 2020 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apac...
"""Log area provider data module.""" class Logarea: """Log area data object.""" _log_area_dictionary = None def __init__(self, **log_area): """Take a dictionary as input and setattr on instance. :param log_area: Dictionary to set attributes from. :type log_area: dict """ ...
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Examp...
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Examp...
class Tile(): """ The smallest building block in a map """ def __init__(self): self.tile = '.' def get(self): return self.tile def set(self, item): self.tile = item
class Tile: """ The smallest building block in a map """ def __init__(self): self.tile = '.' def get(self): return self.tile def set(self, item): self.tile = item
def longestDigitsPrefix(inputString): # iterate through the string arr = '' for i in inputString: if i.isdigit(): arr += i else: break return arr
def longest_digits_prefix(inputString): arr = '' for i in inputString: if i.isdigit(): arr += i else: break return arr
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
"""Provides the stamp info file containing the Bazel non-volatile keys """ def _impl(ctx): output = ctx.outputs.out ctx.actions.run_shell(outputs=[output], inputs=[ctx.info_file], command='cp {src} {dst}'.format(src=ctx.info_file.path, dst=output.path)) stamp_info = rule(implementation=_impl, outputs={'out': '...
"""Debug functions for notebooks. """ def count(df, name=None): """Print the count of dataframe with title.""" if name: print("Dataset: %s" % (name)) print("Count: %d" % (df.count())) def show(df, name=None, num_rows=1): """Print title and show a dataframe""" if name: print("Data...
"""Debug functions for notebooks. """ def count(df, name=None): """Print the count of dataframe with title.""" if name: print('Dataset: %s' % name) print('Count: %d' % df.count()) def show(df, name=None, num_rows=1): """Print title and show a dataframe""" if name: print('Dataset: %...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # --------------------------------------------------------- class LCS: """ Compute the Longest Common Subsequence (LCS) of two given string.""" def __init__...
class Lcs: """ Compute the Longest Common Subsequence (LCS) of two given string.""" def __init__(self, str_m, str_n): self.str_m_len = len(str_m) self.str_n_len = len(str_n) dp_table = self._construct_dp_table(str_m, str_n) self._lcs_len = dp_table[self.str_m_len][self.str_n_len...
class Error: none_or_invalid_attribute = "main attributes should have value." unacceptable_json = "json input has unacceptable format." unacceptable_object_type = "object has unacceptable type"
class Error: none_or_invalid_attribute = 'main attributes should have value.' unacceptable_json = 'json input has unacceptable format.' unacceptable_object_type = 'object has unacceptable type'
def decimalni_zapis(deljenec, delitelj): memo = set() decimalni_zapis = '' while (deljenec, delitelj) not in memo: if deljenec % delitelj == 0: decimalni_zapis += str(deljenec // delitelj) return decimalni_zapis, deljenec, delitelj elif deljenec < delitelj: ...
def decimalni_zapis(deljenec, delitelj): memo = set() decimalni_zapis = '' while (deljenec, delitelj) not in memo: if deljenec % delitelj == 0: decimalni_zapis += str(deljenec // delitelj) return (decimalni_zapis, deljenec, delitelj) elif deljenec < delitelj: ...
class Solution: """ @param grids: a maxtrix with alphabet @return: return sorted lists """ def CounterDiagonalSort(self, grids): # write your code here m = len(grids) n = len(grids[0]) table = [] for i in range(m): temp = [] row = i ...
class Solution: """ @param grids: a maxtrix with alphabet @return: return sorted lists """ def counter_diagonal_sort(self, grids): m = len(grids) n = len(grids[0]) table = [] for i in range(m): temp = [] row = i col = 0 ...
#!/usr/bin/python3 bridgera = ['Arijit','Soumya','Gunjan','Arptia','Bishwa','Rintu','Satya','Lelin'] # Generator Function iterarates through all items of array def gen_func(data): for i in range(len(data)): yield data[i] data_gen = list(gen_func(bridgera)) print (data_gen) # Normal Functio...
bridgera = ['Arijit', 'Soumya', 'Gunjan', 'Arptia', 'Bishwa', 'Rintu', 'Satya', 'Lelin'] def gen_func(data): for i in range(len(data)): yield data[i] data_gen = list(gen_func(bridgera)) print(data_gen) def norm_func(data): for i in range(len(data)): return data[i] norm_gen = list(norm_func(bri...
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove, search, pop """ def __init__(self, value=None): s...
class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove, search, pop """ def __init__(self, value=None): ...
def data_for_fitting(*, building_id, date): """ Retrieves data for fitting from the previous business day taking into account holidays """ lease_start = None while lease_start is None: # Previous business day according to Pandas (might be a holiday) previous_bday = pd.to_datetim...
def data_for_fitting(*, building_id, date): """ Retrieves data for fitting from the previous business day taking into account holidays """ lease_start = None while lease_start is None: previous_bday = pd.to_datetime(date) - b_day(1) lease_start = db().execute(building_daily_stats...
"""Top-level package for leimpy.""" __author__ = """Marco Berzborn""" __email__ = 'marco.berzborn@akustik.rwth-aachen.de' __version__ = '0.0.0'
"""Top-level package for leimpy.""" __author__ = 'Marco Berzborn' __email__ = 'marco.berzborn@akustik.rwth-aachen.de' __version__ = '0.0.0'
class Node: """ A node in a graph """ def __init__(self, identifier): """ :param identifier: Identifier is hash of given Shape Object """ self.identifier = identifier self.outgoing_pointers = [] self.incoming_pointers = [] def get_identifier(self): ...
class Node: """ A node in a graph """ def __init__(self, identifier): """ :param identifier: Identifier is hash of given Shape Object """ self.identifier = identifier self.outgoing_pointers = [] self.incoming_pointers = [] def get_identifier(self): ...
#implicit type conversion num1 = 12 num2= 13.5 num3 = num1 + num2 print(type(num1)) print(type(num2)) print(num3) print(type(num3))
num1 = 12 num2 = 13.5 num3 = num1 + num2 print(type(num1)) print(type(num2)) print(num3) print(type(num3))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool ...
class Solution(object): def find_target(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ t = [] def preorder(r): if r: t.append(r.val) preorder(r.left) preorder(r.right) ...
load("@rules_cuda//cuda:defs.bzl", "cuda_library") NVCC_COPTS = ["--expt-relaxed-constexpr", "--expt-extended-lambda"] def cu_library(name, srcs, copts = [], **kwargs): cuda_library(name, srcs = srcs, copts = NVCC_COPTS + copts, **kwargs)
load('@rules_cuda//cuda:defs.bzl', 'cuda_library') nvcc_copts = ['--expt-relaxed-constexpr', '--expt-extended-lambda'] def cu_library(name, srcs, copts=[], **kwargs): cuda_library(name, srcs=srcs, copts=NVCC_COPTS + copts, **kwargs)
''' Author: jianzhnie Date: 2022-03-04 17:13:55 LastEditTime: 2022-03-04 17:13:55 LastEditors: jianzhnie Description: '''
""" Author: jianzhnie Date: 2022-03-04 17:13:55 LastEditTime: 2022-03-04 17:13:55 LastEditors: jianzhnie Description: """
#!/usr/bin/env python3 #: Program Purpose: #: Read an integer N. For all non-negative integers i < N #: print i * i. #: #: Program Author: Happi Yvan <ivensteinpoker@gmail.com #: Program Date : 11/04/2019 (mm/dd/yyyy) def process(int_val): for x in range(int_val): print(x * x) def main...
def process(int_val): for x in range(int_val): print(x * x) def main(): val = int(input()) process(val) if __name__ == '__main__': main()
def names(name_list): with open('textfile3.txt', 'w') as myfile: myfile.writelines(name_list) myfile.close() print(name_list) menu() def display_name(n): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() print(name_list[n-1]) retu...
def names(name_list): with open('textfile3.txt', 'w') as myfile: myfile.writelines(name_list) myfile.close() print(name_list) menu() def display_name(n): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() print(name_list[n - 1]) return namelist...
test = { 'name': 'Problem 7', 'points': 1, 'suites': [ { 'cases': [ { 'answer': '103495fc3358e1b6354d1d4a277039e6', 'choices': [ r""" Pair('quote', Pair(A, nil)), where: A is the quoted expression """, r""" ...
test = {'name': 'Problem 7', 'points': 1, 'suites': [{'cases': [{'answer': '103495fc3358e1b6354d1d4a277039e6', 'choices': ["\n Pair('quote', Pair(A, nil)), where:\n A is the quoted expression\n ", '\n [A], where:\n A is the quoted expression\n ',...
n = int(input()) even_numbers_set = set() odd_numbers_set = set() for current_iteration_count in range(1, n+1): name = input() current_sum = sum([ord(el) for el in name]) // current_iteration_count if current_sum % 2 == 0: even_numbers_set.add(current_sum) else: odd_numbers_set.add(cu...
n = int(input()) even_numbers_set = set() odd_numbers_set = set() for current_iteration_count in range(1, n + 1): name = input() current_sum = sum([ord(el) for el in name]) // current_iteration_count if current_sum % 2 == 0: even_numbers_set.add(current_sum) else: odd_numbers_set.add(cur...
# -*- coding: utf-8 -*- r"""Testing code for the (Python) bandit library. Testing is done via the Testify package: https://github.com/Yelp/Testify This package includes: * Test cases/test setup files * Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon` * Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb` * Tes...
"""Testing code for the (Python) bandit library. Testing is done via the Testify package: https://github.com/Yelp/Testify This package includes: * Test cases/test setup files * Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon` * Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb` * Tests for bandit/bla: :mod:`...
num = int(input("Numero: ")) for i in range(1,13): m = num * i print(num,"X",i,"=",m)
num = int(input('Numero: ')) for i in range(1, 13): m = num * i print(num, 'X', i, '=', m)
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return # use first row as "cols" array, use first column as "rows" array # to do that, first store what ne...
class Solution: def set_zeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return first_row_zeros = False first_col_zeros = False m = len(matrix) n = len(matrix[0])...
class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ hash_map = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick hash_map[str(sum)]...
class Solution(object): def least_bricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ hash_map = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick hash_map[str(sum)] = hash_map.setd...
# function type class function(object): def __get__(self, obj, objtype): # when used as attribute a function returns a bound method or the function itself object = ___id("%object") method = ___id("%method") NoneType = ___id("%NoneType") if obj is None and objtype is not NoneType: # no obj...
class Function(object): def __get__(self, obj, objtype): object = ___id('%object') method = ___id('%method') none_type = ___id('%NoneType') if obj is None and objtype is not NoneType: return self else: new_method = object.__new__(method) m...
class GenerationTemplate: def __init__( self, source_path: str, template: str, group_template: str, unit_template: str ): self.source_path: str = source_path self.template: str = template self.group_template: str = group_temp...
class Generationtemplate: def __init__(self, source_path: str, template: str, group_template: str, unit_template: str): self.source_path: str = source_path self.template: str = template self.group_template: str = group_template self.unit_template: str = unit_template
#!/usr/bin/env python3 # # eask: # The initialization program (your puzzle input) can either update the bitmask # or write a value to memory. Values and memory addresses are both 36-bit # unsigned integers. For example, ignoring bitmasks for a moment, a line # like mem[8] = 11 would write the value 11 to memory address...
input_file = 'input.txt' def main(): instructions = [line.strip('\n') for line in open(INPUT_FILE, 'r')] mask = None memory = {} for instruction in instructions: if instruction.startswith('mask = '): mask = instruction.split(' = ')[1] elif instruction.startswith('mem['): ...
class Email: client = None optional_arguments = [ "antispamlevel", "antivirus", "autorespond", "autorespondsaveemail", "autorespondmessage", "password", "quota" ] def __init__(self, client): self.client = client def overview(self): return self.client.get("/email/overview") def globalquota(se...
class Email: client = None optional_arguments = ['antispamlevel', 'antivirus', 'autorespond', 'autorespondsaveemail', 'autorespondmessage', 'password', 'quota'] def __init__(self, client): self.client = client def overview(self): return self.client.get('/email/overview') def globa...
class MyArray: def __init__(self, *args): self.elems = list(args) def __repr__(self): return str(self.elems) def __getitem__(self, index): return self.elems[index] def __setitem__(self, index, value): self.elems[index] = value def __delitem__(self, index): ...
class Myarray: def __init__(self, *args): self.elems = list(args) def __repr__(self): return str(self.elems) def __getitem__(self, index): return self.elems[index] def __setitem__(self, index, value): self.elems[index] = value def __delitem__(self, index): ...
n = input() def odd_even(a): odd = 0 even = 0 for i in range(len(a)): if int(a[i]) % 2 == 0: even += int(a[i]) else: odd += int(a[i]) return (f'Odd sum = {odd}, Even sum = {even}') print(odd_even(n))
n = input() def odd_even(a): odd = 0 even = 0 for i in range(len(a)): if int(a[i]) % 2 == 0: even += int(a[i]) else: odd += int(a[i]) return f'Odd sum = {odd}, Even sum = {even}' print(odd_even(n))
""" Entradas numero_hombres-->int-->p_h numero_mujeres-->int-->p_m salidas Porcentaje de hombres-->float-->p_h Porcentaje de mujeres-->float-->p_m """ numero_hombres=int(input("digite total de hombres: ")) numero_mujeres=int(input("digite total de mujeres: ")) #caja negra p_h=numero_hombres*100/(numero_hombres+numero_...
""" Entradas numero_hombres-->int-->p_h numero_mujeres-->int-->p_m salidas Porcentaje de hombres-->float-->p_h Porcentaje de mujeres-->float-->p_m """ numero_hombres = int(input('digite total de hombres: ')) numero_mujeres = int(input('digite total de mujeres: ')) p_h = numero_hombres * 100 / (numero_hombres + numero_m...
load("//internal/jsweet_transpile:jsweet_transpile.bzl", "jsweet_transpile","TRANSPILE_ATTRS") load("@npm_bazel_typescript//:index.bzl", "ts_library") JWSEET_TRANSPILE_KEYS = TRANSPILE_ATTRS.keys() def jsweet_ts_lib(name, **kwargs): transpile_args = dict() for transpile_key in JWSEET_TRANSPILE_KEYS: i...
load('//internal/jsweet_transpile:jsweet_transpile.bzl', 'jsweet_transpile', 'TRANSPILE_ATTRS') load('@npm_bazel_typescript//:index.bzl', 'ts_library') jwseet_transpile_keys = TRANSPILE_ATTRS.keys() def jsweet_ts_lib(name, **kwargs): transpile_args = dict() for transpile_key in JWSEET_TRANSPILE_KEYS: i...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() output = dummy # l1_eol...
class Solution: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = list_node() output = dummy while 1: if l1 is None: output.next = l2 break if l2 is None: output.next = l1 break ...
text = """first row second row third row""" print(text)
text = 'first row\nsecond row\nthird row' print(text)
# WSADMIN SCRIPT TO SHOW USEFUL ADMINTASK COMMANDS AND HELP TOWARDS THEM # Santiago Garcia Arango # Command: # wsadmin.sh -lang jython -f /tmp/test.py print("***** Showing AdminTask help *****") print(AdminTask.help()) print("***** Showing AdminTask commands *****") print(AdminTask.help("-commands")) print("***** Sh...
print('***** Showing AdminTask help *****') print(AdminTask.help()) print('***** Showing AdminTask commands *****') print(AdminTask.help('-commands')) print('***** Showing AdminTask commands with <*something*> pattern *****') print(AdminTask.help('-commands', '*server*')) print(AdminTask.help('-commands', '*jvm*')) pri...
def dummy_function(a): return a DUMMY_GLOBAL_CONSTANT_0 = 'FOO'; DUMMY_GLOBAL_CONSTANT_1 = 'BAR';
def dummy_function(a): return a dummy_global_constant_0 = 'FOO' dummy_global_constant_1 = 'BAR'
# Matrix solver (TDMA) # parameters required: # n: number of unknowns (length of x) # a: coefficient matrix # b: RHS/constant array # return output: # b: solution array def solve_TDMA(n, a, b): # forward substitution a[0][2] = -a[0][2] / a[0][1] b[0] = b[0] / a[0][1] for i in range(1, n): a[...
def solve_tdma(n, a, b): a[0][2] = -a[0][2] / a[0][1] b[0] = b[0] / a[0][1] for i in range(1, n): a[i][2] = -a[i][2] / (a[i][1] + a[i][0] * a[i - 1][2]) b[i] = (b[i] - a[i][0] * b[i - 1]) / (a[i][1] + a[i][0] * a[i - 1][2]) for i in range(n - 2, -1, -1): b[i] = a[i][2] * b[i + 1]...
allowed_request_categories = [ 'stock', 'mutual_fund', 'intraday', 'history', 'history_multi_single_day', 'forex', 'forex_history', 'forex_single_day', 'stock_search' ]
allowed_request_categories = ['stock', 'mutual_fund', 'intraday', 'history', 'history_multi_single_day', 'forex', 'forex_history', 'forex_single_day', 'stock_search']
#Encontrar el menor valor en un array #con busqueda binaria def menor (array): l=0 r=len(array)-1 while l<=r: mid = l+(r-l)//2 if array[mid] > array[r]: l=mid+1 if array[mid]< array[r]: r=mid if r==l or mid==0: return array[r] n...
def menor(array): l = 0 r = len(array) - 1 while l <= r: mid = l + (r - l) // 2 if array[mid] > array[r]: l = mid + 1 if array[mid] < array[r]: r = mid if r == l or mid == 0: return array[r] nums = [15, 18, 25, 35, 1, 3, 12] print(menor(num...
def fun(s): ans = 0 o = 0 c = 0 for i in s: if(i=="("): o+=1 elif(i==")"): c+=1 if(c>o): c-=1 o+=1 ans+=1 return ans t = int(input()) for _ in range(t): n = int(input()) s = input() ans = 0 N = 10**9+7 value = ((n+1)*n)//2 value = pow(value,N-2,N) prin...
def fun(s): ans = 0 o = 0 c = 0 for i in s: if i == '(': o += 1 elif i == ')': c += 1 if c > o: c -= 1 o += 1 ans += 1 return ans t = int(input()) for _ in range(t): n = int(input()) s = input() ans = 0 ...
for _ in range(int(input())): s = set() n = input().split() while True: m = input().split() if m[-1] == "say?": break s.add(m[-1]) for i in n: if i not in s: print(i, end=' ') print()
for _ in range(int(input())): s = set() n = input().split() while True: m = input().split() if m[-1] == 'say?': break s.add(m[-1]) for i in n: if i not in s: print(i, end=' ') print()
# Copyright (c) 2018 Stephen Bunn <stephen@bunn.io> # MIT License <https://opensource.org/licenses/MIT> __name__ = "standardfile" __repo__ = "https://github.com/stephen-bunn/standardfile" __description__ = "A library for accessing and interacting with a Standard File server." __version__ = "0.0.0" __author__ = "Stephe...
__name__ = 'standardfile' __repo__ = 'https://github.com/stephen-bunn/standardfile' __description__ = 'A library for accessing and interacting with a Standard File server.' __version__ = '0.0.0' __author__ = 'Stephen Bunn' __contact__ = 'stephen@bunn.io' __license__ = 'MIT License'
""" LIST: CHUNKING """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' # Example of Chunking (Grouping an item with its next) def chunks(list, number): # Requires a list and a number for index in range(0, len(list), number): # For every # index inside of a n...
""" LIST: CHUNKING """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' def chunks(list, number): for index in range(0, len(list), number): yield list[index:index + number] item_list = [0, 1, 2, 3, 4, 5] count = 2 chunks_list = chunks(itemList, count) out = chun...
class Dataset(object): def __init__(self, env_spec): self._env_spec = env_spec def get_batch(self, batch_size, horizon): raise NotImplementedError def get_batch_iterator(self, batch_size, horizon, randomize_order=False, is_tf=True): raise NotImplementedError
class Dataset(object): def __init__(self, env_spec): self._env_spec = env_spec def get_batch(self, batch_size, horizon): raise NotImplementedError def get_batch_iterator(self, batch_size, horizon, randomize_order=False, is_tf=True): raise NotImplementedError
# -------------- ##File path for the file file_path def read_file(path): f=open(path,'r') sentence=f.readline() f.close() return sentence sample_message=read_file(file_path) #Code starts here # -------------- #Code starts here file_path_1 file_path_2 message_1=read_file(file_pa...
file_path def read_file(path): f = open(path, 'r') sentence = f.readline() f.close() return sentence sample_message = read_file(file_path) file_path_1 file_path_2 message_1 = read_file(file_path_1) message_2 = read_file(file_path_2) (message_1, message_2) def fuse_msg(message_a, message_b): ima = ...
class Agent(object): def __init__(self, id): self.id = id def act(self, state): raise NotImplementedError() def transition(self, state, actions, new_state, reward): pass
class Agent(object): def __init__(self, id): self.id = id def act(self, state): raise not_implemented_error() def transition(self, state, actions, new_state, reward): pass
n = int(input()) arr = [list(map(int,input().split())) for i in range(n)] ans = [0]*n ans[0] = int(pow((arr[0][1]*arr[0][2])//arr[1][2], 0.5)) for i in range(1,n): ans[i]=(arr[0][i]//ans[0]) print(*ans)
n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] ans = [0] * n ans[0] = int(pow(arr[0][1] * arr[0][2] // arr[1][2], 0.5)) for i in range(1, n): ans[i] = arr[0][i] // ans[0] print(*ans)
class Relaxation: def __init__(self): self.predecessors = {} def buildPath(self, graph, node_from, node_to): nodes = [] current = node_to while current != node_from: if self.predecessors[current] == current and current != node_from: return None ...
class Relaxation: def __init__(self): self.predecessors = {} def build_path(self, graph, node_from, node_to): nodes = [] current = node_to while current != node_from: if self.predecessors[current] == current and current != node_from: return None ...
''' It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transa...
""" It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transa...
"""Top-level package for Python Boilerplate.""" __author__ = """Mathanraj Sharma""" __email__ = "rvmmathanraj@gmail.com" __version__ = "0.1.0"
"""Top-level package for Python Boilerplate.""" __author__ = 'Mathanraj Sharma' __email__ = 'rvmmathanraj@gmail.com' __version__ = '0.1.0'
""" namecom: result_models.py Defines response result models for the api. Tianhong Chu [https://github.com/CtheSky] License: MIT """ class RequestResult(object): """Base class for Response class. Attributes ---------- resp : http response from requests.Response status_code : int ...
""" namecom: result_models.py Defines response result models for the api. Tianhong Chu [https://github.com/CtheSky] License: MIT """ class Requestresult(object): """Base class for Response class. Attributes ---------- resp : http response from requests.Response status_code : int ...
""" Exceptions used by the impact estimation program """ class RecipeCreationError(Exception): pass class SolverTimeoutError(Exception): pass class NoKnownIngredientsError(Exception): pass class NoCharacterizedIngredientsError(Exception): pass
""" Exceptions used by the impact estimation program """ class Recipecreationerror(Exception): pass class Solvertimeouterror(Exception): pass class Noknowningredientserror(Exception): pass class Nocharacterizedingredientserror(Exception): pass
# Copyright 2015 Google Inc. All rights reserved. # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd { 'includes': [ ], 'targets': [ { 'target_name': 'mkvmuxer', 'type': 'static_libr...
{'includes': [], 'targets': [{'target_name': 'mkvmuxer', 'type': 'static_library', 'sources': ['src/mkvmuxer.cpp', 'src/mkvmuxer.hpp', 'src/mkvmuxerutil.cpp', 'src/mkvmuxerutil.hpp', 'src/mkvwriter.cpp', 'src/mkvwriter.hpp']}]}
# -*- coding: utf-8 -*- """ First paragraph of docs. .. wikisection:: faq :title: Why? Well... Second paragraph of docs. """
""" First paragraph of docs. .. wikisection:: faq :title: Why? Well... Second paragraph of docs. """
class Address(object): def __init__(self,addr): self.addr=addr @classmethod def fromhex(cls,addr): return cls(bytes.fromhex(addr)) def equal(self,other): if not isinstance(other, Address): raise Exception('peer is not an address') if not len(self.addr) == le...
class Address(object): def __init__(self, addr): self.addr = addr @classmethod def fromhex(cls, addr): return cls(bytes.fromhex(addr)) def equal(self, other): if not isinstance(other, Address): raise exception('peer is not an address') if not len(self.addr)...
# job_list_one_shot.py --- # # Filename: job_list_one_shot.py # Author: Abhishek Udupa # Created: Tue Jan 26 15:13:19 2016 (-0500) # # # Copyright (c) 2015, Abhishek Udupa, University of Pennsylvania # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permit...
[(['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_103_10.sl'], 'icfp_103_10-one-shot', 'icfp_103_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_113_1000.sl'], 'icfp_113_1000-one-shot', 'icfp_113_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchm...
class OnlyStaffMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: messages.error(request, "Only Staff members can do this.") try: return HttpResponseRedirect(request.META['HTTP_REFERER']) except KeyEr...
class Onlystaffmixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: messages.error(request, 'Only Staff members can do this.') try: return http_response_redirect(request.META['HTTP_REFERER']) except KeyError: ...
def plant_recommendation(care): if care == 'low': print('aloe') elif care == 'medium': print('pothos') elif care == 'high': print('orchid') plant_recommendation('low') plant_recommendation('medium') plant_recommendation('high')
def plant_recommendation(care): if care == 'low': print('aloe') elif care == 'medium': print('pothos') elif care == 'high': print('orchid') plant_recommendation('low') plant_recommendation('medium') plant_recommendation('high')
class Settings(): def __init__(self): self.screen_width = 1024 # screen Width self.screen_height = 512 # screen height self.bg_color = (255, 255, 255) # overall background color self.init_speed = 30 # speed factor of dino self.dhmax = 23 self.alt_freq...
class Settings: def __init__(self): self.screen_width = 1024 self.screen_height = 512 self.bg_color = (255, 255, 255) self.init_speed = 30 self.dhmax = 23 self.alt_freq = 3
# Maths # Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length. # # Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1: # # If S[i] == "I", then A[i] < A[i+1] # If S[i] == "D", then A[i] > A[i+1] # # # Example 1: # # Input: "IDID" # Output: [0,4,1,3,2] # Exam...
class Solution: def di_string_match(self, S): """ :type S: str :rtype: List[int] """ (low, high) = (0, len(S)) output = [] for x in S: if x == 'I': output.append(low) low += 1 else: outpu...
# Interface for a "set" of cases class CaseSet: def __init__(self, time): self.time = time def __len__(self): raise NotImplementedError() def iterator(self): raise NotImplementedError() def get_time(self): return self.time def set_time(self, time): self.t...
class Caseset: def __init__(self, time): self.time = time def __len__(self): raise not_implemented_error() def iterator(self): raise not_implemented_error() def get_time(self): return self.time def set_time(self, time): self.time = time
def array_count9(nums): count = 0 # Standard loop to look at each value for num in nums: if num == 9: count = count + 1 return count
def array_count9(nums): count = 0 for num in nums: if num == 9: count = count + 1 return count
# # @lc app=leetcode id=747 lang=python3 # # [747] Largest Number At Least Twice of Others # # https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ # # algorithms # Easy (40.25%) # Total Accepted: 47.6K # Total Submissions: 118K # Testcase Example: '[0,0,0,1]' # # In a giv...
class Solution: def dominant_index(self, nums: List[int]) -> int: indexmax1 = 0 max1 = 0 indexmax = 0 max = 0 for i in range(len(nums)): if nums[i] > max: max1 = max indexmax1 = indexmax max = nums[i] ...
# Speed of light in m/s speed_light = 299792458 # J s Planck_constant = 6.626e-34 # m Wavelenght of band V wavelenght_visual = 550e-9 # flux density (Jy) in V for a 0 mag star Fv = 3640.0 # photons s-1 m-2 in Jy Jy = 1.51e7 #1 rad = 57.3 grad RAD = 57.29578 # 1 AU ib cn AU = 149.59787e11 # Radius in cm R_Earth =...
speed_light = 299792458 planck_constant = 6.626e-34 wavelenght_visual = 5.5e-07 fv = 3640.0 jy = 15100000.0 rad = 57.29578 au = 14959787000000.0 r__earth = 637800000.0 r_moon = 173740000.0 atmosphere = 10000000.0 jd_2018 = 2458119.5 km = 100000.0 m2 = 10000.0 g = 6.67384e-11 mu__earth = 398600000000000.0 timestamp_2018...
factors = [1, 2, 4] pads = [32, 64, 128, 256, 512] gen_scope = "gen" dis_scope = "dis" outputs_prefix = "output_" lr_key = "lr" hr_key = "hr" lr_input_name = "lr_input" hr_input_name = "hr_input" pretrain_key = "pretrain" train_key = "train" epoch_key = "per_epoch"
factors = [1, 2, 4] pads = [32, 64, 128, 256, 512] gen_scope = 'gen' dis_scope = 'dis' outputs_prefix = 'output_' lr_key = 'lr' hr_key = 'hr' lr_input_name = 'lr_input' hr_input_name = 'hr_input' pretrain_key = 'pretrain' train_key = 'train' epoch_key = 'per_epoch'
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Examp...
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Examp...
# generic warnings UNEXPECTED_FIELDS = 'A GTFS fares-v2 file has column name(s) not defined in the specification.' UNUSED_AREA_IDS = 'Areas defined in areas.txt are unused in other fares files.' UNUSED_NETWORK_IDS = 'Networks defined in routes.txt are unused in other fares files.' UNUSED_TIMEFRAME_IDS = 'Timeframes def...
unexpected_fields = 'A GTFS fares-v2 file has column name(s) not defined in the specification.' unused_area_ids = 'Areas defined in areas.txt are unused in other fares files.' unused_network_ids = 'Networks defined in routes.txt are unused in other fares files.' unused_timeframe_ids = 'Timeframes defined in timeframes....
def test_contacts_on_home_page(app): contact_from_home_page = app.contact.get_contacts_list()[1] contact_from_edit_page = app.contact.get_info_from_edit_page(1) assert contact_from_edit_page.email_1 == contact_from_home_page.email_1 assert contact_from_edit_page.email_2 == contact_from_home_page.emai...
def test_contacts_on_home_page(app): contact_from_home_page = app.contact.get_contacts_list()[1] contact_from_edit_page = app.contact.get_info_from_edit_page(1) assert contact_from_edit_page.email_1 == contact_from_home_page.email_1 assert contact_from_edit_page.email_2 == contact_from_home_page.email_2...
# # PySNMP MIB module OPTIX-SONET-EQPTMGT-MIB-V2 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPTIX-SONET-EQPTMGT-MIB-V2 # Produced by pysmi-0.3.4 at Mon Apr 29 20:26:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ...
#!/usr/bin/env python3 CAVE_DEPTH = 6969 TARGET_LOC = (9, 796) GEO_INDEX_CACHE = { (0, 0): 0, TARGET_LOC: 0 } def get_geo_index(x, y): key = (x, y) if key not in GEO_INDEX_CACHE: if y == 0: GEO_INDEX_CACHE[key] = x * 16807 elif x == 0: GEO_INDEX_CACHE[key] = y...
cave_depth = 6969 target_loc = (9, 796) geo_index_cache = {(0, 0): 0, TARGET_LOC: 0} def get_geo_index(x, y): key = (x, y) if key not in GEO_INDEX_CACHE: if y == 0: GEO_INDEX_CACHE[key] = x * 16807 elif x == 0: GEO_INDEX_CACHE[key] = y * 48271 else: G...
"""Globally register callables and call via matching keywords. Example: >>> # register print function for keyword my_value >>> set_recorder(my_value=print) >>> record(my_value="Hello World.") Hello World. """ _recorders = {} def set_recorder(**kwargs): """Globally register a callable to which record calls are ...
"""Globally register callables and call via matching keywords. Example: >>> # register print function for keyword my_value >>> set_recorder(my_value=print) >>> record(my_value="Hello World.") Hello World. """ _recorders = {} def set_recorder(**kwargs): """Globally register a callable to which record calls are de...
def is_string(thing): try: return isinstance(thing, basestring) except NameError: return isinstance(thing, str)
def is_string(thing): try: return isinstance(thing, basestring) except NameError: return isinstance(thing, str)
def authenticated_method(func): def _decorated(self, *args, **kwargs): if not self.api_key: raise ValueError("you need to set your API KEY for this method.") response = func(self, *args, **kwargs) if response.status_code == 401: raise ValueError("invalid private/pu...
def authenticated_method(func): def _decorated(self, *args, **kwargs): if not self.api_key: raise value_error('you need to set your API KEY for this method.') response = func(self, *args, **kwargs) if response.status_code == 401: raise value_error('invalid private/pu...
class Frac: def __init__(self, idx: int, idy: int, x: int, y: int) -> None: self.idx = idx self.idy = idy self.x = x self.y = y def __lt__(self, other: "Frac") -> bool: return self.x * other.y < self.y * other.x class Solution: def kthSmallestPrimeFraction(self, arr...
class Frac: def __init__(self, idx: int, idy: int, x: int, y: int) -> None: self.idx = idx self.idy = idy self.x = x self.y = y def __lt__(self, other: 'Frac') -> bool: return self.x * other.y < self.y * other.x class Solution: def kth_smallest_prime_fraction(self...
while True: try: num=int(input("Input your number: ")) print("Your number is {}".format(num)) break except: print("Please insert number!")
while True: try: num = int(input('Input your number: ')) print('Your number is {}'.format(num)) break except: print('Please insert number!')
class XnorController: pass
class Xnorcontroller: pass
class MovingAverage: """ [1,10,3,5] size = 3 n = 4 [0,1,11,14,19] """ def __init__(self, size: int): self.size = size self.prefixes = [0] def next(self, val: int) -> float: n = len(self.prefixes) self.prefixes.append(val) self.prefixes[-1] +=...
class Movingaverage: """ [1,10,3,5] size = 3 n = 4 [0,1,11,14,19] """ def __init__(self, size: int): self.size = size self.prefixes = [0] def next(self, val: int) -> float: n = len(self.prefixes) self.prefixes.append(val) self.prefixes[-1] +...
birth_year = 1999 if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6") if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6")
birth_year = 1999 if birth_year < 2000: print('line 1') print('line 2') print('line 3') else: print('line 4') print('line 5') print('line 6') if birth_year < 2000: print('line 1') print('line 2') print('line 3') else: print('line 4') print('line 5') print('line 6')
class TreeNode: def __init__(self, x): self.val = x self.next = None class Solution: def inorderTraversal(self, root: TreeNode) -> list: if root == None: return [] stack = [] visited = set() trav = [] stack.append(root) wh...
class Treenode: def __init__(self, x): self.val = x self.next = None class Solution: def inorder_traversal(self, root: TreeNode) -> list: if root == None: return [] stack = [] visited = set() trav = [] stack.append(root) while len(st...
# Time: O(n + k) # Space: O(k) # 28 # Implement strStr(). # # Returns a pointer to the first occurrence of needle in haystack, # or null if needle is not part of haystack. # # Wiki of KMP algorithm: # http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm class Solution(object): def strStr(self, haystack, ne...
class Solution(object): def str_str(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 return self.KMP(haystack, needle) def kmp(self, text, pattern): prefix = self.preKmp(patter...
for i in range(0,3): f = open("dato.txt") f.seek(17+(i*77),0) x1= int(f.read(2)) f.seek(20+(i*77),0) y1= int(f.read(2)) f.seek(35+(i*77),0) a= int(f.read(2)) f.seek(38+(i*77),0) b= int(f.read(2)) f.seek(60+(i*77),0) x2= int(f.read(2)) f.seek(63+(i*77),0) y2= int...
for i in range(0, 3): f = open('dato.txt') f.seek(17 + i * 77, 0) x1 = int(f.read(2)) f.seek(20 + i * 77, 0) y1 = int(f.read(2)) f.seek(35 + i * 77, 0) a = int(f.read(2)) f.seek(38 + i * 77, 0) b = int(f.read(2)) f.seek(60 + i * 77, 0) x2 = int(f.read(2)) f.seek(63 + i * ...
a=int(input('Enter number of terms ')) f=1 s=0 for i in range(1,a+1): f=f*i s+=f print('Sum of series =',s)
a = int(input('Enter number of terms ')) f = 1 s = 0 for i in range(1, a + 1): f = f * i s += f print('Sum of series =', s)
# You need Elemental codex 1+ to cast "Haste" hero.cast("haste", hero) hero.moveXY(14, 30) hero.moveXY(20, 30) hero.moveXY(28, 15) hero.moveXY(69, 15) hero.moveXY(72, 58)
hero.cast('haste', hero) hero.moveXY(14, 30) hero.moveXY(20, 30) hero.moveXY(28, 15) hero.moveXY(69, 15) hero.moveXY(72, 58)
""" Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. Every eight bits in the binary string represents one character on the ASCII table. Examples: csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" 01101100 -> 108 -> "l" 01100001 -> 97 -> "...
""" Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. Every eight bits in the binary string represents one character on the ASCII table. Examples: csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" 01101100 -> 108 -> "l" 01100001 -> 97 -> "...
# A Bubble class class Bubble(object): # Create the Bubble def __init__(self, x, y, diameter, name): self.x = x self.y = y self.diameter = diameter self.name = name self.over = False # Checking if mouse is over the Bubble def rollover(self, px, ...
class Bubble(object): def __init__(self, x, y, diameter, name): self.x = x self.y = y self.diameter = diameter self.name = name self.over = False def rollover(self, px, py): d = dist(px, py, self.x, self.y) self.over = d < self.diameter / 2 def disp...
queue = [] visited = [] def bfs(visited, graph, start, target): visited.append(start) queue.append(start) while queue: cur = queue.pop(0) if cur == target: break for child in graph[cur]: if child not in visited: visited.append(child) ...
queue = [] visited = [] def bfs(visited, graph, start, target): visited.append(start) queue.append(start) while queue: cur = queue.pop(0) if cur == target: break for child in graph[cur]: if child not in visited: visited.append(child) ...
# 621. Task Scheduler class Solution: # Greedy def leastInterval(self, tasks: List[str], n: int) -> int: # Maximum possible number of idle slots is defined by the frequency of the most frequent task. freq = [0] * 26 for t in tasks: freq[ord(t) - ord('A')] += 1 freq....
class Solution: def least_interval(self, tasks: List[str], n: int) -> int: freq = [0] * 26 for t in tasks: freq[ord(t) - ord('A')] += 1 freq.sort() max_freq = freq.pop() idle_time = (max_freq - 1) * n while freq and idle_time > 0: idle_time -=...
def ugly1(): q2, q3, q5 = [2], [3], [5] while 1: # print q2, q3, q5 if q2[0] < q3[0] and q2[0] < q5[0]: ret = q2.pop(0) q2.append(ret * 2) q3.append(ret * 3) q5.append(ret * 5) elif q3[0] < q2[0] and q3[0] < q5[0]: ret = q3.pop(...
def ugly1(): (q2, q3, q5) = ([2], [3], [5]) while 1: if q2[0] < q3[0] and q2[0] < q5[0]: ret = q2.pop(0) q2.append(ret * 2) q3.append(ret * 3) q5.append(ret * 5) elif q3[0] < q2[0] and q3[0] < q5[0]: ret = q3.pop(0) q3.appen...
def fetch_ID(url): ''' Takes a video.dtu.dk link and returns the video ID. TODO: This should make some assertions about the url. ''' return '0_' + url.split('0_')[-1].split('/')[0]
def fetch_id(url): """ Takes a video.dtu.dk link and returns the video ID. TODO: This should make some assertions about the url. """ return '0_' + url.split('0_')[-1].split('/')[0]
""" __init__.py @Organization: @Author: Ming Zhou @Time: 4/22/21 5:28 PM @Function: """
""" __init__.py @Organization: @Author: Ming Zhou @Time: 4/22/21 5:28 PM @Function: """
def sametype(s1: str, s2: str) -> bool: return s1.lower() == s2.lower() def reduct(polymer: str)-> str: did_reduce = True while did_reduce : did_reduce = False for i in range(1, len(polymer)): unit1 = polymer[i-1] unit2 = polymer[i] if sametyp...
def sametype(s1: str, s2: str) -> bool: return s1.lower() == s2.lower() def reduct(polymer: str) -> str: did_reduce = True while did_reduce: did_reduce = False for i in range(1, len(polymer)): unit1 = polymer[i - 1] unit2 = polymer[i] if sametype(unit1, u...
def run_model(models, features): # First decision for experiment in ["Invasive v.s. Noninvasive", "Atypia and DCIS v.s. Benign", "DCIS v.s. Atypia"]: pca = models[experiment + " PCA"] if pca is not None: features = pca.transform(fea...
def run_model(models, features): for experiment in ['Invasive v.s. Noninvasive', 'Atypia and DCIS v.s. Benign', 'DCIS v.s. Atypia']: pca = models[experiment + ' PCA'] if pca is not None: features = pca.transform(features).reshape(1, -1) model = models[experiment + ' model'] ...