content
stringlengths
7
1.05M
def saddle_points(matrix): if not all(len(row) == len(matrix[0]) for row in matrix): raise ValueError("Rows have different length!") _rot_mat = zip(*matrix[::1]) return set([ (row,i) for row in range(len(matrix)) for i,x in enumerate(matrix[row]) if x == max(matrix[row])]) & set([ (i,row) for row in range(len(_rot_mat)) for i,x in enumerate(_rot_mat[row]) if x == min(_rot_mat[row])])
# -*- coding: utf-8 -*- """ @author: Dr Michael GUEDJ Algorithmique -- TP4 -- Boucles "Pour" """ # 1 def dix(): for i in range(10): print(i) # 2 def n_premiers_entiers(n): for i in range(n): print(i) # 3 def n_premiers_entiers_carre(n): for i in range(n): print(i*i) # 4 def n_premiers_entiers_pairs(n): for i in range(n): if i%2 == 0: print(i) # 5 def n_premiers_entiers_impairs(n): for i in range(n): if i%2 == 1: print(i) # 6 def _10_fois_coucou(): for i in range(10): print("coucou") # 7 def n_fois_coucou(n): for i in range(n): print("coucou") # 8 def somme_n_premiers_entiers(n): res = 0 for i in range(n): res += i return res # 9 def somme_n_premiers_carres(n): res = 0 for i in range(n): res += i*i return res # 10 def somme_n_premiers_pairs(n): res = 0 for i in range(n): if i%2 == 0: res += i return res # 11 def somme_n_premiers_impairs(n): res = 0 for i in range(n): if i%2 == 1: res += i return res # 12 def somme_n_premiers_pairs_carre(n): res = 0 for i in range(n): if i%2 == 0: res += i*i return res # 13 def toto(n): res = 0 for i in range(n): if i%3 == 0: res += i return res # 14 def toto2(n, k): res = 0 for i in range(n): if i%k == 0: res += i return res # 15 def toto_bis(n): return toto2(n,3) if __name__ == "__main__": print("exo 1:") dix() print("exo 2:") n_premiers_entiers(5) print("exo 3:") n_premiers_entiers_carre(5) print("exo 4:") n_premiers_entiers_pairs(10) print("exo 5:") n_premiers_entiers_impairs(10) print("exo 6:") _10_fois_coucou() print("exo 7:") n_fois_coucou(5) print("exo 8:", somme_n_premiers_entiers(5)) # 10 print("exo 9:", somme_n_premiers_carres(5)) # 30 print("exo 10:", somme_n_premiers_pairs(10)) # 20 print("exo 11:", somme_n_premiers_impairs(10)) # 25 print("exo 12:", somme_n_premiers_pairs_carre(5)) # 20 print("exo 13:", toto(10)) # 18 print("exo 14:", toto2(10, 3)) # 18 print("exo 15:", toto_bis(10) == toto(10)) # True
# Create empty list: empty = [] print("empty_list: ", empty ) # Create list of fruits: fruits = ["apple", "banana", "strawberry", "banana", "orange"] print("fruits: ", fruits) # Create list of numbers: numbers = [1,2,3,4,5] # Indexing from start to end: print(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]) # Indexing from end to start: print(numbers[-1], numbers[-2], numbers[-3], numbers[-4], numbers[-5])
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class UpgradePhysicalServerAgentsRequest(object): """Implementation of the 'Upgrade Physical Server Agents Request.' model. Specifies a request to upgrade the Cohesity agents on one or more Physical Servers registered on the Cohesity Cluster. Attributes: agent_ids (list of long|int): Array of Agent Ids. Specifies a list of agentIds associated with the Physical Servers to upgrade with the agent release currently available from the Cohesity Cluster. """ # Create a mapping from Model property names to API property names _names = { "agent_ids":'agentIds' } def __init__(self, agent_ids=None): """Constructor for the UpgradePhysicalServerAgentsRequest class""" # Initialize members of the class self.agent_ids = agent_ids @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary agent_ids = dictionary.get('agentIds') # Return an object of this model return cls(agent_ids)
# If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), # then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, # what time do I get home for breakfast? sec_in_1m = 60 left_home_at_in_sec = 6 * 3600 + 52 * 60 total_journey_in_sec = (2 * 8 * sec_in_1m + 2 * 15) + (3 * 7 * sec_in_1m + 3 * 12) got_home_at_in_sec = left_home_at_in_sec + total_journey_in_sec m, s = divmod(got_home_at_in_sec, 60) h, m = divmod(m, 60) print("{:02d}:{:02d}:{:02d}".format(h, m, s))
""" Pipeline for processing the Chile VMS data """ __version__ = '4.1.0' __author__ = 'Enrique Tuya' __email__ = 'enrique@globalfishingwatch.org' __source__ = 'https://github.com/GlobalFishingWatch/pipe-vms-chile' __license__ = """ Copyright 2022 Global Fishing Watch Inc. Authors: Enrique Tuya <enrique@globalfishingwatch.org> 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. """
# Copyright 2013 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of Google Inc. 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 HOLDERS AND CONTRIBUTORS # "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 # OWNER OR CONTRIBUTORS 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. # This file is automatically generated from the V8 source and should not # be modified manually, run 'make grokdump' instead to update this file. # List of known V8 instance types. INSTANCE_TYPES = { 64: "STRING_TYPE", 68: "ASCII_STRING_TYPE", 65: "CONS_STRING_TYPE", 69: "CONS_ASCII_STRING_TYPE", 67: "SLICED_STRING_TYPE", 71: "SLICED_ASCII_STRING_TYPE", 66: "EXTERNAL_STRING_TYPE", 70: "EXTERNAL_ASCII_STRING_TYPE", 74: "EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE", 82: "SHORT_EXTERNAL_STRING_TYPE", 86: "SHORT_EXTERNAL_ASCII_STRING_TYPE", 90: "SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE", 0: "INTERNALIZED_STRING_TYPE", 4: "ASCII_INTERNALIZED_STRING_TYPE", 1: "CONS_INTERNALIZED_STRING_TYPE", 5: "CONS_ASCII_INTERNALIZED_STRING_TYPE", 2: "EXTERNAL_INTERNALIZED_STRING_TYPE", 6: "EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE", 10: "EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE", 18: "SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE", 22: "SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE", 26: "SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE", 128: "SYMBOL_TYPE", 129: "MAP_TYPE", 130: "CODE_TYPE", 131: "ODDBALL_TYPE", 132: "CELL_TYPE", 133: "PROPERTY_CELL_TYPE", 134: "HEAP_NUMBER_TYPE", 135: "FOREIGN_TYPE", 136: "BYTE_ARRAY_TYPE", 137: "FREE_SPACE_TYPE", 138: "EXTERNAL_INT8_ARRAY_TYPE", 139: "EXTERNAL_UINT8_ARRAY_TYPE", 140: "EXTERNAL_INT16_ARRAY_TYPE", 141: "EXTERNAL_UINT16_ARRAY_TYPE", 142: "EXTERNAL_INT32_ARRAY_TYPE", 143: "EXTERNAL_UINT32_ARRAY_TYPE", 144: "EXTERNAL_FLOAT32_ARRAY_TYPE", 145: "EXTERNAL_FLOAT64_ARRAY_TYPE", 146: "EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE", 147: "FIXED_INT8_ARRAY_TYPE", 148: "FIXED_UINT8_ARRAY_TYPE", 149: "FIXED_INT16_ARRAY_TYPE", 150: "FIXED_UINT16_ARRAY_TYPE", 151: "FIXED_INT32_ARRAY_TYPE", 152: "FIXED_UINT32_ARRAY_TYPE", 153: "FIXED_FLOAT32_ARRAY_TYPE", 154: "FIXED_FLOAT64_ARRAY_TYPE", 155: "FIXED_UINT8_CLAMPED_ARRAY_TYPE", 157: "FILLER_TYPE", 158: "DECLARED_ACCESSOR_DESCRIPTOR_TYPE", 159: "DECLARED_ACCESSOR_INFO_TYPE", 160: "EXECUTABLE_ACCESSOR_INFO_TYPE", 161: "ACCESSOR_PAIR_TYPE", 162: "ACCESS_CHECK_INFO_TYPE", 163: "INTERCEPTOR_INFO_TYPE", 164: "CALL_HANDLER_INFO_TYPE", 165: "FUNCTION_TEMPLATE_INFO_TYPE", 166: "OBJECT_TEMPLATE_INFO_TYPE", 167: "SIGNATURE_INFO_TYPE", 168: "TYPE_SWITCH_INFO_TYPE", 170: "ALLOCATION_MEMENTO_TYPE", 169: "ALLOCATION_SITE_TYPE", 171: "SCRIPT_TYPE", 172: "CODE_CACHE_TYPE", 173: "POLYMORPHIC_CODE_CACHE_TYPE", 174: "TYPE_FEEDBACK_INFO_TYPE", 175: "ALIASED_ARGUMENTS_ENTRY_TYPE", 176: "BOX_TYPE", 179: "FIXED_ARRAY_TYPE", 156: "FIXED_DOUBLE_ARRAY_TYPE", 180: "CONSTANT_POOL_ARRAY_TYPE", 181: "SHARED_FUNCTION_INFO_TYPE", 182: "JS_MESSAGE_OBJECT_TYPE", 185: "JS_VALUE_TYPE", 186: "JS_DATE_TYPE", 187: "JS_OBJECT_TYPE", 188: "JS_CONTEXT_EXTENSION_OBJECT_TYPE", 189: "JS_GENERATOR_OBJECT_TYPE", 190: "JS_MODULE_TYPE", 191: "JS_GLOBAL_OBJECT_TYPE", 192: "JS_BUILTINS_OBJECT_TYPE", 193: "JS_GLOBAL_PROXY_TYPE", 194: "JS_ARRAY_TYPE", 195: "JS_ARRAY_BUFFER_TYPE", 196: "JS_TYPED_ARRAY_TYPE", 197: "JS_DATA_VIEW_TYPE", 184: "JS_PROXY_TYPE", 198: "JS_SET_TYPE", 199: "JS_MAP_TYPE", 200: "JS_WEAK_MAP_TYPE", 201: "JS_WEAK_SET_TYPE", 202: "JS_REGEXP_TYPE", 203: "JS_FUNCTION_TYPE", 183: "JS_FUNCTION_PROXY_TYPE", 177: "DEBUG_INFO_TYPE", 178: "BREAK_POINT_INFO_TYPE", } # List of known V8 maps. KNOWN_MAPS = { 0x08081: (136, "ByteArrayMap"), 0x080a9: (129, "MetaMap"), 0x080d1: (131, "OddballMap"), 0x080f9: (4, "AsciiInternalizedStringMap"), 0x08121: (179, "FixedArrayMap"), 0x08149: (134, "HeapNumberMap"), 0x08171: (137, "FreeSpaceMap"), 0x08199: (157, "OnePointerFillerMap"), 0x081c1: (157, "TwoPointerFillerMap"), 0x081e9: (132, "CellMap"), 0x08211: (133, "GlobalPropertyCellMap"), 0x08239: (181, "SharedFunctionInfoMap"), 0x08261: (179, "NativeContextMap"), 0x08289: (130, "CodeMap"), 0x082b1: (179, "ScopeInfoMap"), 0x082d9: (179, "FixedCOWArrayMap"), 0x08301: (156, "FixedDoubleArrayMap"), 0x08329: (180, "ConstantPoolArrayMap"), 0x08351: (179, "HashTableMap"), 0x08379: (128, "SymbolMap"), 0x083a1: (64, "StringMap"), 0x083c9: (68, "AsciiStringMap"), 0x083f1: (65, "ConsStringMap"), 0x08419: (69, "ConsAsciiStringMap"), 0x08441: (67, "SlicedStringMap"), 0x08469: (71, "SlicedAsciiStringMap"), 0x08491: (66, "ExternalStringMap"), 0x084b9: (74, "ExternalStringWithOneByteDataMap"), 0x084e1: (70, "ExternalAsciiStringMap"), 0x08509: (82, "ShortExternalStringMap"), 0x08531: (90, "ShortExternalStringWithOneByteDataMap"), 0x08559: (0, "InternalizedStringMap"), 0x08581: (1, "ConsInternalizedStringMap"), 0x085a9: (5, "ConsAsciiInternalizedStringMap"), 0x085d1: (2, "ExternalInternalizedStringMap"), 0x085f9: (10, "ExternalInternalizedStringWithOneByteDataMap"), 0x08621: (6, "ExternalAsciiInternalizedStringMap"), 0x08649: (18, "ShortExternalInternalizedStringMap"), 0x08671: (26, "ShortExternalInternalizedStringWithOneByteDataMap"), 0x08699: (22, "ShortExternalAsciiInternalizedStringMap"), 0x086c1: (86, "ShortExternalAsciiStringMap"), 0x086e9: (64, "UndetectableStringMap"), 0x08711: (68, "UndetectableAsciiStringMap"), 0x08739: (138, "ExternalInt8ArrayMap"), 0x08761: (139, "ExternalUint8ArrayMap"), 0x08789: (140, "ExternalInt16ArrayMap"), 0x087b1: (141, "ExternalUint16ArrayMap"), 0x087d9: (142, "ExternalInt32ArrayMap"), 0x08801: (143, "ExternalUint32ArrayMap"), 0x08829: (144, "ExternalFloat32ArrayMap"), 0x08851: (145, "ExternalFloat64ArrayMap"), 0x08879: (146, "ExternalUint8ClampedArrayMap"), 0x088a1: (148, "FixedUint8ArrayMap"), 0x088c9: (147, "FixedInt8ArrayMap"), 0x088f1: (150, "FixedUint16ArrayMap"), 0x08919: (149, "FixedInt16ArrayMap"), 0x08941: (152, "FixedUint32ArrayMap"), 0x08969: (151, "FixedInt32ArrayMap"), 0x08991: (153, "FixedFloat32ArrayMap"), 0x089b9: (154, "FixedFloat64ArrayMap"), 0x089e1: (155, "FixedUint8ClampedArrayMap"), 0x08a09: (179, "NonStrictArgumentsElementsMap"), 0x08a31: (179, "FunctionContextMap"), 0x08a59: (179, "CatchContextMap"), 0x08a81: (179, "WithContextMap"), 0x08aa9: (179, "BlockContextMap"), 0x08ad1: (179, "ModuleContextMap"), 0x08af9: (179, "GlobalContextMap"), 0x08b21: (182, "JSMessageObjectMap"), 0x08b49: (135, "ForeignMap"), 0x08b71: (187, "NeanderMap"), 0x08b99: (170, "AllocationMementoMap"), 0x08bc1: (169, "AllocationSiteMap"), 0x08be9: (173, "PolymorphicCodeCacheMap"), 0x08c11: (171, "ScriptMap"), 0x08c61: (187, "ExternalMap"), 0x08cb1: (176, "BoxMap"), 0x08cd9: (158, "DeclaredAccessorDescriptorMap"), 0x08d01: (159, "DeclaredAccessorInfoMap"), 0x08d29: (160, "ExecutableAccessorInfoMap"), 0x08d51: (161, "AccessorPairMap"), 0x08d79: (162, "AccessCheckInfoMap"), 0x08da1: (163, "InterceptorInfoMap"), 0x08dc9: (164, "CallHandlerInfoMap"), 0x08df1: (165, "FunctionTemplateInfoMap"), 0x08e19: (166, "ObjectTemplateInfoMap"), 0x08e41: (167, "SignatureInfoMap"), 0x08e69: (168, "TypeSwitchInfoMap"), 0x08e91: (172, "CodeCacheMap"), 0x08eb9: (174, "TypeFeedbackInfoMap"), 0x08ee1: (175, "AliasedArgumentsEntryMap"), 0x08f09: (177, "DebugInfoMap"), 0x08f31: (178, "BreakPointInfoMap"), } # List of known V8 objects. KNOWN_OBJECTS = { ("OLD_POINTER_SPACE", 0x08081): "NullValue", ("OLD_POINTER_SPACE", 0x08091): "UndefinedValue", ("OLD_POINTER_SPACE", 0x080a1): "TheHoleValue", ("OLD_POINTER_SPACE", 0x080b1): "TrueValue", ("OLD_POINTER_SPACE", 0x080c1): "FalseValue", ("OLD_POINTER_SPACE", 0x080d1): "UninitializedValue", ("OLD_POINTER_SPACE", 0x080e1): "NoInterceptorResultSentinel", ("OLD_POINTER_SPACE", 0x080f1): "ArgumentsMarker", ("OLD_POINTER_SPACE", 0x08101): "NumberStringCache", ("OLD_POINTER_SPACE", 0x08909): "SingleCharacterStringCache", ("OLD_POINTER_SPACE", 0x08d11): "StringSplitCache", ("OLD_POINTER_SPACE", 0x09119): "RegExpMultipleCache", ("OLD_POINTER_SPACE", 0x09521): "TerminationException", ("OLD_POINTER_SPACE", 0x09531): "MessageListeners", ("OLD_POINTER_SPACE", 0x0954d): "CodeStubs", ("OLD_POINTER_SPACE", 0x0ca65): "MegamorphicSymbol", ("OLD_POINTER_SPACE", 0x0ca75): "UninitializedSymbol", ("OLD_POINTER_SPACE", 0x10ae9): "NonMonomorphicCache", ("OLD_POINTER_SPACE", 0x110fd): "PolymorphicCodeCache", ("OLD_POINTER_SPACE", 0x11105): "NativesSourceCache", ("OLD_POINTER_SPACE", 0x11155): "EmptyScript", ("OLD_POINTER_SPACE", 0x11189): "IntrinsicFunctionNames", ("OLD_POINTER_SPACE", 0x141a5): "ObservationState", ("OLD_POINTER_SPACE", 0x141b1): "FrozenSymbol", ("OLD_POINTER_SPACE", 0x141c1): "NonExistentSymbol", ("OLD_POINTER_SPACE", 0x141d1): "ElementsTransitionSymbol", ("OLD_POINTER_SPACE", 0x141e1): "EmptySlowElementDictionary", ("OLD_POINTER_SPACE", 0x1437d): "ObservedSymbol", ("OLD_POINTER_SPACE", 0x1438d): "AllocationSitesScratchpad", ("OLD_POINTER_SPACE", 0x14795): "MicrotaskState", ("OLD_POINTER_SPACE", 0x36241): "StringTable", ("OLD_DATA_SPACE", 0x08099): "EmptyDescriptorArray", ("OLD_DATA_SPACE", 0x080a1): "EmptyFixedArray", ("OLD_DATA_SPACE", 0x080a9): "NanValue", ("OLD_DATA_SPACE", 0x08141): "EmptyByteArray", ("OLD_DATA_SPACE", 0x08149): "EmptyConstantPoolArray", ("OLD_DATA_SPACE", 0x0828d): "EmptyExternalInt8Array", ("OLD_DATA_SPACE", 0x08299): "EmptyExternalUint8Array", ("OLD_DATA_SPACE", 0x082a5): "EmptyExternalInt16Array", ("OLD_DATA_SPACE", 0x082b1): "EmptyExternalUint16Array", ("OLD_DATA_SPACE", 0x082bd): "EmptyExternalInt32Array", ("OLD_DATA_SPACE", 0x082c9): "EmptyExternalUint32Array", ("OLD_DATA_SPACE", 0x082d5): "EmptyExternalFloat32Array", ("OLD_DATA_SPACE", 0x082e1): "EmptyExternalFloat64Array", ("OLD_DATA_SPACE", 0x082ed): "EmptyExternalUint8ClampedArray", ("OLD_DATA_SPACE", 0x082f9): "InfinityValue", ("OLD_DATA_SPACE", 0x08305): "MinusZeroValue", ("CODE_SPACE", 0x138e1): "JsConstructEntryCode", ("CODE_SPACE", 0x21361): "JsEntryCode", }
# Databricks notebook source # MAGIC %md-sandbox # MAGIC # MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> # MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> # MAGIC </div> # COMMAND ---------- # MAGIC %md # MAGIC # Conditionals and Loops # MAGIC # MAGIC ## In this lesson you: # MAGIC - Create a simple list # MAGIC - Iterate over a list using a **`for`** expression # MAGIC - Conditionally execute statements using **`if`**, **`elif`** and **`else`** expressions # COMMAND ---------- # MAGIC %md # MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) C-Style For Loops # MAGIC # MAGIC If you have any programming experience in other structured programming languages, you should be familair with **C-Style For Loops** # MAGIC # MAGIC If not, a little history wont hurt... # MAGIC # MAGIC The classic c-style for loop will look something like this: # COMMAND ---------- # MAGIC %md # MAGIC # MAGIC ``` # MAGIC for (i = 0; i < 10; i++) { # MAGIC print(i) # MAGIC } # MAGIC ``` # COMMAND ---------- # MAGIC %md # MAGIC What is unique about this syntax is: # MAGIC * **`i`** is a varaible that is initially set to **`0`** # MAGIC * **`i`** is incremented by one (**`i++`**) after each iteration of the loop # MAGIC * Incrementation and block-execution is repeated while the prescribed condition (**`i < 10`**) is true # COMMAND ---------- # MAGIC %md # MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) For-In Loops # MAGIC # MAGIC More modern programming languages such as Python, Scala, Java, and others, have abandoned if not deprecated this type of loop. # MAGIC # MAGIC Instead they use a for-in methodology that amounts to executing a block of code once for every item in a list. # MAGIC # MAGIC To see how this works, we need to first introduce a list - we will cover lists in more details in a latter section. # COMMAND ---------- # MAGIC %md # MAGIC Let's make a <a href="https://docs.python.org/3/library/stdtypes.html#list" target="_blank">list</a> of what everyone ate for breakfast this morning. # MAGIC # MAGIC <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Scrambed_eggs.jpg/1280px-Scrambed_eggs.jpg" width="20%" height="10%"> # COMMAND ---------- breakfast_list = ["pancakes", "eggs", "waffles"] # Declare the list print(breakfast_list) # Print the entire list # COMMAND ---------- # MAGIC %md # MAGIC There are a lot of different things we can do with a list such as: # MAGIC * Iterating over a list # MAGIC * Accessing specific elements of a list # MAGIC * Slicing a list # MAGIC * Appending to a list # MAGIC * Removing items from a list # MAGIC * Concatenating lists # MAGIC * and so on... # MAGIC # MAGIC For now, let's focus on iterating over a list and printing each individual item in the list: # COMMAND ---------- for food in breakfast_list: print(food) print("This is executed once because it is outside the for loop") # COMMAND ---------- # MAGIC %md So how does one replicate a C-Style For Loop on a range of numbers in Python? # MAGIC # MAGIC For that, we can use the <a href="https://docs.python.org/3/library/functions.html#func-range" target="_blank">range</a> function which produces an immutable collection of nubmers (a type of list). # COMMAND ---------- for i in range(0, 5): print(i) # COMMAND ---------- # MAGIC %md We will talk more about collections in a later section including lists, ranges, dictionaries, etc. # MAGIC # MAGIC The key thing to remember here is that they are all iterable and the **`for-in`** expression allows us to iterate over them. # COMMAND ---------- # MAGIC %md # MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) Conditionals # MAGIC # MAGIC Before exploring loops further, let's take a look at conditionals. # MAGIC # MAGIC At the end of this lesson, we combine these two concepts so as to develop more complex constructs. # COMMAND ---------- # MAGIC %md # MAGIC # MAGIC We don't always want to execute every line of code. # MAGIC # MAGIC We can that process by employing **`if`**, **`elif`**, and **`else`** expressions. # MAGIC # MAGIC We can see a few examples here: # COMMAND ---------- food = "bacon" if food == "eggs": print("Make scrambled eggs") print("All done") # COMMAND ---------- # MAGIC %md In the example above, line #5 is not executed. # MAGIC # MAGIC Edit line #2 above and set the variable **`food`** to **`"eggs"`** and rerun the command. # COMMAND ---------- # MAGIC %md Let's build on this example with an **`else`** expression... # COMMAND ---------- food = "bacon" if food == "eggs": print("Make scrambled eggs") else: print(f"I don't know what to do with {food}") print("All done") # COMMAND ---------- # MAGIC %md And lastly, we can introduce the **`elif`** expression... # COMMAND ---------- food = "bacon" if food == "eggs": print("Make scrambled eggs") elif food == "waffles": print("I need syrup for my waffles") else: print(f"I don't know what to do with {food}") print("All done") # COMMAND ---------- # MAGIC %md # MAGIC What if the expression needs to be more complex? # MAGIC # MAGIC For example, if I need syrup with waffles or pancakes? # MAGIC # MAGIC Each **`if`** and **`elif`** expression can get increasignly more complex by adding more conditional statements and combining them with various **`and`** &amp; **`or`** operators # COMMAND ---------- food = "bacon" if food == "eggs": print("Make scrambled eggs") elif food == "waffles" or food == "pancakes": print(f"I need syrup for my {food}") else: print(f"I don't know what to do with {food}") print("All done") # COMMAND ---------- # MAGIC %md # MAGIC Besides compounding conditional statements, we can also nest **`if`**, **`elif`** and **`else`** expressions: # COMMAND ---------- food = "bacon" if food != "eggs": if food == "waffles" or food == "pancakes": print(f"I need syrup for my {food}") else: print(f"I don't know what to do with {food}") else: print("Make scrambled eggs") print("All done") # COMMAND ---------- # MAGIC %md # MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) Loops & Conditionals # MAGIC # MAGIC Lastly, let's take a look at how we can combine these two constructs. # MAGIC # MAGIC Before we do, let's review the contents of our breakfast list: # COMMAND ---------- for food in breakfast_list: print(food) # COMMAND ---------- # MAGIC %md Next we will iterate over that list and instead of printing each item, we can run through our conditionals instead # COMMAND ---------- for food in breakfast_list: if food != "eggs": if food == "waffles" or food == "pancakes": print(f"I need syrup for my {food}") else: print(f"I don't know what to do with {food}") else: print("Make scrambled eggs") print("All done") # COMMAND ---------- # MAGIC %md-sandbox # MAGIC &copy; 2020 Databricks, Inc. All rights reserved.<br/> # MAGIC Apache, Apache Spark, Spark and the Spark logo are trademarks of the <a href="http://www.apache.org/">Apache Software Foundation</a>.<br/> # MAGIC <br/> # MAGIC <a href="https://databricks.com/privacy-policy">Privacy Policy</a> | <a href="https://databricks.com/terms-of-use">Terms of Use</a> | <a href="http://help.databricks.com/">Support</a>
# -*- coding: utf-8 -*- """ Created on Fri Jun 4 09:31:28 2021 @author: dsd """ if __name__ == '__main__': wrd = input("Введите предложение: ") smb = input("Введите символ: ") cout = wrd.count(smb) while cout > 0: print(smb) cout =- 1
""" The purpose of the prototype DMA Performance Measurement application is to measures mode-independent trip-based traveler mobility and system productivity by taking trip or trajectory based vehicle input and aggregating that information into system wide performance measures. The DMA Performance Measurement application uses trip-based system performance measure algorithms developed under the Integrated Corridor Management (ICM) Program and adapts them for use with observed data to measure travel time reliability, delay,and throughput. The program has four(4) files: DPM.py - Main program Files.py - Classes used to read in all of the input files sqlload.py - Classes to control the program's interface with the SQLlite database timeslice.py - Class that is used for managing and determining the individual time slices based on the trip starting time To run the program type the following from a command prompt: >>python DPM.py -file [your control file name] """ __author__ = 'Jim Larkin (Noblis)' __date__ = 'February 2012' __credits__ = ["Meenakshy Vasudevan (Noblis)","Karl Wunderlich (Noblis)"] __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Jim Larkin (Noblis)" __email__ = "jlarkin@noblis.org" __status__ = "Prototype" class Timeslice: """ Class that is used for managing and determining the individual time slices based on the trip starting time. """ def __init__(self, start, end, interval ): """ Creation method that sets the baseline parameters of starting time, ending time, and interval length @param start - integer value for starting time of evaluation in seconds @param end - integer value for ending time of evaluation in seconds @param interval - integer value for the time interval for each time slice in seconds @return Nothing """ self.interval = interval self.start = start self.end = end self.interval_start = start self.interval_end = int(start) + int(interval) def bin_num(self, start_time): """ Determines which bin (time slice) a trip should be placed in based on the trip start time and returns the bin number. @param start_time - integer/float/str value for the starting time of the trip. @return integer value for the bin number for the trip """ #if in range if float(self.start) <= float(start_time) <= float(self.end): value = int(abs(float(self.start) - float(start_time))/ float(self.interval)) return value def __iter__(self): """ Method that allows the Time slices to be iterated over @param None @return self """ return self def reset(self): """ Returns the interval values to their starting values @param None @return None """ self.interval_start = self.start self.interval_end = self.start + self.interval def next(self): """ Method that runs when the class is used in a loop to pull the next value @param None @return None """ if (self.interval_start + self.interval) >= self.end: raise StopIteration else: self.interval_start += self.interval self.interval_end += self.interval def __str__(self): """ Method that returns a string representation of the time interval @param None @return string with the starting and ending time for the current interval """ return "{} - {}".format(self.interval_start, self.interval_end)
def solution(): T = int(input()) for t in range(1, T+1): solve(t) def solve(t): m = int(input()) c = list(map(int, input().split(' '))) c[0] = -c[0] # Newton's method, not well, binary is good f = lambda x: sum([e*x**(m-i) for i,e in enumerate(c)]) ef = lambda x: sum([(m-i)*e*x**(m-i-1) for i,e in enumerate(c)]) x = 1.0 left, right = 10**-10, 2.0 - 10**-10 while right - left > 10**-10: a = f(left) b = f(x) if a==0: x = a break if b==0: break if a*b > 0: left = x else: right = x x = (left+right)/2 print('Case #%d: %.12f' % (t, x-1)) solution()
class destination(object): planet = 1 debris = 2 moon = 3 def coordinates(galaxy, system, position=None, dest=destination.planet): return [galaxy, system, position, dest] class mission(object): attack = 1 transport = 3 park = 4 park_ally = 5 spy = 6 colonize = 7 recycle = 8 destroy = 9 expedition = 15 class speed(object): _10 = 1 _20 = 2 _30 = 3 _40 = 4 _50 = 5 _60 = 6 _70 = 7 _80 = 8 _90 = 9 _100 = 10 max = 10 min = 1 class buildings(object): metal_mine = 1, 1, 'supplies' crystal_mine = 2, 1, 'supplies' deuterium_mine = 3, 1, 'supplies' solar_plant = 4, 1, 'supplies' fusion_plant = 12, 1, 'supplies' def solar_satellite(self=1): return 212, self, 'supplies' def crawler(self=1): return 217, self, 'supplies' metal_storage = 22, 1, 'supplies' crystal_storage = 23, 1, 'supplies' deuterium_storage = 24, 1, 'supplies' robotics_factory = 14, 1, 'facilities' shipyard = 21, 1, 'facilities' research_laboratory = 31, 1, 'facilities' alliance_depot = 34, 1, 'facilities' missile_silo = 44, 1, 'facilities' nanite_factory = 15, 1, 'facilities' terraformer = 33, 1, 'facilities' repair_dock = 36, 1, 'facilities' def rocket_launcher(self=1): return 401, self, 'defenses' def laser_cannon_light(self=1): return 402, self, 'defenses' def laser_cannon_heavy(self=1): return 403, self, 'defenses' def gauss_cannon(self=1): return 404, self, 'defenses' def ion_cannon(self=1): return 405, self, 'defenses' def plasma_cannon(self=1): return 406, self, 'defenses' def shield_dome_small(self=1): return 407, self, 'defenses' def shield_dome_large(self=1): return 408, self, 'defenses' def missile_interceptor(self=1): return 502, self, 'defenses' def missile_interplanetary(self=1): return 503, self, 'defenses' moon_base = 41, 1, 'facilities' sensor_phalanx = 42, 1, 'facilities' jump_gate = 43, 1, 'facilities' class research(object): energy = 113, 1, 'research' laser = 120, 1, 'research' ion = 121, 1, 'research' hyperspace = 114, 1, 'research' plasma = 122, 1, 'research' combustion_drive = 115, 1, 'research' impulse_drive = 117, 1, 'research' hyperspace_drive = 118, 1, 'research' espionage = 106, 1, 'research' computer = 108, 1, 'research' astrophysics = 124, 1, 'research' research_network = 123, 1, 'research' graviton = 199, 1, 'research' weapons = 109, 1, 'research' shielding = 110, 1, 'research' armor = 111, 1, 'research' class ships(object): def light_fighter(self): return 204, self, 'shipyard' def heavy_fighter(self): return 205, self, 'shipyard' def cruiser(self): return 206, self, 'shipyard' def battleship(self): return 207, self, 'shipyard' def interceptor(self): return 215, self, 'shipyard' def bomber(self): return 211, self, 'shipyard' def destroyer(self): return 213, self, 'shipyard' def deathstar(self): return 214, self, 'shipyard' def reaper(self): return 218, self, 'shipyard' def explorer(self): return 219, self, 'shipyard' def small_transporter(self): return 202, self, 'shipyard' def large_transporter(self): return 203, self, 'shipyard' def colonyShip(self): return 208, self, 'shipyard' def recycler(self): return 209, self, 'shipyard' def espionage_probe(self): return 210, self, 'shipyard' def is_ship(ship): if ship[2] == 'shipyard': return True else: return False def get_ship_name(ship): if ships.is_ship(ship): if ship[0] == 204: return 'light_fighter' if ship[0] == 205: return 'heavy_fighter' if ship[0] == 206: return 'cruiser' if ship[0] == 207: return 'battleship' if ship[0] == 215: return 'interceptor' if ship[0] == 211: return 'bomber' if ship[0] == 213: return 'destroyer' if ship[0] == 214: return 'deathstar' if ship[0] == 218: return 'reaper' if ship[0] == 219: return 'explorer' if ship[0] == 202: return 'small_transporter' if ship[0] == 203: return 'large_transporter' if ship[0] == 208: return 'colonyShip' if ship[0] == 209: return 'recycler' if ship[0] == 210: return 'espionage_probe' if ship[0] == 217: return 'crawler' def get_ship_amount(ship): if ships.is_ship(ship): return ship[1] def get_ship_id(ship): if ships.is_ship(ship): return ship[0] def resources(metal=0, crystal=0, deuterium=0): return [metal, crystal, deuterium] class status: inactive = 'inactive' longinactive = 'longinactive' vacation = 'vacation' admin = 'admin' noob = 'noob' honorable_target = 'honorableTarget' active = 'active'
""" 1) The conditional probability distribution is using a measurement to restrict the likely value of one of the variables. If there is correlation, this will also affect what we know (conditionally) about the other! However, the marginal probability *only* depends on the direction along which we are marginalizing. So, when the conditional probability is based on a measurement at the means, it is the same as marginalization, as there is no additional information. A further note is that we can also marginalize along other directions (e.g. a diagonal), but we are not exploring this here. 2) The larger the correlation, the more shared information. So the more we gain about the second variable (or hidden state) by measuring a value from the other. 3) The variable (hidden state) with the lower variance will produce a narrower conditional probabilty for the other variable! As you shift the correlation, you will see small changes in the variable with the low variance shifting the conditional mean of the variable with the large variance! (So, if X has low variance, changing CY has a big effect.) """
""" 系统中的常量 """ # ############在后台管理中需要使用的常量############# # 在修改基础数据页面,前端v-model需要的key BASE_DATA_KEY = { "Locus_tags": 'locus_tags', "TSS_ID": 'tss_id', "Chromosome": 'chromosome', "Strand": 'strand', "Position": 'position', "Distances to start codon": 'distance', "Locus_tag": 'locus_tag', "Chrs": 'chrs', "Start": 'start', "End": 'end', "ID": 'id', "Type": 'type', "Product": 'product', "ProAccNo": 'pro_acc_no' } # ############在前台展示中需要使用的常量#############
class Solution: def intToRoman(self, num: int) -> str: M = ["", "M", "MM", "MMM"] C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] return M[num // 1000] + C[num % 1000 // 100] + X[num % 100 // 10] + I[num % 10] # TESTS for num, expected in [ (3, "III"), (4, "IV"), (9, "IX"), (58, "LVIII"), (1994, "MCMXCIV"), ]: sol = Solution() actual = sol.intToRoman(num) print("Int", num, "to roman ->", actual) assert actual == expected
# coding=utf-8 """ @project : formula-manager @ide : PyCharm @file : __init__.py @author : illusion @desc : @create : 2021/8/8 11:13 上午:54 """
helpstring = "voice <nick>" arguments = ["self", "info", "args"] minlevel = 3 def main(connection, info, args) : """Voices a user""" for person in args[1:] : connection.rawsend("MODE %s +v %s\n" % (info["channel"], person))
# # PySNMP MIB module CISCO-ZS-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ZS-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:21:44 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") vsanIndex, = mibBuilder.importSymbols("CISCO-VSAN-MIB", "vsanIndex") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ObjectIdentity, IpAddress, Gauge32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, NotificationType, Integer32, TimeTicks, Unsigned32, Counter64, Bits, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "Gauge32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "NotificationType", "Integer32", "TimeTicks", "Unsigned32", "Counter64", "Bits", "Counter32", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ciscoZsExtMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 427)) ciscoZsExtMIB.setRevisions(('2006-01-03 00:00', '2004-08-11 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoZsExtMIB.setRevisionsDescriptions(('Added objects czseGlobalDefaultZoneBehaviour and czseGlobalPropagationMode.', 'Initial version of this MIB.',)) if mibBuilder.loadTexts: ciscoZsExtMIB.setLastUpdated('200601030000Z') if mibBuilder.loadTexts: ciscoZsExtMIB.setOrganization('Cisco Systems Inc.') if mibBuilder.loadTexts: ciscoZsExtMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoZsExtMIB.setDescription("The MIB module for the management of zoning within the framework of Cisco's Zoning Server (ZS) Archi- tecture which realizes the FC-GS4/SW3 requirements for Zone Server. This MIB is an extension to the CISCO-ZS-MIB, which is for managing zoning conforming to FC-GS3/SW2. The FC-GS4 specification is Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8. The SW3 specification is Fibre-Channel - Switch Fabric - 3 T11/Project 1508- D/Rev 6.6. GS4/SW3 allows zoning to operate in either basic or enhanced mode of operation. Basic mode is essentially GS3/SW2 compatible mode (as modelled by CISCO-ZS-MIB). Enhanced mode of operation provides additional capabilities. In enhanced mode of operation, all the configuration should be done within the scope of a session. The current 'Running Configuration' on the local device for zone server is called the 'effective' database. When the first configuration command on the zone server data is received, a snapshot of the current 'effective database' is taken on the local device. This snapshot is called the 'copy' database. An implicit session is started by the Zone Server on the local device and all subsequent SET operations take place in the context of this session. The 'copy' database is used for all further modifications in the session. There can be only one session active in the entire Fibre Channel fabric. The user who initiates the creation of this 'copy', is called the owner of session. When a session has been created on a device in the Fibre Channel fabric, if an attempt is made to start a session from any other device in the fabric, it results in error. Once the modifications to the 'copy' are done, a 'commit' operation can be done. The 'commit' done on the local device, results in the local 'effective database' being overwritten with the 'copy' and then the new local 'effective database' is distributed to all other devices in the Fibre Channel fabric. The successful 'commit' operation also results in destroying the 'copy' on the local device. The 'commit' can only be performed by the owner of the session. The 'copy' can optionally be destroyed without any distribution. This can be done by performing a 'clear' operation. Glossary of terms used in this MIB ---------------------------------- VSAN - Virtual Storage Area Network.") ciscoZsExtMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 0)) ciscoZsExtMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1)) ciscoZsExtMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2)) czseConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1)) czseStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 2)) class CzseSessOwnerType(TextualConvention, Integer32): description = 'Represents the type of owner of a GS4 session. other - other type of owner. cli - Command Line Interface (CLI) is the owner. gs4client - Fibre Channel GS4 services client. snmp - SNMP is the owner.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("other", 1), ("cli", 2), ("gs4client", 3), ("snmp", 4)) czseCapabilityTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1), ) if mibBuilder.loadTexts: czseCapabilityTable.setStatus('current') if mibBuilder.loadTexts: czseCapabilityTable.setDescription('This table lists the capabilities of the Zone Server on the local device. This information is maintained on a per VSAN basis.') czseCapabilityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseCapabilityEntry.setStatus('current') if mibBuilder.loadTexts: czseCapabilityEntry.setDescription('An entry represents the capability of the Zone Server on the local device on a VSAN.') czseCapabilityObject = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("enhancedMode", 0), ("zsetDb", 1), ("dirAct", 2), ("hardZoning", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseCapabilityObject.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 6.1.22.4.4') if mibBuilder.loadTexts: czseCapabilityObject.setStatus('current') if mibBuilder.loadTexts: czseCapabilityObject.setDescription("This bitmap represents the capability of the local Zone Server on this VSAN. If 'enhancedMode(0)' bit is set, the local Zone Server is capable of supporting enhanced Zoning mode of operation. If this bit is reset, it does not have this capability. If 'zsetDb(1)' bit is set, the local Zone Server supports maintaining of zoneset database. If this bit is reset, the local Zone Server does not allow maintaining of zoneset database. If 'dirAct(2)' bit is set, the local Zone Server supports direct activation command. If this bit is reset, the local Zone Server does not support this. If 'hardZoning(3)' bit is set, the local Zone Server supports hard zoning. If this bit is reset, the local Zone Server does not support hard zoning.") czseModeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2), ) if mibBuilder.loadTexts: czseModeTable.setStatus('current') if mibBuilder.loadTexts: czseModeTable.setDescription('A table containing information on the mode of operation of the zone server on all VSANs on the local device.') czseModeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseModeEntry.setStatus('current') if mibBuilder.loadTexts: czseModeEntry.setDescription('An entry represents the mode of operation of the local zone server on a VSAN. The mode can be modified on a VSAN and the outcome of the operation obtained.') czseOperationMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("basic", 1), ("enhanced", 2))).clone('basic')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseOperationMode.setReference('Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8 Section 6.4.7. Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.6') if mibBuilder.loadTexts: czseOperationMode.setStatus('current') if mibBuilder.loadTexts: czseOperationMode.setDescription("This object when set to 'basic(1)', results in the zone server operating in the basic mode as defined by FC-GS4 standards. This object when set to 'enhanced(2)', results in the zone server operating in the enhanced mode as defined by FC-GS4 standards. The local zone server can move to the enhanced mode of operation only if all devices in the Fibre Channel fabric are capable of working in enhanced mode. Otherwise, the set operation trying to set this object to 'enhanced(2)' will fail.") czseOperationModeResult = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("success", 1), ("failure", 2), ("inProgress", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseOperationModeResult.setStatus('current') if mibBuilder.loadTexts: czseOperationModeResult.setDescription('The outcome of setting the mode of operation of the local Zone Server on this VSAN.') czseReadFrom = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("effectiveDB", 1), ("copyDB", 2))).clone('effectiveDB')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseReadFrom.setStatus('current') if mibBuilder.loadTexts: czseReadFrom.setDescription("This object specifies whether the management station wishes to read from the 'effective database' or from the 'copy' database.") czseSessionTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4), ) if mibBuilder.loadTexts: czseSessionTable.setStatus('current') if mibBuilder.loadTexts: czseSessionTable.setDescription("A table containing information on sessions on the local device on all VSANs. Operations are permitted on this table only when the zone server is running in 'enhanced' mode.") czseSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseSessionEntry.setStatus('current') if mibBuilder.loadTexts: czseSessionEntry.setDescription('An entry contains information on the owner of a session on a VSAN. It also assists in performing commit/clear operations on the session.') czseSessionOwnerType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 1), CzseSessOwnerType()).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionOwnerType.setStatus('current') if mibBuilder.loadTexts: czseSessionOwnerType.setDescription('This object specifies the owner type for this session.') czseSessionOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionOwner.setStatus('current') if mibBuilder.loadTexts: czseSessionOwner.setDescription("This object specifies the owner for this session. If the value of the corresponding instance of czseSessionOwnerType object is 'cli', this object will contain the user name of the CLI (Command Line Interface) user, who is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'gs4client', this object will contain the FCID of the GS4 management station, which is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'snmp', this object will contain the IP address of the management station, which is the owner of the session on this VSAN.") czseSessionCntl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("commitChanges", 1), ("cleanup", 2), ("noop", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseSessionCntl.setStatus('current') if mibBuilder.loadTexts: czseSessionCntl.setDescription("This object assists in committing or clearing the contents of the 'copy' database on this session. No action is taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'. The above operation can only be performed by the owner of the session.") czseSessionCntlResult = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("commitSuccess", 1), ("commitFailure", 2), ("inProgress", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionCntlResult.setStatus('current') if mibBuilder.loadTexts: czseSessionCntlResult.setDescription("This object indicates the outcome of setting the corresponding instance of czseSessionCntl object to 'commitChanges(1)'.") czseMergeControlTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5), ) if mibBuilder.loadTexts: czseMergeControlTable.setStatus('current') if mibBuilder.loadTexts: czseMergeControlTable.setDescription("A table containing information on zone merge control policy on all VSANs in the entire fabric. Operations on this table are permitted only when the zone server is running in 'enhanced' mode.") czseMergeControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseMergeControlEntry.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.5.2.2') if mibBuilder.loadTexts: czseMergeControlEntry.setStatus('current') if mibBuilder.loadTexts: czseMergeControlEntry.setDescription('An entry contains information on the Merge Control policy on a VSAN. The policy can be modified on a per VSAN basis by making use of czseMergeContolRestrict object.') czseMergeControlRestrict = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("restrict", 2))).clone('allow')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseMergeControlRestrict.setStatus('current') if mibBuilder.loadTexts: czseMergeControlRestrict.setDescription("This object controls the zone merge behavior. If this object is set to 'allow', then the merge takes place according to the merge rules. If this object is set to 'restrict', then if the merging databases are not exactly identical, the Inter-Switch Link (ISL) between the devices is isolated.") czseGlobalDefaultZoneBehaviour = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2))).clone('deny')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setStatus('current') if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setDescription("This object represents the initial value for default zone behaviour on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the default zone behaviour will be set to the value specified for this object. The semantics of setting this object to 'permit' or 'deny' are described in the description for zoneDefaultZoneBehaviour object in CISCO-ZS-MIB. After a VSAN has been created, if the value for default zone behaviour for that VSAN has to be changed, the zoneDefaultZoneBehaviour object in CISCO-ZS-MIB has to be used.") czseGlobalPropagationMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("fullZoneset", 1), ("activeZoneset", 2))).clone('activeZoneset')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseGlobalPropagationMode.setStatus('current') if mibBuilder.loadTexts: czseGlobalPropagationMode.setDescription("This object represents the initial value for zone set propagation mode on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the zone set propagation mode will be set to the value specified for this object. The semantics of setting this object to 'fullZoneset' or 'activeZoneset' are described in the description for zoneSetPropagationMode object in CISCO-ZS-MIB. After a VSAN has been created, if the value for zone set propagation mode has to be changed for that particular VSAN, the zoneSetPropagationMode object in CISCO-ZS-MIB has to be used.") ciscoZsExtMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1)) ciscoZsExtMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2)) ciscoZsExtMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 1)).setObjects(("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtMIBCompliance = ciscoZsExtMIBCompliance.setStatus('deprecated') if mibBuilder.loadTexts: ciscoZsExtMIBCompliance.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') ciscoZsExtMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 2)).setObjects(("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroup"), ("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroupSup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtMIBComplianceRev1 = ciscoZsExtMIBComplianceRev1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtMIBComplianceRev1.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') ciscoZsExtConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 1)).setObjects(("CISCO-ZS-EXT-MIB", "czseCapabilityObject"), ("CISCO-ZS-EXT-MIB", "czseOperationMode"), ("CISCO-ZS-EXT-MIB", "czseOperationModeResult"), ("CISCO-ZS-EXT-MIB", "czseReadFrom"), ("CISCO-ZS-EXT-MIB", "czseSessionOwnerType"), ("CISCO-ZS-EXT-MIB", "czseSessionOwner"), ("CISCO-ZS-EXT-MIB", "czseSessionCntl"), ("CISCO-ZS-EXT-MIB", "czseSessionCntlResult"), ("CISCO-ZS-EXT-MIB", "czseMergeControlRestrict")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtConfigGroup = ciscoZsExtConfigGroup.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroup.setDescription('A collection of object(s) for configuring and displaying Zone Server conforming with FC-GS4/SW3.') ciscoZsExtConfigGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 2)).setObjects(("CISCO-ZS-EXT-MIB", "czseGlobalDefaultZoneBehaviour"), ("CISCO-ZS-EXT-MIB", "czseGlobalPropagationMode")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtConfigGroupSup1 = ciscoZsExtConfigGroupSup1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroupSup1.setDescription('A collection of objects for configuring global zoning policies.') mibBuilder.exportSymbols("CISCO-ZS-EXT-MIB", czseOperationMode=czseOperationMode, czseSessionEntry=czseSessionEntry, czseMergeControlTable=czseMergeControlTable, czseSessionOwnerType=czseSessionOwnerType, czseMergeControlEntry=czseMergeControlEntry, PYSNMP_MODULE_ID=ciscoZsExtMIB, czseOperationModeResult=czseOperationModeResult, czseCapabilityTable=czseCapabilityTable, ciscoZsExtMIBCompliance=ciscoZsExtMIBCompliance, ciscoZsExtMIB=ciscoZsExtMIB, czseModeEntry=czseModeEntry, czseModeTable=czseModeTable, czseSessionCntlResult=czseSessionCntlResult, czseCapabilityObject=czseCapabilityObject, czseSessionOwner=czseSessionOwner, czseCapabilityEntry=czseCapabilityEntry, ciscoZsExtMIBComplianceRev1=ciscoZsExtMIBComplianceRev1, ciscoZsExtMIBConform=ciscoZsExtMIBConform, czseStats=czseStats, ciscoZsExtMIBGroups=ciscoZsExtMIBGroups, czseSessionTable=czseSessionTable, ciscoZsExtConfigGroupSup1=ciscoZsExtConfigGroupSup1, ciscoZsExtMIBCompliances=ciscoZsExtMIBCompliances, czseGlobalPropagationMode=czseGlobalPropagationMode, ciscoZsExtConfigGroup=ciscoZsExtConfigGroup, czseSessionCntl=czseSessionCntl, czseReadFrom=czseReadFrom, czseMergeControlRestrict=czseMergeControlRestrict, czseConfiguration=czseConfiguration, ciscoZsExtMIBObjects=ciscoZsExtMIBObjects, CzseSessOwnerType=CzseSessOwnerType, czseGlobalDefaultZoneBehaviour=czseGlobalDefaultZoneBehaviour, ciscoZsExtMIBNotifs=ciscoZsExtMIBNotifs)
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) dp = [cost[0], cost[1], 0] for i in range(2, n): dp[i % 3] = cost[i] + min(dp[(i - 1) % 3], dp[(i - 2) % 3]) return min(dp[(n - 1) % 3], dp[(n - 2) % 3])
""" Do not import anything from the rest of Kolibri in this module, it's crucial that it can be loaded without the settings/configuration/django stack! """
# Copyright (c) 2018 PrimeVR # All rights Reserved ############################################################################### # print helpers ############################################################################### CHILL_WHITE = '\x1b[0;37;40m' CHILL_PURPLE = '\x1b[0;35;40m' CHILL_LIGHT_BLUE = '\x1b[0;36;40m' CHILL_BLUE = '\x1b[0;34;40m' MEGA_WHITE = '\x1b[1;37;40m' LIGHT_BLUE = '\x1b[1;36;40m' BLUE = '\x1b[1;34;40m' GREEN = '\x1b[1;32;40m' CHILL_GREEN = '\x1b[0;32;40m' RED = '\x1b[1;31;40m' YELLOW = '\x1b[1;33;40m' CHILL_YELLOW = '\x1b[0;33;40m' FANCY_BLUE = '\x1b[1;37;44m' ANNOYING = '\x1b[5;31;44m' ENDC = '\x1b[0m' def print_red(string): print(RED + string + ENDC) def print_green(string): print(GREEN + string + ENDC) def print_chill_green(string): print(CHILL_GREEN + string + ENDC) def print_light_blue(string): print(LIGHT_BLUE + string + ENDC) def print_fancy_blue(string): print(FANCY_BLUE + string + ENDC) def print_blue(string): print(BLUE + string + ENDC) def print_yellow(string): print(YELLOW + string + ENDC) def print_chill_yellow(string): print(CHILL_YELLOW + string + ENDC) def print_chill_white(string): print(CHILL_WHITE + string + ENDC) def print_chill_purple(string): print(CHILL_PURPLE + string + ENDC) def print_chill_light_blue(string): print(CHILL_LIGHT_BLUE + string + ENDC) def print_chill_blue(string): print(CHILL_BLUE + string + ENDC) def print_mega_white(string): print(MEGA_WHITE + string + ENDC) def print_annoying(string): print(ANNOYING + string + ENDC) ################################################################## def red_str(string): return RED + string + ENDC def chill_green_str(string): return CHILL_GREEN + string + ENDC def light_blue_str(string): return LIGHT_BLUE + string + ENDC def fancy_blue_str(string): return FANCY_BLUE + string + ENDC def blue_str(string): return BLUE + string + ENDC def yellow_str(string): return YELLOW + string + ENDC def chill_yellow_str(string): return CHILL_YELLOW + string + ENDC def chill_white_str(string): return CHILL_WHITE + string + ENDC def chill_purple_str(string): return CHILL_PURPLE + string + ENDC def chill_light_blue_str(string): return CHILL_LIGHT_BLUE + string + ENDC def chill_blue_str(string): return CHILL_BLUE + string + ENDC def mega_white_str(string): return MEGA_WHITE + string + ENDC def annoying_str(string): return ANNOYING + string + ENDC
#%% """ - Search in Rotated Sorted Array - https://leetcode.com/problems/search-in-rotated-sorted-array/ - Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ #%% class S1: def search(self, nums, target): if target in nums: return nums.index(target) else: return -1 #%% class S2: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ l, r = 0, len(nums) - 1 while l <= r: mid = l + ((r-l) >> 2) if nums[mid] == target: return mid if nums[mid] < nums[r]: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 else: if nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 return -1
def jonSnowParents(dad, mom): if dad == 'Rhaegar Targaryen' and mom == 'Lyanna Stark': return 'Jon Snow you deserve the throne' return 'Jon Snow, you know nothing'
""" Test Suite for UMAP to ensure things are working as expected. The test suite comprises multiple testing modules, including multiple test cases related to a specific set of UMAP features under test. Backend ------- pytest is the reference backend for testing environment and execution, also integrating with pre-existent nose-based tests Shared Testing code ------------------- Whenever needed, each module includes a set of _utility_ functions that specify shared (and repeated) testing operations. Fixtures -------- All data dependency has been implemented as test fixtures (preferred to shared global variables). All the fixtures shared by multiple test cases are defined in the `conftest.py` module. Fixtures allow the execution of each test module in isolation, as well as within the whole test suite. Modules in Tests (to keep up to date) ------------------------------------- - conftest: pytrest fixtures - test_plot: basic tests for umap.plot - test_umap_df_validation_params: Tests on parameters validation for DataFrameUMAP - test_umap_metrics: Tests for UMAP metrics - spatial, binary, and sparse - test_umap_nn: Tests for NearestNeighbours - test_umap_on_iris: Tests for UMAP on Iris Dataset - test_umap_ops: Tests for general UMAP ops (e.g. clusterability, transform stability) - test_umap_repeated_data: UMAP tests on repeated data (sparse|dense; spatial|binary) - test_umap_trustworthiness: Tests on UMAP Trustworthiness - test_umap_validation_params: Tests for fit parameters validation """
# -*- coding: utf-8 -*- """This module contains the Food Ordering Blueprint Application""" NLP_CONFIG = { "resolve_entities_using_nbest_transcripts": [], "system_entity_recognizer": {}, } INTENT_MODEL_CONFIG = { "model_type": "text", "model_settings": {"classifier_type": "logreg"}, "param_selection": { "type": "k-fold", "k": 5, "grid": { "fit_intercept": [True, False], "C": [0.01, 1, 10, 100], "class_bias": [0.7, 0.3, 0], }, }, "features": { "bag-of-words": {"lengths": [1, 2]}, "edge-ngrams": {"lengths": [1, 2]}, "in-gaz": {}, "exact": {"scaling": 10}, "gaz-freq": {}, "freq": {"bins": 5}, }, } DOMAIN_MODEL_CONFIG = { "model_type": "text", "model_settings": {"classifier_type": "logreg"}, "params": { "C": 10, }, "features": { "bag-of-words": {"lengths": [1, 2]}, "edge-ngrams": {"lengths": [1, 2]}, "in-gaz": {}, "exact": {"scaling": 10}, "gaz-freq": {}, "freq": {"bins": 5}, "average-token-length": {}, # Custom feature }, } MAX_HISTORY_LEN = 5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 9. Вводится число экзаменов N ≤ 20. # Напечатать фразу Мы успешно сдали N экзаменов, согласовав слово "экзамен" с числом N. if __name__ == '__main__': N = input("Введите N число: ") ending = "" if N.isnumeric(): for x in ['0', '5', '6', '7', '8', '9']: if N.endswith(x): ending = "ов" for x in ['2', '3', '4']: if N.endswith(x): ending = "a" print(f"Мы успешно сдали {N} экзамен{ending}")
if node.os != 'ubuntu' and node.os != 'raspbian': raise Exception('{} {} is not supported by this bundle'.format(node.os, node.os_version)) pkg_apt = {} files = {} actions = { } if node.metadata.get('grub', {}).get('enabled', False): pkg_apt['grub2-common'] = {} actions['update-grub'] = { 'command': 'update-grub', 'triggered': True, 'cascade_skip': False, } name = '' if node.os == 'ubuntu': name = 'Ubuntu' if node.os == 'debian': name = 'Debian' if node.os == 'raspbian': name = 'Raspbian' if len(name) == 0: raise Exception('can not find name for grub files') files['/etc/default/grub'] = { 'source': 'default-grub', 'content_type': 'mako', 'mode': '0644', 'owner': 'root', 'group': 'root', 'context': { 'name': name, 'default': node.metadata.get('grub', {}).get('default', ''), 'cmd_args': node.metadata.get('grub', {}).get('cmd_args', {}), 'serial': node.metadata.get('grub', {}).get('serial', False), }, 'triggers': ['action:update-grub'], 'needs': ['pkg_apt:grub2-common'], }
# 461. Hamming Distance easy # The Hamming distance between two integers is the number of positions at which the corresponding bits are different. # # Given two integers x and y, calculate the Hamming distance. # # Note: # 0 ≤ x, y < 231. # # Example: # # Input: x = 1, y = 4 # # Output: 2 # # Explanation: # 1 (0 0 0 1) # 4 (0 1 0 0) # ↑ ↑ # # The above arrows point to positions where the corresponding bits are different. class Solution: def hammingDistance(self, x: int, y: int) -> int: xor = x^y bin_str = "{0:032b}".format(xor) print(bin_str) count =0 for char in bin_str: if char == '1': count +=1 return count
""" aiida_nanotech_empa AiiDA plugin containing plugins/work chains developed at nanotech@surfaces group from Empa. """ __version__ = "0.4.1"
class FileSystemInfo(MarshalByRefObject,ISerializable): """ Provides the base class for both System.IO.FileInfo and System.IO.DirectoryInfo objects. """ def Delete(self): """ Delete(self: FileSystemInfo) Deletes a file or directory. """ pass def GetObjectData(self,info,context): """ GetObjectData(self: FileSystemInfo,info: SerializationInfo,context: StreamingContext) Sets the System.Runtime.Serialization.SerializationInfo object with the file name and additional exception information. info: The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown. context: The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination. """ pass def MemberwiseClone(self,*args): """ MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject Creates a shallow copy of the current System.MarshalByRefObject object. cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the object to be assigned a new identity when it is marshaled across a remoting boundary. A value of false is usually appropriate. true to copy the current System.MarshalByRefObject object's identity to its clone,which will cause remoting client calls to be routed to the remote server object. Returns: A shallow copy of the current System.MarshalByRefObject object. MemberwiseClone(self: object) -> object Creates a shallow copy of the current System.Object. Returns: A shallow copy of the current System.Object. """ pass def Refresh(self): """ Refresh(self: FileSystemInfo) Refreshes the state of the object. """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,*args): #cannot find CLR constructor """ __new__(cls: type) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass def __reduce_ex__(self,*args): pass Attributes=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the attributes for the current file or directory. Get: Attributes(self: FileSystemInfo) -> FileAttributes Set: Attributes(self: FileSystemInfo)=value """ CreationTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the creation time of the current file or directory. Get: CreationTime(self: FileSystemInfo) -> DateTime Set: CreationTime(self: FileSystemInfo)=value """ CreationTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the creation time,in coordinated universal time (UTC),of the current file or directory. Get: CreationTimeUtc(self: FileSystemInfo) -> DateTime Set: CreationTimeUtc(self: FileSystemInfo)=value """ Exists=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether the file or directory exists. Get: Exists(self: FileSystemInfo) -> bool """ Extension=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the string representing the extension part of the file. Get: Extension(self: FileSystemInfo) -> str """ FullName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the full path of the directory or file. Get: FullName(self: FileSystemInfo) -> str """ LastAccessTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time the current file or directory was last accessed. Get: LastAccessTime(self: FileSystemInfo) -> DateTime Set: LastAccessTime(self: FileSystemInfo)=value """ LastAccessTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time,in coordinated universal time (UTC),that the current file or directory was last accessed. Get: LastAccessTimeUtc(self: FileSystemInfo) -> DateTime Set: LastAccessTimeUtc(self: FileSystemInfo)=value """ LastWriteTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time when the current file or directory was last written to. Get: LastWriteTime(self: FileSystemInfo) -> DateTime Set: LastWriteTime(self: FileSystemInfo)=value """ LastWriteTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time,in coordinated universal time (UTC),when the current file or directory was last written to. Get: LastWriteTimeUtc(self: FileSystemInfo) -> DateTime Set: LastWriteTimeUtc(self: FileSystemInfo)=value """ Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """For files,gets the name of the file. For directories,gets the name of the last directory in the hierarchy if a hierarchy exists. Otherwise,the Name property gets the name of the directory. Get: Name(self: FileSystemInfo) -> str """ FullPath=None OriginalPath=None
# coding=utf-8 """ Helper methods to access xml elements """ def get_module_name(module): return next(module.iter("ModuleName")).text def get_module_tracked_methods(module): return next(module.iter("TrackedMethods")) def get_module_classes(module): return next(module.iter("Classes")) def get_module_files(module): return next(module.iter("Files")) def get_class_methods(clazz): return next(clazz.iter("Methods")) def get_method_name(method): return next(method.iter("Name")).text def get_method_file_ref(method): return next(method.iter("FileRef"), None) def get_method_coverage(method): # Get method point tag method_point = next(method.iter("MethodPoint"), None) if method_point is None or not list(method_point): return [None, None] # Look at tracked method refs tracked_refs = method_point[0] if not list(tracked_refs): return [None, None] # Return uids of tests that visit the 1st sequence point tests_uids = list(map(lambda x: x.attrib["uid"], tracked_refs)) return [get_method_name(method), tests_uids]
def myif(test, trueval, falseval): if test: return trueval else: return falseval myif(True, "hello", "goodbye")
def apply_async(func, args, *, callback): result = func(*args) callback(result) def print_result(result): print('Got:', result) def add(x, y): return (x + y) apply_async(add, (2, 3), callback=print_result) apply_async(add, ("hello", "world"), callback=print_result) def make_handler(): sequence = 0 def handler(result): nonlocal sequence sequence += 1 print('[{}] Got: {}'.format(sequence, result)) return handler handler = make_handler() apply_async(add, (2, 3), callback=handler) apply_async(add, ("hello", "world"), callback=handler)
class Solution: def __init__(self): self.dic_no_circle = {} def rob_no_circle(self, nums: List[int], start, end) -> int: n = len(nums) if (start,end) in self.dic_no_circle: return self.dic_no_circle[start,end] if n == 0: return 0 if n == 1: self.dic_no_circle[start,end] = nums[0] return nums[0] if n == 2: self.dic_no_circle[start,end] = max(nums[0], nums[1]) return self.dic_no_circle[start,end] ans = max(self.rob_no_circle(nums[:-2], start, end-2)+nums[-1],self.rob_no_circle(nums[:-1], start, end-1)) self.dic_no_circle[start,end] = ans return ans def rob(self, nums: List[int]) -> int: n = len(nums) if n <= 2: return self.rob_no_circle(nums, 0, n) if n == 3: return max(nums[0], nums[1], nums[2]) # if the robber robs at the last (n-1 th) house, you cannot rob from index 0 and n-2. profit = self.rob_no_circle(nums[1:-2], 1, n-2) + nums[-1] # if the robber robs as the first (0 th) house, you cannot rob from index 1 and n-1. profit = max(profit, self.rob_no_circle(nums[2:-1], 2, n-1) + nums[0]) # what if we choose neither index 0 nor index n-1? profit = max(profit, self.rob_no_circle(nums[1:-1], 1, n-1)) return profit
#!/usr/bin/env python # vim: set ts=4 sw=4 et smartindent ignorecase fileencoding=utf8: REDMINE_URL = None REDMINE_KEY = None # 何日前になったら通知するか REDMINE_DAYS = 7 # 見るプロジェクトのID。リスト指定([1,2,...]全プロジェクトの場合は空([]) PROJECT_ID = [] # 参照するTrackerID。全部の場合はNone TRACKER_ID = None # Slack Incoming Webhook URL SLACK_URL = None # Slack User Name SLACK_USERNAME = None # Slack Channel SLACK_CHANNEL = 'general' # Slack eomji SLACK_EMOJI = ':ghost:'
# t = True # count= 0 # sum = 0 # while t==True: # x = int(input()) # if x >=0: # count+=1 # sum+=x # if x<0: # t = False # print(sum) # print(f'{sum/count:.2f}') t = True count= 0 sum = 0 while t==True: x = int(input()) if x<=0: t = False else: count+=1 sum+=x print(sum) print(f'{sum/count:.2f}')
class Files(object): def __init__(self): return @staticmethod def save_output(filename, content): try: with open('./' + filename, 'w') as out_file: out_file.write('\n'.join(content) + '\n') out_file.close() except IOError as err: print('Error writing file')
# (c) 2019 Alexander Korzun # This file is licensed under the MIT license. See LICENSE file class Posinfo(object): """ Represents a position in the source code (column and row) """ def __init__(self, row, col): """ Constructor Arguments: row - row, indexed from 1 col - column, indexed from 1 Raises: None """ self.row = row self.col = col def feed(self, data, start=0, end=None): """ Make this object point to some next position in the source code Assuming `data` is the source code and the current position points to data[start], the resulting position will point to data[end] This interface may seem inconvenient, but it also allows to be used in quite different way. Consider the following code: class MyStringProcessor: def __init__(self, string): self.string = string self.posinfo = Posinfo(1, 1) self.offset = 0 def process_part(self, length): # Process part of the string starting from the current position and with specified length part = self.string[self.offset : self.offset + length] # ... Do something with the string ... # Update Posinfo and offset # equivalent to: self.posinfo.feed(self.string, self.offset, self.offset + length) self.posinfo.feed(part) self.offset += length In it we pass only the current part of the string to Posinfo.feed(), which is possible too (and may be the preferred way of using this method) Unlike from_data() function, this method is usually safe to use from the perspective of the performance because if used properly, all invocations of this method will make O(n) operations in total, where n is the total number of characters processed Arguments: data - source code start - current position end - next position. None means len(data) Returns: None Raises: IndexError if end < start or start < 0 or end > len(data) Complexity: O(end - start) """ if end is None: end = len(data) if end < start or start < 0 or end > len(data): raise IndexError((start, end)) for i in range(start, end): if data[i] == '\n': self.row += 1 self.col = 1 else: self.col += 1 def __str__(self): return '{}:{}'.format(self.row, self.col) def __repr__(self): return 'Posinfo({})'.format(str(self)) def __eq__(self, other): return (self.row, self.col) == (other.row, other.col) def __ne__(self, other): return not (self == other) def from_data(data, offset): """ Construct a Posinfo object given the input string and offset in it Warning: this function is quite slow, as it has to iterate over all characters in data[:offset] (see Complexity section). If misused, it may make tokenization run in O(n²), where n is the length of input Arguments: data - input string offset - offset in `data`, indexed from 0 Returns: Posinfo object with row and column information Raises: IndexError if offset is out of range [0; length), where length = len(data) Complexity: O(offset) """ if offset < 0 or offset >= len(data): raise IndexError(offset) row, col = 1, 1 for index in range(offset): if data[index] == '\n': row += 1 col = 1 else: col += 1 return Posinfo(row, col)
#!/usr/bin/env python3 '''This is Example module''' print("useless script")
class Node: def __init__(self, x): self.val = x self.next = None def __str__(self): string = "[" node = self while node: string += "{} ->".format(node.val) node = node.next string += "None]" return string def get_nodes(values): next_node = None for value in values[::-1]: node = Node(value) node.next = next_node next_node = node return next_node def get_list(head): node = head nodes = list() while node: nodes.append(node.val) node = node.next return nodes def partition(llist, k): head = llist prev, curr = head, head.next while curr: if curr.val < k: prev.next = curr.next curr.next = head head = curr curr = prev.next else: prev = curr curr = curr.next return head # Tests assert get_list(partition(get_nodes([5, 1, 8, 0, 3]), 3)) == [0, 1, 5, 8, 3]
common_urls_http = [ 'http://www.youtube.com' 'http://www.facebook.com' 'http://www.baidu.com' 'http://www.yahoo.com' 'http://www.amazon.com' 'http://www.wikipedia.org' 'http://www.qq.com' 'http://www.google.co.in' 'http://www.twitter.com' 'http://www.live.com' 'http://www.taobao.com' 'http://www.bing.com' 'http://www.instagram.com' 'http://www.weibo.com' 'http://www.sina.com.cn' 'http://www.linkedin.com' 'http://www.yahoo.co.jp' 'http://www.msn.com' 'http://www.vk.com' 'http://www.google.de' 'http://www.yandex.ru' 'http://www.hao123.com' 'http://www.google.co.uk' 'http://www.reddit.com' 'http://www.ebay.com' 'http://www.google.fr' 'http://www.t.co' 'http://www.tmall.com' 'http://www.google.com.br' 'http://www.360.cn' 'http://www.sohu.com' 'http://www.amazon.co.jp' 'http://www.pinterest.com' 'http://www.netflix.com' 'http://www.google.it' 'http://www.google.ru' 'http://www.microsoft.com' 'http://www.google.es' 'http://www.wordpress.com' 'http://www.gmw.cn' 'http://www.tumblr.com' 'http://www.paypal.com' 'http://www.blogspot.com' 'http://www.imgur.com' 'http://www.stackoverflow.com' 'http://www.aliexpress.com' 'http://www.naver.com' 'http://www.ok.ru' 'http://www.apple.com' 'http://www.github.com' 'http://www.chinadaily.com.cn' 'http://www.imdb.com' 'http://www.google.co.kr' 'http://www.fc2.com' 'http://www.jd.com' 'http://www.blogger.com' 'http://www.163.com' 'http://www.google.ca' 'http://www.whatsapp.com' 'http://www.amazon.in' 'http://www.office.com' 'http://www.tianya.cn' 'http://www.google.co.id' 'http://www.youku.com' 'http://www.rakuten.co.jp' 'http://www.craigslist.org' 'http://www.amazon.de' 'http://www.nicovideo.jp' 'http://www.google.pl' 'http://www.soso.com' 'http://www.bilibili.com' 'http://www.dropbox.com' 'http://www.xinhuanet.com' 'http://www.outbrain.com' 'http://www.pixnet.net' 'http://www.alibaba.com' 'http://www.alipay.com' 'http://www.microsoftonline.com' 'http://www.booking.com' 'http://www.googleusercontent.com' 'http://www.google.com.au' 'http://www.popads.net' 'http://www.cntv.cn' 'http://www.zhihu.com' 'http://www.amazon.co.uk' 'http://www.diply.com' 'http://www.coccoc.com' 'http://www.cnn.com' 'http://www.bbc.co.uk' 'http://www.twitch.tv' 'http://www.wikia.com' 'http://www.google.co.th' 'http://www.go.com' 'http://www.google.com.ph' 'http://www.doubleclick.net' 'http://www.onet.pl' 'http://www.googleadservices.com' 'http://www.accuweather.com' 'http://www.googleweblight.com' 'http://www.answers.yahoo.com' 'http://www.sans.org' ] common_urls_https = [ 'https://www.youtube.com', 'https://www.facebook.com', 'https://www.baidu.com', 'https://www.yahoo.com', 'https://www.amazon.com', 'https://www.wikipedia.org', 'https://www.qq.com', 'https://www.google.co.in', 'https://www.twitter.com', 'https://www.live.com', 'https://www.taobao.com', 'https://www.bing.com', 'https://www.instagram.com', 'https://www.weibo.com', 'https://www.sina.com.cn', 'https://www.linkedin.com', 'https://www.yahoo.co.jp', 'https://www.msn.com', 'https://www.vk.com', 'https://www.google.de', 'https://www.yandex.ru', 'https://www.hao123.com', 'https://www.google.co.uk', 'https://www.reddit.com', 'https://www.ebay.com', 'https://www.google.fr', 'https://www.t.com', 'https://www.tmall.com', 'https://www.google.com.br', 'https://www.360.cn', 'https://www.sohu.com', 'https://www.amazon.co.jp', 'https://www.pinterest.com', 'https://www.netflix.com', 'https://www.google.it', 'https://www.google.ru', 'https://www.microsoft.com', 'https://www.google.es', 'https://www.wordpress.com', 'https://www.gmw.cn', 'https://www.tumblr.com', 'https://www.paypal.com', 'https://www.blogspot.com', 'https://www.imgur.com', 'https://www.stackoverflow.com', 'https://www.aliexpress.com', 'https://www.naver.com', 'https://www.ok.ru', 'https://www.apple.com', 'https://www.github.com', 'https://www.chinadaily.com.cn', 'https://www.imdb.com', 'https://www.google.co.kr', 'https://www.fc2.com', 'https://www.jd.com', 'https://www.blogger.com', 'https://www.163.com', 'https://www.google.ca', 'https://www.whatsapp.com', 'https://www.amazon.in', 'https://www.office.com', 'https://www.tianya.cn', 'https://www.google.co.id', 'https://www.youku.com', 'https://www.rakuten.co.jp', 'https://www.craigslist.org', 'https://www.amazon.de', 'https://www.nicovideo.jp', 'https://www.google.pl', 'https://www.soso.com', 'https://www.bilibili.com', 'https://www.dropbox.com', 'https://www.xinhuanet.com', 'https://www.outbrain.com', 'https://www.pixnet.net', 'https://www.alibaba.com', 'https://www.alipay.com', 'https://www.microsoftonline.com', 'https://www.booking.com', 'https://www.googleusercontent.com', 'https://www.google.com.au', 'https://www.popads.net', 'https://www.cntv.cn', 'https://www.zhihu.com', 'https://www.amazon.co.uk', 'https://www.diply.com', 'https://www.coccoc.com', 'https://www.cnn.com', 'https://www.bbc.co.uk', 'https://www.twitch.tv', 'https://www.wikia.com', 'https://www.google.co.th', 'https://www.go.com', 'https://www.google.com.ph', 'https://www.doubleclick.net', 'https://www.onet.pl', 'https://www.googleadservices.com', 'https://www.accuweather.com', 'https://www.googleweblight.com', 'https://www.answers.yahoo.com', 'https://www.sans.org', 'https://support.google.com', 'https://www.adobe.com', 'https://www.gulf-times.com', ]
# Implement a quicksort items = [20, 6, 8, 53, 56, 23, 87, 41, 49, 19] def quickSort(dataset, first, last): if first < last: # calculate the split point pivotIdx = partition(dataset, first, last) # now sort the two partitions quickSort(dataset, first, pivotIdx-1) quickSort(dataset, pivotIdx+1, last) def partition(datavalues, first, last): # choose the first item as the pivot value pivotvalue = datavalues[first] # establish the upper and lower indexes lower = first + 1 upper = last # start searching for the crossing point done = False while not done: # advance the lower index while lower <= upper and datavalues[lower] <= pivotvalue: lower += 1 # advance the upper index while datavalues[upper] >= pivotvalue and upper >= lower: upper -= 1 # if the two indexes cross, we have found the split point if upper < lower: done = True else: # exchange the two values temp = datavalues[lower] datavalues[lower] = datavalues[upper] datavalues[upper] = temp # when the split point is found, exchange the pivot value temp = datavalues[first] datavalues[first] = datavalues[upper] datavalues[upper] = temp # return the split point index return upper # test the merge sort with data print(items) quickSort(items, 0, len(items)-1) print(items)
FOUND_PYTORCH = True # TODO check using code CONFIG = "config_file" BASELOGFOLDER = 'base_log_folder' SEED = 'seed' DEVICE = None
def is_palindrome(n): s, r = str(n), str(n)[::-1] return s == r def solve(d): n, m, largest = 10 ** (d - 1), 10 ** d, 0 for i in range(n, m): for j in range(i + 1, m): p = i * j if largest < p and is_palindrome(p): largest = p return largest # d = 2 d = 3 print(solve(d))
# TC: O(n) | SC: O(n) def solution_1(price): profit = [0]*len(price) # right to left max_price = price[-1] for i in range(len(price)-2, -1, -1): if price[i] > max_price: max_price = price[i] profit[i] = max(profit[i+1], (max_price-price[i])) # left to right min_price = price[0] for i in range(1, len(price)): if min_price > price[i]: min_price = price[i] profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) return profit[-1] if __name__ == '__main__': price = [10, 22, 5, 75, 65, 80] # 87 # price = [2, 30, 15, 10, 8, 25, 80] # 100 # price = [100, 30, 15, 10, 8, 25, 80] # 72 # price = [90, 80, 70, 60, 50] # 0 print('solution_1: ', solution_1(price))
input_string = input('Please input a number: ') if input_string.isnumeric(): print('The number is accepted') else: print('The input is invalid')
input() S=input() dot=S.count(".") ans=dot sharp=0 for s in S: if s=="#":sharp+=1 else:dot-=1 ans=min(ans,sharp+dot) print(ans)
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ __debug_recursion_depth = -1 __debug_output_enabled_f = False # True / False def __debug_print(msg, msg2="", msg3=""): global __debug_recursion_depth if not __debug_output_enabled_f: return if type(msg2) != str: msg2 = repr(msg2) if type(msg3) != str: msg3 = repr(msg3) txt = "##" + " " * __debug_recursion_depth + msg + " " + msg2 + " " + msg3 txt = txt.replace("\n", "\n " + " " * __debug_recursion_depth) print(txt) def __debug_exit(result, stream): global __debug_recursion_depth __debug_recursion_depth -= 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace("\n", "\\n") stream.seek(pos) __debug_print("##exit: [%s], remainder = \"%s\"" % (type(result), txt)) return result def __debug_entry(function_name, stream): global __debug_recursion_depth __debug_recursion_depth += 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace("\n", "\\n") stream.seek(pos) __debug_print("##entry: %s, remainder = \"%s\"" % (function_name, txt)) def __debug_print_stream(Prefix, stream): pos = stream.tell() print("#%s: [%s]" % (Prefix, stream.read(64).replace("\n", "\\n"))) stream.seek(pos)
dollar_bill = 10 if dollar_bill < 1000: print('bill exist') else: print ('bill does not exist') # dollar_bill = 1000 # # if dollar_bill < 800: # print ('bill exist') # else: # print ('bill does not exist') # # dollar_bill = 1000 # if dollar_bill > 500: # print ('bill exist') # else: # print ('bill does not exist') # # dollar_bill = 1000 # if dollar_bill > 500: # print('bill exist') # else: # print('bill does not exist') jKDK
def abc() : print('a') print('b') print('c') def get_vat(price) : percent = 0.1 return price*percent p = 1000 answer = get_vat(p) print(answer)
class CreateOrderController: def __init__(self, create_order_use_case): self.create_order_use_case = create_order_use_case def route(self, body): if body is not None: consumed_in = body["consumed_in"] if "consumed_in" in body else None table = body["table"] if "table" in body else None payment_method = body["payment_method"] if "payment_method" in body else None obs = body["obs"] if "obs" in body else None response = self.create_order_use_case.create_order( consumed_in=consumed_in, table=table, payment_method=payment_method, obs=obs) return response return {"data": None, "status": 400, "errors": ["Invalid request"]}
################################################################## # this function will print any AST that follows the # # (TYPE [, child1, child2,...]) # # tuple format for tree nodes. def dumpast(node): _dumpast(node) print('') def _dumpast(node, level=0): if isinstance(node, tuple): indent(level) nchildren = len(node) - 1 print("(%s" % node[0], end='') if nchildren > 0: print(" ", end='') for c in range(nchildren): _dumpast(node[c+1], level+1) if c != nchildren-1: print(' ', end='') print(")", end='') elif isinstance(node, list): indent(level) nchildren = len(node) print("[", end='') if nchildren > 0: print(" ", end='') for c in range(nchildren): _dumpast(node[c], level+1) if c != nchildren-1: print(' ', end='') print("]", end='') else: print("%s" % str(node), end='') def indent(level): print('') for i in range(level): print(' |',end='')
class FlameLabel(QtWidgets.QLabel): """ Custom Qt Flame Label Widget For different label looks set label_type as: 'normal', 'background', or 'outline' To use: label = FlameLabel('Label Name', 'normal', window) """ def __init__(self, label_name, label_type, parent_window, *args, **kwargs): super(FlameLabel, self).__init__(*args, **kwargs) self.setText(label_name) self.setParent(parent_window) self.setMinimumSize(110, 28) self.setMaximumHeight(28) self.setFocusPolicy(QtCore.Qt.NoFocus) # Set label stylesheet based on label_type if label_type == 'normal': self.setStyleSheet('QLabel {color: #9a9a9a; border-bottom: 1px inset #282828; font: 14px "Discreet"}' 'QLabel:disabled {color: #6a6a6a}') elif label_type == 'background': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #393939; font: 14px "Discreet"') elif label_type == 'outline': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #212121; border: 1px solid #404040; font: 14px "Discreet"')
#Faça um programa que mostre os n termos da Série a seguir: #o S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n/m. #Imprima no final a soma da série. n=int(input("Informe o termo N que deseja visualizar: ")) serie=[] serie_attN=[] serie_attV=[] cima=1 baixo=1 serie.append(cima) serie.append(baixo) for c in range(1,n): cima+=1 baixo+=2 serie.append(cima) serie.append(baixo) txt=f"{str(serie[0])}/{str(serie[1])}" num=serie[0]/serie[1] serie_attN.append(num) serie_attV.append(txt) for c in range(2,n*2,2): num=serie[c]/serie[c+1] txt=f"+ {str(serie[c])}/{str(serie[c+1])}" serie_attN.append(num) serie_attV.append(txt) print(f"S = {serie_attV} = {round(sum(serie_attN),2)}")
""" This module provides a wrapper for dict and list items that exposes dict entries as it's attributes - Example:: # import from obj import to_obj # initialize object = to_obj({ 'foo': 'bar' }) array = to_obj([{ 'baz': 'qux' }]) # provides accessors object.foo # provdes deep array[0].baz # in the iterator item.baz for item in array """ __version__ = "1.0.0" __docformat__ = "reStructuredText" class Obj(dict): """ Wrap `dict` to `Obj` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, name): return to_obj(super().__getitem__(name)) def __getattr__(self, name): return to_obj(super().__getitem__(name)) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): if name in self: del self[name] else: raise AttributeError("No such attribute: " + name) def copy(self): return Obj(super().copy()) def fromkeys(self, value): """ Overwrite built-in `fromkeys` to return a wrapped value """ return Obj(super().fromkeys(value)) def get(self, value, default=None): return to_obj(super().get(value, default)) def pop(self, value): return to_obj(super().pop(value)) def popitem(self): value = super().popitem() return (value[0], to_obj(value[1])) class Arr(list): """ Wrap `list` to `Arr` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, index): # if isinstance(index, slice): # for item in super().__getitem__(index): # return to_obj(item) # else: return to_obj(super().__getitem__(index)) def __iter__(self): for value in list.__iter__(self): yield to_obj(value) def copy(self): return to_obj(super().copy()) def pop(self, value=0): return to_obj(super().pop(value)) def to_obj(value): """ Wrap `dict` to `Obj` Wrap `list` to `Arr` otherwise return original value """ if isinstance(value, dict): return Obj(value) if isinstance(value, list): return Arr(value) return value
print('- '*27) si = float(input('Digite o sálario atual do funcionário: R$')) ap = int(input('Digite o aumento em porcentagem (apenas números): ')) print('') vap = si * (ap/100) # valor aumento porcentagem vf = si + vap # valor final # print('O valor do sálario R${:.2f}, teve um aumento de {}%'.format(si, ap)) print('O salário atual é de R${:.2f}'.format(vf)) print('- '*27)
#Made by Piotr Łądkowski def sudoku_empty(sudoku): for row in sudoku: for element in row: if type(element) is not int: return False return True def solve_sudoku(sudoku): initPossibles = [1, 2, 3, 4, 5, 6, 7, 8, 9] sudoku = sudoku[:] solved = False while not solved: for row in range( len(sudoku) ): for element in range( len(sudoku[row]) ): if type(sudoku[row][element]) is not int: possibles = initPossibles[:] #check in grid for rowCount in range(row - (row % 3), row - (row % 3) + 3): for elemCount in range(element-(element%3), element-(element%3)+3): if sudoku[rowCount][elemCount] in possibles: possibles.remove(sudoku[rowCount][elemCount]) #check in row for elem in sudoku[row]: if elem in possibles: possibles.remove(elem) #check in column for checkRow in sudoku: if checkRow[element] in possibles: possibles.remove(checkRow[element]) if len(possibles) is 1: possibles = possibles[0] sudoku[row][element] = possibles solved = sudoku_empty(sudoku) return sudoku def print_sudoku(sudoku): for row in sudoku: printRow = "" for elem in row: printRow += str(elem) if elem is "" or '': printRow += "[]" printRow += " " print(printRow)
def read_passports(): with open('input.txt') as fh: lines = fh.readlines() pp_chunks = [] chunk = "" for li in range(len(lines)): if lines[li].strip(): chunk += lines[li].strip() + " " else: pp_chunks.append(chunk) chunk = "" # I added 2 newlines at the end of the input so this will catch the last one. HAX. print(len(pp_chunks), pp_chunks) # each chunk is a one-line string containing all fields passports = [] for chunk in pp_chunks: p = dict() try: for tok in chunk.strip().split(' '): if not tok.strip(): # could have multiple spaces, no biggie continue k, v = tok.split(':') # might error if bad token p[k] = v except Exception: # invalid - skip. print("skipping chunk:", chunk) continue passports.append(p) print(len(passports,), passports) return passports def check_required_fields_present(p): # cid not actually required min_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} for field in min_fields: if field not in p: print("p missing", field, len(p), ":", p) return False return True def main(): pps = read_passports() valid_pps = [] for p in pps: if not check_required_fields_present(p): continue valid_pps.append(p) print(len(valid_pps)) if __name__ == '__main__': # 225 - too low # 235 - too high, so the idea's roughly right. main()
""" Copyright (c) 2014-2015 F-Secure See LICENSE for details """
#Brian Condon # 28/02/18 Week 5 formatting exercise # prints the headings # opens the data file print("petal length, petal width, sepal length, sepal width") with open("data/iris.csv") as data_file: # loops through the data file # prints and formats the data using the line split for line in data_file: print('{:13} {:12} {:13} {:8}'.format(line.split(',')[0], line.split(',')[1], line.split(',')[2], line.split(',')[3]))
classification_file = open('classifications.csv') new_class_file = open('new_class.csv', mode='w') new_class_file.write(classification_file.readline()) for line in classification_file: line = line.strip().split(',') new_class_file.write(line[0] + ',') new_class_file.write(('1' if line[1] == 'True' else '0') + '\n')
class Solution: def scoreOfParentheses(self, S): stack, res = [], 0 for c in S: if c == "(": stack.append(0) else: add = 2 * stack.pop() or 1 if stack: stack[-1] += add else: res += add return res
#!/usr/bin/python #template collection _file = open("basic_template.html") basic_template = _file.read() index = "<br><p>Welcome to this beautiful library at this nice day.</p><p>Today it is the <i><?= date ?></i>. On the left you can see the interactive menu with all the functions you need. </p><p>If you need any assistance either contact the library master or don't hesitate to ask the programmer (murph@gmx.net) for assistance." successful = "Your action has been done successfully!" error = "Sorry for the inconvenience, but an error occured: <br><p><?= msg ?></p>" ###back from javascript should be included! ########################################### ########################################### ### Persons call_add_person = """<p><table><tr><form action='/do_add_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text'></input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_edit_person = """<p>Please specify which student should be edited<br><table><tr><form action='/do_edit_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> <i>If the student's ID is supposed to be changed delete the student and add him/her again.</i>""" do_edit_person = """<table><tr><form action='/do_edit_person_2'></tr> <tr><td>Student ID</td><td><?= person_id?><input name='person_id' type='hidden' value='<?= person_id ?>'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text' value='<?= firstname ?>'></input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text' value='<?= surname ?>'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text' value='<?= cellphone ?>'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text' value='<?= _class ?>'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text' value='<?= semester ?>'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> The student ID cannot be changed. If that is necissary delete the student and add a new one.""" call_delete_person = """<p>Please specify which student should be <b>deleted</b><br><table><tr><form action='/do_delete_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_show_persons_none = """<p>In the Library System following students are registered:<br> <p>No students are in the database</p> """ call_show_persons = """<p>In the Library System following students are registered:<br><br></p> <table border=1> <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr> <? for student_set in res: ?> <tr> <? for el in student_set: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?> </tr> <? end ?> </table> """ call_search_person = """<p>Please enter some keywords<table><tr><form action='/do_search_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text' </input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ do_search_person = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ do_search_person_none = """<p>The result of the search was as follows:<br> <p>No students could be found</p> """ #################################################### #################################################### ### BOOKS ###################################### call_add_book = """<p><table><tr><form action='/do_add_book'></tr> <tr><td>Author</td><td><input name='author' type='text'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',')""" call_edit_book = """<p>Please specify which book should be edited<br><table><tr><form action='/do_edit_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ do_edit_book = """<p><table><tr><form action='/do_edit_book_2'></tr> <tr><td>Book ID</td><td><?= book_id?><input name='book_id' type='hidden' value='<?= book_id ?>'></td></tr> <tr><td>Author</td><td><input name='author' type='text' value='<?= author ?>'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text' value='<?= title?>'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text' value='<?= amount ?>'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text' value='<?= tags ?>'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',')<br> The Book ID cannot be edited. Please delete the book and add it again if a new ID is nessicary.""" call_delete_book = """<p>Please specify which book should be <b>deleted</b><br><table><tr><form action='/do_delete_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_show_books_none = """<p>In the Library System following books are registered:<br> <p>No books are in the database</p> """ call_show_books = """<p>In the Library System following books are registered:<br><br></p> <table border=1> <tr><td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Tags</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=24% HEIGHT=19><? if el: ?><?= el ?><? end ?><? if not el: ?><i>None</i><? end ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_search_book = """<p>Please enter some keywords<table><tr><form action='/do_search_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Author</td><td><input name='author' type='text'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',') """ do_search_book = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Tags</b></td></tr> <? for row in res: ?> <tr><? for el in row: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ do_search_book_none = """<p>The result of the search was as follows:<br> <p>No books could be found</p> """ ############################################ ############################################ ###Library call_lend_book = """Please specify which book will be lent to whom:<br><br> <table><form action='/do_lend_book'> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_return_book = """Please specify who wants to return which book<br><br> <table><form action='/do_return_book'> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_show_lent_books = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Student ID</b></td> <td><b>First name</b></td> <td><b>Surname</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_lent_books_to = """<p>Please specify for which student you want to have the list of the books to return<br><table><tr><form action='/do_lent_books_to'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_show_lent_books_to = """<p>The result for student '<?= person_id ?>' was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_to_when_deleting = """<p>The student '<?= person_id ?>' could not be deleted because s/he still possesses books of the library:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td><td><b>Book ID</b></td><td><b>Author</b></td><td><b>Title</b></td><td><b>Amount</b></td><td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_to_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_lent_books_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_show_books_over_limit = """ "<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Student ID</b></td> <td><b>First name</b></td> <td><b>Surname</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_books_over_limit_none = """<p>The result of the search was as follows:<br> <p>No lent books over limit could be found</p> """ call_backup = """<p>Welcome to the backup function</p><br> <table> <tr> <td> For creating a backup, please press: </td> <td> <a href='/create_backup'>HERE</a></td> </tr> <tr> <td> For inserting an old backup: </td> <td> <form action='/upload_backup' method="post" enctype="multipart/form-data"><input type="file" name="myFile" /><br /> <input type="submit" value="INSERT BACKUP" /> </td> </tr> </table> """
nome = str(input('Qual o seu nome?')).upper().strip() if nome == 'RAI': print ('\033[31mVocê tem um nome muito lindo!') elif nome == 'PEDRO' or nome == 'MARIA' or nome == 'LUCAS' or nome == 'JOÃO': print('Seu nome é bem popular no Brasil!') elif nome in 'LUANA, KIANA, YUUKA, PATRICIA': print('Belo nome') else: print('Você é muito normal!') print('Bom dia {}'.format(nome)) #Isso é uma estrutura condicional aninhada, uma estrutura dentro da outra
# Colors (Fixed Color Graph Indices) # Returns (red, green, blue, opacity) colors = [ "EEEEEE", # White (1, n) "FF0000", # Red (i, s) "00FF00", # Green (j, t) "0000FF", # Blue (k, u) "DDDDDD", # Gray (L, N) "00FFFF", # Cyan (I, S) "FF00FF", # Magenta (J, T) "FFFF00", # Yellow (K, U) "CCCCCC", # Gray (m, o) "FF8000", # Orange (p, v) "FF0080", # Pink (q, w) "80FF00", # Lime (r, x) "BBBBBB", # Gray (M, O) "FF8000", # Teal (P, V) "8000FF", # Purple (Q, W) "0080FF", # Blue (R, X) ] * 2 def color(order, id): negative = True if id >= 2**order else False id -= 2**order if negative else 0 color = colors[id] out = [0, 0, 0, 1] for i in range(3): hex = color[i * 2 : i * 2 + 2] out[i] = int(hex, 16) / 0xFF if negative: out[i] *= 0.50 # Color 50% Darker If Negative return tuple(out) # Location (Fixed Location Graph Indices) # Returns [Horizontal, Vertical] # Left / Top := [-, -] # Left / Bottom := [-, +] # Right / Bottom := [+, +] # Right / Top := [+, -] # Center := [0, 0] locations = [ [1, 0], [0, -1], # 1, i, Complex [2, 2], [2, -2], # j, k, Quaternion [-1.5, -4], [-4, -1.5], [-4, 1.5], [-1.5, 4], # L, I, J, K Octonion [-2, -6], [-5, -6], [-6, -5], [-6, -2], # m, p, q, r Sedenion [-6, 2], [-6, 5], [-5, 6], [-2, 6], # M, P, Q, R Sedenion [-6, -9], [-8, -9], [-9, -8], [-9, -6], # n, s, t, u Pathion [-9, 6], [-9, 8], [-8, 9], [-6, +9], # N, S, T, U Pathion [-9, 4], [-11, 3], [-11, -3], [-9, -4], # o, v, w, x Pathion [4, 9], [3, 11], [-3, 11], [-4, 9], # O, V, W, X Pathion ] def location(order, id): negative = True if id >= 2**order else False id -= 2**order if negative else 0 location = locations[id] for i in range(2): if negative: location[i] *= -1 # Reversed Location If Negative return location
def set_default(default_dict, result_dict): """Sets default values for a dictionary recursively. :param default_dict: The template dictionary to use to set values :param result_dict: The dictionary to load the template values into :rtype: dict """ # Iterate through default values for tag in default_dict: # If the tag does not exist in the result dictionary, add it if tag not in result_dict: result_dict[tag] = default_dict[tag] # Tag exists in guild dict, see if tag is a dictionary else: if type(result_dict[tag]) == dict: result_dict[tag] = set_default(default_dict[tag], result_dict[tag]) return result_dict
# HEAD # DataType - Strings with Sequence/Tuples behaviour # DESCRIPTION # Describes how strings behave as a list or a sequence # Strings can be referenced per character using indexes like lists # String indexing also starts from 0/Zero # Strings can be looped like lists # RESOURCES # name = 'Zophie' print(name[0]) # 'Z' print(name[-2]) # 'i' print(name[0:4]) # 'Zoph' print('Zo' in name) # True print('z' in name) # False print('p' not in name) # False for i in name: print('* * * ' + i + ' * * *')
APPLICATION_NAME = "Actuator Updater" APP_AUTHOR_DIR = "FarSite" APP_NAME_DIR = "ActuatorUpdater" # MENU_DISCONNECTED = "Connect to site..." MENU_DISCONNECTED = "Connect/disconnect" MENU_CONNECTED = "Disconnect from site"
''' This is a first name / last name dictionary & retrieval system Try this: 1. Add your name 2. Use the difflib tricks in Challenge0 to match SIMILAR names (instead of exact names) ''' database = { 'Luke':'Skywalker', 'Leia':'Skywalker', 'Han':'Solo', 'Chewie':'Chewbacca', 'Finn':'FN-2187', } # in case you forgot to type the keys (prompts) as all lower case for key in dict(database): if key != key.lower(): # if some upper case characters # Add an extra entry with all lower case characters in prompt database[key.lower()] = database[key] def sorry(): print('Sorry, no records found matching that name!') while True: typ = input('Search By First Name or Last Name? (type "first" or "last") >> ') if typ.lower() == 'first': name = input('First Name? >> ') name = name.lower() if name in database.keys(): print('Last Name Is', database[name]) else: sorry() elif typ.lower() == 'last': name = input('Last Name? >> ') name = name.lower() if name in database.values(): for first, last in database.items(): if last == name: print('First Name Is', first) break # quit this for loop else: sorry()
pkgname = "icu" pkgver = "70.1" pkgrel = 0 build_wrksrc = "source" build_style = "gnu_configure" configure_args = [ "--with-data-packaging=archive", "--enable-static", ] make_cmd = "gmake" hostmakedepends = ["gmake", "pkgconf"] checkdepends = ["python"] pkgdesc = "Robust and fully-featured Unicode libraries" maintainer = "q66 <q66@chimera-linux.org>" license = "ICU" url = "https://home.unicode.org" source = f"https://github.com/unicode-org/{pkgname}/releases/download/release-{pkgver.replace('.', '-')}/icu4c-{pkgver.replace('.', '_')}-src.tgz" sha256 = "8d205428c17bf13bb535300669ed28b338a157b1c01ae66d31d0d3e2d47c3fd5" tool_flags = {"CFLAGS": ["-fPIC"], "CXXFLAGS": ["-fPIC"]} def init_configure(self): if not self.profile().cross: return # we build special host icu for cross self.configure_args.append( "--with-cross-build=" + str(self.chroot_cwd / "icu-host") ) def pre_configure(self): if not self.profile().cross: return # host build; first clean up potential old stuff self.rm("build-host", recursive = True, force = True) self.rm("icu-host", recursive = True, force = True) self.mkdir("build-host") # override most build-related environment self.do( self.chroot_cwd / "configure", "--prefix=/", "--sbindir=/bin", wrksrc = "build-host", env = { "CC": "cc", "LD": "ld", "CXX": "c++", "AR": "ar", "AS": "cc", "RANLIB": "ranlib", "STRIP": "strip", "CFLAGS": "-Os", "CXXFLAGS": "-Os", "LDFLAGS": "", } ) self.make.build(wrksrc = "build-host") self.mkdir("icu-host/config", parents = True) # copy over icucross for f in (self.cwd / "build-host/config").glob("icucross.*"): self.cp(f, "icu-host/config") # finally install host icu into special prefix self.make.install( ["DESTDIR=" + str(self.chroot_cwd / "icu-host")], wrksrc = "build-host", default_args = False ) def post_install(self): # FIXME: check if cross-endian icudt is still busted later self.install_license(self.builddir / self.wrksrc / "LICENSE") @subpackage("icu-libs") def _libs(self): return self.default_libs(extra = [ f"usr/share/icu/{pkgver}/icudt*.dat" ]) @subpackage("icu-devel") def _devel(self): return self.default_devel(extra = ["usr/share/icu", "usr/lib/icu"])
def intersection(start_i, end_i, start_j, end_j): i0 = max(start_i, start_j) i1 = min(end_i, end_j) if i0 >= i1: return 0 else: return i1 - i0 def percentage_intervention(doc, shot_start, shot_end): interventions = doc.getElementsByTagName("Intervention") case_size = shot_end - shot_start percentage = {'long': 0, 'short': 0} for intervention in interventions: intervention_start = float(intervention.getAttribute('start')) intervention_end = float(intervention.getAttribute('end')) intervention_type = intervention.getAttribute('type') intersect = intersection(shot_start, shot_end, intervention_start, intervention_end) percentage[intervention_type] = percentage[intervention_type] + intersect # print "intervention_start: " + str(intervention_start) # print "intervention_end: " + str(intervention_end) # print "shot_start: " + str(shot_start) # print "shot_end: " + str(shot_end) # print "shot_end: " + str(percentage[intervention_type]) percentage['long'] = round(percentage['long'] * 100 / case_size, 2) percentage['short'] = round(percentage['short'] * 100 / case_size, 2) return percentage
# -*- Python -*- # Copyright 2017-2021 The Verible Authors. # # 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. """Bazel rule to run bison toolchain """ # Adapter rule around the @rules_bison toolchain. def genyacc( name, src, header_out, source_out, extra_options = [], extra_outs = []): """Build rule for generating C or C++ sources with Bison. """ native.genrule( name = name, srcs = [src], outs = [header_out, source_out] + extra_outs, cmd = select({ "@platforms//os:windows": "$(BISON) --defines=$(location " + header_out + ") --output-file=$(location " + source_out + ") " + " ".join(extra_options) + " $<", "//conditions:default": "M4=$(M4) $(BISON) --defines=$(location " + header_out + ") --output-file=$(location " + source_out + ") " + " ".join(extra_options) + " $<", }), toolchains = select({ "@platforms//os:windows": ["@rules_bison//bison:current_bison_toolchain"], "//conditions:default": [ "@rules_bison//bison:current_bison_toolchain", "@rules_m4//m4:current_m4_toolchain", ], }), )
def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num))
# -------------- #Code starts here #Function to check for palindrome def palindrome_check(num): num=str(num) return (num[::-1]==num) #Function to find the smallest palindrome def palindrome(num): while(1): num=num+1 if palindrome_check(num): return num #Code ends here # -------------- #Code starts here #Function to find anagram of one word in another def a_scramble(str_1,str_2): result=True for i in (str_2.lower()): if i not in (str_1.lower()): result=False break str_1=str_1.replace(i,'',1) #Removing the letters from str_1 that are already checked return (result) #Code ends here # -------------- #Code starts here def check_fib(num): a,b = 0,1 L = [0,1] c = a + b for i in range(2,num+1): L.append(c) a = b b = c c = a + b if num in L: return True else: return False # -------------- #Code starts here def compress(word): count,index,i = 0,1,0 word = word.lower() new_word = "" while (i < len(word)): w = word[i] for j in range(i,len(word)): if w == word[j]: count += 1 else: break new_word = new_word+w+str(count) i = i+count count=0 print(new_word) return new_word # -------------- #Code starts here def k_distinct(string,k): string = string.lower() L = [] for i in range(len(string)): if string[i] not in L: L.append(string[i]) else: continue if len(L) >=k: return True else: return False
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 14:35:41 2018 @author: misskeisha """ passw = input() if (any(x.isupper() for x in passw) and any(x.islower() for x in passw) and (passw.isalnum() == False) and len(passw) >= 8) and any(x.isdigit() for x in passw): print('good password') else: print('poor password')
class ChainingTimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class Curvature2DAngleF0D: def __init__(self): pass def __call__(self, it): pass class Curvature2DAngleF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class CurveMaterialF0D: pass class CurveNatureF0D: def __init__(self): pass def __call__(self, it): pass class CurveNatureF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class DensityF0D: def __init__(self, sigma=2.0): pass def __call__(self, it): pass class DensityF1D: def __init__(self, sigma=2.0, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetCompleteViewMapDensityF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetCurvilinearAbscissaF0D: def __init__(self): pass def __call__(self, it): pass class GetDirectionalViewMapDensityF1D: def __init__(self, orientation, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetOccludeeF0D: def __init__(self): pass def __call__(self, it): pass class GetOccludeeF1D: def __init__(self): pass def __call__(self, inter): pass class GetOccludersF0D: def __init__(self): pass def __call__(self, it): pass class GetOccludersF1D: def __init__(self): pass def __call__(self, inter): pass class GetParameterF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedXF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedXF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetProjectedYF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedYF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetProjectedZF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedZF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetShapeF0D: def __init__(self): pass def __call__(self, it): pass class GetShapeF1D: def __init__(self): pass def __call__(self, inter): pass class GetSteerableViewMapDensityF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetViewMapGradientNormF0D: def __init__(self, level): pass def __call__(self, it): pass class GetViewMapGradientNormF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetXF0D: def __init__(self): pass def __call__(self, it): pass class GetXF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetYF0D: def __init__(self): pass def __call__(self, it): pass class GetYF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetZF0D: def __init__(self): pass def __call__(self, it): pass class GetZF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class IncrementChainingTimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class LocalAverageDepthF0D: def __init__(self, mask_size=5.0): pass def __call__(self, it): pass class LocalAverageDepthF1D: def __init__(self, sigma, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class MaterialF0D: def __init__(self): pass def __call__(self, it): pass class Normal2DF0D: def __init__(self): pass def __call__(self, it): pass class Normal2DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation2DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation3DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class QuantitativeInvisibilityF0D: def __init__(self): pass def __call__(self, it): pass class QuantitativeInvisibilityF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class ReadCompleteViewMapPixelF0D: def __init__(self, level): pass def __call__(self, it): pass class ReadMapPixelF0D: def __init__(self, map_name, level): pass def __call__(self, it): pass class ReadSteerableViewMapPixelF0D: def __init__(self, orientation, level): pass def __call__(self, it): pass class ShapeIdF0D: def __init__(self): pass def __call__(self, it): pass class TimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class VertexOrientation2DF0D: def __init__(self): pass def __call__(self, it): pass class VertexOrientation3DF0D: def __init__(self): pass def __call__(self, it): pass class ZDiscontinuityF0D: def __init__(self): pass def __call__(self, it): pass class ZDiscontinuityF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class pyCurvilinearLengthF0D: pass class pyDensityAnisotropyF0D: pass class pyDensityAnisotropyF1D: pass class pyGetInverseProjectedZF1D: pass class pyGetSquareInverseProjectedZF1D: pass class pyInverseCurvature2DAngleF0D: pass class pyViewMapGradientNormF0D: pass class pyViewMapGradientNormF1D: pass class pyViewMapGradientVectorF0D: def __init__(self, level): pass
def bubblesort(A): for i in range(len(A)): for k in range(len(A) - 1, i, -1): if (A[k] < A[k - 1]): swap(A,k,k-1) def swap(A,x,y): temp = A[x] A[x] = A[y] A[y] = temp A= [534,689,235,124,525,216,134,356] bubblesort(A) print(A)
BACKGROUND = "red" FONT_NAME = "Consolas" FONT_SIZE = 19 DEFAULT_FONT = (FONT_NAME, FONT_SIZE) HEADER_FONT = (FONT_NAME, int(FONT_SIZE*1.3))
'''Developed by Jakub21 in June 2018 License: MIT Python version: 3.6.5 ''' class Chunk: '''Chunk Class Contains methods inherited by ProvGroup and Province classes ''' def __init__(self, parent, name, type): '''Constructor''' self.parent, self.name, self.type = parent, name, type self.marked = False self.pixels = [] def __repr__(self): '''Generates repr string of the object''' i = ' '*4 text = 'Chunk "'+str(self.name)+'"\n' text += i + 'Type: '+str(self.type)+'\n' text += i + 'Is marked: '+str(self.marked)+'\n' text += i + 'Pixels count: '+str(len(self.pixels))+'\n' try: text += i+'Colors: '+str([self.color, self.g_clr, self.m_clr])+'\n' except AttributeError: text += i + 'Colors not set\n' return text def set_pixels(self, pixels): '''Sets pixels of the chunk''' self.pixels = pixels def set_color(self, color): '''Sets chunk colors. Pass identifier color as a parameter. Marked and Grayed colors are calculated by helper methods. ''' self.color = color self.g_clr = self._get_gray(color) self.m_clr = self._get_marked(color) def mark(self, modify_map=True, force=None): '''Marks or Unmarks the chunk. To skip map update set modify_map to False. To force state of marked attr. use force parameter. ''' color = { True: self.m_clr, False: self.g_clr, } if force in (True, False): self.marked = force else: self.marked = not self.marked if modify_map == True: self.parent.mark_chunk(self.pixels, color[self.marked]) elif modify_map == 'provs': self.parent.mark_src_map(self.pixels, color[self.marked]) # set_color helper methods def _get_gray(self, color): r, g, b = color r = (r+100)//4 g = (g+100)//4 b = (b+100)//4 return r, g, b def _get_marked(self, color): r, g, b = color r = (r+510)//3 g = (g+510)//3 b = (b+510)//3 return r, g, b
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Module authors: # Björn Pedersen <bjoern.pedersen@frm2.tum.de> # # ***************************************************************************** """A general nicos proxy superclass.""" class NicosProxy: """ General proxy class to add special behaviour to classes. See http://code.activestate.com/recipes/252151-generalized-delegates-and-proxies/ """ _obj = None def __init__(self, obj): super().__init__(obj) self._obj = obj def __getattr__(self, name): return getattr(self._obj, name) def __setattr__(self, name, value): if name == '_obj': self.__dict__[name] = value elif self._obj: return setattr(self._obj, name, value) def __repr__(self): return self._obj.__repr__() # Auxiliary getter function. def getter(attrib): return lambda self, *args, **kwargs: \ getattr(self._obj, attrib)(*args, **kwargs) def ProxyFactory(obj, names, proxyclass=NicosProxy): """Factory function for Proxies that can delegate magic names.""" # Build class. cls = type("%sNicosProxy" % obj.__class__.__name__, (proxyclass,), {}) # Add magic names. for name in names: # Filter magic names. if name.startswith("__") and name.endswith("__"): if hasattr(obj.__class__, name): # Set attribute. setattr(cls, name, getter(name)) # Return instance. return cls(obj)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"log_it": "00_tspecscores.ipynb", "tsi": "00_tspecscores.ipynb", "spm": "00_tspecscores.ipynb", "zscore": "00_tspecscores.ipynb", "tau": "00_tspecscores.ipynb", "ts_func": "00_tspecscores.ipynb", "calc_ts": "00_tspecscores.ipynb"} modules = ["tspecscores.py"] doc_url = "https://morriso1.github.io/tspecscores/" git_url = "https://github.com/morriso1/tspecscores/tree/main/" def custom_doc_links(name): return None
class Sample(): """ A sample for a song, composed of slices (parts). """ def __init__(self, slices, song, size, index): self.slices = slices self.song = song self.size = size self.index = index class Slice(): """ A sample of the smallest size, used to construct longer samples. """ def __init__(self, file): self.file = file
n = int(input()) s = set(map(int, input().split())) for x in range(int(input())): method, *args = input().split() getattr(s, method)(*map(int, args)) print(sum(s))
# Copyright (c) 2011 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. { 'includes': [ 'mini_chromium/build/common.gypi', ], 'targets': [ { 'target_name': 'csfde', 'type': 'executable', 'include_dirs': [ 'mini_chromium', ], 'sources': [ 'csfde.mm', 'mini_chromium/base/basictypes.h', 'mini_chromium/base/compiler_specific.h', 'mini_chromium/base/logging.h', 'mini_chromium/base/logging.cc', 'mini_chromium/base/mac/scoped_cftyperef.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.mm', 'mini_chromium/base/memory/scoped_nsobject.h', 'mini_chromium/base/safe_strerror_posix.h', 'mini_chromium/base/safe_strerror_posix.cc', 'mini_chromium/build/build_config.h', 'mini_chromium/chrome/browser/mac/scoped_ioobject.h', ], 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/DiskArbitration.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/OpenDirectory.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/DiskManagement.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/EFILogin.framework', '$(SDKROOT)/usr/lib/libcsfde.dylib', ], 'xcode_settings': { 'ARCHS': [ 'x86_64', 'i386', ], 'FRAMEWORK_SEARCH_PATHS': [ '$(SDKROOT)/System/Library/PrivateFrameworks', ], }, }, ], }
''' Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: stack = [[root]] self.final = [] while stack: cur_list = [] onelist = stack.pop() tmp_list = [] for x in onelist: if x != None: tmp_list.append(x.val) if x.left != None: cur_list.append(x.left) if x.right != None: cur_list.append(x.right) if len(cur_list) > 0: stack.append(cur_list) if len(tmp_list) > 0: self.final.append(tmp_list) return self.final
""" Faça um programa que calcula a associação em paralelo de dois resistores R1 e R2 fornecidos pelo usuário via teclado. O programa fica pedindo estes valores e calculando até que o usuário entre com um valor para resistência igual a zero R = (R1 * R2)/(R1 + R2) """ while True: r1 = float(input('Insira um valor para resistor: ')) r2 = float(input('Insira um valor para resistor: ')) if r1 > 0 and r2 > 0: r = (r1 * r2)/(r1 + r2) print(f'Esse é valor da resistência {r:.2f}') else: break
""" Version information for `pip-audit`. """ __version__ = "1.1.1"
# model model = Model() i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{3,4}, 0.5f, 1") # a vector of input k = Int32Scalar("k", 2) i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{3,2}, 0.5f, 1") # values of output i3 = Output("op3", "TENSOR_INT32", "{3,2}") # indexes of output model = model.Operation("TOPK_V2", i1, k).To([i2, i3]) # Example 1. Input in operand 0, input0 = {i1: # input 0 [3, 4, 5, 6, 7, 8, 9, 1, 2, 18, 19, 11]} output0 = {i2: # output 0 [6, 5, 9, 8, 19, 18], i3: # output 1 [3, 2, 2, 1, 2, 1]} # Instantiate an example Example((input0, output0))
def memmove(data, dest, src, n): '''Copy data in the array from ``src`` to ``dest``. Like ``memmove(3)`` in C, the source and destination may overlap. Arguments: data (list): The list being manipulated. dest (int): The destination index of the copy. src (int): The source index of the copy. n (int): The number of elements to copy. ''' if dest < src: for i in range(n): data[dest + i] = data[src + i] else: for i in range(n): data[dest + n - i - 1] = data[src + n - i - 1] def test_memmove(): data = ['_', '_', 'A', 'B', 'C', '_', '_', '_'] data1 = data.copy() memmove(data1, 5, 2, 3) assert data1 == ['_', '_', 'A', 'B', 'C', 'A', 'B', 'C'] data2 = data.copy() memmove(data2, 3, 2, 3) assert data2 == ['_', '_', 'A', 'A', 'B', 'C', '_', '_'] data3 = data.copy() memmove(data3, 1, 2, 3) assert data3 == ['_', 'A', 'B', 'C', 'C', '_', '_', '_'] data4 = data.copy() memmove(data4, 2, 2, 3) assert data4 == ['_', '_', 'A', 'B', 'C', '_', '_', '_']
def insertion_sort(arr): for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: arr[pos] = arr[pos - 1] pos = pos - 1 arr[pos] = cursor return arr a = insertion_sort([3, 2, 5, 4, 1, 0]) print(a)
''' Juan Ivan Medina Martinez Exercise 5.6 ''' def stepLife(yourAge): if isinstance(yourAge,int): if(yourAge>=0): if(yourAge<2): print("Yo are an baby.") elif(4>yourAge>=2): print("You are an toddler.") elif(13>yourAge>=4): print("You are an kid.") elif(20>yourAge>=13): print("You are an teenager.") elif(65>yourAge>=20): print("You are an adult.") else: print("You are an elder.") else: print("Sorry, only positives.") else: print("Sorry, only 'int'.") if __name__ == '__main__': print(" *** Welcome to stageLife.py ***") age=input("Please enter your age: ") #if isinstance(age,int): # stepLife(age)
class TestUser(object): """Wraps a user data dictionary.""" # Private attributes: # dict<basestring, mixed> _data - The data dictionary. def __init__(self, data): self._data = data def favorite_food(self): return self._data['favoriteFood']
for i in range(10): n=int(input()) if(n< 1): n = 1 print("X[%d] = %d" % (i, n))
class GithubRequest(): def clone(self): raise NotImplementedError() def auth(self): raise NotImplementedError() def execute(self): raise NotImplementedError()
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"h3.libh3.experimentalH3ToLocalIj.restype": "00_core.ipynb", "h3.libh3.experimentalH3ToLocalIj.argtypes": "00_core.ipynb", "local_ij_delta": "00_core.ipynb", "local_ij_delta_to_class": "00_core.ipynb", "coordinatesToH3IndexSequence": "00_core.ipynb", "window": "00_core.ipynb", "generate_sequences_with_next_hex_class": "00_core.ipynb", "generate_sequences_with_next_hex_class_from_path": "00_core.ipynb", "parse_strava_gpx": "00_core.ipynb"} modules = ["core.py"] doc_url = "https://jaredwinick.github.io/h3_sequence/" git_url = "https://github.com/jaredwinick/h3_sequence/tree/master/" def custom_doc_links(name): return None
#!/usr/bin/env python ###################################################################################### ## Copyright (c) 2010-2011 The Department of Arts and Culture, ## ## The Government of the Republic of South Africa. ## ## ## ## Contributors: Meraka Institute, CSIR, South Africa. ## ## ## ## Permission is hereby granted, free of charge, to any person obtaining a copy ## ## of this software and associated documentation files (the "Software"), to deal ## ## in the Software without restriction, including without limitation the rights ## ## to use, copy, modify, merge, publish, distribute, sublicense, and#or sell ## ## copies of the Software, and to permit persons to whom the Software is ## ## furnished to do so, subject to the following conditions: ## ## The above copyright notice and this permission notice shall be included in ## ## all copies or substantial portions of the Software. ## ## ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ## ## THE SOFTWARE. ## ## ## ###################################################################################### ## ## ## AUTHOR : Daniel van Niekerk, Aby Louw ## ## DATE : October 2010 ## ## ## ###################################################################################### ## ## ## A rule rewriting module, can be used for G2P, syllabification, etc... ## ## ## ## ## ## ## ###################################################################################### class RewriteRule(object): """ Simply keeps rule info together... Rules are: LC [ A ] RC => B """ def __init__(self, LC, A, RC, B, ordinal): # fix LC if LC != None: tmp = list() skip = False for i in range(0, len(LC)): if skip: skip = False continue if (i < len(LC) - 1) and ((LC[i + 1] == "*") or (LC[i + 1] == "+")): tmp.append(LC[i + 1]) skip = True tmp.append(LC[i]) tmp.reverse() self.LC = tmp else: self.LC = LC self.A = A self.RC = RC self.B = B self.ordinal = ordinal def __str__(self): """Print in 'semicolon format'... """ ### PYTHON2 ### return ";".join([str(self.LC), str(self.A), str(self.RC), str(self.B), str(self.ordinal)]) ### PYTHON2 ### def _itemMatch(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def getRightHandSide(self): return self.B def _contextMatch(self, pattern, string, sets): """ Returns True if this rule matches the given context... """ # pattern is rule left or right context # string is itape if len(pattern) == 0: # rule context is none, so match return True elif len(string) == 0: # rule context is not none and itape context is none return False elif len(pattern) > 1 and pattern[1] == "*": r = self._contextMatch(pattern[2:], string, sets) tmp = pattern[2:] tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string, sets) t = self._itemMatch(pattern[0], string[0], sets) and self._contextMatch(pattern, string[1:], sets) return (r or s or t) elif len(pattern) > 1 and pattern[1] == "+": r = self._itemMatch(pattern[0], string[0], sets) tmp = pattern[2:] tmp.insert(0, "*") tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string[1:], sets) return (r and s) elif self._itemMatch(pattern[0], string[0], sets): return self._contextMatch(pattern[1:], string[1:], sets) else: return False def ruleMatches(self, LC, RC, sets): """ Returns this rule if it matches the given context... """ # right context (actually A + RC) must be at least as long as rule's A if len(RC) < len(self.A): return None # check if [ A ] matches counter = 0 a_match = [] for c1, c2 in zip(self.A, RC): if not self._itemMatch(c1, c2, sets): return None, None a_match.append(c2) counter += 1 # Check LC: LC may have some limited regex stuff rLC = list(LC) rLC.reverse() if (self._contextMatch(self.LC, rLC,sets) and self._contextMatch(self.RC, RC[counter:],sets)): return a_match, RC[counter:] else: return None, None class Rewrites(object): """ Class to contain and implement the application of rewrite rules to predict pronunciations of isolated words... ruleset is a dict of lists where the each list contains all RewriteRules associated with a specific grapheme... """ def __init__(self, sets=None): self.ruleset = {} self.sets = sets def _add_rule(self, index, rule): try: self.ruleset[index].append(rule) except KeyError: self.ruleset[index] = [] self.ruleset[index].append(rule) def addRule(self, index, rule): if index in self.sets: for set_entry in self.sets[index]: self._add_rule(set_entry, rule) else: self._add_rule(index, rule) def itemMatch(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def get_otape(self, rRHS, am): new_otape = [] ruleRHS = list(rRHS) ruleRHS.reverse() a_match = list(am) a_match.reverse() while len(ruleRHS) > 0: p = ruleRHS.pop() if p == "-": new_otape.append(p) else: r = a_match.pop() new_otape.append(r) return new_otape def rewrite(self, itape): """ Run rules on itape (LC A RC) to create rewrites otape (B) :param itape: Input tape consisting of LC A RC :type itape: List :return: Output tape B :rtype: List """ LC = itape[0:1] RC = itape[1:] otape = list() while len(RC) > 1: found_rule = False # search through rewrite rules to find matching one for rule in self.ruleset[RC[0]]: a_match, newRC = rule.ruleMatches(LC, RC, self.sets) if newRC is not None: found_rule = True break if not found_rule: res = "Failed to find rewrite rule for itape sequence '" + str(itape) + "'" raise RuntimeError(res) otape += self.get_otape(rule.getRightHandSide(), a_match) LC = LC + RC[0:len(RC) - len(newRC)] RC = newRC return otape
class Datacenter(object): def __init__(self, name=None, location=None, # pylint: disable=unused-argument description=None, volumes=None, servers=None, lans=None, loadbalancers=None): """ The Datacenter class initializer. :param name: The data center name.. :type name: ``str`` :param location: The data center geographical location. :type location: ``str`` :param description: Optional description. :type description: ``str`` :param volumes: List of volume dicts. :type volumes: ``list`` :param servers: List of server dicts. :type servers: ``list`` :param lans: List of LAN dicts. :type lans: ``list`` :param loadbalancers: List of load balancer dicts. :type loadbalancers: ``list`` """ if volumes is None: volumes = [] if servers is None: servers = [] if lans is None: lans = [] if loadbalancers is None: loadbalancers = [] self.name = name self.description = description self.location = location self.servers = servers self.volumes = volumes self.lans = lans self.loadbalancers = loadbalancers def __repr__(self): return (('<Datacenter: name=%s, location=%s, description=%s> ...>') % (self.name, self.location, self.description))
#!/usr/bin/python coins = [1,5,6,8] target = 51 def cons(e, xs): ys = xs.copy() ys.append(e) return ys # DP solution find the least number of coins for a given total # minCoins[i] is list of coins needed to make i # O(c * y) compared to O(c ^ n) def search(): minCoins = [[]] * (target + 1) for i in range(1, target+1): for c in coins: if i == c: minCoins[i] = [c] elif i > c: prev = len(minCoins[i-c]) curr = len(minCoins[i]) if prev > 0 and (curr == 0 or prev + 1 < curr): minCoins[i] = cons(c, minCoins[i-c]) # print(minCoins) return minCoins[target] soln = search() print(f'min coins {len(soln)}') print(soln)
print("Strings, (c) Verloka Vadim 2018\n\n\n") S1 = "example" S2 = "string" print(S1 + " " + S2) print(S1 * 2) #exampleexample print("Lenght - " + str(len(S1))) #len - длина строки print(S1[0]) #строка как масив символов print(S1[1]) print(S1[2]) print(S1[3]) print(S1[4]) print(S1[5]) print(S1[6]) print(S1[1:4]) print(S1[:4]) print(S1[1:]) print(ord("R")) #get ASCII code for symbol print(chr(82)) #get symbol by ASCII code
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Google Inc. 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. """MPEG-4 constants.""" TRAK_TYPE_VIDE = "vide" # Leaf types. TAG_STCO = "stco" TAG_CO64 = "co64" TAG_FREE = "free" TAG_MDAT = "mdat" TAG_XML = "xml " TAG_HDLR = "hdlr" TAG_FTYP = "ftyp" TAG_ESDS = "esds" TAG_SOUN = "soun" TAG_SA3D = "SA3D" # Container types. TAG_MOOV = "moov" TAG_UDTA = "udta" TAG_META = "meta" TAG_TRAK = "trak" TAG_MDIA = "mdia" TAG_MINF = "minf" TAG_STBL = "stbl" TAG_STSD = "stsd" TAG_UUID = "uuid" TAG_WAVE = "wave" # Sound sample descriptions. TAG_NONE = "NONE" TAG_RAW_ = "raw " TAG_TWOS = "twos" TAG_SOWT = "sowt" TAG_FL32 = "fl32" TAG_FL64 = "fl64" TAG_IN24 = "in24" TAG_IN32 = "in32" TAG_ULAW = "ulaw" TAG_ALAW = "alaw" TAG_LPCM = "lpcm" TAG_MP4A = "mp4a" SOUND_SAMPLE_DESCRIPTIONS = frozenset([ TAG_NONE, TAG_RAW_, TAG_TWOS, TAG_SOWT, TAG_FL32, TAG_FL64, TAG_IN24, TAG_IN32, TAG_ULAW, TAG_ALAW, TAG_LPCM, TAG_MP4A, ]) CONTAINERS_LIST = frozenset([ TAG_MDIA, TAG_MINF, TAG_MOOV, TAG_STBL, TAG_STSD, TAG_TRAK, TAG_UDTA, TAG_WAVE, ]).union(SOUND_SAMPLE_DESCRIPTIONS)