content stringlengths 7 1.05M |
|---|
"""
File: file_lines.py
Prompts the user for a file name, then reads
the file and outputs the number of lines.
After this, the user can enter a line number, and
the program returns what is on that particular line
"""
input_filename = 'Enter a file name: '
f = open(input_filename, 'r')
lines = f.read().splitlines()
... |
#
# PySNMP MIB module NTNTECH-NMS-TRAPS-V1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NTNTECH-NMS-TRAPS-V1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
config = {
"--acoustic-scale":[0.1,float],
"--allow-partial":["false",str],
"--beam":[13,int],
"--beam-delta":[0.5,float],
"--delta":[0.000976562,float],
"--determinize-lattice":["true",str],
"--hash-ratio":[2,int],
"--latti... |
tape5 = """\
-1
-1
-1
CUT 5 {CUT_OFF} -1
RDA FIND CROSS SECTION LIBRARY IDENTIFIER NUMBERS IN YOUR LIBRARY FILE
LIB 0 1 2 3 {NLB1} {NLB2} {NLB3} 9 3 0 3 0
OPTL 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
OPTA 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
OPTF 8 8 8 8 7 8 8 8... |
"""
Usecases with Python 3 syntax in the signatures. This is a separate module
in order to avoid syntax errors with Python 2.
"""
class TestClass1(object):
def __init__(self, x, y, z=1, *, a=5):
self.x = x
self.y = y
self.z = z
self.a = a
class TestClass2(object):
def __init_... |
#
# This file is part of SNMP simulator Control Plane software.
#
# Copyright (c) 2019-2020, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpsim/license.html
#
# SNMP Agent Simulator: REST API management server
#
class DefaultConfig(object):
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory'
SQ... |
expected_output = {
"total_num_of_entries": {
"arp_table_entries": 100409,
"dynamic_arp_entries": 100204,
"incomplete_arp_entries": 0,
"interface_arp_entries": 205,
"static_arp_entries": 0,
"alias_arp_entries": 0,
"simple_application_arp_entries": 0,
},
... |
#
# PySNMP MIB module RAQMON-RDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-RDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:52:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: he... |
class Runner:
def __init__(self, installer):
self.installer = installer
installer.set_runner(self)
pass
def process(self):
return True
def key_event(self, keys):
return True
|
# Unlike with a stack, the performance implication of using a Python list as a queue is
# significant. The implementation shown below uses insert(0, item) to enqueue a new item,
# which will be an O(n) operation.
# many Python programmers will use the standard library’s collections.deque class
# to achieve O(1)O(1) en... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the first node in the cycle in the linked list
def detectCycle(self, root):
if root is None... |
S = input()
N = len(S)
dp = [[0] * 2 for _ in range(N + 1)]
if N == 1:
print(1)
exit()
if S[0] == S[1]:
dp[0][0] = 0
dp[1][1] = 1
dp[0][1] = 1
dp[1][0] = 1
else:
dp[0][0] = 0
dp[0][1] = 1
dp[1][0] = 1
dp[1][1] = 2
for i in range(2, N):
if S[i - 1] != S[i]:
dp[i][1]... |
birdsnap_classnames = [
"Coopers Hawk", "Northern Goshawk", "Sharp shinned Hawk", "Golden Eagle", "White tailed Hawk", "Zone tailed Hawk",
"Red tailed Hawk", "Rough legged Hawk", "Red shouldered Hawk", "Broad winged Hawk", "Ferruginous Hawk",
"Swainsons Hawk", "Common Black Hawk", "Northern Harrier", "Swall... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
s1 = "concord"
s2 = "souix city"
s3 = "HONOLULU"
s4 = "TopHat"
print(s1.capitalize())
print(s2.swapcase())
print(s2.upper())
print(s3.lower())
print(s4.title()) |
def format_title(title, row_len, sep):
rem = row_len - len(title) # How many spaces available?
left = (rem//2) * sep
right = (rem-len(left)) * sep
return '{}{}{}'.format(left, title, right)
def get_widest_cols(data):
# Get number of columns and rows
num_rows = len(data)
num_cols = len(dat... |
num = int(input("Digite um número inteiro e descubra se ele é par ou impar: "))
n = num % 2
if n == 0:
print("Você digitou {}, e ele é PAR".format(num))
else:
print("Você digitou {}, e ele é IMPAR".format(num))
|
class Node:
"""
Node object for a linked list class
"""
def __init__(self, val):
self.val = val
self.next = None
def set_next(self, next_):
self.next = next_
def get_next(self):
return self.next
def get_val(self):
return self.val
def set_val(s... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 10106.py
# Description: UVa Online Judge - 10106
# =============================================================================
while True:... |
## FROM GEEKS4GEEKS
def K(V, W, C, n):
# base case
if n == 0 or C == 0:
return 0
# if any item in the weights arr > capacity it cannot be included so we skip the index with n-1
if W[n-1] > C:
return K(V, W, C, n-1)
else:
return max(V[n-1] + K(V, W, C-W[n-1], n-1), # ca... |
"""Monkey patch H11 to ensure that it sends headers the way the SkyQ box wants them to be."""
def write_headers_titlecase(headers, write):
"""Monkey-patch h11 header handling.
See https://github.com/python-hyper/h11/issues/31 for the details. Essentially SkyQ box is
not RFC compliant as regards case-insen... |
class ApplicationInfo:
def __init__(self, application_id = None, application_instance_id = None, application_domain_name = None,
application_class_name = None, application_name = None, application_version = None,
application_stage = None, application_runtime = None,
application_runtime... |
'''
This program calculates the factorial of a number.
It is an example program for the Pylint poster.
The function name doesn't follow the snake case.
'''
def computeFactorial(num):#pylint: disable=invalid-name
'''Returns the factorial of a number.'''
if num == 1:
return 1
return num*computeFactori... |
"""This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has... |
print('Hello World')
sauce = 'tomato'
order_description = """
Blah blah blah
"""
if sauce.startswith('toma'):
print("It's probably tomato..")
else:
print("Not tomato")
print(order_description)
|
"""
Functions for popular string operations.
The purpose of this module is to allow students to work with strings without having to
understand method calls. We do not provide all string methods as functions -- just the
most popular ones.
The functions that would normally return lists return tuples. That is because,... |
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum... |
class Day():
def __init__(self, data_path):
with open(data_path, "r") as file:
for line in file:
self.instructions = line.strip()
def part1(self):
floor = 0
for char in self.instructions:
if char == '(':
floor += 1
elif... |
# OpenWeatherMap API Key
weather_api_key = "d3bc8c276acb9f0ad7660e4353716e90"
# Google API Key
g_key = "AIzaSyDibsDuYSaDy7VFjswzeuRETk5kiCuRBhs"
|
'''
Created on 31 Mar 2017
@author: Federico Cerutti <federico.cerutti@acm.org>
'''
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def isint(value):
try:
int(value)
return True
except ValueError:
return False |
"""This module contains API-related exceptions."""
class APIError(Exception):
"""An exception denoting generic API errors.
This error is raised when the API returns invalid
response data, like invalid JSON.
"""
pass
class EmptyResponseError(APIError):
"""An exception denoting an empty API ... |
# Custom Functions:
def list_print(subject, dest=None):
for dia in subject:
if dest is not None:
print(dia, file=dest)
else:
print(dia)
# Creating the data to be saved.
man = []
other = []
try:
data = open('sketch.txt')
for line in data:
try:
... |
def bmi_calculator(height, weight):
return (weight/(height**2)) * 702
# Write 4 unit tests and check that at least 2 of them are testing edge cases
# There are many different tests that could have been written for this question.
# Here are a few examples.
assert bmi_calculator(1, 1) == 702.0, 'Input arguments g... |
# Source and destination file names.
test_source = "dangerous.txt"
test_destination = "dangerous.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html"
# Settings
settings_overrides['file_insertion_enabled'] = False
settings_overrides['raw_enabled'] = Fa... |
class Bank1Account(object):
tax = 1.0
def __init__(self, number):
self.number = number
self.__total = 0
def deposit(self, value):
self.__total += value
def withdraw(self, value):
self.__total -= value
# self.__total -= 1
self.__total -= type(self).tax
... |
#!/usr/bin/python3
""" Module of a inherited class Rectangle"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
""" Class inherited form BaseGeometry """
def __init__(self, width, height):
""" Initializes a new object Rectangle """
super().integer_valid... |
"""matplotlib rc params for APS journals
Gives a dictionary with the proper sizes for APS journals.
Modified from:
- M.V. DePalatis, 2010-09-01. Licensed under the GNU GPL v3
- http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
Examples
--------
>>> import pylab
>>> from pylab import arange, pi, sin, co... |
# Copyright (c) IBM Corporation and Others. All Rights Reserved.
# very loosely based on icu.gyp from Chromium:
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'icu_src_derb': [... |
len,m=map(int,input().split())
tree=[0 for i in range(len+1)]
for i in range(m):
l,r=map(int,input().split())
tree[l]+=1
tree[r]-=1
sum=0
flag=0
for i in tree:
if i==0 and flag==0:
sum+=1
else:
flag+=i
print(sum) |
#!/usr/bin/env python
'''Provides an Extruder base class for the RepRap.
All extruders extend this class, and can therefore be chosen by the
user at runtime.
Copyright 2011 Joseph Lewis <joehms22@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Pub... |
# Beautiful Pairs
# Change an element of B and calculate the number of pairwise disjoint beautiful pairs.
#
# https://www.hackerrank.com/challenges/beautiful-pairs/problem
#
def beautifulPairs(A, B):
# compte les nombres de A
n = [0] * 1001
for i in A:
n[i] += 1
# compare avec les nombres de B... |
class ApiSidebar():
def __init__(self, hass, cfg):
self.hass = hass
@property
def panel(self):
return self.hass.data.get("frontend_panels", {})
def remove(self, _path):
if _path in self.panel:
self.hass.components.frontend.async_remove_panel(_path)
def add(se... |
nomes = ['CARLOS', 'JOAO', 'PEDRO']
idades = ['30', '25', '22']
rows = len(nomes)
for i in range(rows):
print(nomes[i] + ":" + idades[i])
#https://pt.stackoverflow.com/q/414318/101
|
while 1:
user_number = int(input("Entersitive number: "))
if user_number > 0:
break
print("Do somet7hing with number!")
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class Weather:
def __init__(self, temp):
self.temp = temp
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Application:
def __init__(self):
pass
def get_webpage(self):
print('From application')
clas... |
"""
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl", "thrift_interface")
load("@fbcode_macros//build_defs/lib:haskell_common.bzl", "haskell_common")
load("@fbcode_macros//build_defs/lib:haskell_rules.bzl", "haskell_rules")
load("@fbcode_macros//build_... |
def zero_fuel(distance_to_pump, mpg, fuel_left):
#Happy Coding! ;)
if distance_to_pump<=fuel_left*mpg:
return 1
else:
return 0
|
[ ## list of dictionnaries for different arities of the same functor
{
'functor' : { ## intrinsics values related to functor
'arity' : 2, ## functor number of parameters
#'ret_arity' : "2", ## must be '0' or omitted if not a tuple
'types' : ['real_'],##, 'unsigned_int_', 'sign... |
# Sphinx uses the all list to check every module is loaded, but in some cases it is not and a warning is generated:
# missing attribute mentioned in :members: or __all__: module
"""Allows users to do ``from xyz import *`` """
__all__ = ["couchdb", "mongodb"]
|
print("Dados da primeira pessoa")
nome1 = input("Nome: ")
idade1 = int(input("Idade: "))
print("Dados da segunda pessoa ")
nome2 = input("Nome: ")
idade2 = int(input("Idade: "))
media = (idade1 + idade2) / 2
print(f"A idade media de {nome1} e {nome2} e de {media:.1f} anos") |
#!/usr/bin/env python3
def DAfromTopWdth(TopWdth):
return (TopWdth/2.44) ** 2.941176470588235
def CSA(DA):
return 0.75 * DA ** 0.53
def cross_section_area_BlckBrn(TopWdth):
'''
Calculate channel cross sectional area from channel Top Width using Blackburn et
al. 2017 equations
'''
cs_area ... |
# %%
#caesar cipher
class his_cip:
def __init__(self):
self.alf = "abcdefghijklmnopqrstuvwxyz"
self.alf2 = self.alf*2
self.len_ = len(self.alf)
def caesar_enc(self,plaintext,key):
ciphertext = ""
alpha = self.alf*2
#replace dots and getting all in lower ... |
# /xhr/resources/conditional.py -- to fake a 304 response
def main(request, response):
tag = request.GET.first(b"tag", None)
redirect = request.GET.first(b"redirect", None)
match = request.headers.get(b"If-None-Match", None)
date = request.GET.first(b"date", b"")
modified = request.headers.get(b"If... |
"""
For more details regarding inputs and output in form of complex dictionaries see the original source docs at:
%host%/docs/source/ProjectInterface.html
for example:
`https://editor.webgme.org/docs/source/ProjectInterface.html <https://editor.webgme.org/docs/source/ProjectInterface.html>`_
"""
class P... |
__title__ = 'emailer'
__description__ = 'Send scheduled emails'
__url__ = 'https://github.com/WhiteHalmos/emailer'
__author__ = 'Peter Wen'
__author_email__ = 'peter@whitehalmos.org'
__license__ = 'MIT'
__version__ = '1.0.17-dev'
|
def runLengthEncoding(string):
curr_mult = 1
new_str = []
for i in range(len(string) - 1):
if string[i] != string[i + 1] or curr_mult == 9:
new_str.append(str(curr_mult) + string[i])
curr_mult = 1
else:
curr_mult += 1
return ''.join(new_str + [str(cu... |
ASSETS = [
{
"name": "Very Conservative Streep",
"id": 15077
},
{
"name": "Conservative Clooney",
"id": 188
},
{
"name": "Moderate Pit",
"id": 187
},
{
"name": "Risky Norris",
"id": 186
}
]
|
#!/usr/bin/python
# /****************************************************************************
# exportKML
# Copyright (c) 2014-2018, Kjeld Jensen <kj@kjen.dk>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... |
'''
URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/
Difficulty: Easy
Description: Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with... |
class B:
def __init__(self,a,b,c,**others):
self.a = a
self.b = b
self.c = c
def verify(self):
print(self.a,self.b,self.c)
args = {'a':10,'b':20,'c':30,'extra':'unexpected'}
x = B(**args)
x.verify()
|
for _ in range(int(input())):
n = int(input())
_n = int(str(n)[::-1])
res = str(n + _n)
print('YES' if res == res[::-1] else 'NO')
|
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
class map_output_transform:
def __init__(self, video_level=False):
self.video_level = video_level
def __call__(self, output):
probs, y_mh, ids = output
if self.video_level:
ids = [x.rsplit("... |
# 文件名: var.py
i = 5
print(i)
i = i + 1
print(i)
s = '''This is a multi-line string.
This is the second line.'''
print(s) |
input = """120183
105169
58942
105283
100729
57778
59601
86011
148930
76533
132625
79105
66334
87695
148836
129384
71225
96010
67221
139037
90010
72531
145543
137983
63687
131307
62602
129223
76717
98896
58484
127996
128840
60723
149932
141443
96997
96196
104670
104055
129552
54426
104507
80241
91570
140053
106108
1197... |
def test_command_char():
assert True # Placeholder
|
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, login, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_xpath("//*[@id='username']").send_keys(login)
wd.find_element_by_css_selector(".width-40").click()
wd.fi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'leetcode'
__file__ = '__init__.py'
__author__ = 'king'
__time__ = '2020/1/9 17:34'
_ooOoo_
o8888888o
88" . "88
(| -_- |)
... |
W=lambda A:(ord(A[0])-ord('A'))*26*26+(ord(A[1])-ord('A'))*26+(ord(A[2])-ord('A'))
for _ in range(int(input())):
A,B=input().split('-')
if abs(W(A)-int(B))<=100: print('nice')
else: print('not nice') |
for _ in range(int(input())):
n,k=map(int,input().split())
n1=n
arr=list(map(int,input().split()))
maxe=max(arr)+1
arr.sort()
k1=k
while(k1):
k1-=1
arr.append(maxe)
print(arr[(n1+k)//2])
|
# coding: utf-8
create_app_validate = {
"type": "object", "properties": {
"name": {"type": "string"},
"nick_name": {"type": "string"},
"env_id": {"type": "string"}
},
"required": ["name", "nick_name", "env_id"],
"additionalProperties": True
}
update_application_validate = {
... |
# -*- coding: utf-8 -*-
tables_and_views = [
{
"schema_object_id": 16441,
"table_schema": "app",
"table_object_id": 16442,
"table_name": "customers",
"table_type": "base table",
"properties": {},
"columns": [
{
"column_object_id":... |
#Exercício Python 094: Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: A) Quantas pessoas foram cadastradas B) A média de idade C) Uma lista com as mulheres D) Uma lista de pessoas com idade acima d... |
outFile = open('cdf_transcription.sub.format.csv','w')
with open('cdf_transcription.sub.tsv','r') as inFile:
firstLine = inFile.readline().split()
firstLine = ','.join(firstLine)
outFile.write(firstLine)
for line in inFile:
line = line.split()
gene = line[0].split('|')[0]
entry = [gene]
for x in line[1... |
class Data:
def __init__(self, alrd, v, score, cin, vv):
self.alrd = alrd
self.v = v
self.score = score
self.cin = cin
self.vv = vv
|
#! /usr/bin/env python
__author__ = "Andy Tsang"
__credits__ = ["Andy Tsang"]
__version__ = "0.0.0"
__maintainer__ = "Andy Tsang"
__email__ = "atc1992andy@gmail.com"
class PyQueue():
"""
Queue with peek function
"""
# https://hg.python.org/cpython/file/2.7/Lib/Queue.py
def __init__(self, maxsize=0):
self.maxsi... |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
print(f'\033[33m{"—"*30:^30}\033[m')
print(f'\033[36m{"EXERCÍCIO Nº 1":^30}\033[m')
print(f'\033[33m{"—"*30:^30}\033[m')
print("Gerador de boas vindas")
nome = input("Digite seu nome de usuário: ")
print (f"Olá {nome}! Bem-vindo ao VS Code")
|
#
# PySNMP MIB module E5-110-AS-ATM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/E5-110-AS-ATM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:58:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# 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, ... |
#
# PySNMP MIB module Wellfleet-IREDUND-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-IREDUND-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
test = {
'name': 'q2_1_2',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Make sure you can use any two movies;
>>> correct_dis = 0.000541242;
>>> dis = distance_two_features("clerks.", "the avengers", "water", "feel");
>>> np.isclose... |
class AverageMeter(object):
'''
computes and stores the average and current value
Example:
>>> loss = AverageMeter()
>>> for step,batch in enumerate(train_data):
>>> pred = self.model(batch)
>>> raw_loss = self.metrics(pred,target)
>>> loss.update(raw_loss... |
# Solution 1
# O(n) time / O(1) space
def findThreeLargetsNumbers(array):
threeLargest = [None, None, None]
for num in array:
updateLargest(threeLargest, num)
return threeLargest
def updateLargest(threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
shiftAndUpdate(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 15:25:24 2019
@author: jonasg
"""
f1 = 'CAM6-Oslo_altRHpiclimaer_od550aer_Column_9999_monthly.nc.csv'
f2 = 'CAM6-Oslo_altRHpiclimaer_od550csaer_Column_9999_monthly.nc.csv'
stats1, stats2 = [], []
with open(f1, 'r') as f:
for line in f:
... |
'''
In a town, there are n people labelled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You a... |
print('Digite dois números, para ver qual é o maior deles')
n1 = int(input('Número 1: '))
n2 = int(input('Número 2: '))
if n1 > n2:
print(f'O primeiro número {n1} é maior que o segundo número {n2}')
else:
print(f'O primeiro número {n2} é maior que o segundo número {n1}') |
# A simple Python3 program
# to calculate Euler's
# Totient Function
# Function to return
# gcd of a and b
def gcd(a, b):
if (a == 0):
return b
return gcd(b % a, a)
# A simple method to evaluate
# Euler Totient Function
def phi(n):
result = 1
for i in range(2, n):
if (gcd(i, n... |
'''Write a console program that enters an integer a and calculates the face of a square with a.'''
a = int(input('a = '))
area = a * a
print('Square =', area)
|
def calc(op, n1, n2):
if op == "+":
return n1+n2
if op == "-":
return n1-n2
if op == "*":
return n1*n2
if n2 == 0:
return "erro"
return n1//n2
n1 = int(input())
op1 = input()
n2 = int(input())
op2 = input()
n3 = int(input())
try:
if op1 != "*" and op1 != "/" and... |
#!/usr/bin/env python3
class Handheld(object):
NOP = 0
JMP = 1
ACC = 2
OP_MAP = { 'nop': NOP, 'jmp': JMP, 'acc': ACC }
def __init__(self):
self._instructions = []
self._acc = 0
self._i = 0
def load_firmware(self, firmware):
self._instructions = []
... |
def givemap():
with open('advent3.txt', 'r') as f:
return [i.replace('\n', '') for i in f.readlines()]
treemap = givemap()
rows = len(treemap)
slopes = [[1,1], [3,1], [5,1], [7,1], [1,2]]
treemult = 1
for slope in slopes:
hindex, vindex = [0,0]
trees = 0
for row in range(rows):... |
_base_ = [
'../_base_/models/ocrnet_hr18.py', '../_base_/datasets/cityscapes.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
# 1. dataset settings
# Modify dataset related settings
classes = (
'background',
'balloon',
'text_format',
'text_effect',
)
dataset_typ... |
# A dictionary stores key-value pairs,
# where each unique key is an index which holds the value associated with it.
# Creating a Dictionary
empty_dict = {} # Empty dictionary
print(empty_dict)
phone_book = {"Batman": 468426,
"Cersei": 237734,
"Ghostbusters": 44678}
print(phone_book)
# d... |
# 6.00 Problem Set 2
#
# Successive Approximation
#
def evaluate_poly(poly, x):
"""
Computes the polynomial function for a given value x. Returns that value.
Example:
# >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2
# >>> x = -13
# >>> print evaluate_poly(poly, x) # f(... |
print('Vou pintar as paredes da minha casa, mas não sei quanto usar de tinta. Então vamos calcular.')
alt = float(input('Qual é a altura da parede? '))
lar = float(input('Qual é a largura da parede? '))
mao = float(input('Quantas demãos serão dada? '))
m2 = alt * lar
ma1 = m2 * mao
t2 = ma1 / 2
print('Sua parede tem um... |
address = "1600 Pennsylvania Ave NW Washington, DC"
# .split() is a string method (a function that works only on strings) that splits a string into a list based on some delimiter.
# In this example, we're splitting address into a list at every space.
address = address.split(" ")
# Address is now a list equal to:
# ['... |
""" Holds constants required by tacorn.
This mostly means paths into the Tacotron 2 and WaveRNN repositories. """
PRETRAINED_ACOUSTIC_MODELS = {
"lj": {"tacotron2": "https://www.dropbox.com/s/kx7ephpl2oj72s3/taco_pretrained.zip?dl=1"}
}
PRETRAINED_WAVEGEN_MODELS = {
"lj": {"wavernn_alt": "https://www.drop... |
def classes():
# think of a class as a blueprint and an object as the constructed counterpart of that blueprint.
# the class can be used multiple times to build the same thing, but each iteration is a unique object.
class FirstClass:
# __init__ is a special constructor method that performs actio... |
"""
Lowest Common Multiple
----------------------
Simple implementation of the Lowest Common Multiple Algorithm.
Pseudo Code: https://en.wikipedia.org/wiki/Least_common_multiple
"""
def lcm(a, b):
"""
Simple version of lcm, that does not have any dependencies.
:param a: Integer
:para... |
class _Break(BaseException):
def __init__(self, tx, commit):
super().__init__()
self.tx = tx
self.commit = commit
class GinoTransaction:
"""
Represents an underlying database transaction and its connection, offering
methods to manage this transaction.
:class:`.GinoTransact... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.