content stringlengths 5 1.05M |
|---|
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/plots.ipynb (unless otherwise specified).
__all__ = ['river_reliability_diagram', 'class_wise_river_reliability_diagram', 'confidence_reliability_diagram',
'class_wise_confidence_reliability_diagram']
# Cell
from riverreliability import utils, metrics ... |
import json
import os
import shutil
import subprocess
from ..util.constants import LOG
from .constants import LOCAL_REPO_DIR
from .google_benchmark.gbench2junit import GBenchToJUnit
class MicroBenchmarksRunner(object):
""" A runner for microbenchmark tests. It will run the microbenchmarks
based on a config o... |
"""
********************************************************************************
all your parameters
********************************************************************************
"""
import sys
import os
import numpy as np
import tensorflow as tf
# network structure
in_dim = 3
out_dim = 3
width = 2 ** 8 # 2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os, shutil, logging, uuid
import os.path as osp, numpy as np
from array import array
import hgcalhistory
logger = logging.getLogger('hgcalhistory')
import ROOT
class Histogram2D(object):
def __init__(self):
super... |
import asyncio
import logging
import threading
import time
from watchgod import watch
WAIT_SEC = 2
class FileSystemWatcher:
def __init__(self, path_to_watch, reload_configuration):
self.active = True
self.change_detected = False
self.path_to_watch = path_to_watch
self.reload_confi... |
#Tests proper handling of Verifications with Transactions which don't exist.
#Types.
from typing import Dict, IO, Any
#SignedVerification class.
from python_tests.Classes.Consensus.Verification import SignedVerification
#Blockchain class.
from python_tests.Classes.Merit.Blockchain import Blockchain
#TestError Excep... |
# ADB File Explorer `tool`
# Copyright (C) 2022 Azat Aldeshov [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
import os
import gconf
from xdg.DesktopEntry import DesktopEntry
from fluxgui.exceptions import DirectoryCreationError
################################################################
# Color temperatures.
# The color options available in the color preferences dropdown in the
# "Preferences" GUI are defined in ./pref... |
from .load import * |
import sys
import glob
import os
from functools import partial
import numpy as np
import pandas as pd
from PyQt5.QtCore import (Qt, QObject, QProcess, QSettings, QThread, QTimer,
pyqtSignal, pyqtSlot)
from PyQt5.QtMultimedia import QAudioFormat, QAudioOutput, QMediaPlayer
from PyQt5.QtWidgets import QMainWindo... |
#
# PySNMP MIB module DT1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DT1-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:39:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... |
'''
run.py
Run file for photo service.
Author: Nicolas Inden
eMail: [email protected]
GPG-Key-ID: B2F8AA17
GPG-Fingerprint: A757 5741 FD1E 63E8 357D 48E2 3C68 AE70 B2F8 AA17
License: MIT License
'''
import os, os.path
import sys
import cherrypy
import redis
import sqlite3
import common
import config
from service_... |
n = float(input("digite um valor: "))
v = []
i = 0
v.append(n)
print("N["+str(i)+"] = "+str(v[i]))
while i < 9:
n *= 2
v.append(n)
i += 1
print("N["+str(i)+"] = "+str(v[i]))
|
from .stopword_modification import StopwordModification
from .repeat_modification import RepeatModification
from .input_column_modification import InputColumnModification
from .max_word_index_modification import MaxWordIndexModification
from .min_word_length import MinWordLength
|
import numpy as np
from skimage.measure import shannon_entropy
from tqdm import tqdm
def read_label_string():
label_path = "./cifar100_text.txt"
f = open(label_path, "r")
labels = f.read()
labels = labels.split(",")
labels = [i.rstrip().lstrip() for i in labels]
# labels = [i.split(' ')[0] for ... |
from tonks.vision.models.multi_task_resnet import ResnetForMultiTaskClassification
|
import json,os
import boto3
from datetime import *
import json, logging
import pprint,re
from elasticsearch import Elasticsearch, helpers
from opensearchpy import OpenSearch,helpers, RequestsHttpConnection
import requests
from requests_aws4auth import AWS4Auth
import urllib.parse
from botocore.exceptions import Clien... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: zparteka
"""
def read_data(infile):
masks = {}
with open(infile, 'r') as f:
data = f.readlines()
for i in range(len(data)):
if data[i].strip().startswith("mask"):
mask = data[i].strip()[7:]
c... |
class ProcessingHelper():
def __init__(self, df):
self.dframe = df
|
from django.shortcuts import render
from django.views.generic import TemplateView, View, ListView, DetailView
from league.models import Schedule, Standings, Season, Player, Team, STANDINGS_ORDER
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
class StandingsFull(ListView):
... |
import os
import tkMessageBox
def default():
if (not tkMessageBox.askyesno("Default Settings", "Do you really want to force Default Settings?")):
return
os.popen('iptables -F',"r")
os.popen('iptables -A INPUT -p tcp -s 0/0 --dport 1:1024 -j DROP',"r")
os.popen('iptables -A INPUT -p udp -s 0/0 --dport 1:1024 -j ... |
#SERVER Configuration
KoboENV = "production"
KoboConfig = {
'local': {
'USERNAME': '',
'PASSWORD': '',
'PROTOCOL': 'http',
'SCHEME': 'kobo',
'IP': '127.0.0.1',
'HOST': '',
'PORT': '',
'VERSION':'v1',
'TIMEOUT': 7200,
'FORM': ''
},... |
#author : eric mourgya
#
import commands
from flask import jsonify
from flask import Flask, Response, request, redirect,session, url_for
from flask.ext.login import LoginManager, UserMixin,login_required, login_user, logout_user
#@app.after_request
#def treat_as_plain_text(response):
# response.headers["content-typ... |
from django.test import TestCase
from oscar.core import compat
class TestCustomUserModel(TestCase):
def test_can_be_created_without_error(self):
klass = compat.get_user_model()
try:
klass.objects.create_user('_', '[email protected]', 'pa55w0rd')
except Exception, e:
self.fai... |
class NoConfigException(Exception):
pass
class ConfigFormatException(Exception):
pass
class FeedNotFoundException(Exception):
pass
|
"""
================================
Make an MNE-Report with a Slider
================================
In this example, MEG evoked data are plotted in an html slider.
"""
# Authors: Teon Brooks <[email protected]>
# Eric Larson <[email protected]>
#
# License: BSD (3-clause)
from mne.report import... |
"""Module containing graphQL client."""
import aiohttp
import requests
class GraphqlClient:
"""Class which represents the interface to make graphQL requests through."""
def __init__(self, endpoint: str, headers: dict = None):
"""Insantiate the client."""
self.endpoint = endpoint
self... |
import uncompyle2
with open("sql_quality_check.py", "wb") as fileobj:
uncompyle2.uncompyle_file("/Users/Minat_Verma/Desktop/sql_quality_check.pyc", fileobj)
|
# -*- coding: utf-8 -*-
import glm
import material
from random import random
from math import pi
class Triangle(object):
"""
Triangle ( vertex1 (vec3), vertex2 (vec3), vertex3 (vec3) )
Creates triangles on the scene.
"""
def __init__(self, *args, **kwargs):
if kwargs:
self.vertex1 = kwargs.get('vertex1', gl... |
import torch
import math
from time import time
import torch.distributions as tdis
import matplotlib.pyplot as plt
from torch import nn
from torch import optim
from torch.utils.data import TensorDataset, RandomSampler, BatchSampler, DataLoader
def get_model(in_size):
return nn.Sequential(
nn.Linear(in_s... |
import argparse
import json
import os
import string
import time
import uuid
import boto3
greengrass_client = boto3.client("greengrassv2")
s3_client = boto3.client("s3")
sts_client = boto3.client("sts")
class ParseKwargs(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
... |
import time
from behave import given, when, then
from selenium.webdriver.chrome.webdriver import WebDriver
@given(u'I navigate to the Manager Home Page')
def step_impl(context):
context.driver.get('http://127.0.0.1:5000/home')
@when(u'I Login In')
def step_impl(context):
context.employee_home_page.login()... |
from abc import abstractmethod
import numpy as np
from scipy.optimize import minimize
from ..opt_control_defaults import lbfgsb_control_defaults
from ..output import (
add_g_to_retlist,
add_llik_to_retlist,
add_posterior_to_retlist,
df_ret_str,
g_in_output,
g_ret_str,
llik_in_output,
l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Written as part of https://www.scrapehero.com/how-to-scrape-amazon-product-reviews-using-python/
import json
import requests
import urllib
import re
import shutil
def getInfo(url):
file = open("list.txt", "w")
while True:
print(url)
file.write(... |
from fastapi import FastAPI
# from pydantic import BaseModel
# from typing import Optional
import random
import mechanize
from bs4 import BeautifulSoup
import html5lib
import requests
import json
rockauto_api = FastAPI()
@rockauto_api.get("/")
async def root():
return {"message": "Hello Worl... |
"""
app.recipe_users.utils
----------------------
Utils file to handle recipe users utilities functions
"""
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
"""
Manager class to perform users functions
"""
def create_user(
self,
email:... |
import tkinter
import tkinter.messagebox
class MyGUI:
def __init__(self) -> None:
# Create the main window
self.window = tkinter.Tk()
self.button = tkinter.Button(self.window, text="Click Me", command=self.do_something)
self.quit_button = tkinter.Button(self.window, text="Quit", command=self.window.destroy)
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from pyro_models.load import load
from pyro_models.utils import data
__all__ = [
'load',
'data'
]
|
from inspect import getsourcefile
from os.path import abspath
print(abspath(getsourcefile(lambda:0))) |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class Provide... |
from unittest import TestCase
from pybridair.auth import *
from pybridair.data import *
auth = BridAuth('10.101.30.42')
class TestGetStatus(TestCase):
"""
Test pybrid.data.get_status function against live Brid device
"""
def test_get_current_air(self):
"""
Tests pybrid.data.get_st... |
import struct
import pyb
CONFIG_MODE = 0x00
ACCONLY_MODE = 0x01
MAGONLY_MODE = 0x02
GYRONLY_MODE = 0x03
ACCMAG_MODE = 0x04
ACCGYRO_MODE = 0x05
MAGGYRO_MODE = 0x06
AMG_MODE = 0x07
IMUPLUS_MODE = 0x08
COMPASS_MODE = 0x09
M4G_MODE = 0x0a
NDOF_FMC_OFF_MODE = 0x0b
NDOF_MODE = 0x0c
AXIS_P0 = bytes([0x21, 0x04])
AXIS_P1 = b... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .SwitchNorm import SwitchNorm2d
def make_layers(
cfg, block, in_chns=None, norm=True, skip=False, downsampling="maxpooling", upsampling="transconv"
):
layers = []
cur_chns = in_chns
for ii, v in enumerate(cfg):
... |
# minimal potential length of requirement
test_text = 'При первом открытии а п.1.23приложения "Х" должен появляться новый экран. ' \
'1.1 Если экран успешно открылся, то начнет загружаться новая страница. ' \
'1.2 Если появилась ошибка, то стоит отобразить юзеру модальное окно с текстом ошибки.... |
import numpy as np
import tensorflow as tf
from gym.spaces import Box, Discrete
EPS = 1e-8
def placeholder(dim=None):
return tf.placeholder(dtype=tf.float32, shape=(None,dim) if dim else (None,))
def placeholders(*args):
return [placeholder(dim) for dim in args]
def placeholder_from_space(space):
if spa... |
from predict_flask import classify
body = "Al-Sisi has denied Israeli reports stating that he offered to extend the Gaza Strip."
head = "Apple installing safes in-store to protect gold Watch Edition"
print (classify([head, body])) |
from django.urls import path, re_path
from apps.user import views
urlpatterns = [
path('register/', views.RegisterView.as_view(), name='register'), # 用户注册页面
path('login/', views.LoginView.as_view(), name='login'), # 用户注册页面
re_path('active/(?P<token>.*)$', views.ActiveView.as_view(), name='active'), ... |
#!/usr/bin/env python
import json
import sys
release_type="patch"
if len(sys.argv) > 1:
release_type = sys.argv[1]
default_version_data = \
"""
{
"version": { "major": 0, "minor": 0, "patch": 0 }
}
"""
# supported types
types = ['major', 'minor', 'patch']
def get_version(release_type_):
if release_type_ not... |
from flee import flee
from flee.datamanager import handle_refugee_data
from flee.datamanager import DataTable # DataTable.subtract_dates()
from flee import InputGeography
import numpy as np
import flee.postprocessing.analysis as a
import sys
import argparse
import time
def date_to_sim_days(date):
return DataTabl... |
#!/usr/bin/env python
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# NASA Jet Propulsion Laboratory
# California Institute of Technology
# (C) 2008 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~... |
from __future__ import absolute_import, division, print_function
import stripe
import pytest
pytestmark = pytest.mark.asyncio
TEST_RESOURCE_ID = "or_123"
class TestOrder(object):
async def test_is_listable(self, request_mock):
resources = await stripe.Order.list()
request_mock.assert_requeste... |
# Copyright (c) 2009 by Yaco S.L.
#
# This file is part of PyCha.
#
# PyCha 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 version 3 of the License, or
# (at your option) any later version.
#
# ... |
from datetime import datetime
from time import mktime
import feedparser
import requests
from analyzer.tasks import parse_html_entry
from celery import shared_task
from celery.utils.log import get_task_logger
from django.db.models import Q
from django.utils.timezone import make_aware
from crawler.models import RSSEntr... |
expected_output = {
"segment_routing": {"sid": {"12345": {"state": "S", "state_info": "Shared"}}}
}
|
# from core.Backup import Backup
# from core.Jobs import Jobs
# jobs = Jobs()
# for job in range(len(jobs)):
# try:
# job = jobs.next()
# bu = Backup(job)
# print(bu.command())
# except Exception as err:
# print(err)
# from core.Notifier import Notifier
# email = Notifier()
... |
from __future__ import unicode_literals
import os
import sys
import urllib
import datetime
import logging
import subprocess
import eeUtil
import urllib.request
import requests
from bs4 import BeautifulSoup
import copy
import numpy as np
import ee
import time
from string import ascii_uppercase
import j... |
#!/usr/bin/env python3
import logging
import time
from acceptance.common.log import LogExec, initLog
from acceptance.common import test
test.TEST_NAME = "leader_failure"
logger = logging.getLogger(__name__)
class Test(test.Base):
"""
Test that we can kill the patroni leader node and the cluster will fail o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
from pprint import pprint as print
import os
import re
import datetime
import struct
from math import ceil
from ctypes import *
from functools import wraps, partial
from itertools import chain, islice
from bisect... |
# File: gitn_branch.py
# Author: kmnk <kmnknmk at gmail.com>
# License: MIT license
from gitn.util.gitn import Gitn
from denite.process import Process
import copy
import os
import re
from .gitn import Source as Base
HIGHLIGHT = {
'container': {
'name': 'gitn_branch_line',
'pattern': '\\v([* ]) (.... |
"""Multiple functions used in the pipeline"""
import os
import json
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
from rssnet.loaders.dataloaders import Rescale, Flip
from rssnet.utils import RSSNET_HOME
def get_class_weights(path_to_weights, signal_type):
"""Load class weights for ... |
# -*- coding: UTF-8 -*-
from assopy import models
from conference import models as cmodels
from django.db.models import Q
from collections import defaultdict
from decimal import Decimal
def _orders(**kw):
qs = models.Order.objects.filter(_complete=True)
if 'year' in kw:
qs = qs.filter(created__year=kw[... |
import tweepy as tw
import json
with open("key.json", "r") as f:
key = json.load(f)
auth = tw.OAuthHandler(key['API_KEY'], key['API_SECRET_KEY'])
auth.set_access_token(key['ACCESS_TOKEN'], key['ACCESS_TOKEN_SECRET'])
api = tw.API(auth, wait_on_rate_limit=True)
#api.update_status("Hello World!")
search_words = "... |
"""
LLDB AppKit formatters
part of The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
"""
# summary provider for NS(Mutable)IndexSet
import lldb
import ctypes
import lldb.runtime.objc.objc_runtime
import lldb.formatters.metrics
i... |
import numpy as np
from gym.envs.mujoco import HalfCheetahEnv
import inspect
def get_all_function_arguments(function, locals):
kwargs_dict = {}
for arg in inspect.getfullargspec(function).kwonlyargs:
if arg not in ["args", "kwargs"]:
kwargs_dict[arg] = locals[arg]
args = [locals[arg] f... |
import xlwt
from django.http import HttpResponse
from users.models import Usuario
from mrp.models import Report, ReportItem, ReportPeriod
from decimal import Decimal
from .functions import dollarFormat
def export_report_xls(request, report_id):
report = Report.objects.get(pk=report_id)
items = ReportItem.obje... |
# Copyright 2015 Mirantis, 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 ... |
""" Cisco_IOS_XR_platform_pifib_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR platform\-pifib package operational data.
This YANG module augments the
Cisco\-IOS\-XR\-lpts\-pre\-ifib\-oper
module with state data.
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"... |
__name__ = ["phonology"]
__version__ = "1.5.4"
##################################################################
#
#
# Phonology - Consonants
def gen_nasal_stops_():
return [ "m", "n", "ŋ" ]
nasal_stop = gen_nasal_stops_()
def gen_non_nasal_stops_():
return [ "b", "d", "ɡ" , "p", "t", "k"... |
import re
from typing import Any
from core import Program
from core.commons import log_objects
from core.interfaces.singleton import Singleton
from cryptography.fernet import Fernet
class Hasher(metaclass=Singleton):
__metaclass__ = Singleton
WRAP_REGEX: str = '<HASHED_DATA_SDBA>{(.+?)}</HASHED_DATA_SDBA>'
... |
#!/usr/bin/env python3
""" Video output writer for faceswap.py converter """
import os
from collections import OrderedDict
from math import ceil
import imageio
import imageio_ffmpeg as im_ffm
from ffmpy import FFmpeg, FFRuntimeError
from ._base import Output, logger
class Writer(Output):
""" Video output writer... |
def lsb(p):
res = 0
for byte in p[::-1]:
res = res << 8
res += byte
return res
def signed2lsb(v, n=2):
v = int(v)
res = list(v.to_bytes(length=n, byteorder='little', signed=True))
# print(f'V: {v} to', res)
return res
def lsb2signed(p):
return int.from_bytes(bytes(p... |
"""Giza URL Configuration"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^$',
views.show_giza,
name="show giza"
),
url(
r'^all/$',
views.show_all_giza,
name="show all giza"
),
url(
r'^new/$',
views.new... |
# -*- coding: utf-8 -*-
"""HAR_Opportunity.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qfhns0ykD6eLkoWICPu6WbdD4r7V-6Uf
# Introduction
This notebook presents the several machine learning models using CNN and LSTM for HAR. To obtain a detail... |
import shutil
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import Dataset, DataLoader
from transformers import (
BertModel,
BertTokenizer,
... |
"""
A Product specifies a persistent object in disk such as a file in the local
filesystem or an table in a database. Each Product is uniquely identified,
for example a file can be specified using a absolute path, a table can be
fully specified by specifying a database, a schema and a name. Names
are lazy evaluated, th... |
from leer.core.storage.merkle_storage import MMR
from secp256k1_zkp import PedersenCommitment, PublicKey
from leer.core.storage.default_paths import txo_storage_path
from leer.core.lubbadubdub.ioput import IOput
import os
import hashlib
def _hash(data):
#TODO move to utils
m=hashlib.sha256()
... |
import os
#: Location of the wordle API
WORDLE_API_URL = os.environ.get("INPUT_WORDLEAPIURL", "")
#: Puzzle size to solve
PUZZLE_SIZE = int(os.environ.get("INPUT_PUZZLESIZE", "5"))
|
import bpy
from bpy.types import (Panel,
Menu,
Operator,
PropertyGroup,
)
import blvcw.crystal_well_global_state as GlobalState
from blvcw.crystal_well_components import CrystalWellLoader, CrystalWellSettings
from blvcw.crystal_... |
# Copyright (c) MONAI Consortium
# 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, so... |
import redis
redisClient = redis.Redis(host='redis')
|
def factorial(n):
answer = 1
for i in range(1, n+1):
answer *= i
return(answer)
def Leibniz(goto):
pi = 0
sign = 1
for i in range(1, 1+goto):
pi += 1/((2*i-1)*sign)
sign = -sign
pi = pi*4
return(pi)
def AbrahamSharp(goto):
pi = 0
for i in range(goto+1):
... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.electric_load_center import GeneratorFuelCellAuxiliaryHeater
log = logging.getLogger(__name__)
class TestGeneratorFuelCellAuxiliaryHeater(unittest.TestCase):
def setUp(self... |
#!/usr/bin/env python3
import requests
import json
import sys
#get the secrets from your Google Cloud project, use the Oauth2 Playground for your refresh token
client_id=sys.argv[1]
client_secret=sys.argv[2]
refresh_token=sys.argv[3]
credentials=sys.argv[4]
def get_list_from_file(filename):
try:
# open and... |
import os.path as osp
import torch
import torch.utils.data as data
import numpy as np
__all__ = ['CNNDataLayer']
def c3d_loader(path, number):
data = []
for index in range(number - 2, number + 3):
index = min(max(index, 1), 3332)
data.append(np.load(osp.join(path, str(index).zfill(5)+'.npy'))... |
#!/usr/bin/env python
# coding=utf-8
import pickle
import os
import sys, locale
import time
import get_pickle
import numpy as np
import tensorflow as tf
from configparser import ConfigParser
#cfg = ConfigParser()
#cfg.read(u'conf/ner_conf.ini')
path = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(path... |
#faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto
#minha resposta
print('\033[1;36m+=\033[m'*15, '\033[1;7;36mPRODUTO COM DESCONTO\033[m', '\033[1;36m+=\033[m'*15)
produto = float(input ('\033[31mQual o preço do produto? R$\033[m'))
calculo = produto * 0.05 #5% do valor
desco... |
"""Contains the Goon Character class"""
import json
from botc import Character, Outsider
from ._utils import BadMoonRising, BMRRole
with open('botc/gamemodes/badmoonrising/character_text.json') as json_file:
character_text = json.load(json_file)[BMRRole.goon.value.lower()]
class Goon(Outsider, BadMoonRising, C... |
# -*- coding: utf-8 -*-
import sys
import subprocess
from functools import wraps
import matplotlib as mpl
import seaborn as sns
import pandas as pd
def customize(func):
@wraps(func)
def call_w_context(*args, **kwargs):
if not PlotConfig.FONT_SETTED:
_use_chinese(True)
set_con... |
#!/bin/python
# Read a list of score files from the Gobnilp's scorer and learn the BN structure using Gobnilp.
import sys
import os
from subprocess import call
def LearnWithGobnilp(pathToGobnilp, pathToScore):
print "Learning the network structures from file", pathToScore, "using Gobnilp."
baseName = os.path.splitex... |
input_value=int(input())
print("{:,}".format(input_value)) |
from datetime import datetime, timedelta
import jwt
from fastapi import Depends, HTTPException
from jwt import PyJWTError
from passlib.context import CryptContext
from pydantic import EmailStr
from starlette import status
from config import apisecrets, oauth2_scheme
from models import User
from v1.services.user impor... |
"""Test pipe subpackage"""
import typing
from src.oolongt.pipe import noop, pipe
from tests.params.pipe import param_noop, param_pipe
@param_noop()
def test_noop(expected: typing.Any):
"""Test `noop`
Arguments:
expected {typing.Any} -- expected value (same as input)
"""
received = noop(expec... |
from dfs.datasheets.parsers.treatments.parser_2014 import TreatmentDatasheetParser2014
import dfs.datasheets.datatabs as datatabs
import dfs.datasheets.datasheet as datasheet
class TreatmentDatasheetParser2017(TreatmentDatasheetParser2014):
def format_output_filename(self, input_filename):
return input_fi... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from pathlib import PurePath
from typing import Dict, Optional, Set
from pants.backend.python.target_types import PythonRequirementsField, PythonSources
... |
AL = 'AL'
NL = 'NL'
MLB = 'MLB'
LEAGUES = [AL, NL, MLB]
def mlb_teams(year):
""" For given year return teams active in the majors.
Caveat, list is not complete; those included are only those
with a current team still active.
"""
year = int(year)
return sorted(al_teams(year) + nl_teams(y... |
import socket, sys
from threading import Thread
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 53331))
print("Connected to chat")
def messenger():
while True:
message = input()
if message == "exit":
sock.send(message.encode())
... |
input_num = int(input())
count = 0
# 1と0以外が混ざっている場合は終了する
for i in str(input_num):
# 1がある値をカウントアップ
if int(i) == 1:
count += 1
print(count)
|
# Raspberry Pi Cat Laser Server
# Flask-based web appplication that allows control and calibration of the cat
# laser toy. This shouldn't be exposed out to other users! Rather this is meant
# for internal use and calibration (like getting a calibration.json file to use
# with the laser driver script).
# Author: Tony ... |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Charmed Machine Operator for the PostgreSQL database."""
import logging
import secrets
import string
import subprocess
from typing import List
from charms.operator_libs_linux.v0 import apt
from ops.charm import Action... |
from PIL import Image as Img
from nbtschematic import SchematicFile
from getbrightnessval import get_bright
def get_image_pixels(path, dark, light):
try:
im = Img.open(path)
except:
print("unable to get image file")
size = im.size
sizex = size[0]
sizey = size[1]
pi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.