text
stringlengths
1
927k
import torch.nn as nn import torch.nn.functional as F from torch.nn import init class ConditionalBatchNorm2d(nn.BatchNorm2d): """Conditional Batch Normalization""" def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=True): super(ConditionalBat...
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
from typing import Any, Dict, Hashable, List, Optional import numpy as np import xarray as xr from .typing import ArrayLike from .utils import create_dataset DIM_VARIANT = "variants" DIM_SAMPLE = "samples" DIM_PLOIDY = "ploidy" DIM_ALLELE = "alleles" DIM_GENOTYPE = "genotypes" def create_genotype_call_dataset( ...
from random import shuffle n0 = input('1ª Aluna: ') n1 = input('2ª Aluna: ') n2 = input('3ª Aluna: ') n3 = input('4ª Aluna: ') l = [n0, n1, n2, n3] shuffle(l) print('A ordem dos alunos é {}'.format(l))
#!/usr/bin/env python from sys import stdout from iterators import Example e = Example() e.add("a") e.add("b") e.add("c") print [ s for s in e.strings() ]
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.18.0'...
from argparse import ArgumentParser from configs.paths_config import model_paths from dataclasses import dataclass @dataclass class TrainOptionsDataClass: exp_dir: str dataset_type: str = "ffhq_encode" encoder_type: str = "GradualStyleEncoder" input_nc: int = 3 label_nc: int = 0 batch_size: ...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Pelix Remote Services: Java-compatible RPC, based on the Jabsorb library :author: Thomas Calmant :copyright: Copyright 2020, Thomas Calmant :license: Apache License 2.0 :version: 1.0.1 .. Copyright 2020 Thomas Calmant Licensed under the Apache Licens...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os from tempfile import mkstemp import numpy as np from nipy.testing import assert_true, assert_false, assert_equal, \ assert_array_almost_equal, funcfile from nipy.io.api import load_image, s...
""" Django settings for makewiki project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os ...
#!/usr/bin/env python # Copyright (c) 2013 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from utils import convert_timestamp from rasa_sdk.events import AllSlotsReset import datetime from datetime import timedelta, date import dateutil.parser import boto3 from boto3.dynamodb.cond...
#__all__ = ['dlmPlot'] #import pydlm.plot.dlmPlot as dlmPlot
# Armin Pourshafeie #TODO write a generator that takes the chromosome and spits out data. do the regression in parallel #TODO documentation # Running the gwas import logging import numpy as np import gzip, h5py, os, re, gc, tqdm from sklearn.linear_model import LogisticRegression import statsmodels.formula.api as smf...
"""SentimentInvestor View""" __docformat__ = "numpy" import os import logging from typing import Optional, List from matplotlib import pyplot as plt from openbb_terminal.decorators import check_api_key from openbb_terminal.cryptocurrency.defi import smartstake_model from openbb_terminal.helper_funcs import ( exp...
from .bme280_handler import BME280, BME280Exception
from krwordrank.word import KRWordRank import krwordrank def wordrank(textdir: str): def get_texts_scores(fname: str): with open(fname, encoding='utf-8') as f: docs = [doc.lower().replace('\n', '').split('\t') for doc in f] docs = [doc for doc in docs if len(doc) == 2] ...
import numpy as np from copy import deepcopy from numpy.random import randint def TournamentSelect( population, how_many_to_select, tournament_size=4 ): pop_size = len(population) selection = [] while len(selection) < how_many_to_select: best = population[randint(pop_size)] for i in range(tournament_size - 1)...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import ros_numpy import cv2 class image_listenner: def __init__(self): self.bridge = CvBridge() self.image_sub = ros...
# -*- coding: utf-8 -*- """FreshPRINCE test code.""" import numpy as np from numpy import testing from sklearn.metrics import accuracy_score from sktime.classification.feature_based import FreshPRINCE from sktime.datasets import load_unit_test def test_fresh_prince_on_unit_test_data(): """Test of FreshPRINCE on ...
# -*- coding: utf-8 -*- ############################################################################# # # # EIDEChannesManager # # ...
# # PySNMP MIB module CISCO-ENTITY-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-EXT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:39:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# coding: utf-8 from django.contrib import admin from .models import Hive, Captor, Data # Possibilité ajout capteur : # ajoute dans la bdd une table pour le nouveau capteur, ainsi que l'identifiant qui devra être utilisé pour parser le flux de la ruche # admin.site.register(Hive) admin.site.register(Captor) admin.si...
import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET url = input('Enter XML URL: ') data = urllib.request.urlopen(url).read() tree = ET.fromstring(data) counts = tree.findall('.//count') total = 0 for count in counts: total += int(count.text) print(total)
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt import collections from functools import lru_cache from astroid.context import _invalidate...
# Copyright The IETF Trust 2012-2020, All Rights Reserved # -*- coding: utf-8 -*- from django.contrib import admin from ietf.meeting.models import (Meeting, Room, Session, TimeSlot, Constraint, Schedule, SchedTimeSessAssignment, ResourceAssociation, FloorPlan, UrlResource, SessionPresentation, ImportantDate,...
# testing/exclusions.py # Copyright (C) 2005-2019 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import contextlib import operator import re from . import config from .. imp...
# coding=utf-8 # Copyright 2021 The Uncertainty Baselines 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 ap...
############################################################################# ## ## Copyright (c) 2013 Riverbank Computing Limited <info@riverbankcomputing.com> ## ## This file is part of PyQt5. ## ## This file may be used under the terms of the GNU General Public License ## version 3.0 as published by the Free Softw...
''' Blockchain base prepared by Ren Jun in April 2019 with reference from ??. Run blockchain base before running any of the simulation. This code is to prepare one starting block of the blockchain, which is a passive block without any data, and also, the function to add subsequent blocks to the blockchain by getting d...
from subprocess import Popen, STDOUT import os def clone_hy(dest): owd = os.getcwd() os.chdir(dest) cmd = "git clone https://github.com/hylang/hy.git" proc = Popen(cmd, stdout=STDOUT, stderr=STDOUT) outp, _ = proc.communicate() print outp if proc.returncode != 0: raise Exception("U...
import sys import pandas as pd import geopandas as gpd def main(csv, gpkg, out): df = pd.read_csv(csv).assign( Income=lambda x: pd.to_numeric(x.Income.str.replace(",", "")) ) gpd.read_file(gpkg).get(["MSOA01CD", "geometry"]).merge( df, how="inner", left_on="MSOA01CD", right_on="MSOA" ...
import os import tensorflow as tf from keras.layers import LSTM, Dense, Dropout from keras.models import Sequential from Source.config import Model from Source.driver import Driver tf.logging.set_verbosity(tf.logging.ERROR) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def run(): dataset = Driver() n_time_step...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from os import getenv SQLALCHEMY_DATABASE_URL = getenv("DATABASE_URL") engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bin...
class Worker(): def __init__(self): """ initialize Worker class """ self.cloudlets = [] self.bandwidth = {} self.mips = int self.position = int self.timer = 0 def attachCloudlet(self, cloudlet): """ attach cloudlet to worker Args: ...
# Copyright 2013-2021 Aerospike, 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 agreed to in writ...
import re from hearthstone import cardxml from hearthstone.cardxml import CardXML from hearthstone.enums import CardType, GameTag, Race, Rarity ERR_LANG_NOT_FOUND = "Language not found. Supported language keys are e.g. `enUS` or `deDE`" db, _ = cardxml.load() def loc_name(self, locale): return self.strings[Game...
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from django.test import Client from organization.models import Organization class AdminSiteTests(TestCase): def setUp(self): admin_email = 'admin@pnsn.org' admin_pass = 'password123' ...
from course_lib.Base.Recommender_utils import check_matrix from course_lib.Base.BaseSimilarityMatrixRecommender import BaseItemSimilarityMatrixRecommender from course_lib.Base.Recommender_utils import similarityMatrixTopK from course_lib.Base.Incremental_Training_Early_Stopping import Incremental_Training_Early_Stoppin...
"""Tests for the Neg Strategy""" import axelrod as axl from .test_player import TestPlayer C, D = axl.Action.C, axl.Action.D class TestNegation(TestPlayer): name = "Negation" player = axl.Negation expected_classifier = { "memory_depth": 1, "stochastic": True, "makes_use_of": se...
""" This is a sample program to show how to draw using the Python programming language and the Arcade library. """ # Import the "arcade" library import arcade # Open up a window. # From the "arcade" library, use a function called "open_window" # Set the window title to "Drawing Example" # Set the dimensions (width an...
""" WSGI config for OBB_Train_Station project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJ...
from logging import log import dash import dash_leaflet as dl import dash_leaflet.express as dlx from dash.dependencies import Input, Output from dash_extensions.javascript import assign, arrow_function import pandas as pd import dash_html_components as html external_stylesheets = ['https://codepen.io/chriddyp/pen/bWL...
# Copyright 2020 Open Source Robotics Foundation, 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...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################# ## # This file is part of Taurus ## # http://taurus-scada.org ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Taurus is free software: you can redistribute it and/or modify #...
import numpy as np from matplotlib import pyplot as plt import seaborn as sns import pandas as pd from sklearn.model_selection import train_test_split from sklearn import linear_model from sklearn import neighbors from sklearn import svm from sklearn.model_selection import GridSearchCV from sundial.price_model.utils.fi...
#!/usr/bin/env python3 import sys plotterdir = '..' sys.path.insert(0, plotterdir) from plotter import calpost_reader import plotter.plotter_multi as plotter_multi from plotter.plotter_util import LambertConformalTCEQ from plotter.plotter_background import BackgroundManager import cartopy.crs as ccrs import geopanda...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from photoCoordinates import photoCoordinates from PIL import Image, ImageFont, ImageDraw class photoImposer: pc = photoCoordinates() allCoordinates = pc.allCoordinates all_images = {} def __init__(self): self.all_images['KICKOFF'] = "formation...
import torch as th from torch.utils.data import BatchSampler, RandomSampler, SequentialSampler from syft.generic import ObjectStorage from syft.federated.train_config import TrainConfig class FederatedClient(ObjectStorage): """A Client able to execute federated learning in local datasets.""" def __init__(se...
#!/usr/bin/python2 # # ditrit.py # Copyright 2006 Ryan Barrett <ditrit@ryanb.org> # http://snarfed.org/ditrit # # See docstring for usage details. # # Ideas: # url open in browser, whois, alexa/netcraft # email address compose in mail client, add to address book # email mai...
import numpy as np from pyrieef.geometry.differentiable_geometry import DifferentiableMap class LinearTranslation(DifferentiableMap): """ Simple linear translation """ def __init__(self, p0=np.zeros(2)): assert isinstance(p0, np.ndarray) self._p = p0 def forward(self, q): ...
# -*- coding: utf-8 -*- from flask import request, current_app from domain.models import Image, Document from validation.base_validators import ParameterizedValidator import repo class CanCreateFacilityValidator(ParameterizedValidator): def validate(self, f, *args, **kwargs): user_id = repo.get_user_id_f...
""" Functions to compute various statistics of the data and their associated errors. """ #Compute statistics about the variance of an estimator: import numpy as np from scipy import stats import math #The following functions as involved in estimating the standard def Moment(Sample,k) : """ This function com...
import json from typing import Any, Dict, Iterable, List, Tuple, Union import graphene from django.db.models import Model as DjangoModel, Q, QuerySet from graphene.relay.connection import Connection from graphene_django.types import DjangoObjectType from graphql.error import GraphQLError from graphql_relay.connection....
from unittest import TestCase from tests import get_data from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson class StorageTestKT1HYegMXP5pqPe83SbeYdHuJZub4tuG2ZvN(TestCase): @classmethod def setUpClass(cls): cls.maxDiff = None cls....
from scripts.downloader import * import fiona from shapely.geometry import shape import geopandas as gpd import matplotlib.pyplot as plt from pprint import pprint import requests import json import time import os # Constant variables input_min_lat = 50.751797561 input_min_lon = 5.726110232 input_max_lat = 50.938216069...
# # Copyright 2018-2021 Elyra Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
import numpy as np # import open3d as o3d import face_recognition # import cv2 from skimage import draw #,morphology # from .depth import depthPreprocess from .image import getConvexHullMask,getMaskedImg2, maskClosing,maskDilation,maskErosion def faceLandmarks(image): ''' 人脸边框+特征点 ''' image=np.as...
import math import sys import pandas as pd from decison_tree import decision_btree from file_healper import file_operation def classify_validation_data(cls_validation_data): classification_result = list() for idx in cls_validation_data.index: if cls_validation_data["TailLn"][idx]<=9.0: if cls_validation_data["Ha...
import numpy as np import scipy.sparse as sp import torch import json as js import pandas as pd def encode_onehot(labels): # The classes must be sorted before encoding to enable static class encoding. # In other words, make sure the first class always maps to index 0. classes = sorted(list(set(labels))) ...
import os import logging import newrelic.agent as agent from sgmon.log import get_logger logger = get_logger(__name__) def init_newrelic_agent(): try: _ = os.environ["NEW_RELIC_LICENSE_KEY"] except KeyError: logger.info("Agent will not report data to New Relic APM") else: config_...
def pth(N,K,P): # too slow for the huge inputs A=set(map(int,raw_input().split())) try: return [x for x in range(1,N+1) if x not in A][P-1] except IndexError: return -1 def ppth(N,K,P): x=P e = map(int,raw_input().split()) for i in xrange(K): if(e[i]<=x): x+=...
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test multiple RPC users.""" from test_framework.test_framework import BitcoinTestFramework from test_f...
#!/usr/bin/env python from extensions import * from config import * from sets import Set from re import match def get_wordnik_json(route, extra_params): params = { "limit": 1, "api_key": wordnik_key } params.update(extra_params) request_json = [] while not request_json: request_json = get_request_json("htt...
# -*- coding: utf-8 -*- """ idfy_rest_client.models.packaging This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ import idfy_rest_client.models.pades_settings class Packaging(object): """Implementation of the 'Packaging' model. TODO: type model description h...
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
""" .. module sgsclient This module contains the client library code. In general, a client should subclass ``StratumGSClientInstance`` and call the ``main`` function. """ import json import socket import sys version = "0.1.0" class StratumGSClient(object): def __init__(self, settings, client_instance_constru...
#!/usr/bin/python import sys import macro_compiler as mc import os import app_ui as ui import terminal_colors as tc import argparse import led_command as lc import math import utils as u import datetime global app_description, verbose_mode, random_seed app_description = None verbose_mode = None random_seed = 1 glob...
# Copyright (C) 2019-2021 Intel Corporation # # SPDX-License-Identifier: MIT from collections import OrderedDict from enum import Enum from django.conf import settings from django.db import transaction from django.utils import timezone from cvat.apps.engine import models, serializers from cvat.apps.engine.plugins im...
#!/bin/env python # Automatically translated python version of # OpenSceneGraph example program "osganimationhardware" # !!! This program will need manual tuning before it will work. !!! import sys from osgpypp import osg from osgpypp import osgAnimation from osgpypp import osgDB from osgpypp import osgGA from osgp...
from abc import ABC, abstractmethod from django import forms from django.core.management import BaseCommand class AdminCommand(BaseCommand, ABC): name = None template = "admintool_command/command.html" class Form(forms.Form): pass def init_context(self, request=None, **kwargs): retu...
import colorsys import os import numpy as np from keras import backend as K from keras.layers import Input from keras.models import load_model from PIL import Image, ImageDraw, ImageFont from nets.yolo3 import yolo_body, yolo_eval from utils.utils import letterbox_image class YOLO(object): _defaults = { ...
"""OAuth 2.0 WSGI server middleware implements support for basic bearer tokens and also X.509 certificates as access tokens OAuth 2.0 Authorisation Server """ __author__ = "R B Wilkinson" __date__ = "12/12/11" __copyright__ = "(C) 2011 Science and Technology Facilities Council" __license__ = "BSD - see LICENSE file i...
# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate import torch from PIL import Image import numpy as np import torchvision.transforms as transforms import additional_transforms as add_transforms from abc import abstractmethod from torchvision.datasets import CIFAR100, CIFAR10...
from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import MobileNetV2 from tensorflow.keras.layers import AveragePooling2D from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow...
CSP_AUTHORIZATION_URL = "csp/gateway/am/api/auth/api-tokens/authorize" HTTPS_URL_PREFIX = "https://" URL_SUFFIX = "/" REFRESH_TOKEN = "refresh_token" CONTENT_TYPE = "Content-Type" ACCESS_TOKEN = "access_token" APPLICATION_JSON = "application/json" CSP_AUTH_TOKEN = "csp-auth-token" ERROR = "error" ERROR_MSG = "error_mes...
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
import logging import mimetypes import os import shutil import tempfile import zipfile from cgi import escape from inspect import isclass import metadata from galaxy import util from galaxy.datatypes.metadata import MetadataElement # import directly to maintain ease of use in Datatype class definitions from galaxy.ut...
# -*- coding: utf-8 -*- # Copyright 2020 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...
""" Character database schema """ from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine base = declarative_base() class Character(base): """ Character database schema """ __tablename__ = 'character' id = Column(Integ...
from jnius import autoclass, JavaException def _class_call(cls, args: tuple, instantiate: bool): if not args: return cls() if instantiate else cls else: return cls(*args) def _browserx_except_cls_call(namespace: str, args: tuple, instantiate: bool): try: return _class_call(autocl...
from matplotlib import pyplot as plt from shapely.geometry import Point from shapely.geometry.polygon import Polygon #from lineSegmentAoE import * import numpy as np import sys class dubinsUAV(): def __init__(self, position, velocity, heading, dt=0.1): self.velocity = velocity self.turnRateLimite...
# Generated by Django 3.0.4 on 2020-04-13 09:05 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0005_trip'), ] operations = [ migrations.AlterField( m...
class DimError(Exception): code = 1 error_types = dict( InvalidPoolError=2, InvalidIPError=3, InvalidVLANError=4, InvalidStatusError=5, InvalidPriorityError=6, InvalidGroupError=7, InvalidUserError=8, InvalidAccessRightError=9, InvalidZoneError=10, InvalidViewError=11, ...
import os import argparse from model import Face def find_module(filename): ext = os.path.splitext(filename)[1].lower() if ext == '.vrsketch': from _vrconv import vrsketch as result_module elif ext == '.skp': from _vrconv import sketchup as result_module else: raise ValueError(...
# Web PDF Saver (Standard GUI-Windows). Liscensed under Apache License 2.0. # Release v1.0 # Not in standard library- img2pdf, pyautogui, PIL import img2pdf import time import tkinter as tk from PIL import ImageGrab import pyautogui import os #Main window creation # Top level window frame = tk.Tk() frame.title("S...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from django.apps import AppConfig class StackoverflowrecommenderConfig(AppConfig): name = 'stackoverflowRecommender' def __init__(self, app_name, app_module): super(StackoverflowrecommenderConfig, self).__init__(app_name, app_mo...
from datetime import datetime from html import unescape import logging from dateutil.parser import parse as parse_date import htmlmin from scrapy import Request from scrapy.spiders import Spider, CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.loader.processors import TakeFirst, MapCompos...
import time import json import logging import tempfile import random from datetime import datetime import pytest import requests from tests.common.fixtures.ptfhost_utils import run_icmp_responder # lgtm[py/unused-import] from tests.common.fixtures.ptfhost_utils import copy_ptftests_directory # lgtm[py/u...
"""Thread module emulating a subset of Java's threading model.""" import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice try: from _collections import deque as _deque except Impor...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Acervo(models.Model): tipoObra = models.CharField(max_length=11) tituloObra = models.CharField(max_length=20) description = models.TextField() begin_date = models.DateField(auto_now_add=True) a...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Basic acceptance test harness for the Multicast_sender and receiver # components. # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - ple...
import os import numpy as np import torch from torch.optim import Adam from .base import BaseAgent from sacd.model import TwinnedQNetwork, CategoricalPolicy from sacd.utils import disable_gradients # If you want to use Prioritized Experience Replay(PER), N-step return # or Dueling Networks, change use_per, multi_ste...
from vocoder.models.fatchord_version import WaveRNN from vocoder import hparams as hp import torch _model = None # type: WaveRNN def load_model(weights_fpath, verbose=True): global _model if verbose: print("Building Wave-RNN") _model = WaveRNN( rnn_dims=hp.voc_rnn_dims, fc_...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import Joy from sensor_msgs.msg import LaserScan from math import radians import numpy as np class BehaviorSwitch(object): def __init__(self): self.running = False def callback(self, joy_msg): if joy_m...
import pandas as pd import math as m import numpy as np """ algorithm that calculate the best alternative from supplier order bracket based on data provided. """ #input data here! # demand_in_cases = # order_cost = # cost_per_case = # bracket_cost = [] # bracket_minimum = [] # holding_rate = EOQ0 = np.sqrt((2*deman...
import json import numpy as np from typing import Optional, List from pathlib import Path from dataclasses import dataclass # pip install dataclasses from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.preprocessing.text import tokeniz...
# -*- coding: utf-8 -*- # # Copyright (C) 2018 CERN. # # Asclepias Broker is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Metadata functions.""" from datetime import datetime from typing import List import idutils from flask impor...
import zipfile, os, sys, aiohttp, json, requests from modules.manifest_reader import ManifestReader class Manifest: def __init__(self, directory, headers=None): self.headers = headers self.directory = directory self.manifests = { 'en': '', 'fr': '', 'es': '', 'de': '', 'it': '', 'ja': '', ...
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...