content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# "Common block" loaded by the cfi and the cfg to communicate egmID parameters
electronVetoId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto'
electronLooseId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose'
electronMediumId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium'
electronTightId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight'
electronHLTId = 'egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1'
electronMVAWP90 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp90'
electronMVAWP80 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp80'
electronCombIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt'
electronEcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_ecalPFClusterIso.txt'
electronHcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_hcalPFClusterIso.txt'
photonLooseId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-loose'
photonMediumId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium'
photonTightId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight'
photonCHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfChargedHadrons_90percentBased.txt'
photonNHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfNeutralHadrons_90percentBased.txt'
photonPhIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfPhotons_90percentBased.txt'
# https://twiki.cern.ch/twiki/bin/view/CMS/EGMSmearer#Energy_smearing_and_scale_correc
# https://github.com/ECALELFS/ScalesSmearings/tree/Moriond17_23Jan_v2
electronSmearingData = {
"Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015",
"76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc",
"80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV1_2016_ele",
"Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC corrections
}
photonSmearingData = {
"Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015",
"76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc",
"80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV2_2016_pho",
"Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC correctionsb
}
| electron_veto_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto'
electron_loose_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose'
electron_medium_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium'
electron_tight_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight'
electron_hlt_id = 'egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1'
electron_mvawp90 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp90'
electron_mvawp80 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp80'
electron_comb_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt'
electron_ecal_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_ecalPFClusterIso.txt'
electron_hcal_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_hcalPFClusterIso.txt'
photon_loose_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-loose'
photon_medium_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium'
photon_tight_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight'
photon_ch_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfChargedHadrons_90percentBased.txt'
photon_nh_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfNeutralHadrons_90percentBased.txt'
photon_ph_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfPhotons_90percentBased.txt'
electron_smearing_data = {'Prompt2015': 'SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015', '76XReReco': 'SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc', '80Xapproval': 'SUEPProd/Producer/data/ScalesSmearings/80X_ichepV1_2016_ele', 'Moriond2017_JEC': 'SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele'}
photon_smearing_data = {'Prompt2015': 'SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015', '76XReReco': 'SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc', '80Xapproval': 'SUEPProd/Producer/data/ScalesSmearings/80X_ichepV2_2016_pho', 'Moriond2017_JEC': 'SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele'} |
class Plugin(object):
def __init__(self, myarg):
self.myarg = myarg
def do_it(self):
print("doing it with myarg={} inside plugin1".format(self.myarg))
| class Plugin(object):
def __init__(self, myarg):
self.myarg = myarg
def do_it(self):
print('doing it with myarg={} inside plugin1'.format(self.myarg)) |
load("//:packages.bzl", "CDK_PACKAGES")
# Base rollup globals for dependencies and the root entry-point.
CDK_ROLLUP_GLOBALS = {
'tslib': 'tslib',
'@angular/cdk': 'ng.cdk',
}
# Rollup globals for subpackages in the form of, e.g., {"@angular/cdk/table": "ng.cdk.table"}
CDK_ROLLUP_GLOBALS.update({
"@angular/cdk/%s" % p: "ng.cdk.%s" % p for p in CDK_PACKAGES
})
| load('//:packages.bzl', 'CDK_PACKAGES')
cdk_rollup_globals = {'tslib': 'tslib', '@angular/cdk': 'ng.cdk'}
CDK_ROLLUP_GLOBALS.update({'@angular/cdk/%s' % p: 'ng.cdk.%s' % p for p in CDK_PACKAGES}) |
res = client.get_smtp_servers() # The SMTP properties are related to alert routing
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# Valid fields: continuation_token, filter, ids, limit, names, offset, sort
# See section "Common Fields" for examples
| res = client.get_smtp_servers()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items)) |
mimic_tables_dir = './mimic_tables/' # location of the metadata tables of the mimic-cxr dataset. Inside this folder:'mimic-cxr-2.0.0-chexpert.csv' and 'mimic-cxr-2.0.0-split.csv'
jpg_path = './dataset_mimic_jpg/' # location of the full mimic-cxr-jpg dataset. Inside this folder: "physionet.org" folder
dicom_path = './dataset_mimic/' # location of the dicom images of the mimic-cxr dataset that were included in the eyetracking dataset. Inside this folder: "physionet.org" folder
h5_path = '/scratch/' # folder where to save hdf5 files containing the full resized mimic dataset to speed up training
eyetracking_dataset_path = './dataset_et/main_data/' # location of the eye-tracking dataset. Inside this folder: metadata csv and all cases folders
segmentation_model_path = './segmentation_model/' #Inside this folder: trained_model.hdf5, from https://github.com/imlab-uiip/lung-segmentation-2d | mimic_tables_dir = './mimic_tables/'
jpg_path = './dataset_mimic_jpg/'
dicom_path = './dataset_mimic/'
h5_path = '/scratch/'
eyetracking_dataset_path = './dataset_et/main_data/'
segmentation_model_path = './segmentation_model/' |
class GCode(object):
def comment(self):
return ""
def __str__(self) -> str:
return f"{self.code()}{self.comment()}"
class G0(GCode):
def __init__(self, x=None, y=None, z=None) -> None:
if (x is None and y is None and z is None):
raise TypeError("G0 needs at least one axis")
self.x = x
self.y = y
self.z = z
def coordinate(self):
result = []
if self.x is not None:
result.append(f"X{self.x}")
if self.y is not None:
result.append(f"Y{self.y:.4f}")
if self.z is not None:
result.append(f"Z{self.z}")
return result
def code(self):
return f"G0 {' '.join(self.coordinate())}"
class G1(GCode):
def __init__(self, x=None, y=None, z=None, feedrate=None) -> None:
if (x is None and y is None and z is None and feedrate is None):
raise TypeError("G1 needs at least one axis, or a feedrate")
self.x = x
self.y = y
self.z = z
self.feedrate = feedrate
def coordinate(self):
result = []
if self.x is not None:
result.append(f"X{self.x}")
if self.y is not None:
result.append(f"Y{self.y:.4f}")
if self.z is not None:
result.append(f"Z{self.z}")
return result
def comment(self):
return f"; Set feedrate to {self.feedrate} mm/min" if self.feedrate else ""
def code(self):
attributes = self.coordinate()
if self.feedrate:
attributes.append(f"F{self.feedrate}")
return f"G1 {' '.join(attributes)}"
class G4(GCode):
def __init__(self, duration) -> None:
self.duration = duration
def comment(self):
return f"; Wait for {self.duration} seconds"
def code(self):
return f"G4 P{self.duration}"
class G21(GCode):
def comment(self):
return f"; mm-mode"
def code(self):
return f"G21"
class G54(GCode):
def comment(self):
return f"; Work Coordinates"
def code(self):
return f"G54"
class G90(GCode):
def comment(self):
return f"; Absolute Positioning"
def code(self):
return f"G90"
class G91(GCode):
def comment(self):
return f"; Relative Positioning"
def code(self):
return f"G91"
class M3(GCode):
def __init__(self, spindle_speed) -> None:
self.spindle_speed = spindle_speed
def comment(self):
return f"; Spindle on to {self.spindle_speed} RPM"
def code(self):
return f"M3 S{self.spindle_speed}"
class M5(GCode):
def comment(self):
return f"; Stop spindle"
def code(self):
return f"M5 S0"
| class Gcode(object):
def comment(self):
return ''
def __str__(self) -> str:
return f'{self.code()}{self.comment()}'
class G0(GCode):
def __init__(self, x=None, y=None, z=None) -> None:
if x is None and y is None and (z is None):
raise type_error('G0 needs at least one axis')
self.x = x
self.y = y
self.z = z
def coordinate(self):
result = []
if self.x is not None:
result.append(f'X{self.x}')
if self.y is not None:
result.append(f'Y{self.y:.4f}')
if self.z is not None:
result.append(f'Z{self.z}')
return result
def code(self):
return f"G0 {' '.join(self.coordinate())}"
class G1(GCode):
def __init__(self, x=None, y=None, z=None, feedrate=None) -> None:
if x is None and y is None and (z is None) and (feedrate is None):
raise type_error('G1 needs at least one axis, or a feedrate')
self.x = x
self.y = y
self.z = z
self.feedrate = feedrate
def coordinate(self):
result = []
if self.x is not None:
result.append(f'X{self.x}')
if self.y is not None:
result.append(f'Y{self.y:.4f}')
if self.z is not None:
result.append(f'Z{self.z}')
return result
def comment(self):
return f'; Set feedrate to {self.feedrate} mm/min' if self.feedrate else ''
def code(self):
attributes = self.coordinate()
if self.feedrate:
attributes.append(f'F{self.feedrate}')
return f"G1 {' '.join(attributes)}"
class G4(GCode):
def __init__(self, duration) -> None:
self.duration = duration
def comment(self):
return f'; Wait for {self.duration} seconds'
def code(self):
return f'G4 P{self.duration}'
class G21(GCode):
def comment(self):
return f'; mm-mode'
def code(self):
return f'G21'
class G54(GCode):
def comment(self):
return f'; Work Coordinates'
def code(self):
return f'G54'
class G90(GCode):
def comment(self):
return f'; Absolute Positioning'
def code(self):
return f'G90'
class G91(GCode):
def comment(self):
return f'; Relative Positioning'
def code(self):
return f'G91'
class M3(GCode):
def __init__(self, spindle_speed) -> None:
self.spindle_speed = spindle_speed
def comment(self):
return f'; Spindle on to {self.spindle_speed} RPM'
def code(self):
return f'M3 S{self.spindle_speed}'
class M5(GCode):
def comment(self):
return f'; Stop spindle'
def code(self):
return f'M5 S0' |
class ListNode:
def __init__(self, data):
self.data= data
self.next= None
class Solution:
def delete_nth_from_last(self, head: ListNode, n: int) -> ListNode:
ans= ListNode(0)
ans.next= head
first= ans
second= ans
for i in range(1, n+2):
first= first.next
while(first is not None):
first= first.next
second= second.next
second.next= second.next.next
return ans.next
def print_list(self, head: ListNode) -> None:
while (head):
print(head.data)
head = head.next
s= Solution()
ll_1= ListNode(1)
ll_2= ListNode(2)
ll_3= ListNode(3)
ll_4= ListNode(4)
ll_5= ListNode(5)
ll_1.next= ll_2
ll_2.next= ll_3
ll_3.next= ll_4
ll_4.next= ll_5
s.print_list(ll_1)
new_head= s.delete_nth_from_last(ll_1,2)
print()
s.print_list(new_head) | class Listnode:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def delete_nth_from_last(self, head: ListNode, n: int) -> ListNode:
ans = list_node(0)
ans.next = head
first = ans
second = ans
for i in range(1, n + 2):
first = first.next
while first is not None:
first = first.next
second = second.next
second.next = second.next.next
return ans.next
def print_list(self, head: ListNode) -> None:
while head:
print(head.data)
head = head.next
s = solution()
ll_1 = list_node(1)
ll_2 = list_node(2)
ll_3 = list_node(3)
ll_4 = list_node(4)
ll_5 = list_node(5)
ll_1.next = ll_2
ll_2.next = ll_3
ll_3.next = ll_4
ll_4.next = ll_5
s.print_list(ll_1)
new_head = s.delete_nth_from_last(ll_1, 2)
print()
s.print_list(new_head) |
#functions with output
def format_name(f_name, l_name):
if f_name == '' or l_name == '':
return "You didn't privide valid inputs"
formated_f_name = f_name.title()
formated_l_name = l_name.title()
#print(f'{formated_f_name} {formated_l_name}')
return f'{formated_f_name} {formated_l_name}'
#formated_string = format_name('eDgar', 'CanRo')
#print(formated_string)
#print(format_name('eDgar', 'CanRo'))
#output = len('Edgar')
print(format_name(input('What is you firts name?: '),
input('What is your last name?: '))) | def format_name(f_name, l_name):
if f_name == '' or l_name == '':
return "You didn't privide valid inputs"
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f'{formated_f_name} {formated_l_name}'
print(format_name(input('What is you firts name?: '), input('What is your last name?: '))) |
def Sum(value1, value2=200, value3=300):
return value1 + value2 + value3
print(Sum(10))
print(Sum(10, 20))
print(Sum(10, 20, 30))
print(Sum(10, value2=20))
print(Sum(10, value3=30))
print(Sum(10, value2=20, value3=30))
| def sum(value1, value2=200, value3=300):
return value1 + value2 + value3
print(sum(10))
print(sum(10, 20))
print(sum(10, 20, 30))
print(sum(10, value2=20))
print(sum(10, value3=30))
print(sum(10, value2=20, value3=30)) |
liste = []
entiers = 0
somme = 0
isZero = False
while not isZero:
number = float(input("Entrez un nombre: "))
if number == 0: isZero = True
elif number - int(number) == 0:
entiers += 1
somme += number
liste += [number]
print("Liste:", liste)
print("Nombre d'entiers:", entiers)
print("Somme des entiers:", somme)
| liste = []
entiers = 0
somme = 0
is_zero = False
while not isZero:
number = float(input('Entrez un nombre: '))
if number == 0:
is_zero = True
elif number - int(number) == 0:
entiers += 1
somme += number
liste += [number]
print('Liste:', liste)
print("Nombre d'entiers:", entiers)
print('Somme des entiers:', somme) |
# -*- coding:utf-8 -*-
# author: lyl
def get_age():
age = 18
name = 'Alex'
return age
print() | def get_age():
age = 18
name = 'Alex'
return age
print() |
#!/usr/bin/env python3
pwd=os.walk(os.getcwd())
for a,b,c in pwd:
for i in c:
if re.search('.*\.txt$',i):
file_FullPath=os.path.join(a,i)
file_open=open(file_FullPath,'r',encoding='gbk')
file_read=file_open.read()
file_open.close()
file_write=open(file_FullPath,'w',encoding='utf-8')
file_write.write(file_read)
file_write.close()
| pwd = os.walk(os.getcwd())
for (a, b, c) in pwd:
for i in c:
if re.search('.*\\.txt$', i):
file__full_path = os.path.join(a, i)
file_open = open(file_FullPath, 'r', encoding='gbk')
file_read = file_open.read()
file_open.close()
file_write = open(file_FullPath, 'w', encoding='utf-8')
file_write.write(file_read)
file_write.close() |
class ValidationError(Exception):
def __init__(self, message):
super().__init__(message)
class FieldError(Exception):
def __init__(self, field_name, available_fields):
msg = (f"The field '{field_name}' is not present on your model. "
f"Available fields are: {', '.join(available_fields)}")
super().__init__(msg)
class ParserError(Exception):
def __init__(self):
msg = (f"You should provide one of html_document, html_tag or HTMLResponse "
"object to the model in order to resolve fields with a "
"value from the HTML document")
super().__init__(msg)
class ProjectExistsError(FileExistsError):
def __init__(self):
super().__init__('The project path does not exist.')
class ProjectNotConfiguredError(Exception):
def __init__(self):
super().__init__(("You are trying to run a functionnality that requires "
"you project to be fully configured via your settings file."))
class ModelNotImplementedError(Exception):
def __init__(self, message: str=None):
super().__init__(("Conditional (When), aggregate (Add, Substract, Multiply, Divide)"
f" functions should point to a model. {message}"))
class ModelExistsError(Exception):
def __init__(self, name: str):
super().__init__((f"Model '{name}' is already registered."))
class ImproperlyConfiguredError(Exception):
def __init__(self):
super().__init__('Your project is not properly configured.')
class SpiderExistsError(Exception):
def __init__(self, name: str):
super().__init__(f"'{name}' does not exist in the registry. "
f"Did you create '{name}' in your spiders module?")
class ResponseFailedError(Exception):
def __init__(self):
super().__init__("Zineb will not be able to generate a BeautifulSoup object from the response. "
"This is due to a response with a fail status code or being None.")
class RequestAborted(Exception):
pass
class ModelConstrainError(Exception):
def __init__(self, field_name, value):
super().__init__(f"Constraint not respected on '{field_name}'. '{value}' already present in the model.")
| class Validationerror(Exception):
def __init__(self, message):
super().__init__(message)
class Fielderror(Exception):
def __init__(self, field_name, available_fields):
msg = f"The field '{field_name}' is not present on your model. Available fields are: {', '.join(available_fields)}"
super().__init__(msg)
class Parsererror(Exception):
def __init__(self):
msg = f'You should provide one of html_document, html_tag or HTMLResponse object to the model in order to resolve fields with a value from the HTML document'
super().__init__(msg)
class Projectexistserror(FileExistsError):
def __init__(self):
super().__init__('The project path does not exist.')
class Projectnotconfigurederror(Exception):
def __init__(self):
super().__init__('You are trying to run a functionnality that requires you project to be fully configured via your settings file.')
class Modelnotimplementederror(Exception):
def __init__(self, message: str=None):
super().__init__(f'Conditional (When), aggregate (Add, Substract, Multiply, Divide) functions should point to a model. {message}')
class Modelexistserror(Exception):
def __init__(self, name: str):
super().__init__(f"Model '{name}' is already registered.")
class Improperlyconfigurederror(Exception):
def __init__(self):
super().__init__('Your project is not properly configured.')
class Spiderexistserror(Exception):
def __init__(self, name: str):
super().__init__(f"'{name}' does not exist in the registry. Did you create '{name}' in your spiders module?")
class Responsefailederror(Exception):
def __init__(self):
super().__init__('Zineb will not be able to generate a BeautifulSoup object from the response. This is due to a response with a fail status code or being None.')
class Requestaborted(Exception):
pass
class Modelconstrainerror(Exception):
def __init__(self, field_name, value):
super().__init__(f"Constraint not respected on '{field_name}'. '{value}' already present in the model.") |
a = int(input())
if a > 0:
print(1)
elif a== 0:
print(0)
else:
print(-1) | a = int(input())
if a > 0:
print(1)
elif a == 0:
print(0)
else:
print(-1) |
txhash = "0xb538eabb6cea1fc3af58f1474c2b8f1adbf36a209ec8dc5534618b1f2d860c8e"
version = "1.1.0"
network = "ropsten"
address = 'bc1qzse3hm25w3nx70e8nlss6nlfusj7wd4q3m8gax'
transaction_data = {
'txid': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b',
'hash': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b',
'version': 2,
'size': 222,
'vsize': 222,
'weight': 888,
'locktime': 1865235,
'vin': [{
'txid': '3c1324004cf55aff8d4153bda4b6059a82f6fdc4aa43b5b2d26fa3a97eed0e4f',
'vout': 0,
'scriptSig': {
'asm': '3044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff89251043[ALL] 0299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6',
'hex': '473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6'
},
'sequence': 4294967293
}],
'vout': [{
'value': 0.01,
'n': 0,
'scriptPubKey': {
'asm': '0 89c82f97d743d939d5c9f4068e3a53dfd09ec5fc',
'hex': '001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc',
'reqSigs': 1,
'type': 'witness_v0_keyhash',
'addresses': ['tb1q38yzl97hg0vnn4wf7srguwjnmlgfa30uq3nrwt']}
}, {
'value': 1.989997,
'n': 1,
'scriptPubKey': {
'asm': 'OP_DUP OP_HASH160 4c8bda34fa519008db22b421711ee6b9fb52b559 OP_EQUALVERIFY OP_CHECKSIG',
'hex': '76a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac',
'reqSigs': 1,
'type': 'pubkeyhash',
'addresses': ['mnVhBkEWwvP4MMeTBZoZa3GGTVsNm135eG']}
}],
'hex': '02000000014f0eed7ea9a36fd2b2b543aac4fdf6829a05b6a4bd53418dff5af54c0024133c000000006a473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6fdffffff0240420f000000000016001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc947edc0b000000001976a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac13761c00',
'blockhash': '0000000005629b78403c6b58bf094b1987dd9e62a9349f71ff4882c05f0ad517',
'confirmations': 24854,
'time': 1603872469,
'blocktime': 1603872469
}
| txhash = '0xb538eabb6cea1fc3af58f1474c2b8f1adbf36a209ec8dc5534618b1f2d860c8e'
version = '1.1.0'
network = 'ropsten'
address = 'bc1qzse3hm25w3nx70e8nlss6nlfusj7wd4q3m8gax'
transaction_data = {'txid': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'hash': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'version': 2, 'size': 222, 'vsize': 222, 'weight': 888, 'locktime': 1865235, 'vin': [{'txid': '3c1324004cf55aff8d4153bda4b6059a82f6fdc4aa43b5b2d26fa3a97eed0e4f', 'vout': 0, 'scriptSig': {'asm': '3044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff89251043[ALL] 0299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6', 'hex': '473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6'}, 'sequence': 4294967293}], 'vout': [{'value': 0.01, 'n': 0, 'scriptPubKey': {'asm': '0 89c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'hex': '001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'reqSigs': 1, 'type': 'witness_v0_keyhash', 'addresses': ['tb1q38yzl97hg0vnn4wf7srguwjnmlgfa30uq3nrwt']}}, {'value': 1.989997, 'n': 1, 'scriptPubKey': {'asm': 'OP_DUP OP_HASH160 4c8bda34fa519008db22b421711ee6b9fb52b559 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': ['mnVhBkEWwvP4MMeTBZoZa3GGTVsNm135eG']}}], 'hex': '02000000014f0eed7ea9a36fd2b2b543aac4fdf6829a05b6a4bd53418dff5af54c0024133c000000006a473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6fdffffff0240420f000000000016001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc947edc0b000000001976a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac13761c00', 'blockhash': '0000000005629b78403c6b58bf094b1987dd9e62a9349f71ff4882c05f0ad517', 'confirmations': 24854, 'time': 1603872469, 'blocktime': 1603872469} |
class CognitiveAbilitiesGroupingPolicy:
@staticmethod
def group(filename: str) -> str:
return filename.split(".")[0].split("-")[0]
| class Cognitiveabilitiesgroupingpolicy:
@staticmethod
def group(filename: str) -> str:
return filename.split('.')[0].split('-')[0] |
n=int(input());s=input();r=0;l=len(s)
for i in range(l):
r+=(ord(s[i])-ord('a')+1)*31**i
print(r%1234567891)
| n = int(input())
s = input()
r = 0
l = len(s)
for i in range(l):
r += (ord(s[i]) - ord('a') + 1) * 31 ** i
print(r % 1234567891) |
#!/usr/bin/env python3
def edit_distance(s1: str, s2: str) -> int:
n = len(s1)
m = len(s2)
edit = [[None for i in range(1 + m)] for j in range(1 + n)]
for i in range(1 + m):
edit[0][i] = i
for i in range(1, 1 + n):
edit[i][0] = i
for j in range(1, 1 + m):
replace = edit[i-1][j-1]
insert = 1 + edit[i][j - 1]
delete = 1 + edit[i - 1][j]
if not (s1[i - 1] == s2[j - 1]):
replace += 1
edit[i][j] = min(insert, delete, replace)
return edit[n][m]
if __name__ == '__main__':
s1 = input('s1: ')
s2 = input('s2: ')
print(edit_distance(s1, s2))
| def edit_distance(s1: str, s2: str) -> int:
n = len(s1)
m = len(s2)
edit = [[None for i in range(1 + m)] for j in range(1 + n)]
for i in range(1 + m):
edit[0][i] = i
for i in range(1, 1 + n):
edit[i][0] = i
for j in range(1, 1 + m):
replace = edit[i - 1][j - 1]
insert = 1 + edit[i][j - 1]
delete = 1 + edit[i - 1][j]
if not s1[i - 1] == s2[j - 1]:
replace += 1
edit[i][j] = min(insert, delete, replace)
return edit[n][m]
if __name__ == '__main__':
s1 = input('s1: ')
s2 = input('s2: ')
print(edit_distance(s1, s2)) |
FILTERS = [
[4, 1, 2],
[2, 2, 4],
[1, 4, 4],
[1, 4, 1]
]
MSG_LEN = 16
KEY_LEN = 16
BATCH_SIZE = 512
NUM_EPOCHS = 60
LEARNING_RATE = 0.0008
| filters = [[4, 1, 2], [2, 2, 4], [1, 4, 4], [1, 4, 1]]
msg_len = 16
key_len = 16
batch_size = 512
num_epochs = 60
learning_rate = 0.0008 |
def metade(preco=0, formato=False):
res = preco / 2
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if formato is False else moeda(res)
def aumento(preco=0, taxa=0, formato=False):
res = preco * (1 + taxa/100)
return res if formato is False else moeda(res)
def reducao(preco=0, taxa=0, formato=False):
res = preco * (1 - taxa/100)
return res if formato is False else moeda(res)
def moeda(preco=0, moeda='R$'):
return f' {moeda} {preco:7.2f}'.replace('.',',') | def metade(preco=0, formato=False):
res = preco / 2
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if formato is False else moeda(res)
def aumento(preco=0, taxa=0, formato=False):
res = preco * (1 + taxa / 100)
return res if formato is False else moeda(res)
def reducao(preco=0, taxa=0, formato=False):
res = preco * (1 - taxa / 100)
return res if formato is False else moeda(res)
def moeda(preco=0, moeda='R$'):
return f' {moeda} {preco:7.2f}'.replace('.', ',') |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#---------------------------------------------------------------------------
#
# Author: lubo
# E-mail: 454331202@qq.com
# LastModified: 2014-05-23 11:18:31
# Filename: gl.py
# Desc:
#
#---------------------------------------------------------------------------
headline1 = ''
headline2 = ''
mysql_headline1 = ''
mysql_headline2 = ''
ncpu = 0 #Number of processors
# Options Flag
optflag = 0 #whether input opt
timeFlag = 0 # -t : print current time
interval = 1 # -i : time(second) interval
my_load = 0 # -l : print load info
my_cpu = 0 # -c : print cpu info
my_swap = 0 # -s : print swap info
my_disk = None # -d : print disk info
my_net = None # -n : print net info
mysql = 0 # -mysql: print mysql status
mysql_conn ='' # mysql conn info
com = 0; # -com : print mysql status
innodb_hit = 0 # -hit : Print Innodb Hit%
innodb_rows = 0 # -innodb_rows : Print Innodb Rows Status
innodb_pages= 0 # -innodb_pages: Innodb Buffer Pool Pages Status
innodb_data = 0 # -innodb_data : Innodb Data Status
innodb_log = 0 # -innodb_log : Innodb Log Status
innodb_status=0 # -innodb_status: Show Engine Innodb Status
threads = 0 # -T : Print Threads Status
bytes = 0 # -B : Print Bytes Status
my_port = '3306' # default prot 3306
my_socket =None # sockfile
my_pwd =None # root user password
dbrt = 0 # -rt
lock_file=''
tcprstat_logfile=''
tcprstat_dir='/tmp/'
orz_logfile=None
old_console=''
logfile_by_day=0 # one day one logfile
# Variables For :
#-----> Get SysInfo (from /proc/stat): CPU
sys_cpu1 = (0,0,0,0,0,0,0,0)
total_1 = 0
#
#<----- Get SysInfo (from /proc/stat): CPU
#-----> Get SysInfo (from /proc/vmstat): SWAP
swap1 ={'pswpin':0,'pswpout':0}
swap_not_first = 0
#<----- Get SysInfo (from /proc/vmstat): SWAP
#-----> Get SysInfo (from /proc/net/dev): NET
net1 ={'recv':0,'send':0}
net_not_first = 0
#<----- Get SysInfo (from /proc/net/dev): NET
#-----> Get SysInfo (from /proc/diskstats): IO
sys_io1 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
io_not_first = 0; # no print first value
#ncpu = `grep processor /proc/cpuinfo | wc -l`; #/* Number of processors */
# grep "HZ" -R /usr/include/*
# /usr/include/asm-x86_64/param.h:#define HZ 100
HZ = 100
#<----- Get SysInfo (from /proc/diskstats): IO
#-----> Get Mysql Status
mystat1={"Com_select":0,
"Com_delete":0 ,
"Com_update":0,
"Com_insert":0,
"Innodb_buffer_pool_read_requests":0,
"Innodb_rows_inserted":0,
"Innodb_rows_updated":0,
"Innodb_rows_deleted":0,
"Innodb_rows_read":0,
"Threads_created":0,
"Bytes_received":0,
"Bytes_sent":0,
"Innodb_buffer_pool_pages_flushed":0,
"Innodb_data_read":0,
"Innodb_data_reads":0,
"Innodb_data_writes":0,
"Innodb_data_written":0,
"Innodb_os_log_fsyncs":0,
"Innodb_os_log_written":0}
mysql_no_first = 0
#<----- Get Mysql Status
HAS_COLOR=1
count=None #times
python_version=''
| headline1 = ''
headline2 = ''
mysql_headline1 = ''
mysql_headline2 = ''
ncpu = 0
optflag = 0
time_flag = 0
interval = 1
my_load = 0
my_cpu = 0
my_swap = 0
my_disk = None
my_net = None
mysql = 0
mysql_conn = ''
com = 0
innodb_hit = 0
innodb_rows = 0
innodb_pages = 0
innodb_data = 0
innodb_log = 0
innodb_status = 0
threads = 0
bytes = 0
my_port = '3306'
my_socket = None
my_pwd = None
dbrt = 0
lock_file = ''
tcprstat_logfile = ''
tcprstat_dir = '/tmp/'
orz_logfile = None
old_console = ''
logfile_by_day = 0
sys_cpu1 = (0, 0, 0, 0, 0, 0, 0, 0)
total_1 = 0
swap1 = {'pswpin': 0, 'pswpout': 0}
swap_not_first = 0
net1 = {'recv': 0, 'send': 0}
net_not_first = 0
sys_io1 = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
io_not_first = 0
hz = 100
mystat1 = {'Com_select': 0, 'Com_delete': 0, 'Com_update': 0, 'Com_insert': 0, 'Innodb_buffer_pool_read_requests': 0, 'Innodb_rows_inserted': 0, 'Innodb_rows_updated': 0, 'Innodb_rows_deleted': 0, 'Innodb_rows_read': 0, 'Threads_created': 0, 'Bytes_received': 0, 'Bytes_sent': 0, 'Innodb_buffer_pool_pages_flushed': 0, 'Innodb_data_read': 0, 'Innodb_data_reads': 0, 'Innodb_data_writes': 0, 'Innodb_data_written': 0, 'Innodb_os_log_fsyncs': 0, 'Innodb_os_log_written': 0}
mysql_no_first = 0
has_color = 1
count = None
python_version = '' |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"display": "00_core.ipynb",
"Markdown": "00_core.ipynb",
"Audio": "00_core.ipynb",
"first_run": "00_core.ipynb",
"beep": "00_core.ipynb",
"h1": "00_core.ipynb",
"h2": "00_core.ipynb",
"h3": "00_core.ipynb",
"h4": "00_core.ipynb",
"h5": "00_core.ipynb",
"h6": "00_core.ipynb",
"from_file": "00_core.ipynb",
"good_url": "00_core.ipynb",
"user_agent": "00_core.ipynb",
"extract_apex": "00_core.ipynb",
"extract_meta_link": "00_core.ipynb",
"extract_links": "00_core.ipynb",
"extract_title": "00_core.ipynb",
"extract_meta": "00_core.ipynb",
"extract_hx": "00_core.ipynb",
"extract_body": "00_core.ipynb",
"extract_stemmed": "00_core.ipynb",
"extract_url_keywords": "00_core.ipynb",
"extract_keywords": "00_core.ipynb",
"gsc_guess_site": "00_core.ipynb",
"gsc_url2keyword_query": "00_core.ipynb",
"gsc_url_query": "00_core.ipynb",
"gsc2df": "00_core.ipynb",
"df_allout": "00_core.ipynb",
"ga_accounts": "00_core.ipynb",
"ga_properties": "00_core.ipynb",
"ga_properties_g4": "00_core.ipynb",
"ga_profiles": "00_core.ipynb",
"ga_everything": "00_core.ipynb",
"inspect_url": "00_core.ipynb",
"drop_table": "00_core.ipynb",
"pk_compositor": "00_core.ipynb",
"pk_inserter": "00_core.ipynb",
"config2dict": "00_core.ipynb",
"build_google_search_query": "00_core.ipynb",
"extract_serps": "00_core.ipynb",
"run_me": "00_core.ipynb",
"look": "00_core.ipynb",
"show_globals": "00_core.ipynb",
"enlighten_me": "00_core.ipynb",
"save_me": "00_core.ipynb",
"please_explain": "00_core.ipynb",
"bs": "00_core.ipynb",
"lr": "10_requirements.ipynb",
"SPACES": "00_core.ipynb",
"LINES": "00_core.ipynb",
"pstem": "00_core.ipynb",
"stop_words": "00_core.ipynb",
"pkl": "00_core.ipynb",
"unpkl": "00_core.ipynb",
"svc_ga": "00_core.ipynb",
"svc_ga4": "00_core.ipynb",
"svc_gsc": "00_core.ipynb",
"svc_mail": "00_core.ipynb",
"svc_oauth": "00_core.ipynb",
"svc_sheet": "00_core.ipynb",
"svc_photo": "00_core.ipynb",
"svc_youtube": "00_core.ipynb",
"out": "10_requirements.ipynb",
"table": "10_requirements.ipynb",
"upgrades": "10_requirements.ipynb",
"outputs": "10_requirements.ipynb"}
modules = ["core.py",
"pip_upgrades.py"]
doc_url = "https://miklevin.github.io/mlseo/"
git_url = "https://github.com/miklevin/mlseo/tree/main/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'display': '00_core.ipynb', 'Markdown': '00_core.ipynb', 'Audio': '00_core.ipynb', 'first_run': '00_core.ipynb', 'beep': '00_core.ipynb', 'h1': '00_core.ipynb', 'h2': '00_core.ipynb', 'h3': '00_core.ipynb', 'h4': '00_core.ipynb', 'h5': '00_core.ipynb', 'h6': '00_core.ipynb', 'from_file': '00_core.ipynb', 'good_url': '00_core.ipynb', 'user_agent': '00_core.ipynb', 'extract_apex': '00_core.ipynb', 'extract_meta_link': '00_core.ipynb', 'extract_links': '00_core.ipynb', 'extract_title': '00_core.ipynb', 'extract_meta': '00_core.ipynb', 'extract_hx': '00_core.ipynb', 'extract_body': '00_core.ipynb', 'extract_stemmed': '00_core.ipynb', 'extract_url_keywords': '00_core.ipynb', 'extract_keywords': '00_core.ipynb', 'gsc_guess_site': '00_core.ipynb', 'gsc_url2keyword_query': '00_core.ipynb', 'gsc_url_query': '00_core.ipynb', 'gsc2df': '00_core.ipynb', 'df_allout': '00_core.ipynb', 'ga_accounts': '00_core.ipynb', 'ga_properties': '00_core.ipynb', 'ga_properties_g4': '00_core.ipynb', 'ga_profiles': '00_core.ipynb', 'ga_everything': '00_core.ipynb', 'inspect_url': '00_core.ipynb', 'drop_table': '00_core.ipynb', 'pk_compositor': '00_core.ipynb', 'pk_inserter': '00_core.ipynb', 'config2dict': '00_core.ipynb', 'build_google_search_query': '00_core.ipynb', 'extract_serps': '00_core.ipynb', 'run_me': '00_core.ipynb', 'look': '00_core.ipynb', 'show_globals': '00_core.ipynb', 'enlighten_me': '00_core.ipynb', 'save_me': '00_core.ipynb', 'please_explain': '00_core.ipynb', 'bs': '00_core.ipynb', 'lr': '10_requirements.ipynb', 'SPACES': '00_core.ipynb', 'LINES': '00_core.ipynb', 'pstem': '00_core.ipynb', 'stop_words': '00_core.ipynb', 'pkl': '00_core.ipynb', 'unpkl': '00_core.ipynb', 'svc_ga': '00_core.ipynb', 'svc_ga4': '00_core.ipynb', 'svc_gsc': '00_core.ipynb', 'svc_mail': '00_core.ipynb', 'svc_oauth': '00_core.ipynb', 'svc_sheet': '00_core.ipynb', 'svc_photo': '00_core.ipynb', 'svc_youtube': '00_core.ipynb', 'out': '10_requirements.ipynb', 'table': '10_requirements.ipynb', 'upgrades': '10_requirements.ipynb', 'outputs': '10_requirements.ipynb'}
modules = ['core.py', 'pip_upgrades.py']
doc_url = 'https://miklevin.github.io/mlseo/'
git_url = 'https://github.com/miklevin/mlseo/tree/main/'
def custom_doc_links(name):
return None |
#17/02/21
#What does this code do?
# This code takes an input "n" and counts out until that number is reached.
# This works similarly to the previous code, except with numbers.
n = int(input('Enter a number: '))
for i in range(n):
print(i + 1)
#What is happening here?
# In line 1, our code is taking an integer input, and assigning it to "n"
# After that, it prints i+1, until n is reached.
| n = int(input('Enter a number: '))
for i in range(n):
print(i + 1) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
strarr=[]
for x in range(n):
strin=input()
strarr.append(strin)
stradd=set(strarr)
print(len(stradd))
| n = int(input())
strarr = []
for x in range(n):
strin = input()
strarr.append(strin)
stradd = set(strarr)
print(len(stradd)) |
'''
580C. Kefa and Park
dfs and similar, graphs, trees, 1500
http://codeforces.com/problemset/problem/580/C
'''
n, m = map(int, input().split())
cat = 1
empty = 0
status = [-1] + list(map(int, input().split()))
tree = {}
for _ in range(n-1):
s, e = map(int, input().split())
if s not in tree:
tree[s] = [e]
else:
tree[s].append(e)
if e not in tree:
tree[e] = [s]
else:
tree[e].append(s)
count = 0
# graph: dict type, s: start node code
def BFS(graph, s):
queue = []
queue.append(s)
seen = set()
seen.add(s[0])
result = 0
while (len(queue) > 0):
vertex, current_c = queue.pop(0)
if current_c <= m:
nodes = graph[vertex]
# if is the restaurant(leaves)
if vertex != s[0] and len(nodes) == 1:
result += 1
else:
# if not leaves, add the children
for w in nodes:
if w not in seen:
# if not exceed max cat met
if status[w] == empty:
queue.append([w, 0])
elif current_c+status[w] <= m:
queue.append([w, current_c+status[w]])
seen.add(w)
return result
count = BFS(tree, [1, status[1]])
print(count) | """
580C. Kefa and Park
dfs and similar, graphs, trees, 1500
http://codeforces.com/problemset/problem/580/C
"""
(n, m) = map(int, input().split())
cat = 1
empty = 0
status = [-1] + list(map(int, input().split()))
tree = {}
for _ in range(n - 1):
(s, e) = map(int, input().split())
if s not in tree:
tree[s] = [e]
else:
tree[s].append(e)
if e not in tree:
tree[e] = [s]
else:
tree[e].append(s)
count = 0
def bfs(graph, s):
queue = []
queue.append(s)
seen = set()
seen.add(s[0])
result = 0
while len(queue) > 0:
(vertex, current_c) = queue.pop(0)
if current_c <= m:
nodes = graph[vertex]
if vertex != s[0] and len(nodes) == 1:
result += 1
else:
for w in nodes:
if w not in seen:
if status[w] == empty:
queue.append([w, 0])
elif current_c + status[w] <= m:
queue.append([w, current_c + status[w]])
seen.add(w)
return result
count = bfs(tree, [1, status[1]])
print(count) |
# https://adventofcode.com/2021/day/14
test = "2021-14_sample.txt"
run = "2021-14_input.txt"
def part1(fname):
template = None
inserts = {}
for i, line in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = line[6]
#print(template)
for _ in range(10):
reversed = [template[-1]]
for i in range(len(template)-2, -1, -1):
pair = template[i:i+2]
#print(f'{pair}')
if pair in inserts:
reversed.append(inserts[pair])
reversed.append(template[i])
template = ''.join(reversed[::-1])
#print(template)
counts = {}
for c in template:
counts[c] = counts.get(c, 0) + 1
print(counts)
return max(counts.values()) - min(counts.values())
def print_nonzero(inserts):
print('---')
for k, v in inserts.items():
if v['count'] > 0:
print(f' {k} : {v}')
print('---')
def part2(fname, steps):
inserts = {}
for i, line in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = {'count':0, 'next':[line[0]+line[6], line[6]+line[1]]}
print(template)
for i in range(len(template)-1):
pair = template[i:i+2]
inserts[pair]['count'] += 1
#print_nonzero(inserts)
for _ in range(steps):
# with 40 steps the string becomes terabytes in size
state = {}
for k in inserts:
state[k] = inserts[k]['count']
inserts[k]['count'] = 0
for k in state:
for nk in inserts[k]['next']:
inserts[nk]['count'] += state[k]
#print_nonzero(inserts)
counts = {template[-1]:1}
for pair in inserts:
c = pair[0]
counts[c] = counts.get(c, 0) + inserts[pair]['count']
for i in counts.items():
print(i)
return max(counts.values()) - min(counts.values())
assert part1(test) == 1588
print(f'part1: {part1(run)}')
assert part2(test, 10) == 1588
assert part2(test, 40) == 2188189693529
print(f'part2: {part2(run, 40)}')
| test = '2021-14_sample.txt'
run = '2021-14_input.txt'
def part1(fname):
template = None
inserts = {}
for (i, line) in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = line[6]
for _ in range(10):
reversed = [template[-1]]
for i in range(len(template) - 2, -1, -1):
pair = template[i:i + 2]
if pair in inserts:
reversed.append(inserts[pair])
reversed.append(template[i])
template = ''.join(reversed[::-1])
counts = {}
for c in template:
counts[c] = counts.get(c, 0) + 1
print(counts)
return max(counts.values()) - min(counts.values())
def print_nonzero(inserts):
print('---')
for (k, v) in inserts.items():
if v['count'] > 0:
print(f' {k} : {v}')
print('---')
def part2(fname, steps):
inserts = {}
for (i, line) in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = {'count': 0, 'next': [line[0] + line[6], line[6] + line[1]]}
print(template)
for i in range(len(template) - 1):
pair = template[i:i + 2]
inserts[pair]['count'] += 1
for _ in range(steps):
state = {}
for k in inserts:
state[k] = inserts[k]['count']
inserts[k]['count'] = 0
for k in state:
for nk in inserts[k]['next']:
inserts[nk]['count'] += state[k]
counts = {template[-1]: 1}
for pair in inserts:
c = pair[0]
counts[c] = counts.get(c, 0) + inserts[pair]['count']
for i in counts.items():
print(i)
return max(counts.values()) - min(counts.values())
assert part1(test) == 1588
print(f'part1: {part1(run)}')
assert part2(test, 10) == 1588
assert part2(test, 40) == 2188189693529
print(f'part2: {part2(run, 40)}') |
'''
Created on 11 Dec 2021
@author: laurentmichel
'''
class MappingException(Exception):
pass
class ParsingException(Exception):
pass
class NotImplementedException(Exception):
pass
| """
Created on 11 Dec 2021
@author: laurentmichel
"""
class Mappingexception(Exception):
pass
class Parsingexception(Exception):
pass
class Notimplementedexception(Exception):
pass |
_base_ = [
'../_base_/models/dla34up_lane.py',
'../_base_/datasets/bdd100k_lane.py',
'../_base_/schedules/bdd100k_lane_12e.py',
'../_base_/default_runtime.py'
]
| _base_ = ['../_base_/models/dla34up_lane.py', '../_base_/datasets/bdd100k_lane.py', '../_base_/schedules/bdd100k_lane_12e.py', '../_base_/default_runtime.py'] |
class ColumnLayer(tf.keras.layers.Layer):
def __init__(
self,
upstream_dim,
num_column_instances,
position_dim,
context_fan_in,
context_num_samples,
context_initial_sharpness,
train_context,
noise_rate,
bypass_rate,
):
super(ColumnLayer, self).__init__()
self.upstream_dim = upstream_dim
self.num_column_instances = num_column_instances
self.position_dim = position_dim
self.context_fan_in = context_fan_in
self.context_num_samples = context_num_samples
self.context_initial_sharpness = context_initial_sharpness
self.train_context = train_context
self.noise_rate = noise_rate
self.bypass_rate = bypass_rate
def build(self, input_shape):
self.context_aggregator = ContextAggregationLayer(
context_fan_in=self.context_fan_in,
position_dim=self.position_dim,
num_samples=self.context_num_samples,
initial_sharpness=self.context_initial_sharpness,
train_context=self.train_context,
dtype='mixed_float16',
)
self.permanence_separator = PermanenceSeparatorLayer(
upstream_dim=self.upstream_dim,
position_dim=self.position_dim,
bypass_rate=self.bypass_rate,
noise_rate=self.noise_rate,
)
self.column_selector = ColumnSelectorLayer(
num_column_instances=self.num_column_instances,
)
super(ColumnLayer, self).build(input_shape)
def reconstruct(self, upstream_state):
reconstruction = self.permanence_separator.reconstruct(upstream_state)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return reconstruction
def call(self, centered_input, training, is_bootstrapping=False):
enriched_input = self.context_aggregator(centered_input)
full_upstream_state, full_reconstruction = self.permanence_separator(
enriched_input,
is_bootstrapping=is_bootstrapping,
)
full_reconstruction = self.context_aggregator.reconstruct(full_reconstruction)
upstream_state = self.column_selector(full_upstream_state)
# Restore unit length for the selected upstream states
upstream_state = tf.math.l2_normalize(upstream_state, axis=-1, epsilon=tf.keras.backend.epsilon())
reconstruction = self.permanence_separator.reconstruct(upstream_state, training=training)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return [upstream_state, reconstruction, full_reconstruction]
| class Columnlayer(tf.keras.layers.Layer):
def __init__(self, upstream_dim, num_column_instances, position_dim, context_fan_in, context_num_samples, context_initial_sharpness, train_context, noise_rate, bypass_rate):
super(ColumnLayer, self).__init__()
self.upstream_dim = upstream_dim
self.num_column_instances = num_column_instances
self.position_dim = position_dim
self.context_fan_in = context_fan_in
self.context_num_samples = context_num_samples
self.context_initial_sharpness = context_initial_sharpness
self.train_context = train_context
self.noise_rate = noise_rate
self.bypass_rate = bypass_rate
def build(self, input_shape):
self.context_aggregator = context_aggregation_layer(context_fan_in=self.context_fan_in, position_dim=self.position_dim, num_samples=self.context_num_samples, initial_sharpness=self.context_initial_sharpness, train_context=self.train_context, dtype='mixed_float16')
self.permanence_separator = permanence_separator_layer(upstream_dim=self.upstream_dim, position_dim=self.position_dim, bypass_rate=self.bypass_rate, noise_rate=self.noise_rate)
self.column_selector = column_selector_layer(num_column_instances=self.num_column_instances)
super(ColumnLayer, self).build(input_shape)
def reconstruct(self, upstream_state):
reconstruction = self.permanence_separator.reconstruct(upstream_state)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return reconstruction
def call(self, centered_input, training, is_bootstrapping=False):
enriched_input = self.context_aggregator(centered_input)
(full_upstream_state, full_reconstruction) = self.permanence_separator(enriched_input, is_bootstrapping=is_bootstrapping)
full_reconstruction = self.context_aggregator.reconstruct(full_reconstruction)
upstream_state = self.column_selector(full_upstream_state)
upstream_state = tf.math.l2_normalize(upstream_state, axis=-1, epsilon=tf.keras.backend.epsilon())
reconstruction = self.permanence_separator.reconstruct(upstream_state, training=training)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return [upstream_state, reconstruction, full_reconstruction] |
###################
# COLOR CONSTANTS
###################
HEADER = '\033[95m'
OK_BLUE = '\033[94m'
OK_GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
###########################
# ERROR MESSAGES CONSTANTS
###########################
BASE_ERROR_MSG = '\n\nAll available commands:\n' \
'flaskbox --init \tInit the flaskbox.yml file' \
'\nflaskbox --start \tRun your mock Server\n'
FILE_EXISTS_MESSAGE = OK_GREEN + 'flaskbox.yml' \
+ ENDC + ' already exists'
NOT_EXISTS_MESSAGE = 'You need to create the ' + OK_GREEN + \
'flaskbox.yml' + ENDC + ' file' + BASE_ERROR_MSG
| header = '\x1b[95m'
ok_blue = '\x1b[94m'
ok_green = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
base_error_msg = '\n\nAll available commands:\nflaskbox --init \tInit the flaskbox.yml file\nflaskbox --start \tRun your mock Server\n'
file_exists_message = OK_GREEN + 'flaskbox.yml' + ENDC + ' already exists'
not_exists_message = 'You need to create the ' + OK_GREEN + 'flaskbox.yml' + ENDC + ' file' + BASE_ERROR_MSG |
def copyFile():
with open('test.txt') as file:
content = file.read()
with open('anotherTest.txt', 'w') as file:
file.write(content)
copyFile() | def copy_file():
with open('test.txt') as file:
content = file.read()
with open('anotherTest.txt', 'w') as file:
file.write(content)
copy_file() |
#!/usr/bin/env python3
# Day 10: Excel Sheet Column Number
#
# Given a column title as appear in an Excel sheet, return its corresponding
# column number.
# A = 1
# B = 2
# C = 3
# ...
# Z = 26
# AA = 27
# AB = 28
# ...
class Solution:
def titleToNumber(self, s: str) -> int:
# In other words, convert from base 26 to base 10, plus 1 as we
# don't start at zero
decimal = 0
for digit in s:
decimal *= 26
decimal += ord(digit) - ord("A") + 1
return decimal
# Tests
assert Solution().titleToNumber("A") == 1
assert Solution().titleToNumber("AB") == 28
assert Solution().titleToNumber("ZY") == 701
| class Solution:
def title_to_number(self, s: str) -> int:
decimal = 0
for digit in s:
decimal *= 26
decimal += ord(digit) - ord('A') + 1
return decimal
assert solution().titleToNumber('A') == 1
assert solution().titleToNumber('AB') == 28
assert solution().titleToNumber('ZY') == 701 |
class MissingValueError(ValueError):
pass
class ValidationError(ValueError):
pass
| class Missingvalueerror(ValueError):
pass
class Validationerror(ValueError):
pass |
class AImodel:
def __init__(self):
pass
def process(self,input):
return -1 | class Aimodel:
def __init__(self):
pass
def process(self, input):
return -1 |
#Factorial digit sum
#Recursive funtion to calculate
def factorial(num):
#For negative numbers 0 or 1 will return 1
if num <= 1:
return 1
else:
#If num is greater than 1 multiply num by num-1 recursively until it returns 1(lowest value)
return num * factorial(num-1)
#Ask user to input a number and asgn value to f
f = input("Please, enter a natural number to calculate factorial from: ")
#Call function passing in f parsed and print the returning value.
print(factorial(int(f)))
| def factorial(num):
if num <= 1:
return 1
else:
return num * factorial(num - 1)
f = input('Please, enter a natural number to calculate factorial from: ')
print(factorial(int(f))) |
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n = len(arr)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
cnt += abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c
return cnt
| class Solution:
def count_good_triplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n = len(arr)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
cnt += abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and (abs(arr[i] - arr[k]) <= c)
return cnt |
def intdiv(a, b):
return a // b
if __name__ == "__main__":
print("Hi, I can calculate the integer division of two numers")
a = int(input("a = "))
b = int(input("b = "))
print(f"a // b = {intdiv(a, b)}")
print("Bye!")
| def intdiv(a, b):
return a // b
if __name__ == '__main__':
print('Hi, I can calculate the integer division of two numers')
a = int(input('a = '))
b = int(input('b = '))
print(f'a // b = {intdiv(a, b)}')
print('Bye!') |
def power_consumption():
pass
def deadlines():
pass
def idle_cranes():
pass
def idle_machines():
pass
def buffer_usage():
pass
def material_pickup():
pass
| def power_consumption():
pass
def deadlines():
pass
def idle_cranes():
pass
def idle_machines():
pass
def buffer_usage():
pass
def material_pickup():
pass |
def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_
+ ".tests": [
"coveragerc",
"data/*.h5",
"data/*.dat",
"data/*.npy",
"integration_tests/*/*.yml",
"integration_tests/*/*.dat",
]
}
| def get_package_data():
return {_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*.h5', 'data/*.dat', 'data/*.npy', 'integration_tests/*/*.yml', 'integration_tests/*/*.dat']} |
#
# Exercism.io
# Python track
# Problem #1 - Hello World
# github.com/marnovo/Exercism
#
name = input("Tell your name: ")
def hello(name=''):
if name == '':
message = "Hello, World!"
else:
message = "Hello, " + name + "!"
return message
print(hello(name))
| name = input('Tell your name: ')
def hello(name=''):
if name == '':
message = 'Hello, World!'
else:
message = 'Hello, ' + name + '!'
return message
print(hello(name)) |
#Challenge042
v1 = float(input(' medida 1: '))
v2 = float(input(' medida 2: '))
v3 = float(input(' medida 3: '))
#if v1+v2+v3 == 180:
if v1 == v2 == v3:
print('Triangulo equilatero: com todos os lados iguais')
elif (v1 == v2 or v3) and (v2 == v1 or v3 ):
print('tringulo isoceles dois lados iguais')
elif (v1 != v2 or v3) and (v2 != v1 or v3) and (v3 != v1 or v2):
print('escaleno')
else:
print('nao e um triangulo') | v1 = float(input(' medida 1: '))
v2 = float(input(' medida 2: '))
v3 = float(input(' medida 3: '))
if v1 == v2 == v3:
print('Triangulo equilatero: com todos os lados iguais')
elif (v1 == v2 or v3) and (v2 == v1 or v3):
print('tringulo isoceles dois lados iguais')
elif (v1 != v2 or v3) and (v2 != v1 or v3) and (v3 != v1 or v2):
print('escaleno')
else:
print('nao e um triangulo') |
# Copyright (c) 2018 PaddlePaddle 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class CaseTwoItem(object):
def __init__(self, ts, nginx_pods, running_trainers, collector):
self.ts = ts
self.nginx_pods = nginx_pods
self.running_trainers = running_trainers
self.cpu_utils = collector.cpu_utils()
self.gpu_utils = collector.gpu_utils()
#def values(self):
# return [str(self.times), str(self.nginx_pods), str(self.running_trainers), str(self.cpu_utils)]
class CaseTwoReport(object):
def __init__(self):
self.items = []
self.avg_cpu_utils = 0.0
self.cnt = 0
def append_item(self, item):
# append new item only if Nginx pods changed
if not self.items or \
self.items[-1].nginx_pods != item.nginx_pods or \
self.items[-1].running_trainers != item.running_trainers:
self.items.append(item)
self.avg_cpu_utils += float(item.cpu_utils)
self.cnt += 1
def title(self):
return ['TIME', 'NGINX PODS', 'RUNNING TRAINERS', 'CLUSTER CPU UTILS']
def to_csv(self, fn):
self.avg_cpu_utils /= self.cnt
with open(fn, 'w') as f:
f.write('|'.join(self.title()) + '\n')
for item in self.items:
f.write('|'.join([
str(item.ts), str(item.nginx_pods), str(
item.running_trainers), item.cpu_utils
]) + '\n')
| class Casetwoitem(object):
def __init__(self, ts, nginx_pods, running_trainers, collector):
self.ts = ts
self.nginx_pods = nginx_pods
self.running_trainers = running_trainers
self.cpu_utils = collector.cpu_utils()
self.gpu_utils = collector.gpu_utils()
class Casetworeport(object):
def __init__(self):
self.items = []
self.avg_cpu_utils = 0.0
self.cnt = 0
def append_item(self, item):
if not self.items or self.items[-1].nginx_pods != item.nginx_pods or self.items[-1].running_trainers != item.running_trainers:
self.items.append(item)
self.avg_cpu_utils += float(item.cpu_utils)
self.cnt += 1
def title(self):
return ['TIME', 'NGINX PODS', 'RUNNING TRAINERS', 'CLUSTER CPU UTILS']
def to_csv(self, fn):
self.avg_cpu_utils /= self.cnt
with open(fn, 'w') as f:
f.write('|'.join(self.title()) + '\n')
for item in self.items:
f.write('|'.join([str(item.ts), str(item.nginx_pods), str(item.running_trainers), item.cpu_utils]) + '\n') |
def isDigit(symbol):
'''
Determine if the given character is a digit or not.
'''
return symbol.isdigit()
| def is_digit(symbol):
"""
Determine if the given character is a digit or not.
"""
return symbol.isdigit() |
a = list(" " * 9)
step = 0
def printgame():
print('-' * 9)
for i in range(3):
print("| {} {} {} |".format(a[0 + 3 * i], a[1 + 3 * i], a[2 + 3 * i]))
print('-' * 9)
while " " in a:
playx, playy = input("Enter the coordinates:").split()
if (int(playx) or int(playy)) not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print("You should enter numbers!")
elif (int(playx) or int(playy)) not in [1, 2, 3]:
print("Coordinates should be from 1 to 3!")
elif a[(int(playx) - 1) + abs(int(playy) - 3) * 3] != " ":
print("This cell is occupied! Choose another one!")
else:
if step == 0:
a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "X"
step = 1
elif step == 1:
a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "O"
step = 0
printgame()
rule = [a[:3], a[3:6], a[6:], a[0:9:3], a[1:9:3], a[2:9:3], a[0:9:4], a[2:7:2]]
if ['X', 'X', 'X'] in rule:
print("X wins")
elif ['O', 'O', 'O'] in rule:
print("O wins")
elif a.count(" ") == 0:
print("Draw") | a = list(' ' * 9)
step = 0
def printgame():
print('-' * 9)
for i in range(3):
print('| {} {} {} |'.format(a[0 + 3 * i], a[1 + 3 * i], a[2 + 3 * i]))
print('-' * 9)
while ' ' in a:
(playx, playy) = input('Enter the coordinates:').split()
if (int(playx) or int(playy)) not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print('You should enter numbers!')
elif (int(playx) or int(playy)) not in [1, 2, 3]:
print('Coordinates should be from 1 to 3!')
elif a[int(playx) - 1 + abs(int(playy) - 3) * 3] != ' ':
print('This cell is occupied! Choose another one!')
else:
if step == 0:
a[int(playx) - 1 + abs(int(playy) - 3) * 3] = 'X'
step = 1
elif step == 1:
a[int(playx) - 1 + abs(int(playy) - 3) * 3] = 'O'
step = 0
printgame()
rule = [a[:3], a[3:6], a[6:], a[0:9:3], a[1:9:3], a[2:9:3], a[0:9:4], a[2:7:2]]
if ['X', 'X', 'X'] in rule:
print('X wins')
elif ['O', 'O', 'O'] in rule:
print('O wins')
elif a.count(' ') == 0:
print('Draw') |
#!/usr/bin/python3
def new_in_list(my_list, idx, element):
list1 = my_list.copy()
leng = len(my_list)
if idx < 0:
return list1
if idx >= leng:
return list1
list1[idx] = element
return list1
| def new_in_list(my_list, idx, element):
list1 = my_list.copy()
leng = len(my_list)
if idx < 0:
return list1
if idx >= leng:
return list1
list1[idx] = element
return list1 |
'''
Leap year is an year with 366 days. Leap Year should be divisible by 4.
Also it should be divisible by 400 and not divisible by 100.
'''
def checkLeapYear(year):
if year % 400 == 0:
return 1
if year % 100 == 0:
return 0
if year % 4 == 0:
return 1
return 0
year1 = int(input("Enter the first year:\n"))
year2 = int(input("Enter the second year:\n"))
print("The leap years between %d and %d are:" % (year1, year2))
for year in range(year1, year2):
if checkLeapYear(year) == 1:
print(year)
'''
Input:
2000
2050
Output:
The leap years between 2000 and 2050 are:
2000
2004
2008
2012
2016
2020
2024
2028
2032
2036
2040
2044
2048
'''
| """
Leap year is an year with 366 days. Leap Year should be divisible by 4.
Also it should be divisible by 400 and not divisible by 100.
"""
def check_leap_year(year):
if year % 400 == 0:
return 1
if year % 100 == 0:
return 0
if year % 4 == 0:
return 1
return 0
year1 = int(input('Enter the first year:\n'))
year2 = int(input('Enter the second year:\n'))
print('The leap years between %d and %d are:' % (year1, year2))
for year in range(year1, year2):
if check_leap_year(year) == 1:
print(year)
'\nInput:\n2000\n2050\n\nOutput:\nThe leap years between 2000 and 2050 are:\n2000\n2004\n2008\n2012\n2016\n2020\n2024\n2028\n2032\n2036\n2040\n2044\n2048\n' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def Eq(field, value):
return {'_field': field, '_value': value}
def Gt(field, value):
return {'_gt': {field: value}}
def Gte(field, value):
return {'_gte': {field: value}}
def Lt(field, value):
return {'_lt': {field: value}}
def Lte(field, value):
return {'_lte': {field: value}}
def And(*criteria):
return {'_and': criteria}
def Or(*criteria):
return {'_or': criteria}
def Not(criterion):
return {'_not': criterion}
def In(field, values):
return {'_in': {'_field': field, '_values': values}}
def Contains(field):
return {'_contains': field}
def Id(id):
return {'_id': id}
def Between(field, from_value, to_value):
return {'_between': {'_field': field, '_from': from_value, '_to': to_value}}
def ParentId(tpe, id):
return {'_parent': {'_type': tpe, '_id': id}}
def Parent(tpe, criterion):
return {'_parent': {'_type': tpe, '_query': criterion}}
def Child(tpe, criterion):
return {'_child': {'_type': tpe, '_query': criterion}}
def Type(tpe):
return {'_type': tpe}
def String(query_string):
return {'_string': query_string}
| def eq(field, value):
return {'_field': field, '_value': value}
def gt(field, value):
return {'_gt': {field: value}}
def gte(field, value):
return {'_gte': {field: value}}
def lt(field, value):
return {'_lt': {field: value}}
def lte(field, value):
return {'_lte': {field: value}}
def and(*criteria):
return {'_and': criteria}
def or(*criteria):
return {'_or': criteria}
def not(criterion):
return {'_not': criterion}
def in(field, values):
return {'_in': {'_field': field, '_values': values}}
def contains(field):
return {'_contains': field}
def id(id):
return {'_id': id}
def between(field, from_value, to_value):
return {'_between': {'_field': field, '_from': from_value, '_to': to_value}}
def parent_id(tpe, id):
return {'_parent': {'_type': tpe, '_id': id}}
def parent(tpe, criterion):
return {'_parent': {'_type': tpe, '_query': criterion}}
def child(tpe, criterion):
return {'_child': {'_type': tpe, '_query': criterion}}
def type(tpe):
return {'_type': tpe}
def string(query_string):
return {'_string': query_string} |
class LinkNodeIter:
def __init__(self, link):
self._link = link
def __iter__(self):
return self
def __next__(self):
next_value = self._link
if next_value is not None:
self._link = next_value.next_link
else:
raise StopIteration
return next_value
| class Linknodeiter:
def __init__(self, link):
self._link = link
def __iter__(self):
return self
def __next__(self):
next_value = self._link
if next_value is not None:
self._link = next_value.next_link
else:
raise StopIteration
return next_value |
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
count = 0
for index in range(len(points)-1):
count += max(abs(points[index][0]-points[index+1][0]), abs(points[index][1]-points[index+1][1]))
return count
| class Solution:
def min_time_to_visit_all_points(self, points: List[List[int]]) -> int:
count = 0
for index in range(len(points) - 1):
count += max(abs(points[index][0] - points[index + 1][0]), abs(points[index][1] - points[index + 1][1]))
return count |
async def db_get(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
async for row in cursor:
yield dict(row)
async def db_get_one(db, column, query, **parameters):
async for row in db_get(db, query, **parameters):
return row.get(column, None)
else:
return None
async def db_get_first(db, query, **parameters):
async for row in db_get(db, query, **parameters):
return row
else:
return None
async def insert_one(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
return cursor.lastrowid
| async def db_get(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
async for row in cursor:
yield dict(row)
async def db_get_one(db, column, query, **parameters):
async for row in db_get(db, query, **parameters):
return row.get(column, None)
else:
return None
async def db_get_first(db, query, **parameters):
async for row in db_get(db, query, **parameters):
return row
else:
return None
async def insert_one(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
return cursor.lastrowid |
red = "#c91111"
orange = "#e09401"
pale_blue = "#13aed5"
dark_blue = "#1321d8"
purple = "#642197"
| red = '#c91111'
orange = '#e09401'
pale_blue = '#13aed5'
dark_blue = '#1321d8'
purple = '#642197' |
# -*- coding: UTF-8 -*-
logger.info("Loading 8 objects to table lists_list...")
# fields: id, ref, designation, list_type, remarks
loader.save(create_lists_list(1,None,['Announcements', 'Ank\xfcndigungen', 'Announcements'],1,u''))
loader.save(create_lists_list(2,None,['Weekly newsletter', 'Weekly newsletter', 'Weekly newsletter'],1,u''))
loader.save(create_lists_list(3,None,['General discussion', 'General discussion', 'General discussion'],2,u''))
loader.save(create_lists_list(4,None,['Beginners forum', 'Beginners forum', 'Beginners forum'],2,u''))
loader.save(create_lists_list(5,None,['Developers forum', 'Developers forum', 'Developers forum'],2,u''))
loader.save(create_lists_list(6,None,['PyCon 2014', 'PyCon 2014', 'PyCon 2014'],3,u''))
loader.save(create_lists_list(7,None,['Free Software Day 2014', 'Free Software Day 2014', 'Free Software Day 2014'],3,u''))
loader.save(create_lists_list(8,None,['Schools', 'Schulen', 'Schools'],3,u''))
loader.flush_deferred_objects()
| logger.info('Loading 8 objects to table lists_list...')
loader.save(create_lists_list(1, None, ['Announcements', 'Ankündigungen', 'Announcements'], 1, u''))
loader.save(create_lists_list(2, None, ['Weekly newsletter', 'Weekly newsletter', 'Weekly newsletter'], 1, u''))
loader.save(create_lists_list(3, None, ['General discussion', 'General discussion', 'General discussion'], 2, u''))
loader.save(create_lists_list(4, None, ['Beginners forum', 'Beginners forum', 'Beginners forum'], 2, u''))
loader.save(create_lists_list(5, None, ['Developers forum', 'Developers forum', 'Developers forum'], 2, u''))
loader.save(create_lists_list(6, None, ['PyCon 2014', 'PyCon 2014', 'PyCon 2014'], 3, u''))
loader.save(create_lists_list(7, None, ['Free Software Day 2014', 'Free Software Day 2014', 'Free Software Day 2014'], 3, u''))
loader.save(create_lists_list(8, None, ['Schools', 'Schulen', 'Schools'], 3, u''))
loader.flush_deferred_objects() |
if __name__ == '__main__':
N = int(input())
elements = []
posicion = ""
dato = ""
for i in range(N):
commands = input()
longitud = len(commands)
if commands[0:6] == "insert" :
if(commands[8] == " "):
posicion = commands[7]
dato = commands[9:longitud+1]
elif commands[9] == " ":
posicion = commands[7:8]
dato = commands[10:longitud+1]
elements.insert(int(posicion),int(dato))
elif commands == "print":
print(elements)
elif commands[0:6] == "remove":
elements.remove(int(commands[7:longitud+1]))
elif commands[0:6] == "append":
elements.append(int(commands[7:longitud+1]))
elif commands == "sort":
elements.sort()
elif commands == "pop":
elements.pop()
else:
elements.reverse()
| if __name__ == '__main__':
n = int(input())
elements = []
posicion = ''
dato = ''
for i in range(N):
commands = input()
longitud = len(commands)
if commands[0:6] == 'insert':
if commands[8] == ' ':
posicion = commands[7]
dato = commands[9:longitud + 1]
elif commands[9] == ' ':
posicion = commands[7:8]
dato = commands[10:longitud + 1]
elements.insert(int(posicion), int(dato))
elif commands == 'print':
print(elements)
elif commands[0:6] == 'remove':
elements.remove(int(commands[7:longitud + 1]))
elif commands[0:6] == 'append':
elements.append(int(commands[7:longitud + 1]))
elif commands == 'sort':
elements.sort()
elif commands == 'pop':
elements.pop()
else:
elements.reverse() |
IMG_HEIGHT = 480
IMG_WIDTH = 640
CLASS_NUM = 3
ANCHORS_GROUP = {
32:[[730,145],[288,190],[216,540]],
16:[[365,73],[144,95],[108,270]],
8:[[180,37],[72,44],[54,135]]
}
ANCHORS_GROUP_AREA = {
32: [x * y for x, y in ANCHORS_GROUP[32]],
16: [x * y for x, y in ANCHORS_GROUP[16]],
8: [x * y for x, y in ANCHORS_GROUP[8]],
}
color=['#ff0000','#0000ff','#00ff00']
| img_height = 480
img_width = 640
class_num = 3
anchors_group = {32: [[730, 145], [288, 190], [216, 540]], 16: [[365, 73], [144, 95], [108, 270]], 8: [[180, 37], [72, 44], [54, 135]]}
anchors_group_area = {32: [x * y for (x, y) in ANCHORS_GROUP[32]], 16: [x * y for (x, y) in ANCHORS_GROUP[16]], 8: [x * y for (x, y) in ANCHORS_GROUP[8]]}
color = ['#ff0000', '#0000ff', '#00ff00'] |
def devedor(*args):
try:
telaDevedores = args[0]
telaErro = args[1]
cursor = args[2]
banco10 = args[3]
data = args[4]
id = telaDevedores.codigo.text()
sql = ("select id from gerenciarPedido where id = %s and dataa = %s")
values = (id, data)
cursor.execute(sql, values)
dados2 = cursor.fetchall()
id2 = dados2[0][0]
sql = ("select dataa, hora, nome, telefone, valorTotal from gerenciarPedido where id = %s and dataa = %s")
values = (id2, data)
cursor.execute(sql, values)
inf_cliente = cursor.fetchall()
motivo = telaDevedores.motivo_dever.text()
sql = "insert into devedores(id, dataa, hora, nome, telefone, valor, motivo) values (%s, %s, %s, %s, %s, %s, %s)"
insert = (str(id2), str(inf_cliente[0][0]), str(inf_cliente[0][1]),
str(inf_cliente[0][2]), str(inf_cliente[0][3]),
str(inf_cliente[0][4]), str(motivo))
cursor.execute(sql, insert)
banco10.commit()
telaDevedores.hide()
except:
telaErro.show()
telaErro.label.setText('Codigo invalido, tente novamente!') | def devedor(*args):
try:
tela_devedores = args[0]
tela_erro = args[1]
cursor = args[2]
banco10 = args[3]
data = args[4]
id = telaDevedores.codigo.text()
sql = 'select id from gerenciarPedido where id = %s and dataa = %s'
values = (id, data)
cursor.execute(sql, values)
dados2 = cursor.fetchall()
id2 = dados2[0][0]
sql = 'select dataa, hora, nome, telefone, valorTotal from gerenciarPedido where id = %s and dataa = %s'
values = (id2, data)
cursor.execute(sql, values)
inf_cliente = cursor.fetchall()
motivo = telaDevedores.motivo_dever.text()
sql = 'insert into devedores(id, dataa, hora, nome, telefone, valor, motivo) values (%s, %s, %s, %s, %s, %s, %s)'
insert = (str(id2), str(inf_cliente[0][0]), str(inf_cliente[0][1]), str(inf_cliente[0][2]), str(inf_cliente[0][3]), str(inf_cliente[0][4]), str(motivo))
cursor.execute(sql, insert)
banco10.commit()
telaDevedores.hide()
except:
telaErro.show()
telaErro.label.setText('Codigo invalido, tente novamente!') |
name1_0_0_0_1_1_0 = None
name1_0_0_0_1_1_1 = None
name1_0_0_0_1_1_2 = None
name1_0_0_0_1_1_3 = None
name1_0_0_0_1_1_4 = None | name1_0_0_0_1_1_0 = None
name1_0_0_0_1_1_1 = None
name1_0_0_0_1_1_2 = None
name1_0_0_0_1_1_3 = None
name1_0_0_0_1_1_4 = None |
LOCATIONemojis = {
"fastbackwards": "<:fast_forward_left:870781340692402226>",
"backwards": "<:left_arrow:870781340990197860>",
"close": "<:Cross:863313854069997578>",
"forwards": "<:right_arrow:870781340314898473>",
"fastforwards": "<:fast_forward_right:870781340839202837>",
}
COGemojis = {
"JesterInfo": 863075610048987166,
"Feedback": 863075610851147777,
"Music": 863075611320647719,
"Snipe": 863075611269791794,
"Fun": 863075609781075968,
"Mod": 863075610784301068,
"Games": 863075611329167380,
"Utils": 863075611161788478,
"Images": 863075611277656124,
"Economy": 863075610913800233,
"Misc": 863075610979729409,
"Levels": 863075611182628895,
"Config": 863075611169259550,
"Love": 863075611374125056,
"JesterJokes": 873327129016811528,
"Cryptocurrency": 872473402764570624,
"Countries": 872473402638762025,
"ChatBot": 872473402693259324,
"DiscordTogether": 872473402840076288,
"UrbanDictionary": 924074967673503796,
"Random": 924074967405051965,
"Trivia": 924152372001910834,
"Crime": 924411072729985046,
"Docs": 925222917946605629,
}
CLOSE = "<:Cross:863313854069997578>"
HOME = "<:Arrow:863313854040506379>"
LINK = "<:links:870781340700782612>"
CATEGORIES = "<:menus:870781340746932225>"
TRASHCAN = "<:trashbin:873564727006089287>"
j = "<:J_:863313855286607932>"
e = "<:E_:863313854150606848>"
s = "<:S:863313855061164062>"
t = "<:T:863313855399329812>"
r = "<:R_:863313855119360022>"
| locatio_nemojis = {'fastbackwards': '<:fast_forward_left:870781340692402226>', 'backwards': '<:left_arrow:870781340990197860>', 'close': '<:Cross:863313854069997578>', 'forwards': '<:right_arrow:870781340314898473>', 'fastforwards': '<:fast_forward_right:870781340839202837>'}
co_gemojis = {'JesterInfo': 863075610048987166, 'Feedback': 863075610851147777, 'Music': 863075611320647719, 'Snipe': 863075611269791794, 'Fun': 863075609781075968, 'Mod': 863075610784301068, 'Games': 863075611329167380, 'Utils': 863075611161788478, 'Images': 863075611277656124, 'Economy': 863075610913800233, 'Misc': 863075610979729409, 'Levels': 863075611182628895, 'Config': 863075611169259550, 'Love': 863075611374125056, 'JesterJokes': 873327129016811528, 'Cryptocurrency': 872473402764570624, 'Countries': 872473402638762025, 'ChatBot': 872473402693259324, 'DiscordTogether': 872473402840076288, 'UrbanDictionary': 924074967673503796, 'Random': 924074967405051965, 'Trivia': 924152372001910834, 'Crime': 924411072729985046, 'Docs': 925222917946605629}
close = '<:Cross:863313854069997578>'
home = '<:Arrow:863313854040506379>'
link = '<:links:870781340700782612>'
categories = '<:menus:870781340746932225>'
trashcan = '<:trashbin:873564727006089287>'
j = '<:J_:863313855286607932>'
e = '<:E_:863313854150606848>'
s = '<:S:863313855061164062>'
t = '<:T:863313855399329812>'
r = '<:R_:863313855119360022>' |
#!/usr/local/bin/python
# Think Like a Programmer Chapter 2: Pure Puzzles exercises
def main():
test_pound_shapes = False
test_base_conversion = True
if test_pound_shapes:
poundV()
print()
poundDiamond()
if test_base_conversion:
tests = [
# [1, 1, 2, 1], # ValueError test
# ['G', 17, 10, 17], # ValueError test
# [15, 10, 10, '15'],
# ['101', 2, 10, '5'],
# ['1000', 2, 10, '8'],
# ['A', 16, 10, '10'],
# ['10', 16, 10, '16'],
[11, 10, 16, 'B'],
['1100', 2, 16, 'C']
]
for t in tests:
print("Testing baseConversion({}, {}, {})"
.format(t[0], t[1], t[2]))
try:
res = baseConversion(t[0], t[1], t[2])
if t[3] == res:
print("PASSED: baseConversion({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print("FAILED: baseConversion({}, {}, {}) returned {}, "
"answer: {}".format(t[0], t[1], t[2], res, t[3]))
except ValueError:
print("PASSED: ValueError test")
def poundV():
'''
Using only single output statements of a space, pound, or new line, create:
########
######
####
##
'''
n = 4
space = ' '
pound = '#'
for i in range(n, 0, -1):
print((space * (n - i)) + (pound * i * 2) + (space * (n - i)))
def poundDiamond():
'''
Using only single output statements of a space, pound, or new line, create:
##
####
######
########
########
######
####
##
'''
n = 4
space = ' '
pound = '#'
rangeItem = list(range(1, n + 1))
for i in rangeItem + rangeItem[::-1]:
print((space * (n - i)) + (pound * i * 2) + (space * (n - i)))
def baseConversion(num, s_base, t_base):
'''
Takes a number num as str or int. Converts it from the source base (s_base,
an int) into the target base (t_base, an int) and returns new number
as a string.
Source and target bases must be between 2 and 16.
Input: num (str), s_base (int), t_base (int)
Output: str
'''
num = str(num)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']
# Input checking
if type(s_base) is not int or type(t_base) is not int:
raise ValueError
if (s_base < 2 or s_base > 16 or t_base < 2 or t_base > 16):
raise ValueError
# Convert number to base 10
if s_base == 10:
# print("Num in base 10 already: {}".format(num))
base_10 = int(num)
else:
# print("Converting {} to base 10 from base {}".format(num, s_base))
base_10 = sum([digits.index(ch) * (s_base ** i) for i, ch in
enumerate(list(num)[::-1])])
# print("Num in base 10 is: {}".format(base_10))
# Convert base-10 number to target base
converted = ''
if t_base == 10:
converted = str(base_10)
else:
while base_10 > 0:
r = base_10 % t_base
converted = digits[r] + converted
# print("Num: {}, num/{}: {}, digit: {}"
# .format(base_10, t_base, r, digits[r]))
base_10 //= t_base
return converted
if __name__ == '__main__':
main()
| def main():
test_pound_shapes = False
test_base_conversion = True
if test_pound_shapes:
pound_v()
print()
pound_diamond()
if test_base_conversion:
tests = [[11, 10, 16, 'B'], ['1100', 2, 16, 'C']]
for t in tests:
print('Testing baseConversion({}, {}, {})'.format(t[0], t[1], t[2]))
try:
res = base_conversion(t[0], t[1], t[2])
if t[3] == res:
print('PASSED: baseConversion({}, {}, {}) returned {}'.format(t[0], t[1], t[2], res))
else:
print('FAILED: baseConversion({}, {}, {}) returned {}, answer: {}'.format(t[0], t[1], t[2], res, t[3]))
except ValueError:
print('PASSED: ValueError test')
def pound_v():
"""
Using only single output statements of a space, pound, or new line, create:
########
######
####
##
"""
n = 4
space = ' '
pound = '#'
for i in range(n, 0, -1):
print(space * (n - i) + pound * i * 2 + space * (n - i))
def pound_diamond():
"""
Using only single output statements of a space, pound, or new line, create:
##
####
######
########
########
######
####
##
"""
n = 4
space = ' '
pound = '#'
range_item = list(range(1, n + 1))
for i in rangeItem + rangeItem[::-1]:
print(space * (n - i) + pound * i * 2 + space * (n - i))
def base_conversion(num, s_base, t_base):
"""
Takes a number num as str or int. Converts it from the source base (s_base,
an int) into the target base (t_base, an int) and returns new number
as a string.
Source and target bases must be between 2 and 16.
Input: num (str), s_base (int), t_base (int)
Output: str
"""
num = str(num)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
if type(s_base) is not int or type(t_base) is not int:
raise ValueError
if s_base < 2 or s_base > 16 or t_base < 2 or (t_base > 16):
raise ValueError
if s_base == 10:
base_10 = int(num)
else:
base_10 = sum([digits.index(ch) * s_base ** i for (i, ch) in enumerate(list(num)[::-1])])
converted = ''
if t_base == 10:
converted = str(base_10)
else:
while base_10 > 0:
r = base_10 % t_base
converted = digits[r] + converted
base_10 //= t_base
return converted
if __name__ == '__main__':
main() |
class Table(object):
def __init__(self):
self.rows = []
def to_ascii_table(self):
if not self.rows:
return ""
lines = []
def print_row(row):
line = ""
for column, l in zip(row, lens):
if column is None:
s = ""
else:
s = str(column)
line += "| " + s + " " * (l - len(s)) + " "
line += "|\n"
lines.append(line)
lens = []
for i, column in enumerate(self.rows[0]):
lens.append(max(len(str(r[i]))
for r in self.rows if r[i] is not None))
width = sum(lens) + 3 * len(self.rows[0]) + 1
separator = ("-" * width) + "\n"
lines.append(separator)
print_row(self.rows[0])
lines.append(separator)
if len(self.rows) == 1:
return
for row in self.rows[1:]:
print_row(row)
lines.append(separator)
return "".join(lines)
def transpose(self):
if not self.rows:
return
table = Table()
for i in xrange(len(self.rows[0])):
table.add_row([r[i] for r in self.rows])
return table
def add_row(self, data):
self.rows.append(data)
def add_rows(self, rows):
self.rows.extend(rows)
def add_dictionaries(self, items, columns):
self.add_row(columns)
for item in items:
row = [item.get(column) for column in columns]
self.add_row(row)
| class Table(object):
def __init__(self):
self.rows = []
def to_ascii_table(self):
if not self.rows:
return ''
lines = []
def print_row(row):
line = ''
for (column, l) in zip(row, lens):
if column is None:
s = ''
else:
s = str(column)
line += '| ' + s + ' ' * (l - len(s)) + ' '
line += '|\n'
lines.append(line)
lens = []
for (i, column) in enumerate(self.rows[0]):
lens.append(max((len(str(r[i])) for r in self.rows if r[i] is not None)))
width = sum(lens) + 3 * len(self.rows[0]) + 1
separator = '-' * width + '\n'
lines.append(separator)
print_row(self.rows[0])
lines.append(separator)
if len(self.rows) == 1:
return
for row in self.rows[1:]:
print_row(row)
lines.append(separator)
return ''.join(lines)
def transpose(self):
if not self.rows:
return
table = table()
for i in xrange(len(self.rows[0])):
table.add_row([r[i] for r in self.rows])
return table
def add_row(self, data):
self.rows.append(data)
def add_rows(self, rows):
self.rows.extend(rows)
def add_dictionaries(self, items, columns):
self.add_row(columns)
for item in items:
row = [item.get(column) for column in columns]
self.add_row(row) |
class DeviceSelectCredential:
def __init__(self, number):
pass
def __call__(self, status):
pass
| class Deviceselectcredential:
def __init__(self, number):
pass
def __call__(self, status):
pass |
expected_output={
"rlist_id": {
"0xf0001ae8": {
"flags": "0x0",
"packets": 38793,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001ae9": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001aea": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001aeb": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
}
}
}
| expected_output = {'rlist_id': {'0xf0001ae8': {'flags': '0x0', 'packets': 38793, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001ae9': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001aea': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001aeb': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}}} |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
v = self.gf(l1) + self.gf(l2)
ll = ListNode(str(v)[::-1][0])
t = ll
for i in str(v)[::-1][1:]:
t.next = ListNode(i)
t = t.next
return ll
def gf(self, l: ListNode):
s = 0
c = 1
while l.next:
s += l.val * c
c *= 10
l = l.next
s += l.val * c
return s
def ii(ll):
l = ListNode(ll[0])
t = l
for i in ll[1:]:
print(i)
t.next = ListNode(i)
t = t.next
return l
def p(lll):
print("=====")
while lll.next:
print(lll.val)
lll = lll.next
print(lll.val)
if __name__ == "__main__":
ll1 = [2, 4, 3]
ll2 = [5, 6, 4]
p(ii(ll1))
# ss = Solution()
| class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
v = self.gf(l1) + self.gf(l2)
ll = list_node(str(v)[::-1][0])
t = ll
for i in str(v)[::-1][1:]:
t.next = list_node(i)
t = t.next
return ll
def gf(self, l: ListNode):
s = 0
c = 1
while l.next:
s += l.val * c
c *= 10
l = l.next
s += l.val * c
return s
def ii(ll):
l = list_node(ll[0])
t = l
for i in ll[1:]:
print(i)
t.next = list_node(i)
t = t.next
return l
def p(lll):
print('=====')
while lll.next:
print(lll.val)
lll = lll.next
print(lll.val)
if __name__ == '__main__':
ll1 = [2, 4, 3]
ll2 = [5, 6, 4]
p(ii(ll1)) |
file = open('rosalind_cons.txt', 'r')
target = file.read()
d_list = []
class DNAcon:
def __init__(self):
self.A = 0
self.C = 0
self.G = 0
self.T = 0
def add_A(self, value):
self.A += value
def add_C(self, value):
self.C += value
def add_G(self, value):
self.G += value
def add_T(self, value):
self.T += value
def inserter(target_str, target_list):
raw = target_str
while not raw.isspace() or len(raw) == 0:
if raw[0] == '>':
raw = raw[raw.index('\n') + 1:]
try:
loc = raw[0: raw.index('>')]
loc = loc.replace('\n', '')
target_list.append(loc)
except:
loc = raw[0:]
loc = loc.replace('\n', '')
target_list.append(loc)
return
raw = raw[raw.index('>'):]
else:
return
inserter(target, d_list)
maxlen = 0
for con in d_list:
see = len(con)
if see >= maxlen:
maxlen = see
matrix = []
for i in range(maxlen):
target = DNAcon()
for con in d_list:
try:
val = con[i]
if val == 'A':
target.add_A(1)
elif val == 'C':
target.add_C(1)
elif val == 'G':
target.add_G(1)
elif val == 'T':
target.add_T(1)
except:
continue
matrix.append(target)
consensus = ''
for dna in matrix:
maximum = 0
val = ''
if dna.A >= maximum:
maximum = dna.A
val = 'A'
if dna.C >= maximum:
maximum = dna.C
val = 'C'
if dna.G >= maximum:
maximum = dna.G
val = 'G'
if dna.T >= maximum:
maximum = dna.T
val = 'T'
consensus += val
print(consensus)
for i in range(4):
if i == 0:
print('A:', end=' ')
for dna in matrix:
print(dna.A, end=' ')
elif i == 1:
print('C:', end=' ')
for dna in matrix:
print(dna.C, end=' ')
elif i == 2:
print('G:', end=' ')
for dna in matrix:
print(dna.G, end=' ')
elif i == 3:
print('T:', end=' ')
for dna in matrix:
print(dna.T, end=' ')
print()
| file = open('rosalind_cons.txt', 'r')
target = file.read()
d_list = []
class Dnacon:
def __init__(self):
self.A = 0
self.C = 0
self.G = 0
self.T = 0
def add_a(self, value):
self.A += value
def add_c(self, value):
self.C += value
def add_g(self, value):
self.G += value
def add_t(self, value):
self.T += value
def inserter(target_str, target_list):
raw = target_str
while not raw.isspace() or len(raw) == 0:
if raw[0] == '>':
raw = raw[raw.index('\n') + 1:]
try:
loc = raw[0:raw.index('>')]
loc = loc.replace('\n', '')
target_list.append(loc)
except:
loc = raw[0:]
loc = loc.replace('\n', '')
target_list.append(loc)
return
raw = raw[raw.index('>'):]
else:
return
inserter(target, d_list)
maxlen = 0
for con in d_list:
see = len(con)
if see >= maxlen:
maxlen = see
matrix = []
for i in range(maxlen):
target = dn_acon()
for con in d_list:
try:
val = con[i]
if val == 'A':
target.add_A(1)
elif val == 'C':
target.add_C(1)
elif val == 'G':
target.add_G(1)
elif val == 'T':
target.add_T(1)
except:
continue
matrix.append(target)
consensus = ''
for dna in matrix:
maximum = 0
val = ''
if dna.A >= maximum:
maximum = dna.A
val = 'A'
if dna.C >= maximum:
maximum = dna.C
val = 'C'
if dna.G >= maximum:
maximum = dna.G
val = 'G'
if dna.T >= maximum:
maximum = dna.T
val = 'T'
consensus += val
print(consensus)
for i in range(4):
if i == 0:
print('A:', end=' ')
for dna in matrix:
print(dna.A, end=' ')
elif i == 1:
print('C:', end=' ')
for dna in matrix:
print(dna.C, end=' ')
elif i == 2:
print('G:', end=' ')
for dna in matrix:
print(dna.G, end=' ')
elif i == 3:
print('T:', end=' ')
for dna in matrix:
print(dna.T, end=' ')
print() |
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
x3, y3 = list(map(int, input().split()))
x4 = 0
y4 = 0
if x1 == x2:
x4 = x3
elif x2 == x3:
x4 = x1
else:
x4 = x2
if y1 == y2:
y4 = y3
elif y2 == y3:
y4 = y1
else:
y4 = y2
print("{0} {1}".format(x4, y4))
| (x1, y1) = list(map(int, input().split()))
(x2, y2) = list(map(int, input().split()))
(x3, y3) = list(map(int, input().split()))
x4 = 0
y4 = 0
if x1 == x2:
x4 = x3
elif x2 == x3:
x4 = x1
else:
x4 = x2
if y1 == y2:
y4 = y3
elif y2 == y3:
y4 = y1
else:
y4 = y2
print('{0} {1}'.format(x4, y4)) |
def non_repeating(data):
state = dict()
for i in data:
if i not in state:
state[i] = 1
else:
state[i] = state[i] + 1
for i in data:
if state[i] == 1:
return i
return None
if __name__ == "__main__":
print(non_repeating("aaabbcdde"))
print(non_repeating("aaabbeddc"))
print(non_repeating("aabb"))
| def non_repeating(data):
state = dict()
for i in data:
if i not in state:
state[i] = 1
else:
state[i] = state[i] + 1
for i in data:
if state[i] == 1:
return i
return None
if __name__ == '__main__':
print(non_repeating('aaabbcdde'))
print(non_repeating('aaabbeddc'))
print(non_repeating('aabb')) |
# 200090310
sm.warp(200000141, 0)
sm.dispose()
| sm.warp(200000141, 0)
sm.dispose() |
'''
1) Implement the Node class to create
a binary search tree. The constructor
should initialize values 'data', 'left',
and 'right'.
2) Implement the 'insert' method for the
Node class. Insert should accept an argument
'data', then create a new node at the appropriate
location in the tree.
3) Implement the 'contains' method for the Node
class. Contains should accept a 'data' argument
and return the Node in the tree with the same value.
'''
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(self, data):
if data == self.data:
raise NotImplemented
elif data < self.data and self.left is None:
self.left = Node(data)
elif data > self.data and self.right is None:
self.right = Node(data)
elif data < self.data:
self.left.insert(data)
elif data > self.data:
self.right.insert(data)
else:
raise Exception('Unexpected edge case')
def contains(self, data):
if data == self.data:
return self
elif data < self.data and self.left is not None:
return self.left.contains(data)
elif data > self.data and self.right is not None:
return self.right.contains(data)
return None
| """
1) Implement the Node class to create
a binary search tree. The constructor
should initialize values 'data', 'left',
and 'right'.
2) Implement the 'insert' method for the
Node class. Insert should accept an argument
'data', then create a new node at the appropriate
location in the tree.
3) Implement the 'contains' method for the Node
class. Contains should accept a 'data' argument
and return the Node in the tree with the same value.
"""
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(self, data):
if data == self.data:
raise NotImplemented
elif data < self.data and self.left is None:
self.left = node(data)
elif data > self.data and self.right is None:
self.right = node(data)
elif data < self.data:
self.left.insert(data)
elif data > self.data:
self.right.insert(data)
else:
raise exception('Unexpected edge case')
def contains(self, data):
if data == self.data:
return self
elif data < self.data and self.left is not None:
return self.left.contains(data)
elif data > self.data and self.right is not None:
return self.right.contains(data)
return None |
NO_SUCH_OPTION_ERROR_TEMPLATE = "Error: no such option: {}"
NO_SUCH_COMMAND_ERROR_TEMPLATE = "Error: No such command \"{}\""
MISSING_COMMAND_ERROR_TEMPLATE = "Error: Missing command."
| no_such_option_error_template = 'Error: no such option: {}'
no_such_command_error_template = 'Error: No such command "{}"'
missing_command_error_template = 'Error: Missing command.' |
property_value_alias_age_long_to_short = {
"Unassigned": "NA",
"V10_0": "10.0",
"V11_0": "11.0",
"V12_0": "12.0",
"V12_1": "12.1",
"V13_0": "13.0",
"V1_1": "1.1",
"V2_0": "2.0",
"V2_1": "2.1",
"V3_0": "3.0",
"V3_1": "3.1",
"V3_2": "3.2",
"V4_0": "4.0",
"V4_1": "4.1",
"V5_0": "5.0",
"V5_1": "5.1",
"V5_2": "5.2",
"V6_0": "6.0",
"V6_1": "6.1",
"V6_2": "6.2",
"V6_3": "6.3",
"V7_0": "7.0",
"V8_0": "8.0",
"V9_0": "9.0",
}
| property_value_alias_age_long_to_short = {'Unassigned': 'NA', 'V10_0': '10.0', 'V11_0': '11.0', 'V12_0': '12.0', 'V12_1': '12.1', 'V13_0': '13.0', 'V1_1': '1.1', 'V2_0': '2.0', 'V2_1': '2.1', 'V3_0': '3.0', 'V3_1': '3.1', 'V3_2': '3.2', 'V4_0': '4.0', 'V4_1': '4.1', 'V5_0': '5.0', 'V5_1': '5.1', 'V5_2': '5.2', 'V6_0': '6.0', 'V6_1': '6.1', 'V6_2': '6.2', 'V6_3': '6.3', 'V7_0': '7.0', 'V8_0': '8.0', 'V9_0': '9.0'} |
def fib(num):
output = [1,1]
before_previous_num = 1
previous_num = 1
for i in range(1,num+1):
new_num = before_previous_num + previous_num
output.append(new_num)
before_previous_num = previous_num
previous_num = new_num
nth = output[num-1]
return nth
'''
Powers of 2 for some reason :X
output = []
i = 0
last_num = 0
new_num = 1
while i < 10:
last_num = new_num
new_num = last_num+new_num
output.append(new_num)
i+=1
print(output)
'''
| def fib(num):
output = [1, 1]
before_previous_num = 1
previous_num = 1
for i in range(1, num + 1):
new_num = before_previous_num + previous_num
output.append(new_num)
before_previous_num = previous_num
previous_num = new_num
nth = output[num - 1]
return nth
'\nPowers of 2 for some reason :X\n\noutput = []\ni = 0\nlast_num = 0\nnew_num = 1\nwhile i < 10:\n last_num = new_num\n new_num = last_num+new_num\n output.append(new_num)\n i+=1\nprint(output)\n' |
class Score:
def __init__(self):
self.score = 0
def get_score_text(self):
score_text = f"Score: {self.score}"
return score_text
def add_score(self, points):
self.score += points
| class Score:
def __init__(self):
self.score = 0
def get_score_text(self):
score_text = f'Score: {self.score}'
return score_text
def add_score(self, points):
self.score += points |
data = (
'k', # 0x00
'kh', # 0x01
'g', # 0x02
'gh', # 0x03
'ng', # 0x04
'c', # 0x05
'ch', # 0x06
'j', # 0x07
'jh', # 0x08
'ny', # 0x09
'nny', # 0x0a
'tt', # 0x0b
'tth', # 0x0c
'dd', # 0x0d
'ddh', # 0x0e
'nn', # 0x0f
'tt', # 0x10
'th', # 0x11
'd', # 0x12
'dh', # 0x13
'n', # 0x14
'p', # 0x15
'ph', # 0x16
'b', # 0x17
'bh', # 0x18
'm', # 0x19
'y', # 0x1a
'r', # 0x1b
'l', # 0x1c
'w', # 0x1d
's', # 0x1e
'h', # 0x1f
'll', # 0x20
'a', # 0x21
'[?]', # 0x22
'i', # 0x23
'ii', # 0x24
'u', # 0x25
'uu', # 0x26
'e', # 0x27
'[?]', # 0x28
'o', # 0x29
'au', # 0x2a
'[?]', # 0x2b
'aa', # 0x2c
'i', # 0x2d
'ii', # 0x2e
'u', # 0x2f
'uu', # 0x30
'e', # 0x31
'ai', # 0x32
'[?]', # 0x33
'[?]', # 0x34
'[?]', # 0x35
'N', # 0x36
'\'', # 0x37
':', # 0x38
'', # 0x39
'[?]', # 0x3a
'[?]', # 0x3b
'[?]', # 0x3c
'[?]', # 0x3d
'[?]', # 0x3e
'[?]', # 0x3f
'0', # 0x40
'1', # 0x41
'2', # 0x42
'3', # 0x43
'4', # 0x44
'5', # 0x45
'6', # 0x46
'7', # 0x47
'8', # 0x48
'9', # 0x49
' / ', # 0x4a
' // ', # 0x4b
'n*', # 0x4c
'r*', # 0x4d
'l*', # 0x4e
'e*', # 0x4f
'sh', # 0x50
'ss', # 0x51
'R', # 0x52
'RR', # 0x53
'L', # 0x54
'LL', # 0x55
'R', # 0x56
'RR', # 0x57
'L', # 0x58
'LL', # 0x59
'[?]', # 0x5a
'[?]', # 0x5b
'[?]', # 0x5c
'[?]', # 0x5d
'[?]', # 0x5e
'[?]', # 0x5f
'[?]', # 0x60
'[?]', # 0x61
'[?]', # 0x62
'[?]', # 0x63
'[?]', # 0x64
'[?]', # 0x65
'[?]', # 0x66
'[?]', # 0x67
'[?]', # 0x68
'[?]', # 0x69
'[?]', # 0x6a
'[?]', # 0x6b
'[?]', # 0x6c
'[?]', # 0x6d
'[?]', # 0x6e
'[?]', # 0x6f
'[?]', # 0x70
'[?]', # 0x71
'[?]', # 0x72
'[?]', # 0x73
'[?]', # 0x74
'[?]', # 0x75
'[?]', # 0x76
'[?]', # 0x77
'[?]', # 0x78
'[?]', # 0x79
'[?]', # 0x7a
'[?]', # 0x7b
'[?]', # 0x7c
'[?]', # 0x7d
'[?]', # 0x7e
'[?]', # 0x7f
'[?]', # 0x80
'[?]', # 0x81
'[?]', # 0x82
'[?]', # 0x83
'[?]', # 0x84
'[?]', # 0x85
'[?]', # 0x86
'[?]', # 0x87
'[?]', # 0x88
'[?]', # 0x89
'[?]', # 0x8a
'[?]', # 0x8b
'[?]', # 0x8c
'[?]', # 0x8d
'[?]', # 0x8e
'[?]', # 0x8f
'[?]', # 0x90
'[?]', # 0x91
'[?]', # 0x92
'[?]', # 0x93
'[?]', # 0x94
'[?]', # 0x95
'[?]', # 0x96
'[?]', # 0x97
'[?]', # 0x98
'[?]', # 0x99
'[?]', # 0x9a
'[?]', # 0x9b
'[?]', # 0x9c
'[?]', # 0x9d
'[?]', # 0x9e
'[?]', # 0x9f
'A', # 0xa0
'B', # 0xa1
'G', # 0xa2
'D', # 0xa3
'E', # 0xa4
'V', # 0xa5
'Z', # 0xa6
'T`', # 0xa7
'I', # 0xa8
'K', # 0xa9
'L', # 0xaa
'M', # 0xab
'N', # 0xac
'O', # 0xad
'P', # 0xae
'Zh', # 0xaf
'R', # 0xb0
'S', # 0xb1
'T', # 0xb2
'U', # 0xb3
'P`', # 0xb4
'K`', # 0xb5
'G\'', # 0xb6
'Q', # 0xb7
'Sh', # 0xb8
'Ch`', # 0xb9
'C`', # 0xba
'Z\'', # 0xbb
'C', # 0xbc
'Ch', # 0xbd
'X', # 0xbe
'J', # 0xbf
'H', # 0xc0
'E', # 0xc1
'Y', # 0xc2
'W', # 0xc3
'Xh', # 0xc4
'OE', # 0xc5
'[?]', # 0xc6
'[?]', # 0xc7
'[?]', # 0xc8
'[?]', # 0xc9
'[?]', # 0xca
'[?]', # 0xcb
'[?]', # 0xcc
'[?]', # 0xcd
'[?]', # 0xce
'[?]', # 0xcf
'a', # 0xd0
'b', # 0xd1
'g', # 0xd2
'd', # 0xd3
'e', # 0xd4
'v', # 0xd5
'z', # 0xd6
't`', # 0xd7
'i', # 0xd8
'k', # 0xd9
'l', # 0xda
'm', # 0xdb
'n', # 0xdc
'o', # 0xdd
'p', # 0xde
'zh', # 0xdf
'r', # 0xe0
's', # 0xe1
't', # 0xe2
'u', # 0xe3
'p`', # 0xe4
'k`', # 0xe5
'g\'', # 0xe6
'q', # 0xe7
'sh', # 0xe8
'ch`', # 0xe9
'c`', # 0xea
'z\'', # 0xeb
'c', # 0xec
'ch', # 0xed
'x', # 0xee
'j', # 0xef
'h', # 0xf0
'e', # 0xf1
'y', # 0xf2
'w', # 0xf3
'xh', # 0xf4
'oe', # 0xf5
'f', # 0xf6
'[?]', # 0xf7
'[?]', # 0xf8
'[?]', # 0xf9
'[?]', # 0xfa
' // ', # 0xfb
'[?]', # 0xfc
'[?]', # 0xfd
'[?]', # 0xfe
)
| data = ('k', 'kh', 'g', 'gh', 'ng', 'c', 'ch', 'j', 'jh', 'ny', 'nny', 'tt', 'tth', 'dd', 'ddh', 'nn', 'tt', 'th', 'd', 'dh', 'n', 'p', 'ph', 'b', 'bh', 'm', 'y', 'r', 'l', 'w', 's', 'h', 'll', 'a', '[?]', 'i', 'ii', 'u', 'uu', 'e', '[?]', 'o', 'au', '[?]', 'aa', 'i', 'ii', 'u', 'uu', 'e', 'ai', '[?]', '[?]', '[?]', 'N', "'", ':', '', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' / ', ' // ', 'n*', 'r*', 'l*', 'e*', 'sh', 'ss', 'R', 'RR', 'L', 'LL', 'R', 'RR', 'L', 'LL', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', 'A', 'B', 'G', 'D', 'E', 'V', 'Z', 'T`', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Zh', 'R', 'S', 'T', 'U', 'P`', 'K`', "G'", 'Q', 'Sh', 'Ch`', 'C`', "Z'", 'C', 'Ch', 'X', 'J', 'H', 'E', 'Y', 'W', 'Xh', 'OE', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', 'a', 'b', 'g', 'd', 'e', 'v', 'z', 't`', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'zh', 'r', 's', 't', 'u', 'p`', 'k`', "g'", 'q', 'sh', 'ch`', 'c`', "z'", 'c', 'ch', 'x', 'j', 'h', 'e', 'y', 'w', 'xh', 'oe', 'f', '[?]', '[?]', '[?]', '[?]', ' // ', '[?]', '[?]', '[?]') |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def helper(ans, res, nums):
if not nums:
ans.append(res[:])
else:
element = nums.pop()
helper(ans, res, nums)
res.append(element)
helper(ans, res, nums)
res.pop()
nums.append(element)
return ans
return helper([], [], nums)
| class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def helper(ans, res, nums):
if not nums:
ans.append(res[:])
else:
element = nums.pop()
helper(ans, res, nums)
res.append(element)
helper(ans, res, nums)
res.pop()
nums.append(element)
return ans
return helper([], [], nums) |
#!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-03-31
# Written by Matt Warren
#
def foo():
print("completely out of ideas")
if __name__ == "__main__":
foo()
| def foo():
print('completely out of ideas')
if __name__ == '__main__':
foo() |
# see https://www.codewars.com/kata/5ba38ba180824a86850000f7/solutions/python
def solve(arr):
i = 0
while i < len(arr):
if arr.count(arr[i]) > 1:
arr.pop(i)
else:
i+= 1
return arr
print(solve([3,4,4,3,6,3]) == [4,6,3])
print(solve([1,2,1,2,1,2,3]) == [1,2,3])
print(solve([1,2,3,4]) == [1,2,3,4])
print(solve([1,1,4,5,1,2,1]) == [4,5,2,1])
| def solve(arr):
i = 0
while i < len(arr):
if arr.count(arr[i]) > 1:
arr.pop(i)
else:
i += 1
return arr
print(solve([3, 4, 4, 3, 6, 3]) == [4, 6, 3])
print(solve([1, 2, 1, 2, 1, 2, 3]) == [1, 2, 3])
print(solve([1, 2, 3, 4]) == [1, 2, 3, 4])
print(solve([1, 1, 4, 5, 1, 2, 1]) == [4, 5, 2, 1]) |
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
for i in reversed(range(len(num))):
k, num[i] = divmod(num[i] + k, 10)
while k > 0:
num = [k % 10] + num
k //= 10
return num
| class Solution:
def add_to_array_form(self, num: List[int], k: int) -> List[int]:
for i in reversed(range(len(num))):
(k, num[i]) = divmod(num[i] + k, 10)
while k > 0:
num = [k % 10] + num
k //= 10
return num |
# Complete the printLinkedList function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def printLinkedList(head):
if(head is not None):
print(head.data)
printLinkedList(head.next)
| def print_linked_list(head):
if head is not None:
print(head.data)
print_linked_list(head.next) |
class BalanceUnderLimitError(Exception):
pass
class BalanceOverLimitError(Exception):
pass
| class Balanceunderlimiterror(Exception):
pass
class Balanceoverlimiterror(Exception):
pass |
nbPaquets = int(input())
poidsPaquet = int(input())
poidsTotal = nbPaquets * poidsPaquet
if (poidsTotal > 105):
print("Surcharge !") | nb_paquets = int(input())
poids_paquet = int(input())
poids_total = nbPaquets * poidsPaquet
if poidsTotal > 105:
print('Surcharge !') |
def test_root_api(api_client):
status_code, body, _ = api_client.get('/')
assert 200 == status_code
assert 'API' in body
assert {{cookiecutter.project_short_description}} == body['API']
| def test_root_api(api_client):
(status_code, body, _) = api_client.get('/')
assert 200 == status_code
assert 'API' in body
assert {{cookiecutter.project_short_description}} == body['API'] |
PATH_MESHES = '../output'
PATH_DATASET = '../input'
PATH_UNIT_MESHES = '../unit_meshes'
STR_LEGO_2_4 = 'lego_2_4.stl'
STR_CUBE = 'cube.stl'
| path_meshes = '../output'
path_dataset = '../input'
path_unit_meshes = '../unit_meshes'
str_lego_2_4 = 'lego_2_4.stl'
str_cube = 'cube.stl' |
general = "ffmpeg -f gdigrab -framerate 20 -offset_x"
# Encoding method:
# amd: hevc_amf
# nvidia: hevc_nvenc
encoder = "hevc_nvenc" | general = 'ffmpeg -f gdigrab -framerate 20 -offset_x'
encoder = 'hevc_nvenc' |
_base_ = './solo_r50_fpn_3x_coco.py'
# model settings
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='torchvision://resnet101')))
| _base_ = './solo_r50_fpn_3x_coco.py'
model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101'))) |
{
"targets": [
{
"target_name": "compressor",
"sources": [ "./dev/compressor/bit_reader.cpp", "./dev/compressor/bit_writer.cpp", "./dev/compressor/encoding.cpp",
"./dev/compressor/tree_node.cpp", "./dev/compressor/huffman.cpp", "./dev/compressor/node_wrapper.cpp" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
]
}
]
} | {'targets': [{'target_name': 'compressor', 'sources': ['./dev/compressor/bit_reader.cpp', './dev/compressor/bit_writer.cpp', './dev/compressor/encoding.cpp', './dev/compressor/tree_node.cpp', './dev/compressor/huffman.cpp', './dev/compressor/node_wrapper.cpp'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
cur.sendQuery("exec exampleproc");
field00=cur.getFieldByIndex(0,0);
field01=cur.getFieldByIndex(0,1);
field02=cur.getFieldByIndex(0,2);
field10=cur.getFieldByIndex(1,0);
field11=cur.getFieldByIndex(1,1);
field12=cur.getFieldByIndex(1,2);
| cur.sendQuery('exec exampleproc')
field00 = cur.getFieldByIndex(0, 0)
field01 = cur.getFieldByIndex(0, 1)
field02 = cur.getFieldByIndex(0, 2)
field10 = cur.getFieldByIndex(1, 0)
field11 = cur.getFieldByIndex(1, 1)
field12 = cur.getFieldByIndex(1, 2) |
# Worker Processes
worker_class = 'sync'
socket_path = 'unix:/tmp/web-info.sock'
bind = socket_path
| worker_class = 'sync'
socket_path = 'unix:/tmp/web-info.sock'
bind = socket_path |
word="banana"
def bananas(s):
return helper(s, [], "", len(word))
def helper(s, arr, remain, length):
if length==0:
arr.append(remain+len(s)*"-")
return
for i,j in enumerate(s):
if j==word[len(word)-length]:
helper(s[i+1:], arr, remain+"-"*i+j, length-1)
return arr | word = 'banana'
def bananas(s):
return helper(s, [], '', len(word))
def helper(s, arr, remain, length):
if length == 0:
arr.append(remain + len(s) * '-')
return
for (i, j) in enumerate(s):
if j == word[len(word) - length]:
helper(s[i + 1:], arr, remain + '-' * i + j, length - 1)
return arr |
lst = open("p26.txt", 'r')
biggest = [0, 0]
for z, line in enumerate(lst):
x = line.split()
if int(x[1]) > int(biggest[1]):
print("Old: ", biggest)
biggest[0] = x[0]
biggest[1] = x[1]
print("New: ", biggest)
if z == 999:
break
print(biggest)
| lst = open('p26.txt', 'r')
biggest = [0, 0]
for (z, line) in enumerate(lst):
x = line.split()
if int(x[1]) > int(biggest[1]):
print('Old: ', biggest)
biggest[0] = x[0]
biggest[1] = x[1]
print('New: ', biggest)
if z == 999:
break
print(biggest) |
# Name of the Project : cal-cli.py
# Written by NoobScience : https://github.com/newtoallofthis123
# Modules Used : None
''' The following is registered under the MIT License, NoobScience 2021. You are free to use it
as you like as long as you know what you are doing.
Enjoy using and check some of my other projects at https://github.com/newtoallofthis123'''
# Don't Change the code after this line unless you know what you are doing.
#! /usr/bin/env python3
'''
A simple cli tool written in python to be used as a calculator.
By NoobScience. To use it,
just switch to the directory you stored it in and open the terminal there and
type python alarm.py
Available for Windows, Mac, Linux and written in python'''
# Getting the user imput about the two numbers and operation
print("Cal-cli by NoobScience")
num1 = float(input("Enter the first number "))
num2 = float(input("Enter the second Number "))
operator= input("Enter the operator ")
# Defining operators and printing the operated numbers
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("Unknown, please try again")
# Enjoy
| """ The following is registered under the MIT License, NoobScience 2021. You are free to use it
as you like as long as you know what you are doing.
Enjoy using and check some of my other projects at https://github.com/newtoallofthis123"""
'\nA simple cli tool written in python to be used as a calculator.\nBy NoobScience. To use it,\njust switch to the directory you stored it in and open the terminal there and\ntype python alarm.py\nAvailable for Windows, Mac, Linux and written in python'
print('Cal-cli by NoobScience')
num1 = float(input('Enter the first number '))
num2 = float(input('Enter the second Number '))
operator = input('Enter the operator ')
if operator == '+':
print(num1 + num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
print(num1 / num2)
else:
print('Unknown, please try again') |
{
"variables": {
"module_name": "core",
"module_path": "./dist"
},
'targets': [
{
'target_name': '<(module_name)',
'sources': [
'src/index.cpp',
'src/LameAsyncWorker.cpp',
'src/EncodeWorker.cpp',
'src/lz4dec.c',
],
'includes': [
'./common.gypi'
],
'dependencies': [
'deps/lame/libmp3lame.gyp:mp3lame',
'deps/lz4/lz4.gyp:lz4',
'deps/fdk-aac/fdk-aac.gyp:fdk-aac'
],
},
{
"target_name": "action_after_build",
"type": "none",
"dependencies": [ "<(module_name)" ],
"copies": [
{
"files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
"destination": "<(module_path)"
}
]
}
]
}
| {'variables': {'module_name': 'core', 'module_path': './dist'}, 'targets': [{'target_name': '<(module_name)', 'sources': ['src/index.cpp', 'src/LameAsyncWorker.cpp', 'src/EncodeWorker.cpp', 'src/lz4dec.c'], 'includes': ['./common.gypi'], 'dependencies': ['deps/lame/libmp3lame.gyp:mp3lame', 'deps/lz4/lz4.gyp:lz4', 'deps/fdk-aac/fdk-aac.gyp:fdk-aac']}, {'target_name': 'action_after_build', 'type': 'none', 'dependencies': ['<(module_name)'], 'copies': [{'files': ['<(PRODUCT_DIR)/<(module_name).node'], 'destination': '<(module_path)'}]}]} |
class MetaPackage:
instances = []
def __init__(self, pkgname, pkgtype=None, pkgorg=None):
self.instances.append(self) # adding the instance to colllective
if len(pkgname.split(':')) == 2:
if pkgtype == "maven":
if pkgorg == None:
self._pkg_name = pkgname.split(':')[1]
self._orgId = pkgname.split(':')[0]
else:
self._pkg_name = pkgname
self._orgId = pkgorg
self._exists = None
self._pkg_type = pkgtype
self._score = None
self._timestamp = None
self._verCount = None
#self._pkg_ver = pkgver TBA
def __repr__(self):
return self._pkg_name
def __str__(self):
return str(self._pkg_name)
def listall(self):
lister = []
lister.append(self._pkg_name)
lister.append(self._pkg_type)
lister.append(self._exists)
lister.append(self._orgId)
lister.append(self._score)
lister.append(self._verCount)
lister.append(self._timestamp)
return lister
def get_instances():
return MetaPackage.instances
@property
def pkg_name(self):
return self._pkg_name
@property
def author(self):
return self._author
@author.setter
def author(self, a):
self._author = a
@property
def author_email(self):
return self._author_email
@author_email.setter
def author_email(self, a):
self._author_email = a
@property
def exists(self):
return self._exists
@exists.setter
def exists(self, a):
self._exists = a
@property
def publisher(self):
return self._publisher
@publisher.setter
def publisher(self, a):
self._publisher = a
@property
def publisher_email(self):
return self._publisher_email
@publisher.setter
def publisher(self, a):
self._publisher_email = a
@property
def maintainer(self):
return self._maintainer
@maintainer.setter
def maintainer(self, a):
self._maintainer = a
@property
def maintainer_email(self):
return self._maintainer_email
@maintainer_email.setter
def maintainer_email(self, a):
self._maintainer_email = a
@property
def forkCount(self):
return self._forkCount
@forkCount.setter
def forkCount(self, a):
self._forkCount = a
@property
def subsCount(self):
return self._subsCount
@subsCount.setter
def subsCount(self, a):
self._subsCount = a
@property
def starCount(self):
return self._starCount
@starCount.setter
def starCount(self, a):
self._starCount = a
@property
def downloadCount(self):
return self._downloadCount
@downloadCount.setter
def downloadCount(self, a):
self._downloadCount = a
@property
def score(self):
return self._score
@score.setter
def score(self, a):
self._score = a
@property
def dependencies(self):
return self._dependencies
@dependencies.setter
def dependencies(self, a):
self._dependencies = a
@property
def issueCount(self):
return self._issueCount
@issueCount.setter
def issueCount(self, a):
self._issueCount = a
@property
def contributorCount(self):
return self._contributorCount
@contributorCount.setter
def contributorCount(self, a):
self._contributorCount = a
@property
def orgId(self):
return self._orgId
@orgId.setter
def orgId(self, a):
self._orgId = a
@property
def verCount(self):
return self._verCount
@verCount.setter
def verCount(self, a):
self._verCount = a
@property
def timestamp(self):
return self._timestamp
@timestamp.setter
def timestamp(self, a): #unix timestamp
self._timestamp = a
# not-supported for now: hasTests, testsSize, privateRepo | class Metapackage:
instances = []
def __init__(self, pkgname, pkgtype=None, pkgorg=None):
self.instances.append(self)
if len(pkgname.split(':')) == 2:
if pkgtype == 'maven':
if pkgorg == None:
self._pkg_name = pkgname.split(':')[1]
self._orgId = pkgname.split(':')[0]
else:
self._pkg_name = pkgname
self._orgId = pkgorg
self._exists = None
self._pkg_type = pkgtype
self._score = None
self._timestamp = None
self._verCount = None
def __repr__(self):
return self._pkg_name
def __str__(self):
return str(self._pkg_name)
def listall(self):
lister = []
lister.append(self._pkg_name)
lister.append(self._pkg_type)
lister.append(self._exists)
lister.append(self._orgId)
lister.append(self._score)
lister.append(self._verCount)
lister.append(self._timestamp)
return lister
def get_instances():
return MetaPackage.instances
@property
def pkg_name(self):
return self._pkg_name
@property
def author(self):
return self._author
@author.setter
def author(self, a):
self._author = a
@property
def author_email(self):
return self._author_email
@author_email.setter
def author_email(self, a):
self._author_email = a
@property
def exists(self):
return self._exists
@exists.setter
def exists(self, a):
self._exists = a
@property
def publisher(self):
return self._publisher
@publisher.setter
def publisher(self, a):
self._publisher = a
@property
def publisher_email(self):
return self._publisher_email
@publisher.setter
def publisher(self, a):
self._publisher_email = a
@property
def maintainer(self):
return self._maintainer
@maintainer.setter
def maintainer(self, a):
self._maintainer = a
@property
def maintainer_email(self):
return self._maintainer_email
@maintainer_email.setter
def maintainer_email(self, a):
self._maintainer_email = a
@property
def fork_count(self):
return self._forkCount
@forkCount.setter
def fork_count(self, a):
self._forkCount = a
@property
def subs_count(self):
return self._subsCount
@subsCount.setter
def subs_count(self, a):
self._subsCount = a
@property
def star_count(self):
return self._starCount
@starCount.setter
def star_count(self, a):
self._starCount = a
@property
def download_count(self):
return self._downloadCount
@downloadCount.setter
def download_count(self, a):
self._downloadCount = a
@property
def score(self):
return self._score
@score.setter
def score(self, a):
self._score = a
@property
def dependencies(self):
return self._dependencies
@dependencies.setter
def dependencies(self, a):
self._dependencies = a
@property
def issue_count(self):
return self._issueCount
@issueCount.setter
def issue_count(self, a):
self._issueCount = a
@property
def contributor_count(self):
return self._contributorCount
@contributorCount.setter
def contributor_count(self, a):
self._contributorCount = a
@property
def org_id(self):
return self._orgId
@orgId.setter
def org_id(self, a):
self._orgId = a
@property
def ver_count(self):
return self._verCount
@verCount.setter
def ver_count(self, a):
self._verCount = a
@property
def timestamp(self):
return self._timestamp
@timestamp.setter
def timestamp(self, a):
self._timestamp = a |
LARGURA = 500
ALTURA = 500
CANVAS_L = 400
CANVAS_A = 400
| largura = 500
altura = 500
canvas_l = 400
canvas_a = 400 |
class Constants:
# Version data
VERSION_NUMBERS = (0, 1, 3, 0)
VERSION_STR = ".".join([str(num) for num in VERSION_NUMBERS[0:3]])
VERSION_SUFFIX = "b"
VERSION_VSTR = "v" + VERSION_STR + VERSION_SUFFIX
VERSION_FILENAME = "version.py"
WHOAMI = "Brian Yao"
# Process info
PROGRAM_NAME = "VALORANT-ystr"
PROGRAM_EXE = PROGRAM_NAME + ".exe"
PROGRAM_PROC_COUNT = 2 # Number of active processes per instance of this program
GAME_EXES = ["VALORANT-Win64-Shipping.exe", "RiotClientServices.exe"]
GAME_CLIENT_UX_EXES = ["RiotClientUx.exe", "RiotClientUxRender.exe"]
# Resources
ICON_URI = "https://raw.githubusercontent.com/theyaoster/valorant-ystr/master/favicon.ico"
LATEST_RELEASE_API_URL = "https://api.github.com/repos/theyaoster/valorant-ystr/releases/latest"
REPO_URL = "https://github.com/theyaoster/valorant-ystr"
# Filenames
CONFIG_FILENAME = "config.json"
ICON_FILENAME = "favicon.ico"
LOG_FILENAME = "debug.log"
# Field names
NAME = "name"
SECRET = "secret"
ENDPOINT = "endpoint"
STATUS = "status"
CONTRACT = "contract_agent"
IGN = "ign"
# Values
LOADING_STATUS = "Loading"
OFFLINE_STATUS = "Offline"
UPDATING_STATUS = "Updating"
# API paths
LIVE_STATUS_PATH = "live_status"
CONTRACT_PATH = "contract"
GAME_DATA_PATH = "game_data" | class Constants:
version_numbers = (0, 1, 3, 0)
version_str = '.'.join([str(num) for num in VERSION_NUMBERS[0:3]])
version_suffix = 'b'
version_vstr = 'v' + VERSION_STR + VERSION_SUFFIX
version_filename = 'version.py'
whoami = 'Brian Yao'
program_name = 'VALORANT-ystr'
program_exe = PROGRAM_NAME + '.exe'
program_proc_count = 2
game_exes = ['VALORANT-Win64-Shipping.exe', 'RiotClientServices.exe']
game_client_ux_exes = ['RiotClientUx.exe', 'RiotClientUxRender.exe']
icon_uri = 'https://raw.githubusercontent.com/theyaoster/valorant-ystr/master/favicon.ico'
latest_release_api_url = 'https://api.github.com/repos/theyaoster/valorant-ystr/releases/latest'
repo_url = 'https://github.com/theyaoster/valorant-ystr'
config_filename = 'config.json'
icon_filename = 'favicon.ico'
log_filename = 'debug.log'
name = 'name'
secret = 'secret'
endpoint = 'endpoint'
status = 'status'
contract = 'contract_agent'
ign = 'ign'
loading_status = 'Loading'
offline_status = 'Offline'
updating_status = 'Updating'
live_status_path = 'live_status'
contract_path = 'contract'
game_data_path = 'game_data' |
# https://leetcode.com/problems/flipping-an-image
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
R, C = len(A), len(A[0])
for r in range(R):
for c in range(int(C / 2)):
A[r][c], A[r][C - 1 - c] = A[r][C - 1 - c], A[r][c]
for r in range(R):
for c in range(C):
if A[r][c] == 0:
A[r][c] = 1
else:
A[r][c] = 0
return A
| class Solution:
def flip_and_invert_image(self, A: List[List[int]]) -> List[List[int]]:
(r, c) = (len(A), len(A[0]))
for r in range(R):
for c in range(int(C / 2)):
(A[r][c], A[r][C - 1 - c]) = (A[r][C - 1 - c], A[r][c])
for r in range(R):
for c in range(C):
if A[r][c] == 0:
A[r][c] = 1
else:
A[r][c] = 0
return A |
#!/usr/bin/env python3
filename = 'p022_names.txt'
with open(filename, 'r') as tfile:
all_names = tfile.read().replace("\"", '')
all_names = all_names.split(',')
all_names.sort()
total_score = 0
print('name, index, name_score, total_score')
for ind, name in enumerate(all_names):
index = ind + 1
name_score = 0
for char in name:
# ord('A') = 65 so if we - 64 we get 1
name_score += ord(char) - 64
name_score *= index
total_score += name_score
print('%s %s %s %s' % (name, index, name_score, total_score))
print('total_score=%s' % total_score)
| filename = 'p022_names.txt'
with open(filename, 'r') as tfile:
all_names = tfile.read().replace('"', '')
all_names = all_names.split(',')
all_names.sort()
total_score = 0
print('name, index, name_score, total_score')
for (ind, name) in enumerate(all_names):
index = ind + 1
name_score = 0
for char in name:
name_score += ord(char) - 64
name_score *= index
total_score += name_score
print('%s %s %s %s' % (name, index, name_score, total_score))
print('total_score=%s' % total_score) |
#
# main.py
# Mich, 2016-01-15
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
if False:
mldb = None
mldb.log("mldb_py_argv_test_plugin loaded")
| if False:
mldb = None
mldb.log('mldb_py_argv_test_plugin loaded') |
def mascotas (mascota):
mascotas = {
'firulais': 1,
'venus': 2,
'lira': 3,
'pinto': 4
}
if mascota in mascotas:
return 1
else:
return 0
| def mascotas(mascota):
mascotas = {'firulais': 1, 'venus': 2, 'lira': 3, 'pinto': 4}
if mascota in mascotas:
return 1
else:
return 0 |
##
# EXCEPTIONS
##
##
# Exchange
##
EXCHANGECONNECTIONERROR = (
"Problem connecting to the Exchange, please check your Exchange credentials"
)
EXCHANGEPRIVILEGESERROR = (
"Problem executing the action on the Exchange, "
"please check the permissions assign to the API key provided"
)
EXCHANGEINVALIDSYMBOLERROR = "Problem trying to fetch symbol on the Exchange, probably the symbol is NOT supported"
EXCHANGEINVALIDQUANTITYERROR = (
"The quantity introduced is not within the Exchange allowed parameters"
)
EXCHANGEEXTENDEDFUNCTIONALITYERROR = (
"Please to use enchance functionalities add a supported exchange"
)
##
# Account
##
ACCOUNTREQUIREDERROR = "You need to have at least one account configured"
##
# Utilities
##
PAIRNOTSUPPORTEDERROR = (
"Please select another pair, this is not supported for the operation requested"
)
| exchangeconnectionerror = 'Problem connecting to the Exchange, please check your Exchange credentials'
exchangeprivilegeserror = 'Problem executing the action on the Exchange, please check the permissions assign to the API key provided'
exchangeinvalidsymbolerror = 'Problem trying to fetch symbol on the Exchange, probably the symbol is NOT supported'
exchangeinvalidquantityerror = 'The quantity introduced is not within the Exchange allowed parameters'
exchangeextendedfunctionalityerror = 'Please to use enchance functionalities add a supported exchange'
accountrequirederror = 'You need to have at least one account configured'
pairnotsupportederror = 'Please select another pair, this is not supported for the operation requested' |
def gobad(x, y):
return x / y
def gosouth(x):
print(gobad(x, 0))
gosouth(1)
| def gobad(x, y):
return x / y
def gosouth(x):
print(gobad(x, 0))
gosouth(1) |
class OptBase:
def __init__(self):
pass
def set_func(self, func):
self.func = func
def set_grad(self, func):
self.grad = func
| class Optbase:
def __init__(self):
pass
def set_func(self, func):
self.func = func
def set_grad(self, func):
self.grad = func |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.