content stringlengths 7 1.05M |
|---|
expected_output = {
'instance': {
'default': {
'vrf': {
'red': {
'address_family': {
'': {
'prefixes': {
'11.11.11.11/32': {
'available_path': '1',
'best_path': '1',
'index': {
1: {
'binding_sid': {
'color': '7',
'sid': '22',
'state': 'UP',
},
'cluster_list': '8.8.8.9',
'ext_community': 'RT:2:2 Color:1 Color:2 Color:3 Color:4 Color:7',
'gateway': '7.7.7.9',
'imported_path_from': '1:1:11.11.11.11/32 (global)',
'localpref': 100,
'metric': 0,
'mpls_labels': {
'in': 'nolabel',
'out': '19',
},
'next_hop': '4.4.4.4',
'next_hop_igp_metric': '20',
'next_hop_via': 'default',
'origin_codes': '?',
'originator': '8.8.8.9',
'recipient_pathid': '0',
'refresh_epoch': 5,
'route_info': '1',
'status_codes': '*>',
'transfer_pathid': '0x0',
'update_group': 5,
},
},
'paths': '1 available, best #1, table red',
'table_version': '17',
},
},
},
},
},
},
},
},
}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
# compute the length of each seq
lenA = lenB = 1
nodeA = headA
while nodeA.next:
nodeA = nodeA.next
lenA += 1
nodeB = headB
while nodeB.next:
nodeB = nodeB.next
lenB += 1
if lenA < lenB: # make sure seq A is longer or equal to seq B
headA, headB = headB, headA
lenA, lenB = lenB, lenA
for i in range(lenA - lenB): # move only the seqA part longer than seq B forward
headA = headA.next
while headA and headB and headA != headB: # find the intersection
headA = headA.next
headB = headB.next
return headA |
def list_users_in_account(request_ctx, account_id, search_term=None,
include=None, per_page=None, **request_kwargs):
"""
Retrieve the list of users associated with this account.
@example_request
curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \
-X GET \
-H 'Authorization: Bearer <token>'
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param account_id: (required) ID
:type account_id: string
:param search_term: (optional) The partial name or full ID of the users to match and return in the
results list. Must be at least 3 characters.
Note that the API will prefer matching on canonical user ID if the ID has
a numeric form. It will only search against other fields if non-numeric
in form, or if the numeric value doesn't yield any matches. Queries by
administrative users will search on SIS ID, name, or email address; non-
administrative queries will only be compared against name.
:type search_term: string or None
:param include: (optional) One of (avatar_url, email, last_login, time_zone)
:type include: array or None
:param per_page: (optional) Set how many results canvas should return, defaults to config.LIMIT_PER_PAGE
:type per_page: integer or None
:return: List users in account
:rtype: requests.Response (with array data)
"""
if per_page is None:
per_page = request_ctx.per_page
include_types = ('avatar_url', 'email', 'last_login', 'time_zone')
utils.validate_attr_is_acceptable(include, include_types)
path = '/v1/accounts/{account_id}/users'
payload = {
'include[]': include,
'search_term': search_term,
'per_page': per_page,
}
url = request_ctx.base_api_url + path.format(account_id=account_id)
response = client.get(request_ctx, url, payload=payload, **request_kwargs)
return response
|
# Autogenerated file for HID Mouse
# Add missing from ... import const
_JD_SERVICE_CLASS_HID_MOUSE = const(0x1885dc1c)
_JD_HID_MOUSE_BUTTON_LEFT = const(0x1)
_JD_HID_MOUSE_BUTTON_RIGHT = const(0x2)
_JD_HID_MOUSE_BUTTON_MIDDLE = const(0x4)
_JD_HID_MOUSE_BUTTON_EVENT_UP = const(0x1)
_JD_HID_MOUSE_BUTTON_EVENT_DOWN = const(0x2)
_JD_HID_MOUSE_BUTTON_EVENT_CLICK = const(0x3)
_JD_HID_MOUSE_BUTTON_EVENT_DOUBLE_CLICK = const(0x4)
_JD_HID_MOUSE_CMD_SET_BUTTON = const(0x80)
_JD_HID_MOUSE_CMD_MOVE = const(0x81)
_JD_HID_MOUSE_CMD_WHEEL = const(0x82) |
def is_substitution_cipher(s1, s2):
dict1={}
dict2={}
for i,j in zip(s1, s2):
dict1[i]=dict1.get(i, 0)+1
dict2[j]=dict2.get(j, 0)+1
if len(dict1)!=len(dict2):
return False
return True |
"""properties.py module"""
DEFAULT_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
DEFAULT_FILE_NAME = ".secret.txt"
DEFAULT_LENGTH_OF_SECRET_KEY = 50
|
# A program to rearrange array in alternating positive & negative items with O(1) extra space
class ArrayRearrange:
def __init__(self, arr, n):
self.arr = arr
self.n = n
def rearrange_array(self):
arr = self.arr.copy()
out_of_place = -1
for i in range(self.n):
if out_of_place == -1:
# conditions for A[i] to
# be in out of place
if (arr[i] >= 0 and i % 2 == 0) or (arr[i] < 0 and i % 2 == 1):
out_of_place = i
if out_of_place >= 0:
if (arr[i] >= 0 and arr[out_of_place] < 0) or (arr[i] < 0 and arr[out_of_place] >= 0):
arr = self.right_rotate(arr, out_of_place, i)
if i - out_of_place > 2:
out_of_place += 2
else:
out_of_place = -1
return arr
@staticmethod
def right_rotate(arr, out_of_place, cur):
temp = arr[cur]
for i in range(cur, out_of_place, -1):
arr[i] = arr[i - 1]
arr[out_of_place] = temp
return arr
# Driver Code
arr = [-5, -2, 5, 2, 4,7, 1, 8, 0, -8]
s= ArrayRearrange(arr, len(arr))
print(f"Rearranged array is: {s.rearrange_array()}") |
expected_output = {
'pid': 'WS-C4507R',
'os': 'ios',
'platform': 'cat4k',
'version': '12.2(18)EW5',
}
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 17:22:59 2021
Default paths for the different folders.
Should be changed priori to any computation.
@author: amarmore
"""
# RWC
path_data_persisted_rwc = "C:/Users/amarmore/Desktop/data_persisted" ## Path where pre-computed data on RWC Pop should be stored (spectrograms, NTD, neural networks, etc)
path_annotation_rwc = "C:/Users/amarmore/Desktop/Audio samples/RWC Pop/annotations" ## Path of the annotations of RWC Pop. Should be parent folder of "AIST" and/or "MIREX10"
path_entire_rwc = "C:/Users/amarmore/Desktop/Audio samples/RWC Pop/Entire RWC" ## Path where are stored wav files of RWC
path_even_songs_rwc = "C:/Users/amarmore/Desktop/Audio samples/RWC Pop/Even songs" ## Path containing only the wav files of songs of odd numbers
path_odd_songs_rwc = "C:/Users/amarmore/Desktop/Audio samples/RWC Pop/Odd songs" ## Path containing only the wav files of songs of even numbers
path_debug_rwc = "C:/Users/amarmore/Desktop/Audio samples/RWC Pop/debug" ## Debug path, containing only two songs, to fix functions quickly
# SALAMI
path_data_persisted_salami = "C:/Users/amarmore/Desktop/Audio samples/Salami/data_persisted" ## Path where pre-computed data on the SALAMI dataset should be stored (spectrograms, NTD, neural networks, etc)
path_entire_salami = "C:/Users/amarmore/Desktop/Audio samples/Salami" ## Path where are stored wav files of SALAMI (path where it is downloaded by mirdata also) |
# -*- coding: utf-8 -*-
# @Brief: 配置文件
train_data_path = "./Omniglot/images_background/"
test_data_path = "./Omniglot/images_evaluation/"
summary_path = "./summary"
batch_size = 4
val_batch_size = 20
epochs = 10
inner_lr = 0.02
outer_lr = 0.0001
n_way = 5
k_shot = 1
q_query = 1
input_shape = (28, 28, 1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern"""
class Handler:
def __init__(self):
self._successor = None
def successor(self, successor):
self._successor = successor
def handle(self, request):
raise NotImplementedError('Must provide implementation in subclass.')
class ConcreteHandler1(Handler):
def handle(self, request):
if 0 < request <= 10:
print('request {} handled in handler 1'.format(request))
elif self._successor:
self._successor.handle(request)
class ConcreteHandler2(Handler):
def handle(self, request):
if 10 < request <= 20:
print('request {} handled in handler 2'.format(request))
elif self._successor:
self._successor.handle(request)
class ConcreteHandler3(Handler):
def handle(self, request):
if 20 < request <= 30:
print('request {} handled in handler 3'.format(request))
elif self._successor:
self._successor.handle(request)
class DefaultHandler(Handler):
def handle(self, request):
print('end of chain, no handler for {}'.format(request))
class Client:
def __init__(self):
h1 = ConcreteHandler1()
h2 = ConcreteHandler2()
h3 = ConcreteHandler3()
h4 = DefaultHandler()
h1.successor(h2)
h2.successor(h3)
h3.successor(h4)
self.handlers = (h1, h2, h3, h4,)
def delegate(self, requests):
for request in requests:
self.handlers[0].handle(request)
if __name__ == "__main__":
client = Client()
requests = [2, 5, 14, 22, 18, 3, 35, 27, 20]
client.delegate(requests)
### OUTPUT ###
# request 2 handled in handler 1
# request 5 handled in handler 1
# request 14 handled in handler 2
# request 22 handled in handler 3
# request 18 handled in handler 2
# request 3 handled in handler 1
# end of chain, no handler for 35
# request 27 handled in handler 3
# request 20 handled in handler 2
|
"""
A block cipher is a method of encrypting text,
in which a cryptographic key and algorithm are applied to a block of data
(for example, 64 contiguous bits) at once as a group rather than to one bit at a time.
A block cipher is a deterministic algorithm operating on fixed-length groups of bits,
called a block, with an unvarying transformation that is specified by a symmetric key.
Block ciphers operate as important elementary components in the design of many cryptographic protocols,
and are widely used to implement encryption of bulk data.
"""
def dummy():
pass
|
_MAJOR = 0
_MINOR = 6
_PATCH = 4
__version__ = str(_MAJOR) + '.' + str(_MINOR) + '.' + str(_PATCH)
def version():
'''
Returns a string representation of the version
'''
return __version__
def version_tuple():
'''
Returns a 3-tuple of ints that represent the version
'''
return (_MAJOR, _MINOR, _PATCH)
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/python-lists/
if __name__ == '__main__':
N = int(input())
lst = []
for i in range(N):
cmd = input().rstrip().split()
if(cmd[0] == 'insert'):
lst.insert(int(cmd[1]), int(cmd[2]))
elif(cmd[0] == 'print'):
print(lst)
elif(cmd[0] == 'remove'):
lst.remove(int(cmd[1]))
elif(cmd[0] == 'append'):
lst.append(int(cmd[1]))
elif(cmd[0] == 'sort'):
lst.sort()
elif(cmd[0] == 'pop'):
lst.pop()
elif(cmd[0] == 'reverse'):
lst.reverse()
|
class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
n1, s1 = 0, 1
for i in range(1, len(A)):
n2 = s2 = float("inf")
if A[i - 1] < A[i] and B[i - 1] < B[i]:
n2 = min(n2, n1)
s2 = min(s2, s1 + 1)
if A[i - 1] < B[i] and B[i - 1] < A[i]:
n2 = min(n2, s1)
s2 = min(s2, n1 + 1)
n1, s1 = n2, s2
print(n1, s2)
return min(n1, s1)
|
__author__ = 'xelhark'
class ErrorWithList(ValueError):
def __init__(self, message, errors_list=None):
self.errors_list = errors_list
super(ErrorWithList, self).__init__(message)
class ModelValidationError(ErrorWithList):
pass
class InstanceValidationError(ErrorWithList):
pass
|
config = {
"username": "",
"password": "",
"phonename": "iPhone",
"sms_csv": ""
} |
# Faça um programa que peça um numero inteiro positivo e em seguida mostre este numero invertido.
# Exemplo:
# 12376489
# => 98467321
print('Invertendo numeros')
nota = input('Informe um numero: ')
numeroInvertido = nota[::-1]
print(numeroInvertido) |
class BitDocument:
"""Wrapper for Firestore document (https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents)
"""
def __init__(self, doc):
self.id = doc['id']['stringValue']
self.title = self._get_field(doc, 'title', 'stringValue', '')
self.content = self._get_field(doc, 'content', 'stringValue', '')
self.tags = self._get_field(doc, 'tags', 'arrayValue', [])
def _get_field(self, doc, name, field_type, default_value=None):
if name in doc:
if field_type == 'arrayValue':
if doc[name][field_type]:
return [val['stringValue'] for val in doc[name][field_type]['values']]
else:
return doc[name][field_type]
return default_value
def as_partial(self):
"""Return string representing a partial bit document, used for
displaying search results, mapped to term / id in our index.
"""
return dict(id=self.id, title=self.title, tags=self.tags)
def as_indexable_str(self):
"""Concatenated string of all indexable fields.
"""
return ' '.join([self.title, self.content, ' '.join(self.tags or [])])
|
mylist = list()
def maior(*lst):
m = 0
print(f'Os valores informados foram -> ', end=' ')
for i, v in enumerate(lst[0]):
print(v, end=' ')
if i == 0:
m = v
else:
if v > m:
m = v
print(f'\nO maior valor informado foi {m}')
while True:
while True:
qtd_num = input('Informe a quantidades de números que vc deseja inserir no sistema: ').strip().lower()
if qtd_num.isnumeric():
qtd_num = int(qtd_num)
break
else:
print('\033[41mInforme um valor válido!\033[m')
for c in range(0, qtd_num):
while True:
valor = input('Informe um número inteiro: ')
if valor.isnumeric():
mylist.append(int(valor))
print('\033[42mValor salvo com sucesso!\033[m')
break
else:
print('\033[41mInforme um valor válido!\033[m')
maior(mylist)
while True:
resposta = input('Deseja fazer para mais valores [S/N]: ').strip().lower()[0]
if resposta == 's' or resposta == 'n':
break
else:
print('\033[41mInforme uma resposta válida!\033[m')
if resposta == 'n':
break
mylist.clear()
print('Encerrando o programa!')
print('Programa encerrado!')
|
#This program takes in a postive integer and applies a calculation to it.
# It then outputs a sequence that ends in 1
#creates a list called L
mylist=[]
#take the input for the user
value = int(input("Please enter a positive integer: "))
# Adds the input to the list.
# The append wouldnt work unless I made i an int value when tring to append
mylist.append(int(value))
#starts a while loop that will stop when i reaches 1
# The next value is gotten by taking the current value and
# if it is even, divide it by two, but if it is odd, multiply it by three and add one.
# The program ends if the current value is one., if the user enters 1 then the loop wont run
while value != 1:
if value % 2 == 0:
value /= 2
mylist.append(int(value))
else:
value = (value*3)+1
mylist.append(int(value))
print(mylist)
#based on andrew's feedback I tried to make my variable names more meaning full |
class Aritmatika:
@staticmethod
def tambah(a, b):
return a + b
@staticmethod
def kurang(a, b):
return a - b
@staticmethod
def bagi(a, b):
return a / b
@staticmethod
def bagi_int(a, b):
return a // b
@staticmethod
def pangkat(a, b):
return a ** b
# Langsung call class dan method
print(Aritmatika.tambah(5, 5))
# Bikin object dlu
objekA = Aritmatika()
print(objekA.pangkat(2, 3)) |
# Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
def solve(board):
"""
Do not return anything, modify board in-place instead.
"""
if not board: return board
nrow = len(board)
ncol = len(board[0])
if nrow <= 2 or ncol <= 2: return board
for i in range(nrow):
for j in range(ncol):
if (i == 0 or i == nrow-1 or j == 0 or j == ncol-1) and board[i][j] == 'O':
dfs(board, i, j)
for i in range(nrow):
for j in range(ncol):
if board[i][j] == 'O':
board[i][j] = 'X'
elif board[i][j] == 'o':
board[i][j] = 'O'
return board
def dfs(self, board, i, j):
nrow = len(board)
ncol = len(board[0])
if i >= 0 and i < nrow and j >= 0 and j < ncol and board[i][j] == 'O':
board[i][j] = 'o'
dfs(board, i-1, j)
dfs(board, i+1, j)
dfs(board, i, j-1)
dfs(board, i, j+1)
return
|
#Exercise 1: Revise a previous program as follows: Read and parse the
#“From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
#After all the data has been read, print the person with the most commits
#by creating a list of (count, email) tuples from the dictionary. Then
#sort the list in reverse order and print out the person who has the most
#commits.
#Sample Line:
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#Enter a file name: mbox-short.txt
#cwen@iupui.edu 5
#Enter a file name: mbox.txt
#zqian@umich.edu 195
filename=input("enter a file name: ")
fhand=open(filename)
days={}
for line in fhand:
if line.startswith("From "):
day=line.split()[1]
days[day]=days.get(day,0)+1
list=[]
for key,value in days.items():
list.append((value,key))
list.sort(reverse=True)
tuple=list[0]
print(tuple[1],tuple[0])
|
# Aula 7
n1 = int(input('Digite um número inteiro: '))
n2 = int(input('Digite outro número inteiro: '))
s = n1 + n2
sub = n1 - n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
r = n1 % n2
e = n1 ** n2
print('A soma dos números {} e {} é igual a {}.'.format(n1, n2, s), end=' ')
# end='' serve para não pular linha. Para pular, utiliza-se o /n
print('A subtração é {}, a multiplicação é {}, a divisão é {:.2f}'.format(sub, m, d), end=' >>> ')
# No end='' anterior, só inclui >>> para mostarr que pode ter conteúdo dentro das aspas e que ele aparece
print('A divisão inteira é {}, o resto da divisão é {}, um elevado ao outro é {}'.format(di, r, e))
|
def calculate_similarity(my, theirs, tags):
similarity = {}
for group in ('personal', 'hobbies'):
all_names = {tag.code for tag in tags if tag.group == group}
my_names = all_names & my
their_names = all_names & theirs
both = my_names | their_names
same = my_names & their_names
similarity[group] = len(same) * 100 / len(both) if both else 0
return similarity
def is_role_manageable_by_user(role, user):
if role in (user.ROLE_GOD, user.ROLE_MODERATOR):
return user.is_god
if role == user.ROLE_CURATOR:
return user.is_moderator
return False
|
"""
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Average:
def __init__(self, js: dict):
self._allDamageDoneAvgPer10Min = js["allDamageDoneAvgPer10Min"] if "allDamageDoneAvgPer10Min" in js else 0
self._barrierDamageDoneAvgPer10Min = js[
"barrierDamageDoneAvgPer10Min"] if "barrierDamageDoneAvgPer10Min" in js else 0
self._deathsAvgPer10Min = js["deathsAvgPer10Min"] if "deathsAvgPer10Min" in js else 0
self._eliminationsAvgPer10Min = js["eliminationsAvgPer10Min"] if "eliminationsAvgPer10Min" in js else 0
self._finalBlowsAvgPer10Min = js["finalBlowsAvgPer10Min"] if "finalBlowsAvgPer10Min" in js else 0
self._healingDoneAvgPer10Min = js["healingDoneAvgPer10Min"] if "healingDoneAvgPer10Min" in js else 0
self._heroDamageDoneAvgPer10Min = js["heroDamageDoneAvgPer10Min"] if "heroDamageDoneAvgPer10Min" in js else 0
self._objectiveKillsAvgPer10Min = js["objectiveKillsAvgPer10Min"] if "objectiveKillsAvgPer10Min" in js else 0
self._objectiveTimeAvgPer10Min = js["objectiveTimeAvgPer10Min"] if "objectiveTimeAvgPer10Min" in js else 0
self._soloKillsAvgPer10Min = js["_soloKillsAvgPer10Min"] if "_soloKillsAvgPer10Min" in js else 0
self._timeSpentOnFireAvgPer10Min = js["timeSpentOnFireAvgPer10Min"] if "timeSpentOnFireAvgPer10Min" in js else 0
@property
def allDamageDoneAvgPer10Min(self) -> int:
return self._allDamageDoneAvgPer10Min
@property
def barrierDamageDoneAvgPer10Min(self) -> int:
return self._barrierDamageDoneAvgPer10Min
@property
def deathsAvgPer10Min(self) -> int:
return self._deathsAvgPer10Min
@property
def eliminationsAvgPer10Min(self) -> int:
return self._eliminationsAvgPer10Min
@property
def finalBlowsAvgPer10Min(self) -> int:
return self._finalBlowsAvgPer10Min
@property
def healingDoneAvgPer10Min(self) -> int:
return self._healingDoneAvgPer10Min
@property
def heroDamageDoneAvgPer10Min(self) -> int:
return self._heroDamageDoneAvgPer10Min
@property
def objectiveKillsAvgPer10Min(self) -> int:
return self._objectiveKillsAvgPer10Min
@property
def objectiveTimeAvgPer10Min(self) -> int:
return self._objectiveTimeAvgPer10Min
@property
def soloKillsAvgPer10Min(self) -> int:
return self._soloKillsAvgPer10Min
@property
def timeSpentOnFireAvgPer10Min(self) -> int:
return self._timeSpentOnFireAvgPer10Min
|
# Method 1: using index find the max first, and then process
def validMountainArray(self, A):
if len(A) < 3: return False
index = A.index(max(A))
if index == 0 or index == len(A) -1: return False
for i in range(1, len(A)):
if i <= index:
if A[i] <= A[i - 1]: return False
else:
if A[i] >= A[i - 1]: return False
return True
# Method 2: one pass, using two pointers trace from the begining and end
def validMountainArray(self, A):
i, j = 0, len(A) - 1
while i < len(A) - 1 and A[i] < A[i + 1]: i += 1
while j > 0 and A[j - 1] > A[j]: j -= 1
return 0 < i == j < len(A) - 1 |
# 69. Sqrt(x) Easy
# Implement int sqrt(int x).
#
# Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
#
# Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
#
# Example 1:
#
# Input: 4
# Output: 2
# Example 2:
#
# Input: 8
# Output: 2
# Explanation: The square root of 8 is 2.82842..., and since
# the decimal part is truncated, 2 is returned.
def mySqrt(self, x: int) -> int:
'''
Runtime: 56 ms, faster than 54.11% of Python3 online submissions for Sqrt(x).
Memory Usage: 13.1 MB, less than 79.16% of Python3 online submissions for Sqrt(x).
'''
# 2^2 = 4
# 2.82842^2 = 8
# x > 1, range(1, x)
# x < 1, range(0, 1)
if x == 1 or x == 0:
return x
max_range = max(1, x)
min_range = 0
result = 0
while (max_range - min_range != 0):
mid = min_range + (max_range - min_range) // 2
result = mid * mid
print(result)
if int(result) <= x < (mid + 1) * (mid + 1):
return int(mid)
if result < x:
min_range = mid
else:
max_range = mid
|
class Line(object):
"""Represents a line on the road, which consists of a list of coordinates.
Attributes:
line_id: an integer indicating which line this is.
coordinates: a list of tuples indicating the coordinates on the line.
"""
def __init__(self, line_id, coordinates):
"""Initializes the Line class."""
self.line_id = line_id
self.coordinates = coordinates
def get_coordinates(self):
"""Returns the array of coordinates."""
return self.coordinates
def get_id(self):
"""Returns the line's id."""
return self.line_id
|
class UncleEngineer:
'''
test = UncleEngineer()
test.art()
'''
def __init__(self):
self.name = 'Uncle Engineer'
def art(self):
asciiart = '''
Z
Z
.,., z
(((((()) z
((('_ _`) '
((G \ |)
(((` " ,
.((\.:~: .--------------.
__.| `"'.__ | \ |
.~~ `---' ~. | . :
/ ` | `-.__________)
| ~ | : :
| | : |
| _ | | [ ## :
\ ~~-. | , oo_______.'
`_ ( \) _____/~~~~ `--___
| ~`-) ) `-. `--- ( - a:f -
| '///` | `-.
| | | | `-.
| | | | `-.
| | |\ |
| | | \|
`-. | | |
`-| '
'''
print(asciiart)
def __str__(self):
return self.name
class UncleEngineer:
'''
test = BTT()
test.art()
'''
def __init__(self):
self.name = 'BTT'
def art(self):
asciiart = '''
;::::;
;::::; :;
;:::::' :;
;:::::; ;.
,:::::' ; OOO\
::::::; ; OOOOO\
;:::::; ; OOOOOOOO
,;::::::; ;' / OOOOOOO
;:::::::::`. ,,,;. / / DOOOOOO
.';:::::::::::::::::;, / / DOOOO
,::::::;::::::;;;;::::;, / / DOOO
;`::::::`'::::::;;;::::: ,#/ / DOOO
:`:::::::`;::::::;;::: ;::# / DOOO
::`:::::::`;:::::::: ;::::# / DOO
`:`:::::::`;:::::: ;::::::#/ DOO
:::`:::::::`;; ;:::::::::## OO
::::`:::::::`;::::::::;:::# OO
`:::::`::::::::::::;'`:;::# O
`:::::`::::::::;' / / `:#
::::::`:::::;' / / `#
'''
print(asciiart)
def __str__(self):
return self.name
|
class Vscode():
def execute(self):
print("code is compiling and code is running")
class Pycharm():
def execute(self):
print("code is compiling and code is running")
class python():
def execute(self):
print("python is using")
class CPP():
def execute(self):
print("C++ is using")
class Laptop():
def code(self,ide,lang):
ide.execute(self)
lang.execute(self)
lap1=Laptop()
lap1.code(Vscode,python)
lap1.code(Pycharm,CPP)
|
n = int(input('Digite um número inteiro: '))
print()
print('Escolha uma das bases para conversão:')
print(' [ 1 ] Converte para BÍNARIO')
print(' [ 2 ] Converte para OCTAL')
print(' [ 3 ] Converte para HEXADECIMAL')
print()
opcao = int(input('ESCOLHA SUA OPÇÃO: '))
if (opcao >= 1) and (opcao <= 3):
if opcao == 1:
print('{} convertido para BINÁRIO é igual a {}'.format(n, bin(n)[2:]))
elif opcao == 2:
print('{} convertido para OCTAL é igual a {}'.format(n, oct(n)[2:]))
elif opcao == 3:
print('{} convertido para HEXADECIMAL é igual a {}'.format(n, hex(n)[2:]))
else:
print('Valor digitado para conversão inexistente!')
|
#! /usr/bin/python
__version__ = "0.1.0"
__description__ = "Connection facilitator"
__logo__ = """
___ ____ ____ __ ____ __ __ ___
/ __)(_ _)( _ \ /__\ (_ _)( )( )/ __)
\__ \ )( ) / /(__)\ )( )(__)( \__ \\
(___/ (__) (_)\_)(__)(__)(__) (______)(___/
"""
PORT = 5678
TIME_OUT = 20
BIND_TIME = 0.1
ALL_CLIENTS = "__all__"
DOUBLE_LINE_BREAK = "\r\n\r\n"
CONNECTION_REFUSED = "Connection Refused"
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 10:28:28 2019
@author: Paul
"""
def generate_passwords(start, stop):
"""
Generates and returns a list strings of all possible passwords in the range
start-stop, meeting the following requirements:
- Passwords are six digit numbers
- In each password two adjacent digits must be the same
- In each password, going from largest to smallest digit, the size of
the digit does not decrease:
111123, 135679, 111111 meet the criteria
223450 does not (decreasing pair of digits 50)
123789 does not (no double adjacent digits)
"""
passwords = []
for i in range(start, stop+1, 1):
passwords.append(str(i))
return passwords
def valid_passwords_1(passwords):
"""
Takes a list of password strings, and returns the number of passwords in
the list meeting the following criteria:
- Passwords are six digit numbers
- In each password two adjacent digits must be the same
- In each password, going from largest to smallest digit, the size of
the digit does not decrease:
111123, 135679, 111111 meet the criteria
223450 does not (decreasing pair of digits 50)
123789 does not (no double adjacent digits)
"""
valid = 0
for entry in passwords:
adjacent = False
order = True
#Check for adjacent duplicate numbers
for i in range(len(entry) - 1):
if entry[i] == entry[i+1]:
adjacent = True
for i in range(len(entry) - 1):
if entry[i] > entry[i+1]:
order = False
if adjacent and order:
valid += 1
return valid
def valid_passwords_2(passwords):
"""
Takes a list of password strings, and returns the number of passwords in
the list meeting the following criteria:
- Passwords are six digit numbers
- In each password two adjacent digits must be the same
- The two adjacent digits meeting the above requirement must not be
part of a larger repeated block ie. 123455 is valid, 123444 is not.
- In each password, going from largest to smallest digit, the size of
the digit does not decrease:
111123, 135679, 111111 meet the criteria
223450 does not (decreasing pair of digits 50)
123789 does not (no double adjacent digits)
"""
valid = 0
for entry in passwords:
adjacent = False
order = True
#Check for adjacent duplicate numbers
for i in range(len(entry) - 1):
if (entry[i] == entry[i+1]):
test_num = entry[i]
if entry.count(test_num) == 2:
adjacent = True
for i in range(len(entry) - 1):
if entry[i] > entry[i+1]:
order = False
if adjacent and order:
valid += 1
return valid
#passwords = ["112233", "123444", "111122"] #Test Passwords
passwords = generate_passwords(256310, 732736)
valid_pass_num1 = valid_passwords_1(passwords)
valid_pass_num2 = valid_passwords_2(passwords)
print("Part 1: Number of valid passwords in range: ", valid_pass_num1)
print("Part 2: Number of valid passwords in range: ", valid_pass_num2) |
nums = [2, 3, 4, 5, 7, 10, 12]
for n in nums:
print(n, end=", ")
class CartItem:
def __init__(self, name, price) -> None:
self.price = price
self.name = name
def __repr__(self) -> str:
return "({0}, ${1})".format(self.name, self.price)
class ShoppingCart:
def __init__(self) -> None:
self.items = []
def add(self, cart_item):
self.items.append(cart_item)
def __iter__(self):
return self.items.__iter__()
@property
def total_price(self):
total = 0.0
for item in self.items:
total += item.price
return total
print()
print()
cart = ShoppingCart()
cart.add(CartItem("CD", 9.99))
cart.add(CartItem("Vinyle", 14.99))
for c in cart:
print(c)
print("Total is ${0:,}".format(cart.total_price))
|
# Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).
# missing_char('kitten', 1) → 'ktten'
# missing_char('kitten', 0) → 'itten'
# missing_char('kitten', 4) → 'kittn'
def missing_char(sam_str, n):
new_str = ""
for index in range(0,len(sam_str)):
if(index != n):
new_str+=sam_str[index];
print(new_str)
missing_char('kitten', 1) |
highest_seat_id = 0
with open("input.txt", "r") as f:
lines = [line.rstrip() for line in f.readlines()]
for line in lines:
rows = [0, 127]
row = None
columns = [0, 7]
column = None
for command in list(line):
if command == "F":
rows = [rows[0], ((rows[1] - rows[0]) // 2) + rows[0]]
elif command == "B":
rows = [((rows[1] - rows[0]) // 2) + rows[0] + 1, rows[1]]
elif command == "L":
columns = [columns[0], ((columns[1] - columns[0]) // 2) + columns[0]]
elif command == "R":
columns = [((columns[1] - columns[0]) // 2) + columns[0] + 1, columns[1]]
if rows[0] == rows[1]:
row = rows[0]
if columns[0] == columns[1]:
column = columns[0]
seat_id = row * 8 + column
if seat_id > highest_seat_id:
highest_seat_id = seat_id
#print(f"line: {line}, row: {row}, column: {column}, seat ID: {seat_id}")
print(f"\nWhat is the highest seat ID on a boarding pass? {highest_seat_id}")
|
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
if k ==0 or pRoot is None:
return None
stack = []
cur = pRoot
while(True):
while(cur is not None):
stack.append(cur)
cur = cur.left
if len(stack) == 0:
break
cur = stack.pop()
k -= 1
if k ==0:
break
cur = cur.right
return cur |
#! /usr/bin/env python
"""
Make a small MDV file containing a grid with X and Y axes in degrees.
Partial grid is taken from full sized file 000000.mdv which is contained in
the 200202.MASTER15.mdv.tar.gz file available online at:
http://www2.mmm.ucar.edu/imagearchive/WSI/mdv/
"""
# The MDV RLE decoding routine ends at the end of the data stream even if not
# all data point have been read. Therefore a file truncated at a break in the
# RLE can still be read but data past the last data point will be filled with
# random data. Here we end after the first non-keyed RLE byte.
infile = open('000000.mdv', 'rb')
outfile = open('example_mdv_grid.mdv', 'wb')
outfile.write(infile.read(8134))
infile.close()
outfile.close()
|
class Vertex:
def __init__(self, label: str = None, weight: int = float("inf"), key: int = None):
self.label: str = label
self.weight: int = weight
self.key: int = key
|
class Solution:
def dfs(self, s:str, n:int, pos:int, sub_res:list, total_res:list, left:int):
if left == 0 and pos >= n:
total_res.append(sub_res[:])
return
if left == 0 and pos < n:
return
if pos < n and s[pos] == '0':
sub_res.append(s[pos])
self.dfs(s,n,pos + 1, sub_res,total_res, left - 1)
sub_res.pop()
return
for delt in range(3, 0, -1):
if delt + pos > n:
continue
target = int(s[pos:delt + pos])
if target > 255:
continue
sub_res.append(s[pos:delt + pos])
self.dfs(s, n, pos + delt, sub_res, total_res, left - 1)
sub_res.pop()
def restoreIpAddresses(self, s: str):
n = len(s)
if n < 4:
return []
if n == 4:
return [".".join(s)]
res = []
self.dfs(s, n, 0, [], res, 4)
return [".".join(x) for x in res]
# sl = Solution()
# t1 = "25525511135"
# res = sl.restoreIpAddresses(t1)
# print(res)
sl = Solution()
t1 = "010010"
res = sl.restoreIpAddresses(t1)
print(res)
|
collection = ["gold", "silver", "bronze"]
# list comprehension
new_list = [item.upper for item in collection]
# generator expression
# it is similar to list comprehension, but use () round brackets
my_gen = (item.upper for item in collection) |
grader_tools = {}
def tool(f):
grader_tools[f.__name__] = f
return f
@tool
def percentage(x, y):
"""
Convert x/y into a percentage. Useful for calculating success rate
Args:
x (int)
y (int)
Returns:
str: percentage formatted into a string
"""
return '%.2f%%' % (100 * x / y)
|
# This is where all of our model classes are defined
class PhysicalAttributes:
def __init__(self, width=None, height=None, depth=None, dimensions=None, mass=None):
self.width = width
self.height = height
self.depth = depth
self.dimensions = dimensions
self.mass = mass
def serialize(self):
return {
'width': self.width,
'height': self.height,
'depth': self.depth,
'dimensions': self.dimensions,
'mass': self.mass
}
def __repr__(self):
return repr(self.serialize())
class Hardware:
def __init__(self, cpu=None, gpu=None, ram=None, nonvolatile_memory=None):
self.cpu = cpu
self.gpu = gpu
self.ram = ram
self.nonvolatile_memory = nonvolatile_memory
def serialize(self):
return {
'cpu': self.cpu.serialize() if self.cpu is not None else None,
'gpu': self.gpu.serialize() if self.gpu is not None else None,
'ram': self.ram.serialize() if self.ram is not None else None,
'nonvolatile_memory': self.nonvolatile_memory.serialize() if self.nonvolatile_memory is not None else None
}
def __repr__(self):
return repr(self.serialize())
class Cpu:
def __init__(self, model=None, additional_info=None, clock_speed=None):
self.model = model
self.clock_speed = clock_speed
self.additional_info = additional_info \
if not additional_info or not isinstance(additional_info, str) \
else [additional_info]
def serialize(self):
return {
'model': self.model,
'additional_info': self.additional_info,
'clock_speed': self.clock_speed
}
def __repr__(self):
return repr(self.serialize())
class Gpu:
def __init__(self, model=None, clock_speed=None):
self.model = model
self.clock_speed = clock_speed
def serialize(self):
return {
'model': self.model,
'clock_speed': self.clock_speed
}
def __repr__(self):
return repr(self.serialize())
class Ram:
def __init__(self, type_m=None, capacity=None):
self.type_m = type_m
self.capacity = capacity
def serialize(self):
return {
'type': self.type_m,
'capacity': self.capacity
}
def __repr__(self):
return repr(self.serialize())
class NonvolatileMemory:
def __init__(self, type_m=None, capacity=None):
self.type_m = type_m
self.capacity = capacity
def serialize(self):
return {
'type': self.type_m,
'capacity': self.capacity
}
def __repr__(self):
return repr(self.serialize())
class Display:
def __init__(self, resolution=None, diagonal=None, width=None, height=None, bezel_width=None,
area_utilization=None, pixel_density=None, type_m=None, color_depth=None, screen=None):
self.resolution = resolution
self.diagonal = diagonal
self.width = width
self.height = height
self.bezel_width = bezel_width
self.area_utilization = area_utilization
self.pixel_density = pixel_density
self.type_m = type_m
self.color_depth = color_depth
self.screen = screen
def serialize(self):
return {
'resolution': self.resolution,
'diagonal': self.diagonal,
'width': self.width,
'height': self.height,
'bezel_width': self.bezel_width,
'area_utilization': self.area_utilization,
'pixel_density': self.pixel_density,
'type': self.type_m,
'color_depth': self.color_depth,
'screen': self.screen
}
def __repr__(self):
return repr(self.serialize())
class Camera:
def __init__(self, placement=None, module=None, sensor=None, sensor_format=None, resolution=None,
num_pixels=None, aperture=None, optical_zoom=None, digital_zoom=None, focus=None,
camcorder=None, flash=None):
self.placement = placement
self.module = module
self.sensor = sensor
self.sensor_format = sensor_format
self.resolution = resolution
self.num_pixels = num_pixels
self.aperture = aperture
self.optical_zoom = optical_zoom
self.digital_zoom = digital_zoom
self.focus = focus
self.camcorder = camcorder
self.flash = flash
def serialize(self):
return {
'placement': self.placement,
'module': self.module,
'sensor': self.sensor,
'sensor_format': self.sensor_format,
'resolution': self.resolution,
'num_pixels': self.num_pixels,
'aperture': self.aperture,
'optical_zoom': self.optical_zoom,
'digital_zoom': self.digital_zoom,
'focus': self.focus,
'camcorder': self.camcorder.serialize() if self.camcorder is not None else None,
'flash': self.flash
}
def __repr__(self):
return repr(self.serialize())
class Camcorder:
def __init__(self, resolution=None, formats=None):
self.resolution = resolution
self.formats = formats
def serialize(self):
return {
'resolution': self.resolution,
'formats': self.formats
}
def __repr__(self):
return repr(self.serialize())
class Software:
def __init__(self, platform=None, os=None, software_extras=None):
self.platform = platform
self.os = os
self.software_extras = software_extras \
if not software_extras or not isinstance(software_extras, str) \
else [software_extras]
def serialize(self):
return {
'platform': self.platform,
'os': self.os,
'software_extras': self.software_extras
}
def __repr__(self):
return repr(self.serialize())
class Model:
def __init__(self, image=None, name=None, brand=None, model=None, release_date=None,
hardware_designer=None, manufacturers=None, codename=None, market_countries=None,
market_regions=None, carriers=None, physical_attributes=None,
hardware=None, software=None, display=None, cameras=None):
# singular attributes
self.image = image
self.name = name
self.brand = brand
self.model = model
self.release_date = release_date
self.hardware_designer = hardware_designer
self.codename = codename
# list attributes (convert to list if it's neither str nor None)
self.manufacturers = manufacturers \
if not manufacturers or not isinstance(manufacturers, str) else [manufacturers]
self.market_countries = market_countries \
if not market_countries or not isinstance(market_countries, str) else [market_countries]
self.market_regions = market_regions \
if not market_regions or not isinstance(market_regions, str) else [market_regions]
self.carriers = carriers \
if not carriers or not isinstance(carriers, str) else [carriers]
# classed attributes
self.physical_attributes = physical_attributes
self.hardware = hardware
self.software = software
self.display = display
self.cameras = cameras
def serialize(self):
return {
'image': self.image,
'name': self.name,
'brand': self.brand,
'model': self.model,
'release_date': self.release_date,
'hardware_designer': self.hardware_designer,
'manufacturers': self.manufacturers,
'codename': self.codename,
'market_countries': self.market_countries,
'market_regions': self.market_regions,
'carriers': self.carriers,
'physical_attributes': self.physical_attributes.serialize() if self.physical_attributes is not None else None,
'software': self.software.serialize() if self.software is not None else None,
'hardware': self.hardware.serialize() if self.hardware is not None else None,
'display': self.display.serialize() if self.display is not None else None,
'cameras': [camera.serialize() for camera in self.cameras]
}
def __repr__(self):
return repr(self.serialize())
class Brand:
def __init__(self, image=None, name=None, type_m=None, industries=None, found_date=None, location=None,
area_served=None, phone_models=None, carriers=None, os=None, founders=None,
parent=None):
self.image = image
self.name = name
self.type_m = type_m
self.found_date = found_date
self.location = location
self.area_served = area_served
self.parent = parent
self.industries = industries \
if not industries or not isinstance(industries, str) else [industries]
self.phone_models = phone_models \
if not phone_models or not isinstance(phone_models, str) else [phone_models]
self.carriers = carriers \
if not carriers or not isinstance(carriers, str) else [carriers]
self.os = os \
if not os or not isinstance(os, str) else [os]
self.founders = founders \
if not founders or not isinstance(founders, str) else [founders]
def serialize(self):
return {
'image': self.image,
'name': self.name,
'type': self.type_m,
'industries': self.industries,
'found_date': self.found_date,
'location': self.location,
'area_served': self.area_served,
'phone_models': self.phone_models,
'carriers': self.carriers,
'os': self.os,
'founders': self.founders,
'parent': self.parent
}
def __repr__(self):
return repr(self.serialize())
class OS:
def __init__(self, image=None, name=None, developer=None, release_date=None, version=None,
os_kernel=None, os_family=None, supported_cpu_instruction_sets=None,
predecessor=None, brands=None, models=None, codename=None,
successor=None):
self.image = image
self.name = name
self.developer = developer
self.release_date = release_date
self.version = version
self.os_kernel = os_kernel
self.os_family = os_family
self.supported_cpu_instruction_sets = supported_cpu_instruction_sets \
if not supported_cpu_instruction_sets or not isinstance(supported_cpu_instruction_sets, str) \
else [supported_cpu_instruction_sets]
self.predecessor = predecessor
self.brands = brands \
if not brands or not isinstance(brands, str) else [brands]
self.models = models \
if not models or not isinstance(models, str) else [models]
self.codename = codename
self.successor = successor
def serialize(self):
return {
'image': self.image,
'name': self.name,
'developer': self.developer,
'release_date': self.release_date,
'version': self.version,
'os_kernel': self.os_kernel,
'os_family': self.os_family,
'supported_cpu_instruction_sets': self.supported_cpu_instruction_sets,
'predecessor': self.predecessor,
'brands': self.brands,
'models': self.models,
'codename': self.codename,
'successor': self.successor
}
def __repr__(self):
return repr(self.serialize())
class Carrier:
def __init__(self, image=None, name=None, short_name=None, cellular_networks=None,
covered_countries=None, brands=None, models=None):
self.image = image
self.name = name
self.short_name = short_name
self.cellular_networks = cellular_networks \
if not cellular_networks or not isinstance(cellular_networks, str) else [cellular_networks]
self.covered_countries = covered_countries \
if not covered_countries or not isinstance(covered_countries, str) else [covered_countries]
self.brands = brands \
if not brands or not isinstance(brands, str) else [brands]
self.models = models \
if not models or not isinstance(models, str) else [models]
def serialize(self):
return {
'image': self.image,
'name': self.name,
'short_name': self.short_name,
'cellular_networks': self.cellular_networks,
'covered_countries': self.covered_countries,
'brands': self.brands,
'models': self.models
}
def __repr__(self):
return repr(self.serialize())
|
class Identifier(object):
def __init__(self, name, value, declared=False, id_type=None, constant=False):
self.name = name
self.value = value
self.declared = declared
self.type = id_type
self.constant = constant
def __str__(self):
return self.name |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 21:34:17 2017
@author: chen
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# class Solution(object):
# def hasCycle(self, head):
# """
# :type head: ListNode
# :rtype: bool
# """
# if head == None:
# return False
# middleN = endN = head
# count = 1
# while endN != None:
# if endN.next ==None:
# return False
# endN = endN.next
# if count%2 ==0:
# middleN = middleN.next
# if endN == middleN:
# return True
# count+=1
# return False
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
a= ListNode(0)
b = ListNode(1)
c = ListNode(2)
a.next = b
b.next = c
c.next = b
D = None
A = Solution()
print(A.hasCycle(a))
|
def mostra_adicionais(*args):
telaProduto = args[0]
cursor = args[1]
QtWidgets = args[2]
telaProduto.frame_adc.show()
listaAdc = []
sql1 = ("select * from adcBroto")
cursor.execute(sql1)
dados1 = cursor.fetchall()
sql2 = ("select * from adcSeis ")
cursor.execute(sql2)
dados2 = cursor.fetchall()
sql3 = ("select * from adcOito")
cursor.execute(sql3)
dados3 = cursor.fetchall()
sql4 = ("select * from adcDez")
cursor.execute(sql4)
dados4 = cursor.fetchall()
slq5 = ("select * from adcSem")
cursor.execute(slq5)
dados5 = cursor.fetchall()
for i, j, k, l in zip(dados1, dados2, dados3, dados4):
listaAdc.append(i)
listaAdc.append(j)
listaAdc.append(k)
listaAdc.append(l)
for m in dados5:
listaAdc.append(m)
telaProduto.tableWidget_cadastro_2.setRowCount(len(listaAdc))
telaProduto.tableWidget_cadastro_2.setColumnCount(4)
for i in range(0, len(listaAdc)):
for j in range(4):
telaProduto.tableWidget_cadastro_2.setItem(i, j, QtWidgets.QTableWidgetItem(str(listaAdc[i][j]))) |
"""
describe all supported datasets.
"""
DATASET_LSUN = 0x00010000
DATASET_LSUN_BEDROOM_TRAINING = DATASET_LSUN + 0x00000000
DATASET_LSUN_BEDROOM_VALIDATION = DATASET_LSUN + 0x00000001
DATASET_LSUN_BRIDGE_TRAINING = DATASET_LSUN + 0x00000002
DATASET_LSUN_BRIDGE_VALIDATION = DATASET_LSUN + 0x00000003
DATASET_LSUN_CHURCH_OUTDOOR_TRAINING = DATASET_LSUN + 0x00000004
DATASET_LSUN_CHURCH_OUTDOOR_VALIDATION = DATASET_LSUN + 0x00000005
DATASET_LSUN_CLASSROOM_TRAINING = DATASET_LSUN + 0x00000006
DATASET_LSUN_CLASSROOM_VALIDATION = DATASET_LSUN + 0x00000007
DATASET_LSUN_CONFERENCE_ROOM_TRAINING = DATASET_LSUN + 0x00000008
DATASET_LSUN_CONFERENCE_ROOM_VALIDATION = DATASET_LSUN + 0x00000009
DATASET_LSUN_DINING_ROOM_TRAINING = DATASET_LSUN + 0x0000000a
DATASET_LSUN_DINING_ROOM_VALIDATION = DATASET_LSUN + 0x0000000b
DATASET_LSUN_KITCHEN_TRAINING = DATASET_LSUN + 0x0000000c
DATASET_LSUN_KITCHEN_VALIDATION = DATASET_LSUN + 0x0000000d
DATASET_LSUN_LIVING_ROOM_TRAINING = DATASET_LSUN + 0x0000000e
DATASET_LSUN_LIVING_ROOM_VALIDATION = DATASET_LSUN + 0x0000000f
DATASET_LSUN_RESTAURANT_TRAINING = DATASET_LSUN + 0x00000010
DATASET_LSUN_RESTAURANT_VALIDATION = DATASET_LSUN + 0x00000011
DATASET_LSUN_TOWER_TRAINING = DATASET_LSUN + 0x00000012
DATASET_LSUN_TOWER_VALIDATION = DATASET_LSUN + 0x00000013
DATASET_LSUN_TEST = DATASET_LSUN + 0x00000014
DATASET_MNIST = 0x00020000
DATASET_MNIST_TRAINING = DATASET_MNIST + 0x00000000
DATASET_MNIST_TEST = DATASET_MNIST + 0x00000001
DATASET_CIFAR_10 = 0x00030000
DATASET_CIFAR_10_TRAINING = DATASET_CIFAR_10 + 0x00000000
DATASET_CIFAR_10_TEST = DATASET_CIFAR_10 + 0x00000001
DATASET_KAGGLE_MNIST = 0x00040000
DATASET_KAGGLE_MNIST_TRAINING = DATASET_KAGGLE_MNIST + 0x00000000
DATASET_KAGGLE_MNIST_TEST = DATASET_KAGGLE_MNIST + 0x00000001
LABEL_INVALID = -1
# https://github.com/fyu/lsun/blob/master/category_indices.txt
LABEL_LSUN_BEDROOM = 0
LABEL_LSUN_BRIDGE = 1
LABEL_LSUN_CHURCH_OUTDOOR = 2
LABEL_LSUN_CLASSROOM = 3
LABEL_LSUN_CONFERENCE_ROOM = 4
LABEL_LSUN_DINING_ROOM = 5
LABEL_LSUN_KITCHEN = 6
LABEL_LSUN_LIVING_ROOM = 7
LABEL_LSUN_RESTAURANT = 8
LABEL_LSUN_TOWER = 9
LABEL_MNIST_0 = 0
LABEL_MNIST_1 = 1
LABEL_MNIST_2 = 2
LABEL_MNIST_3 = 3
LABEL_MNIST_4 = 4
LABEL_MNIST_5 = 5
LABEL_MNIST_6 = 6
LABEL_MNIST_7 = 7
LABEL_MNIST_8 = 8
LABEL_MNIST_9 = 9
LABEL_KAGGLE_MNIST_0 = 0
LABEL_KAGGLE_MNIST_1 = 1
LABEL_KAGGLE_MNIST_2 = 2
LABEL_KAGGLE_MNIST_3 = 3
LABEL_KAGGLE_MNIST_4 = 4
LABEL_KAGGLE_MNIST_5 = 5
LABEL_KAGGLE_MNIST_6 = 6
LABEL_KAGGLE_MNIST_7 = 7
LABEL_KAGGLE_MNIST_8 = 8
LABEL_KAGGLE_MNIST_9 = 9
|
n1 = float(input('Primeiro número da subtraçâo:'))
n2 = float(input('Segundo número da subtraçâo:'))
n3 = float(input('Terceiro número da subtraçâo:'))
print('O resultado da subtraçâo é: {}'.format(n1 - n2 - n3))
|
#!/usr/bin/env pyrate
foo_obj = object_file('foo_obj', ['foo.cpp'], compiler_opts = '-O3')
executable('example07.bin', ['test.cpp', foo_obj])
|
#! /usr/bin/python
Ada, C, GUI, SIMULINK, VHDL, OG, RTDS, SYSTEM_C, SCADE6, VDM, CPP = range(11)
thread, passive, unknown = range(3)
PI, RI = range(2)
synch, asynch = range(2)
param_in, param_out = range(2)
UPER, NATIVE, ACN = range(3)
cyclic, sporadic, variator, protected, unprotected = range(5)
enumerated, sequenceof, sequence, set, setof, integer, boolean, real, choice, octetstring, string = range(11)
functions = {}
functions['joystickdriver'] = {
'name_with_case' : 'JoystickDriver',
'runtime_nature': thread,
'language': OG,
'zipfile': '',
'interfaces': {},
'functional_states' : {}
}
functions['joystickdriver']['interfaces']['step'] = {
'port_name': 'step',
'parent_fv': 'joystickdriver',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': cyclic,
'period': 100,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['joystickdriver']['interfaces']['step']['paramsInOrdered'] = []
functions['joystickdriver']['interfaces']['step']['paramsOutOrdered'] = []
functions['joystickdriver']['interfaces']['cmd'] = {
'port_name': 'cmd',
'parent_fv': 'joystickdriver',
'direction': RI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 0,
'wcet_low': 0,
'wcet_low_unit': '',
'wcet_high': 0,
'wcet_high_unit': '',
'distant_fv': 'cmddispatcher',
'calling_threads': {},
'distant_name': 'cmd',
'queue_size': 1
}
functions['joystickdriver']['interfaces']['cmd']['paramsInOrdered'] = ['cmd_val']
functions['joystickdriver']['interfaces']['cmd']['paramsOutOrdered'] = []
functions['joystickdriver']['interfaces']['cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'cmd',
'param_direction': param_in
}
functions['cmddispatcher'] = {
'name_with_case' : 'CmdDispatcher',
'runtime_nature': thread,
'language': OG,
'zipfile': '',
'interfaces': {},
'functional_states' : {}
}
functions['cmddispatcher']['interfaces']['cmd'] = {
'port_name': 'cmd',
'parent_fv': 'cmddispatcher',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 10,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['cmddispatcher']['interfaces']['cmd']['paramsInOrdered'] = ['cmd_val']
functions['cmddispatcher']['interfaces']['cmd']['paramsOutOrdered'] = []
functions['cmddispatcher']['interfaces']['cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'cmd',
'param_direction': param_in
}
functions['cmddispatcher']['interfaces']['log_cmd'] = {
'port_name': 'log_cmd',
'parent_fv': 'cmddispatcher',
'direction': RI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 0,
'wcet_low': 0,
'wcet_low_unit': '',
'wcet_high': 0,
'wcet_high_unit': '',
'distant_fv': 'logger',
'calling_threads': {},
'distant_name': 'log_cmd',
'queue_size': 1
}
functions['cmddispatcher']['interfaces']['log_cmd']['paramsInOrdered'] = ['cmd_val']
functions['cmddispatcher']['interfaces']['log_cmd']['paramsOutOrdered'] = []
functions['cmddispatcher']['interfaces']['log_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'log_cmd',
'param_direction': param_in
}
functions['cmddispatcher']['interfaces']['test_cmd'] = {
'port_name': 'test_cmd',
'parent_fv': 'cmddispatcher',
'direction': RI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 0,
'wcet_low': 0,
'wcet_low_unit': '',
'wcet_high': 0,
'wcet_high_unit': '',
'distant_fv': 'watchdog',
'calling_threads': {},
'distant_name': 'test_cmd',
'queue_size': 1
}
functions['cmddispatcher']['interfaces']['test_cmd']['paramsInOrdered'] = ['cmd_val']
functions['cmddispatcher']['interfaces']['test_cmd']['paramsOutOrdered'] = []
functions['cmddispatcher']['interfaces']['test_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'test_cmd',
'param_direction': param_in
}
functions['watchdog'] = {
'name_with_case' : 'Watchdog',
'runtime_nature': thread,
'language': CPP,
'zipfile': '',
'interfaces': {},
'functional_states' : {}
}
functions['watchdog']['interfaces']['test_cmd'] = {
'port_name': 'test_cmd',
'parent_fv': 'watchdog',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 10,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['watchdog']['interfaces']['test_cmd']['paramsInOrdered'] = ['cmd_val']
functions['watchdog']['interfaces']['test_cmd']['paramsOutOrdered'] = []
functions['watchdog']['interfaces']['test_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'test_cmd',
'param_direction': param_in
}
functions['watchdog']['interfaces']['purge'] = {
'port_name': 'purge',
'parent_fv': 'watchdog',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': cyclic,
'period': 80,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['watchdog']['interfaces']['purge']['paramsInOrdered'] = []
functions['watchdog']['interfaces']['purge']['paramsOutOrdered'] = []
functions['watchdog']['interfaces']['mot_cmd'] = {
'port_name': 'mot_cmd',
'parent_fv': 'watchdog',
'direction': RI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 0,
'wcet_low': 0,
'wcet_low_unit': '',
'wcet_high': 0,
'wcet_high_unit': '',
'distant_fv': 'blsclient',
'calling_threads': {},
'distant_name': 'mot_cmd',
'queue_size': 1
}
functions['watchdog']['interfaces']['mot_cmd']['paramsInOrdered'] = ['cmd_val']
functions['watchdog']['interfaces']['mot_cmd']['paramsOutOrdered'] = []
functions['watchdog']['interfaces']['mot_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'mot_cmd',
'param_direction': param_in
}
functions['logger'] = {
'name_with_case' : 'Logger',
'runtime_nature': thread,
'language': OG,
'zipfile': '',
'interfaces': {},
'functional_states' : {}
}
functions['logger']['interfaces']['log_cmd'] = {
'port_name': 'log_cmd',
'parent_fv': 'logger',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 10,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['logger']['interfaces']['log_cmd']['paramsInOrdered'] = ['cmd_val']
functions['logger']['interfaces']['log_cmd']['paramsOutOrdered'] = []
functions['logger']['interfaces']['log_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'log_cmd',
'param_direction': param_in
}
functions['blsclient'] = {
'name_with_case' : 'BLSClient',
'runtime_nature': thread,
'language': OG,
'zipfile': '',
'interfaces': {},
'functional_states' : {}
}
functions['blsclient']['interfaces']['mot_cmd'] = {
'port_name': 'mot_cmd',
'parent_fv': 'blsclient',
'direction': PI,
'in': {},
'out': {},
'synchronism': asynch,
'rcm': sporadic,
'period': 10,
'wcet_low': 0,
'wcet_low_unit': 'ms',
'wcet_high': 10,
'wcet_high_unit': 'ms',
'distant_fv': '',
'calling_threads': {},
'distant_name': '',
'queue_size': 1
}
functions['blsclient']['interfaces']['mot_cmd']['paramsInOrdered'] = ['cmd_val']
functions['blsclient']['interfaces']['mot_cmd']['paramsOutOrdered'] = []
functions['blsclient']['interfaces']['mot_cmd']['in']['cmd_val'] = {
'type': 'Base_commands_Motion2D',
'asn1_module': 'Base_Types',
'basic_type': sequence,
'asn1_filename': '/home/taste/esrocos_workspace/tutorial_integration_bip/dataview-uniq.asn',
'encoding': NATIVE,
'interface': 'mot_cmd',
'param_direction': param_in
}
|
# Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
PYTHON_VERSION_COMPATIBILITY = 'PY2+3'
DEPS = [
'futures',
'step',
]
def RunSteps(api):
futures = []
for i in range(10):
def _runner(i):
api.step(
'sleep loop [%d]' % (i+1),
['python3', '-u', api.resource('sleep_loop.py'), i],
cost=api.step.ResourceCost(),
)
return i + 1
futures.append(api.futures.spawn(_runner, i))
for helper in api.futures.iwait(futures):
api.step('Sleeper %d complete' % helper.result(), cmd=None)
def GenTests(api):
yield api.test('basic')
|
"""
hello module
"""
__version__ = '0.7.0dev'
|
'''Defines the `google_java_format_toolchain` rule.
'''
GoogleJavaFormatToolchainInfo = provider(
fields = {
"google_java_format_deploy_jar": "A JAR `File` containing Google Java Format and all of its run-time dependencies.",
"colordiff_executable": "A `File` pointing to `colordiff` executable (in the host configuration)."
},
)
def _google_java_format_toolchain_impl(ctx):
toolchain_info = platform_common.ToolchainInfo(
google_java_format_toolchain_info = GoogleJavaFormatToolchainInfo(
google_java_format_deploy_jar = ctx.file.google_java_format_deploy_jar,
colordiff_executable = ctx.file.colordiff_executable,
),
)
return [toolchain_info]
google_java_format_toolchain = rule(
implementation = _google_java_format_toolchain_impl,
attrs = {
"google_java_format_deploy_jar": attr.label(
allow_single_file = True,
mandatory = True,
executable = True,
cfg = "host",
),
"colordiff_executable": attr.label(
allow_single_file = True,
mandatory = True,
executable = True,
cfg = "host",
),
},
)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = """
---
module: lilatomic.api.http
short_description: A nice and friendly HTTP API
description:
- An easy way to use the [requests](https://docs.python-requests.org/en/master/) library to make HTTP requests
- Define connections and re-use them across tasks
version_added: "0.1.0"
options:
connection:
description: the name of the connection to use
required: true
type: string
method:
description: the HTTP method to use
required: true
default: GET
type: string
path:
description: the slug to join to the connection's base
data:
description: object to send in the body of the request.
required: false
type: string or dict
json:
description: json data to send in the body of the request.
required: false
type: string or dict
headers:
description: HTTP headers for the request
required: false
type: dict
default: dict()
status_code:
description: acceptable status codes
required: false
default: requests default, status_code < 400
type: list
elements: int
timeout:
description: timeout in seconds of the request
required: false
default: 15
type: float
log_request:
description: returns information about the request. Useful for debugging. Censors Authorization header unless log_auth is used.
required: false
default: false
type: bool
log_auth:
description: uncensors the Authorization header.
required: false
default: false
type: bool
kwargs:
description: Access hatch for passing kwargs to the requests.request method. Recursively merged with and overrides kwargs set on the connection.
required: false
default: None
type: dict
"""
EXAMPLES = """
---
- name: post
lilatomic.api.http:
connection: httpbin
method: POST
path: /post
data:
1: 1
2: 2
vars:
lilatomic_api_http:
httpbin:
base: "https://httpbingo.org/"
- name: GET with logging of the request
lilatomic.api.http:
connection: fishbike
path: /
log_request: true
vars:
lilatomic_api_http:
httpbin:
base: "https://httpbingo.org/"
- name: GET with Bearer auth
lilatomic.api.http:
connection: httpbin_bearer
path: /bearer
log_request: true
log_auth: true
vars:
lilatomic_api_http:
httpbin_bearer:
base: "https://httpbin.org"
auth:
method: bearer
token: hihello
- name: Use Kwargs for disallowing redirects
lilatomic.api.http:
connection: httpbin
path: redirect-to?url=get
kwargs:
allow_redirects: false
status_code: [ 302 ]
vars:
lilatomic_api_http:
httpbin:
base: "https://httpbingo.org/"
"""
RETURN = """
---
json:
description: json body
returned: response has headers Content-Type == "application/json"
type: complex
sample: {
"authenticated": true,
"token": "hihello"
}
content:
description: response.content
returned: always
type: str
sample: |
{\\n "authenticated": true, \\n "token": "hihello"\\n}\\n
msg:
description: response body
returned: always
type: str
sample: |
{\\n "authenticated": true, \\n "token": "hihello"\\n}\\n
content-length:
description: response Content-Length header
returned: always
type: int
sample: 51
content-type:
description: response Content-Type header
returned: always
type: string
sample: "application/json"
cookies:
description: the cookies from the response
returned: always
type: dict
sample: { }
date:
description: response Date header
returned: always
type: str
sample: "Sat, 10 Jul 2021 23:14:14 GMT"
elapsed:
description: seconds elapsed making the request
returned: always
type: int
sample: 0
redirected:
description: if response was redirected
returned: always
type: bool
sample: false
server:
description: response Server header
returned: always
type: str
sample: "gunicorn/19.9.0"
status:
description: response status code; alias for status_code
returned: always
type: str
sample: 200
url:
description: the URL from the response
returned: always
type: str
sample: "https://httpbin.org/bearer"
encoding:
description: response encoding
returned: always
type: str
sample: "utf-8"
headers:
description: response headers
returned: always
type: dict
elements: str
sample: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"Connection": "keep-alive",
"Content-Length": "51",
"Content-Type": "application/json",
"Date": "Sat, 10 Jul 2021 23:14:14 GMT",
"Server": "gunicorn/19.9.0"
}
reason:
description: response status reason
returned: always
type: str
sample: "OK"
status_code:
description: response status code
returned: always
type: str
sample: 200
request:
description: the original request, useful for debugging
returned: when log_request == true
type: complex
contains:
body:
description: request body
returned: always
type: str
headers:
description: request headers. Authorization will be censored unless `log_auth` == true
returned: always
type: dict
elements: str
method:
description: request HTTP method
returned: always
type: str
path_url:
description: request path url; the part of the url which is called the path; that's its technical name
returned: always
type: str
url:
description: the full url
returned: always
type: str
sample: {
"body": null,
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Bearer hihello",
"Connection": "keep-alive",
"User-Agent": "python-requests/2.25.1"
},
"method": "GET",
"path_url": "/bearer",
"url": "https://httpbin.org/bearer"
}
""" |
def getScore(savings, monthly, bills, cost, payDay):
score = 0
if cost > savings:
score = 0
elif savings < 1000:
score = savings/pow(cost,1.1)
else:
a = savings/(cost*1.1)
score += (1300*(monthly-bills))/(max(1,a)*pow(cost,1.1)*pow(payDay,0.8)) + (30*savings)/(pow(cost,1.1))
score = round(score/100,2)
if score > 10:
score = 9.99
return score
'''
while True:
savings = int(input("savings"))
monthly = int(input("monthly"))
bills = int(input("bills per month"))
cost = int(input("cost"))
payDay = int(input("days until next pay")) #days until next payday
print(getScore(savings, monthly, bills, cost, payDay))
#score += ((monthly - bills)/(max(1,(pow(a,1.5))*1.2))/cost)*(700/payDay)
#score = (4840*monthly)/(savings*pow(payDay,0.8)*pow(cost,0.1)) + (70*savings) / (cost*1.1)
'''
|
#!/usr/bin/env python
# Copyright 2017 The Forseti Security 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.
'''Test instances data.'''
FAKE_API_RESPONSE1 = [
{
'kind': 'compute#instance',
'id': '6440513679799924564',
'creationTimestamp': '2017-05-26T22:08:11.094-07:00',
'name': 'iap-ig-79bj',
'tags': {
'items': [
'iap-tag'
],
'fingerprint': 'gilEhx3hEXk='
},
'machineType': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/machineTypes/f1-micro',
'status': 'RUNNING',
'zone': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c',
'canIpForward': False,
'networkInterfaces': [
{
'kind': 'compute#networkInterface',
'network': 'https://www.googleapis.com/compute/v1/projects/project1/global/networks/default',
'subnetwork': 'https://www.googleapis.com/compute/v1/projects/project1/regions/us-central1/subnetworks/default',
'networkIP': '10.128.0.2',
'name': 'nic0',
'accessConfigs': [
{
'kind': 'compute#accessConfig',
'type': 'ONE_TO_ONE_NAT',
'name': 'External NAT',
'natIP': '104.198.131.130'
}
]
}
],
'disks': [
{
'kind': 'compute#attachedDisk',
'type': 'PERSISTENT',
'mode': 'READ_WRITE',
'source': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/disks/iap-ig-79bj',
'deviceName': 'iap-it-1',
'index': 0,
'boot': True,
'autoDelete': True,
'licenses': [
'https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-8-jessie'
],
'interface': 'SCSI'
}
],
'metadata': {
'kind': 'compute#metadata',
'fingerprint': '3MpZMMvDTyo=',
'items': [
{
'key': 'instance-template',
'value': 'projects/600687511243/global/instanceTemplates/iap-it-1'
},
{
'key': 'created-by',
'value': 'projects/600687511243/zones/us-central1-c/instanceGroupManagers/iap-ig'
}
]
},
'serviceAccounts': [
{
'email': '600687511243-compute@developer.gserviceaccount.com',
'scopes': [
'https://www.googleapis.com/auth/devstorage.read_only',
'https://www.googleapis.com/auth/logging.write',
'https://www.googleapis.com/auth/monitoring.write',
'https://www.googleapis.com/auth/servicecontrol',
'https://www.googleapis.com/auth/service.management.readonly',
'https://www.googleapis.com/auth/trace.append'
]
}
],
'selfLink': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/instances/iap-ig-79bj',
'scheduling': {
'onHostMaintenance': 'MIGRATE',
'automaticRestart': True,
'preemptible': False
},
'cpuPlatform': 'Intel Haswell'
}
]
FAKE_API_RESPONSE2 = []
FAKE_PROJECT_INSTANCES_MAP = {
'project1': [
{
'kind': 'compute#instance',
'id': '6440513679799924564',
'creationTimestamp': '2017-05-26T22:08:11.094-07:00',
'name': 'iap-ig-79bj',
'tags': {
'items': [
'iap-tag'
],
'fingerprint': 'gilEhx3hEXk='
},
'machineType': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/machineTypes/f1-micro',
'status': 'RUNNING',
'zone': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c',
'canIpForward': False,
'networkInterfaces': [
{
'kind': 'compute#networkInterface',
'network': 'https://www.googleapis.com/compute/v1/projects/project1/global/networks/default',
'subnetwork': 'https://www.googleapis.com/compute/v1/projects/project1/regions/us-central1/subnetworks/default',
'networkIP': '10.128.0.2',
'name': 'nic0',
'accessConfigs': [
{
'kind': 'compute#accessConfig',
'type': 'ONE_TO_ONE_NAT',
'name': 'External NAT',
'natIP': '104.198.131.130'
}
]
}
],
'disks': [
{
'kind': 'compute#attachedDisk',
'type': 'PERSISTENT',
'mode': 'READ_WRITE',
'source': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/disks/iap-ig-79bj',
'deviceName': 'iap-it-1',
'index': 0,
'boot': True,
'autoDelete': True,
'licenses': [
'https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-8-jessie'
],
'interface': 'SCSI'
}
],
'metadata': {
'kind': 'compute#metadata',
'fingerprint': '3MpZMMvDTyo=',
'items': [
{
'key': 'instance-template',
'value': 'projects/600687511243/global/instanceTemplates/iap-it-1'
},
{
'key': 'created-by',
'value': 'projects/600687511243/zones/us-central1-c/instanceGroupManagers/iap-ig'
}
]
},
'serviceAccounts': [
{
'email': '600687511243-compute@developer.gserviceaccount.com',
'scopes': [
'https://www.googleapis.com/auth/devstorage.read_only',
'https://www.googleapis.com/auth/logging.write',
'https://www.googleapis.com/auth/monitoring.write',
'https://www.googleapis.com/auth/servicecontrol',
'https://www.googleapis.com/auth/service.management.readonly',
'https://www.googleapis.com/auth/trace.append'
]
}
],
'selfLink': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/instances/iap-ig-79bj',
'scheduling': {
'onHostMaintenance': 'MIGRATE',
'automaticRestart': True,
'preemptible': False
},
'cpuPlatform': 'Intel Haswell'
}
],
}
EXPECTED_LOADABLE_INSTANCES = [
{
'can_ip_forward': False,
'cpu_platform': 'Intel Haswell',
'creation_timestamp': '2017-05-26 22:08:11',
'description': None,
'disks': '[{"source": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/disks/iap-ig-79bj", "kind": "compute#attachedDisk", "mode": "READ_WRITE", "autoDelete": true, "deviceName": "iap-it-1", "licenses": ["https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-8-jessie"], "index": 0, "interface": "SCSI", "boot": true, "type": "PERSISTENT"}]',
'id': '6440513679799924564',
'machine_type': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/machineTypes/f1-micro',
'metadata': '{"items": [{"value": "projects/600687511243/global/instanceTemplates/iap-it-1", "key": "instance-template"}, {"value": "projects/600687511243/zones/us-central1-c/instanceGroupManagers/iap-ig", "key": "created-by"}], "kind": "compute#metadata", "fingerprint": "3MpZMMvDTyo="}',
'name': 'iap-ig-79bj',
'network_interfaces': '[{"kind": "compute#networkInterface", "network": "https://www.googleapis.com/compute/v1/projects/project1/global/networks/default", "accessConfigs": [{"kind": "compute#accessConfig", "type": "ONE_TO_ONE_NAT", "name": "External NAT", "natIP": "104.198.131.130"}], "networkIP": "10.128.0.2", "subnetwork": "https://www.googleapis.com/compute/v1/projects/project1/regions/us-central1/subnetworks/default", "name": "nic0"}]',
'project_id': 'project1',
'scheduling': '{"automaticRestart": true, "preemptible": false, "onHostMaintenance": "MIGRATE"}',
'service_accounts': '[{"scopes": ["https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring.write", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append"], "email": "600687511243-compute@developer.gserviceaccount.com"}]',
'status': 'RUNNING',
'status_message': None,
'tags': '{"items": ["iap-tag"], "fingerprint": "gilEhx3hEXk="}',
'zone': 'https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c',
'raw_instance': '{"status": "RUNNING", "cpuPlatform": "Intel Haswell", "kind": "compute#instance", "machineType": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/machineTypes/f1-micro", "name": "iap-ig-79bj", "zone": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c", "tags": {"items": ["iap-tag"], "fingerprint": "gilEhx3hEXk="}, "disks": [{"source": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/disks/iap-ig-79bj", "kind": "compute#attachedDisk", "mode": "READ_WRITE", "autoDelete": true, "deviceName": "iap-it-1", "licenses": ["https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-8-jessie"], "index": 0, "interface": "SCSI", "boot": true, "type": "PERSISTENT"}], "scheduling": {"automaticRestart": true, "preemptible": false, "onHostMaintenance": "MIGRATE"}, "canIpForward": false, "serviceAccounts": [{"scopes": ["https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring.write", "https://www.googleapis.com/auth/servicecontrol", "https://www.googleapis.com/auth/service.management.readonly", "https://www.googleapis.com/auth/trace.append"], "email": "600687511243-compute@developer.gserviceaccount.com"}], "metadata": {"items": [{"value": "projects/600687511243/global/instanceTemplates/iap-it-1", "key": "instance-template"}, {"value": "projects/600687511243/zones/us-central1-c/instanceGroupManagers/iap-ig", "key": "created-by"}], "kind": "compute#metadata", "fingerprint": "3MpZMMvDTyo="}, "creationTimestamp": "2017-05-26T22:08:11.094-07:00", "id": "6440513679799924564", "selfLink": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-c/instances/iap-ig-79bj", "networkInterfaces": [{"kind": "compute#networkInterface", "network": "https://www.googleapis.com/compute/v1/projects/project1/global/networks/default", "accessConfigs": [{"kind": "compute#accessConfig", "type": "ONE_TO_ONE_NAT", "name": "External NAT", "natIP": "104.198.131.130"}], "networkIP": "10.128.0.2", "subnetwork": "https://www.googleapis.com/compute/v1/projects/project1/regions/us-central1/subnetworks/default", "name": "nic0"}]}',
}
]
|
# coding: utf-8
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
# Module current version
version_major = 0
version_minor = 0
version_micro = 5
# Expected by setup.py: string of form "X.Y.Z"
__version__ = "{0}.{1}.{2}".format(version_major, version_minor, version_micro)
# Expected by setup.py: the status of the project
CLASSIFIERS = ["Development Status :: 1 - Planning",
"Environment :: Console",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering"]
# Project descriptions
description = """
pycaravel: Python package that enables you to parse various source of data.
"""
SUMMARY = """
.. container:: summary-carousel
pycaravel is a Python module for **data searching** that offers:
* a common API for parsing multiple source of data (BIDS, CubicWeb, ...).
* a common API to search in those datasets.
* some utilities to load the retrived data.
"""
long_description = (
"This module has been created to simplify the search of datasets in "
"a BIDS directory or a CubicWeb instance.")
# Main setup parameters
NAME = "pycaravel"
ORGANISATION = "CEA"
MAINTAINER = "Antoine Grigis"
MAINTAINER_EMAIL = "antoine.grigis@cea.fr"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
EXTRANAME = "NeuroSpin webPage"
EXTRAURL = "http://joliot.cea.fr/drf/joliot/Pages/Entites_de_recherche/NeuroSpin.aspx"
URL = "https://github.com/neurospin/pycaravel"
DOWNLOAD_URL = "https://github.com/neurospin/pycaravel"
LICENSE = "CeCILL-B"
CLASSIFIERS = CLASSIFIERS
AUTHOR = """
Antoine Grigis <antoine.grigis@cea.fr>
"""
AUTHOR_EMAIL = "antoine.grigis@cea.fr"
PLATFORMS = "Linux,OSX"
ISRELEASE = True
VERSION = __version__
PROVIDES = ["caravel"]
REQUIRES = [
"pandas>=0.19.2",
"grabbit>=0.2.5",
"nibabel>=2.3.1",
"cwbrowser>=2.2.1",
"numpy>=1.11.0",
"imageio"
]
EXTRA_REQUIRES = {}
|
s=input("Enter string: ")
word=s.split()
word=list(reversed(word))
print("OUTPUT: ",end="")
print(" ".join(word)) |
# encoding: utf-8
__author__ = "Patrick Lampe"
__email__ = "uni at lampep.de"
class Point:
def __init__(self, id, location):
self.id = id
self.location = location
def getId(self):
return self.id
def get_distance_in_m(self, snd_node):
return self.get_distance_in_km(snd_node) * 1000
def get_distance_in_km(self, snd_node):
return self.location.get_distance_in_km(snd_node.location)
def get_heading(self, snd_node):
return self.location.get_heading(snd_node.location)
def get_lat(self):
return self.location.get_lat_lon().to_string()[0]
def get_lon(self):
return self.location.get_lat_lon().to_string()[1]
|
# x_8_6
#
#
result = 70
if 0 <= result <= 40:
print('追試です')
elif 40 < result <= 60:
print('頑張りましょう')
elif 60 < result <= 80:
print('まずまずです')
elif 85 < result <= 100:
print('よくできました')
|
"""
Error and Exceptions in the SciTokens library
"""
class MissingKeyException(Exception):
"""
No private key is present.
The SciToken required the use of a public or private key, but
it was not provided by the caller.
"""
pass
class UnsupportedKeyException(Exception):
"""
Key is present but is of an unsupported format.
A public or private key was provided to the SciToken, but
could not be handled by this library.
"""
pass
class MissingIssuerException(Exception):
"""
Missing the issuer in the SciToken, unable to verify token
"""
pass
class NonHTTPSIssuer(Exception):
"""
Non HTTPs issuer, as required by draft-ietf-oauth-discovery-07
https://tools.ietf.org/html/draft-ietf-oauth-discovery-07
"""
pass
class InvalidTokenFormat(Exception):
"""
Encoded token has an invalid format.
"""
pass
class UnableToCreateCache(Exception):
"""
Unable to make the KeyCache
"""
|
# Given a linked list, remove the n-th node from the end of list and return its head.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int):
# maintaining dummy to resolve edge cases
dummy = ListNode(0)
dummy.next = head
# this is a two pointer technique.
# Here we will be advancing one of the pointer to the n number of nodes and then advancing them equally
prevPtr, nextPtr = dummy, dummy
for i in range(n+1):
nextPtr = nextPtr.next
while nextPtr:
prevPtr = prevPtr.next
nextPtr = nextPtr.next
prevPtr.next = prevPtr.next.next
return dummy.next
if __name__ == "__main__":
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
head = Solution().removeNthFromEnd(a, 2)
while head:
print(head.val)
head = head.next
|
def write_data_to_es():
df = update_preprocessing_data()
try:
# df 출력 스키마대로 뽑기
df = df[['timestamp', 'hostname', 'program', 'pid', 'path', 'message', 'score', 'is_anomaly']]
df['timestamp'] = pd.to_datetime(df['timestamp'])
# df['timestamp'] = datetime.datetime.strptime(df['timestamp'], '%Y-%m-%d %H:%M:%S')
except Exception as ex:
print('출력 스키마 형태 구 실패 : ', ex)
# spark dataframe 변경성
try:
spark_df = spark_sess.createDataFrame(data=df)
except Exception as ex:
print('spark dataframe 변경 실패 : ', ex)
try:
# schema 형식 맞추기
spark_df = spark_df.withColumn('score',spark_df['score'].cast("float").alias('score'))
spark_df = spark_df.withColumn('pid', spark_df['pid'].cast("float").alias('pid'))
spark_df = spark_df.withColumn("is_anomaly", when(F.col("is_anomaly") == -1, 'True').otherwise(F.col('is_anomaly')))
spark_df = spark_df.withColumn("is_anomaly", when(F.col("is_anomaly") == 1, 'False').otherwise(F.col('is_anomaly')))
spark_df = spark_df.withColumn("is_anomaly", F.col("is_anomaly").cast('boolean'))
# host를 위한 처리
final_df = spark_df.withColumnRenamed('hostname', 'host.hostname') \
.withColumn('pid', F.when(F.isnan(F.col('pid')), None).otherwise(F.col('pid')))
#final_df.printschema()
print('shcema change success')
except Exception as ex:
print('spark schema 형식 맞춤 실패 : ', ex)
try:
# es 데이터 삽입
now = datetime.datetime.now()
date = now.strftime('%Y.%m.%d')
spark.save_to_es(final_df, 'sym-anomaly-log-{}'.format(date))
print('data save')
except Exception as ex:
print('ES 데이터 적재 실패 : ', ex)
if __name__ == '__main__':
write_data_to_es()
|
def bmi_calculator(weight, height):
'''
Function calculates bmi according to passed arguments
weight (int or float) = weight of the person; ex: 61 or 61.0 kg
height (float) = height of the person, in meter; ex: 1.7 m
'''
bmi = weight / (height**2)
return bmi |
class VertexWeightProximityModifier:
falloff_type = None
mask_constant = None
mask_tex_map_object = None
mask_tex_mapping = None
mask_tex_use_channel = None
mask_tex_uv_layer = None
mask_texture = None
mask_vertex_group = None
max_dist = None
min_dist = None
proximity_geometry = None
proximity_mode = None
target = None
vertex_group = None
|
class Solution:
def trimMean(self, arr: List[int]) -> float:
count = int(len(arr) * 0.05)
arr = sorted(arr)[count:-count]
return sum(arr) / len(arr)
|
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
row = []
for i in range(rowIndex+1):
n = i+1
tmp = [1]*n
for j in range(1, n-1):
tmp[j] = row[j-1] + row[j]
row = tmp
return row
|
def get_twos_sum(result, arr):
i, k = 0, len(arr) - 1
while i < k:
a, b = arr[i], arr[k]
res = a + b
if res == result:
return (a, b)
elif res < result:
i += 1
else:
k -= 1
def get_threes_sum(result, arr):
arr.sort()
for i in range(len(arr)):
c = arr[i]
if c > result:
continue
twos = get_twos_sum(result - c, arr[:i] + arr[i+1:])
if twos:
return True
return get_twos_sum(result, arr)
# Tests
assert get_threes_sum(49, [20, 303, 3, 4, 25])
assert not get_threes_sum(50, [20, 303, 3, 4, 25])
|
# Skill: Bitwise XOR
#Given an array of integers, arr, where all numbers occur twice except one number which occurs once, find the number. Your solution should ideally be O(n) time and use constant extra space.
#Example:
#Input: arr = [7, 3, 5, 5, 4, 3, 4, 8, 8]
#Output: 7
#Analysis
# Exploit the question of all numbers occurs twice except one number
# we use chain of bitwise operator XOR to "zero" the duplicate
# With XOR property, it allow single occur number remain
# Example:
# 1 ^ 3 ^ 5 ^ 1 ^ 5 = 3
# Time complexity O(N) space complexity O(1)
class Solution(object):
def findSingle(self, nums):
# Fill this in.
tmp = 0
for n in nums:
tmp = tmp ^ n
return tmp
if __name__ == "__main__":
nums = [1, 1, 3, 4, 4, 5, 6, 5, 6]
print(Solution().findSingle(nums))
# 3 |
email = input("What is your email id ").strip()
user_name = email[:email.index('@')]
domain_name = email[email.index('@')+1:]
result = "Your username is '{}' and your domain is '{}'".format(user_name, domain_name)
print(result)
|
def step(part, instruction, pos, dir):
c, n = instruction
if c in "FNEWS":
change = {"N": 1j, "E": 1, "W": -1, "S": -1j, "F": dir}[c] * n
if c == "F" or part == 1:
return pos + change, dir
else:
return pos, dir + change
else:
return pos, dir * (1j - 2j * (c == "R")) ** (n // 90)
def dist_to_endpoint(part, steps, pos, dir):
if not steps:
return int(abs(pos.real) + abs(pos.imag))
return dist_to_endpoint(part, steps[1:], *step(part, steps[0], pos, dir))
with open("input.txt") as f:
instructions = [(line[0], int(line[1:])) for line in f]
print("Part 1:", dist_to_endpoint(part=1, steps=instructions, pos=0, dir=1))
print("Part 2:", dist_to_endpoint(part=2, steps=instructions, pos=0, dir=10 + 1j))
|
#!/usr/bin/env python
# coding: utf-8
def mi_funcion():
print("una funcion")
class MiClase:
def __init__(self):
print ("una clase")
print ("un modulo") |
# url 数据去重
class DistinctPipeline(object):
def __init__(self):
#set为集合,集合为数据不重复无排序的
self.existedUrls = set()
def is_similar(self, sourceUrl, targetUrl):
'''
判断两个 Url 是否相似,如果相似则忽略,否则保留
'''
pass
def process_item(self, url):
# 如果数据已经存在,则返回 False,忽略
if url in self.existedUrls:
return False
# 不存在时,就添加数据
self.existedUrls.add(url)
return True
|
NON_RELATION_TAG = "NonRel"
BRAT_REL_TEMPLATE = "R{}\t{} Arg1:{} Arg2:{}"
EN1_START = "[s1]"
EN1_END = "[e1]"
EN2_START = "[s2]"
EN2_END = "[e2]"
SPEC_TAGS = [EN1_START, EN1_END, EN2_START, EN2_END] |
class InvalidEpubException(Exception):
'''Exception class to hold errors that occur during processing of an ePub file'''
archive = None
def __init__(self, *args, **kwargs):
if 'archive' in kwargs:
self.archive = kwargs['archive']
super(InvalidEpubException, self).__init__(*args)
|
S = input()
if S == 'RRR':
print(3)
elif S.find('RR') != -1:
print(2)
elif S == 'SSS':
print(0)
else:
print(1) |
class SpecialOffer:
""" Represents a special offer that can be done by a supermarket.
Attributes:
count(int): number of items needed to perform the special offer.
price(int): new price for the count of items.
free_item(<StockKeepingUnit>): the special offer instead of a different price offers a free item.
"""
def __init__(self, count, price, free_item):
self.count = count
self.price = price
self.free_item = free_item
|
#Dette er det Første Kapitelet i boken
WIDTH = 800
HEIGHT = 600
player_x = 600
player_y = 350
def draw():
screen.blit(images.backdrop, (0, 0))
screen.blit(images.mars, (50, 50))
screen.blit(images.astronaut, (player_x, player_y))
screen.blit(images.ship, (550, 300))
def game_loop():
global player_x, player_y
if keyboard.right:
player_x += 10
elif keyboard.left:
player_x -= 10
elif keyboard.up:
player_y -= 10
elif keyboard.down:
player_y += 10
clock.schedule_interval(game_loop, 0.03)
take_off_checklist = ["Put on suit",
"seal hatch",
"Check cabin pressure",
"fasten seatbelt"]
take_off_checklist.append("Tell Mission Control checks are complete")
take_off_checklist.remove("seal hatch")
take_off_checklist.insert(1, "seal hatch")
take_off_checklist[3] = "Take A Selfie"
take_off_checklist[3] = "Fasten Seatbelt"
del take_off_checklist[2]
spacewalk_checklist = [ "Put On Suit" ,
"Check Oxygen",
"Seal Helmet",
"Test Radio",
"Open airlock"]
skills_list = take_off_checklist + spacewalk_checklist
pr_list = ["Taking a Selfie",
"Delivering lectures",
"Doing TV inerviews",
"Meeting the public"]
skills_list += pr_list
print(skills_list)
#Making Map
room_map = [ [1, 0, 0, 0, 0],
[0, 0, 0, 2, 0],
[0, 0, 0, 0, 0],
[0, 3, 0, 0, 0],
[0, 0, 0, 0, 4]
]
print(room_map[3][1])
room_map[0][0] = 5
print(room_map) |
"""
Wrappers for the `torch.nn.Module` class, and can be used to parameterize policy
functions, value functions, cost functions, etc. for use in reinforcement
learning and imitation learning algorithms.
To create a custom network, see `BaseNetwork` for more details.
""" |
# These are the compilation flags that will be used in case there's no
# compilation database set.
flags = [
'-Wall',
'-Wextra',
'-std=c++14',
'-stdlib=libc++',
'-x', 'c++',
'-I', '.',
'-I', 'include',
'-isystem', '/usr/include/c++/v1',
'-isystem', '/usr/include'
]
def FlagsForFile(filename):
return {
'flags': flags,
'do_cache': True
}
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2016 Anler Hernández <hello@anler.me>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def attach_members(queryset, as_field="members_attr"):
"""Attach a json members representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the members as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(row_to_json(t))
FROM (
SELECT users_user.id,
users_user.username,
users_user.full_name,
users_user.email,
concat(full_name, username) complete_user_name,
users_user.color,
users_user.photo,
users_user.is_active,
users_role.id "role",
users_role.name role_name
FROM projects_membership
LEFT JOIN users_user ON projects_membership.user_id = users_user.id
LEFT JOIN users_role ON users_role.id = projects_membership.role_id
WHERE projects_membership.project_id = {tbl}.id
ORDER BY complete_user_name
) t
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_milestones(queryset, as_field="milestones_attr"):
"""Attach a json milestons representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the milestones as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(row_to_json(t))
FROM (
SELECT milestones_milestone.id,
milestones_milestone.slug,
milestones_milestone.name,
milestones_milestone.closed
FROM milestones_milestone
WHERE milestones_milestone.project_id = {tbl}.id
ORDER BY estimated_start
) t
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_closed_milestones(queryset, as_field="closed_milestones_attr"):
"""Attach a closed milestones counter to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the counter as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT COUNT(milestones_milestone.id)
FROM milestones_milestone
WHERE milestones_milestone.project_id = {tbl}.id AND
milestones_milestone.closed = True
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_notify_policies(queryset, as_field="notify_policies_attr"):
"""Attach a json notification policies representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the notification policies as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(row_to_json(notifications_notifypolicy))
FROM notifications_notifypolicy
WHERE notifications_notifypolicy.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_epic_statuses(queryset, as_field="epic_statuses_attr"):
"""Attach a json epic statuses representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the epic statuses as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_epicstatus)
ORDER BY projects_epicstatus.order
)
FROM projects_epicstatus
WHERE projects_epicstatus.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_userstory_statuses(queryset, as_field="userstory_statuses_attr"):
"""Attach a json userstory statuses representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the userstory statuses as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_userstorystatus)
ORDER BY projects_userstorystatus.order
)
FROM projects_userstorystatus
WHERE projects_userstorystatus.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_points(queryset, as_field="points_attr"):
"""Attach a json points representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the points as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_points)
ORDER BY projects_points.order
)
FROM projects_points
WHERE projects_points.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_task_statuses(queryset, as_field="task_statuses_attr"):
"""Attach a json task statuses representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the task statuses as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_taskstatus)
ORDER BY projects_taskstatus.order
)
FROM projects_taskstatus
WHERE projects_taskstatus.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_issue_statuses(queryset, as_field="issue_statuses_attr"):
"""Attach a json issue statuses representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the statuses as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_issuestatus)
ORDER BY projects_issuestatus.order
)
FROM projects_issuestatus
WHERE projects_issuestatus.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_issue_types(queryset, as_field="issue_types_attr"):
"""Attach a json issue types representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the types as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_issuetype)
ORDER BY projects_issuetype.order
)
FROM projects_issuetype
WHERE projects_issuetype.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_priorities(queryset, as_field="priorities_attr"):
"""Attach a json priorities representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the priorities as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_priority)
ORDER BY projects_priority.order
)
FROM projects_priority
WHERE projects_priority.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_severities(queryset, as_field="severities_attr"):
"""Attach a json severities representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the severities as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(projects_severity)
ORDER BY projects_severity.order
)
FROM projects_severity
WHERE projects_severity.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_epic_custom_attributes(queryset, as_field="epic_custom_attributes_attr"):
"""Attach a json epic custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the epic custom attributes as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(custom_attributes_epiccustomattribute)
ORDER BY custom_attributes_epiccustomattribute.order
)
FROM custom_attributes_epiccustomattribute
WHERE custom_attributes_epiccustomattribute.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_userstory_custom_attributes(queryset, as_field="userstory_custom_attributes_attr"):
"""Attach a json userstory custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the userstory custom attributes as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(custom_attributes_userstorycustomattribute)
ORDER BY custom_attributes_userstorycustomattribute.order
)
FROM custom_attributes_userstorycustomattribute
WHERE custom_attributes_userstorycustomattribute.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_task_custom_attributes(queryset, as_field="task_custom_attributes_attr"):
"""Attach a json task custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the task custom attributes as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(custom_attributes_taskcustomattribute)
ORDER BY custom_attributes_taskcustomattribute.order
)
FROM custom_attributes_taskcustomattribute
WHERE custom_attributes_taskcustomattribute.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_issue_custom_attributes(queryset, as_field="issue_custom_attributes_attr"):
"""Attach a json issue custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the issue custom attributes as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(custom_attributes_issuecustomattribute)
ORDER BY custom_attributes_issuecustomattribute.order
)
FROM custom_attributes_issuecustomattribute
WHERE custom_attributes_issuecustomattribute.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_roles(queryset, as_field="roles_attr"):
"""Attach a json roles representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the roles as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
sql = """
SELECT json_agg(
row_to_json(users_role)
ORDER BY users_role.order
)
FROM users_role
WHERE users_role.project_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_is_fan(queryset, user, as_field="is_fan_attr"):
"""Attach a is fan boolean to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the boolean as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
if user is None or user.is_anonymous():
sql = "SELECT false"
else:
sql = """
SELECT COUNT(likes_like.id) > 0
FROM likes_like
INNER JOIN django_content_type ON likes_like.content_type_id = django_content_type.id
WHERE django_content_type.model = 'project' AND
django_content_type.app_label = 'projects' AND
likes_like.user_id = {user_id} AND
likes_like.object_id = {tbl}.id
"""
sql = sql.format(tbl=model._meta.db_table, user_id=user.id)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_my_role_permissions(queryset, user, as_field="my_role_permissions_attr"):
"""Attach a permission array to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the permissions as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
if user is None or user.is_anonymous():
sql = "SELECT '{}'"
else:
sql = """
SELECT users_role.permissions
FROM projects_membership
LEFT JOIN users_user ON projects_membership.user_id = users_user.id
LEFT JOIN users_role ON users_role.id = projects_membership.role_id
WHERE projects_membership.project_id = {tbl}.id AND
users_user.id = {user_id}"""
sql = sql.format(tbl=model._meta.db_table, user_id=user.id)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_private_projects_same_owner(queryset, user, as_field="private_projects_same_owner_attr"):
"""Attach a private projects counter to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the counter as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
if user is None or user.is_anonymous():
sql = "SELECT 0"
else:
sql = """
SELECT COUNT(id)
FROM projects_project p_aux
WHERE p_aux.is_private = True AND
p_aux.owner_id = {tbl}.owner_id
"""
sql = sql.format(tbl=model._meta.db_table, user_id=user.id)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_public_projects_same_owner(queryset, user, as_field="public_projects_same_owner_attr"):
"""Attach a public projects counter to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the counter as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
if user is None or user.is_anonymous():
sql = "SELECT 0"
else:
sql = """
SELECT COUNT(id)
FROM projects_project p_aux
WHERE p_aux.is_private = False AND
p_aux.owner_id = {tbl}.owner_id
"""
sql = sql.format(tbl=model._meta.db_table, user_id=user.id)
queryset = queryset.extra(select={as_field: sql})
return queryset
def attach_extra_info(queryset, user=None):
queryset = attach_members(queryset)
queryset = attach_closed_milestones(queryset)
queryset = attach_notify_policies(queryset)
queryset = attach_epic_statuses(queryset)
queryset = attach_userstory_statuses(queryset)
queryset = attach_points(queryset)
queryset = attach_task_statuses(queryset)
queryset = attach_issue_statuses(queryset)
queryset = attach_issue_types(queryset)
queryset = attach_priorities(queryset)
queryset = attach_severities(queryset)
queryset = attach_epic_custom_attributes(queryset)
queryset = attach_userstory_custom_attributes(queryset)
queryset = attach_task_custom_attributes(queryset)
queryset = attach_issue_custom_attributes(queryset)
queryset = attach_roles(queryset)
queryset = attach_is_fan(queryset, user)
queryset = attach_my_role_permissions(queryset, user)
queryset = attach_private_projects_same_owner(queryset, user)
queryset = attach_public_projects_same_owner(queryset, user)
queryset = attach_milestones(queryset)
return queryset
|
def test():
assert (
'spacy.blank("es")' in __solution__
), "¿Creaste el modelo de español en blanco?"
assert (
len(nlp.pipe_names) == 1 and nlp.pipe_names[0] == "ner"
), "¿Añadiste el entity recognizer al pipeline?"
assert (
len(ner.labels) == 1 and ner.labels[0] == "ROPA"
), "¿Añadiste el label al entity recognizer?"
__msg__.good(
"¡Bien hecho! Ahora el pipeline está listo, así que vamos a comenzar a escribir el "
"loop de entrenamiento."
)
|
# Link to the problem: http://www.spoj.com/problems/ANARC09A/
def main():
n = input()
count = 1
while n[0] != '-':
o, c, ans = 0, 0, 0
for i in n:
if i == '{':
o += 1
elif i == '}':
if o > 0:
o -= 1
else:
c += 1
ans += (o // 2) + (c // 2)
if o % 2 == 1 and c % 2 == 1:
ans += 2
print('{}. {}'.format(count, ans))
count += 1
n = input()
if __name__ == '__main__':
main()
|
"""
@author Yuto Watanabe
@version 1.0.0
Copyright (c) 2020 Yuto Watanabe
"""
|
class RunResultError(Exception):
"""Exception thrown when running a command fails"""
def __init__(self, runresult):
super(RunResultError, self).__init__(str(runresult))
self.runresult = runresult
class MatchError(Exception):
"""Exception for output match errors"""
def __init__(self, match, output):
message = "Could not match " + match
message += " in:\n" + output
super(MatchError, self).__init__(message)
|
# Credits:
# 1) https://gist.github.com/evansneath/4650991
# 2) https://www.tutorialspoint.com/How-to-convert-string-to-binary-in-Python
def crc(msg, div, code='000'):
# Append the code to the message. If no code is given, default to '000'
msg = msg + code
# Convert msg and div into list form for easier handling
msg = list(msg)
div = list(div)
# Loop over every message bit (minus the appended code)
for i in range(len(msg)-len(code)):
# If that messsage bit is 1, perform modulo 2 multiplication
if msg[i] == '1':
for j in range(len(div)):
# Perform modulo 2 multiplication on each index of the divisor
# msg[i+j] = str((int(msg[i+j])+int(div[j])) % 2)
msg[i+j] = str(int(msg[i+j]) ^ int(div[j]))
# Output the last error-checking code portion of the message generated
return ''.join(msg[-len(code):])
print("Sender's side....")
# Use a divisor that simulates: x^3 + x + 1
div = '1011'
msg = input('Enter message: ')
msg = ''.join(format(ord(x), 'b') for x in msg)
print(f'Binary encoded input message: {msg}')
print(f'Binary encoded G(x): {div}')
code = crc(msg, div)
print(f"Remaider calculated at sender's side: {code}")
print("\nReceiver's side....")
def printCheck(msg, div, code):
remainder = crc(msg, div, code)
print(f'Remainder is: {remainder}')
print('Success:', remainder == '000')
def errorFunc(msg, div, code):
Error = input("Introduce error(T/F): ")
if Error in ('T', 't'):
msg = list(msg)
msg[7] = str(int(msg[7]) ^ 1)
msg = ''.join(msg)
printCheck(msg, div, code)
else:
printCheck(msg, div, code)
errorFunc(msg, div, code)
|
class Employee:
"""This class represents employees in a company """
num_of_employees = 0 #public static attribute
# init method or constructor
def __init__(self , first , last , pay):
self._first = first #protected Attribute
self._last = last #protected Attribute
self._pay = pay
Employee.num_of_employees += 1
@property
def full_name(self)-> str:
return f'{self._first} {self._last}'
@property
def first(self)->str:
return self._first
@property
def last(self)->str:
return self._last
@property
def pay(self)-> int:
return self._pay
@property
def email(self):
return f'{self.first}.{self.last}@gmail.com'
def __str__(self):
return f'Full Name: {self.full_name}.\
\nPayment: {self.pay}.\
\nEmail: {self.email}'
def __repr__(self):
return f"Employee('{self.first}' , '{self.last}' , {self.pay})"
#Additional constructor
@classmethod
def from_string(cls , str , delimiter = '-'):
first , last , pay = str.split(delimiter)
return cls(first , last , pay)
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
if __name__ == '__main__':
hussein = Employee('Hussein' , 'Sarea' , 15000)
print(hussein)
moataz = Employee.from_string('Moataz-Sarea-20000')
print(moataz)
#import datetime
#date = datetime.date(2021 , 6 , 23)
#print(Employee.is_workday(date))
#print(hussein.get_full_name())
print(hussein.__repr__()) #Employee('Hussein' , 'Sarea' , 15000)
|
class HDateException(Exception):
pass
class HMoneyException(Exception):
pass
class Dict_Exception(Exception):
pass
|
a = float(input('Digite o primeiro valor: '))
b = float(input('Digite o segundo valor: '))
c = 0
while c != 5:
c = int(input(''''Escolha uma opção:
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos Números
[5] Sair do programa: '''))
if c == 1:
print(f'A o resultado da soma de {a} + {b} é igual a {a + b}.' )
if c == 2:
print(f'O produto da multiplicação de {a} e {b} é igual a {a*b}. ')
if c == 3:
if a > b:
print(f'O Primeiro valor {a}, é maior que o segundo valor {b}')
elif b > a:
print(f'O Segundo valor {b}, é maior que o primeiro valor {a}')
elif b == a:
print(f'Os dois valores, {a} e {b}, são iguais')
if c == 4:
a = float(input('Digite o primeiro novo valor: '))
b = float(input('Digite o segundo novo valor: '))
if c > 5 or c < 1:
print('Por favor digite uma operação válida') |
"""
**qecsimext** is an example Python 3 package that extends `qecsim`_ with additional components.
See the README at `qecsimext`_ for details.
.. _qecsim: https://github.com/qecsim/qecsim
.. _qecsimext: https://github.com/qecsim/qecsimext
"""
__version__ = '0.1b9'
|
# -*- coding: utf-8 -*-
__author__ = 'PCPC'
sumList = [n for n in range(1000) if n%3==0 or n%5==0]
print(sum(sumList)) |
def factory(x):
def fn():
return x
return fn
a1 = factory("foo")
a2 = factory("bar")
print(a1())
print(a2())
|
""" var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls,name):
"fetch var with given name"
return cls.list(name=name)[0]
@classmethod
def next(cls,name,advance=True):
"give (and, if advance, then increment) a counter variable"
v=cls.fetch(name)
next=v.value
if advance:
v.value=next+1
v.flush()
return next
@classmethod
def add(cls,name,value=0,textvalue='',datevalue=None,comment=''):
"add a new var of given name with given values"
v=cls.new()
v.name=name
v.value=value
v.textvalue=textvalue
v.datevalue=datevalue
v.comment=comment
v.flush()
@classmethod
def amend(cls,name,value=None,textvalue=None,datevalue=None,comment=None):
"update var of given name with given values"
v=cls.fetch(name)
if value is not None:
v.value=value
if textvalue is not None:
v.textvalue=textvalue
if datevalue is not None:
v.datevalue=datevalue
if comment is not None:
v.comment=comment
v.flush()
@classmethod
def say(cls,name):
v=cls.fetch(name)
return "%s : %s (%s) (%s) %s" % (v.name,v.value,v.textvalue,v.datevalue,v.comment)
|
def find_pivot(arr, low, high):
if high < low:
return -1
if high == low:
return low
mid = int((low + high)/2)
if mid < high and arr[mid] > arr[mid + 1]:
return mid
if mid > low and arr[mid] < arr[mid - 1]:
return mid-1
if arr[low] >= arr[mid]:
return find_pivot(arr, low, mid-1)
return find_pivot(arr, mid+1, high)
def binary_search(arr, low, high, key):
if high < low:
return -1
mid = int((low+high)/2)
if key == arr[mid]:
return mid
if key > arr[mid]:
return binary_search(arr, mid+1, high, key)
return binary_search(arr, low, mid-1,key)
def pivoted_search(arr, low, high, key):
pivot = find_pivot(arr, 0, n-1)
if pivot == -1:
return binary_search(arr, 0, n-1, key)
if arr[pivot] == key:
return pivot
if arr[0] <= key:
return binary_search(arr, 0, pivot-1, key)
return binary_search(arr, pivot+1, n-1, key)
|
_base_ = './pascal_voc12.py'
# dataset settings
data = dict(
train=dict(
ann_dir='SegmentationClassAug',
split=[
'ImageSets/Segmentation/train.txt',
'ImageSets/Segmentation/aug.txt'
]
),
val=dict(
ann_dir='SegmentationClassAug',
),
test=dict(
ann_dir='SegmentationClassAug',
)
)
|
"""
# Useful git config for working with git submodules in this repo
(
git config status.submodulesummary 1
git config push.recurseSubmodules check
git config diff.submodule log
git config checkout.recurseSubmodules 1
git config alias.sdiff '!'"git diff && git submodule foreach 'git diff'"
git config alias.spush 'push --recurse-submodules=on-demand'
)
"""
"""
# Disable prompting for passwords - works with git version 2.3 or above
export GIT_TERMINAL_PROMPT=0
# Harder core version of disabling the username/password prompt.
GIT_CREDENTIAL_HELPER=$PWD/.git/git-credential-stop
cat > $GIT_CREDENTIAL_HELPER <<EOF
cat
echo "username=git"
echo "password=git"
EOF
chmod a+x $GIT_CREDENTIAL_HELPER
git config credential.helper $GIT_CREDENTIAL_HELPER
"""
"""
# Fetching non shallow + tags to allow `git describe` information.
git fetch origin --unshallow || true
git fetch origin --tags
"""
"""
Clone a users version of a submodule if they have one.
Original from https://github.com/timvideos/litex-buildenv/blob/master/.travis/add-local-submodule.sh
USER_SLUG="$1"
SUBMODULE="$2"
REV=$(git rev-parse HEAD)
echo "Submodule $SUBMODULE"
# Get the pull request info
REQUEST_USER="$(echo $USER_SLUG | perl -pe 's|^([^/]*)/.*|\1|')"
REQUEST_REPO="$(echo $USER_SLUG | perl -pe 's|.*?/([^/]*)$|\1|')"
echo "Request user is '$REQUEST_USER'".
echo "Request repo is '$REQUEST_REPO'".
# Get current origin from git
ORIGIN_URL="$(git config -f .gitmodules submodule.$SUBMODULE.url)"
#ORIGIN_URL="$(git remote get-url origin)"
if echo $ORIGIN_URL | grep -q "github.com"; then
echo "Found github"
else
echo "Did not find github, skipping"
exit 0
fi
ORIGIN_SLUG=$(echo $ORIGIN_URL | perl -pe 's|.*github.com/(.*?)(.git)?$|\1|')
echo "Origin slug is '$ORIGIN_SLUG'"
ORIGIN_USER="$(echo $ORIGIN_SLUG | perl -pe 's|^([^/]*)/.*|\1|')"
ORIGIN_REPO="$(echo $ORIGIN_SLUG | perl -pe 's|.*?/([^/]*)$|\1|')"
echo "Origin user is '$ORIGIN_USER'"
echo "Origin repo is '$ORIGIN_REPO'"
USER_URL="git://github.com/$REQUEST_USER/$ORIGIN_REPO.git"
# Check if the user's repo exists
echo -n "User's repo would be '$USER_URL' "
if git ls-remote --exit-code --heads "$USER_URL" > /dev/null 2>&1; then
echo "which exists!"
else
echo "which does *not* exist!"
USER_URL="$ORIGIN_URL"
fi
# If submodule doesn't exist, clone directly from the users repo
if [ ! -e $SUBMODULE/.git ]; then
echo "Cloning '$ORIGIN_REPO' from repo '$USER_URL'"
git clone $USER_URL $SUBMODULE --origin user
fi
# If the submodule does exist, add a new remote.
(
cd $SUBMODULE
git remote rm user >/dev/null 2>&1 || true
if [ "$USER_URL" != "$ORIGIN_URL" ]; then
git remote add user $USER_URL
git fetch user
fi
git remote rm origin >/dev/null 2>&1 || true
git remote add origin $ORIGIN_URL
git fetch origin
)
# Checkout the submodule at the right revision
git submodule update --init $SUBMODULE
# Call ourselves recursively.
(
cd $SUBMODULE
git submodule status
echo
git submodule status | while read SHA1 MODULE_PATH DESC
do
"$SCRIPT_SRC" "$USER_SLUG" "$MODULE_PATH"
done
exit 0
) || exit 1
exit 0
"""
# Return True if the given tree needs to be initialized
def check_module_recursive(root_path, depth, verbose=False):
if verbose:
print('git-dep: checking if "{}" requires updating...'.format(root_path))
# If the directory isn't a valid git repo, initialization is required
if not os.path.exists(root_path + os.path.sep + '.git'):
return True
# If there are no submodules, no initialization needs to be done
if not os.path.isfile(root_path + os.path.sep + '.gitmodules'):
return False
# Loop through the gitmodules to check all submodules
gitmodules = open(root_path + os.path.sep + '.gitmodules', 'r')
for line in gitmodules:
parts = line.split("=", 2)
if parts[0].strip() == "path":
path = parts[1].strip()
if check_module_recursive(root_path + os.path.sep + path, depth + 1, verbose=verbose):
return True
return False
# Determine whether we need to invoke "git submodules init --recurse"
def check_submodules(script_path, args):
if check_module_recursive(script_path, 0, verbose=args.lx_verbose):
print("Missing submodules -- updating")
subprocess.Popen(["git", "submodule", "update",
"--init", "--recursive"], cwd=script_path).wait()
elif args.lx_verbose:
print("Submodule check: Submodules found")
|
def out(status, message, padding=0, custom=None):
if status == '?':
return input(
' ' * padding
+ '\033[1;36m'
+ '[?]'
+ '\033[0;0m'
+ ' ' + message
+ ': '
)
elif status == 'I':
print(
' ' * padding
+ '\033[1;32m['
+ (str(custom) if custom != None else 'I')
+ ']\033[0;0m'
+ ' '
+ message
)
elif status == 'E':
print(
' ' * padding
+ '\033[1;31m['
+ (str(custom) if custom != None else 'E')
+ ']\033[0;0m'
+ ' '
+ message
)
elif status == 'W':
print(
' ' * padding
+ '\033[1;33m['
+ (str(custom) if custom != None else 'W')
+ ']\033[0;0m'
+ ' '
+ message
)
|
class Animal(object):
"""docstring for Animal"""
def __init__(self):
super(Animal, self).__init__()
def keu(self):
print("I am an animal")
class Plant(object):
"""docstring for Plant"""
def __init__(self):
super(Plant, self).__init__()
def keu(self):
print("I am a plant")
def qh(self):
print("I am qhing")
class Cat(Animal):
"""docstring for Cat"""
def __init__(self, arg):
super(Cat, self).__init__()
self.arg = arg
def keu(self):
print("I am a cat")
class BlackCat(Animal, Plant):
"""docstring for BlackCat"""
def __init__(self, arg):
super(BlackCat, self).__init__()
self.arg = arg
# def keu():
# print("I am a black cat")
if __name__ == '__main__':
bc = BlackCat(1)
bc.keu()
bc.qh()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.