content stringlengths 5 1.05M |
|---|
"""Tests for check_hash function"""
import unittest
from block_chain.utils.check_hash import check_hash
from block_chain.core.hash_chain_node import HashChainNode
class CheckHashTest(unittest.TestCase):
"""Main class for checking check_hash"""
def test_parent_child_hash_success(self):
"""Check if th... |
from pyproj import Proj, transform
# illustrates the use of the transform function to
# perform coordinate transformations with datum shifts.
#
# This example is from Roberto Vidmar
#
# Test point is Trieste, Molo Sartorio
#
# This data come from the Istituto Geografico Militare (IGM), as well as
# the 7 par... |
#!/usr/bin/python3
import re
def target_version():
with open('cffi/recompiler.py', encoding='UTF-8') as f:
for line in f:
m = re.match(r'^VERSION = "(0x[0-9A-F]+)"$', line)
if m:
return int(m.group(1), 16)
raise Exception('Version not found')
def backend_supp... |
from aws_cdk import (
aws_autoscaling as autoscaling,
aws_ec2 as ec2,
aws_ecs as ecs,
App, Stack
)
from constructs import Construct
class ECSCluster(Stack):
def __init__(self, scope: Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, *kwargs)
vpc = ec2.Vpc(
... |
"""
Testing package level reload.
"""
import importlib
# check if modules allready loaded
if not ('testing' in dir()):# load package if it is not yet loaded
from . import testing # must use relative import if same named module
else: # reload package if allready loaded in
importlib.reload(testing)
# init scr... |
# encoding: utf-8
# module Microsoft.Diagnostics.Runtime.Utilities calls itself Utilities
# from Microsoft.Diagnostics.Runtime, Version=2.0.5.1201, Culture=neutral, PublicKeyToken=31bf3856ad364e35
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class COMHelper(object):
""" Base clas... |
# -*- coding: utf-8 -*-
import unittest
import numpy
from sagar.crystal.structure import Cell
# from sagar.io.ase import read, write
class TestCellIO(unittest.TestCase):
def setUp(self):
self.latt = numpy.array([[4, 0, 0],
[0, 4, 0],
[0, ... |
# Copyright 2019 The TensorFlow 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 applica... |
import glob
import os
import shutil
from universal_build import build_utils
from universal_build.helpers import build_python
# Project specific configuration
MAIN_PACKAGE = "opyrator"
GITHUB_URL = "https://github.com/ml-tooling/opyrator"
HERE = os.path.abspath(os.path.dirname(__file__))
def main(args: dict) -> Non... |
import json
import logging
import requests
import datetime
BASE_URL = 'https://tuoficinaonline.repsolluzygas.com/api'
DEFAULT_HEADERS = {
'Market-Type': 'ML',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
}
class RepsolLYG... |
from unittest import TestCase
from games.connect_4 import has_winner, play_game, random_player
class TestTicTacToeX(TestCase):
def test_has_winner(self):
board_state = ((0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(1, 0, ... |
from outsourcer import Code
from .base import Expression
from .constants import RESULT, STATUS
class PythonExpression(Expression):
is_tagged = False
is_commented = False
num_blocks = 0
def __init__(self, source_code):
self.source_code = source_code
def __str__(self):
return f'`{... |
import os
import requests
from flask import make_response
from flask import request
from slackclient import SlackClient
from jama import search
from jama import comment
from jama import oauth
from jama.tools import user_error
from jama.tools import make_dict
from jama.tools import commands_info
from slack import tools... |
from unittest import TestCase
from hw04_paraphrases import small_functions as sf
import numpy as np
class TestSmallFunctions(TestCase):
# Exercise 2.1
def test01a_square_roots(self):
np.testing.assert_almost_equal([2., 2.54950976, 3.], sf.square_roots(4, 9, 3))
# Exercise 2.1
def test01b_squ... |
version = "0.2.24"
|
# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4
# Or download the file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate e... |
"""
:author: Maikel Punie <maikel.punie@gmail.com>
"""
from __future__ import annotations
import json
from velbusaio.command_registry import register_command
from velbusaio.message import Message
COMMAND_CODE = 0xD4
class EdgeSetCustomColor(Message):
"""
send by:
received by: VMB4RYLD
"""
def ... |
# Generated by Django 3.2.8 on 2021-12-14 22:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feed', '0006_post_adult_content'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='adult_content',... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
import re
from abc import ABC, abstractmethod
from textwrap import dedent
from typing import Callable, ClassVar, Iterator, cast
from typing_e... |
"""Tests file for Home Assistant CLI (hass-cli)."""
import json
import unittest.mock as mocker
from unittest.mock import ANY
from click.testing import CliRunner
import requests_mock
import homeassistant_cli.autocompletion as autocompletion
import homeassistant_cli.cli as cli
from homeassistant_cli.config import Confi... |
import cv2
import numpy as np
from .utils import project_points
__all__ = ['triangulate_points',
'filter_triangulated_points',
'filter_matching_inliers']
def triangulate_points(ptsLeft, ptsRight, projL, projR):
"""
Uses Direct Linear Transform (DLT) method to triangulate 3D points f... |
from stable_baselines.ppo.policies import MlpPolicy
from stable_baselines.ppo.ppo import PPO
|
import numpy as np
# Wasserstein distance on the real line
def wasserstein(x, y, p, a=None, b=None):
n = len(x)
m = len(y)
if a is None:
a = np.ones(n) / n
if b is None:
b = np.ones(m) / m
# cumulative distirbutions
ca = np.cumsum(a)
cb = np.cumsum(b)
# points on w... |
"""EfficientDet Configurations
Adapted from official impl at https://github.com/google/automl/tree/master/efficientdet
TODO use a different config system (OmegaConfig -> Hydra?), separate model from train specific hparams
"""
from omegaconf import OmegaConf
from copy import deepcopy
import itertools
def default_de... |
a = 10
b =20
c=3333
d = 300
|
import FWCore.ParameterSet.Config as cms
process = cms.Process("ERRORSANALYZER")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(0)
)
process.ErrorsPropagationAnalyzerModule = cms.EDAnalyzer(
"ErrorsPropagationAnalyzer",
InputFileName = cms.... |
import xml.etree.ElementTree as ET
import os
from tqdm import tqdm
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dir_path', type=str, default='dataset/')
args = parser.parse_args()
return args
sets = [('2007', 'test'), ('2007', 'train'), ('2007', 'val')]... |
# Robot class
import config
from libs.loglib import logfile # logging
import libs.aux_functions as aux_functions # various auxiliary functions
import exch_api # to get balance when there is no input
import libs.lambobot as lambobot
from sys import exit
from libs.aux_functions import send_chat_message
class Scripti... |
# Copyright 2021 The ProLoaF Authors. All Rights Reserved.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^transaction/completed/$',
views.TransactionCompletedView.as_view(),
name='transaction_completed'
),
url(
r'^transaction/status/$',
... |
from . import test_flow
|
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class GANLossGenerator(nn.Module):
"""
This class implements the standard generator GAN loss proposed in:
https://papers.nips.cc/paper/2014/file/5ca3e9b122f61f8f06494c97b1afccf3-Paper.pdf
"""
def __ini... |
# Copyright (c) 2018, Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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/lic... |
import sys
import re
from colored import fg, style
from typing import Any, Callable, List, Union
from cloc.utils import trace, echo
class BaseArg(object):
"""BaseArg - Base implementation of an argument found on the cli
Args:
name {str} -- used as name for invoking arg
type {Any} -- A ty... |
################################################################################
# NAM Groningen 2017 Model: DeepNL/Utrecht University/Seismology
#
# Purpose:
# 1) load numpy npz files of the Groning Subsurface Volume
# 2) smooth each property volume (i.e. VP, VS, Rho)
# 3) create an... |
""" project admin view """
from flask import flash, url_for, redirect
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, FormField, FieldList, BooleanField, IntegerField
from wtforms.validators import DataRequired
from textflow import auth, services
from textflow.mode... |
from kotodama import kotodama
# import nagisa
# kotodama.setSegmentationEngine(kotodama.SegmentationEngine.NAGISA, nagisa)
# from janome.tokenizer import Tokenizer
# tokenizer = Tokenizer()
# kotodama.setSegmentationEngine(kotodama.SegmentationEngine.JANOME, tokenizer)
# from pyknp import Juman
# juman = Juman()
# k... |
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import copy
DictProxyType = type(object.__dict__)
from VyPy.tools import numpy_isloaded, array_type, matrix_type
# -------------------------------... |
# -*- coding:utf8 -*-
# File : rpredictor_schedule.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 22/08/2017
#
# This file is part of TensorArtist.
class CollectorScheduler(object):
def __init__(self, nr_total, nr_pretrain, nr_epochs):
self._nr_total = nr_total
self._nr_pre... |
# -*- coding: utf-8 -*-
## \package wiz.pginit
#
# The initial wizard page
# MIT licensing
# See: docs/LICENSE.txt
import wx
from dbr.language import GT
from globals.ident import pgid
from ui.hyperlink import Hyperlink
from ui.layout import BoxSizer
from wiz.wizard import WizardPage
## The initial wizard page... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from windtalker.asymmetric import AsymmetricCipher
class TestAsymmetricCipher(object):
def test_encrypt_decrypt_data(self):
data = "Turn right at blue tree".encode("utf-8")
A_pubkey, A_privkey = AsymmetricCipher.newkeys()
B_pub... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 16 11:04:21 2020
@author: Mansi
"""
# Imports
from tkinter import *
import tkinter.ttk as ttk
from tkinter import colorchooser
from tkinter import filedialog
import PIL
from PIL import Image, ImageDraw, ImageGrab, ImageTk
from tkinter import messagebox
r... |
"""
Lie Conformal Algebra Element
AUTHORS:
- Reimundo Heluani (2019-08-09): Initial implementation.
"""
#******************************************************************************
# Copyright (C) 2019 Reimundo Heluani <heluani@potuz.net>
#
# This program is free software: you can redistribute it and/or mo... |
# Generated by Django 3.0.1 on 2020-06-12 01:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('preboarding', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='preboarding',
name='to_do',
),
... |
from vispy import scene
from .markers import MarkersVisual
from .hyperaxis import HyperAxisVisual
Markers = scene.visuals.create_visual_node(MarkersVisual)
HyperAxis = scene.visuals.create_visual_node(HyperAxisVisual)
class Scatter:
def __init__(self, data, proj, c=None, labels=None, parent=None):
self.m... |
from setuptools import setup, find_packages
with open("README.md", 'r') as f:
long_description = f.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(name="foamfile",
version="0.11",
description='OpenFOAM config file parser',
long_description=long_description,... |
import argparse
from pathlib import Path
from tqdm import tqdm
# torch
import torch
from einops import repeat
# vision imports
from PIL import Image
from torchvision.utils import make_grid, save_image
# dalle related classes and utils
from dalle_pytorch import DiscreteVAE, OpenAIDiscreteVAE, VQGanVAE1024, DALLE
... |
import logging
import os
import random
import requests
from google.api_core import exceptions
import vk_api as vk
from dotenv import load_dotenv
from vk_api.longpoll import VkLongPoll, VkEventType
from utils import TelegramBotHandler, detect_intent_texts
logger = logging.getLogger(__name__)
def send_vk_message(eve... |
# -*- coding: utf-8 -*-
import level
from engine import scene
from engine import text
from engine.graphics import scale_image
from pyglet.window import mouse
class Game(scene.Scene):
""" The main scene where most of the game is happening. """
def __init__(self, manager, campaign, lvl_num,
... |
import itertools
import numpy as np
import time
import pychunkedgraph.backend.chunkedgraph_utils
from pychunkedgraph.backend.utils import column_keys
from pychunkedgraph.backend import chunkedgraph
from multiwrapper import multiprocessing_utils as mu
def _family_consistency_test_thread(args):
""" Helper to test ... |
import sys
input = sys.stdin.readline
while True:
I = input()
n = int(I[0])
if n == 0:
break
m = 0
A = [0 for _ in xrange(n)] + map(int, I[2:].split())
for i in xrange (n-1,0,-1):
A[i] = min(A[i << 1], A[i << 1 | 1])
def find_min(i,j):
a,b = i,j
label = -1
... |
from twittercrawl import TwitterCrawl
import time
if __name__ == '__main__':
param = {}
param['q'] = "Japan Travel OR Japan Tourism"
twittercrawl = TwitterCrawl('config.ini')
while True:
twittercrawl.search(param)
time.sleep(24*3600)
|
import json
from source.simulation import Simulation
from source.web_socket_visualiser import VisualiserServer
class SimulationVisualiser(object):
def __init__(self, simulation=None, visualiser=None):
"""
Visualises a simulation instance by piping serialised simulation elements to a visualisation... |
"""You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.
Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , num... |
#python3
#steven 24/04/2020 Apollonian gasket
#Reference:https://en.wikipedia.org/wiki/Apollonian_gasket
import numpy as np
import matplotlib.pyplot as plt
def getCircle(pt,r):
x = np.linspace(pt[0] - r, pt[0] + r, 50)
y = np.linspace(pt[1] - r, pt[1] + r, 50)
X, Y = np.meshgrid(x, y)
return X, Y, (X-p... |
# -*- coding: utf-8 -*-
""" HMS Kiosk BoxesScreen
Author: Matt Lloyd
Copyright (c) 2021 Nottingham Hackspace
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Name: extensions.py
# Purpose: Sphinx extension for hiding and showing lines in docs
#
# Authors: Josiah Wolf Oberholtzer
#
# Copyright: Copyright © 2013 Michael Scott Cuthbert and the music21 ... |
"""pytmx is a python tool to work with tmx files."""
__copyright__ = 'Copyright (C) 2021 Daniel K. Elder'
__version__ = '0.0.1'
__license__ = 'MIT'
__author__ = 'Daniel K. Elder'
__url__ = 'https://github.com/elderdk/pytmx'
from .api import (
PYTMX as pytmx
) |
from __future__ import absolute_import, unicode_literals
import copy
import collections
from itertools import chain
from django.conf import settings
from django.db import connections
from django.db.models import Model
from sqlbuilder import smartsql
from sqlbuilder.smartsql.dialects import mysql
from django_sqlbuilder... |
from tds import *
from auxiliares import *
import lexico as Lexico
import scanner as Scanner
def inicio():
if(Lexico.token == Lexico.simbolo.dputok):
Scanner.obtoken()
bloque()
else:
error(29)
def bloque():
if(Lexico.token == Lexico.simbolo.mdputok):
return
temp = None
... |
"""
pygclip
~~~~~~~
Pygmentize to clipboard for macOS
:copyright: © 2018 by Bryan Lee McKelvey.
:license: MIT, see LICENSE for more details.
"""
__version__ = '0.0.8'
|
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
#from sklearn import metrics
#from sklearn import model_selection
#from sklearn.metrics import *
#import os
#import mat... |
import falcon
from sqlalchemy import func
from sqlalchemy.exc import SQLAlchemyError
from db import session
import model
import util
class CorrectionInfo(object):
def on_get(self, req, resp, id):
try:
user = req.context['user']
year = req.context['year']
if (not user... |
import pytest
from bocadillo import API
from bocadillo.constants import ALL_HTTP_METHODS
from tests.utils import RouteBuilder
def test_can_register_class_based_view(builder: RouteBuilder):
builder.class_based("/")
@pytest.mark.parametrize("method", map(str.lower, ALL_HTTP_METHODS))
def test_if_method_not_imple... |
# View more python learning tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('500x500')
var1 = tk.St... |
import re
import os
import argparse
from bs4 import BeautifulSoup
from urllib.request import urlopen
import ssl
'''
argparse to enable finicky command-line args
'''
parser = argparse.ArgumentParser()
parser.add_argument('website_url')
parser.add_argument('file_path')
parser.add_argument('relative_url', nargs='?', defa... |
import sys
import ctypes
from .base import _LIB, check_call, py_str, c_str, _FFI_MODE, _RUNTIME_ONLY
try:
if _FFI_MODE == "ctypes":
raise ImportError()
from ._cy3.core import _register_object
from ._cy3.core import convert_to_cvm_func, _get_global_func, PackedFuncBase
except (RuntimeError, ImportE... |
with open("E:\\Projects\\CSE5544\\assignment04\\data\\testGHZ400.data") as f:
with open("E:\\Projects\\CSE5544\\assignment04\\data\\testGHZ400clean.data", "w") as out:
for line in f:
print(",".join(line.split()), file=out)
|
"""Contains helper methods for working with OSM API through OsmApi package."""
import logging
from typing import List, Dict, Any
from synchrosm.models import Node
from osmapi import OsmApi
# Create a custom logger
logger = logging.getLogger('OSM API')
def _split_list_into_chunks(x: List[Any], chunk_size: int = 5... |
# Copyright 2018, The Ssite Authors.
#
# 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 wr... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: annotations.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message a... |
#!/usr/bin/env python
# This is a derivative, modified, work from the verify-sigs project.
# Please refer to the LICENSE file in the distribution for more
# information. Original filename: auth_data.py
#
# Parts of this file are licensed as follows:
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed unde... |
# Copyright 2021 MosaicML. All Rights Reserved.
"""The GPU device used for training."""
from __future__ import annotations
from typing import Any, Dict, TypeVar
import torch
import torch.cuda.amp
import torch.utils.data
from composer.trainer.devices.device import Device
from composer.utils import dist
__all__ = [... |
from collections import defaultdict
from ansiblelater.standard import StandardBase
class CheckUniqueNamedTask(StandardBase):
sid = "ANSIBLE0003"
description = "Tasks and handlers must be uniquely named within a single file"
helptext = "name '{name}' appears multiple times"
version = "0.1"
types ... |
import os
import pathlib
from dotenv import load_dotenv
PROJECT_ROOT = pathlib.Path(__file__).parent
load_dotenv(dotenv_path=PROJECT_ROOT.parent / '.env')
class Config:
FLASK_APP = "app"
PORT = os.getenv("APP_PORT")
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-... |
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@rules_java//java:reposito... |
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import edward2 as ed
import warnings
plt.style.use("ggplot")
warnings.filterwarnings('ignore')
num_schools = 8 # number of schools
treatme... |
nombre = input("Ingresa tu nombre: ")
print("Hola, " + nombre + ". ¡Un gusto conocerte!")
print("\nPresiona la tecla Enter para finalizar el programa.")
input()
print("FIN.") |
import numpy
from amuse.test import amusetest
from amuse.ext.orbital_elements import (
generate_binaries,
get_orbital_elements_from_binaries,
new_binary_from_orbital_elements,
# get_orbital_elements_from_binary,
orbital_elements_for_rel_posvel_arrays,
orbital_elements,
... |
import wx
import pyautogui
def get_center(state):
return state["x_pos"] + (state["width"]/2), state["y_pos"] + (state["height"] /2)
def get_initial_state():
width, height = wx.GetDisplaySize()
return {
"height": height,
"width": width,
"x_pos": 0,
"y_pos": 0
}
def ge... |
# find the kth min and max element of an array given that all the elements of the array are distinct
# expected complexity : O(n)
def kth_min_max(arr: list, k: int) :
arr.sort()
print(arr)
return (arr[k-1], arr[len(arr)-k])
if __name__ == "__main__":
print(kth_min_max([7,10,4,20,15], 4))
|
from output.models.nist_data.atomic.any_uri.schema_instance.nistschema_sv_iv_atomic_any_uri_min_length_3_xsd.nistschema_sv_iv_atomic_any_uri_min_length_3 import NistschemaSvIvAtomicAnyUriMinLength3
__all__ = [
"NistschemaSvIvAtomicAnyUriMinLength3",
]
|
'''
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
'''
import rouge
import time
import json
import nltk
import os
from tqdm import tqdm
import debugger
nltk.... |
# pedindo um valor
n = int(input('Digite um numero: '))
# mostrando seu antecessor e sucessor
print(f'Numero digitado foi {n}, seu Antecessor {n-1} e seu Sucessor e {n+1}') |
import collections
import contextlib
from energyRatioByVAD import getEnergyRatio
from os import curdir, path
import sys
import wave
from matplotlib.pyplot import bar_label
from numpy import compare_chararrays, true_divide
import webrtcvad
def read_wave(path):
"""Reads a .wav file.
Takes the path, and retur... |
import json
import boto3
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
table = dynamodb.Table('Players')
if event['httpMethod'] == 'PUT':
if 'body' in event:
body_text = event['body']
body = json.loads(body_text)
if 'Username' in bod... |
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
import os
import DCGAN_VAE_pixel as DVAE
import ... |
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def my_incident_json():
return {
'id': 'anId',
'processDefinitionId': 'aDefinitionId',
'processInstanceId': 'anInstanceId',
'executionId': 'anExecutionId',
'incidentType': 'failedExternalTask',
'activityId': 'an... |
from distutils.core import setup
setup(
name='django-auditlog',
version='0.4.3',
packages=['auditlog', 'auditlog.migrations', 'auditlog.management', 'auditlog.management.commands'],
package_dir={'': 'src'},
url='https://github.com/jjkester/django-auditlog',
license='MIT',
author='Jan-Jelle ... |
import os
from flask import (Flask, Blueprint, render_template,
request, current_app)
from uricomcuscuz.models import User, Submission, Problem
bp = Blueprint('app', __name__)
@bp.route('/')
def index():
page, category = (request.args.get('page', 1, type=int),
request.ar... |
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits == []:
return [1]
if digits[-1] == 9:
digits = self.plusOne(digits[:-1])
digits.extend([0])
else:
digits[-1] += 1
return digits
|
from setuptools import setup, find_packages
setup(
name = "exchange_rate",
author = "ksysiupeel",
author_email = "ksysiupeel@protonmail.com",
install_requires = ["requests"],
version = "1.0",
description = "Simple wrapper using exchangeratesapi.io",
long_description = open("README.md").read... |
"""adding bool in feed to trigger reddit integration
Revision ID: 9be35ef7b987
Revises: 8744eda9fa05
Create Date: 2017-05-03 00:28:25.199151
"""
# revision identifiers, used by Alembic.
revision = '9be35ef7b987'
down_revision = '8744eda9fa05'
branch_labels = None
depends_on = None
from alembic import op
import sqla... |
from django.db import models
import uuid
def generate_uuid():
return uuid.uuid4().hex
TELEGRAM_CONNECT_USER_HELP = """Для получения уведомлений в Telegram вам необходимо:
1. Отправить боту https://t.me/{telegram_bot_name} сообщение /start:
2. Отправить ему сообщение /set {telegram_secret}
3. Все, вы будете полу... |
def calcL1Ainterval(rate):
"""
Returns the L1Ainterval in BX associated with a given rate in Hz
"""
from math import floor
return floor((1.0 / rate) * (1e9 / 25))
def getCardName(shelf,slot):
return "gem-shelf%02d-amc%02d"%(shelf,slot)
def getGeoInfoFromCardName(cardName):
"""
cardName... |
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from api.models.customer_model import CustomerModel
from api.serializers.customer_serializer import CustomerSerializer
class CustomerView(ModelViewSet):
permission_classes = (IsAuthenticated,)
queryset = C... |
#!/usr/bin/env python
#
# cococonet related functions
# convert identifiers using gene_info.csv files from cococonet
#
#
#
import argparse
import os
import sys
import logging
import traceback
INFOCOLS=['EntrezID','EnsemblID','GeneSymbol','LocusTag','Synonyms','dbXrefs','Chromosome','Type',
'UniProtID','UniP... |
'''046 - CONTAGEM REGRESSIVA
PROGRAMA QUE MOSTRE NA TELA UM ACONTAGEM REGRESSIVA.'''
from time import sleep
for contagem in range(5, -1, -1):
print(contagem)
sleep(1)
print('KAMBOOM! BOOM! TU! DU! DU! PÁ! IHULL')
|
import numpy as np
def dataset_Circles(n=1000, radius=0.7, noise=0.0):
X = np.zeros((n, 2, 1))
Y = np.zeros((n, 1, 1))
for currentN in range(n):
i, j = 2 * np.random.rand(2) - 1
r = np.sqrt(i ** 2 + j ** 2)
if (noise > 0.0):
r += np.random.rand() * noise
if (... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.