content stringlengths 7 1.05M |
|---|
"""
spider.unsupervised_learning sub-package
__init__.py
@author: kgilman
Primitive that performs GRASTA to learn low-rank subspace and sparse outliers from streaming data
defines the module index
"""
# to allow from spider.unsupervized_learning import *
__all__ = [
"grasta",
]
|
# Copyright (c) 2018-2019 Alexander L. Hayes (@hayesall)
#
# 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... |
class Document :
# Default constructor
def __init__ ( self , _id ):
# initialize
self.id = _id
self.title =""
self.text= ""
self.succ = dict()
self.pred = dict()
#Setters
def setText(self,Text):
self.text = Text
def setT... |
class Calculator():
def __init__(self):
pass
def add(self, val1, val2):
try:
return val1 + val2
except:
raise ValueError("Not int")
def subtract(self, val1, val2):
val1 = self._checker(val1)
val2 = self._checker(val2)
if val1 and... |
class Torre:
def __init__(self):
self.id = int()
self.nome = str()
self.endereco = str()
def cadastrar(self, id, nome, endereco):
self.id = id
self.nome = nome
self.endereco = endereco
def imprimir(self):
print("ID TORRE:", self.id, " - TORRE", ... |
# Copyright 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Exposes an auto-public version of android_library"""
def visible_android_library(**kwargs):
"""android_library that is by def... |
#!/usr/bin/env python3
# pylint: disable=C0111
def all_steps(state):
result = list()
for action in range(len(state[0])):
if state[0][action] != 0:
next_state = jump(state, action, 1) or jump(state, action, 2)
if next_state:
result = result + all_steps(... |
'''
codegen: this is the code generator for our Cuppa3 compiler
NOTE: this code generator does not need access to the symbol table,
the abstraction level of the AST has been lowered already to the level
of the abstract machine code
'''
######################################################################... |
def generate_code_str(body, argname, global_name):
""" Generate python code to eval()
"""
body = body.replace('\n', '\n ')
return f"""def f({argname}):
{body}
output = f({global_name})"""
|
def double(oldimage):
oldw = oldimage.getWidth()
oldh = oldimage.getHeight()
newim = EmptyImage(oldw*2,oldh*2)
for row in range(newim.getWidth()): #// \label{lst:dib1}
for col in range(newim.getHeight()): #// \label{lst:dib2}
originalCol = col//2 #// \label{lst:dib3... |
#Exercício 7
lista_filmes = ["Esquadrão Suicida", "Homem Aranha"]
lista_jogos = ["Rocket League", "GTA"]
lista_livros = ["A Culpa é das Estrelas", "O Diário de Anne Frank"]
lista_esportes = ["Handebol", "Basquete"]
#a)
#Lista A
lista_filmes.append("Harry Potter")
lista_filmes.append("Velozes e Furiosos")
print... |
# 1
stringHamlet_1 = 'To be or not to be.'
# 2
print(len(stringHamlet_1))
# 3
stringHamlet_2 = 'That is the question.'
# 4
stringHamlet = stringHamlet_1 + stringHamlet_2
# 5
stringHamletTrinity = stringHamlet * 3 |
"""
Task Score: 100%
Complexity: O(N * log(N))
"""
def is_triangle(a, b, c):
# apply given formulate to triplet
return a + b > c and \
b + c > a and \
a + c > b
def solution(A):
"""
I am sure there is a mathematical proof for this somewhere, however I
thought by looking at ... |
###################################################################################
#
# Copyright (C) 2020 Cetmix OÜ
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as
# published by the Free Software Foundation, either ... |
# For defining [Topic]hint_type, [Question]hint_type, [NLP_hints]hint_type
HINT_TYPE_CHOICES = (
('NONE', 'No hint'),
('WHERE', 'Where'),
('WHO', 'Who'),
('HOW MANY', 'How many'),
('WHEN', 'When'),
)
# nlp_exporter uses for requesting all available hints from NLP-Hints service
Q... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by pat on 5/11/18
"""
.. currentmodule:: modlit.testing
.. moduleauthor:: Pat Daburu <pat@daburu.net>
This package contains resources for testing your data model.
"""
|
"""
Private fields are specified by prefixing an attribute's name with a double
underscore.
They can be accessed directly by methods of the containing class
Private attrib behaviour is implemented witha a simple transformation of the
attribute name.
__private_field transforms to _ClassName__private_field.
Why... |
## TuplesAndLists
#
# Demonstration of techniques with tuples and lists
# Tuples cannot be changed, values enclosed with parenthesis.
# Tuples can be used as replacement for constant arrays
# available in other languages.
# Lists can be modified.
list1 = [ 10, 20, 30, 40, 50, 5, 2 ]
tuple1 = ( 10, 20, 30, 40, 50, ... |
DEFAULT = False
called = DEFAULT
def reset_app():
global called
called = DEFAULT
def generate_sampledata(options):
global called
assert called == DEFAULT
called = True
|
"""
16120. PPAP
작성자: xCrypt0r
언어: Python 3
사용 메모리: 36,496 KB
소요 시간: 532 ms
해결 날짜: 2021년 10월 31일
"""
def main():
s = input()
q = []
for i in range(len(s)):
q.append(s[i])
while len(q) >= 4 and q[-4:] == ['P', 'P', 'A', 'P']:
del q[-3:]
print('PPAP' if q == ['P'] else 'NP'... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
x=0
tot=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
pos=line.find(":")
l=line[pos+1:]
l=l.strip()
tot+=float(l)
x+=1
print("Average spam confidence: "+str(tot/x)... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
p = self.reverseList(head.next)
... |
_poolinfo_reply_EN = """
<b><code>{ticker}</code> {pool_name}</b>
<i>{desc}</i>
🌐{homepage}
<b>🆔 Pool ID</b>
<code>{pool_id}</code>
<b> ℹ️ Pool info</b>
rank: <code>#️{pool_rank}</code>
pledge: <code>{pledge} ₳</code>
cost: <code>{cost} ₳</code>
margin: <code>{margin_perc}%</code>
<b>📈 Metrics</b>... |
# https://leetcode.com/problems/3sum/
#%%
nums = [-1,0,1,2,-1,-4]
target = 0
#%%
def threeSum(nums: list):
nums.sort()
indeces = []
values = []
uniqueIndeces = {}
#need to stop when I reach len(nums) - 2 because that I am going to deal with 2 pointers
for ind in range(0, len(nums) - 2):
... |
input = """
c num blocks = 1
c num vars = 180
c minblockids[0] = 1
c maxblockids[0] = 180
p cnf 180 795
5 49 137 0
-146 -16 161 0
-116 106 -77 0
28 -33 -87 0
-70 -56 -28 0
123 76 88 0
-160 128 45 0
-29 169 180 0
-96 -69 100 0
56 82 -38 0
-14 -108 -88 0
-147 -93 4 0
-130 6 38 0
-50 -149 8 0
142 -96 -68 0
-104 47 168 0
1... |
#Leia uma distancia em milhas e apresente-a convertida em quilometros.
#A formula de conversao eh K =M*1.61 ,
# sendo K a distancia em quilometros e M em milhas.
m=float(input("Informe a distancia em milhas: "))
K=m*1.61
print(f"A distancia convertida em km eh {K}km/h") |
"""
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The length of inpu... |
lista = []
for cont in range(0, 5):
núm = (int(input('Digite um valor : ')))
if cont == 0 or núm > lista[-1]:
lista.append(núm)
print('Valor adicionado no final da lista...')
else:
pos = 0
while pos < len(lista):
if núm <= lista[pos]:
lista.insert(... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def contain1(root):
... |
class TaskType:
JOINT = 'joint'
MENTION_LOCALIZATION = 'mention_localization'
COREFERENCE_RESOLUTION = 'coreference_resolution'
ENTITY_CLASSIFICATION = 'entity_classification'
RELATION_CLASSIFICATION = 'rel_classification'
|
nome = "Robozinho"
posicao = [0, 0]
direcao = ["Norte"]
def iniciarRobot():
print(f"""{nome} inicou
a posição atual do {nome} é: {posicao}
a direção atual do {nome} é: {direcao[0]} """)
def statusRobot():
print(f"""A posição atual do {nome} é: {posicao}
S direção atual do {nome} é: {direcao[0]} """)
1
... |
def multiuply(multiplyer,multiplycant):
result = multiplyer * multiplycant
return result
answer = multiuply(10.5,4)
print(answer)
print (multiuply(8,10))
def __init__(self):
return(__init__+3) |
"""
Set up Google authentication parameters here.
"""
#GOOGLE_AUTH = {
# 'account': '<gmail address>',
# 'password': '<password>',
#}
|
RECURSE_INTO = {
"p",
"blockquote",
"div",
"em",
"i",
"b",
"u",
"strong",
"h2",
"figure",
}
INCLUDE_TAGNAME = {
"blockquote",
"em",
"i",
"b",
"u",
"strong",
"h2",
}
INCLUDE_VERBATIM = {"li", "ul", "ol"}
NEWLINE_AFTER = {
"blockquote",
"h2",
}
D... |
def first_check():
pass
def second_check():
pass
def main():
print('badge checks TODO')
first_check()
second_check()
if __name__ == "__main__":
main()
|
#26. Faça um programa que leia uma frase e mostre: quantas vezes aparece a letra 'a'; em que posição ela aparece a primeira e ultima vez.
#27. Faça um programa que leia o nome completo e mostre o primeiro e ultimo nome separadamente.
def Main026():
frase = str(input('Frase: ')).strip().lower()
print('Tem {} ... |
# Copyright 2015 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.
"""Tests that step_data can accept multiple specs at once."""
DEPS = [
'step',
]
def RunSteps(api):
raise TypeError("BAD DOGE")
def GenTest... |
''' Print Asterisks
Write a program that can print the line of asterisks. I have to define a founction called printAsterisks(). This finction should take single argument/parameter. This argument will take an interger value that represents the number of asterisks. My program should print the number of asterisks ... |
N = int(input())
L = len(str(N))
ans = 0
for i in range(2, L+1, 2):
if i == L:
head = int(str(N)[:i//2])
tail = int(str(N)[i//2:])
if head <= 9:
if head > tail:
head -= 1
ans += head
else:
if head > tail:
head -= 1
... |
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
w = grenal = inter = gremio = empates = 0
while w == 0:
grenal += 1
g1, g2 = input().split(' ')
g1 = int(g1)
g2 = int(g2)
if g1 == g2:
empates += 1
elif g1 > g2:
inter += 1
else:
gremio += 1
print('Novo grenal (1-sim 2-nao)')
op = int(input())
if op == 2:
... |
"""
Soft Actor Critic (SAC) Control
===============================
"""
|
# Copyright 2021 Kotaro Terada
#
# 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... |
query = """
select * from languages;
"""
query = """
select *
from games
where test=0
"""
def get_query1():
query = (
f"SELEct max(weight) from world where ocean='Atlantic' and water is not null"
)
return query
def get_query2():
limit = 6
query = f"SELEct speed from worl... |
# Write a Python program to multiplies all the items in a list.
def multiply_list(items):
multiply_numbers = 1
for x in items:
multiply_numbers *= x
return multiply_numbers
print(multiply_list([5,2,-8])) |
def _jar_jar_impl(ctx):
ctx.action(
inputs=[ctx.file.rules, ctx.file.input_jar],
outputs=[ctx.outputs.jar],
executable=ctx.executable._jarjar_runner,
progress_message="jarjar %s" % ctx.label,
arguments=["process", ctx.file.rules.path, ctx.file.input_jar.path, ctx.outputs.jar.path])
return Java... |
def square(a):
return a * a
print(square(4))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is Blogofile -- http://www.Blogofile.com
Definition: Blogophile --
A person who is fond of or obsessed with blogs or blogging.
Definition: Blogofile --
A static file blog engine/compiler, inspired by Jekyll.
Blogofile transforms a set of templates into an en... |
# Aufgabe 2 - Übung 3
#
# Erweitern Sie das BMI-Programm aus der Vorlesung und geben Sie zusätzlich die folgende Interpretation aus:
# BMI < 18.5 Untergewicht
# BMI 18.5 - 24.9 Normalgewicht
# BMI 25.0 - 29.9 Übergewicht
# BMI > 30.0 Adipositas
#
# BMI = masse / (körpergröße zum quadrat in m)
untergewicht = 18.5
norma... |
#!/usr/bin/env python
NAME = 'SiteGround (SiteGround)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
if any(i in page for i in (b'Our system thinks you might be a robot!',
b'The page you are trying to acce... |
class Solution:
def solve(self, a, b):
def multiply(x,y,c):
m = x*y + c
return m//10,m%10
e1,e2 = -1,-1
si = 1
if a[0] == "-":
e1 = 0
si *=-1
if b[0] == "-":
e2 = 0
si *=-1
n1 = len(a)
... |
# Copyright 2015 by Hurricane Labs LLC
#
# 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 ... |
# %% [markdown]
# # 1 - Print
# %% [markdown]
# `print()` is build in function in python that takes any type of object as it's parameter
#
# The [print](https://docs.python.org/3/library/functions.html#print) function let's you send an output to the terminal
#
#
# Python [built-in functions](https://docs.python.or... |
#
# PySNMP MIB module AC-PM-ATM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-PM-ATM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
def Shell(A):
t = int(len(A)/2)
while t > 0:
for i in range(len(A)-t):
j = i
while j >= 0 and A[j] > A[j+t]:
A[j], A[j+t] = A[j+t], A[j]
j -= 1
t = int(t/2) |
# 함수로 negative/zero/positive
def f(key):
if key > 0: # key가 양수일 경우
print("positive")
elif key == 0: # key가 0일 경우
print("zero")
else: # key가 음수일 경우
print("negative")
f(int(input())) |
"""
479. Largest Palindrome Product
Find the largest palindrome made from the product of two n-digit numbers.
Since the result could be very large, you should return the largest palindrome mod 1337.
Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Note:
The range of n is [1,8].
"""
c... |
# Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
n1 = int(input('Informe um número: '))
n2 = int(input('Informe outro número: '))
if n1 > n2:
print(f'O primeiro número {n1} é maior que o segundo {n2}.')
elif n1 < n2:
print(f'O segundo número {n2} é maior que o primeiro {n1}.')
else:
print(f'O primeiro número {n1} e o segundo {n2} são iguais.')
|
"""
- domain: Sphere online judge
- contest: list of classical problems
- problem: JULKA - Julka
- link: https://www.spoj.com/problems/JULKA/
- hash: $$$$$$$$$$name
- author: Vitor SRG
- version: $$$$$$$$$$date
- tags: tests biginteger
- language: Python3
"""
... |
'''
Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu IMC e mostre seu
status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do peso
- Entre 18.5 e 25: Peso ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida
'''
print('-=-' * 10)
print('CÁLCULO DE I... |
def validMountainArray(arr):
N = len(arr)
i = 0
while i + 1 < N and arr[i] < arr[i+1]:
i += 1
if i == 0 or i == N-1:
return False
while i + 1 < N and arr[i] > arr [i+1]:
i += 1
return i == N-1
arr = [2,1]
x = validMountainArray(arr)
print(x)
arr1 = [3,5,5]
x = v... |
""" Django package for use typograf in models. """
VERSION = 0, 1, 2
__version__ = '.'.join(map(str, VERSION))
|
def main(j, args, params, tags, tasklet):
page = args.page
filters = dict()
tagsmap = {
'jsname': 'name',
'jsorganization': 'organization',
}
fieldids = ['id', 'jsname', 'jsorganization', 'category', 'descr']
for tag, val in args.tags.tags.iteritems():
key = tagsmap.get... |
bad_result_count = int(input())
count_bad = 0
count = 0
last_problem = ''
all_score = 0
while True:
task = input()
if task == 'Enough':
break
rating = float(input())
if rating <= 4:
count_bad += 1
if count_bad == bad_result_count:
print(f'You need a break, {bad_resu... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
def post(node):
if node:
pos... |
class SagemakerData(object):
amazon_reviews_raw_data = "s3://amazon-reviews-pds/tsv/amazon_reviews_us_Digital_Video_Download_v1_00.tsv.gz"
sagemaker_data_repo = SagemakerData()
|
class Feature(object):
def __init__(self):
self.docCountOfClasses = {}
self.frequencies = {}
# Increase class of a document.
def increaseClass(self, className):
self.docCountOfClasses[className] = self.docCountOfClasses.get(className, 0) + 1
# Increase token of a class.
d... |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "com_google_cloud_go",
importpath = "cloud.google.com/go",
version = "v0.51.0",
sum = "h1:PvKAVQWCtlGUSlZkGW3QLelKaWq7KYv/MW1EboG8bfM=",
build_extra_args = [
"-go_nami... |
def dp_fibonacci(num):
'''
Returns fibonacci number of a given integer
using dynamic programming for faster runtime
Runtime: O(n)
'''
# Returns -1 if num is negative
if num < 0:
return -1
if num == 0:
return 0
if num == 1 or num == 2:
return 1
... |
Clock.bpm=var([120,60,30,15,2],[124,2,1,1/2,1/2]) # wait for the drop!
Scale.default="major"
d1 >> play("<|V0|:>< O ><|[--]5|>", sample=2)
d2 >> play("<...(+|L2|)>< m>")
c1 >> play("n", dur=1/4, sample=PRand(8), pan=PWhite(-1,1))
b1 >> dbass(var([0,-2],8), dur=PDur(3,9), shape=PWhite(0,0.5), sus=2, chop=4, pan=PWhite(... |
# Find the duplicate number - Leetcode
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
freq = {}
for i in range(len(nums)):
if nums[i] not in freq.keys():
freq[nums[i]] = 1
else:
freq[nums[i... |
'''
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas... |
#!/usr/bin/env python3
# Day 13: Remove K Digits
#
# Given a non-negative integer num represented as a string, remove k digits
# from the number so that the new number is the smallest possible.
#
# Notes:
# - The length of num is less than 10002 and will be ≥ k.
# - The given num does not contain any leading zero.
c... |
#!/usr/bin/python3
the_file = input("Enter the file name, e.g. Covid_19.fasta ")
o_file = open(the_file, 'r')
line_number = 0
number_of_lines = 0
by_hundred = [0] * 6
for line in o_file:
line_number += 1
if ">" in line and number_of_lines == 0:
virus_name = line
continue
elif ">" in line... |
# encoding: utf-8
# module Rhino.Runtime.InteropWrappers calls itself InteropWrappers
# from Rhino3dmIO,Version=5.1.30000.14,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class MeshPointDataStruct(object):
# no doc
m_ci_index=None
m_ci_type=Non... |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = []
self.bt(candidates,0,[],target, res)
return res
def bt(self, candidates, idx, tempList, target, res):
if target < 0:
return
... |
class RoomAlreadyEmpty(Exception):
pass
class CannotAllocateRoom(Exception):
pass
|
"""Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista."""
num = []
for n in range(1, 6):
num.append(int(input(f'Digite um nº para a {n}ª posição: ')))
print(f'Números digitados: {num}')
print(f'O... |
file_location = 'results_googlenet.txt'
text_file = open(file_location, "r")
lines = text_file.readlines()
living_room = []
for i in range(74):
living_room.append(i)
dining_room = []
for i in range(74, 113):
dining_room.append(i)
for i in range(183, 205):
dining_room.append(i)
kitchen = []
for i in r... |
#!/usr/bin/python
# Miscellaneous TIFF-related tests
# Regression test -- we once had a bug where 'separate' planarconfig
# tiled float files would have data corrupted by a buffer overwrite.
command += (oiio_app("oiiotool") + "--pattern checker 128x128 4 --tile 64 64 --planarconfig separate -d float -o check1.tif"... |
patches = [
# Add AWS::MemoryDB::Cluster Endpoint
{
"op": "add",
"path": "/ResourceTypes/AWS::MemoryDB::Cluster/Properties/ClusterEndpoint",
"value": {"Type": "Endpoint"},
},
]
|
class GenerateWPAD:
head = []
foot = []
def __init__(self):
self.head = [
'/**\n',
'The original template was created by Sam Gleske\n',
'This author and license block must stay intact for use even if this script is \n',
'modified!\n',
... |
########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: O programa recebe dois ou mais números inteiros e retorna o máximo divisor comum deles.
########
def calcular_mdc(a, b):
# o mesmo que while != 0
# while 0 = False
while b:
a, b = b, a%b
... |
class SlewLimiter:
def __init__(self, limit):
self.limit = limit
self.output = 0.0
def Feed(self, value):
error = value - self.output
if error > self.limit:
error = self.limit
elif error < (self.limit * -1):
error = self.limit * -1
sel... |
description = 'setup for the execution daemon'
group = 'special'
devices = dict(
# The entries for the password hashes are generated from randomized
# passwords and not reproduceable, please don't forget to create new ones.
# see https://forge.frm2.tum.de/nicos/doc/nicos-stable/services/daemon/#nicos.servi... |
# _update_parameter.py
__module_name__ = "_update_parameter.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
def _update_parameter(class_object, parameter, value):
class_object.__setattr__(parameter, value) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# rce-core/rce/util/iaas.py
#
# This file is part of the RoboEarth Cloud Engine framework.
#
# This file was originally created for RoboEearth
# http://www.roboearth.org/
#
# The research leading to these results has received funding from
# the Eur... |
BATCH_SIZE = 256
MAX_SEQ_LEN=5
SEED = 98765
PADDING_IDX = 0
ACTIVATION_FUNC = None
model_type = 'sdm'
SDM_INIT_TRANSFORM_TYPE='identity'
|
BROADCAST_PORT = 0xD6D9
MESSAGE_TYPE = {
'POWER_ON' : 0x3110000,
'BRIGHTNESS': 0x3130000,
'COLOR_TEMP': 0x31b0000,
'QUERY' : 0x30f0000,
'SEARCH' : 0x2010000,
}
MESSAGE_OFFSET = {
'SRC_IP' : 0x00,
'SRC_PORT' : 0x04,
'DEST_IP' : 0x08,
'DEST_PORT' : 0x0C,... |
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return
stack = []
cur = head
while cur:
stack.append(cur)
cur = cur.next
count... |
#!/usr/bin/env python
def read(path):
with open(path) as f:
timers = list(map(int, f.read().strip().split(",")))
return timers
def slow(timers, num_steps):
timers = list(timers)
step = 0
n = len(timers)
while step < num_steps:
to_extend = []
for j in range(n):
... |
class Solution:
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
pending = [id]
imp = 0
while(len(pending)>0):
pending, imp = self.processing(employees, pending, imp)
return imp
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 5 15:00:34 2018
@author: James Jiang
"""
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
grid = [[i for i in line] for line in all_lines]
for y_corners in [0, 99]:
for x_corners in [0, 99]:
grid[y_corners][x_corners] = '#'
grid_num_neighbors =... |
#definicion de variables u otros
print("Ejercicio 01: Area Triangulo")
#Datos de Entrada
b=int(input("Ingrese Base:"))
h=int(input("Ingrese Altura:"))
#Proceso
area=(b*h)/2
#Datos de Salida
print("El area es: ", area) |
"""
0593. Valid Square
Medium
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
Note:
All the... |
num=list((input()))
count=[0]*10
for n in num:
i=0
while i<=10:
if int(n)==i:
count[i]+=1
i+=1
for c in count:
print(c)
|
class HybridShape(object):
"""
Python class to manage Catia's Hybrid Shape Abstract Object
"""
def __init__(self, parent, cat_constructor):
"""
:param parent:
:param cat_constructor:
"""
self.parent = parent[parent[-1]]
self.parentsDict = par... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: sml2h3
@contact: sml2h3@gmail.com
@software: openlawClawer
@file: system.py
@time: 17-12-16 上午4:43
@desc:
''' |
num = int(input())
arr = sorted(list(map(int, input().split())))
assert len(arr) == num
def leftright(l):
llen = len(l)
return l[:(llen//2)], l[-(llen//2):]
def median(l):
llen = len(l)
if llen % 2 == 1:
return l[llen//2]
else:
return (l[(llen//2)-1]+l[llen//2]) // 2
left, right =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.