content stringlengths 7 1.05M |
|---|
"""
zip
"""
list_name = ["郭世鑫", "万忠刚", "赵文杰"]
list_age = [22, 26]
# for 变量 in zip(可迭代对象1,可迭代对象2)
for item in zip(list_name, list_age):
print(item)
# 应用:矩阵转置
map = [
[2, 0, 0, 2],
[4, 2, 0, 2],
[2, 4, 2, 4],
[0, 4, 0, 4]
]
# new_map = []
# for item in zip(map[0],map[1],map[2],map[3]):
# new... |
"""Given an array length 1 or more of ints, return the difference between the
largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2)
functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
"""
def b... |
class ObjectContext:
def __init__(self) -> None:
self.definedTypes = {}
self.definedSymbols = {}
def get_type(self, typeName: str):
return self.definedTypes[typeName]
def type_of(self, symbol: str):
if self.definedSymbols.__contains__(symbol):
return self.defin... |
class Scenario:
_requests = None
def __init__(self, requests):
self._requests = requests
def get_requests(self):
return self._requests
|
#Calcular y mostrar la nota final para cada materia, y el promedio general de las tres materias
def calc_matematicas(examen, tarea1, tarea2, tarea3):
valor_examen = examen * 0.9
total_tareas = tarea1 + tarea2 + tarea3
promedio_tareas = total_tareas / 3
valor_tareas = promedio_tareas * 0.1
final_mate... |
'''
2 - Atribuição aumentada (ex.: x += 5):
x = 10
x = x + 10 # x=20
x += 10 # x=30
x *= 2 # x=60
x = 2
x **= 10 # x=1024
''' |
my_list = [20, 39, 34, 20, 24, 20, 10, 11]
my_set = sorted(set(my_list))
print(my_set)
|
settings = {
'token': 'DISCORD_BOT_TOKEN',
'id': BOT_ID,
'prefix': 'PREFIX',
'embedcolor': EMBED_COLOR_(0x123456),
'author-id': YOUR_ID,
'vk-api-token': 'VK_API_TOKEN',
'bot_avatar_url': 'BOT_AVATAR_URL',
'youtube_apikey': 'YOUTUBE_DATA_API_KEY',
'weather_token': 'OPENWEATHERMAP_TOKE... |
''' ***
*
*** '''
n = int(input())
while n:
n=n-1
num = int(input())
if num<38 or (num%5)<3:
print(num)
else:
print(num+(5-(num%5)))
|
class GlocalMerchantRequest:
def __init__(self, xgl_token_external, payload):
self.xgl_token_external = xgl_token_external
self.payload = payload
def get_payload(self):
return self.payload
def get_xgl_token_external(self):
return self.xgl_token_external
def set_xgl_tok... |
DEFAULT_SPECIAL_TOKEN_BOXES = {
"[UNK]": [0, 0, 0, 0],
"[PAD]": [0, 0, 0, 0],
"[CLS]": [0, 0, 0, 0],
"[MASK]": [0, 0, 0, 0],
"[SEP]": [1000, 1000, 1000, 1000],
}
MAX_LINE_PER_PAGE = 200
MAX_TOKENS_PER_LINE = 25
MAX_BLOCK_PER_PAGE = 40
MAX_TOKENS_PER_BLOCK = 100
MAX_2D_POSITION_EMBEDDINGS = 1024 |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name = "indexing_suite/python_iterator.hpp"
code = """// -*- mode:c++ ... |
#!/usr/bin/env python3
numbers = [42, 9001]
letters = "ace"
try:
print(numbers + letters)
except TypeError as err:
print(err) # can only concatenate list (not "str") to list
words = ["ace", "in", "hole"]
print(numbers + words) # [42, 9001, 'ace', 'in', 'hole']
|
once = 0
res = (0,0)
def calc():
global once, res
if once > 0: return
with open("../stream/input15.txt", "r") as file:
data = [int(y) for y in [x.strip() for x in file.read().splitlines()][0].split(',')]
occurences = {data[i-1]:[i] for i in range(1, len(data)+1)}
current = ... |
"""
Implement regular expression matching with support for '.' and '*'.
The matching should cover the entire input string (not partial).
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aa", "a*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
"""
class Solution:
def i... |
n = int(input())
for i in range(n):
c=input()
lst=list(c)
l=len(c)
c2=[]
for i2 in range(l):
if(lst[i2]=='4'):
lst[i2]='3'
c2.append('1')
else:
c2.append('0')
print("".join(lst)+" "+"".join(c2))
|
# Faça um programa que leia a largura e a altura de uma parade em metros,
# calcule a sua área e a quantidade de tinta necessária para pinta-la,
# sabendo que cada litro de tinta, pinta uma área de 2m².
print('This program will tell you, how many liters of paint you will need to paint the area you want.')
h = float(i... |
def crf_pos_features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word=' + word, #current word
'word[-4:]=' + word[-4:], #last 4 characters
'word[-3:]=' + word[-3:], #last 3 characters
'word... |
nop = b'\x00\x00'
brk = b'\x00\xA0'
lda = b'\x6A\x02' # Load 0x02 into register VA
ldb = b'\x6D\xDD' # Load 0xDD into register VD
ldx = b'\x8D\xA0' # Load register VA into VD
with open("ldvxvytest.bin", 'wb') as f:
f.write(lda) # 0x0200 <-- Load the byte 0x02 into register VA
f.write(ldb) # 0x0202 <-- ... |
#!/usr/bin/env python2
#
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
BUNDLE_BUCKET = '${BUNDLE_BUCKET}'
NOREPLY_EMAIL = '${NOREPLY_EMAIL}'
FAILURE_EMAIL = '${FAILURE_EMAIL}'
|
# Push Bullet API Token Here
# https://www.pushbullet.com/#settings/account
login = {
'pushbullet_api_token' : 'ITSASECRET',
'hassio_password' : 'ITSASECRET'
} |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains", "rust_repository_set")
load("//third_party/rust/crates:crates.bzl", "raze_... |
'''__init__.py'''
__version__ = '21.40.2dev'
version = '21w40b-dev'
|
# Comments are lines that exist in computer programs that are ignored by
# compilers and interpreters.
#
# Including comments in programs makes code more readable
# for humans as it provides some information or explanation
# about what each part of a program is doing.
#
# In general, it is a good idea to write c... |
# 9.23
def find_happy_number(num):
# TODO: Write your code here
fastSum, slowSum = num, num
while True:
# currSum = sumOfSqaures(fastSum)
# nextSum = sumOfSqaures(fastSum)
# if currSum == 1 or nextSum == 1:
# return True
fastSum = sumOfSqaures(sumOfSqaures(fastSum))
slowSum = sumOfSqaur... |
# Given a binary tree, flatten it to a linked list in-place.
# For example, given the following tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Hints:
# If you notice caref... |
# MiClase tendrá un constructor alternativo, que usará una lista en lugar de una cadena
class Persona:
def __init__(self, nombre=''):
self.nombre = nombre
@classmethod
def fromList(cls, l):
# Instanciamos un nuevo objeto de la clase
x = cls()
# Lo rellenamos y lo devolvemo... |
INFURA_PROJECT_ID = 'FILL_YOUR_KEY'
# Networks
# Rinkeby
NETWORK = 'rinkeby'
PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY'
# ETH mainnet
# NETWORK = 'mainnet'
PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY' |
class UnchainedException(Exception):
def __init__(self):
super(UnchainedException, self).__init__(self.message)
class DoesntExist(UnchainedException):
message = "Attempting to get data by a key that doesn't exist"
|
MODELS = [
'ConvLSTM',
'ConvLSTM_REF',
'LSTM'
]
DATASETS = [
'GeneratedSins',
'GeneratedNoise',
'Stocks',
'MovingMNIST',
'KTH',
'BAIR'
]
KTH_CLASSES = [
'boxing',
'handclapping',
'handwaving',
'jogging',
'running',
'walking'
]
OPTS = {
'model': {
... |
# -*- coding: utf-8 -*-
# http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address
REGEX_IPADDR = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
REGEX_HOSTNAME = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-... |
# -*- coding: utf-8 -*-
"""
BuzzlogixTextAnalysisAPILib.Configuration
This file was automatically generated for buzzlogix by APIMATIC BETA v2.0 on 12/06/2015
"""
class Configuration :
# The base Uri for API calls
BASE_URI = "https://buzzlogix-text-analysis.p.mashape.com"
|
'''https://leetcode.com/problems/generate-parentheses/'''
#iterative solution
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
stack = [("(", 1, 0)]
while stack:
x, l, r = stack.pop()
if r>l or l>n or r>n:
continue
... |
# Ex. 086 +=
matriz = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for i in range(3):
for j in range(3):
matriz[i][j] = int(input(f"Digite um valor para a posição [{i}, {j}]: "))
print("-" * 30)
for linha in matriz:
for coluna in linha:
print(f"[{coluna:^5}]", end=" ")
print()
|
celsius = [0.7, 2.1, 4.2, 8.2, 12.5, 15.6, 16.9, 16.3, 13.6, 9.5, 4.6, 2.3] #Durschnittstemperaturen Bielefeld
# Liste Umrechnung in Fahrenheit erzeugen (FOR-Schleife)
wertefahrenheit = []
for wertecelsius in celsius:
wertefahrenheit.append(round((wertecelsius*1.8)+32, 2)) # F = C*1.8 + 32 C = (F-32)/1.8... |
"""
Merge two sorted linked lists and return it as a new list. The new list should
be made by splicing together the nodes of the first two lists.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
... |
def bumpVersion(file_loc, which="patch", dry_run = False, all_matching_lines = False, write_loc = None):
if which not in ["major", "minor", "patch"]:
print(f"Argument must be one of major, minor, or patch, instead was {which}")
raise ValueError(which)
with open(file_loc, "r") as f:
lines = []
lines... |
INTERSECTION_SIZE = 9 # number of pixels; any odd number should work (cars will be VERY thin though)
# very customized functions, may not be perfect for every layout
def make_grid(grid_cols, grid_rows, scale_factor, segment_len=100, margin=20):
margin = margin + segment_len
return {"render_screen_size": (mar... |
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
'''
Python program to find the number of zeros at the end of a factorial of a given positive number
'''
def factendzero (n):
factorial = 1
x = n // 5
y = x
if n < 0:
print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
... |
# coding: utf-8
days = '周一 周二 周三 周四 周五 周六 周日'
months = '\n一月\n二月\n三月\n四月\n五月\n六月\n七月\n八月\n九月\n十月\n十一月\n十二月'
print('Here are the days:', days)
print('Here are the months:', months)
print('''
1. 前端
2. 后端
3. 设计
4. 测试
''')
|
class ReplayBuffer(object):
pass
|
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
"""Project Euler problem 7"""
def is_prime(number):
"""Returns True if the specified number is prime"""
if number <= 1:
return False
count = 2
while count ** 2 <= number:
if number % count == 0:
return False
count += 1
return True
def calculate(last_prime):
... |
shelf = input().split("&")
line = input().split(" | ")
while line[0] != "Done":
command = line[0]
book = line[1] # може и е по-добре да е тук, за да не се повтаря на всякъде
if command == "Add Book":
# for book in line[1:]: излишно e
if book not in shelf:
shelf.insert(0, book)... |
nome = str(input('Qual é o seu nome? '))
if nome == 'Denis':
print('Que nome lindo!')
elif nome == 'Joao' or nome == 'Maria' or nome == 'Paulo':
print('Seu nome é comum demais.')
elif nome in 'Ana, Julia, Mariana, Julia':
print('Seu nome é lindo demais!')
print('Tenha um ótimo dia, {}.'.format(nome)) |
# Description
# The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
# Given two integers x and y, calculate the Hamming distance.
# Example
# Input: x = 1, y = 4
# Output: 2
class Solution:
"""
@param x: an integer
@param y: an integer
... |
def init_lst():
return [i for i in range(0, 256)]
class KnotTier:
def __init__(self):
self.pos = 0
self.skip = 0
def tie_a_knot(self, start, length, lst):
if length < 2:
return
end = (start + length - 1) % len(lst)
lst[start], lst[end] = lst[end], lst[s... |
#
# PySNMP MIB module TPT-ATA-REG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-ATA-REG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:26:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#!/usr/bin/python3
def test_ternery1(evmtester, branch_results):
evmtester.terneryBranches(1, True, False, False, False)
results = branch_results()
assert [2582, 2583] in results[True]
assert [2610, 2611] in results[False]
evmtester.terneryBranches(1, False, False, False, False)
results = bra... |
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
answer = []
keypad = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
def helper(prefix, idx):
# reached end of this current backtrack and isn't just ''
... |
class baseparser:
"""
Parser interface.
"""
def parse_file(self, source):
"""
Parses a Graph from an OSM file.
This is the preferred way for parsing when on execution mode.
parse_file(source) -> graph
@type source: string
@param sou... |
def parse_page_obj(raw_obj):
return {
"wiki_db": raw_obj['wiki_db'],
"event_entity": raw_obj['event_entity'],
"event_type": raw_obj['event_type'],
"event_timestamp": raw_obj['event_timestamp'],
"event_comment": raw_obj['event_comment'],
"event_user": {
"i... |
while True:
try:
user_input = int(input("Please enter a integer between 0 to 1000: "))
except:
print("Please enter a numeric value")
continue
if user_input < 1:
print("Please enter a positive integer")
continue
break
if (user_input % 2) == 0:
print("Th... |
"""
Tangerine Whistle Utility Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. contents:: Table of Contents
:backlinks: none
:local:
Introduction
------------
Utility functions used in this tangerine whistle version of specification.
"""
|
"""
1100 : 하얀 칸
URL : https://www.acmicpc.net/problem/1100
Input :
.F.F...F
F...F.F.
...F.F.F
F.F...F.
.F...F..
F...F.F.
.F.F.F.F
..FF..F.
Output :
1
"""
chess = []
for i in range(8):
chess.append(input())
count = 0
for i, row... |
run = ['''
<PhysicsModeling>:
name: "physicsmodel"
# canvas.before:
# Color:
# rgb: .2, .2, .2
# Rectangle:
# size: self.size
# source: '/background.png'
# this below is variables in the .py file being assigned to the id's
# below in the .kv file here to al... |
"""
The dependencies for running the gen_rust_project binary.
"""
load("//tools/rust_analyzer/raze:crates.bzl", "rules_rust_tools_rust_analyzer_fetch_remote_crates")
def rust_analyzer_deps():
rules_rust_tools_rust_analyzer_fetch_remote_crates()
# For legacy support
gen_rust_project_dependencies = rust_analyzer_d... |
class Solution:
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
while tx >= sx and ty >= sy:
tx, ty = tx % ty, ty % tx
return sx == tx and (ty - sy) % sx == 0 or... |
# The following function returns by recursion the length L of the longest palindromic substring of a given string s
def lps(s):
n = len(s)
# basic cases: L = 0 if s is an empty substring, L = 1 if s has only one character
if n == 0 or n == 1:
L = n
# the recursion goes a... |
#Einfügen von "get"- und "set"- Methoden für private Attribute
#Es ist anscheinend besser mit der "get"- und "set"-Funktion zu arbeiten
class Behaelter(object):
def __init__(self, volumen):
self.__volumen = float(volumen)
def setVolumen(self, neues_Volumen):
self.__volumen=floa... |
"""Used to single sourcing metadata about caluma."""
__title__ = "caluma"
__description__ = "Caluma Service providing GraphQL API"
__version__ = "2.0.0"
|
f = open('/home/bu807/Downloads/keras-yolo3-master2/keras-yolo3-master2/result/result.txt',encoding='utf8')
s = f.readlines()
result_path ='/home/bu807/Downloads/keras-yolo3-master2/keras-yolo3-master2/mAP-master/input/detection-results/'
for i in range(len(s)): # 中按行存放的检测内容,为列表的形式
r = s[i].split('.jpg ')
fil... |
#!/usr/bin/python
def displayPathtoPrincess(n, grid):
# print all the moves here
counter = 1
for row in grid:
if 'p' in row:
px = row.index('p') + 1
py = n - counter + 1
if 'm' in row:
mx = row.index('m') + 1
my = n - counter + 1
count... |
def profile_update(request):
user = request.user
if request.method == 'POST':
form = UpdateProfile(
request.POST, request.FILES or None, instance=request.user,)
if form.is_valid():
username = form.cleaned_data.get('username')
obj = form.save(commit=False)
... |
try:
error= open("dummy.txt","r")
print(error.read())# perform file operations
finally:
error.close()
|
init_code = """
if not "Friends" in USER_GLOBAL:
raise NotImplementedError("Where is 'Friends'?")
Friends = USER_GLOBAL['Friends']
"""
PASS_CODE = """
RET['code_result'] = True, "Ok"
"""
def prepare_test(middle_code, test_code, show_code, show_answer):
if show_code is None:
show_code = middle_code
... |
__author__ = 'Sushant'
class ClusterIndices(object):
@staticmethod
def calculate_EI_index(graph, cluster_nodes, standardize=True):
all_edges = graph.get_edges()
external_connections_strength = 0.0
internal_connections_strength = 0.0
internal_nodes = len(cluster_nodes)
e... |
num = int(input('Enter a number: '))
x = 0
y = 1
# 0 1 1 2 3 5 7
z = x + y
for i in range(num):
print(z)
x = y
y = z
z = x + y
|
# This is an input class. Do not edit.
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Solution
# O(n) time / O(h) space
# n - number of nodes in the binary tree
# h - height of the binary tree
class TreeInfo:
... |
'''
33. Search in Rotated Sorted Array Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no du... |
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "com_fasterxml_jackson_core_jackson_annotations",
artifact = "com.fasterxml.jackson.core:jackson-annotations:2.9.0",
artifact_sha256 = "45d32ac... |
uni_cars = set()
while True:
command = input()
if command == 'END':
break
else:
direction, plate = command.split(', ')
if direction == 'IN':
uni_cars.add(plate)
elif direction == 'OUT':
if plate in uni_cars:
uni_cars.remove(p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
opticalIsomers = 1
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS8c_f12.out'),
#'CCSD(T)-F12/cc-pVTZ-F12': -382.9338341073141
}
frequencies = GaussianLog('TSfreq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), ... |
def arrayMode(sequence):
count = []
answer = 0
for i in range(10):
count.append(0)
for i in range(len(sequence)):
count[sequence[i] - 1] += 1
if count[sequence[i] - 1] > count[answer]:
answer = sequence[i] - 1
return answer+1
|
# encoding=utf-8
_KANA_LOW = ord('ぁ')
_KANA_HIGH = ord('ゖ')
_KANA_DIFF = ord('ア') - ord('あ')
def lower_kana(ch):
code = ord(ch)
if _KANA_LOW <= code <= _KANA_HIGH:
return chr(code + _KANA_DIFF)
return ch
def lower_kanas(u):
return ''.join([lower_kana(ch) for ch in u])
_FULL_WIDTH_LOW = ord... |
async def get_params(request):
method = request.method
if method == 'POST':
params = await request.post()
elif method == 'GET':
params = request.rel_url.query
else:
raise ValueError("Unsupported HTTP method: %s" % method)
return params
|
def maybeBuildTrap(x, y):
hero.moveXY(x, y)
if hero.findNearestEnemy():
hero.buildXY("fire-trap", x, y)
while True:
maybeBuildTrap(20, 34)
maybeBuildTrap(38, 20)
maybeBuildTrap(68, 34)
|
def binary_search(array, x, low, high):
while low < high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [12, 15, 17, 24, 56, 89, 90]
x = 24
result = bina... |
print ("hola word")
nome = input('Nome: ')
sobrenome = input()
email = input ()
print (nome,"\n Sobrenome:",sobrenome,"\n E-mail:",email) |
# coding: utf-8
n = int(input())
d = [int(i) for i in input().split()]
s, t = [int(i) for i in input().split()]
if s > t:
s, t = t, s
circu = sum(d)
len1 = sum(d[s-1:t-1])
len2 = circu-len1
print(min(len1,len2))
|
#makes a smaller dataset for testing
n = 20000
with open("tests/data/combined_data_3.txt", "r") as f:
lines = f.readlines()
print(len(lines))
with open("tests/data/combined_data_3_small.txt", "w") as f:
for i in range(n):
f.write(lines[i])
|
class WorkflowCommand(object):
def __init__(self, command, arguments):
self._command = command
self._arguments = arguments
def encode(self):
return {'command': self._command, 'arguments': self._arguments}
class SkipPhasesUntilCommand(WorkflowCommand):
COMMAND = 'skip_phases_until'... |
#TODO move whole class to IBDT.py
MOVEMENT = {'FIXATION':0,
'SACCADE':1,
'PURSUIT':2,
'NOISE':3,
'UNDEF':4
}
class GazeDataEntry():
"""Helper class
IS a data sample with only 4 values: timestamp, eyetracking quality confidence, X and Y coordina... |
# # O(n^2) time | O(n) space
# brute force
class MyClass:
def __init__(self, string:str) -> bool:
self.string = string
def isPalindrome(self):
reversedString = ""
for i in reversed(range(len(self.string))):
reversedString += self.string[i] # creating newString -> increase... |
#1
def RemoveDuplicates(arr: list) -> list:
if len(arr) <= 1:
return arr
else:
i = 1
n = len(arr)
while i < n :
if arr[i] == arr[i-1]:
arr.pop(i)
n -= 1
continue
i += 1
return arr
print(RemoveDuplicates([1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,6,6,7,8]))
|
def potencia(func):
def wrapper(voltaje, resistencia):
intensidad = func(voltaje, resistencia)
potencia = intensidad*voltaje
print(f"La intensidad es {intensidad} A")
print(f"La potencia es {potencia} W")
return wrapper
@potencia
def corriente(voltaje, resistencia):
return v... |
Pi1 ='10.0.0.1'
Pi2 ='10.0.0.2'
Pi3 ='10.0.0.3'
Pi4 ='10.0.0.4'
Pi5 ='10.0.0.5'
Pi6 ='10.0.0.6'
GW1 ='10.0.0.8'
GW2 ='10.0.0.9'
R1=[GW1,Pi1]
R2=[GW1,Pi4]
R3=[Pi1,Pi4]
R4=[Pi1,Pi2]
R5=[Pi4,Pi5]
R6=[Pi2,Pi5]
R7=[Pi3,Pi2]
R8=[Pi6,Pi5]
R9=[Pi3,Pi6]
R10=[GW2,Pi3]
R11=[GW2,Pi6]
N = 10
S1=[R1]
S2=[R2]
S3=[R3,R9]
S4=[R4]
S5... |
BASE_ENS = 'https://www2.agenciatributaria.gob.es/ADUA/internet/es/aeat/dit/adu/aden/'
ADUANET_SERVICES = {
'ens_fork': {
'verbose_name': 'Servicio Solicitud Desvío ENS V5.0',
'wsdl': f'{BASE_ENS}enswsv5/IE323V5.wsdl',
'operation': 'IE323V5',
'port_production': 'IE323V5',
'p... |
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
# the magic function that makes it all work.
# wow, it took forever to get this right.
def recursive_constru... |
def should_discard_line(l):
patterns = ['${PROJECT_NAME}_tests', '${PROJECT_NAME}_cli', '${PROJECT_NAME}_shared', 'CONFIGURATION_DUMMY']
for p in patterns:
if p in l:
return True
return False
f = open('botan/CMakeLists.txt', 'r')
content = f.read()
f.close()
f = open('botan/CMakeLists.txt', 'w')
for l in co... |
"""Stores some global constants, mostly to save on a lot of repetitive arguments.
These are mostly of interest for demonstrating different variants of the algorithms as discussed
in the accompanying article."""
# Both marching cube and dual contouring are adaptive, i.e. they select
# the vertex that best describes th... |
class phase_cavity_sys:
def __init__(self):
"""Creating all the variables that are common to all phase cavities"""
self.Prog_name = []
self.Cav_Set = [] # Number of pairs of pcavs really two caviy makes up one system
self.Cav_Num = [] # Number of cavities
self.Cav_RF_Freq = [] # Cavity RF frequency
self.... |
class Solution:
# @param {integer} numRows
# @return {integer[][]}
def generate(self, numRows):
res = []
row = []
for i in range(0,numRows):
n = len(row)
row =[1]+[row[j-1] + (row[j] if j<n else 0) for j in range(1,n+1)]
res.append(row)
ret... |
def main(x):
max_test = 2000
is_negative = False
if (x < 0):
is_negative = True
x = abs(x)
x = round(x, 16)
test = int(x - 1)
for i in range (test, max_test):
for j in range (1, max_test):
if (x == i/j):
if is_negative:
print('-... |
#!/home/jepoy/anaconda3/bin/python
def main():
f = open('lines.txt', 'r') # 'w' write - rewrites over the file # a append add to the end of the file
for line in f:
print(line.rstrip())
f.close()
if __name__ == '__main__':
main() |
class TrackingFieldsMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._old_fields = {}
self._set_old_fields()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
result = super().save(force_insert, force_updat... |
_PAD = "_PAD"
_GO = "_GO"
_EOS = "_EOS"
_UNK = "_UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]
PAD_ID = 0
GO_ID = 1
EOS_ID = 2
UNK_ID = 3
OP_DICT_IDS = [PAD_ID, GO_ID, EOS_ID, UNK_ID] |
"""Subcommand won't stop complaining about jupyterlab-git."""
# Configuration file for jupyter serverextension.
# ------------------------------------------------------------------------------
# Application(SingletonConfigurable) configuration
# ------------------------------------------------------------------------... |
fp = open('greetings.txt','w')
fp.write("Hello, World!\n")
fp.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.