content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
##Generalize orienteering contours=name ##maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm=number4 ##contours=vector ##min=string37 ##generalizecontours=output vector outputs_QGISFIELDCALCULATOR_1=processing.runalg('qgis:fieldcalculator', contours,'length',0,10.0,2.0,True,'round($length,2)',None) outputs_QGISEXTRACTBYATTRIBUTE_1=processing.runalg('qgis:extractbyattribute', outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'],'length',3,min,None) outputs_GRASS7V.GENERALIZE.SIMPLIFY_1=processing.runalg('grass7:v.generalize.simplify', outputs_QGISEXTRACTBYATTRIBUTE_1['OUTPUT'],0,maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm,7.0,50.0,False,True,None,-1.0,0.0001,0,None) outputs_QGISDELETECOLUMN_1=processing.runalg('qgis:deletecolumn', outputs_GRASS7V.GENERALIZE.SIMPLIFY_1['output'],'length',generalizecontours)
outputs_qgisfieldcalculator_1 = processing.runalg('qgis:fieldcalculator', contours, 'length', 0, 10.0, 2.0, True, 'round($length,2)', None) outputs_qgisextractbyattribute_1 = processing.runalg('qgis:extractbyattribute', outputs_QGISFIELDCALCULATOR_1['OUTPUT_LAYER'], 'length', 3, min, None) outputs_GRASS7V.GENERALIZE.SIMPLIFY_1 = processing.runalg('grass7:v.generalize.simplify', outputs_QGISEXTRACTBYATTRIBUTE_1['OUTPUT'], 0, maximumdistancebetweentheoriginalandthesimplifiedcurvedouglaspeuckeralgorithm, 7.0, 50.0, False, True, None, -1.0, 0.0001, 0, None) outputs_qgisdeletecolumn_1 = processing.runalg('qgis:deletecolumn', outputs_GRASS7V.GENERALIZE.SIMPLIFY_1['output'], 'length', generalizecontours)
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) # norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet18_v1c', backbone=dict( type='BiseNetV1', base_model='ResNetV1c', depth=18, out_indices=(0, 1, 2), with_sp=False, # using the Spatial Path or not # dilations=(1, 1, 1, 1), # no dilations in BiseNet, so this line can be annotated # strides=(1, 2, 1, 1), # need downsample for regular resnet, so this line can be annotated norm_cfg=norm_cfg, align_corners=False), decode_head=dict( type='FCNHead', in_index=-1, # Backbone stage index in_channels=256, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=[ dict( type='FCNHead', in_index=-2, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), dict( type='FCNHead', in_index=-3, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), ], # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained='open-mmlab://resnet18_v1c', backbone=dict(type='BiseNetV1', base_model='ResNetV1c', depth=18, out_indices=(0, 1, 2), with_sp=False, norm_cfg=norm_cfg, align_corners=False), decode_head=dict(type='FCNHead', in_index=-1, in_channels=256, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=[dict(type='FCNHead', in_index=-2, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), dict(type='FCNHead', in_index=-3, in_channels=128, channels=64, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))], train_cfg=dict(), test_cfg=dict(mode='whole'))
#For packaging ''' Users api handles JWT auth for users '''
""" Users api handles JWT auth for users """
def run(params={}): return { 'project_name': 'Core', 'bitcode': True, 'min_version': '9.0', 'enable_arc': True, 'enable_visibility': True, 'conan_profile': 'ezored_ios_framework_profile', 'archs': [ {'arch': 'armv7', 'conan_arch': 'armv7', 'platform': 'OS'}, {'arch': 'armv7s', 'conan_arch': 'armv7s', 'platform': 'OS'}, {'arch': 'arm64', 'conan_arch': 'armv8', 'platform': 'OS64'}, {'arch': 'arm64e', 'conan_arch': 'armv8.3', 'platform': 'OS64'}, {'arch': 'x86_64', 'conan_arch': 'x86_64', 'platform': 'SIMULATOR64'}, ], 'build_types': ['Debug', 'Release'], 'install_headers': [ { 'type': 'dir', 'path': 'files/djinni/001-app-domain/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/002-app-core/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/003-app-data-services/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/004-app-system-service/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/005-app-helpers/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/datetime/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/file-helper/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/httpclient/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/shared-data/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/logger/generated-src/objc', }, { 'type': 'dir', 'path': 'files/djinni/string-helper/generated-src/objc', }, { 'type': 'dir', 'path': 'files/src/file-helper/objc', }, { 'type': 'dir', 'path': 'files/src/httpclient/objc', }, { 'type': 'dir', 'path': 'files/src/logger/objc', }, { 'type': 'dir', 'path': 'files/src/shared-data/objc', }, ] }
def run(params={}): return {'project_name': 'Core', 'bitcode': True, 'min_version': '9.0', 'enable_arc': True, 'enable_visibility': True, 'conan_profile': 'ezored_ios_framework_profile', 'archs': [{'arch': 'armv7', 'conan_arch': 'armv7', 'platform': 'OS'}, {'arch': 'armv7s', 'conan_arch': 'armv7s', 'platform': 'OS'}, {'arch': 'arm64', 'conan_arch': 'armv8', 'platform': 'OS64'}, {'arch': 'arm64e', 'conan_arch': 'armv8.3', 'platform': 'OS64'}, {'arch': 'x86_64', 'conan_arch': 'x86_64', 'platform': 'SIMULATOR64'}], 'build_types': ['Debug', 'Release'], 'install_headers': [{'type': 'dir', 'path': 'files/djinni/001-app-domain/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/002-app-core/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/003-app-data-services/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/004-app-system-service/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/005-app-helpers/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/datetime/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/file-helper/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/httpclient/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/shared-data/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/logger/generated-src/objc'}, {'type': 'dir', 'path': 'files/djinni/string-helper/generated-src/objc'}, {'type': 'dir', 'path': 'files/src/file-helper/objc'}, {'type': 'dir', 'path': 'files/src/httpclient/objc'}, {'type': 'dir', 'path': 'files/src/logger/objc'}, {'type': 'dir', 'path': 'files/src/shared-data/objc'}]}
#!/usr/bin/python # encoding: utf-8 """ custom_stopwords Purpose: Collect custom stopwords lists Author: datadonk23 (datadonk23@gmail.com) Date: 2018-05-01 """ arxiv_stopwords = ["arxiv", "astro-ph", "astro-ph.co", "astro-ph.ep", "astro-ph.ga", "astro-ph.he", "astro-ph.im", "astro-ph.sr", "cond-mat.dis-nn", "cond-mat.mes-hall", "cond-mat.mtrl-sci", "cond-mat.other", "cond-mat.quant-gas", "cond-mat.soft", "cond-mat.stat-mech", "cond-mat.str-el", "cond-mat.supr-con", "cs.ai", "cs.ar", "cs.CC", "cs.ce", "cs.cg", "cs.cl", "cs.cr", "cs.cv", "cs.cy", "cs.db", "cs.dc", "cs.dl", "cs.dm", "cs.ds", "cs.et", "cs.fl", "cs.gl", "cs.gr", "cs.gt", "cs.hc", "cs.ir", "cs.it", "cs.lg", "cs.lo", "cs.ma","cs.mm", "cs.ms", "cs.na", "cs.ne", "cs.ni", "cs.oh", "cs.os", "cs.pf", "cs.pl", "cs.ro", "cs.sc", "cs.sd", "cs.se", "cs.si", "cs.sy", "econ.em", "eess.as", "eess.iv", "eess.sp", "gr-qc", "hep-ex", "hep-lat", "hep-ph", "hep-th", "math.ac", "math.ag", "math.ap","math.at", "math.ca", "math.co", "math.ct", "math.cv", "math.dg", "math.ds", "math.fa", "math.gm", "math.gn", "math.gr", "math.gt", "math.ho", "math.it", "math.kt", "math.lo", "math.mg", "math.mp", "math.na", "math.nt", "math.oa", "math.oc", "math.pr", "math.qa", "math.ra", "math.rt", "math.sg", "math.sp", "math.st", "math-ph", "nlin.ao", "nlin.cd", "nlin.cg", "nlin.ps", "nlin.si", "nucl-ex", "nucl-th", "physics.acc-ph", "physics.ao-ph", "physics.app-ph", "physics.atm-clus", "physics.atom-ph", "physics.bio-ph", "physics.chem-ph", "physics.class-ph", "physics.comp-ph", "physics.data-an", "physics.ed-ph", "physics.flu-dyn", "physics.gen-ph", "physics.geo-ph", "physics.hist-ph", "physics.ins-det", "physics.med-ph", "physics.optics", "physics.plasm-ph", "physics.pop-ph", "physics.soc-ph", "physics.space-ph", "q-bio.bm", "q-bio.cb","q-bio.gn", "q-bio.mn", "q-bio.nc", "q-bio.ot", "q-bio.pe", "q-bio.qm", "q-bio.sc", "q-bio.to", "q-fin.cp", "q-fin.ec", "q-fin.gn", "q-fin.mf", "q-fin.PM", "q-fin.PR", "q-fin.RM", "q-fin.ST", "q-fin.tr", "quant-ph", "stat.ap", "stat.co", "stat.me", "stat.ml", "stat.ot", "stat.th"] def get_stopwords(): """ Make custom stopwords list accessible :return: [stopwords] - List of stopwords """ stopwords_list = arxiv_stopwords # add additional lists with + return stopwords_list
""" custom_stopwords Purpose: Collect custom stopwords lists Author: datadonk23 (datadonk23@gmail.com) Date: 2018-05-01 """ arxiv_stopwords = ['arxiv', 'astro-ph', 'astro-ph.co', 'astro-ph.ep', 'astro-ph.ga', 'astro-ph.he', 'astro-ph.im', 'astro-ph.sr', 'cond-mat.dis-nn', 'cond-mat.mes-hall', 'cond-mat.mtrl-sci', 'cond-mat.other', 'cond-mat.quant-gas', 'cond-mat.soft', 'cond-mat.stat-mech', 'cond-mat.str-el', 'cond-mat.supr-con', 'cs.ai', 'cs.ar', 'cs.CC', 'cs.ce', 'cs.cg', 'cs.cl', 'cs.cr', 'cs.cv', 'cs.cy', 'cs.db', 'cs.dc', 'cs.dl', 'cs.dm', 'cs.ds', 'cs.et', 'cs.fl', 'cs.gl', 'cs.gr', 'cs.gt', 'cs.hc', 'cs.ir', 'cs.it', 'cs.lg', 'cs.lo', 'cs.ma', 'cs.mm', 'cs.ms', 'cs.na', 'cs.ne', 'cs.ni', 'cs.oh', 'cs.os', 'cs.pf', 'cs.pl', 'cs.ro', 'cs.sc', 'cs.sd', 'cs.se', 'cs.si', 'cs.sy', 'econ.em', 'eess.as', 'eess.iv', 'eess.sp', 'gr-qc', 'hep-ex', 'hep-lat', 'hep-ph', 'hep-th', 'math.ac', 'math.ag', 'math.ap', 'math.at', 'math.ca', 'math.co', 'math.ct', 'math.cv', 'math.dg', 'math.ds', 'math.fa', 'math.gm', 'math.gn', 'math.gr', 'math.gt', 'math.ho', 'math.it', 'math.kt', 'math.lo', 'math.mg', 'math.mp', 'math.na', 'math.nt', 'math.oa', 'math.oc', 'math.pr', 'math.qa', 'math.ra', 'math.rt', 'math.sg', 'math.sp', 'math.st', 'math-ph', 'nlin.ao', 'nlin.cd', 'nlin.cg', 'nlin.ps', 'nlin.si', 'nucl-ex', 'nucl-th', 'physics.acc-ph', 'physics.ao-ph', 'physics.app-ph', 'physics.atm-clus', 'physics.atom-ph', 'physics.bio-ph', 'physics.chem-ph', 'physics.class-ph', 'physics.comp-ph', 'physics.data-an', 'physics.ed-ph', 'physics.flu-dyn', 'physics.gen-ph', 'physics.geo-ph', 'physics.hist-ph', 'physics.ins-det', 'physics.med-ph', 'physics.optics', 'physics.plasm-ph', 'physics.pop-ph', 'physics.soc-ph', 'physics.space-ph', 'q-bio.bm', 'q-bio.cb', 'q-bio.gn', 'q-bio.mn', 'q-bio.nc', 'q-bio.ot', 'q-bio.pe', 'q-bio.qm', 'q-bio.sc', 'q-bio.to', 'q-fin.cp', 'q-fin.ec', 'q-fin.gn', 'q-fin.mf', 'q-fin.PM', 'q-fin.PR', 'q-fin.RM', 'q-fin.ST', 'q-fin.tr', 'quant-ph', 'stat.ap', 'stat.co', 'stat.me', 'stat.ml', 'stat.ot', 'stat.th'] def get_stopwords(): """ Make custom stopwords list accessible :return: [stopwords] - List of stopwords """ stopwords_list = arxiv_stopwords return stopwords_list
# Copyright 2020 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.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. """Log area provider data module.""" class LogArea: """Log area data object.""" _log_area_dictionary = None def __init__(self, **log_area): """Take a dictionary as input and setattr on instance. :param log_area: Dictionary to set attributes from. :type log_area: dict """ self._log_area_dictionary = log_area for key, value in log_area.items(): setattr(self, key, value) def __setattr__(self, name, value): """Set log area parameters to dict and object. :param name: Name of parameter to set. :type name: str :param value: Value of parameter. :type value: any """ if self._log_area_dictionary is not None: self._log_area_dictionary[name] = value super().__setattr__(name, value) def update(self, **dictionary): """Update log area dictionary with new data. :param dictionary: Dictionary to update attributes from. :type dictionary: dict """ self._log_area_dictionary.update(**dictionary) for key, value in dictionary.items(): setattr(self, key, value) @property def as_dict(self): """Represent log area as dictionary. :return: Log area dictionary. :rtype: dict """ return self._log_area_dictionary def __repr__(self): """Represent log area as string. :return: Log area dictionary as string. :rtype: str """ return repr(self._log_area_dictionary)
"""Log area provider data module.""" class Logarea: """Log area data object.""" _log_area_dictionary = None def __init__(self, **log_area): """Take a dictionary as input and setattr on instance. :param log_area: Dictionary to set attributes from. :type log_area: dict """ self._log_area_dictionary = log_area for (key, value) in log_area.items(): setattr(self, key, value) def __setattr__(self, name, value): """Set log area parameters to dict and object. :param name: Name of parameter to set. :type name: str :param value: Value of parameter. :type value: any """ if self._log_area_dictionary is not None: self._log_area_dictionary[name] = value super().__setattr__(name, value) def update(self, **dictionary): """Update log area dictionary with new data. :param dictionary: Dictionary to update attributes from. :type dictionary: dict """ self._log_area_dictionary.update(**dictionary) for (key, value) in dictionary.items(): setattr(self, key, value) @property def as_dict(self): """Represent log area as dictionary. :return: Log area dictionary. :rtype: dict """ return self._log_area_dictionary def __repr__(self): """Represent log area as string. :return: Log area dictionary as string. :rtype: str """ return repr(self._log_area_dictionary)
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? ''' class Solution: def isPalindrome(self, x: int) -> bool: y = str(x) if y == y[::-1]: return True else: return False class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False y = 0 count = 1 a = x while a != 0: temp = a%10 a = a // 10 y = 10 * y + temp if y == x: return True else: return False
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? """ class Solution: def is_palindrome(self, x: int) -> bool: y = str(x) if y == y[::-1]: return True else: return False class Solution: def is_palindrome(self, x: int) -> bool: if x < 0: return False y = 0 count = 1 a = x while a != 0: temp = a % 10 a = a // 10 y = 10 * y + temp if y == x: return True else: return False
class Tile(): """ The smallest building block in a map """ def __init__(self): self.tile = '.' def get(self): return self.tile def set(self, item): self.tile = item
class Tile: """ The smallest building block in a map """ def __init__(self): self.tile = '.' def get(self): return self.tile def set(self, item): self.tile = item
def longestDigitsPrefix(inputString): # iterate through the string arr = '' for i in inputString: if i.isdigit(): arr += i else: break return arr
def longest_digits_prefix(inputString): arr = '' for i in inputString: if i.isdigit(): arr += i else: break return arr
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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. """Provides the stamp info file containing the Bazel non-volatile keys """ def _impl(ctx): output = ctx.outputs.out ctx.actions.run_shell( outputs = [output], inputs = [ctx.info_file], command = "cp {src} {dst}".format( src = ctx.info_file.path, dst = output.path, ), ) stamp_info = rule( implementation = _impl, outputs = { # The stamp file. "out": "%{name}.txt", }, )
"""Provides the stamp info file containing the Bazel non-volatile keys """ def _impl(ctx): output = ctx.outputs.out ctx.actions.run_shell(outputs=[output], inputs=[ctx.info_file], command='cp {src} {dst}'.format(src=ctx.info_file.path, dst=output.path)) stamp_info = rule(implementation=_impl, outputs={'out': '%{name}.txt'})
"""Debug functions for notebooks. """ def count(df, name=None): """Print the count of dataframe with title.""" if name: print("Dataset: %s" % (name)) print("Count: %d" % (df.count())) def show(df, name=None, num_rows=1): """Print title and show a dataframe""" if name: print("Dataset: %s" % (name)) df.show(num_rows) def profile(df, name): """Profile a dataframe, initially just count and show.""" count(df, name) show(df, name=name)
"""Debug functions for notebooks. """ def count(df, name=None): """Print the count of dataframe with title.""" if name: print('Dataset: %s' % name) print('Count: %d' % df.count()) def show(df, name=None, num_rows=1): """Print title and show a dataframe""" if name: print('Dataset: %s' % name) df.show(num_rows) def profile(df, name): """Profile a dataframe, initially just count and show.""" count(df, name) show(df, name=name)
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # --------------------------------------------------------- class LCS: """ Compute the Longest Common Subsequence (LCS) of two given string.""" def __init__(self, str_m, str_n): self.str_m_len = len(str_m) self.str_n_len = len(str_n) dp_table = self._construct_dp_table(str_m, str_n) self._lcs_len = dp_table[self.str_m_len][self.str_n_len] self._lcs = self._find_lcs_str(str_m, str_n, dp_table) def _construct_dp_table(self, str_m, str_n): m = self.str_m_len n = self.str_n_len # Initialize DP table dp = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): # Case 1: if char1 == char2 if str_m[i - 1] == str_n[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] # Case 2: take the max of the values in the top and left cell else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp def _find_lcs_str(self, str_m, str_n, dp_table): m = self.str_m_len n = self.str_n_len lcs = "" while m > 0 and n > 0: # same char if str_m[m - 1] == str_n[n - 1]: # prepend the character lcs = str_m[m - 1] + lcs m -= 1 n -= 1 # top cell > left cell elif dp_table[m - 1][n] > dp_table[m][n - 1]: m -= 1 else: n -= 1 return lcs def get_len(self): return self._lcs_len def get_str(self): return self._lcs
class Lcs: """ Compute the Longest Common Subsequence (LCS) of two given string.""" def __init__(self, str_m, str_n): self.str_m_len = len(str_m) self.str_n_len = len(str_n) dp_table = self._construct_dp_table(str_m, str_n) self._lcs_len = dp_table[self.str_m_len][self.str_n_len] self._lcs = self._find_lcs_str(str_m, str_n, dp_table) def _construct_dp_table(self, str_m, str_n): m = self.str_m_len n = self.str_n_len dp = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if str_m[i - 1] == str_n[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp def _find_lcs_str(self, str_m, str_n, dp_table): m = self.str_m_len n = self.str_n_len lcs = '' while m > 0 and n > 0: if str_m[m - 1] == str_n[n - 1]: lcs = str_m[m - 1] + lcs m -= 1 n -= 1 elif dp_table[m - 1][n] > dp_table[m][n - 1]: m -= 1 else: n -= 1 return lcs def get_len(self): return self._lcs_len def get_str(self): return self._lcs
class Error: none_or_invalid_attribute = "main attributes should have value." unacceptable_json = "json input has unacceptable format." unacceptable_object_type = "object has unacceptable type"
class Error: none_or_invalid_attribute = 'main attributes should have value.' unacceptable_json = 'json input has unacceptable format.' unacceptable_object_type = 'object has unacceptable type'
def decimalni_zapis(deljenec, delitelj): memo = set() decimalni_zapis = '' while (deljenec, delitelj) not in memo: if deljenec % delitelj == 0: decimalni_zapis += str(deljenec // delitelj) return decimalni_zapis, deljenec, delitelj elif deljenec < delitelj: decimalni_zapis += '0' memo.add((deljenec, delitelj)) deljenec *= 10 else: decimalni_zapis += str(deljenec // delitelj) memo.add((deljenec, delitelj)) deljenec = deljenec % delitelj * 10 return decimalni_zapis # def je_prastevilo(n): # if n < 2 or n == 4 or n == 6 or n == 8: # return False # i = 3 # while i*i <= n: # if n % i == 0 or n % 2 == 0: # return False # i += 2 # return True slovar = dict() for i in range(2, 1000): slovar[i] = len(decimalni_zapis(1, i)) # for stevilo in range(1, 10 ** 6): # if len(decimalni_zapis(1, stevilo)) == stevilo: # print(stevilo) print(max(slovar, key=slovar.get))
def decimalni_zapis(deljenec, delitelj): memo = set() decimalni_zapis = '' while (deljenec, delitelj) not in memo: if deljenec % delitelj == 0: decimalni_zapis += str(deljenec // delitelj) return (decimalni_zapis, deljenec, delitelj) elif deljenec < delitelj: decimalni_zapis += '0' memo.add((deljenec, delitelj)) deljenec *= 10 else: decimalni_zapis += str(deljenec // delitelj) memo.add((deljenec, delitelj)) deljenec = deljenec % delitelj * 10 return decimalni_zapis slovar = dict() for i in range(2, 1000): slovar[i] = len(decimalni_zapis(1, i)) print(max(slovar, key=slovar.get))
class Solution: """ @param grids: a maxtrix with alphabet @return: return sorted lists """ def CounterDiagonalSort(self, grids): # write your code here m = len(grids) n = len(grids[0]) table = [] for i in range(m): temp = [] row = i col = 0 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) for i in range(m, m + n - 1): temp = [] row = m - 1 col = i - m + 1 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) l = min(m, n) result = [] for t in table: temp = [] i = 0 while len(temp) < l: temp.append(t[i % len(t)]) i += 1 result.append(temp) return sorted(result)
class Solution: """ @param grids: a maxtrix with alphabet @return: return sorted lists """ def counter_diagonal_sort(self, grids): m = len(grids) n = len(grids[0]) table = [] for i in range(m): temp = [] row = i col = 0 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) for i in range(m, m + n - 1): temp = [] row = m - 1 col = i - m + 1 while row >= 0 and col < n: temp.append(grids[row][col]) row -= 1 col += 1 table.append(temp) l = min(m, n) result = [] for t in table: temp = [] i = 0 while len(temp) < l: temp.append(t[i % len(t)]) i += 1 result.append(temp) return sorted(result)
#!/usr/bin/python3 bridgera = ['Arijit','Soumya','Gunjan','Arptia','Bishwa','Rintu','Satya','Lelin'] # Generator Function iterarates through all items of array def gen_func(data): for i in range(len(data)): yield data[i] data_gen = list(gen_func(bridgera)) print (data_gen) # Normal Function iterates through only first item of array def norm_func(data): for i in range(len(data)): return data[i] norm_gen = list(norm_func(bridgera)) print (norm_gen)
bridgera = ['Arijit', 'Soumya', 'Gunjan', 'Arptia', 'Bishwa', 'Rintu', 'Satya', 'Lelin'] def gen_func(data): for i in range(len(data)): yield data[i] data_gen = list(gen_func(bridgera)) print(data_gen) def norm_func(data): for i in range(len(data)): return data[i] norm_gen = list(norm_func(bridgera)) print(norm_gen)
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove, search, pop """ def __init__(self, value=None): self.head = value def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next is not None: node = node.next node.next = Node(value) return def display(self): node = self.head while node: print(node.value) node = node.next def convert_list(self): Pylist = [] node = self.head while node: Pylist.append(node.value) node = node.next return Pylist def prepand(self, value): new_node = Node(value) new_node.next = self.head self.head = new_node def search(self, value): node = self.head while node: if node.value == value: return node node = node.next return None def remove(self, value): node = self.head #If head contains the value, change the head if node is not None: if node.value == value: self.head = node.next node = None return # Keep track of the previous node of the node that contains the value while node: if node.value == value: break prev_node = node node = node.next if node == None: return #Link the previous node to the next node prev_node.next = node.next node = None def pop(self): node = self.head value = node.value self.head = node.next # node = None return value def insert(self, value, pos): node = self.head new_node = Node(value) idx = 0 prev_node = None while node: if idx == pos: break prev_node = node node = node.next idx+=1 if prev_node == None: new_node.next = self.head self.head = new_node return new_node.next = prev_node.next prev_node.next = new_node return LinkedList.insert = insert LinkedList.prepand = prepand LinkedList.pop = pop LinkedList.remove = remove LinkedList.search = search def create_linked_list(_list_): """ The function converts a python list/array into a linked list; Time complexity: O(n) :param _list_: a Python list :return: A linked list """ head = None tail = None for val in _list_: if head is None: head = Node(val) tail = head else: tail.next = Node(val) tail = tail.next return head def reverse(linked_list): """ Reverse a linked list :param linked_list: linked_list :return: reversed linked list """ new_list = LinkedList prev_node = None for value in linked_list: new_node = Node(value) new_node.next = prev_node prev_node = new_node new_list.head = prev_node return new_list def isCircular(linked_list): """ Checks if a linked list is circular i.e., has loops :param linked_list: Linked list :return: True/False """ if linked_list.head is None: return False fast = linked_list.head slow = linked_list.head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False if __name__ == "__main__": llist = LinkedList() llist.append(2) llist.append(-1) llist.append(10) llist.append(1) _list_ = llist.convert_list() print("Linked List: ") llist.display() print("Python List: ", _list_) llist.prepand(8) print("Prepanded Linked List") llist.display() node = llist.search(-1) print("Value searched: ", node.value, " Next Node: ", node.next.value) rm = 10 llist.remove(rm) print("Linked List after removal {}: ".format(rm)) llist.display() Pop = llist.pop() print("Element Popped: {}, Value of the head now: {}, linked list after popping element: ".format(Pop, llist.head.value)) llist.display() print("Insertion: ") llist.insert(3, 2) llist.display() reverse_list = reverse(llist) reverse_list.display()
class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove, search, pop """ def __init__(self, value=None): self.head = value def append(self, value): if self.head is None: self.head = node(value) return node = self.head while node.next is not None: node = node.next node.next = node(value) return def display(self): node = self.head while node: print(node.value) node = node.next def convert_list(self): pylist = [] node = self.head while node: Pylist.append(node.value) node = node.next return Pylist def prepand(self, value): new_node = node(value) new_node.next = self.head self.head = new_node def search(self, value): node = self.head while node: if node.value == value: return node node = node.next return None def remove(self, value): node = self.head if node is not None: if node.value == value: self.head = node.next node = None return while node: if node.value == value: break prev_node = node node = node.next if node == None: return prev_node.next = node.next node = None def pop(self): node = self.head value = node.value self.head = node.next return value def insert(self, value, pos): node = self.head new_node = node(value) idx = 0 prev_node = None while node: if idx == pos: break prev_node = node node = node.next idx += 1 if prev_node == None: new_node.next = self.head self.head = new_node return new_node.next = prev_node.next prev_node.next = new_node return LinkedList.insert = insert LinkedList.prepand = prepand LinkedList.pop = pop LinkedList.remove = remove LinkedList.search = search def create_linked_list(_list_): """ The function converts a python list/array into a linked list; Time complexity: O(n) :param _list_: a Python list :return: A linked list """ head = None tail = None for val in _list_: if head is None: head = node(val) tail = head else: tail.next = node(val) tail = tail.next return head def reverse(linked_list): """ Reverse a linked list :param linked_list: linked_list :return: reversed linked list """ new_list = LinkedList prev_node = None for value in linked_list: new_node = node(value) new_node.next = prev_node prev_node = new_node new_list.head = prev_node return new_list def is_circular(linked_list): """ Checks if a linked list is circular i.e., has loops :param linked_list: Linked list :return: True/False """ if linked_list.head is None: return False fast = linked_list.head slow = linked_list.head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False if __name__ == '__main__': llist = linked_list() llist.append(2) llist.append(-1) llist.append(10) llist.append(1) _list_ = llist.convert_list() print('Linked List: ') llist.display() print('Python List: ', _list_) llist.prepand(8) print('Prepanded Linked List') llist.display() node = llist.search(-1) print('Value searched: ', node.value, ' Next Node: ', node.next.value) rm = 10 llist.remove(rm) print('Linked List after removal {}: '.format(rm)) llist.display() pop = llist.pop() print('Element Popped: {}, Value of the head now: {}, linked list after popping element: '.format(Pop, llist.head.value)) llist.display() print('Insertion: ') llist.insert(3, 2) llist.display() reverse_list = reverse(llist) reverse_list.display()
def data_for_fitting(*, building_id, date): """ Retrieves data for fitting from the previous business day taking into account holidays """ lease_start = None while lease_start is None: # Previous business day according to Pandas (might be a holiday) previous_bday = pd.to_datetime(date) - BDay(1) # If a holiday, this will return None lease_start = ( db() .execute( building_daily_stats.select() .where(building_daily_stats.c.building_id == building_id) .where(building_daily_stats.c.date == previous_bday) ) .fetchone() .lease_obligations_start_at ) date = previous_bday # Retrieve 8 hours of data from the lease start return load_sensor_values( building_id=building_id, start_time=lease_start, end_time=lease_start + timedelta(hours=8), )
def data_for_fitting(*, building_id, date): """ Retrieves data for fitting from the previous business day taking into account holidays """ lease_start = None while lease_start is None: previous_bday = pd.to_datetime(date) - b_day(1) lease_start = db().execute(building_daily_stats.select().where(building_daily_stats.c.building_id == building_id).where(building_daily_stats.c.date == previous_bday)).fetchone().lease_obligations_start_at date = previous_bday return load_sensor_values(building_id=building_id, start_time=lease_start, end_time=lease_start + timedelta(hours=8))
"""Top-level package for leimpy.""" __author__ = """Marco Berzborn""" __email__ = 'marco.berzborn@akustik.rwth-aachen.de' __version__ = '0.0.0'
"""Top-level package for leimpy.""" __author__ = 'Marco Berzborn' __email__ = 'marco.berzborn@akustik.rwth-aachen.de' __version__ = '0.0.0'
class Node: """ A node in a graph """ def __init__(self, identifier): """ :param identifier: Identifier is hash of given Shape Object """ self.identifier = identifier self.outgoing_pointers = [] self.incoming_pointers = [] def get_identifier(self): return self.identifier def point_to(self, identifier): """ Points to Node with the given identifier. :param identifier: :return: """ self.incoming_pointers.append(identifier) def pointed_at(self, identifier): self.outgoing_pointers.append(identifier) def has_edges(self): return len(self.incoming_pointers) > 0 or len(self.outgoing_pointers) > 0 def has_mutual_edge(self): for in_edge in self.incoming_pointers: if in_edge in self.outgoing_pointers: return True return False def search_for(self, identifier): return self.__search_for(identifier, []) def __search_for(self, identifier, exclude): if self.identifier == identifier: return self else: for node in self.incoming_pointers: if not hash(node) in exclude: exclude.append(hash(node)) ret = node.__search_for(identifier, exclude) if ret is not None: return ret def __hash__(self): return self.identifier
class Node: """ A node in a graph """ def __init__(self, identifier): """ :param identifier: Identifier is hash of given Shape Object """ self.identifier = identifier self.outgoing_pointers = [] self.incoming_pointers = [] def get_identifier(self): return self.identifier def point_to(self, identifier): """ Points to Node with the given identifier. :param identifier: :return: """ self.incoming_pointers.append(identifier) def pointed_at(self, identifier): self.outgoing_pointers.append(identifier) def has_edges(self): return len(self.incoming_pointers) > 0 or len(self.outgoing_pointers) > 0 def has_mutual_edge(self): for in_edge in self.incoming_pointers: if in_edge in self.outgoing_pointers: return True return False def search_for(self, identifier): return self.__search_for(identifier, []) def __search_for(self, identifier, exclude): if self.identifier == identifier: return self else: for node in self.incoming_pointers: if not hash(node) in exclude: exclude.append(hash(node)) ret = node.__search_for(identifier, exclude) if ret is not None: return ret def __hash__(self): return self.identifier
#implicit type conversion num1 = 12 num2= 13.5 num3 = num1 + num2 print(type(num1)) print(type(num2)) print(num3) print(type(num3))
num1 = 12 num2 = 13.5 num3 = num1 + num2 print(type(num1)) print(type(num2)) print(num3) print(type(num3))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ t = [] def preorder(r): if r: t.append(r.val) preorder(r.left) preorder(r.right) preorder(root) # print t d = set() for n in t: if n in d: return True d.add(k-n) return False
class Solution(object): def find_target(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ t = [] def preorder(r): if r: t.append(r.val) preorder(r.left) preorder(r.right) preorder(root) d = set() for n in t: if n in d: return True d.add(k - n) return False
load("@rules_cuda//cuda:defs.bzl", "cuda_library") NVCC_COPTS = ["--expt-relaxed-constexpr", "--expt-extended-lambda"] def cu_library(name, srcs, copts = [], **kwargs): cuda_library(name, srcs = srcs, copts = NVCC_COPTS + copts, **kwargs)
load('@rules_cuda//cuda:defs.bzl', 'cuda_library') nvcc_copts = ['--expt-relaxed-constexpr', '--expt-extended-lambda'] def cu_library(name, srcs, copts=[], **kwargs): cuda_library(name, srcs=srcs, copts=NVCC_COPTS + copts, **kwargs)
''' Author: jianzhnie Date: 2022-03-04 17:13:55 LastEditTime: 2022-03-04 17:13:55 LastEditors: jianzhnie Description: '''
""" Author: jianzhnie Date: 2022-03-04 17:13:55 LastEditTime: 2022-03-04 17:13:55 LastEditors: jianzhnie Description: """
#!/usr/bin/env python3 #: Program Purpose: #: Read an integer N. For all non-negative integers i < N #: print i * i. #: #: Program Author: Happi Yvan <ivensteinpoker@gmail.com #: Program Date : 11/04/2019 (mm/dd/yyyy) def process(int_val): for x in range(int_val): print(x * x) def main(): val = int(input()) process(val) if __name__ == '__main__': main()
def process(int_val): for x in range(int_val): print(x * x) def main(): val = int(input()) process(val) if __name__ == '__main__': main()
def names(name_list): with open('textfile3.txt', 'w') as myfile: myfile.writelines(name_list) myfile.close() print(name_list) menu() def display_name(n): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() print(name_list[n-1]) return namelist[n-1] def display_s(): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() for i in name_list: if i[0] in ["s", "S"]: print('the name/names that starts with an s is ', i) def append_to_list(n): global namelist name_list = [] for i in range(n): name_to_append = str( input("enter the name you want to append(add) to the list ")) name_list.append(name_to_append) name_list.append('\n') namelist.append(name_to_append) namelist.append('\n') with open('textfile3.txt', 'a') as myfile: myfile.writelines(name_list) for i in range(0, len(namelist), 2): print(namelist[i]) print('are the names in order ') def menu(): print("----------------------- menu to choose function ------------------------") print("enter your choice") print("enter 1 to display the nth name ") print("enter 2 to display names starting with s ") print("enter 3 to add/append more names ") print("if you want to execute all be my guest enter 4 ") x = int(input("enter choice ")) try: if x == 1: index = int(input("enter the index to display name ")) try: display_name(index) except: print("enter an index in range") if x == 2: display_s() if x == 3: number_of_names_to_append = int( input("enter how many names you want to add ")) append_to_list(number_of_names_to_append) if x == 4: pass except: print("TRY AGAIN", "\n", "please enter a valid option") if x == 4: for i in range(1, 4): x = i if x == 1: index = int(input("enter the index to display name ")) try: display_name(index) except: print("enter an index in range") if x == 2: display_s() if x == 3: number_of_names_to_append = int( input("enter how many names you want to add ")) append_to_list(number_of_names_to_append) namelist = [] x = int(input("enter number of names to enter in list ")) for i in range(x): n = str(input("enter the list element ")) namelist.append(n) namelist.append('\n') names(namelist)
def names(name_list): with open('textfile3.txt', 'w') as myfile: myfile.writelines(name_list) myfile.close() print(name_list) menu() def display_name(n): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() print(name_list[n - 1]) return namelist[n - 1] def display_s(): with open('textfile3.txt', 'r') as myfile: name_list = myfile.readlines() for i in name_list: if i[0] in ['s', 'S']: print('the name/names that starts with an s is ', i) def append_to_list(n): global namelist name_list = [] for i in range(n): name_to_append = str(input('enter the name you want to append(add) to the list ')) name_list.append(name_to_append) name_list.append('\n') namelist.append(name_to_append) namelist.append('\n') with open('textfile3.txt', 'a') as myfile: myfile.writelines(name_list) for i in range(0, len(namelist), 2): print(namelist[i]) print('are the names in order ') def menu(): print('----------------------- menu to choose function ------------------------') print('enter your choice') print('enter 1 to display the nth name ') print('enter 2 to display names starting with s ') print('enter 3 to add/append more names ') print('if you want to execute all be my guest enter 4 ') x = int(input('enter choice ')) try: if x == 1: index = int(input('enter the index to display name ')) try: display_name(index) except: print('enter an index in range') if x == 2: display_s() if x == 3: number_of_names_to_append = int(input('enter how many names you want to add ')) append_to_list(number_of_names_to_append) if x == 4: pass except: print('TRY AGAIN', '\n', 'please enter a valid option') if x == 4: for i in range(1, 4): x = i if x == 1: index = int(input('enter the index to display name ')) try: display_name(index) except: print('enter an index in range') if x == 2: display_s() if x == 3: number_of_names_to_append = int(input('enter how many names you want to add ')) append_to_list(number_of_names_to_append) namelist = [] x = int(input('enter number of names to enter in list ')) for i in range(x): n = str(input('enter the list element ')) namelist.append(n) namelist.append('\n') names(namelist)
test = { 'name': 'Problem 7', 'points': 1, 'suites': [ { 'cases': [ { 'answer': '103495fc3358e1b6354d1d4a277039e6', 'choices': [ r""" Pair('quote', Pair(A, nil)), where: A is the quoted expression """, r""" [A], where: A is the quoted expression """, r""" Pair(A, nil), where: A is the quoted expression """, r""" A, where: A is the quoted expression """ ], 'hidden': False, 'locked': True, 'question': 'What is the structure of the expressions argument to do_quote_form?' } ], 'scored': False, 'type': 'concept' }, { 'cases': [ { 'code': r""" scm> (quote hello) 506108214132d6cb9c307edb2f9d0f8b # locked scm> 'hello 506108214132d6cb9c307edb2f9d0f8b # locked scm> ''hello 11e53d0ebd5fcb87953db84e824e20c7 # locked # choice: (quote hello) # choice: hello # choice: (hello) # choice: (quote (quote (hello))) scm> (quote (1 2)) e0115c13325291c6a30393eff9777ee4 # locked scm> '(1 2) e0115c13325291c6a30393eff9777ee4 # locked scm> (quote (1 . 2)) 9a8a33947ee1cd41aa91f5f15184c47b # locked scm> '(1 . (2)) e0115c13325291c6a30393eff9777ee4 # locked scm> (car '(1 2 3)) 1d6ef7880cd9b59b64a1f4e1a1e35a12 # locked scm> (cdr '(1 2)) 1c70ebb4f1aabfcbe22f96bda497dd0b # locked scm> (car (car '((1)))) 1d6ef7880cd9b59b64a1f4e1a1e35a12 # locked scm> (quote 3) ed2605996ac3b24d98b27c6d58145f06 # locked scm> (eval (cons 'car '('(4 2)))) 5dc34dbe25d53109ac62b4184b75a40f # locked """, 'hidden': False, 'locked': True } ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" >>> read_line(" (quote x) ") 55894b325c4c2817733a8a1223c79f1e # locked >>> read_line(" 'x ") 55894b325c4c2817733a8a1223c79f1e # locked # choice: Pair('x', nil) # choice: 'x' # choice: Pair('quote', 'x') # choice: Pair('quote', Pair('x', nil)) >>> read_line(" (a b) ") 6e7962ce0515005f1aa1ece26c1f9f99 # locked # choice: Pair('a', Pair('b', nil)) # choice: Pair('quote', Pair(Pair('a', Pair('b', nil)), nil)) # choice: Pair('quote', Pair('a', 'b')) # choice: Pair('quote', Pair('a', Pair('b', nil))) >>> read_line(" '(a b) ") 1af43453acd78705e072b903fe9ce759 # locked # choice: Pair('a', Pair('b', nil)) # choice: Pair('quote', Pair(Pair('a', Pair('b', nil)), nil)) # choice: Pair('quote', Pair('a', 'b')) # choice: Pair('quote', Pair('a', Pair('b', nil))) >>> read_line(" '((a)) ") 6b34a9dd52ff83f52d5e6953f2d7375f # locked # choice: Pair('quote', Pair(Pair('a', nil), nil)) # choice: Pair('quote', Pair(Pair('a', nil), nil), nil) # choice: Pair('quote', Pair(Pair('a'), nil)) # choice: Pair('quote', Pair(Pair('a'), nil), nil) # choice: Pair('quote', Pair(Pair(Pair('a', nil), nil), nil)) """, 'hidden': False, 'locked': True } ], 'scored': True, 'setup': r""" >>> from scheme_reader import * """, 'teardown': '', 'type': 'doctest' } ] }
test = {'name': 'Problem 7', 'points': 1, 'suites': [{'cases': [{'answer': '103495fc3358e1b6354d1d4a277039e6', 'choices': ["\n Pair('quote', Pair(A, nil)), where:\n A is the quoted expression\n ", '\n [A], where:\n A is the quoted expression\n ', '\n Pair(A, nil), where:\n A is the quoted expression\n ', '\n A, where:\n A is the quoted expression\n '], 'hidden': False, 'locked': True, 'question': 'What is the structure of the expressions argument to do_quote_form?'}], 'scored': False, 'type': 'concept'}, {'cases': [{'code': "\n scm> (quote hello)\n 506108214132d6cb9c307edb2f9d0f8b\n # locked\n scm> 'hello\n 506108214132d6cb9c307edb2f9d0f8b\n # locked\n scm> ''hello\n 11e53d0ebd5fcb87953db84e824e20c7\n # locked\n # choice: (quote hello)\n # choice: hello\n # choice: (hello)\n # choice: (quote (quote (hello)))\n scm> (quote (1 2))\n e0115c13325291c6a30393eff9777ee4\n # locked\n scm> '(1 2)\n e0115c13325291c6a30393eff9777ee4\n # locked\n scm> (quote (1 . 2))\n 9a8a33947ee1cd41aa91f5f15184c47b\n # locked\n scm> '(1 . (2))\n e0115c13325291c6a30393eff9777ee4\n # locked\n scm> (car '(1 2 3))\n 1d6ef7880cd9b59b64a1f4e1a1e35a12\n # locked\n scm> (cdr '(1 2))\n 1c70ebb4f1aabfcbe22f96bda497dd0b\n # locked\n scm> (car (car '((1))))\n 1d6ef7880cd9b59b64a1f4e1a1e35a12\n # locked\n scm> (quote 3)\n ed2605996ac3b24d98b27c6d58145f06\n # locked\n scm> (eval (cons 'car '('(4 2))))\n 5dc34dbe25d53109ac62b4184b75a40f\n # locked\n ", 'hidden': False, 'locked': True}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'scheme'}, {'cases': [{'code': '\n >>> read_line(" (quote x) ")\n 55894b325c4c2817733a8a1223c79f1e\n # locked\n >>> read_line(" \'x ")\n 55894b325c4c2817733a8a1223c79f1e\n # locked\n # choice: Pair(\'x\', nil)\n # choice: \'x\'\n # choice: Pair(\'quote\', \'x\')\n # choice: Pair(\'quote\', Pair(\'x\', nil))\n >>> read_line(" (a b) ")\n 6e7962ce0515005f1aa1ece26c1f9f99\n # locked\n # choice: Pair(\'a\', Pair(\'b\', nil))\n # choice: Pair(\'quote\', Pair(Pair(\'a\', Pair(\'b\', nil)), nil))\n # choice: Pair(\'quote\', Pair(\'a\', \'b\'))\n # choice: Pair(\'quote\', Pair(\'a\', Pair(\'b\', nil)))\n >>> read_line(" \'(a b) ")\n 1af43453acd78705e072b903fe9ce759\n # locked\n # choice: Pair(\'a\', Pair(\'b\', nil))\n # choice: Pair(\'quote\', Pair(Pair(\'a\', Pair(\'b\', nil)), nil))\n # choice: Pair(\'quote\', Pair(\'a\', \'b\'))\n # choice: Pair(\'quote\', Pair(\'a\', Pair(\'b\', nil)))\n >>> read_line(" \'((a)) ")\n 6b34a9dd52ff83f52d5e6953f2d7375f\n # locked\n # choice: Pair(\'quote\', Pair(Pair(\'a\', nil), nil))\n # choice: Pair(\'quote\', Pair(Pair(\'a\', nil), nil), nil)\n # choice: Pair(\'quote\', Pair(Pair(\'a\'), nil))\n # choice: Pair(\'quote\', Pair(Pair(\'a\'), nil), nil)\n # choice: Pair(\'quote\', Pair(Pair(Pair(\'a\', nil), nil), nil))\n ', 'hidden': False, 'locked': True}], 'scored': True, 'setup': '\n >>> from scheme_reader import *\n ', 'teardown': '', 'type': 'doctest'}]}
n = int(input()) even_numbers_set = set() odd_numbers_set = set() for current_iteration_count in range(1, n+1): name = input() current_sum = sum([ord(el) for el in name]) // current_iteration_count if current_sum % 2 == 0: even_numbers_set.add(current_sum) else: odd_numbers_set.add(current_sum) sum_evens = sum(even_numbers_set) sum_odds = sum(odd_numbers_set) if sum_evens == sum_odds: modified_set = [str(el) for el in odd_numbers_set.union(even_numbers_set)] print(f", ".join(modified_set)) if sum_odds > sum_evens: modified_set = [str(el) for el in odd_numbers_set.difference(even_numbers_set)] print(f", ".join(modified_set)) if sum_evens > sum_odds: modified_set = [str(el) for el in odd_numbers_set.symmetric_difference(even_numbers_set)] print(f", ".join(modified_set))
n = int(input()) even_numbers_set = set() odd_numbers_set = set() for current_iteration_count in range(1, n + 1): name = input() current_sum = sum([ord(el) for el in name]) // current_iteration_count if current_sum % 2 == 0: even_numbers_set.add(current_sum) else: odd_numbers_set.add(current_sum) sum_evens = sum(even_numbers_set) sum_odds = sum(odd_numbers_set) if sum_evens == sum_odds: modified_set = [str(el) for el in odd_numbers_set.union(even_numbers_set)] print(f', '.join(modified_set)) if sum_odds > sum_evens: modified_set = [str(el) for el in odd_numbers_set.difference(even_numbers_set)] print(f', '.join(modified_set)) if sum_evens > sum_odds: modified_set = [str(el) for el in odd_numbers_set.symmetric_difference(even_numbers_set)] print(f', '.join(modified_set))
# -*- coding: utf-8 -*- r"""Testing code for the (Python) bandit library. Testing is done via the Testify package: https://github.com/Yelp/Testify This package includes: * Test cases/test setup files * Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon` * Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb` * Tests for bandit/bla: :mod:`moe.tests.bandit.bla` This package includes: * Test cases/test setup files * Tests for classes and utils in :mod:`moe.bandit` **Files in this package** * :mod:`moe.tests.bandit.bandit_interface_test`: tests for :mod:`moe.bandit.interfaces.bandit_interface.BanditInterface` * :mod:`moe.tests.bandit.bandit_test_case`: base test case for bandit tests with a simple integration test case * :mod:`moe.tests.bandit.linkers_test`: tests for :mod:`moe.bandit.linkers` * :mod:`moe.tests.bandit.utils_test`: tests for :mod:`moe.bandit.utils` """
"""Testing code for the (Python) bandit library. Testing is done via the Testify package: https://github.com/Yelp/Testify This package includes: * Test cases/test setup files * Tests for bandit/epsilon: :mod:`moe.tests.bandit.epsilon` * Tests for bandit/ucb: :mod:`moe.tests.bandit.ucb` * Tests for bandit/bla: :mod:`moe.tests.bandit.bla` This package includes: * Test cases/test setup files * Tests for classes and utils in :mod:`moe.bandit` **Files in this package** * :mod:`moe.tests.bandit.bandit_interface_test`: tests for :mod:`moe.bandit.interfaces.bandit_interface.BanditInterface` * :mod:`moe.tests.bandit.bandit_test_case`: base test case for bandit tests with a simple integration test case * :mod:`moe.tests.bandit.linkers_test`: tests for :mod:`moe.bandit.linkers` * :mod:`moe.tests.bandit.utils_test`: tests for :mod:`moe.bandit.utils` """
num = int(input("Numero: ")) for i in range(1,13): m = num * i print(num,"X",i,"=",m)
num = int(input('Numero: ')) for i in range(1, 13): m = num * i print(num, 'X', i, '=', m)
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return # use first row as "cols" array, use first column as "rows" array # to do that, first store what needs to be done of first row/col # i.e., do they contain zeroes firstRowZeros = False firstColZeros = False m = len(matrix) n = len(matrix[0]) for i in range(m): if matrix[i][0] == 0: firstColZeros = True break for j in range(n): if matrix[0][j] == 0: firstRowZeros = True break for i in range(1,m): for j in range(1,n): if matrix[i][j] == 0: matrix[0][j] = 0 matrix[i][0] = 0 for i in range(1,m): if matrix[i][0] == 0: for j in range(1,n): matrix[i][j] = 0 for j in range(1,n): if matrix[0][j] == 0: for i in range(1,m): matrix[i][j] = 0 if firstRowZeros: for j in range(n): matrix[0][j] = 0 if firstColZeros: for i in range(m): matrix[i][0] = 0 return ############ O(m+n) space ############ # if not matrix: # return # m = len(matrix) # n = len(matrix[0]) # # O(m+n) space # rows = [False] * m # cols = [False] * n # for i in range(m): # for j in range(n): # if matrix[i][j] == 0: # rows[i] = True # cols[j] = True # for i in range(m): # if rows[i]: # for j in range(n): # matrix[i][j] = 0 # for j in range(n): # if cols[j]: # for i in range(m): # matrix[i][j] = 0 # return
class Solution: def set_zeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return first_row_zeros = False first_col_zeros = False m = len(matrix) n = len(matrix[0]) for i in range(m): if matrix[i][0] == 0: first_col_zeros = True break for j in range(n): if matrix[0][j] == 0: first_row_zeros = True break for i in range(1, m): for j in range(1, n): if matrix[i][j] == 0: matrix[0][j] = 0 matrix[i][0] = 0 for i in range(1, m): if matrix[i][0] == 0: for j in range(1, n): matrix[i][j] = 0 for j in range(1, n): if matrix[0][j] == 0: for i in range(1, m): matrix[i][j] = 0 if firstRowZeros: for j in range(n): matrix[0][j] = 0 if firstColZeros: for i in range(m): matrix[i][0] = 0 return
class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ hash_map = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick hash_map[str(sum)] = hash_map.setdefault(str(sum), 0) + 1 return len(wall) - max(hash_map.values()) if hash_map else len(wall)
class Solution(object): def least_bricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ hash_map = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick hash_map[str(sum)] = hash_map.setdefault(str(sum), 0) + 1 return len(wall) - max(hash_map.values()) if hash_map else len(wall)
# function type class function(object): def __get__(self, obj, objtype): # when used as attribute a function returns a bound method or the function itself object = ___id("%object") method = ___id("%method") NoneType = ___id("%NoneType") if obj is None and objtype is not NoneType: # no object to bind, result is the function itself return self else: # result is a method bound to obj with self as the underlying function new_method = object.__new__(method) method.__init__(new_method, self, obj) return new_method def __getattr__(self, key): # the __call__ attribute is the function itself if ___delta("str=", key, "__call__"): return self else: str = ___id("%str") msg = ___delta("str+", "function object has not attribute ", key, str) raise AttributeError(msg) ___assign("%function", function)
class Function(object): def __get__(self, obj, objtype): object = ___id('%object') method = ___id('%method') none_type = ___id('%NoneType') if obj is None and objtype is not NoneType: return self else: new_method = object.__new__(method) method.__init__(new_method, self, obj) return new_method def __getattr__(self, key): if ___delta('str=', key, '__call__'): return self else: str = ___id('%str') msg = ___delta('str+', 'function object has not attribute ', key, str) raise attribute_error(msg) ___assign('%function', function)
class GenerationTemplate: def __init__( self, source_path: str, template: str, group_template: str, unit_template: str ): self.source_path: str = source_path self.template: str = template self.group_template: str = group_template self.unit_template: str = unit_template
class Generationtemplate: def __init__(self, source_path: str, template: str, group_template: str, unit_template: str): self.source_path: str = source_path self.template: str = template self.group_template: str = group_template self.unit_template: str = unit_template
#!/usr/bin/env python3 # # eask: # The initialization program (your puzzle input) can either update the bitmask # or write a value to memory. Values and memory addresses are both 36-bit # unsigned integers. For example, ignoring bitmasks for a moment, a line # like mem[8] = 11 would write the value 11 to memory address 8. # The bitmask is always given as a string of 36 bits, written with the most # significant bit (representing 2^35) on the left and the least significant # bit (2^0, that is, the 1s bit) on the right. The current bitmask is applied # to values immediately before they are written to memory: a 0 or 1 overwrites # the corresponding bit in the value, while an X leaves the bit in the value # unchanged. For example: # - value: 000000000000000000000000000000001011 (decimal 11) # - mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X # - result: 000000000000000000000000000001001001 (decimal 73) # Execute the initialization program. What is the sum of all values left # in memory after it completes? (Do not truncate the sum to 36 bits.) # # Solution: # We read and process input file line by line, tearing each line as instruction # to be executed. If the instruction is mask, we just save the value as is # to a string variable. If the instruction is about writing a value to memory # we read the address as string, which will become identifier (key) in the # memory map (dictionary), and the value to write as integer. Then we process # every bit from the mask string, iterating from the right side with counting # the position (enumerate -> i). If the mask bit is X, we do not perform any # change. If it is 1, we do binary sum of the current value to write with # value 1 shifted left by i-bits. If the mask bit is 0, we produce a value # of all ones, except on a given i-bit (negation of 1 left shifted by i-bits), # and multiply it binary-wise (and) with the value to write to memory. # Then we just save the final value to a dictionary with address as a key. # Finally we sum all values registered in the dictionary. # INPUT_FILE = 'input.txt' def main(): instructions = [line.strip('\n') for line in open(INPUT_FILE, 'r')] mask = None memory = {} for instruction in instructions: if instruction.startswith('mask = '): mask = instruction.split(' = ')[1] elif instruction.startswith('mem['): address, value = instruction.split(' = ') address = address[4:-1] value = int(value) for i, bit in enumerate(mask[::-1]): if bit == 'X': continue elif bit == '0': value = value & ~(1 << i) elif bit == '1': value = value | (1 << i) else: print('BIT VALUE ERROR') return 1 memory[address] = int(value) else: print('VALUE ERROR') return 1 print(sum(memory.values())) if __name__ == '__main__': main()
input_file = 'input.txt' def main(): instructions = [line.strip('\n') for line in open(INPUT_FILE, 'r')] mask = None memory = {} for instruction in instructions: if instruction.startswith('mask = '): mask = instruction.split(' = ')[1] elif instruction.startswith('mem['): (address, value) = instruction.split(' = ') address = address[4:-1] value = int(value) for (i, bit) in enumerate(mask[::-1]): if bit == 'X': continue elif bit == '0': value = value & ~(1 << i) elif bit == '1': value = value | 1 << i else: print('BIT VALUE ERROR') return 1 memory[address] = int(value) else: print('VALUE ERROR') return 1 print(sum(memory.values())) if __name__ == '__main__': main()
class Email: client = None optional_arguments = [ "antispamlevel", "antivirus", "autorespond", "autorespondsaveemail", "autorespondmessage", "password", "quota" ] def __init__(self, client): self.client = client def overview(self): return self.client.get("/email/overview") def globalquota(self, quota = None): data = None if(quota == None): data = self.client.post_request("/email/globalquota") else: data = self.client.post_request("/email/globalquota", { "globalquota": quota }) return data["globalquota"] def list(self, domain): data = self.client.get_request("/email/list", { "domainname": domain }) return { "accounts": data["list"]["emailaccounts"], "aliases": data["list"]["emailaliases"] } def createaccount(self, email, password, extra = None): if(extra != None): for k in extra: if k not in self.optional_arguments: raise Exception( "Invalid parameter: %s " % k) params = extra else: params = {} if(email is None or email == ""): raise Exception("Please supply email address") if(password is None or password == ""): raise Exception("Please supply password") params["emailaccount"] = email params["password"] = password data = self.client.post_request("/email/createaccount", params) return data["emailaccount"] def editaccount(self, email, params): for k in params: if k not in self.optional_arguments: raise Exception("Invalid parameter: %s" % k) if(email is None or email == ""): raise Exception("Please supply email address") params["emailaccount"] = email data = self.client.post_request("/email/editaccount", params) return data["emailaccount"] def delete(self, email): if(email is None or email == ""): raise Exception("Please supply email address") self.client.post_request("/email/delete", { "email": email }) def quota(self, email): if(email is None or email == ""): raise Exception("please supply email address") data = self.client.post_request("/email/quota", { "emailaccount": email }) return data["emailaccount"]
class Email: client = None optional_arguments = ['antispamlevel', 'antivirus', 'autorespond', 'autorespondsaveemail', 'autorespondmessage', 'password', 'quota'] def __init__(self, client): self.client = client def overview(self): return self.client.get('/email/overview') def globalquota(self, quota=None): data = None if quota == None: data = self.client.post_request('/email/globalquota') else: data = self.client.post_request('/email/globalquota', {'globalquota': quota}) return data['globalquota'] def list(self, domain): data = self.client.get_request('/email/list', {'domainname': domain}) return {'accounts': data['list']['emailaccounts'], 'aliases': data['list']['emailaliases']} def createaccount(self, email, password, extra=None): if extra != None: for k in extra: if k not in self.optional_arguments: raise exception('Invalid parameter: %s ' % k) params = extra else: params = {} if email is None or email == '': raise exception('Please supply email address') if password is None or password == '': raise exception('Please supply password') params['emailaccount'] = email params['password'] = password data = self.client.post_request('/email/createaccount', params) return data['emailaccount'] def editaccount(self, email, params): for k in params: if k not in self.optional_arguments: raise exception('Invalid parameter: %s' % k) if email is None or email == '': raise exception('Please supply email address') params['emailaccount'] = email data = self.client.post_request('/email/editaccount', params) return data['emailaccount'] def delete(self, email): if email is None or email == '': raise exception('Please supply email address') self.client.post_request('/email/delete', {'email': email}) def quota(self, email): if email is None or email == '': raise exception('please supply email address') data = self.client.post_request('/email/quota', {'emailaccount': email}) return data['emailaccount']
class MyArray: def __init__(self, *args): self.elems = list(args) def __repr__(self): return str(self.elems) def __getitem__(self, index): return self.elems[index] def __setitem__(self, index, value): self.elems[index] = value def __delitem__(self, index): del self.elems[index] def __contains__(self, item): return item in self.elems delim = '*' * 20 m_a = MyArray(*(range(0, 20, 3))) print('MyArray m_a -->', m_a) print(delim) ind = 2 print('m_a[', ind, '] = ', m_a[ind]) print(delim) new_val = 42 print("setting value ", new_val, " to index ", ind) m_a[ind] = new_val print('MyArray m_a -->', m_a) print(delim) ind = 0 print("delete item from index", ind) del m_a[ind] print('MyArray m_a -->', m_a) print(delim) print("checking if ", new_val, " in m_a") print(new_val in m_a) print('MyArray m_a -->', m_a) print(delim)
class Myarray: def __init__(self, *args): self.elems = list(args) def __repr__(self): return str(self.elems) def __getitem__(self, index): return self.elems[index] def __setitem__(self, index, value): self.elems[index] = value def __delitem__(self, index): del self.elems[index] def __contains__(self, item): return item in self.elems delim = '*' * 20 m_a = my_array(*range(0, 20, 3)) print('MyArray m_a -->', m_a) print(delim) ind = 2 print('m_a[', ind, '] = ', m_a[ind]) print(delim) new_val = 42 print('setting value ', new_val, ' to index ', ind) m_a[ind] = new_val print('MyArray m_a -->', m_a) print(delim) ind = 0 print('delete item from index', ind) del m_a[ind] print('MyArray m_a -->', m_a) print(delim) print('checking if ', new_val, ' in m_a') print(new_val in m_a) print('MyArray m_a -->', m_a) print(delim)
n = input() def odd_even(a): odd = 0 even = 0 for i in range(len(a)): if int(a[i]) % 2 == 0: even += int(a[i]) else: odd += int(a[i]) return (f'Odd sum = {odd}, Even sum = {even}') print(odd_even(n))
n = input() def odd_even(a): odd = 0 even = 0 for i in range(len(a)): if int(a[i]) % 2 == 0: even += int(a[i]) else: odd += int(a[i]) return f'Odd sum = {odd}, Even sum = {even}' print(odd_even(n))
""" Entradas numero_hombres-->int-->p_h numero_mujeres-->int-->p_m salidas Porcentaje de hombres-->float-->p_h Porcentaje de mujeres-->float-->p_m """ numero_hombres=int(input("digite total de hombres: ")) numero_mujeres=int(input("digite total de mujeres: ")) #caja negra p_h=numero_hombres*100/(numero_hombres+numero_mujeres)#float p_m=numero_mujeres*100/(numero_hombres+numero_mujeres)#float #salida print("porcentaje de hombres:", p_h, "y el porcentaje de mujeres: ",p_m)
""" Entradas numero_hombres-->int-->p_h numero_mujeres-->int-->p_m salidas Porcentaje de hombres-->float-->p_h Porcentaje de mujeres-->float-->p_m """ numero_hombres = int(input('digite total de hombres: ')) numero_mujeres = int(input('digite total de mujeres: ')) p_h = numero_hombres * 100 / (numero_hombres + numero_mujeres) p_m = numero_mujeres * 100 / (numero_hombres + numero_mujeres) print('porcentaje de hombres:', p_h, 'y el porcentaje de mujeres: ', p_m)
load("//internal/jsweet_transpile:jsweet_transpile.bzl", "jsweet_transpile","TRANSPILE_ATTRS") load("@npm_bazel_typescript//:index.bzl", "ts_library") JWSEET_TRANSPILE_KEYS = TRANSPILE_ATTRS.keys() def jsweet_ts_lib(name, **kwargs): transpile_args = dict() for transpile_key in JWSEET_TRANSPILE_KEYS: if transpile_key in kwargs: value = kwargs.pop(transpile_key) if value != None: transpile_args[transpile_key] = value jsweet_transpiled_name = name + "_jsweet_transpiled" jsweet_transpile( name = jsweet_transpiled_name, **transpile_args ) jsweet_ts_sources_name = name + "_jsweet_ts_sources" native.filegroup( name = jsweet_ts_sources_name, srcs = [":" + jsweet_transpiled_name], output_group = "ts_sources" ) ts_library( name = name, srcs = [":" + jsweet_ts_sources_name], **kwargs # The remaining arguments go to `ts_library` )
load('//internal/jsweet_transpile:jsweet_transpile.bzl', 'jsweet_transpile', 'TRANSPILE_ATTRS') load('@npm_bazel_typescript//:index.bzl', 'ts_library') jwseet_transpile_keys = TRANSPILE_ATTRS.keys() def jsweet_ts_lib(name, **kwargs): transpile_args = dict() for transpile_key in JWSEET_TRANSPILE_KEYS: if transpile_key in kwargs: value = kwargs.pop(transpile_key) if value != None: transpile_args[transpile_key] = value jsweet_transpiled_name = name + '_jsweet_transpiled' jsweet_transpile(name=jsweet_transpiled_name, **transpile_args) jsweet_ts_sources_name = name + '_jsweet_ts_sources' native.filegroup(name=jsweet_ts_sources_name, srcs=[':' + jsweet_transpiled_name], output_group='ts_sources') ts_library(name=name, srcs=[':' + jsweet_ts_sources_name], **kwargs)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() output = dummy # l1_eol = False # l2_eol = False while 1: # if l1.next == None: # # output.next = l2 # # break # l1_eol = True # if l2.next == None: # # output.next = l1 # # break # l2_eol = True if l1 is None: output.next = l2 break if l2 is None: output.next = l1 break if l1.val < l2.val: output.next = l1 l1= l1.next # print("l1 val ",l1.val) # break else: output.next = l2 l2= l2.next # print("l2 val ",l2.val) # break output = output.next return dummy.next class Solution2: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 == None: return l2 elif l2 == None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
class Solution: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = list_node() output = dummy while 1: if l1 is None: output.next = l2 break if l2 is None: output.next = l1 break if l1.val < l2.val: output.next = l1 l1 = l1.next else: output.next = l2 l2 = l2.next output = output.next return dummy.next class Solution2: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 == None: return l2 elif l2 == None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
text = """first row second row third row""" print(text)
text = 'first row\nsecond row\nthird row' print(text)
# WSADMIN SCRIPT TO SHOW USEFUL ADMINTASK COMMANDS AND HELP TOWARDS THEM # Santiago Garcia Arango # Command: # wsadmin.sh -lang jython -f /tmp/test.py print("***** Showing AdminTask help *****") print(AdminTask.help()) print("***** Showing AdminTask commands *****") print(AdminTask.help("-commands")) print("***** Showing AdminTask commands with <*something*> pattern *****") print(AdminTask.help("-commands", "*server*")) print(AdminTask.help("-commands", "*jvm*")) print(AdminTask.help("-commands", "*user*")) print("***** Showing AdminTask command groups *****") print(AdminTask.help("-commandGroups")) print("***** Showing AdminTask specific command help (some examples) *****") print(AdminTask.help("listNodes")) print(AdminTask.help("listServers")) print(AdminTask.help("showServerInfo")) print(AdminTask.help("setJVMProperties")) print(AdminTask.help("showJVMProperties")) print(AdminTask.help("createAuthDataEntry")) print(AdminTask.help("modifyAuthDataEntry")) print(AdminTask.help("modifyWMQQueue")) print(AdminTask.help("createWMQQueue")) print(AdminTask.help("listUserIDsOfAuthorizationGroup")) print(AdminTask.help("listAuditUserIDsOfAuthorizationGroup")) print(AdminTask.help("createUser"))
print('***** Showing AdminTask help *****') print(AdminTask.help()) print('***** Showing AdminTask commands *****') print(AdminTask.help('-commands')) print('***** Showing AdminTask commands with <*something*> pattern *****') print(AdminTask.help('-commands', '*server*')) print(AdminTask.help('-commands', '*jvm*')) print(AdminTask.help('-commands', '*user*')) print('***** Showing AdminTask command groups *****') print(AdminTask.help('-commandGroups')) print('***** Showing AdminTask specific command help (some examples) *****') print(AdminTask.help('listNodes')) print(AdminTask.help('listServers')) print(AdminTask.help('showServerInfo')) print(AdminTask.help('setJVMProperties')) print(AdminTask.help('showJVMProperties')) print(AdminTask.help('createAuthDataEntry')) print(AdminTask.help('modifyAuthDataEntry')) print(AdminTask.help('modifyWMQQueue')) print(AdminTask.help('createWMQQueue')) print(AdminTask.help('listUserIDsOfAuthorizationGroup')) print(AdminTask.help('listAuditUserIDsOfAuthorizationGroup')) print(AdminTask.help('createUser'))
def dummy_function(a): return a DUMMY_GLOBAL_CONSTANT_0 = 'FOO'; DUMMY_GLOBAL_CONSTANT_1 = 'BAR';
def dummy_function(a): return a dummy_global_constant_0 = 'FOO' dummy_global_constant_1 = 'BAR'
# Matrix solver (TDMA) # parameters required: # n: number of unknowns (length of x) # a: coefficient matrix # b: RHS/constant array # return output: # b: solution array def solve_TDMA(n, a, b): # forward substitution a[0][2] = -a[0][2] / a[0][1] b[0] = b[0] / a[0][1] for i in range(1, n): a[i][2] = -a[i][2] / (a[i][1] + a[i][0] * a[i - 1][2]) b[i] = (b[i] - a[i][0] * b[i - 1]) / (a[i][1] + a[i][0] * a[i - 1][2]) # backward elimination for i in range(n - 2, -1, -1): b[i] = a[i][2] * b[i + 1] + b[i] return b
def solve_tdma(n, a, b): a[0][2] = -a[0][2] / a[0][1] b[0] = b[0] / a[0][1] for i in range(1, n): a[i][2] = -a[i][2] / (a[i][1] + a[i][0] * a[i - 1][2]) b[i] = (b[i] - a[i][0] * b[i - 1]) / (a[i][1] + a[i][0] * a[i - 1][2]) for i in range(n - 2, -1, -1): b[i] = a[i][2] * b[i + 1] + b[i] return b
allowed_request_categories = [ 'stock', 'mutual_fund', 'intraday', 'history', 'history_multi_single_day', 'forex', 'forex_history', 'forex_single_day', 'stock_search' ]
allowed_request_categories = ['stock', 'mutual_fund', 'intraday', 'history', 'history_multi_single_day', 'forex', 'forex_history', 'forex_single_day', 'stock_search']
#Encontrar el menor valor en un array #con busqueda binaria def menor (array): l=0 r=len(array)-1 while l<=r: mid = l+(r-l)//2 if array[mid] > array[r]: l=mid+1 if array[mid]< array[r]: r=mid if r==l or mid==0: return array[r] nums=[15,18,25,35,1,3,12] print(menor(nums))
def menor(array): l = 0 r = len(array) - 1 while l <= r: mid = l + (r - l) // 2 if array[mid] > array[r]: l = mid + 1 if array[mid] < array[r]: r = mid if r == l or mid == 0: return array[r] nums = [15, 18, 25, 35, 1, 3, 12] print(menor(nums))
def fun(s): ans = 0 o = 0 c = 0 for i in s: if(i=="("): o+=1 elif(i==")"): c+=1 if(c>o): c-=1 o+=1 ans+=1 return ans t = int(input()) for _ in range(t): n = int(input()) s = input() ans = 0 N = 10**9+7 value = ((n+1)*n)//2 value = pow(value,N-2,N) print(value) for i in range(n): ans+=fun(s[i:]) print((ans*value)%N)
def fun(s): ans = 0 o = 0 c = 0 for i in s: if i == '(': o += 1 elif i == ')': c += 1 if c > o: c -= 1 o += 1 ans += 1 return ans t = int(input()) for _ in range(t): n = int(input()) s = input() ans = 0 n = 10 ** 9 + 7 value = (n + 1) * n // 2 value = pow(value, N - 2, N) print(value) for i in range(n): ans += fun(s[i:]) print(ans * value % N)
for _ in range(int(input())): s = set() n = input().split() while True: m = input().split() if m[-1] == "say?": break s.add(m[-1]) for i in n: if i not in s: print(i, end=' ') print()
for _ in range(int(input())): s = set() n = input().split() while True: m = input().split() if m[-1] == 'say?': break s.add(m[-1]) for i in n: if i not in s: print(i, end=' ') print()
# Copyright (c) 2018 Stephen Bunn <stephen@bunn.io> # MIT License <https://opensource.org/licenses/MIT> __name__ = "standardfile" __repo__ = "https://github.com/stephen-bunn/standardfile" __description__ = "A library for accessing and interacting with a Standard File server." __version__ = "0.0.0" __author__ = "Stephen Bunn" __contact__ = "stephen@bunn.io" __license__ = "MIT License"
__name__ = 'standardfile' __repo__ = 'https://github.com/stephen-bunn/standardfile' __description__ = 'A library for accessing and interacting with a Standard File server.' __version__ = '0.0.0' __author__ = 'Stephen Bunn' __contact__ = 'stephen@bunn.io' __license__ = 'MIT License'
""" LIST: CHUNKING """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' # Example of Chunking (Grouping an item with its next) def chunks(list, number): # Requires a list and a number for index in range(0, len(list), number): # For every # index inside of a number range starting at '0' # and running to the length of the list, with steps # of a chosen 'number' yield list[index : index + number] # Yield returns # a 'generator' object, so we cast the result to a # 'list' and will return 'list slices' ranging from # the chosen 'index' to the chosen 'index' + chosen # 'number' # Exemplar list itemList = [0, 1, 2, 3, 4, 5] # A simple list of numbers to # parse with our 'chunks' definition count = 2 # A number which we want to chunk to. We choose '2' # which will result in sublists of: [[0, 1], [2, 3], [4,5]] chunksList = chunks(itemList, count) # Here we call our new # 'chunks' definition on our 'itemList' and with our 'count' # then push those results to our variable called 'chunksList' OUT = chunksList # Returning our chunked data
""" LIST: CHUNKING """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' def chunks(list, number): for index in range(0, len(list), number): yield list[index:index + number] item_list = [0, 1, 2, 3, 4, 5] count = 2 chunks_list = chunks(itemList, count) out = chunksList
class Dataset(object): def __init__(self, env_spec): self._env_spec = env_spec def get_batch(self, batch_size, horizon): raise NotImplementedError def get_batch_iterator(self, batch_size, horizon, randomize_order=False, is_tf=True): raise NotImplementedError
class Dataset(object): def __init__(self, env_spec): self._env_spec = env_spec def get_batch(self, batch_size, horizon): raise NotImplementedError def get_batch_iterator(self, batch_size, horizon, randomize_order=False, is_tf=True): raise NotImplementedError
# -------------- ##File path for the file file_path def read_file(path): f=open(path,'r') sentence=f.readline() f.close() return sentence sample_message=read_file(file_path) #Code starts here # -------------- #Code starts here file_path_1 file_path_2 message_1=read_file(file_path_1) message_2=read_file(file_path_2) message_1,message_2 def fuse_msg(message_a,message_b): ima=int(message_a) imb=int(message_b) quotient=int(imb/ima) return str(quotient) #fuse_msg(message_1,message_2) secret_msg_1=fuse_msg(message_1,message_2) # -------------- #Code starts here message_3=read_file(file_path_3) message_3 def substitute_msg(message_c): sub="Data Scientist" if message_c is 'Red':sub='Army General' if message_c is 'Green':sub='Data Scientist' if message_c is 'Blue':sub='Marine Biologist' return sub secret_msg_2=substitute_msg(message_3) secret_msg_2 # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 message_4=read_file(file_path_4) message_5=read_file(file_path_5) message_4,message_5 def compare_msg(message_d,message_e): alist=message_d.split() blist=message_e.split() c_list=(i for i in alist+blist if i not in blist) final_msg=" ".join(c_list) return final_msg secret_msg_3=compare_msg(message_4,message_5) secret_msg_3 # -------------- #Code starts here message_6=read_file(file_path_6) message_6 def extract_msg(message_f): a_list=message_f.split() even_word= lambda x:(len(x)%2==0) b_list=filter(even_word,a_list) print(b_list) final_msg = " ".join(b_list) return final_msg secret_msg_4=extract_msg(message_6) # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] secret_msg=" ".join(message_parts) final_path= user_data_dir + '/secret_message.txt' def write_file(secret_msg,path): file1=open(path,'a+') file1.write(secret_msg) file1.close() write_file(secret_msg,final_path) secret_msg
file_path def read_file(path): f = open(path, 'r') sentence = f.readline() f.close() return sentence sample_message = read_file(file_path) file_path_1 file_path_2 message_1 = read_file(file_path_1) message_2 = read_file(file_path_2) (message_1, message_2) def fuse_msg(message_a, message_b): ima = int(message_a) imb = int(message_b) quotient = int(imb / ima) return str(quotient) secret_msg_1 = fuse_msg(message_1, message_2) message_3 = read_file(file_path_3) message_3 def substitute_msg(message_c): sub = 'Data Scientist' if message_c is 'Red': sub = 'Army General' if message_c is 'Green': sub = 'Data Scientist' if message_c is 'Blue': sub = 'Marine Biologist' return sub secret_msg_2 = substitute_msg(message_3) secret_msg_2 file_path_4 file_path_5 message_4 = read_file(file_path_4) message_5 = read_file(file_path_5) (message_4, message_5) def compare_msg(message_d, message_e): alist = message_d.split() blist = message_e.split() c_list = (i for i in alist + blist if i not in blist) final_msg = ' '.join(c_list) return final_msg secret_msg_3 = compare_msg(message_4, message_5) secret_msg_3 message_6 = read_file(file_path_6) message_6 def extract_msg(message_f): a_list = message_f.split() even_word = lambda x: len(x) % 2 == 0 b_list = filter(even_word, a_list) print(b_list) final_msg = ' '.join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) message_parts = [secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] secret_msg = ' '.join(message_parts) final_path = user_data_dir + '/secret_message.txt' def write_file(secret_msg, path): file1 = open(path, 'a+') file1.write(secret_msg) file1.close() write_file(secret_msg, final_path) secret_msg
class Agent(object): def __init__(self, id): self.id = id def act(self, state): raise NotImplementedError() def transition(self, state, actions, new_state, reward): pass
class Agent(object): def __init__(self, id): self.id = id def act(self, state): raise not_implemented_error() def transition(self, state, actions, new_state, reward): pass
n = int(input()) arr = [list(map(int,input().split())) for i in range(n)] ans = [0]*n ans[0] = int(pow((arr[0][1]*arr[0][2])//arr[1][2], 0.5)) for i in range(1,n): ans[i]=(arr[0][i]//ans[0]) print(*ans)
n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] ans = [0] * n ans[0] = int(pow(arr[0][1] * arr[0][2] // arr[1][2], 0.5)) for i in range(1, n): ans[i] = arr[0][i] // ans[0] print(*ans)
class Relaxation: def __init__(self): self.predecessors = {} def buildPath(self, graph, node_from, node_to): nodes = [] current = node_to while current != node_from: if self.predecessors[current] == current and current != node_from: return None nodes.append(current) current = self.predecessors[current] nodes.append(node_from) nodes.reverse() return nodes
class Relaxation: def __init__(self): self.predecessors = {} def build_path(self, graph, node_from, node_to): nodes = [] current = node_to while current != node_from: if self.predecessors[current] == current and current != node_from: return None nodes.append(current) current = self.predecessors[current] nodes.append(node_from) nodes.reverse() return nodes
''' It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transactions during the month of February, 2015. The first DataFrame describes Hardware transactions, the second describes Software transactions, and the third, Service transactions. Your task is to concatenate the DataFrames horizontally and to create a MultiIndex on the columns. From there, you can summarize the resulting DataFrame and slice some information from it. ''' # Concatenate dataframes: february february = pd.concat(dataframes, axis=1, keys=['Hardware', 'Software', 'Service']) # Print february.info() print(february.info()) # Assign pd.IndexSlice: idx idx = pd.IndexSlice # Create the slice: slice_2_8 slice_2_8 = february.loc['Feb. 2, 2015':'Feb. 8, 2015', idx[:, 'Company']] # Print slice_2_8 print(slice_2_8)
""" It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transactions during the month of February, 2015. The first DataFrame describes Hardware transactions, the second describes Software transactions, and the third, Service transactions. Your task is to concatenate the DataFrames horizontally and to create a MultiIndex on the columns. From there, you can summarize the resulting DataFrame and slice some information from it. """ february = pd.concat(dataframes, axis=1, keys=['Hardware', 'Software', 'Service']) print(february.info()) idx = pd.IndexSlice slice_2_8 = february.loc['Feb. 2, 2015':'Feb. 8, 2015', idx[:, 'Company']] print(slice_2_8)
"""Top-level package for Python Boilerplate.""" __author__ = """Mathanraj Sharma""" __email__ = "rvmmathanraj@gmail.com" __version__ = "0.1.0"
"""Top-level package for Python Boilerplate.""" __author__ = 'Mathanraj Sharma' __email__ = 'rvmmathanraj@gmail.com' __version__ = '0.1.0'
""" namecom: result_models.py Defines response result models for the api. Tianhong Chu [https://github.com/CtheSky] License: MIT """ class RequestResult(object): """Base class for Response class. Attributes ---------- resp : http response from requests.Response status_code : int http status code headers : MutableMapping) http response headers from requests.Response """ def __init__(self, resp): self.resp = resp self.status_code = resp.status_code self.headers = resp.headers class ListRecordsResult(RequestResult): """Response class for ListRecords method. Attributes ---------- records : [] :class:`~namecom.Record` list of Records nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListRecordsResult, self).__init__(resp) self.records = [] self.nextPage = None self.lastPage = None class GetRecordResult(RequestResult): """Response class for GetRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(GetRecordResult, self).__init__(resp) self.record = None class CreateRecordResult(RequestResult): """Response class for CreateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(CreateRecordResult, self).__init__(resp) self.record = None class UpdateRecordResult(RequestResult): """Response class for UpdateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(UpdateRecordResult, self).__init__(resp) self.record = None class DeleteRecordResult(RequestResult): """Response class for DeleteRecord method.""" class ListDnssecsResult(RequestResult): """Response class for ListDnssecs method. Attributes ---------- dnssecs : [] :class:`~namecom.DNSSEC` list of DNSSEC nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDnssecsResult, self).__init__(resp) self.dnssecs = [] self.nextPage = None self.lastPage = None class GetDnssecResult(RequestResult): """Response class for GetDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(GetDnssecResult, self).__init__(resp) self.dnssec = None class CreateDnssecResult(RequestResult): """Response class for CreateDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(CreateDnssecResult, self).__init__(resp) self.dnssec = None class DeleteDnssecResult(RequestResult): """Response class for DeleteDnssec method.""" class ListDomainsResult(RequestResult): """Response class for ListDomains method. Attributes ---------- domains : [] :class:`~namecom.Domain` list of Domains nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDomainsResult, self).__init__(resp) self.domains = [] self.nextPage = None self.lastPage = None class GetDomainResult(RequestResult): """Response class for GetDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(GetDomainResult, self).__init__(resp) self.domain = None class SearchResult(RequestResult): """Response class for Search method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(SearchResult, self).__init__(resp) self.results = [] class CreateDomainResult(RequestResult): """Response class for CreateDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class EnableAutorenewResult(RequestResult): """Response class for EnableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(EnableAutorenewResult, self).__init__(resp) self.domain = None class DisableAutorenewResult(RequestResult): """Response class for DisableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(DisableAutorenewResult, self).__init__(resp) self.domain = None class SetNameserversResult(RequestResult): """Response class for SetNameservers method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetNameserversResult, self).__init__(resp) self.domain = None class SetContactsResult(RequestResult): """Response class for SetContacts method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetContactsResult, self).__init__(resp) self.domain = None class RenewDomainResult(RequestResult): """Response class for RenewDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(RenewDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class PurchasePrivacyResult(RequestResult): """Response class for PurchasePrivacy method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(PurchasePrivacyResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class GetAuthCodeForDomainResult(RequestResult): """Response class for GetAuthCodeForDomain method. Attributes ---------- authCode : str AuthCode is the authorization code needed to transfer a domain to another registrar """ def __init__(self, resp): super(GetAuthCodeForDomainResult, self).__init__(resp) self.authCode = None class LockDomainResult(RequestResult): """Response class for LockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(LockDomainResult, self).__init__(resp) self.domain = None class UnlockDomainResult(RequestResult): """Response class for UnlockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(UnlockDomainResult, self).__init__(resp) self.domain = None class CheckAvailabilityResult(RequestResult): """Response class for CheckAvailability method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(CheckAvailabilityResult, self).__init__(resp) self.results = [] class SearchStreamResult(RequestResult): """Response class for SearchStream method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` a generator yielding of DomainSearchResult """ def __init__(self, resp): super(SearchStreamResult, self).__init__(resp) self.results = [] class ListEmailForwardingsResult(RequestResult): """Response class for ListEmailForwardings method. Attributes ---------- email_forwardings : [] :class:`~namecom.EmailForwarding` list of EmailForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListEmailForwardingsResult, self).__init__(resp) self.email_forwardings = [] self.nextPage = None self.lastPage = None class GetEmailForwardingResult(RequestResult): """Response class for GetEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(GetEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class CreateEmailForwardingResult(RequestResult): """Response class for CreateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(CreateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class UpdateEmailForwardingResult(RequestResult): """Response class for UpdateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(UpdateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class DeleteEmailForwardingResult(RequestResult): """Response class for DeleteEmailForwarding method.""" class ListTransfersResult(RequestResult): """Response class for ListTransfers method. Attributes ---------- transfers : [] :class:`~namecom.Transfer` list of Transfer nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListTransfersResult, self).__init__(resp) self.transfers = [] self.nextPage = None self.lastPage = None class GetTransferResult(RequestResult): """Response class for GetTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(GetTransferResult, self).__init__(resp) self.transfer = None class CreateTransferResult(RequestResult): """Response class for CreateTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateTransferResult, self).__init__(resp) self.transfer = None self.order = None self.totalPaid = None class CancelTransferResult(RequestResult): """Response class for CancelTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(CancelTransferResult, self).__init__(resp) self.transfer = None class ListURLForwardingsResult(RequestResult): """Response class for ListURLForwardins method. Attributes ---------- url_forwardings : [] :class:`~namecom.URLForwarding` list of URLForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListURLForwardingsResult, self).__init__(resp) self.url_forwardings = [] self.nextPage = None self.lastPage = None class GetURLForwardingResult(RequestResult): """Response class for GetURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(GetURLForwardingResult, self).__init__(resp) self.url_forwarding = None class CreateURLForwardingResult(RequestResult): """Response class for CreateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(CreateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class UpdateURLForwardingResult(RequestResult): """Response class for UpdateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(UpdateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class DeleteURLForwardingResult(RequestResult): """Response class for DeleteURLForwarding method.""" class ListVanityNameserversResult(RequestResult): """Response class for ListVanityNameservers method. Attributes ---------- vanityNameservers : [] :class:`~namecom.VanityNameserver` list of VanityNameserver nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListVanityNameserversResult, self).__init__(resp) self.vanityNameservers = [] self.nextPage = None self.lastPage = None class GetVanityNameserverResult(RequestResult): """Response class for GetVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(GetVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class CreateVanityNameserverResult(RequestResult): """Response class for CreateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(CreateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class UpdateVanityNameserverResult(RequestResult): """Response class for UpdateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(UpdateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class DeleteVanityNameserverResult(RequestResult): """Response class for DeleteVanityNameserver method."""
""" namecom: result_models.py Defines response result models for the api. Tianhong Chu [https://github.com/CtheSky] License: MIT """ class Requestresult(object): """Base class for Response class. Attributes ---------- resp : http response from requests.Response status_code : int http status code headers : MutableMapping) http response headers from requests.Response """ def __init__(self, resp): self.resp = resp self.status_code = resp.status_code self.headers = resp.headers class Listrecordsresult(RequestResult): """Response class for ListRecords method. Attributes ---------- records : [] :class:`~namecom.Record` list of Records nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListRecordsResult, self).__init__(resp) self.records = [] self.nextPage = None self.lastPage = None class Getrecordresult(RequestResult): """Response class for GetRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(GetRecordResult, self).__init__(resp) self.record = None class Createrecordresult(RequestResult): """Response class for CreateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(CreateRecordResult, self).__init__(resp) self.record = None class Updaterecordresult(RequestResult): """Response class for UpdateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(UpdateRecordResult, self).__init__(resp) self.record = None class Deleterecordresult(RequestResult): """Response class for DeleteRecord method.""" class Listdnssecsresult(RequestResult): """Response class for ListDnssecs method. Attributes ---------- dnssecs : [] :class:`~namecom.DNSSEC` list of DNSSEC nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDnssecsResult, self).__init__(resp) self.dnssecs = [] self.nextPage = None self.lastPage = None class Getdnssecresult(RequestResult): """Response class for GetDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(GetDnssecResult, self).__init__(resp) self.dnssec = None class Creatednssecresult(RequestResult): """Response class for CreateDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(CreateDnssecResult, self).__init__(resp) self.dnssec = None class Deletednssecresult(RequestResult): """Response class for DeleteDnssec method.""" class Listdomainsresult(RequestResult): """Response class for ListDomains method. Attributes ---------- domains : [] :class:`~namecom.Domain` list of Domains nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDomainsResult, self).__init__(resp) self.domains = [] self.nextPage = None self.lastPage = None class Getdomainresult(RequestResult): """Response class for GetDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(GetDomainResult, self).__init__(resp) self.domain = None class Searchresult(RequestResult): """Response class for Search method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(SearchResult, self).__init__(resp) self.results = [] class Createdomainresult(RequestResult): """Response class for CreateDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class Enableautorenewresult(RequestResult): """Response class for EnableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(EnableAutorenewResult, self).__init__(resp) self.domain = None class Disableautorenewresult(RequestResult): """Response class for DisableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(DisableAutorenewResult, self).__init__(resp) self.domain = None class Setnameserversresult(RequestResult): """Response class for SetNameservers method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetNameserversResult, self).__init__(resp) self.domain = None class Setcontactsresult(RequestResult): """Response class for SetContacts method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetContactsResult, self).__init__(resp) self.domain = None class Renewdomainresult(RequestResult): """Response class for RenewDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(RenewDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class Purchaseprivacyresult(RequestResult): """Response class for PurchasePrivacy method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(PurchasePrivacyResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class Getauthcodefordomainresult(RequestResult): """Response class for GetAuthCodeForDomain method. Attributes ---------- authCode : str AuthCode is the authorization code needed to transfer a domain to another registrar """ def __init__(self, resp): super(GetAuthCodeForDomainResult, self).__init__(resp) self.authCode = None class Lockdomainresult(RequestResult): """Response class for LockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(LockDomainResult, self).__init__(resp) self.domain = None class Unlockdomainresult(RequestResult): """Response class for UnlockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(UnlockDomainResult, self).__init__(resp) self.domain = None class Checkavailabilityresult(RequestResult): """Response class for CheckAvailability method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(CheckAvailabilityResult, self).__init__(resp) self.results = [] class Searchstreamresult(RequestResult): """Response class for SearchStream method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` a generator yielding of DomainSearchResult """ def __init__(self, resp): super(SearchStreamResult, self).__init__(resp) self.results = [] class Listemailforwardingsresult(RequestResult): """Response class for ListEmailForwardings method. Attributes ---------- email_forwardings : [] :class:`~namecom.EmailForwarding` list of EmailForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListEmailForwardingsResult, self).__init__(resp) self.email_forwardings = [] self.nextPage = None self.lastPage = None class Getemailforwardingresult(RequestResult): """Response class for GetEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(GetEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class Createemailforwardingresult(RequestResult): """Response class for CreateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(CreateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class Updateemailforwardingresult(RequestResult): """Response class for UpdateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(UpdateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class Deleteemailforwardingresult(RequestResult): """Response class for DeleteEmailForwarding method.""" class Listtransfersresult(RequestResult): """Response class for ListTransfers method. Attributes ---------- transfers : [] :class:`~namecom.Transfer` list of Transfer nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListTransfersResult, self).__init__(resp) self.transfers = [] self.nextPage = None self.lastPage = None class Gettransferresult(RequestResult): """Response class for GetTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(GetTransferResult, self).__init__(resp) self.transfer = None class Createtransferresult(RequestResult): """Response class for CreateTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateTransferResult, self).__init__(resp) self.transfer = None self.order = None self.totalPaid = None class Canceltransferresult(RequestResult): """Response class for CancelTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(CancelTransferResult, self).__init__(resp) self.transfer = None class Listurlforwardingsresult(RequestResult): """Response class for ListURLForwardins method. Attributes ---------- url_forwardings : [] :class:`~namecom.URLForwarding` list of URLForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListURLForwardingsResult, self).__init__(resp) self.url_forwardings = [] self.nextPage = None self.lastPage = None class Geturlforwardingresult(RequestResult): """Response class for GetURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(GetURLForwardingResult, self).__init__(resp) self.url_forwarding = None class Createurlforwardingresult(RequestResult): """Response class for CreateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(CreateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class Updateurlforwardingresult(RequestResult): """Response class for UpdateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(UpdateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class Deleteurlforwardingresult(RequestResult): """Response class for DeleteURLForwarding method.""" class Listvanitynameserversresult(RequestResult): """Response class for ListVanityNameservers method. Attributes ---------- vanityNameservers : [] :class:`~namecom.VanityNameserver` list of VanityNameserver nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListVanityNameserversResult, self).__init__(resp) self.vanityNameservers = [] self.nextPage = None self.lastPage = None class Getvanitynameserverresult(RequestResult): """Response class for GetVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(GetVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class Createvanitynameserverresult(RequestResult): """Response class for CreateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(CreateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class Updatevanitynameserverresult(RequestResult): """Response class for UpdateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(UpdateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class Deletevanitynameserverresult(RequestResult): """Response class for DeleteVanityNameserver method."""
""" Exceptions used by the impact estimation program """ class RecipeCreationError(Exception): pass class SolverTimeoutError(Exception): pass class NoKnownIngredientsError(Exception): pass class NoCharacterizedIngredientsError(Exception): pass
""" Exceptions used by the impact estimation program """ class Recipecreationerror(Exception): pass class Solvertimeouterror(Exception): pass class Noknowningredientserror(Exception): pass class Nocharacterizedingredientserror(Exception): pass
# Copyright 2015 Google Inc. All rights reserved. # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd { 'includes': [ ], 'targets': [ { 'target_name': 'mkvmuxer', 'type': 'static_library', 'sources': [ 'src/mkvmuxer.cpp', 'src/mkvmuxer.hpp', 'src/mkvmuxerutil.cpp', 'src/mkvmuxerutil.hpp', 'src/mkvwriter.cpp', 'src/mkvwriter.hpp', ], }, ], }
{'includes': [], 'targets': [{'target_name': 'mkvmuxer', 'type': 'static_library', 'sources': ['src/mkvmuxer.cpp', 'src/mkvmuxer.hpp', 'src/mkvmuxerutil.cpp', 'src/mkvmuxerutil.hpp', 'src/mkvwriter.cpp', 'src/mkvwriter.hpp']}]}
# -*- coding: utf-8 -*- """ First paragraph of docs. .. wikisection:: faq :title: Why? Well... Second paragraph of docs. """
""" First paragraph of docs. .. wikisection:: faq :title: Why? Well... Second paragraph of docs. """
class Address(object): def __init__(self,addr): self.addr=addr @classmethod def fromhex(cls,addr): return cls(bytes.fromhex(addr)) def equal(self,other): if not isinstance(other, Address): raise Exception('peer is not an address') if not len(self.addr) == len(other.addr): raise Exception('address lenght mismatch') for i in range(len(self.addr)): if not self.addr[i] == other.addr[i]: return False return True def string(self): return self.addr.hex() MaxPO=16 def prox(one,other): b = int(MaxPO/8) + 1 m = 8 for i in range(b): oxo = one[i] ^ other[i] for j in range(m): if oxo>>(7-j)&0x01 != 0 : return i*8 + j return MaxPO
class Address(object): def __init__(self, addr): self.addr = addr @classmethod def fromhex(cls, addr): return cls(bytes.fromhex(addr)) def equal(self, other): if not isinstance(other, Address): raise exception('peer is not an address') if not len(self.addr) == len(other.addr): raise exception('address lenght mismatch') for i in range(len(self.addr)): if not self.addr[i] == other.addr[i]: return False return True def string(self): return self.addr.hex() max_po = 16 def prox(one, other): b = int(MaxPO / 8) + 1 m = 8 for i in range(b): oxo = one[i] ^ other[i] for j in range(m): if oxo >> 7 - j & 1 != 0: return i * 8 + j return MaxPO
# job_list_one_shot.py --- # # Filename: job_list_one_shot.py # Author: Abhishek Udupa # Created: Tue Jan 26 15:13:19 2016 (-0500) # # # Copyright (c) 2015, Abhishek Udupa, University of Pennsylvania # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by The University of Pennsylvania # 4. Neither the name of the University of Pennsylvania nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # Code: [ (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_103_10.sl'], 'icfp_103_10-one-shot', 'icfp_103_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_113_1000.sl'], 'icfp_113_1000-one-shot', 'icfp_113_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_125_10.sl'], 'icfp_125_10-one-shot', 'icfp_125_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_14_1000.sl'], 'icfp_14_1000-one-shot', 'icfp_14_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_147_1000.sl'], 'icfp_147_1000-one-shot', 'icfp_147_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_28_10.sl'], 'icfp_28_10-one-shot', 'icfp_28_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_39_100.sl'], 'icfp_39_100-one-shot', 'icfp_39_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_51_10.sl'], 'icfp_51_10-one-shot', 'icfp_51_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_68_1000.sl'], 'icfp_68_1000-one-shot', 'icfp_68_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_72_10.sl'], 'icfp_72_10-one-shot', 'icfp_72_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_10.sl'], 'icfp_82_10-one-shot', 'icfp_82_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_1000.sl'], 'icfp_94_1000-one-shot', 'icfp_94_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_10.sl'], 'icfp_96_10-one-shot', 'icfp_96_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_104_10.sl'], 'icfp_104_10-one-shot', 'icfp_104_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_114_100.sl'], 'icfp_114_100-one-shot', 'icfp_114_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_134_1000.sl'], 'icfp_134_1000-one-shot', 'icfp_134_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_143_1000.sl'], 'icfp_143_1000-one-shot', 'icfp_143_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_150_10.sl'], 'icfp_150_10-one-shot', 'icfp_150_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_30_10.sl'], 'icfp_30_10-one-shot', 'icfp_30_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_1000.sl'], 'icfp_45_1000-one-shot', 'icfp_45_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_54_1000.sl'], 'icfp_54_1000-one-shot', 'icfp_54_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_69_10.sl'], 'icfp_69_10-one-shot', 'icfp_69_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_73_10.sl'], 'icfp_73_10-one-shot', 'icfp_73_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_87_10.sl'], 'icfp_87_10-one-shot', 'icfp_87_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_100.sl'], 'icfp_94_100-one-shot', 'icfp_94_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_99_100.sl'], 'icfp_99_100-one-shot', 'icfp_99_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_1000.sl'], 'icfp_105_1000-one-shot', 'icfp_105_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_100.sl'], 'icfp_118_100-one-shot', 'icfp_118_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_135_100.sl'], 'icfp_135_100-one-shot', 'icfp_135_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_1000.sl'], 'icfp_144_1000-one-shot', 'icfp_144_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_21_1000.sl'], 'icfp_21_1000-one-shot', 'icfp_21_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_32_10.sl'], 'icfp_32_10-one-shot', 'icfp_32_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_10.sl'], 'icfp_45_10-one-shot', 'icfp_45_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_56_1000.sl'], 'icfp_56_1000-one-shot', 'icfp_56_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_1000.sl'], 'icfp_7_1000-one-shot', 'icfp_7_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_81_1000.sl'], 'icfp_81_1000-one-shot', 'icfp_81_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_9_1000.sl'], 'icfp_9_1000-one-shot', 'icfp_9_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_95_100.sl'], 'icfp_95_100-one-shot', 'icfp_95_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_100.sl'], 'icfp_105_100-one-shot', 'icfp_105_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_10.sl'], 'icfp_118_10-one-shot', 'icfp_118_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_139_10.sl'], 'icfp_139_10-one-shot', 'icfp_139_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_100.sl'], 'icfp_144_100-one-shot', 'icfp_144_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_25_1000.sl'], 'icfp_25_1000-one-shot', 'icfp_25_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_38_10.sl'], 'icfp_38_10-one-shot', 'icfp_38_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_5_1000.sl'], 'icfp_5_1000-one-shot', 'icfp_5_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_64_10.sl'], 'icfp_64_10-one-shot', 'icfp_64_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_10.sl'], 'icfp_7_10-one-shot', 'icfp_7_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_100.sl'], 'icfp_82_100-one-shot', 'icfp_82_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_93_1000.sl'], 'icfp_93_1000-one-shot', 'icfp_93_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_1000.sl'], 'icfp_96_1000-one-shot', 'icfp_96_1000-one-shot') ] # # job_list_one_shot.py ends here
[(['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_103_10.sl'], 'icfp_103_10-one-shot', 'icfp_103_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_113_1000.sl'], 'icfp_113_1000-one-shot', 'icfp_113_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_125_10.sl'], 'icfp_125_10-one-shot', 'icfp_125_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_14_1000.sl'], 'icfp_14_1000-one-shot', 'icfp_14_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_147_1000.sl'], 'icfp_147_1000-one-shot', 'icfp_147_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_28_10.sl'], 'icfp_28_10-one-shot', 'icfp_28_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_39_100.sl'], 'icfp_39_100-one-shot', 'icfp_39_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_51_10.sl'], 'icfp_51_10-one-shot', 'icfp_51_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_68_1000.sl'], 'icfp_68_1000-one-shot', 'icfp_68_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_72_10.sl'], 'icfp_72_10-one-shot', 'icfp_72_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_10.sl'], 'icfp_82_10-one-shot', 'icfp_82_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_1000.sl'], 'icfp_94_1000-one-shot', 'icfp_94_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_10.sl'], 'icfp_96_10-one-shot', 'icfp_96_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_104_10.sl'], 'icfp_104_10-one-shot', 'icfp_104_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_114_100.sl'], 'icfp_114_100-one-shot', 'icfp_114_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_134_1000.sl'], 'icfp_134_1000-one-shot', 'icfp_134_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_143_1000.sl'], 'icfp_143_1000-one-shot', 'icfp_143_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_150_10.sl'], 'icfp_150_10-one-shot', 'icfp_150_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_30_10.sl'], 'icfp_30_10-one-shot', 'icfp_30_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_1000.sl'], 'icfp_45_1000-one-shot', 'icfp_45_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_54_1000.sl'], 'icfp_54_1000-one-shot', 'icfp_54_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_69_10.sl'], 'icfp_69_10-one-shot', 'icfp_69_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_73_10.sl'], 'icfp_73_10-one-shot', 'icfp_73_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_87_10.sl'], 'icfp_87_10-one-shot', 'icfp_87_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_100.sl'], 'icfp_94_100-one-shot', 'icfp_94_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_99_100.sl'], 'icfp_99_100-one-shot', 'icfp_99_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_1000.sl'], 'icfp_105_1000-one-shot', 'icfp_105_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_100.sl'], 'icfp_118_100-one-shot', 'icfp_118_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_135_100.sl'], 'icfp_135_100-one-shot', 'icfp_135_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_1000.sl'], 'icfp_144_1000-one-shot', 'icfp_144_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_21_1000.sl'], 'icfp_21_1000-one-shot', 'icfp_21_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_32_10.sl'], 'icfp_32_10-one-shot', 'icfp_32_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_10.sl'], 'icfp_45_10-one-shot', 'icfp_45_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_56_1000.sl'], 'icfp_56_1000-one-shot', 'icfp_56_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_1000.sl'], 'icfp_7_1000-one-shot', 'icfp_7_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_81_1000.sl'], 'icfp_81_1000-one-shot', 'icfp_81_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_9_1000.sl'], 'icfp_9_1000-one-shot', 'icfp_9_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_95_100.sl'], 'icfp_95_100-one-shot', 'icfp_95_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_100.sl'], 'icfp_105_100-one-shot', 'icfp_105_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_10.sl'], 'icfp_118_10-one-shot', 'icfp_118_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_139_10.sl'], 'icfp_139_10-one-shot', 'icfp_139_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_100.sl'], 'icfp_144_100-one-shot', 'icfp_144_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_25_1000.sl'], 'icfp_25_1000-one-shot', 'icfp_25_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_38_10.sl'], 'icfp_38_10-one-shot', 'icfp_38_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_5_1000.sl'], 'icfp_5_1000-one-shot', 'icfp_5_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_64_10.sl'], 'icfp_64_10-one-shot', 'icfp_64_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_10.sl'], 'icfp_7_10-one-shot', 'icfp_7_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_100.sl'], 'icfp_82_100-one-shot', 'icfp_82_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_93_1000.sl'], 'icfp_93_1000-one-shot', 'icfp_93_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_1000.sl'], 'icfp_96_1000-one-shot', 'icfp_96_1000-one-shot')]
class OnlyStaffMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: messages.error(request, "Only Staff members can do this.") try: return HttpResponseRedirect(request.META['HTTP_REFERER']) except KeyError: return HttpResponseRedirect('/') return super(OnlyStaffMixin, self).dispatch(request, *args, **kwargs)
class Onlystaffmixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: messages.error(request, 'Only Staff members can do this.') try: return http_response_redirect(request.META['HTTP_REFERER']) except KeyError: return http_response_redirect('/') return super(OnlyStaffMixin, self).dispatch(request, *args, **kwargs)
def plant_recommendation(care): if care == 'low': print('aloe') elif care == 'medium': print('pothos') elif care == 'high': print('orchid') plant_recommendation('low') plant_recommendation('medium') plant_recommendation('high')
def plant_recommendation(care): if care == 'low': print('aloe') elif care == 'medium': print('pothos') elif care == 'high': print('orchid') plant_recommendation('low') plant_recommendation('medium') plant_recommendation('high')
class Settings(): def __init__(self): self.screen_width = 1024 # screen Width self.screen_height = 512 # screen height self.bg_color = (255, 255, 255) # overall background color self.init_speed = 30 # speed factor of dino self.dhmax = 23 self.alt_freq = 3
class Settings: def __init__(self): self.screen_width = 1024 self.screen_height = 512 self.bg_color = (255, 255, 255) self.init_speed = 30 self.dhmax = 23 self.alt_freq = 3
# Maths # Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length. # # Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1: # # If S[i] == "I", then A[i] < A[i+1] # If S[i] == "D", then A[i] > A[i+1] # # # Example 1: # # Input: "IDID" # Output: [0,4,1,3,2] # Example 2: # # Input: "III" # Output: [0,1,2,3] # Example 3: # # Input: "DDI" # Output: [3,2,0,1] # # # Note: # # 1 <= S.length <= 10000 # S only contains characters "I" or "D". class Solution: def diStringMatch(self, S): """ :type S: str :rtype: List[int] """ low, high = 0, len(S) output = [] for x in S: if x == "I": output.append(low) low += 1 else: output.append(high) high -= 1 return output + [low]
class Solution: def di_string_match(self, S): """ :type S: str :rtype: List[int] """ (low, high) = (0, len(S)) output = [] for x in S: if x == 'I': output.append(low) low += 1 else: output.append(high) high -= 1 return output + [low]
# Interface for a "set" of cases class CaseSet: def __init__(self, time): self.time = time def __len__(self): raise NotImplementedError() def iterator(self): raise NotImplementedError() def get_time(self): return self.time def set_time(self, time): self.time = time
class Caseset: def __init__(self, time): self.time = time def __len__(self): raise not_implemented_error() def iterator(self): raise not_implemented_error() def get_time(self): return self.time def set_time(self, time): self.time = time
def array_count9(nums): count = 0 # Standard loop to look at each value for num in nums: if num == 9: count = count + 1 return count
def array_count9(nums): count = 0 for num in nums: if num == 9: count = count + 1 return count
# # @lc app=leetcode id=747 lang=python3 # # [747] Largest Number At Least Twice of Others # # https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ # # algorithms # Easy (40.25%) # Total Accepted: 47.6K # Total Submissions: 118K # Testcase Example: '[0,0,0,1]' # # In a given integer array nums, there is always exactly one largest element. # # Find whether the largest element in the array is at least twice as much as # every other number in the array. # # If it is, return the index of the largest element, otherwise return -1. # # Example 1: # # # Input: nums = [3, 6, 1, 0] # Output: 1 # Explanation: 6 is the largest integer, and for every other number in the # array x, # 6 is more than twice as big as x. The index of value 6 is 1, so we return # 1. # # # # # Example 2: # # # Input: nums = [1, 2, 3, 4] # Output: -1 # Explanation: 4 isn't at least as big as twice the value of 3, so we return # -1. # # # # # Note: # # # nums will have a length in the range [1, 50]. # Every nums[i] will be an integer in the range [0, 99]. # # # # # class Solution: def dominantIndex(self, nums: List[int]) -> int: indexmax1 = 0 max1 = 0 indexmax = 0 max = 0 for i in range(len(nums)): if nums[i] > max: max1 = max indexmax1 = indexmax max = nums[i] indexmax = i elif nums[i] > max1: max1 = nums[i] indexmax1 = i return indexmax if max >= 2*max1 else -1
class Solution: def dominant_index(self, nums: List[int]) -> int: indexmax1 = 0 max1 = 0 indexmax = 0 max = 0 for i in range(len(nums)): if nums[i] > max: max1 = max indexmax1 = indexmax max = nums[i] indexmax = i elif nums[i] > max1: max1 = nums[i] indexmax1 = i return indexmax if max >= 2 * max1 else -1
# Speed of light in m/s speed_light = 299792458 # J s Planck_constant = 6.626e-34 # m Wavelenght of band V wavelenght_visual = 550e-9 # flux density (Jy) in V for a 0 mag star Fv = 3640.0 # photons s-1 m-2 in Jy Jy = 1.51e7 #1 rad = 57.3 grad RAD = 57.29578 # 1 AU ib cn AU = 149.59787e11 # Radius in cm R_Earth = 6378.e5 R_MOON = 1737.4e5 atmosphere = 100.e5 # Julian day corresponding to the beginning of 2018 JD_2018 = 2458119.5 # km in cm KM = 1.e5 # m2 in cm2 M2 = 1.e4 # Gravitational constant in N (m/kg)2 G = 6.67384e-11 # Gravitational parameter (mu = G *M) for Earth in m^3/s^2 mu_Earth = 3.986e14 # Timestamp for the initial time in the simulation # timestamp 2018-01-01 00:00 (GMT as used in STK) (valid for Python/Unix) # timestamp_2018_01_01 = 1514764800 timestamp_2018_01_01 = 1514764800 sideral_day = 23.9344696 #[h] version = '0.8'
speed_light = 299792458 planck_constant = 6.626e-34 wavelenght_visual = 5.5e-07 fv = 3640.0 jy = 15100000.0 rad = 57.29578 au = 14959787000000.0 r__earth = 637800000.0 r_moon = 173740000.0 atmosphere = 10000000.0 jd_2018 = 2458119.5 km = 100000.0 m2 = 10000.0 g = 6.67384e-11 mu__earth = 398600000000000.0 timestamp_2018_01_01 = 1514764800 sideral_day = 23.9344696 version = '0.8'
factors = [1, 2, 4] pads = [32, 64, 128, 256, 512] gen_scope = "gen" dis_scope = "dis" outputs_prefix = "output_" lr_key = "lr" hr_key = "hr" lr_input_name = "lr_input" hr_input_name = "hr_input" pretrain_key = "pretrain" train_key = "train" epoch_key = "per_epoch"
factors = [1, 2, 4] pads = [32, 64, 128, 256, 512] gen_scope = 'gen' dis_scope = 'dis' outputs_prefix = 'output_' lr_key = 'lr' hr_key = 'hr' lr_input_name = 'lr_input' hr_input_name = 'hr_input' pretrain_key = 'pretrain' train_key = 'train' epoch_key = 'per_epoch'
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] """ # TC and Space (O(N)) # Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, # then some non-negative elements with squares in increasing order. # For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. # Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction. # We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction. # Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique. class Solution(object): def sortedSquares(self, nums): # We first declare a list of length, len(A) then add the larger square from the back of the list, denoted by the index r - l res = [0] * len(nums) start, end = 0, len(nums) - 1 while start <= end: left, right = abs(nums[start]), abs(nums[end]) if left > right: res[end - start] = left * left start += 1 else: res[end - start] = right * right end -= 1 return res
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] """ class Solution(object): def sorted_squares(self, nums): res = [0] * len(nums) (start, end) = (0, len(nums) - 1) while start <= end: (left, right) = (abs(nums[start]), abs(nums[end])) if left > right: res[end - start] = left * left start += 1 else: res[end - start] = right * right end -= 1 return res
# generic warnings UNEXPECTED_FIELDS = 'A GTFS fares-v2 file has column name(s) not defined in the specification.' UNUSED_AREA_IDS = 'Areas defined in areas.txt are unused in other fares files.' UNUSED_NETWORK_IDS = 'Networks defined in routes.txt are unused in other fares files.' UNUSED_TIMEFRAME_IDS = 'Timeframes defined in timeframes.txt are unused in other fares files.' # areas.txt NO_AREAS = 'No areas.txt was found, will assume no areas exist.' # routes.txt NO_ROUTES = 'No routes.txt was found, will assume no networks exist.' # stops.txt NO_STOPS = 'No stops.txt was found, will assume stops.txt does not reference any areas.' UNUSED_AREAS_IN_STOPS = 'Areas defined in areas.txt are unused in stops.txt or stop_times.txt.' # calendar.txt, calendar_dates.txt NO_SERVICE_IDS = 'Neither calendar.txt or calendar_dates.txt was found, will assume no service_ids for fares data.' # timeframes.txt NO_TIMEFRAMES = 'No timeframes.txt was found, will assume no timeframes exist.' # rider_categories.txt MAX_AGE_LESS_THAN_MIN_AGE = 'An entry in rider_categories.txt has max_age less than or equal to min_age.' NO_RIDER_CATEGORIES = 'No rider_categories.txt was found, will assume no rider_categories exist.' VERY_LARGE_MAX_AGE = 'An entry in rider_categories.txt has a very large max_age.' VERY_LARGE_MIN_AGE = 'An entry in rider_categories.txt has a very large min_age.' # fare_containers.txt NO_FARE_CONTAINERS = 'No fare_containers.txt was found, will assume no fare_containers exist.' # fare_products.txt NO_FARE_PRODUCTS = 'No fare_products.txt was found, will assume no fare_products exist.' OFFSET_AMOUNT_WITHOUT_OFFSET_UNIT = 'An offset_amount in fare_products.txt is defined without an offset_unit, so duration_unit will be used.' # fare_leg_rules.txt NO_FARE_LEG_RULES = 'No fare_leg_rules.txt was found, will assume no fare_leg_rules exist.' # fare_transfer_rules.txt NO_FARE_TRANSFER_RULES = 'No fare_transfer_rules.txt was found, will assume no fare_transfer_rules exist.' UNUSED_LEG_GROUPS = 'Leg groups defined in fare_leg_rules.txt are unused in fare_transfer_rules.txt.'
unexpected_fields = 'A GTFS fares-v2 file has column name(s) not defined in the specification.' unused_area_ids = 'Areas defined in areas.txt are unused in other fares files.' unused_network_ids = 'Networks defined in routes.txt are unused in other fares files.' unused_timeframe_ids = 'Timeframes defined in timeframes.txt are unused in other fares files.' no_areas = 'No areas.txt was found, will assume no areas exist.' no_routes = 'No routes.txt was found, will assume no networks exist.' no_stops = 'No stops.txt was found, will assume stops.txt does not reference any areas.' unused_areas_in_stops = 'Areas defined in areas.txt are unused in stops.txt or stop_times.txt.' no_service_ids = 'Neither calendar.txt or calendar_dates.txt was found, will assume no service_ids for fares data.' no_timeframes = 'No timeframes.txt was found, will assume no timeframes exist.' max_age_less_than_min_age = 'An entry in rider_categories.txt has max_age less than or equal to min_age.' no_rider_categories = 'No rider_categories.txt was found, will assume no rider_categories exist.' very_large_max_age = 'An entry in rider_categories.txt has a very large max_age.' very_large_min_age = 'An entry in rider_categories.txt has a very large min_age.' no_fare_containers = 'No fare_containers.txt was found, will assume no fare_containers exist.' no_fare_products = 'No fare_products.txt was found, will assume no fare_products exist.' offset_amount_without_offset_unit = 'An offset_amount in fare_products.txt is defined without an offset_unit, so duration_unit will be used.' no_fare_leg_rules = 'No fare_leg_rules.txt was found, will assume no fare_leg_rules exist.' no_fare_transfer_rules = 'No fare_transfer_rules.txt was found, will assume no fare_transfer_rules exist.' unused_leg_groups = 'Leg groups defined in fare_leg_rules.txt are unused in fare_transfer_rules.txt.'
def test_contacts_on_home_page(app): contact_from_home_page = app.contact.get_contacts_list()[1] contact_from_edit_page = app.contact.get_info_from_edit_page(1) assert contact_from_edit_page.email_1 == contact_from_home_page.email_1 assert contact_from_edit_page.email_2 == contact_from_home_page.email_2 assert contact_from_edit_page.email_3 == contact_from_home_page.email_3 def test_phones_on_home_page(app): phones_from_home_page = app.contact.get_contacts_list()[1] phones_from_edit_page = app.contact.get_info_from_edit_page(1) assert phones_from_edit_page.work_phone == phones_from_home_page.work_phone assert phones_from_edit_page.home_phone == phones_from_home_page.home_phone assert phones_from_edit_page.mobile_phone == phones_from_home_page.mobile_phone
def test_contacts_on_home_page(app): contact_from_home_page = app.contact.get_contacts_list()[1] contact_from_edit_page = app.contact.get_info_from_edit_page(1) assert contact_from_edit_page.email_1 == contact_from_home_page.email_1 assert contact_from_edit_page.email_2 == contact_from_home_page.email_2 assert contact_from_edit_page.email_3 == contact_from_home_page.email_3 def test_phones_on_home_page(app): phones_from_home_page = app.contact.get_contacts_list()[1] phones_from_edit_page = app.contact.get_info_from_edit_page(1) assert phones_from_edit_page.work_phone == phones_from_home_page.work_phone assert phones_from_edit_page.home_phone == phones_from_home_page.home_phone assert phones_from_edit_page.mobile_phone == phones_from_home_page.mobile_phone
# # PySNMP MIB module OPTIX-SONET-EQPTMGT-MIB-V2 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPTIX-SONET-EQPTMGT-MIB-V2 # Produced by pysmi-0.3.4 at Mon Apr 29 20:26:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") optixProvisionSonet, = mibBuilder.importSymbols("OPTIX-OID-MIB", "optixProvisionSonet") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Integer32, Unsigned32, NotificationType, ModuleIdentity, Bits, Counter32, IpAddress, Counter64, ObjectIdentity, Gauge32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Unsigned32", "NotificationType", "ModuleIdentity", "Bits", "Counter32", "IpAddress", "Counter64", "ObjectIdentity", "Gauge32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "MibIdentifier") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") optixsonetEqptMgt = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3)) if mibBuilder.loadTexts: optixsonetEqptMgt.setLastUpdated('200605232006Z') if mibBuilder.loadTexts: optixsonetEqptMgt.setOrganization('Your organization') class IntfType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 10, 12, 13, 17, 65, 100, 254)) namedValues = NamedValues(("ds1-asyn-vt1", 1), ("ds3-asyn-sts1", 10), ("ec", 12), ("ds3-tmux-ds1", 13), ("ds3-srv-ds1", 17), ("uas", 65), ("mix", 100), ("invalid", 254)) optixsonetCardInfoTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1), ) if mibBuilder.loadTexts: optixsonetCardInfoTable.setStatus('current') optixsonetCardInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1), ).setIndexNames((0, "OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSlotId"), (0, "OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSfpId")) if mibBuilder.loadTexts: optixsonetCardInfoEntry.setStatus('current') cardIndexSlotId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIndexSlotId.setStatus('current') cardIndexSfpId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIndexSfpId.setStatus('current') cardProvisionType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardProvisionType.setStatus('current') cardPhysicalType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPhysicalType.setStatus('current') cardInterfaceType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 5), IntfType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardInterfaceType.setStatus('current') cardBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardBandwidth.setStatus('current') cardSerialNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSerialNum.setStatus('current') cardCLEICode = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardCLEICode.setStatus('current') cardPartNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPartNum.setStatus('current') cardDOM = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardDOM.setStatus('current') cardPCBVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPCBVersion.setStatus('current') cardSWVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 12), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSWVersion.setStatus('current') cardFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardFPGAVersion.setStatus('current') cardEPLDVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardEPLDVersion.setStatus('current') cardBIOSVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardBIOSVersion.setStatus('current') cardMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardMAC.setStatus('current') cardPSTState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 17), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPSTState.setStatus('current') cardSSTState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 18), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSSTState.setStatus('current') cardTPSPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 19), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardTPSPriority.setStatus('current') cardSwitchState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 254, 255))).clone(namedValues=NamedValues(("stateDNR", 1), ("stateWTR", 2), ("stateMAN", 3), ("stateAUTOSW", 4), ("stateFRCD", 5), ("stateLOCK", 6), ("stateINVALID", 254), ("stateIDLE", 255)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSwitchState.setStatus('current') cardDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 21), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardDescription.setStatus('current') optixsonetEqptMgtConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2)) optixsonetEqptMgtGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1)) currentObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1, 1)).setObjects(("OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSlotId"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSfpId"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardProvisionType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPhysicalType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardInterfaceType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardBandwidth"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSerialNum"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardCLEICode"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPartNum"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardDOM"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPCBVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSWVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardFPGAVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardEPLDVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardBIOSVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardMAC"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPSTState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSSTState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardTPSPriority"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSwitchState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardDescription")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): currentObjectGroup = currentObjectGroup.setStatus('current') optixsonetEqptMgtCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2)) basicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2, 1)).setObjects(("OPTIX-SONET-EQPTMGT-MIB-V2", "currentObjectGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): basicCompliance = basicCompliance.setStatus('current') mibBuilder.exportSymbols("OPTIX-SONET-EQPTMGT-MIB-V2", cardTPSPriority=cardTPSPriority, cardIndexSlotId=cardIndexSlotId, cardDOM=cardDOM, cardEPLDVersion=cardEPLDVersion, cardSerialNum=cardSerialNum, cardInterfaceType=cardInterfaceType, cardDescription=cardDescription, optixsonetEqptMgtGroups=optixsonetEqptMgtGroups, cardSSTState=cardSSTState, basicCompliance=basicCompliance, optixsonetCardInfoTable=optixsonetCardInfoTable, cardBandwidth=cardBandwidth, cardSWVersion=cardSWVersion, cardMAC=cardMAC, cardPSTState=cardPSTState, PYSNMP_MODULE_ID=optixsonetEqptMgt, cardPhysicalType=cardPhysicalType, optixsonetEqptMgt=optixsonetEqptMgt, cardPartNum=cardPartNum, cardBIOSVersion=cardBIOSVersion, cardFPGAVersion=cardFPGAVersion, cardPCBVersion=cardPCBVersion, currentObjectGroup=currentObjectGroup, cardSwitchState=cardSwitchState, optixsonetCardInfoEntry=optixsonetCardInfoEntry, cardCLEICode=cardCLEICode, cardProvisionType=cardProvisionType, optixsonetEqptMgtConformance=optixsonetEqptMgtConformance, cardIndexSfpId=cardIndexSfpId, IntfType=IntfType, optixsonetEqptMgtCompliances=optixsonetEqptMgtCompliances)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion') (optix_provision_sonet,) = mibBuilder.importSymbols('OPTIX-OID-MIB', 'optixProvisionSonet') (notification_group, object_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ObjectGroup', 'ModuleCompliance') (integer32, unsigned32, notification_type, module_identity, bits, counter32, ip_address, counter64, object_identity, gauge32, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'Unsigned32', 'NotificationType', 'ModuleIdentity', 'Bits', 'Counter32', 'IpAddress', 'Counter64', 'ObjectIdentity', 'Gauge32', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'MibIdentifier') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') optixsonet_eqpt_mgt = module_identity((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3)) if mibBuilder.loadTexts: optixsonetEqptMgt.setLastUpdated('200605232006Z') if mibBuilder.loadTexts: optixsonetEqptMgt.setOrganization('Your organization') class Intftype(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 10, 12, 13, 17, 65, 100, 254)) named_values = named_values(('ds1-asyn-vt1', 1), ('ds3-asyn-sts1', 10), ('ec', 12), ('ds3-tmux-ds1', 13), ('ds3-srv-ds1', 17), ('uas', 65), ('mix', 100), ('invalid', 254)) optixsonet_card_info_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1)) if mibBuilder.loadTexts: optixsonetCardInfoTable.setStatus('current') optixsonet_card_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1)).setIndexNames((0, 'OPTIX-SONET-EQPTMGT-MIB-V2', 'cardIndexSlotId'), (0, 'OPTIX-SONET-EQPTMGT-MIB-V2', 'cardIndexSfpId')) if mibBuilder.loadTexts: optixsonetCardInfoEntry.setStatus('current') card_index_slot_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 1), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardIndexSlotId.setStatus('current') card_index_sfp_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 2), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardIndexSfpId.setStatus('current') card_provision_type = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardProvisionType.setStatus('current') card_physical_type = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardPhysicalType.setStatus('current') card_interface_type = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 5), intf_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardInterfaceType.setStatus('current') card_bandwidth = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardBandwidth.setStatus('current') card_serial_num = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardSerialNum.setStatus('current') card_clei_code = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 8), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardCLEICode.setStatus('current') card_part_num = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 9), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardPartNum.setStatus('current') card_dom = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 10), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardDOM.setStatus('current') card_pcb_version = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 11), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardPCBVersion.setStatus('current') card_sw_version = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 12), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardSWVersion.setStatus('current') card_fpga_version = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 13), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardFPGAVersion.setStatus('current') card_epld_version = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 14), octet_string().subtype(subtypeSpec=value_size_constraint(0, 8))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardEPLDVersion.setStatus('current') card_bios_version = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 15), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardBIOSVersion.setStatus('current') card_mac = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 16), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardMAC.setStatus('current') card_pst_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 17), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardPSTState.setStatus('current') card_sst_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 18), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardSSTState.setStatus('current') card_tps_priority = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 19), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: cardTPSPriority.setStatus('current') card_switch_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 254, 255))).clone(namedValues=named_values(('stateDNR', 1), ('stateWTR', 2), ('stateMAN', 3), ('stateAUTOSW', 4), ('stateFRCD', 5), ('stateLOCK', 6), ('stateINVALID', 254), ('stateIDLE', 255)))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardSwitchState.setStatus('current') card_description = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 21), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: cardDescription.setStatus('current') optixsonet_eqpt_mgt_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2)) optixsonet_eqpt_mgt_groups = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1)) current_object_group = object_group((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1, 1)).setObjects(('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardIndexSlotId'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardIndexSfpId'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardProvisionType'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardPhysicalType'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardInterfaceType'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardBandwidth'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardSerialNum'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardCLEICode'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardPartNum'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardDOM'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardPCBVersion'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardSWVersion'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardFPGAVersion'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardEPLDVersion'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardBIOSVersion'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardMAC'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardPSTState'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardSSTState'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardTPSPriority'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardSwitchState'), ('OPTIX-SONET-EQPTMGT-MIB-V2', 'cardDescription')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): current_object_group = currentObjectGroup.setStatus('current') optixsonet_eqpt_mgt_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2)) basic_compliance = module_compliance((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2, 1)).setObjects(('OPTIX-SONET-EQPTMGT-MIB-V2', 'currentObjectGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): basic_compliance = basicCompliance.setStatus('current') mibBuilder.exportSymbols('OPTIX-SONET-EQPTMGT-MIB-V2', cardTPSPriority=cardTPSPriority, cardIndexSlotId=cardIndexSlotId, cardDOM=cardDOM, cardEPLDVersion=cardEPLDVersion, cardSerialNum=cardSerialNum, cardInterfaceType=cardInterfaceType, cardDescription=cardDescription, optixsonetEqptMgtGroups=optixsonetEqptMgtGroups, cardSSTState=cardSSTState, basicCompliance=basicCompliance, optixsonetCardInfoTable=optixsonetCardInfoTable, cardBandwidth=cardBandwidth, cardSWVersion=cardSWVersion, cardMAC=cardMAC, cardPSTState=cardPSTState, PYSNMP_MODULE_ID=optixsonetEqptMgt, cardPhysicalType=cardPhysicalType, optixsonetEqptMgt=optixsonetEqptMgt, cardPartNum=cardPartNum, cardBIOSVersion=cardBIOSVersion, cardFPGAVersion=cardFPGAVersion, cardPCBVersion=cardPCBVersion, currentObjectGroup=currentObjectGroup, cardSwitchState=cardSwitchState, optixsonetCardInfoEntry=optixsonetCardInfoEntry, cardCLEICode=cardCLEICode, cardProvisionType=cardProvisionType, optixsonetEqptMgtConformance=optixsonetEqptMgtConformance, cardIndexSfpId=cardIndexSfpId, IntfType=IntfType, optixsonetEqptMgtCompliances=optixsonetEqptMgtCompliances)
#!/usr/bin/env python3 CAVE_DEPTH = 6969 TARGET_LOC = (9, 796) GEO_INDEX_CACHE = { (0, 0): 0, TARGET_LOC: 0 } def get_geo_index(x, y): key = (x, y) if key not in GEO_INDEX_CACHE: if y == 0: GEO_INDEX_CACHE[key] = x * 16807 elif x == 0: GEO_INDEX_CACHE[key] = y * 48271 else: GEO_INDEX_CACHE[key] = get_erosion_level(x, y - 1) * get_erosion_level(x - 1, y) return GEO_INDEX_CACHE[key] def get_erosion_level(x, y): return (get_geo_index(x, y) + CAVE_DEPTH) % 20183 total_danger = 0 for x in range(TARGET_LOC[0]+1): for y in range(TARGET_LOC[1] + 1): total_danger += get_erosion_level(x, y) % 3 print("Part 1:", total_danger)
cave_depth = 6969 target_loc = (9, 796) geo_index_cache = {(0, 0): 0, TARGET_LOC: 0} def get_geo_index(x, y): key = (x, y) if key not in GEO_INDEX_CACHE: if y == 0: GEO_INDEX_CACHE[key] = x * 16807 elif x == 0: GEO_INDEX_CACHE[key] = y * 48271 else: GEO_INDEX_CACHE[key] = get_erosion_level(x, y - 1) * get_erosion_level(x - 1, y) return GEO_INDEX_CACHE[key] def get_erosion_level(x, y): return (get_geo_index(x, y) + CAVE_DEPTH) % 20183 total_danger = 0 for x in range(TARGET_LOC[0] + 1): for y in range(TARGET_LOC[1] + 1): total_danger += get_erosion_level(x, y) % 3 print('Part 1:', total_danger)
"""Globally register callables and call via matching keywords. Example: >>> # register print function for keyword my_value >>> set_recorder(my_value=print) >>> record(my_value="Hello World.") Hello World. """ _recorders = {} def set_recorder(**kwargs): """Globally register a callable to which record calls are delegated. :param [keyword] callable: Callable to be registered with its keyword as identifier. """ global _recorders for name, recorder in kwargs.items(): _recorders[name] = recorder def record(**kwargs): """Pass value to previously registered callable. :param [keyword] value: This value is passed as the argument to the callable registered with keyword as identifier. """ global _recorders for key, value in kwargs.items(): if key in _recorders.keys(): _recorders[key](value)
"""Globally register callables and call via matching keywords. Example: >>> # register print function for keyword my_value >>> set_recorder(my_value=print) >>> record(my_value="Hello World.") Hello World. """ _recorders = {} def set_recorder(**kwargs): """Globally register a callable to which record calls are delegated. :param [keyword] callable: Callable to be registered with its keyword as identifier. """ global _recorders for (name, recorder) in kwargs.items(): _recorders[name] = recorder def record(**kwargs): """Pass value to previously registered callable. :param [keyword] value: This value is passed as the argument to the callable registered with keyword as identifier. """ global _recorders for (key, value) in kwargs.items(): if key in _recorders.keys(): _recorders[key](value)
def is_string(thing): try: return isinstance(thing, basestring) except NameError: return isinstance(thing, str)
def is_string(thing): try: return isinstance(thing, basestring) except NameError: return isinstance(thing, str)
def authenticated_method(func): def _decorated(self, *args, **kwargs): if not self.api_key: raise ValueError("you need to set your API KEY for this method.") response = func(self, *args, **kwargs) if response.status_code == 401: raise ValueError("invalid private/public key for API.") return response.json() return _decorated
def authenticated_method(func): def _decorated(self, *args, **kwargs): if not self.api_key: raise value_error('you need to set your API KEY for this method.') response = func(self, *args, **kwargs) if response.status_code == 401: raise value_error('invalid private/public key for API.') return response.json() return _decorated
class Frac: def __init__(self, idx: int, idy: int, x: int, y: int) -> None: self.idx = idx self.idy = idy self.x = x self.y = y def __lt__(self, other: "Frac") -> bool: return self.x * other.y < self.y * other.x class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: n = len(arr) q = [Frac(0, i, arr[0], arr[i]) for i in range(1, n)] heapq.heapify(q) for _ in range(k - 1): frac = heapq.heappop(q) i, j = frac.idx, frac.idy if i + 1 < j: heapq.heappush(q, Frac(i + 1, j, arr[i + 1], arr[j])) return [q[0].x, q[0].y]
class Frac: def __init__(self, idx: int, idy: int, x: int, y: int) -> None: self.idx = idx self.idy = idy self.x = x self.y = y def __lt__(self, other: 'Frac') -> bool: return self.x * other.y < self.y * other.x class Solution: def kth_smallest_prime_fraction(self, arr: List[int], k: int) -> List[int]: n = len(arr) q = [frac(0, i, arr[0], arr[i]) for i in range(1, n)] heapq.heapify(q) for _ in range(k - 1): frac = heapq.heappop(q) (i, j) = (frac.idx, frac.idy) if i + 1 < j: heapq.heappush(q, frac(i + 1, j, arr[i + 1], arr[j])) return [q[0].x, q[0].y]
while True: try: num=int(input("Input your number: ")) print("Your number is {}".format(num)) break except: print("Please insert number!")
while True: try: num = int(input('Input your number: ')) print('Your number is {}'.format(num)) break except: print('Please insert number!')
class XnorController: pass
class Xnorcontroller: pass
class MovingAverage: """ [1,10,3,5] size = 3 n = 4 [0,1,11,14,19] """ def __init__(self, size: int): self.size = size self.prefixes = [0] def next(self, val: int) -> float: n = len(self.prefixes) self.prefixes.append(val) self.prefixes[-1] += self.prefixes[-2] if n <= self.size: return self.prefixes[-1] / n return (self.prefixes[-1] - self.prefixes[n-self.size]) / self.size # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
class Movingaverage: """ [1,10,3,5] size = 3 n = 4 [0,1,11,14,19] """ def __init__(self, size: int): self.size = size self.prefixes = [0] def next(self, val: int) -> float: n = len(self.prefixes) self.prefixes.append(val) self.prefixes[-1] += self.prefixes[-2] if n <= self.size: return self.prefixes[-1] / n return (self.prefixes[-1] - self.prefixes[n - self.size]) / self.size
birth_year = 1999 if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6") if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6")
birth_year = 1999 if birth_year < 2000: print('line 1') print('line 2') print('line 3') else: print('line 4') print('line 5') print('line 6') if birth_year < 2000: print('line 1') print('line 2') print('line 3') else: print('line 4') print('line 5') print('line 6')
class TreeNode: def __init__(self, x): self.val = x self.next = None class Solution: def inorderTraversal(self, root: TreeNode) -> list: if root == None: return [] stack = [] visited = set() trav = [] stack.append(root) while len(stack) > 0: if stack[-1].left and stack[-1].left not in visited: # check the left child stack.append(stack[-1].left) else: # no left child or left child has been visited popped = stack.pop() trav.append(popped.val) visited.add(popped) # if has right child, visit it if popped.right: stack.append(popped.right) return trav
class Treenode: def __init__(self, x): self.val = x self.next = None class Solution: def inorder_traversal(self, root: TreeNode) -> list: if root == None: return [] stack = [] visited = set() trav = [] stack.append(root) while len(stack) > 0: if stack[-1].left and stack[-1].left not in visited: stack.append(stack[-1].left) else: popped = stack.pop() trav.append(popped.val) visited.add(popped) if popped.right: stack.append(popped.right) return trav
# Time: O(n + k) # Space: O(k) # 28 # Implement strStr(). # # Returns a pointer to the first occurrence of needle in haystack, # or null if needle is not part of haystack. # # Wiki of KMP algorithm: # http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 return self.KMP(haystack, needle) # https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/ # whenever we detect a mismatch (after some matches), we know some chars match for sure and skip compare them. # the above prefix array store number of chars. Code below stores index of prefix. def KMP(self, text, pattern): prefix = self.preKmp(pattern) j = -1 for i in range(len(text)): while j > -1 and text[i] != pattern[j + 1]: # mismatch, back to use prefix which guaranteed skipable j = prefix[j] if text[i] == pattern[j + 1]: j += 1 if j == len(pattern) - 1: return i - j return -1 def preKmp(self, s): prefix = [-1] * len(s) # prefix[i] = j means pattern[:j+1] prefix is also suffix of pattern[:i+1] j = -1 for i in range(1, len(s)): while j > -1 and s[i] != s[j + 1]: # cannot extend j = prefix[j] if s[i] == s[j + 1]: # extend number of chars which are both prefix and suffix j += 1 prefix[i] = j return prefix # Time: O(n * k) # Space: O(k) class Solution2(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: return i return -1 if __name__ == "__main__": # debug KMP algorithm print(Solution().strStr("abababcdab", "abcd")) # prefix [-1,-1,-1,-1] print(Solution().strStr("AAAAABAAABA", "AAAA")) # prefix [-1,0,1,2] print(Solution().strStr("abababcdab", "ababab")) # prefix [-1,-1,0,1,2,3] print(Solution().strStr("abababcdab", "abab")) # prefix [-1,-1,0,1] print(Solution().strStr("abababcdab", "abcdabc")) # prefix [-1,-1,-1,-1,0,1,2] print(Solution().strStr("a", "")) print(Solution().strStr("abababcdab", "abcacba")) # prefix [-1,-1,-1,0,-1,-1,0] print(Solution().strStr("abababcdab", "abcaac")) # prefix [-1,-1,-1,0,0,-1] print(Solution().strStr("abababcdab", "abbcc")) # prefix [-1,-1,-1,-1,-1] print(Solution().strStr("abababcdab", "ababcdx")) # prefix [-1,-1,0,1,-1,-1,-1]
class Solution(object): def str_str(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 return self.KMP(haystack, needle) def kmp(self, text, pattern): prefix = self.preKmp(pattern) j = -1 for i in range(len(text)): while j > -1 and text[i] != pattern[j + 1]: j = prefix[j] if text[i] == pattern[j + 1]: j += 1 if j == len(pattern) - 1: return i - j return -1 def pre_kmp(self, s): prefix = [-1] * len(s) j = -1 for i in range(1, len(s)): while j > -1 and s[i] != s[j + 1]: j = prefix[j] if s[i] == s[j + 1]: j += 1 prefix[i] = j return prefix class Solution2(object): def str_str(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 if __name__ == '__main__': print(solution().strStr('abababcdab', 'abcd')) print(solution().strStr('AAAAABAAABA', 'AAAA')) print(solution().strStr('abababcdab', 'ababab')) print(solution().strStr('abababcdab', 'abab')) print(solution().strStr('abababcdab', 'abcdabc')) print(solution().strStr('a', '')) print(solution().strStr('abababcdab', 'abcacba')) print(solution().strStr('abababcdab', 'abcaac')) print(solution().strStr('abababcdab', 'abbcc')) print(solution().strStr('abababcdab', 'ababcdx'))
for i in range(0,3): f = open("dato.txt") f.seek(17+(i*77),0) x1= int(f.read(2)) f.seek(20+(i*77),0) y1= int(f.read(2)) f.seek(35+(i*77),0) a= int(f.read(2)) f.seek(38+(i*77),0) b= int(f.read(2)) f.seek(60+(i*77),0) x2= int(f.read(2)) f.seek(63+(i*77),0) y2= int(f.read(2)) f.seek(73+(i*77),0) r= int(f.read(2)) print (x1,y1,a,b,x2,y2,r ," ") f.close() y=(y1+((b/a)*(x2-x1))) #ecuacion es de la recta d=(r*(1+y)) print ("ecuacion", y) f = open("dato.txt","a") f.write("En la opcion "+str(i)+" ecuacuion que falta "+"\n") f.close()
for i in range(0, 3): f = open('dato.txt') f.seek(17 + i * 77, 0) x1 = int(f.read(2)) f.seek(20 + i * 77, 0) y1 = int(f.read(2)) f.seek(35 + i * 77, 0) a = int(f.read(2)) f.seek(38 + i * 77, 0) b = int(f.read(2)) f.seek(60 + i * 77, 0) x2 = int(f.read(2)) f.seek(63 + i * 77, 0) y2 = int(f.read(2)) f.seek(73 + i * 77, 0) r = int(f.read(2)) print(x1, y1, a, b, x2, y2, r, ' ') f.close() y = y1 + b / a * (x2 - x1) d = r * (1 + y) print('ecuacion', y) f = open('dato.txt', 'a') f.write('En la opcion ' + str(i) + ' ecuacuion que falta ' + '\n') f.close()
a=int(input('Enter number of terms ')) f=1 s=0 for i in range(1,a+1): f=f*i s+=f print('Sum of series =',s)
a = int(input('Enter number of terms ')) f = 1 s = 0 for i in range(1, a + 1): f = f * i s += f print('Sum of series =', s)
# You need Elemental codex 1+ to cast "Haste" hero.cast("haste", hero) hero.moveXY(14, 30) hero.moveXY(20, 30) hero.moveXY(28, 15) hero.moveXY(69, 15) hero.moveXY(72, 58)
hero.cast('haste', hero) hero.moveXY(14, 30) hero.moveXY(20, 30) hero.moveXY(28, 15) hero.moveXY(69, 15) hero.moveXY(72, 58)
""" Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. Every eight bits in the binary string represents one character on the ASCII table. Examples: csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" 01101100 -> 108 -> "l" 01100001 -> 97 -> "a" 01101101 -> 109 -> "m" 01100010 -> 98 -> "b" 01100100 -> 100 -> "d" 01100001 -> 97 -> "a" csBinaryToASCII("") -> "" Notes: The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive). In the case of an empty input string, your function should return an empty string. """ def csBinaryToASCII(binary): return "".join([chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)])
""" Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. Every eight bits in the binary string represents one character on the ASCII table. Examples: csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" 01101100 -> 108 -> "l" 01100001 -> 97 -> "a" 01101101 -> 109 -> "m" 01100010 -> 98 -> "b" 01100100 -> 100 -> "d" 01100001 -> 97 -> "a" csBinaryToASCII("") -> "" Notes: The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive). In the case of an empty input string, your function should return an empty string. """ def cs_binary_to_ascii(binary): return ''.join([chr(int(binary[i:i + 8], 2)) for i in range(0, len(binary), 8)])
# A Bubble class class Bubble(object): # Create the Bubble def __init__(self, x, y, diameter, name): self.x = x self.y = y self.diameter = diameter self.name = name self.over = False # Checking if mouse is over the Bubble def rollover(self, px, py): d = dist(px, py, self.x, self.y) self.over = d < self.diameter / 2 # Display the Bubble def display(self): stroke(0) strokeWeight(2) noFill() ellipse(self.x, self.y, self.diameter, self.diameter) if self.over: fill(0) textAlign(CENTER) text(self.name, self.x, self.y + self.diameter / 2 + 20)
class Bubble(object): def __init__(self, x, y, diameter, name): self.x = x self.y = y self.diameter = diameter self.name = name self.over = False def rollover(self, px, py): d = dist(px, py, self.x, self.y) self.over = d < self.diameter / 2 def display(self): stroke(0) stroke_weight(2) no_fill() ellipse(self.x, self.y, self.diameter, self.diameter) if self.over: fill(0) text_align(CENTER) text(self.name, self.x, self.y + self.diameter / 2 + 20)
queue = [] visited = [] def bfs(visited, graph, start, target): visited.append(start) queue.append(start) while queue: cur = queue.pop(0) if cur == target: break for child in graph[cur]: if child not in visited: visited.append(child) queue.append(child) else: return None return visited if __name__ == "__main__": # A # B C # D E F G graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F', 'G'], 'D' : [], 'E' : ['F'], 'F' : [], 'G' : [] } find = "Q" start = "A" res = bfs(visited, graph, start, find) if res == None: print(f"Can't find node {find} in graph...") else: print(f"Found node {find}, visited: {res}")
queue = [] visited = [] def bfs(visited, graph, start, target): visited.append(start) queue.append(start) while queue: cur = queue.pop(0) if cur == target: break for child in graph[cur]: if child not in visited: visited.append(child) queue.append(child) else: return None return visited if __name__ == '__main__': graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F', 'G'], 'D': [], 'E': ['F'], 'F': [], 'G': []} find = 'Q' start = 'A' res = bfs(visited, graph, start, find) if res == None: print(f"Can't find node {find} in graph...") else: print(f'Found node {find}, visited: {res}')
# 621. Task Scheduler class Solution: # Greedy def leastInterval(self, tasks: List[str], n: int) -> int: # Maximum possible number of idle slots is defined by the frequency of the most frequent task. freq = [0] * 26 for t in tasks: freq[ord(t) - ord('A')] += 1 freq.sort() max_freq = freq.pop() idle_time = (max_freq - 1) * n while freq and idle_time > 0: idle_time -= min(max_freq - 1, freq.pop()) idle_time = max(0, idle_time) return idle_time + len(tasks)
class Solution: def least_interval(self, tasks: List[str], n: int) -> int: freq = [0] * 26 for t in tasks: freq[ord(t) - ord('A')] += 1 freq.sort() max_freq = freq.pop() idle_time = (max_freq - 1) * n while freq and idle_time > 0: idle_time -= min(max_freq - 1, freq.pop()) idle_time = max(0, idle_time) return idle_time + len(tasks)
def ugly1(): q2, q3, q5 = [2], [3], [5] while 1: # print q2, q3, q5 if q2[0] < q3[0] and q2[0] < q5[0]: ret = q2.pop(0) q2.append(ret * 2) q3.append(ret * 3) q5.append(ret * 5) elif q3[0] < q2[0] and q3[0] < q5[0]: ret = q3.pop(0) q3.append(ret * 3) q5.append(ret * 5) else: ret = q5.pop(0) q5.append(ret * 5) yield ret class Solution(object): def __init__(self): self.mzlst = [1] self.mzUgly = ugly1() def nthUglyNumber(self, n): """ :type n: int :rtype: int """ if n < len(self.mzlst): return self.mzlst[n - 1] for i in xrange(len(self.mzlst), n): self.mzlst.append(self.mzUgly.next()) return self.mzlst[n - 1]
def ugly1(): (q2, q3, q5) = ([2], [3], [5]) while 1: if q2[0] < q3[0] and q2[0] < q5[0]: ret = q2.pop(0) q2.append(ret * 2) q3.append(ret * 3) q5.append(ret * 5) elif q3[0] < q2[0] and q3[0] < q5[0]: ret = q3.pop(0) q3.append(ret * 3) q5.append(ret * 5) else: ret = q5.pop(0) q5.append(ret * 5) yield ret class Solution(object): def __init__(self): self.mzlst = [1] self.mzUgly = ugly1() def nth_ugly_number(self, n): """ :type n: int :rtype: int """ if n < len(self.mzlst): return self.mzlst[n - 1] for i in xrange(len(self.mzlst), n): self.mzlst.append(self.mzUgly.next()) return self.mzlst[n - 1]
def fetch_ID(url): ''' Takes a video.dtu.dk link and returns the video ID. TODO: This should make some assertions about the url. ''' return '0_' + url.split('0_')[-1].split('/')[0]
def fetch_id(url): """ Takes a video.dtu.dk link and returns the video ID. TODO: This should make some assertions about the url. """ return '0_' + url.split('0_')[-1].split('/')[0]
""" __init__.py @Organization: @Author: Ming Zhou @Time: 4/22/21 5:28 PM @Function: """
""" __init__.py @Organization: @Author: Ming Zhou @Time: 4/22/21 5:28 PM @Function: """
def sametype(s1: str, s2: str) -> bool: return s1.lower() == s2.lower() def reduct(polymer: str)-> str: did_reduce = True while did_reduce : did_reduce = False for i in range(1, len(polymer)): unit1 = polymer[i-1] unit2 = polymer[i] if sametype(unit1, unit2) and unit1 != unit2: polymer = polymer[:i-1] + polymer[i+1:] did_reduce = True print(len(polymer)) break return polymer TEST_CASE ="dabAcCaCBAcCcaDA" assert reduct(TEST_CASE) == "dabCBAcaDA" with open('data/day05.txt') as f: polymer = f.read().strip() print(reduct(polymer))
def sametype(s1: str, s2: str) -> bool: return s1.lower() == s2.lower() def reduct(polymer: str) -> str: did_reduce = True while did_reduce: did_reduce = False for i in range(1, len(polymer)): unit1 = polymer[i - 1] unit2 = polymer[i] if sametype(unit1, unit2) and unit1 != unit2: polymer = polymer[:i - 1] + polymer[i + 1:] did_reduce = True print(len(polymer)) break return polymer test_case = 'dabAcCaCBAcCcaDA' assert reduct(TEST_CASE) == 'dabCBAcaDA' with open('data/day05.txt') as f: polymer = f.read().strip() print(reduct(polymer))
def run_model(models, features): # First decision for experiment in ["Invasive v.s. Noninvasive", "Atypia and DCIS v.s. Benign", "DCIS v.s. Atypia"]: pca = models[experiment + " PCA"] if pca is not None: features = pca.transform(features).reshape(1, -1) model = models[experiment + " model"] rst = model.predict(features)[0] if rst: if experiment == "Invasive v.s. Noninvasive": return 4, "Invasive" if experiment == "Atypia and DCIS v.s. Benign": return 1, "Benign" if experiment == "DCIS v.s. Atypia": return 3, "DCIS" raise("programming error! unknown experiment") if experiment == "DCIS v.s. Atypia" and not rst: return 2, "Atypia" raise("programming error 2! Unknown experiment and rst")
def run_model(models, features): for experiment in ['Invasive v.s. Noninvasive', 'Atypia and DCIS v.s. Benign', 'DCIS v.s. Atypia']: pca = models[experiment + ' PCA'] if pca is not None: features = pca.transform(features).reshape(1, -1) model = models[experiment + ' model'] rst = model.predict(features)[0] if rst: if experiment == 'Invasive v.s. Noninvasive': return (4, 'Invasive') if experiment == 'Atypia and DCIS v.s. Benign': return (1, 'Benign') if experiment == 'DCIS v.s. Atypia': return (3, 'DCIS') raise 'programming error! unknown experiment' if experiment == 'DCIS v.s. Atypia' and (not rst): return (2, 'Atypia') raise 'programming error 2! Unknown experiment and rst'