content
stringlengths
5
1.05M
from django.contrib.auth.models import Group, Permission from rest_framework import serializers from apps.prop.models import UserProfile, User from project.helpers.utils import DynamicFieldsSerializerMixin class NestedProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile ...
from __future__ import unicode_literals import pytest from webtest import Upload def test_create_session(testapp): resp = testapp.post('/sessions', status=201) assert resp.json['session']['id'].startswith('SE') def test_create_encrypted_session(testapp): validation_code = 'suuper_foobar' resp = tes...
""" Handles interactions with the server endpoints. """ __pragma__("kwargs") def request(path, **kwargs): """ Performs a mithril GET request Args: path (str): endpoint to access qargs (dict): if provided uses this as path query arguments Returns: Promise from m.request """...
def f(x): raise Exception('TODO IMPLEMENT ME !')
import json class InputAdepter: def __init__(self, **kwargs): pass def read(self) -> dict: pass class FileInputAdapter(InputAdepter): def __init__(self, **kwargs): super().__init__(**kwargs) self.file_name = kwargs['file_name'] def read(self, **kwargs) -> dict: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/ # Written by Bastian Schnell <bastian.schnell@idiap.ch> # import torch from torch.nn.modules.loss import _Loss from idiaptts.src.neural_networks.pytorch.loss.NamedLoss import NamedLoss class VAEKLDLos...
# imports {{{1 import os import re from subprocess import check_output from .conky_conf_writer import ConkyConfWriter # }}}1 class SystemConkyConf(ConkyConfWriter): def __init__(self): # {{{2 super().__init__('system.conf') def createGotos(self, array): # {{{2 gotos = [] for num i...
from men import * from location import * DATA_2018_10 = [ { 'location': BEIJING, 'date': '2018-10-07', 'matches': [ # 2018-09-29 { 'round': 512, 'players': [ VIKTOR_TROICKI, ZHE_LI ...
# -*- coding:UTF-8 -*- # 钉钉调用授权秘钥,可在钉钉后台获取 CORP_ID = 'dingr9ljos5qjw43ubiy', CORP_SECRET = '4EDpOvXBZVfvrInlYsb2ECeN1rZBftv6XDxjctmLc6ne215oyvbTwo-C5HRa4duF', BASE_URL = 'https://oapi.dingtalk.com/' # 企业应用的agent id AGENT_ID = '319761162'
"""Save markdowns to the disks from the web""" import hashlib import yaml import subprocess from pathlib import Path from helpers.providers import UrlOpener from helpers.db_handler import DB from helpers.logger import Logger from helpers.cleaner import Cleaner from helpers.aws_helper import AWS from helpers.config_hand...
# (c) 2016 Continuum Analytics, Inc. / http://continuum.io # All Rights Reserved # # constructor is distributed under the terms of the BSD 3-clause license. # Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause. from __future__ import print_function, division, absolute_import import os import sys impor...
from typing import cast import os import json from stopcovid.sms.types import OutboundPayload from stopcovid.utils.boto3 import get_boto3_client def publish_outbound_sms(payload: OutboundPayload) -> dict: kinesis = get_boto3_client("kinesis") stage = os.environ.get("STAGE") records = [ { ...
# coding: utf-8 import argparse import time import math import os import torch import torch.nn as nn import torch.onnx from torch.autograd import Variable import data import model parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM Language Model') parser.add_argument('--data', type=str, default=...
""" OVERVIEW: Module to convert various file formats on the platform. """ import os, sys import util import numpy as np import biom from biom.util import biom_open from biom.table import Table import pandas def fastq2fasta((fastqIn, fastaOut)): # Converts FASTQ to FASTA using fastx-toolkit. Written to facili...
from django.contrib import admin import river_admin from examples.shipping_example.models import Shipping class ShippingRiverAdmin(river_admin.RiverAdmin): name = "Shipping Flow" icon = "mdi-truck" list_displays = ['pk', 'product', 'customer', 'shipping_status'] river_admin.site.register(Shipping, "shi...
from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'todos', views.ToDoViewSet, basename='api-todo') urlpatterns = [ path('', views.index, name='index'), path('todos/', views.todo_list_view, name='todos'), path('to...
"""Tests for fan platforms."""
""" Trabajo de fin de master - Universidad Internacional de La Rioja Genera el grafo para analizar con networkX a partir de las relaciones obtenidas con NewsProcessing @author: Sandra Fresnillo Velasco @license: MIT """ import pickle import networkx as nx import re def check_entity(entity): if re.mat...
import bpy from .rails import Rails from .rails_props import RailProperty class BTOOLS_OT_add_railing(bpy.types.Operator): """ Creates rails on selected mesh edges """ bl_idname = "btools.add_railing" bl_label = "Add Railing" bl_options = {"REGISTER", "UNDO"} props: bpy.props.PointerProperty(typ...
from rest_framework.permissions import BasePermission class RequestUserIsRelatedToUser(BasePermission): """ Permission to check if the user is related to the user that made the request (through models) """ def has_permission(self, request, view): """ Return `True` if the request i...
from facebook_snooper import Session __all__ = [ "save_current_page" ] def save_login(session: Session): session._browser.open('https://www.facebook.com') save_current_page(session, 'login') def save_current_page(session: Session, filename): html_ = str(session._browser.get_current_page()) wit...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if head: odd, even, even_head = head, head.next, head.next ...
"""info_generic.py Generic information about Python exceptions. """ from .my_gettext import current_lang, no_information GENERIC = {} SUBCLASS = {} def get_generic_explanation(exception_type): """Provides a generic explanation about a particular exception.""" if hasattr(exception_type, "__name__"): ...
import tensorflow as tf from config import input_shape from albumentations import Compose, OneOf,\ Blur, MotionBlur, MedianBlur, HorizontalFlip, VerticalFlip, ShiftScaleRotate def load_dataset(filename, res=None): bits = tf.io.read_file(filename) image = tf.image.decode_jpeg(bits, channels=3) image = ...
dic= { 1: 'NAVGURUKUL', 2: 'IN', 3:{ 'A' : 'WELCOME', 'B' : 'To', 'C' : 'DHARAMSALA' } } # dic[3].pop('A') # print(dic) del dic[3]['A'] print(dic)
#!/usr/bin/env python import rospy from ublox.msg import RelPos as rp import rospy import matplotlib.animation as animation import matplotlib.pyplot as plt class Dashboard: def __init__(self): self.data_flag = False rospy.init_node('dashboard') self.fig, self.axes = plt.subplots(nrows=2...
#!/usr/bin/env python3 import os import csv import re import operator def main(): error_dic = {} user_dict = {} with open("./syslog.log") as f: for line in f.readlines(): if "ticky: INFO" in line: result = re.search(r"ticky: INFO (.*) \(([a-zA-Z.]+)\)$", line) if not result: ...
#!/usr/bin/env python ### IMPORTS ### import curses import time ### GLOBALS ### screenHeight = 24 screenWidth = 80 ### FUNCTIONS ### def displayMenu( scr): scr.addstr( 0, 0, "<systemName> Control Panel") # Display title scr.addstr( 1, 0, " <hostName> - 0.10 0.01 0.00 - connected") # Realtime information ...
from seamless.highlevel import Context, Transformer ctx = Context() ctx.a = 12 ipycode = """ %%timeit def triple_it(a): return 3 * a result = _ """ ctx.transform = Transformer() ctx.transform.language = "ipython" ctx.transform.code = ipycode ctx.transform.a = ctx.a ctx.transform.debug.direct_print = True ctx.my...
from cereal import car from selfdrive.car import make_can_msg GearShifter = car.CarState.GearShifter VisualAlert = car.CarControl.HUDControl.VisualAlert def create_lkas_hud(packer, enabled, left_lane_visible, right_lane_visible): # Chrysler came up with this scheme, not me if enabled: if left_lane_visible: ...
""" Provides a way to export and import program data """ import sys import json from django.core.management.base import BaseCommand from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from rest_framework import serializers from workflow.models import Program, Sector, Country, SiteProfile, ...
#!/usr/bin/env python # coding: utf-8 # DO NOT EDIT # Autogenerated from the notebook rolling_ls.ipynb. # Edit the notebook and then sync the output with this file. # # flake8: noqa # DO NOT EDIT # # Rolling Regression # # Rolling OLS applies OLS across a fixed windows of observations and then # rolls # (moves or sli...
import configparser import json import os import pandas as pd from datetime import timedelta from datetime import datetime from telethon import TelegramClient, events, sync from telethon.tl.functions.messages import GetHistoryRequest from telethon.tl.types import PeerChannel from telethon.errors import SessionPassword...
import os from ly_python_tools.lint.environ import environ def test_environ(): """Test that context manager environ works as expected.""" key = "__TEST_VAR__" value = "__TEST_VAR_VALUE__" old_env = os.environ.copy() assert key not in os.environ with environ(**{key: value}): assert os...
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'not-a-secret' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = ['app'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', '...
# ### # <<< Add the network initiation code to your device here.>>> # ### import machine import utime import network from ubinascii import hexlify utime.sleep(2) import tests as tests_mod class TestMQTT(tests_mod.TestMQTT): def disable_net(self): # Works with esp32 and esp8266 ports. # If it doe...
import pandas as pd from pptx import Presentation from pptx.dml.color import RGBColor from pptx.dml.line import LineFormat from pptx.enum.dml import MSO_LINE from pptx.enum.text import MSO_ANCHOR from pptx.enum.text import PP_ALIGN from pptx.util import Inches from pptx.util import Pt from pptx.oxml.xmlchemy import Ox...
# coding: utf8 """ weasyprint.tests.test_css ------------------------- Test the CSS parsing, cascade, inherited and computed values. :copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_lit...
import random from typing import List import gym_open_ai from agents.abstract_agent import Agent from arena.game_statistics_duels import GameStatisticsDuels from arena.arena import Arena from mpi4py import MPI comm = MPI.COMM_WORLD n_proc = MPI.COMM_WORLD.Get_size() my_rank = MPI.COMM_WORLD.Get_rank() main_process ...
import uuid from django.db import models from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFill from django.contrib.auth.models import User import os def get_image_path(instance, filename): """ Get image path :param instance: Get user's username :param filename: ...
# key in data name import sys, os name = sys.argv[1] # load data from py.utils.load_data import read_dataset X_train, _, X_test, _ = read_dataset(name) from py.utils.safe_pickle import pickle_dump from tqdm import tqdm import numpy from sentence_transformers import SentenceTransformer model = SentenceTransformer('be...
#!/usr/bin/env python3 import sys import random import time import argparse import importlib import importlib.util import rfw_state from robot.output.xmllogger import XmlLogger from wrapperlistener import WrapperListener class Config(object): def error(self, msg): sys.stderr.write(msg + '\n') sys...
# Functional Programming Language # 1. you can assign it to other variables E.g. x = 10 # 2. you can pass it to other functions E.g. foo(10) # 3. you can return it from a function E.g. return 10 # All of above 3 properties, are for first class. For Eg Number are first class # for a function, variable is the name of...
from unittest import TestCase from asm_6502 import Assembler, AssembleError class TestAssembleLAX(TestCase): def setUp(self) -> None: self.assembler = Assembler() def test_lax_immediate(self): code = "ORG $0080\n" \ "LAX #10" results = self.assembler.assemble(code, ad...
#!/user/bin/env python3 # Note that all the tests in this module require dataset (either network access or cached) import os import glob import shutil import torchtext.data as data from torchtext.datasets import AG_NEWS import torch from torch.testing import assert_allclose from ..common.torchtext_test_case import Torc...
""" Space : O(n) Time : O(n) """ class Solution: def hammingWeight(self, n: int) -> int: ans = 0 binary = bin(n)[2:] n = len(binary) for i in binary: if i == '1': ans += 1 return ans
""" Plotting utilities. """ import warnings from itertools import count from textwrap import wrap from typing import Dict, Generator, Sequence, Tuple, Union import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.stats as stats import seaborn as sns from fractopo.ana...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.7 # kernelspec: # display_name: Python [conda env:bandit_py3] # language: python # name: conda-env-band...
def test_document_symbol(workspace, libspec_manager, data_regression): from robotframework_ls.impl.completion_context import CompletionContext from robotframework_ls.impl.document_symbol import document_symbol workspace.set_root("case4", libspec_manager=libspec_manager) doc = workspace.put_doc("case4.r...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
"""Defines the MQTTPCMBufferReader class. Not sure if this class is even necessary.""" import pyaudio from stream2py.stream_buffer import BufferReader DFLT_SR = 44100 class MQTTPCMBufferReader(BufferReader): """Reads data from a buffer of PCM chunks and plays back. """ _sr: int _width: int _ch...
from pytest import importorskip, raises cuinfo = importorskip("miutil.cuinfo") def test_num_devices(): devices = cuinfo.num_devices() assert isinstance(devices, int) def test_compute_capability(): cc = cuinfo.compute_capability() if cc: assert len(cc) == 2, cc assert all(isinstance(...
import numpy as np import parzen.PARZEN as PARZEN import random def data_generator(mean, cov, count): np.random.seed(1) x, y = np.random.multivariate_normal(mean, cov, count).T # plt.plot(x, y, 'x') # plt.axis('equal') # plt.show() return [x, y] def generate_dataset(count): # class 1 ...
import pygame from constantes import * class Desenvolvedor(): def __init__(self, screen, clock, fase): self.screen = screen self.clock = clock self.cenario = fase.cenario self.player = fase.player self.fase = fase def visualizaColisao(self): for i in self.cenar...
import sys import requests import boto3 import os try: import Image except ImportError: from PIL import Image import pytesseract sqs = boto3.client('sqs', region_name='us-east-1') def extractText(url, filename, urlIndex): try: img_data = requests.get(url).content with open(filename, 'wb') as handler: ...
__version__ = '1.1.0' __all__ = ['api', 'enums', 'models']
import logging from smtplib import SMTPException from threading import Thread from flask import current_app from flask_mail import Message from app import mail logger = logging.getLogger(__name__) def _send_async_mail(app, msg): with app.app_context(): try: mail.send(msg) except SM...
"""Example of the injecting of provided instance attributes and items.""" from dependency_injector import containers, providers class Service: def __init__(self): self.value = "foo" self.values = [self.value] def get_value(self): return self.value def __getitem__(self, item): ...
from gym.envs.registration import register from pddm.mj_envs.mujoco_env import MujocoEnv # Swing the door open register( id='door-v0', entry_point='pddm.mj_envs.hand_manipulation_suite:DoorEnvV0', max_episode_steps=200, ) from pddm.mj_envs.hand_manipulation_suite.door_v0 import DoorEnvV0 # Hammer a nail i...
print('===========Digite a Placa e a Hora==========') placa = input('Digite sua placa :') hora =float(input('Digite a hora de entrada :')) registro = placa horas = hora * 3600 horaf = horas // 3600 placaSaida = input('Digite sua placa, para liberar, seu automovel! :') horaSaida = int(input('Digite a hora de saida :'))...
#!/usr/bin/env python # encoding: utf-8 ''' @author: Zhao Chi @contact: Vectors@aliyun.com @software: PyCharm @file: connect_mysql.py @time: 2018/4/10 0:13 @desc: ''' # 导入: from sqlalchemy import Column, create_engine, ForeignKey from sqlalchemy.types import String,Integer,VARCHAR,TEXT from sqlalchemy.orm impo...
import os, sys, string reverseAATable = { 'ALA' : 'A', 'CYS' : 'C', 'ASP' : 'D', 'GLU' : 'E', 'PHE' : 'F', 'GLY' : 'G', 'HIS' : 'H', 'ILE' : 'I', 'LYS' : 'K', 'MET' : 'M', 'ASN' : 'N', 'PRO' : 'P', 'GLN' : 'Q', 'ARG' : 'R', 'SER' : 'S', ...
import numpy as np import scipy.sparse as sp def bernstein(p, t): """ Evaluate Bernstein polynomials. Args: p: polynomial order t: locations array Returns: polynomial values (locations x functions) Raises: - """ out = np.ones((t.size, 1)) for n in ran...
def isPrime(num) -> bool: count = 2 while (count < num / 2 + 1): if (num % count != 0): count += 1 continue return False return True def fibo(max=100): result = [1, 2] even = [2] i = 2 while result[len(result) - 1] < max: num = result[i -...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from .culture import * from .recognizer import * from .model import * from .extractor import * from .parser import * from .utilities import *
#***************************************************************************** # Copyright (C) 2007 David Kohel <kohel@maths.usyd.edu.au> # # Distributed under the terms of the GNU General Public License (GPL) # # http://www.gnu.org/licenses/ #****************************************************...
# Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. # How many passwords are valid accordi...
from sparknlp.internal import ExtendedJavaWrapper from pyspark.sql import SparkSession, DataFrame class OcrHelper(ExtendedJavaWrapper): def __init__(self): super(OcrHelper, self).__init__("com.johnsnowlabs.nlp.util.io.OcrHelper") self._java_obj = self._new_java_obj(self._java_obj) def create...
# Solver central-time central-space method for wave equation import numpy as np def CTCS_wave(dt,dx,t_max,x_max,C,u0,Du0): s = C*dt/dx x = np.arange(0,x_max+dx,dx) t = np.arange(0,t_max+dt,dt) r = len(t) c = len(x) u = np.zeros([r,c]) u[0,:] = u0 u[1,:] = u0+dt*Du0 for n in range(...
from django.apps import AppConfig class ChannelauditConfig(AppConfig): name = 'channelaudit' verbose_name = '项目数据'
import sys import os import re import time day_number = sys.path[0].split('\\')[-1] if len(sys.argv)==1: path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"input\\{day_number}") else: path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"sample\\{day_number}") with open(...
def pour_problem(X, Y, goal, start=(0, 0)): """ X and Y are the capacity of glasses; (x,y) is current fill levels and represents a state. The goal is a level that can be in either glass. Start at start state and follow successors until we reach the goal. Kepp track of frontier and previously explor...
from django.apps import AppConfig from django.conf import settings from django.utils.functional import classproperty from infi.clickhouse_orm import Database class AppcraftLoggingConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'appcraft_logging' verbose_name = 'Логи запросов...
from __future__ import annotations import asyncio import logging import signal import sys import traceback from typing import Any from typing import Callable from typing import Coroutine from typing import Optional from typing import TYPE_CHECKING from typing import TypeVar, Sequence import aiohttp from defectio.mode...
from flask_restful import Resource, reqparse import pymongo from bson.json_util import dumps from bson.objectid import ObjectId import json import time from flask import jsonify class ups_create(Resource): ''' Post to create a UPS device ''' def __init__(self, **kwargs): self.DB = kwargs['DB...
import os, sys FILE_PATH = os.path.dirname(os.path.abspath(__file__)) xbos_services_path = os.path.dirname(os.path.dirname(os.path.dirname(FILE_PATH))) sys.path.append(xbos_services_path) import utils3 as utils import numpy as np from abc import ABCMeta, abstractmethod class ParentThermalModel: """A Parent to t...
from .Forward_Backward_augment_decoder import * from .Config import * from .Config_for_decoder import * from .GPU_Sampler import * from .PGBN_sampler import * #import Forward_augment import scipy import numpy as np import time import copy from .Utils import * def updatePhi_Pi(sweepi, X_train, Params, Data, SuperParam...
from collections import defaultdict import numpy as np from nltk import pos_tag from nltk.corpus import stopwords from nltk.corpus import wordnet as wn from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize def sentence_preprocessing(Corpus, column_name, output_column_name): # Step - a :...
# -*- coding: utf-8 -*- """Download, convert, and summarize disease-disease relationships with BEL graph.""" import os from typing import Mapping, Optional from zipfile import ZipFile import pandas as pd from tqdm import tqdm from bio2bel.downloading import make_downloader from bio2bel.manager.bel_manager import BE...
import numpy as np import matplotlib.pyplot as plt def linear(t, initial: float, target: float): if(t.shape[0] == 0): return t assert(initial >= 0 and initial <= 1) assert(target >= 0 and target <= 1) x = np.linspace(0, 1, num=t.shape[0]) return (x * (target - initial)) + initial """ ...
import matplotlib.pyplot as plt import glob paths = glob.glob('warmup/c100/*/*/*/*.log') # Readingn the logs logs = [] for path in paths: with open(path) as f: logs.append(f.readlines()) # Fetching accuracies from the logs accuracies = [] for lines in logs: temp = [] for i, line in enumerate(lines...
import numpy as np import torch import torch.nn as nn from utils import torch as uto from s2cnn import s2_equatorial_grid, s2_near_identity_grid, S2Convolution, so3_equatorial_grid, SO3Convolution, so3_near_identity_grid class S2Layer(nn.Module): def __init__(self, bandwidths, features, use_equatorial_grid): ...
from annotypes import Anno, add_call_types, Any from malcolm.core import PartRegistrar, Context from malcolm.modules import ADCore, scanning, builtin with Anno("Sample frequency of ADC signal in Hz"): ASampleFreq = float # Pull re-used annotypes into our namespace in case we are subclassed APartName = ADCore.par...
from django.views.generic import TemplateView class TeamView(TemplateView): template_name = 'mobile/team.html' class PartnersView(TemplateView): template_name = 'mobile/partners.html'
"""Our tape is defined in multiple segments, each separated by a blank character. INPUT<Blank>OUTPUT This program solves the "Merge Overlapping Intervals" problem: Given a sorted list of possibly overlapping (opening, closing) intervals, merge them. Example: [[1, 5], [2, 3], [4, 6], [9, 11]] -> [[1, 6], [9, 11]] We...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivati...
"""The Document model. """ from sqlalchemy.ext.associationproxy import association_proxy from app import db from .base import Base from .unit import Unit from .mixins import NonPrimaryKeyEquivalenceMixin class Document(Unit, NonPrimaryKeyEquivalenceMixin): """A model for a single document file. Documents are...
from pickle import dumps, loads, HIGHEST_PROTOCOL, UnpicklingError from redis import Redis as _Redis from swiper.conf import REDIS class Redis(_Redis): def set(self, name, value, ex=None, px=None, nx=False, xx=False): """ Set the value at key ``name`` to ``value`` ``ex`` sets an expire ...
# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses # Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta # Minha solução inicial, sem usar lista # from sys import exit # # expression = str(input('\nDigite a expressão: ')).stri...
import os import numpy as np from keras import backend from keras.datasets.cifar import load_batch from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export def get_img_class(tf_BatchDataset): data = tf_BatchDataset.unbatch() images = np.array(list(data.map(lambda ...
import copy import pytest import pathlib import numpy as np from rasa.shared.nlu.training_data.message import Message from rasa.engine.storage.resource import Resource from rasa.engine.storage.local_model_storage import LocalModelStorage from rasa.engine.graph import ExecutionContext from rasa.shared.nlu.training_data....
import os import csv import xlwings as xw import numpy as np import pandas as pd from pathlib import Path from typing import Union, Iterable, Optional from pandas import DataFrame, Series from xlwings import Book from xlwings.constants import Constants as C from .utils import is_iterable, safe_path, temp_path class...
""" dataclass for dataset split parameters """ from dataclasses import dataclass, field @dataclass() class SplittingParams: """ Parameters """ test_size: float = field(default=0.25) random_state: int = field(default=31)
import os from coinbase.wallet.client import Client from portfolio import Portfolio API_KEY = os.environ.get("COINBASE_API_KEY") API_SECRET = os.environ.get("COINBASE_API_SECRET") Portfolio.init(API_KEY, API_SECRET) portfolio = Portfolio()
from tkinter.filedialog import askopenfilename def counting_letter(): file_name = askopenfilename() infile = open(file_name, "r") file_read = infile.read() count_for_a = 0 count_for_b = 0 count_for_c = 0 count_for_d = 0 count_for_e = 0 count_for_f = 0 count_for_g = 0 cou...
#! /usr/bin/env python3 import copy from typing import Dict, List, Set, Tuple from utils import get_file_lines class Food: # pylint: disable=too-few-public-methods def __init__(self, line: str): ingredients, allergens = line.split(' (contains ') self.ingredients = ingredients.split() se...
load("//java/private:common.bzl", "MAVEN_PREFIX") load("//java/private:maven_artifacts.bzl", "maven_artifacts") load("//java/private:pom.bzl", "pom_file") load("//java/private:publish.bzl", "maven_publish") def java_export( name, maven_coordinates, pom_template, module_exclude_patterns ...
import tensorflow as tf import numpy as np import poisson_problem import neural_networks import matplotlib.pyplot as plt from matplotlib import rc import matplotlib.ticker as ticker rc('font', **{'size':12, 'family':'serif', 'serif':['Computer Modern Roman']}) rc('text', usetex=True) def draw_magnitude_int_loss(x_r...
from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt import pickle import numpy bjst = {'dongsi_aq' : 0} ''' bjst = {'dongsi_aq' : 0, 'tiantan_aq' : 1, 'guanyuan_aq' : 2, 'wanshouxigong_aq' : 3, 'aotizhongxin_aq' : 4, 'nongzhanguan_aq' : 5, 'wanliu_aq' : 6, 'beibuxinqu_aq' : 7...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...