content
stringlengths
5
1.05M
from premade import * from gen import * from pdataset import * from sprite import * from sprites import * import premade import gen import dataset import sprite import sprites
from setuptools import setup import fcm version = fcm.VERSION requires = [ 'Django==1.10.5', 'djangorestframework>=3.3.1', 'mock==1.0.1', 'pytz==2015.4', 'requests==2.7.0', ] setup(name='django-fcm-android-ios', version=version, author='Ashish and Sunit', author_email='developerbywee...
from typing import Optional, Dict, Any, List from overrides import overrides import torch from allennlp.modules.token_embedders import PretrainedTransformerEmbedder, TokenEmbedder from allennlp.nn import util from allennlp_models.common.pretrained_transformer_masking_embedder import PretrainedTransformerMaskingEmbed...
from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 import time SHAPE_LEN = 4096 NUM_ITER = 1000 GB = 1024 * 1024 * 1024 NUM_REPLICAS = 48 def build_net(net_name, cross_socket): init_net = core.Net(net_name + "_init") init_net.Proto().type = "async_scheduling" numa_device_op...
import numpy as np def force_closure(contact,normals,num_facets,mu,gamma): c1 = contact[:,0] c2 = contact[:,1] f1 = normals[:,0] f2 = normals[:,0] v = (c2-c2).astype(float) theta1 = np.arccos((f1.dot(v))/(np.linalg.norm(f1)*np.linalg.norm(v))) theta2 = np.arccos((f2.dot(-v))/(np.linalg.norm(f2)*np.linalg.norm(-...
from balebot.models.messages.banking.bank_message import BankMessage from balebot.filters.filter import Filter class BankMessageFilter(Filter): def match(self, message): if isinstance(message, BankMessage): return self.validator(message) if self.validator else True else: re...
from django.urls import path, include from social.views import * urlpatterns = [ path('profile/<str:username>/', ProfileViewSet.as_view()), path('profile/', ProfileViewSet.as_view()), path('change-pic/', SetProfilePicViewSet.as_view()), path('pictures/', PaginationApiView.as_view()), path('picture...
""" Contains implementation for raw resample. """ import logging import matplotlib.pyplot as plt import numpy as np from meggie.utilities.messaging import messagebox from meggie.utilities.messaging import exc_messagebox from meggie.utilities.threading import threaded from meggie.actions.raw_resample.dialogs.resampli...
from flask_wtf import FlaskForm from wtforms import SubmitField, DecimalField from wtforms.fields.html5 import DateField from wtforms.validators import DataRequired from datetime import datetime class MaxesForm(FlaskForm): squat = DecimalField("Squat Max", validators=[DataRequired()], default=315.0) bench = D...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 mengskysama # Copyright 2016 Howard Liu # # 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/LIC...
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check class ResizeImages3D(function_node.FunctionNode): def __init__(self, output_shape): self.out_H = output_shape[0] self.out_W = output_shape[1] self.out_D = output_shape[2]...
"""File containing functions for the creation of transactions, input and output scripts.""" import struct from construct import Byte from construct import Bytes from construct import StaticField from construct import Struct from construct import UBInt32 def create_input_script(psz_timestamp): """Using a timestam...
def get_names(): print('Please enter your first name:') first_name = input() print('Please enter your first name:') second_name = input() print('Please enter your first name:') last_name = input() print('{} {} {}'.format(first_name, second_name, last_name)) if __name__ == '__main__': ...
from enum import Enum class CMD_RES(Enum): OK = 0 ERR = 1 WAIT = 2
import csv def save_file(data, filename): """Save data as csv. Args: data (list of lists): Data to save. filename (str): Name of the file. Examples: >>> data = [['0.0416667', '443', '205'], ['0.0833333', '444', '206']] >>> save_file(data, 'file.csv') >>> ...
import uuid from aquascope.webserver.data_access.conversions import group_id_to_container_name from aquascope.webserver.data_access.storage.blob import (exists, create_container, upload_blob, generate_download_sas, make_blob_url) EXPORT_SAS_EXPIRY_MINUTES = 14...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import fhqtest import libtestknowledgebase try: fhqtest.init_enviroment() libtestknowledgebase.run_tests() finally: fhqtest.deinit_enviroment()
nombre = raw_input ("Dame tu nombre") print "Hola" + nombre print "Como estas?" + nombre Estas = raw_input ("Dime como estas") print "yo tambien estoy" + "Bien" + nombre print "cuantos anios tienes?" + nombre Edad = raw_input ("edad") print "mi edad es de 25 minutos" respuesta = raw_input ("Que piensas de mi edad?") ...
#!/usr/bin/env python # -*- encoding: UTF-8 -*- ''' @File : base_bs4.py @Time : 2021/02/24 15:42:38 @Author : Kearney @Contact : 191615342@qq.com @Desc : 在base的基础上,使用bs4提取Bing搜索首页的标题 <title>微软 Bing 搜索 - 国内版</title> ''' import requests from bs4 import BeautifulSoup r = requests.get('https://...
import json from pathlib import Path import pytest from piqe_ocp_lib.api.resources import OcpApps, OcpProjects, OcpServices, OcpTemplates @pytest.fixture(scope="module") def ocp_services(get_kubeconfig) -> OcpServices: return OcpServices(get_kubeconfig) @pytest.fixture(scope="module") def ocp_project(get_kube...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.forms import ModelForm import re
class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): if self.current > self.high: #Stop condition of iteration raise StopIteration #Stop condition of iteration el...
from wordsiv.sentence_models_sources import WordCountSource, RandomModel from pathlib import Path import json # Assuming installed as directory (zip_safe=False) HERE = Path(__file__).parent.absolute() with open(HERE / "meta.json", "r") as f: meta = json.load(f) # Sources should always be prefixed with the packa...
############ 1.8. Decomposição cruzada ############ # O módulo de decomposição cruzada contém estimadores supervisionados para redução e regressão de dimensionalidade, pertencentes à família “Partial Least Squares”. # https://scikit-learn.org/stable/auto_examples/cross_decomposition/plot_compare_cross_de...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file entry implementation using the CPIOArchiveFile.""" from __future__ import unicode_literals import unittest from dfvfs.path import cpio_path_spec from dfvfs.path import os_path_spec from dfvfs.resolver import context from dfvfs.vfs import cpio_file_e...
from typing import Tuple import requests from bs4 import BeautifulSoup from hospital_types import ( AppointmentAvailability, ScrapedData, HospitalAvailabilitySchema, ) def parse_pch_nantou() -> ScrapedData: r = requests.get( "http://web2.pch.org.tw/booking/Covid19Reg/Covid19Reg.aspx?InsType=1"...
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.test import TestCase User = get_user_model() class TestFixPr...
import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = False #ADMINS = [('christos', 'christosstath10@gmail.com')] if not DEBUG: SESSION_COOKI...
from typing import List class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: res = [] index = 0 for i in range(1, n+1): res.append('Push') if i == target[index]: index += 1 else: res.append('Pop') ...
from bar import Bar from guido_rocks import Google class Foo(object): def bar(self): return 'hello,world' def yum(self): bar = Bar() return bar.mitzvah() def what_is_love(self,i_am): bar = Bar() return bar.give_me_some(i_am) def go_google(self): return Google().mobile()
import argparse import logging import os import random import sys import numpy as np import torch import torch.backends.cudnn as cudnn from torch.cuda import is_available import torch.nn as nn from torch.utils.data import DataLoader from tqdm import tqdm from datasets.dataset import SegmentationDataset from utils impor...
#Source https://nft.storage/api-docs/ import requests # from scipy.io import wavfile # import argparse # import numpy as np import json import pprint class NFTStorage: def get_creds(self): with open("creds.json") as f: cred = json.loads(f.read()) return cred["NFTStorage"] def u...
from pathlib import Path import pytest import toml import libcnb @pytest.fixture def mock_store_path(): yield Path("tests") / "testdata" / "store.toml" @pytest.fixture def mock_launch_path(): yield Path("tests") / "testdata" / "launch.toml" @pytest.fixture def mock_build_path(): yield Path("tests") ...
from iso8601 import parse_date from pyramid.security import Allow from schematics.transforms import whitelist from schematics.types import IntType, URLType, BooleanType from schematics.types import StringType from schematics.types.compound import ModelType from zope.interface import implementer, provider from openproc...
import pandas as pd from pandas.api import types as pdt from visions.backends.pandas.series_utils import series_not_empty, series_not_sparse from visions.types.time_delta import TimeDelta @TimeDelta.contains_op.register @series_not_sparse @series_not_empty def time_delta_contains(series: pd.Series, state: dict) -> b...
# -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework_jwt.compat im...
""" COCO dataset parser Copyright 2020 Ross Wightman """ import numpy as np from pycocotools.coco import COCO from .parser import Parser from .parser_config import CocoParserCfg class CocoParser(Parser): def __init__(self, cfg: CocoParserCfg): super().__init__( bbox_yxyx=cfg.bbox_yxyx, ...
from seafileapi.client import SeafileApiClient def connect(server, username, password): """ Connect to Seafile server :param server: address of the seafile server :param username: username :param password: password :return: :class:`SeafileApiClient`. """ seafile_client = SeafileApiClie...
# Django starts so that shared_task will use this app. from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app',)
import hashlib import json import shutil import subprocess from datetime import datetime from pathlib import Path from bson import ObjectId, json_util from pymongo import MongoClient from hive.settings import hive_setting from hive.util.constants import DATETIME_FORMAT from hive.util.common import did_tail_part, crea...
import sys from pathlib import Path from typing import List from setuptools import find_packages, setup # type: ignore assert sys.version_info >= (3, 7, 0), "Requires Python 3.7+" CURRENT_DIR = Path(__file__).parent MAJOR = 0 MINOR = 0 MICRO = 3 NAME = "scrapefruit-jfk" VERSION = f"{MAJOR}.{MINOR}.{MICRO}" def...
### # Copyright (c) 2018, cottongin # Copyright (c) 2020, oddluck <oddluck@riseup.net> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above ...
from keras.preprocessing import image from tqdm import tqdm import numpy as np from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(224, 224)) # convert PIL.Image.Image type to 3...
# Retrieve the version number of methpat from the setup.py file. # This solution was suggested on Stack Overflow: # http://stackoverflow.com/questions/2058802/how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package import pkg_resources # part of setuptools methpat_version = pkg_resources.require("meth...
from django.conf.urls import url from django.contrib import admin from django.urls import reverse from django.contrib.auth import views as auth_views from ravens_metadata_apps.raven_auth import views, views_login #, get_extra_context urlpatterns = [ #url(r'^login/$', auth_views.login, name='login'), url(r'sign...
from django.db import models from django.contrib.auth.models import AbstractUser from django_fields import DefaultStaticImageField # Create your models here. class Profile(AbstractUser): start_year=models.CharField(max_length=200, null=True) sex= models.CharField(max_length=5, null=True) prof...
import json from glob import glob from pathlib import Path import click import yaml from jsonschema import validate @click.command() @click.argument("filespecs", nargs=-1) def validate_recipe(filespecs): schemajson = ( Path(__file__).parent.parent.parent / "schema/snowfakery_recipe.jsonschema.json" )...
# -*- coding: utf-8 -*- # tomolab # Michele Scipioni # Harvard University, Martinos Center for Biomedical Imaging # University of Pisa from ...Core.SimpleWrap import find_c_library, load_c_library, localpath, call_c_function, filepath from ..PetLink import petlink import numpy as np import uuid from IPython.display i...
# Test quiver-time import keras as ks from quiver_engine import server # Load model model = ks.models.load_model('models/my_bestmodel-win.h5') # Launch server server.launch(model, classes=range(7), input_folder='input/')
import cv2 import numpy as np def open_capture(camera_int, width, height): capture = cv2.VideoCapture(camera_int) while True: if capture.isOpened(): break capture.open() capture.set(cv2.CAP_PROP_FRAME_WIDTH, width) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height) return...
""" Django settings for testapp project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os #...
"""Defined some middlewears for my app. Yep, I am sufficiently sloth to make them in my own, so I just copied them from official documentation. https://docs.aiohttp.org/en/stable/web_advanced.html#middlewares """ import aiohttp_jinja2 from aiohttp import web async def handle_404(request): """ 404-Error handling ...
# Library imports import random # Project imports from board import Board from player import HumanPlayer, AiPlayer from view import View class Game(object): def __init__(self, size=3): """ Main game logic class """ # Initialise vars self.board = Board(size) self....
class CountryConstants: ID = None FLAG = None MARCH = None def __init__(self, id, flag, march): self.ID = id self.FLAG = flag self.MARCH = march GREAT_BRITAIN = CountryConstants(1, "🇬🇧", "For the Queen!!!") FRANCE = CountryConstants(2, "🇫🇷", "Crush the Bastille...
import os import argparse import matplotlib.pyplot as plt from data_generators.coco import CocoDataset from visual_tools import GuiCocoViewer if __name__ == '__main__': parser = argparse.ArgumentParser( description='Inspect COCO dataset.') parser.add_argument('-d', '--dataset', required=True, ...
import torch import torch.nn as nn from ..layers.convolutions import Convolutional, Separable_Conv_dila, Separable_Conv, Deformable_Convolutional import torch.nn.functional as F from ..layers.attention_blocks import SELayer class SPP(nn.Module): def __init__(self, depth=512): super(SPP,self).__init__() ...
from platform import platform import lib.conf ARM = False if "arm" in platform(): # nocov ARM = True from neopixel import NeoPixel import board class Panel: """Class representing the Longruner light panel.""" def __init__(self): """Construct.""" self.config = lib.conf.config()[...
# -*- coding: utf-8 -*- ''' Web Flayer organizer module for JSON-LD Recipes In order to use this plugin, a ``jsonld_domains`` table needs to be created: .. code-block:: sql create table jsonld_domains (domain text unique); ''' # Python import json import urllib # 3rd party import requests from bs4 import Beauti...
# Ein kleines Script dass anscheinend gerne bei Vorstellungsgesprächen abgefragt wird. # 1. Es sollen alle Zahlen von 0 bis 100 ausgegeben werden # 2. Ist die ausgegebene Zahl ein vielfaches von 3, schreibe Fizz # 3. Ist die ausgegebene Zahl ein vielfaches von 5, schreibe Buzz # 4. Trifft 2. und 3. zu, schreibe FizzBuz...
"""Authors: Cody Baker and Alessio Buccino.""" import numpy as np from pynwb import NWBFile, TimeSeries from pynwb.epoch import TimeIntervals from hdmf.backends.hdf5.h5_utils import H5DataIO from nwb_conversion_tools.datainterfaces.ecephys.baserecordingextractorinterface import BaseRecordingExtractorInterface from nwb...
carrier = [0.0, 0.963507348203431, 1.68865585100403, 1.99605345685654, 1.80965410493204, 1.17557050458495, 0.250666467128608, -0.736249105369356, -1.54102648555158, -1.96457450145738, -1.90211303259031, -1.36909421185738, -0.497379774329709, 0.497379774329708, 1.36909421185738, 1.90211303259031, 1.96457450145738, 1.541...
''' This script contains general math usefull function ''' import torch def arc_cosh(x): return torch.log(x + torch.sqrt(x**2-1)) def arc_tanh(x): return 0.5 * torch.log((1+x)/(1-x)) def arc_sinh(x): x = torch.clamp(x, -2000, 20000) return torch.log(x +1e-4+ torch.sqrt(x**2 + 1)) torch.arc_cosh =...
import pytest from hat.monitor.server import common infos = [common.ComponentInfo(cid=1, mid=2, name='name', group='group', address='address', rank=3, ...
# -*- coding: utf-8 -*- import html5lib from html5lib import sanitizer DEFAULT_PARSER = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer) def _get_inner_body(doc): # find 'body' def _rec(node): if node.type == 5: # Element Type if node.name == 'body': # the body element ...
import model_data as md import pathway_data as pd from alignment import alignment from bigg_data import bigg_data """ model = md.model_data() #model.load_model_sbml("iCHOv1_final.xml") #model.load_model_cobra_sbml("iCHOv1_final.xml") #model.load_model_mat("gimmeDG44.mat") model.load_model_mat("gimmeS.mat") #model.load...
# Copyright 2015 OpenStack Foundation # # 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 ...
import logging from django.db import connections, transaction, DEFAULT_DB_ALIAS from usaspending_api.awards.models import TransactionNormalized from usaspending_api.etl.award_helpers import update_awards from usaspending_api.broker.helpers.find_related_awards import find_related_awards logger = logging.getLogger("c...
import argparse import datetime import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import register_matplotlib_converters from TimeSeriesCrossValidation import splitTrain from sklearn import linear_model from sklearn import pipeline from sklearn import preprocessing from gamestonk_terminal.helper_...
#escreva um programa que leia um numero n inteiro qualquer e mostre na tela os n primeiros #elementos de uma sequencia de Fibonacci. numero=int(input("Digite quantos termos voce quer: ")) t1=0 t2=1 print("{} -> {} ->".format(t1,t2),end=" ") t3=t1+t2 contador=3 while contador<=numero: t3=t1+t2 print("...
import _thread import os import pycom import GpsSIM28 import strings as s from Configuration import config from loggingpycom import CRITICAL, DEBUG, ERROR, INFO, WARNING from PM_read import pm_thread from RtcDS1307 import clock def initialise_time(rtc, gps_on, logger): """ Acquire UTC timestamp from RTC modu...
from persistencia.ventas_reporsitorio import Vemtas_Repositorio from datetime import datetime, timedelta class Mediciones: def obtener_ventas_dia(self): return Vemtas_Repositorio().obtener_ventas_por_dia() def obtener_total_genero(self): vr = Vemtas_Repositorio().obtener...
# E.g. ApplicationCommunicationMessages -> application-communication-messages def pascal_to_kebab(input): kebab_cased = "" for idx in range(len(input)): letter = input[idx] if idx == 0: kebab_cased += letter.lower() elif letter.isupper(): kebab_cased += "-" + le...
from bs4 import BeautifulSoup from bs4.builder import HTMLTreeBuilder import requests import wikipedia import csv import re wikipedia.set_lang("ru") def get_all_waterfalls_from_csv(): all_waterfalls = [] with open("waterfalls_database.csv","r",encoding="utf-8") as f: fields = ['title', 'summary', 'url'...
#!/usr/bin/python3 import sys import time import os import importlib import requests import logging from prometheus_client import start_http_server from prometheus_client.core import REGISTRY from optparse import OptionParser from tools.helper import yaml_read def default_collectors(): collector_config = yaml_rea...
from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.views.generic import FormView from django.views.generic.base import View from master.forms import ContactQueryForm from .models import ContactQuery def home(request): return render(request, "master/homepage.html...
# Generated by Django 3.0.9 on 2020-08-14 13:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shopping', '0014_auto_20200814_1138'), ] operations = [ migrations.RemoveField( model_name='pri...
import pygame as pg from game import settings from game.map import colorMap from game.resources import resourceManager import time class Menu: """ This class manages the displays inbetween playing the game, like selecting a map, gameover screen and finish screen. """ def __init__(self, dis...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path as osp import argparse from utils import BasicDataset from proposals import generate_basic_proposals, generate_iter_proposals def parse_args(): parser = argparse.ArgumentParser(description='Generate Proposals') parser.add_argument("--name", ...
# -> Assignment - 3.1 # -> myreduce function # -> Input the parameters print("-> Input") number = int(input("-> Enter a Number : ")) # -> function defined def myreduce(number): num_list = list(range(1,number+1)) even_numbers = filter(lambda x:(x%2==0),num_list) return even_numbers # -> F...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 9 19:33:06 2019 This is the Extract Module for my ETL code. It must satisfy the following contract: 1. Accept a query_date, S3 resource instance, a local temp space, and a bucket name as inputs 2. read sample-extract-output.csv from...
# AUTOGENERATED! DO NOT EDIT! File to edit: cycleGAN.ipynb (unless otherwise specified). __all__ = ['AutoTransConv', 'trans_conv_norm_relu', 'pad_conv_norm_relu', 'conv_norm_relu', 'ResBlock', 'generator', 'discriminator', 'cycleGAN', 'DynamicLoss', 'CycleGANLoss', 'cycleGANTrainer'] # Cell from ModernArch...
from matplotlib.ticker import ScalarFormatter class SeqFormatter(ScalarFormatter): def __init__(self, start=0, **kwargs): self.start = start super(SeqFormatter, self).__init__(**kwargs) return def func(self, x, pos=None): x -= self.start if x <= 0: x += 1 ...
# pylint: disable=too-few-public-methods from .CatsParseException import CatsParseException class Scope: """Tuple composed of filename and line number""" def __init__(self, name): self.name = name self.line_number = 0 class ScopeManager: """Manages the current scope composed of filename ...
# run this using # mpiexec [MPI EXEC PARAMETERS] python -m mpi4py.futures wowp_mpi_run_wf.py # running on localhost with 4 processes # mpiexec -n 4 python -m mpi4py.futures wowp_mpi_run_wf.py import json import datetime from wowp.actors import AnnotateInp, FuncActor, LoopWhile, DictionaryMerge from wowp.schedulers im...
#!/usr/local/bin/python # --------------------------------------------------- # Azubu Notification Bot v1 for Reddit by Vangogh500 # --------------------------------------------------- # import all necessary libraries import praw import time from datetime import datetime import urllib2 # the main variables USERNAME...
CENTRALIZED = False EXAMPLE_PAIR = "WETH-DAI" DEFAULT_FEES = [0., 0.] USE_ETHEREUM_WALLET = True FEE_TYPE = "FlatFee" FEE_TOKEN = "ETH" USE_ETH_GAS_LOOKUP = True
import lens, trace New_Lens = lens.Lens(lens_name='doublet',creator='XF') New_Lens.lens_info() New_Lens.add_wavelength(wl = 656.30) New_Lens.add_wavelength(wl = 587.60) New_Lens.add_wavelength(wl = 486.10) New_Lens.list_wavelengths() New_Lens.add_field(angle=0) New_Lens.add_field(angle=5) New_Lens.add_field(angle=...
from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . models import employees from . serializers import employeesSerializer c...
""" Estimates likelihood of generated data using kernel density estimation Author(s): Wei Chen (wchen459@umd.edu) """ import numpy as np from utils import optimize_kde, mean_err def mean_log_likelihood(X_gen, X_test): X_gen = X_gen.reshape((X_gen.shape[0], -1)) X_test = X_test.reshape((X_test.shape[0], -1))...
from pmaf.pipe.factors._metakit import FactorBackboneMetabase class FactorBase(FactorBackboneMetabase): """ """ def __repr__(self): class_name = self.__class__.__name__ repr_str = "<{}:, Factors:[{}], Externals:[{}]>".format(class_name,len(self.factors),len(self.externals)) return repr...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Wed Apr 24 12:13:11 2013 @author: edouard.duchesnay@cea.fr @author: benoit.da_mota@inria.fr @author: jinpeng.li@cea.fr Introduction ------------ The library Epac can create an Epac tree for machine learning algorithms. This example shows how to compute Ep...
#! /usr/bin/env python # -*- coding:UTF-8 -*- import heapq # 大数据序列合并,未排好序,只生成当前最小值 # 单纯合并没什么优势啊? def merge(*subsequences): heap = [] # 临时列表 for seq in subsequences: iterator = iter(seq) for current_value in iterator: heap.append((current_value, iterator)) break hea...
import os from .BaseDataset import BaseDataset from PIL import Image class SRDataset(BaseDataset): def __init__(self, root, cfg, is_train=True): super(SRDataset, self).__init__(cfg, is_train) root = os.path.abspath(root) data_root = os.path.join(root, 'train' if is_train else 'test') ...
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField, BooleanField from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms.validators import ValidationError, DataRequired, Email, EqualTo class LoginForm(FlaskForm): account_id = ...
""" Global tuple to avoid make a new one each time a method is called """ my_tuple = ("London", 123, 18.2) def city_tuple_declaration(): city = ("Rome", "London", "Tokyo") return city def tuple_get_element(index: int): try: element = my_tuple[index] print(element) except IndexError: ...
import asyncio class CoroutineUtil(object): @staticmethod async def run(coroutine): try: return await coroutine except: pass @staticmethod async def run_with_retries(coroutine): curr = 0 max = 3 while curr < max: try: ...
"""Module for SimulatorBase class.""" from __future__ import annotations from ..Configuration import Configuration from ..runner.RunResults import RunResults class SimulatorBase(object): """Generic Simulator interface.""" def __init__(self, name: str) -> None: """ Initialize new SimulatorBas...
# Copyright 2018 IBM Corp. # # 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, s...
import server.app.tictactoeserver as tttServerMod server = tttServerMod.TicTacToeServer("localhost", 7777, identifier="OMEGA-", syncServer=["ALPHA-TicTacToeServer", "EPSILON-TicTacToeServer"]) server.start()
import augeas import os import sys import shutil import re import fnmatch from collections import OrderedDict import express_utils from express_utils import LOGGER from express_utils import APACHE_SERVICES from express_utils import replace_chars class ParserException(Exception): def __init__(self, message, direc...