content
stringlengths
0
894k
type
stringclasses
2 values
from enum import Enum from services.proto import database_pb2 from services.proto import follows_pb2 class GetFollowsReceiver: def __init__(self, logger, util, users_util, database_stub): self._logger = logger self._util = util self._users_util = users_util self._database_stub = ...
python
from des import des from code import apsDB apscursor = apsDB.cursor() insert = "INSERT INTO aps.aps_table (login, senha) VALUES (%s, %s)" if __name__ == '__main__': inputkey = open("key.txt", 'r') key = inputkey.read() user = input("Digite seu usuário: ") textin= input("Digite sua me...
python
# -------------- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split # path- variable storing file path #Code starts here df=pd.read_csv(path) #displaying 1st five columns print(df.head(5)) print(df.columns[:5]) #distributing features X=df.drop('Price',axis=1) ...
python
""" CS 156a: Final Exam Anthony Bartolotta Problems 13,14,15,16,17,18 """ import numpy as np import sklearn.svm as svm def pseudoInverse(X): # Calculate pseudo-inverse tempM = np.linalg.inv(np.dot(np.transpose(X), X)) xPseudo = np.dot(tempM, np.transpose(X)) return xPseudo def generateData(nSamples)...
python
"""get quadratures Calculate the times of quadrature for a series of objects with given ephemerides between two nights in a given observatory Input file must be: name ra(deg) dec(deg) epoch period The output will be: A per target list containing the times of quadratures """ import argparse from datetime impor...
python
import os from googlecloudsdk.core.updater import local_state class Error(Exception): """Exceptions for the endpoints_util module.""" class ScriptNotFoundError(Error): """An error when the parser in appcfg fails to parse the values we pass.""" def __init__(self, error_str): super(ScriptNotFoundError, ...
python
#!/usr/bin/env python3 """ Find new papers in XML tarball files and parse them. """ import csv import multiprocessing as mp import os import pickle import tarfile from collections import Counter from pathlib import Path import lxml.etree as ET import numpy as np import pandas as pd import spacy from utils import se...
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : account.py @Time : 2021/05/11 @Author : levonwoo @Version : 0.1 @Contact : @License : (C)Copyright 2020-2021 @Desc : 账户模块 ''' # here put the import lib import uuid from QuadQuanta.portfolio.position import Position from QuadQuanta.da...
python
API_KEY="" API_SEC="" API_PHR=""
python
class PycamBaseException(Exception): pass class AbortOperationException(PycamBaseException): pass class CommunicationError(PycamBaseException): pass class InitializationError(PycamBaseException): pass class InvalidDataError(PycamBaseException): pass class MissingAttributeError(InvalidDataE...
python
# -*- coding: utf-8 -*- # -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMult...
python
import os import numpy as np if os.environ.get("PYQUANT_DEV", False) == "True": try: import pyximport pyximport.install( setup_args={"include_dirs": np.get_include()}, reload_support=True ) except Exception as e: import traceback traceback.print_exc() ...
python
#coding:utf-8 import tkinter from tkinter import ttk from Icon import ICON from PIL import Image, ImageTk import queue import cv2 import numpy as np import sys import platform OS = platform.system() if OS == 'Windows': import ctypes def DisplayWorker(frame_shared, camera_width, camera_height, measure_params): ...
python
def oper(op, a, b): op = str(op) a = float(a) b = float(b) if op == "*": return a * b elif op == "/": return a / b elif op == "+": return a + b elif op == "-": return a - b elif op == "%": return a % b elif op == "^": return a**b ope...
python
""" Given an integer n, return the first n-line Yang Hui triangle. Example 1: Input : n = 4 Output : [ [1] [1,1] [1,2,1] [1,3,3,1] ] Solution: Construct pascal triangle line by line. """ class Solution: """ @param n: a Integer @return: the first n-line Yang Hui's triangle """ def calcYan...
python
import sys a = sys.stdin.readline() sys.stdout.write(a) sys.stderr.write(a)
python
#!/usr/bin/python # -*- coding: UTF-8 -*- import sys from fn.core import main ROOT = "http://seriesblanco.com" URL_TREE = ROOT+"/serie/1653/rick-and-morty.html" URL = ROOT+"/serie/1653/temporada-{}/capitulo-{}/rick-and-morty.html" main(sys.argv, ROOT, URL_TREE, URL)
python
class Partner: database = def __init__(self, name, age, likes_me): self.database.append(self) self.name = name self.age = age self.likes_me = likes_me Maria = Partner("Maria", 21, False) Florian = Partner("Florian", 116, False) Eve = Partner("Eve", 22, True) Fiona = Partner("...
python
import os import sqlalchemy as sa from dotenv import load_dotenv load_dotenv() def connect(): user = os.environ.get("DB_USER") db_name = os.environ.get("DB_NAME") db_pass = os.environ.get("DB_PASS") db_port = os.environ.get("DB_PORT") db_host = os.environ.get("DB_HOST") # print(user, db_name,...
python
import cv2 import numpy as np import sys path = '../resources/haarcascades/haarcascade_frontalface_default.xml' video = cv2.VideoCapture('/dev/video0') if not video.isOpened(): print('Open video device fail') sys.exit() def empty(p): pass cv2.namedWindow('Camera') cv2.createTrackbar('Scale', 'Camera', ...
python
# vim: set fenc=utf8 ts=4 sw=4 et : import sys import xml.sax import imp from os import path from signal import signal, SIGINT from shutil import copytree, ignore_patterns from pkg_resources import resource_filename from configparser import ConfigParser from .logging import * from .conf import Conf from .plugin impor...
python
from .CancerModel import CancerModel # , CancerModelIterator from .ExperimentalCondition import ExperimentalCondition # , ExpCondIterator from .TreatmentResponseExperiment import TreatmentResponseExperiment # , TREIterator
python
import os import yaml import shutil from dl_playground.path import MODEL_ROOT def load_and_save_config(config_path, model_path): """Loads the config and save a copy to the model folder.""" with open(config_path) as f: config = yaml.safe_load(f) model_path = os.path.expanduser(model_path) # ...
python
# ****************************************************************************** # This file is part of the AaMakro5oul project # (An OSC/MIDI controller for Ableton Live with DJ features) # # Full project source: https://github.com/hiramegl/AaMakro5oul # # License : Apache License 2.0 # Full license: https://githu...
python
import sys, getopt, signal from test_threads import * from sdkcom import * from network_delegation import * # for local def add_threads_dev(threads): # Delegate, 2 threads threads.add_threads(DelegateTxLoad.dev(2)) # UnDelegate, 2 threads threads.add_threads(UnDelegateTxLoad.dev(2)) # WithdrawRew...
python
from functions import * import subprocess import os import traceback from sys import exit if __name__ == '__main__': try: get_admin_permission() if not os.popen("powershell.exe Get-AppXPackage MicrosoftCorporationII.WindowsSubsystemForAndroid").read().strip(): input("Windows Subsystem f...
python
import uuid from django.db.models import Model, UUIDField, DateTimeField class TimeStampedModel(Model): # id = UUIDField( # primary_key=True, # default=uuid.uuid4, # editable=False # ) created_at = DateTimeField( auto_now_add=True, verbose_name='Created datetim...
python
import pickle import unittest from typing import Optional import boost_histogram as bh import numpy as np from bootstraphistogram import BootstrapHistogram def _standard_error_mean(size, sigma=1.0): return sigma / np.sqrt(size) def _standard_error_std(size, sigma=1.0): return np.sqrt(sigma ** 2 / (2.0 * s...
python
''' Simple build error dialog, access to logs etc. ''' import os.path import os os.environ['NO_AT_BRIDGE'] = '0' import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk # pylint:disable=no-name-in-module class Handler(object): ''' Implicit signal handlers declared in glade. ''' def...
python
tot18 = 0 totM = 0 tot20 = 0 while True: idade = int(input('idade: ')) sexo =' ' while sexo not in 'MF': sexo = str(input('Escolha o sexo:[M/F]: ')) if idade >= 18: tot18 += 1 if sexo == 'M': totM += 1 if sexo == 'F': tot20 += 1 r = ' ' wh...
python
# coding: utf-8 import uuid def createUUID(): return uuid.uuid4().fields[ 0 ] def createUUIDList( listSize ): ret = [0] * listSize for i in range( listSize ): ret[ i ] = uuid.uuid4().fields[ 0 ] return ret def float2int( v, defaultValue = 0 ): if( isinstance( v, float ) ): ret...
python
# -*- coding: utf-8 -*- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Time Series Analysis -- Python/NumPy implementation # # Author: Jakob Rørsted Mosumgaard # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##########################################...
python
# Generated by Django 2.2.13 on 2021-11-17 18:05 from django.db import migrations, models import ic_marathon_app.validators class Migration(migrations.Migration): dependencies = [ ('ic_marathon_app', '0010_auto_20201101_0745'), ] operations = [ migrations.AlterField( model_n...
python
import sys sys.path.insert(0,'../..') import json import requests from tqdm import tqdm from lxml import etree from app import base heroes_url = 'http://heroesjson.com/heroes.json' image_prefix = 'http://us.battle.net/heroes/static' class ChampionImporter(base.ChampionImporter): def get_objects(self): ...
python
import mysql.connector from flask import Flask, request, jsonify, redirect import json from datetime import datetime from furl import furl app = Flask(__name__) mydb = mysql.connector.connect( host="127.0.0.1", #port=3308, #user="python_boi", user="admin", #passwd="qrXEoFtaVXGkuJHT", passwd=""...
python
import sys from time import sleep import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event,ai_settings, screen,ship, bullets): """Responde a pressionamentos de tecla.""" # Move a espaçonave para a direira if event.key == pygame.K_RIGHT: ship.moving_right = Tru...
python
''' gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API. The project is distributed under a MIT License . ''' __author__ = "David Winslow" __copyright__ = "Copyright 2012-2018 Boundless, Copyright 2010-2012 OpenPlans" __license__ = "MIT" from geoserver.support import R...
python
from pandas import * from math import ceil from sklearn.ensemble import GradientBoostingRegressor, VotingRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split import numpy as np # Load the data print('Reading the data...') data = read_csv("insurance.csv") print(...
python
import math as math # import random # class Particle (object): # """Paticle module""" # def __init__ (self, mass=1.0, x=0.0, y=0.0, vx=0.0, vy=0.0): # self.mass = mass # self.x = x # self.y = y # self.vx = vx # self.vy = vy # # def __str__ (self): # ...
python
import pytest from spellbot.settings import Settings class TestMigrations: @pytest.mark.nosession def test_alembic(self, settings: Settings): from spellbot.models import create_all, reverse_all create_all(settings.DATABASE_URL) reverse_all(settings.DATABASE_URL)
python
settings = { "aoi":"https://gdh-data.ams3.digitaloceanspaces.com/scarborough.geojson", "systems":["GI", "TRANS", "URBAN", "AG", "HYDRO"], "outputdirectory":"output", "workingdirectory": "working", "sentinelscene": "S2B_MSIL1C_20171126T112359_N0206_R037_T30UXF_20171126T132429", "rivers":"rivers/rivers.shp", "w...
python
# 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, software # distributed under the Li...
python
#!/usr/bin/env python import sys import ast import operator def main(): with open(sys.argv[1]) as infile: for line in infile: topic = ast.literal_eval(line) sorted_x = sorted(topic.items(), key=operator.itemgetter(1), reverse=True) print " ".join([i[0] for i in sorted_x...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
python
import os from random import shuffle import csv def getGenderDict(): return { 'aia' : ['female',0], 'bonnie' : ['female',0], 'jules' : ['male',1], 'malcolm' : ['male',1], 'mery' : ['female',0], 'ray' : ['male',1] } def getEmotionDict(): return { 'anger' : 0, 'disgust' : 1, 'fear' : 2, 'joy'...
python
# coding: utf-8 #model url: http://nixeneko.2-d.jp/hatenablog/20170724_facedetection_model/snapshot_model.npz import urllib.request import os def download_model(url, dest): destdir = os.path.dirname(dest) if not os.path.exists(destdir): os.makedirs(destdir) print("Downloading {}... \nThis ma...
python
from cartography.driftdetect.model import load_detector_from_json_file from cartography.driftdetect.detect_drift import perform_drift_detection from unittest.mock import MagicMock def test_detector_no_drift(): """ Test that a detector that detects no drift returns none. :return: """ mock_session =...
python
# -*- coding: utf-8 -*- """ deserializer interface module. """ from abc import abstractmethod from threading import Lock from pyrin.core.structs import CoreObject, MultiSingletonMeta from pyrin.core.exceptions import CoreNotImplementedError class DeserializerSingletonMeta(MultiSingletonMeta): """ deserializ...
python
import csv import sys import os import os.path as path from datetime import datetime import math import pandas as pd from utility import Logger as log DEBUG = False def log(message): if DEBUG: print(message) def main(argv): workspace = '' # datasets = { # 'pecanstreet': ['California'...
python
from rqalpha.api import * def init(context): context.S1 = "510500.XSHG" context.UNIT = 10000 context.INIT_S = 2 context.MARGIN = 0.08 context.FIRST_P = 0 context.holdid = 0 context.sellcount = 0 context.inited = False logger.info("RunInfo: {}".format(context.run_info)) def before...
python
#// #//------------------------------------------------------------------------------ #// Copyright 2007-2011 Mentor Graphics Corporation #// Copyright 2007-2011 Cadence Design Systems, Inc. #// Copyright 2010 Synopsys, Inc. #// All Rights Reserved Worldwide #// #// Licensed under the Apache License, Version...
python
def rt(ip): return [10,15,20]
python
from unittest import TestCase from ua_model.utils import validate_branch_point_positions class TestFunctionUtils(TestCase): def test_validate_branch_point_positions(self): with self.subTest(msg='valid parameters'): self.assertIsNone(validate_branch_point_positions(t_0=0.1, t_in=1.0)) ...
python
# -*- coding: utf-8 -*- # Copyright 2018 Nagoya University (Tomoki Hayashi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """TTS Interface realted modules.""" from espnet.asr.asr_utils import torch_load try: import chainer except ImportError: Reporter = None else: class Reporter(chainer....
python
# Generated by Django 2.2.5 on 2019-09-09 17:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('product', '00...
python
#!/usr/bin/env python3 from data_stack.dataset.factory import BaseDatasetFactory from data_stack.dataset.iterator import DatasetIteratorIF from data_stack.dataset.meta import MetaFactory from outlier_hub.datasets.toy_datasets.uniform_noise.iterator import UniformNoiseIterator from typing import List, Tuple, Dict, Any ...
python
n = int(input()) // 4 print(n * n)
python
import pandas as pd import numpy as np from web_constants import * from signatures import Signatures, get_signatures_by_mut_type from project_data import ProjectData, get_selected_project_data from compute_reconstruction import compute_reconstruction from scale_samples import scale_samples def plot_reconstruction(ch...
python
# # PySNMP MIB module ADTRAN-IF-PERF-HISTORY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-IF-PERF-HISTORY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:59:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
python
from collections import OrderedDict import gin import matplotlib.cm as cm import numpy as np import pandas as pd import plotly.graph_objs as go import seaborn as sns import torch from graphviz import Digraph from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA i...
python
#!/usr/bin/env python3 # coding: utf-8 from zencad import * def section(w, h, l, t, d, d2): return ( box(2 * t + w, t + l, 2 * t + h) - box(w, l, h).translate(t, 0, t) - box(w - 2 * d, l, h + 2 * t).translate(t + d, 0, 0) - box(w, l + t, h - d2).translate(t, 0, d2 + t) ) # n...
python
import uuid import time import hashlib import json def get_event_metadata(): return { "run_id": str(uuid.uuid1()), "event_id": str(uuid.uuid4()) } # python does some pretty pretting to json objects, we have to change the # separators to have a bare bone stringifying/dumping function, which wi...
python
"""Tables Utilities""" import logging from typing import Dict import numpy as np import tensorflow as tf from deepr.utils.field import TensorType LOGGER = logging.getLogger(__name__) class TableContext: """Context Manager to reuse Tensorflow tables. Tensorflow does not have a ``tf.get_variable`` equival...
python
#!/usr/bin/env python from nbformat import v3, v4 import os import sys with open(sys.argv[1]) as f: text = f.read() nb = v3.reads_py(text) nb = v4.upgrade(nb) with open(os.path.splitext(sys.argv[1])[0] + ".ipynb", "w") as f: f.write(v4.writes(nb))
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import List import functools from .plot_manager import plot_manager class Plot: """ Plotting function wrapper. """ def __init__(self, name, data_requirements: List, func): self.plot_func = func self.data_requirements = data_r...
python
from django.shortcuts import render from branca.element import MacroElement from jinja2 import Template # generic base view from django.views.generic import TemplateView #folium import folium import geojson from folium import plugins import pandas as pd from folium.plugins import MarkerCluster # import ee # fr...
python
from operator import attrgetter from typing import Set import pandas as pd from investmentstk.models.bar import Bar BarSet = Set[Bar] def barset_from_csv_string(csv_string: str) -> BarSet: """ Expected format: date,open,high,low,close without headers """ barset = set() rows = csv_stri...
python
import re from typing import Optional from pydantic import BaseModel, validator class InputQuery(BaseModel): dataStructureName: str version: str population: Optional[list] include_attributes: Optional[bool] = False @validator('version') def check_for_sem_ver(cls, version): pattern = ...
python
from django.db import models class ResourceGroupTextAttributeDefinition(models.Model): class Meta: unique_together = ('name', 'resource_group',) name = models.CharField(max_length=100, blank=False) resource_group = models.ForeignKey('ResourceGroup', ...
python
from pathlib import Path from tempfile import TemporaryDirectory import json import os import unittest from moto import mock_s3 from schematics.exceptions import DataError import boto3 as boto from hidebound.exporters.s3_exporter import S3Config, S3Exporter # ----------------------------------------------------------...
python
#!/usr/bin/python ##------------------------------------------------------------------- ## @copyright 2017 DennyZhang.com ## Licensed under MIT ## https://www.dennyzhang.com/wp-content/mit_license.txt ## ## File : refresh_containers.py ## Author : Denny <contact@dennyzhang.com> ## Description : Restart a list of dock...
python
from barcode import Code128 from svgwrite import cm, mm, px import svgwrite Drawing = svgwrite.Drawing class Size(): def __init__(self, w, h, unit='px'): self.width = w self.height = h self.unit = unit def getS(self, float_precision=2): """String Size -> width[unit], height[uni...
python
""" Simple driver for Monarch GO AT modemcontrol commands """ from time import sleep from logging import getLogger from ..provisioner import ProvisionerError ASCII_EOT = b'\x04' class AtDriver(): """ Low-level AT modem command driver. """ def __init__(self, fwinterface): """ Connstr...
python
import abc import filecmp import inspect import os import shutil from ctranslate2.specs import catalog from ctranslate2.specs.model_spec import ModelSpec def _list_specs(): return { symbol: getattr(catalog, symbol) for symbol in dir(catalog) if inspect.isclass(getattr(catalog, symbol)) an...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render def base(request): return render(request, 'base.html', {}) def report(request): context = {'title': '报表平台'} return render(request, 'reports/report.html', context) def histogram(request): """柱状图""" ...
python
#!/usr/bin/python hostname = 'localhost' username = 'root' password = '' database = 'pythonconn' # Simple routine to run a query on a database and print the results: def doQuery( conn ) : cur = conn.cursor() ''' first='Shreyas' last='Patil' user='Flamestriker' passw='12345' ''' # cur.ex...
python
# Processando uma resposta de API import requests # Faz uma chamada de API e armazena a resposta url = 'https://api.github.com/search/repositories?\ q=language:python&sorts=stars' r = requests.get(url) print('Status code:', r.status_code) # Armazena a resposta da API em uma variável response_dict = r.json() print('T...
python
import json, os import copy class sesh: def __init__(self, sessionUUID, TotalEvents, VersionControlEvents, EditEvents, CommandEvents, DocumentEvents, ActivityEvents, NavigationEvents, TestRunEvents, WindowEvents, CompletionEvents, SystemEvents, DebuggerEvents, SolutionEvents, IDEStateEvents, UndefinedEvents): ...
python
# -*- coding: utf-8 -*- # Copyright (c) 2017, masonarmani38@gmail.com and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestProductionWaste(unittest.TestCase): pass def tear_down(): filters =dict({ "from" : "01-09-2017 17:49:55", "to":"01-12-2017 17...
python
import os import time import torch from options.test_options_CMU import TestOptions from torch.autograd import Variable import numpy as np from PIL import Image from torch.utils.data import DataLoader # from utils.label2Img import label2rgb from dataloader.transform import Transform_test from dataloader.dataset import ...
python
#!/usr/bin/env python import os import smtplib import mimetypes import argparse from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime....
python
# flake8: noqa from .gs_counterfactuals import growing_spheres_search
python
import logging import random import numpy as np connect_success = True logger = logging.getLogger(__name__) set_l3t_count = 0 clear_l3t_count = 0 def connect(ami_str): logger.debug('simulated pyami connect') if not connect_success: raise RuntimeError('simulated fail') else: Entry._conne...
python
# -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest import os.path from getpass import getuser from os import remove, rmdir from socket import gethostn...
python
# Copyright (c) 2015, VMRaid Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals def execute(): from vmraid.installer import remove_from_installed_apps remove_from_installed_apps("shopping_cart")
python
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' from django.db import models from publications.models.orderedmodel import OrderedModel from string import replace, split, strip class Type(OrderedModel): class Meta: ...
python
import keras # noqa: F401 import numpy as np import tensorflow as tf import wandb from wandb.keras import WandbCallback def main(): wandb.init(name=__file__) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(3, 3, activation="relu", input_shape=(28, 28, 1))) model.add(tf.keras.la...
python
class NotImplemented(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, args, kwargs) class NoSuchVirtualMachine(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, args, kwargs) class InvalidOperation(Exception): def __init__(self, *args, **kw...
python
from .wide_resnet50 import WideResNet50 __all__ = ["WideResNet50"]
python
# -*- coding: utf-8 -*- """ Created on Mon Mar 28 16:35:56 2022 @author: Pedro """ def score(mode: str, puntosp1: int, puntosp2: int, name1: str, name2: str, puntajes: tuple, auto_ch: str)->str: """Funcion que simula un game de Tenis, ya sea de forma manual, es decir con intervencion del usuario en los puntos...
python
import json import sys class PolicyResolver(): def __init__(self): self.desc = [] self.desc_by_label = {} def read_json(self, fname): ''' reads the JSON produced by the cle preprocessor ''' with open(fname) as f: fs = f.read() desc1 = jso...
python
""" Unit tests: testing a small bit of code like function or class in isolation of the system From the developers perspective """ import mimetypes import os from pathlib import Path import cv2 import pytest from ..colordetect import ColorDetect, VideoColor, col_share def test_image_vid_parsed_to_class(image, video...
python
""" Main application """ import logging from aiohttp import web from .db import setup_db from .rest import setup_rest, create_router from .session import setup_session from .settings import CONFIG_KEY log = logging.getLogger(__name__) def create(config): """ Initializes service """ log.debug("I...
python
import sys import os def find_directories(directory): for dirpath, dirs, files in os.walk(str(directory)): for dr in dirs: print(dr) if __name__ == '__main__': find_directories(sys.argv[1])
python
''' Programa para jugar al tateti Valentin Berman 13/02/20 ''' # Constantes NADA = '-' X = 'x' O = 'o' MOV = 'hay movimientos' GANA_X = 1 GANA_O = -1 EMPATE = 0 MAX = 'max' # el jugador con X es el MAX MIN = 'min' # el jugador con O es el MIN # Clases class Tateti(): ''' Clase que define un tablero de tateti ...
python
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model class PositionUnit(Enum): PIXELS = "PIXELS" PERCENTS = "PERCENTS"
python
from ares.Lib import Ares """ GENERAL PURPOSE --------------- This script will aim to show how to store data into a database - nothing more Finally database_connection_2.py will show a simple example of data extraction using the AReS connectors capabilities (see the scripts example connectors.py for more info),do s...
python
import numpy as np from boid import Boid width = 100 height = 100 flock = [Boid(*np.random.rand(2)*100, width, height) for _ in range(5)] def updatePositions(): global flock for boid in flock: boid.apply_behaviour(flock) boid.update() boid.edges() print("-----FRAME 1-----") updatePos...
python
__version__ = "0.0.1" version = __version__
python
import pytest from django.contrib.admin.options import get_content_type_for_model from django.contrib.auth.models import Permission from django.contrib.gis.geos import Point from django.utils.timezone import now from rest_framework.authtoken.models import Token from rest_framework.test import APIClient from bikesharin...
python