text stringlengths 1 927k |
|---|
questions = []
Answers = []
ending = "Thank you for taking this quiz!"
def help():
print("SubCommands:")
print("-----------------------------------------")
print("help - shows this help page")
print("addQuestion - adds a question")
print("deleteQuestion - removes a question")
... |
##---------------------- Carga de bibliotecas
from pandas import DataFrame
import streamlit as st
import numpy as np
##---------------------- Base de datos
##---------------------- Funciones
def idea():
'''Genera una frase aleatoria que podrás utilizar como la idea principal del relato.
El programa no utiliza... |
# -*- coding: utf-8 -*-
"""Functions to make simple plots with M/EEG data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Cathy Nangini... |
"""
This file offers the methods to automatically retrieve the graph Alteromonadaceae bacterium Bs31.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein... |
from marshmallow.schema import Schema, SchemaOpts
from . import fields
from marshmallow.decorators import (
pre_dump,
post_dump,
pre_load,
post_load,
validates,
validates_schema,
)
from marshmallow.utils import EXCLUDE, INCLUDE, RAISE, pprint, missing
from marshmallow.exceptions import Validati... |
#!/usr/bin/python
import sys, os
import math, time
import threading
import getopt # comand line argument handling
from low import *
# =============================================================================
def show_help():
""" displays the program parameter list and usage information """
stdout( "usa... |
import math
import torch
from .optimizer import Optimizer
class ASGD(Optimizer):
"""Implements Averaged Stochastic Gradient Descent.
It has been proposed in `Acceleration of stochastic approximation by
averaging`_.
Arguments:
params (iterable): iterable of parameters to optimize or dicts def... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HER... |
from ..util import slice_
def cswap(N, CX, INCX, CY, INCY):
"""Swaps the contents of a vector x with a vector y
Parameters
----------
N : int
Number of elements in input vector
CX : numpy.ndarray
A single precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`))
INCX : in... |
##
# File: WfDataObjectImportTests.py
# Date: 10-Oct-2018 E. Peisach
#
# Updates:
##
"""Test cases for wwpdb.utils.wf - simply import everything to ensure imports work"""
__docformat__ = "restructuredtext en"
__author__ = "Ezra Peisach"
__email__ = "peisach@rcsb.rutgers.edu"
__license__ = "Creative Commons Attributi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import time
import lxml.etree
import randoms
import re
from searchengine import searchengine
class yahoo(searchengine):
"""Search resources from yahoo searchengine, include titles/urls."""
def __init__(self):
super(yahoo, self).__init__()
... |
from allennlp_demo.common.testing import ModelEndpointTestCase
from allennlp_demo.ccg_supertagging.api import CCGSupertaggingModelEndpoint
class TestCCGSupertaggingModelEndpoint(ModelEndpointTestCase):
endpoint = CCGSupertaggingModelEndpoint()
predict_input = {
"sentence": "Did Uriah honestly think he... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Copyright (c) 2017 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import ComparisonTestFrame... |
import pygame, random
def get_new_value(old_gen, old_automata):
# TBC - add code to generate the next row of cells,
# then replace the return statement below to
# return the updated automata
# automata = get_new_value(generations-1, automata)
# If each row = 50 cells (0-49) and generations start a... |
"""
Tests that apply specifically to the Python parser. Unless specifically
stated as a Python-specific issue, the goal is to eventually move as many of
these tests out of this module as soon as the C parser can accept further
arguments when parsing.
"""
from __future__ import annotations
import csv
from io import (
... |
import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def fblogin(bot_handler,message):
if len(message)>=2:
e=message[0]
p=message[1]
driver = webdriver.Chrome('/home/jugtaram/Downloads/chromedriver/chromedriver')
driver.get('http://www.google.com/xhtml')
time.slee... |
class LearningErrorException(Exception):
pass |
#!/usr/bin/env python3
import sys
sys.path.insert(1,'../../python')
import FluidChannel as fc
import numpy as np
aLx_p = 1.0;
aLy_p = 1.0;
aLz_p = 5.0;
aNdivs = 11;
emptyChan = fc.FluidChannel(Lx_p = aLx_p,Ly_p = aLy_p,
Lz_p = aLz_p, N_divs = aNdivs);
emptyChan.write_mat_file('test_geom'... |
"""
Tools for "threading" out specific species from alignments (removing other
species and fixing alignment text).
"""
from copy import deepcopy
def thread(mafs, species):
"""
Restrict an list of alignments to a given list of species by:
1) Removing components for any other species
2) Remove... |
# Generated by Django 2.0.5 on 2018-07-27 11:05
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hospital', '0013_hospital_verified'),
]
operations = [
migrations.AlterField(
model_name='hospital... |
import csv
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--tissue', type=str, default='Brain - Cortex', metavar='tissue',
help='type of tissue filtered for')
parser.add_argument('--save-to', type=str,
default='../../data/gtex_processe... |
import sys
import json
import numpy as np
import os
import pickle as pkl
import time
from pprint import pprint
from stable_baselines3 import PPO, DQN
from stable_baselines3.common.utils import set_random_seed
from pettingzoo.butterfly import cooperative_pong_v3, prospector_v4, knights_archers_zombies_v7
from pettingz... |
# ------------------------------------------------------------------------------
#
# Author:
# Armin Hasitzka (enhancitizer@hasitzka.com)
#
# Licensed under the MIT license.
# See LICENSE in the project root for license information.
#
# ------------------------------------------------------------------------------
... |
# Copyright 2018 The TensorFlow Probability 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 o... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_binayre_ruffian_trandoshan_female_01.iff"
result.attri... |
"""
GroupBunk v.1.2
Leave your Facebook groups quietly
Author: Shine Jayakumar
Github: https://github.com/shine-jayakumar
LICENSE: MIT
"""
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions imp... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.recursive(head)
def recursive(self, head):
... |
from os import linesep
from unittest import TestCase
from unittest.mock import patch
from axelrod import Action, Cooperator, Player
from axelrod.strategies.human import ActionValidator, Human
from prompt_toolkit.validation import ValidationError
from .test_player import TestPlayer
C, D = Action.C, Action.D
class T... |
from time import sleep
import RPi.GPIO as GPIO
########################################################################
#SOURCE - https://www.rototron.info/raspberry-pi-stepper-motor-tutorial/
########################################################################
"""
As always I recommend you start with a freshly w... |
# coding: utf8
from __future__ import unicode_literals
import pytest
NB_TOKEN_EXCEPTION_TESTS = [
(
"Smørsausen brukes bl.a. til fisk",
["Smørsausen", "brukes", "bl.a.", "til", "fisk"],
),
(
"Jeg kommer først kl. 13 pga. diverse forsinkelser",
["Jeg", "kommer", "først", "k... |
__author__ = 'Matthew Witherwax (lemoneer)'
class Constant(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
BAUD_RATE = Constant(BAUD_300=0, BAUD_600=1, BAUD_1200=2, BAUD_2400=3, BAUD_4800=4, BAUD_9600=5, BAUD_14400=6,
BAUD_19200=7, BAUD_28800=8, B... |
#
# A less memory-exploding version of regrtester.py.
# It runs only a fraction of the tests.
#
import sys, re, psyco
assert len(sys.argv) >= 2
match = re.match(r"(\d+)[/](\d+)", sys.argv[1])
assert match, "syntax: regrtester2.py n/m [-nodump] [seed]"
n = int(match.group(1))
m = int(match.group(2))
assert 0 <= n < m... |
WIDTH = 1024
HEIGHT = 768
#colours
WHITE = (255,255,255)
RED = (255,0,0) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created in February 2017 in ComplexCity Lab
@author: github.com/fpfaende
what it does
add metric distance between two nodes of an edge
distance is computed in specified projection system
to maximize precision
parameters
graph
epsg code for targeted projection
how i... |
# -*- coding: utf-8 -*-
"""A supporting module for jplephem to handle data type 21 (Version 0.1.0)
This module computes position and velocity of a celestial small body, from a
NASA SPICE SPK ephemeris kernel file of data type 21 (Extended Modified
Difference Arrays).
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FO... |
# Copyright (c) 2016 IBM 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 req... |
class Source:
"""
Class that generates new instances of news api source results
"""
def __init__(self,id,name,category):
'''
define properties for our objects
'''
self.id = id
self.name = name
self.category = category |
# Exercício Python 12:
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
print('----------------------------')
print(' LEITOR DE PREÇO ')
print('----------------------------')
print()
vl = float(input('Digite o valor do produto? R$'))
d = (vl * 5) /100
print('Pr... |
# -*- coding: utf-8 -*-
import scrapy
import os
from ..items import SinaSpiderItem
from ..settings import COOKIES
import re
class SinaspiderSpider(scrapy.Spider):
name = 'SinaSpider'
allowed_domains = ["sina.com",'sina.com.cn']
start_urls = ['http://www.sina.com.cn/']
def parse(self, response):
... |
"""Class to handle chapter processing for books."""
from __future__ import print_function
import os
import logging
import hashlib
import subprocess
import inspect
import copy
import lxml
from lxml import etree
try:
from termcolor import colored
except ImportError:
logging.error("Please install termcolor:\n s... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import requests
import logging
import time
logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s', level=logging.INFO)
def stream():
"""
Send stream instructions to streamer servers in the form of HTTP POST requests.
The streamer_0 is dedicated to the Twitter sample API, so we don't send ... |
# generated by datamodel-codegen:
# filename: storage.json
from __future__ import annotations
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra
class ResourceMap(BaseModel):
class Config:
extra = Extra.forbid
id: str
rate: str
class ResourceCollectorStorage(Bas... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Pocketcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool re-org scenarios.
Test re-org scenarios with a mempool that contains transactions
that... |
import os
from fractions import Fraction
from PIL import Image
from PIL.ExifTags import TAGS
def get_exif(fn):
ret = {}
i = Image.open(fn)
info = i._getexif()
decoded_dict = {}
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
decoded_dict[decoded] = value
ret['ISO'... |
from dnnv.properties import *
import numpy as np
N1 = Network("N1")
N2 = Network("N2")
class_1 = 8
class_2 = 1
Forall(
x,
Implies(
(0 <= x <= 1),
(np.argmax(N1(x)) != class_1) | (np.argmax(N2(x)) != class_2),
),
) |
# Map Approach [O(n)] :
# Idea is to create a hashmap to store freq of the elements, and lookup those elements while traversing the array to check if their sum is equal to the given sum or not
# GeeksforGeeks Explanation: https://youtu.be/bvKMZXc0jQU
def getPairsCount(arr, n, sum):
m = [0] * 1000
# Store count... |
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
from flask_migrate import Migrate
from os import environ
from sys import exit
from decouple import config
from config import config_dict
from app import create_app, db
# WARNING: Don't run with debug turned on in production!
DEBUG = config('DE... |
import re
import _ctypes
import inspect
import numpy.ctypeslib as npct
from time import time as ostime
from os import path
from os import remove
from sys import platform
from sys import version_info
from ast import FunctionDef
from hashlib import md5
from parcels.tools.loggers import logger
import numpy as np
from nump... |
import random
from ..CardEnum import *
from copy import deepcopy
class GameResult:
def __init__(self,winner,turns):
self.winner = winner
self.turns = turns
class Game:
def __init__(self, players, engine, deck, logger):
random.seed()
self.winner = None
self.total_turns... |
from pydantic import validator, Field
from typing import Dict, List, Any, Literal, Tuple, Union, Optional
from .typings import McdpBaseModel
from .config import check_mc_version, MinecraftVersionError
class MCStringObj(McdpBaseModel):
def json(self, **kw) -> str:
data = self.dict(**kw)
return se... |
"""lower activites
Revision ID: bcb4dc0e73e2
Revises: 25116bbd585c
Create Date: 2020-10-06 11:34:47.860748
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
# revision identifiers, used by Alembic.
revision = 'bcb4dc0e73e2'
down_revision = '25116bbd585c'
branch_labels = None
depends... |
#!/usr/bin/python3
# **************************************************************************** #
# #
# :::::::: #
# Artsy.py :+... |
import numpy as np
from tensorflow import keras
from tensorflow.keras import backend as K
def cosine_decay_with_warmup(global_step,
learning_rate_base,
total_steps,
warmup_learning_rate=0.0,
warmup_steps... |
#!/usr/bin/env python
"""A generic serializer for python dictionaries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import collections
from future.builtins import str
from future.utils import iteritems
from future.utils import itervalues
from futur... |
from keep_alive import keep_alive
import discord
from discord.ext import commands,tasks
from itertools import cycle
import random
intents = discord.Intents(messages = True , guilds = True , reactions = True , members = True , presences = True)
client = commands.Bot(command_prefix = '.', intents = intents)
@client... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import unittest
import numpy as np
from extensions.front.div import Div
from mo.utils.ir_engine.compare_graphs import compare_graphs
from unit_tests.utils.graph import build_graph, result, regular_op_with_shaped_data, valued_const_with... |
#!/usr/bin/env python
import oss2
class PUTCONFIGTOOSS(object):
def __init__(self,DEST,STORESIZE):
self.AK = ''
self.SK = ''
self.ENDPOINT = 'http://oss-cn-hangzhou.aliyuncs.com'
self.BUCKET = 'ali-hangzhou'
self.DEST = DEST
self.STORESIZE = STORESIZE
def INITIAL(self):
try:
A... |
import codecs
import yaml
from .filebased import FileBasedSource
__all__ = (
'YamlFileSource',
)
class YamlFileSource(FileBasedSource):
def __init__(self, *args, **kwargs):
self.encoding = kwargs.pop('encoding', 'utf-8')
super(YamlFileSource, self).__init__(*args, **kwargs)
def get_se... |
from flask import request
from flask_restx import Resource, reqparse
from flask_restx._http import HTTPStatus
from werkzeug.datastructures import FileStorage
from ..service import funding_detail_service as fd_service
from ..service import funding_project_service as fp_service
from .dto import FundingDetailDTO, Funding... |
# Copyright (c) 2018 European Organization for Nuclear Research.
# 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/LIC... |
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print(' A soma é {},\n o produto é {},\n a divisão é {:.3f}'.format(s, m, d))
print(' A divisão inteira é {}\n a potencia é {}'.format(di, e)) |
#!/usr/bin/env python
# mixnmatch.py - find combination of files/dirs that sum below a given threshold
# -- Jose Fonseca
import os
import os.path
import optparse
import sys
from sets import ImmutableSet as set
def get_size(path, block_size):
if os.path.isdir(path):
result = 0
for name in os.list... |
"""
Created by Epic at 9/1/20
"""
class HTTPException(Exception):
def __init__(self, request, data):
self.request = request
self.data = data
super().__init__(data)
class Forbidden(HTTPException):
pass
class NotFound(HTTPException):
def __init__(self, request):
self.requ... |
import os
import time
from dask import dataframe as dd
import jellyfish
from TextExtraction.APIs.TextAPI import getListOfSentences
csv_path = os.path.join(os.path.dirname(__file__), "india-news-headlines.csv")
headlines = dd.read_csv(csv_path).headline_text
def get_mean(sentances_scores):
return sum(sentances_sc... |
#!/usr/bin/python
"""
CSC 315
Spring 2020
John DeGood
This code is from:
https://www.postgresqltutorial.com/postgresql-python/
"""
from ConfigParser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.r... |
from .azure_blob_storage import BlobFromCSV
from .azure_data_lake import (
AzureDataLakeCopy,
AzureDataLakeDownload,
AzureDataLakeList,
AzureDataLakeToDF,
AzureDataLakeUpload,
)
from .azure_key_vault import (
AzureKeyVaultSecret,
CreateAzureKeyVaultSecret,
DeleteAzureKeyVaultSecret,
)
fr... |
# MIT License
#
# Copyright (c) 2020 Genesis Cloud Ltd. <opensource@genesiscloud.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... |
# Copyright (c) 2015-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# coding=utf-8
#
import copy
import pecan
from pecan import rest
import six
import wsme
from wsme import types as wtypes
import wsmeext.pecan as wsme_pecan
from fm_api import const... |
#!/usr/bin/env python2.7
#
# Copyright (C) 2014 Microsoft Research
"""
Created on 2014-04-02
@summary: Helper Module for precomputing principal components for Leave one Chromosme out GWAS
"""
import logging
import numpy as np
import scipy as sp
import pandas as pd
from scipy import stats
import pylab
import fastlmm.p... |
import numpy as np
class Prior(object):
def __init__(self,imageSize, sWindowSize=3, imageCropFactor=[0]):
self.imageSize = imageSize if len(imageSize)==3 else imageSize.append(1)
self.imageCropFactor = imageCropFactor
if np.mod(sWindowSize,2):
self.sWindowSize... |
"""A package for http server"""
# pylint: skip-file
__all__ = [
'demo_server',
'http_server',
] |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Glproto(AutotoolsPackage, XorgPackage):
"""OpenGL Extension to the X Window System.
T... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class BestNet(torch.nn.Module):
def __init__(self, embedding_dim):
super(BestNet, self).__init__()
self.embedding_dim = embedding_dim
self.hidden_dim = 256
self.embedding_dropout=... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.modules.events.papers.models.competences import Paper... |
# Copyright 2021 The Flax 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 wri... |
# output_literals.py
# William Ponton
# 2.10.19
# Import modules
import slot_machine.data_structures
# Constants
WELCOME = "\tWelcome to the Slot Machine!"
RULES = "\tMatch 2 of any kind to win $5\n\tMatch 3 of any fruit to win $10\n\tMatch 3 BELLS to win $50!\n"
ENGAGE = "Do you want to play? (y or n): "
LEVER = "\t... |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
file1=open(path,"r")
sentence=file1.readline()
return sentence
sample_message=read_file(file_path)
# --------------
#Code starts here
def read_file(path):
fp=open(path,"r")
return fp.readline()
def fuse... |
import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="visible", parent_name="table", **kwargs):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import os
import numpy as np
import fitsio
from astrometry.util.fits import fits_table
from astrometry.util.ttime import Time
from wise.unwise import get_unwise_tractor_image
import logging
logger = logging.getLogger('legacypipe.unwise')
def info(*args):
from legacypipe.utils import log_info
log_info(logger, ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 by
# Sergio Nery Simoes <sergionery@gmail.com>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = """\n""".join(['Sérgio Nery Simões <sergionery@gmail.com>',
'Aric Hagberg <aric.hagberg@gmail.com>'])
__all__ = ['a... |
"""
This module implements a multi-layer perceptron (MLP) in NumPy.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from modules import *
class MLP(object):
"""
This class implements a Multi-laye... |
"""
This file handles the details of the loss function during training.
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
from itertools import count
import torch
import torch.nn as nn
import random as rnd
import table
d... |
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from apps.reader.models import UserSubscription
import datetime
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("-d", "--days", dest="days", nargs=1, default=1, help="Days of un... |
import pnlp
DIRECTS = ["E", "S", "W", "N"]
SIGNS = ["++", "+-", "--", "-+"]
def get_direct(directs: list, direct: str, num: int, rotate: str):
count = num // 90
idx = directs.index(direct)
if rotate == "R":
new_idx = idx + count
return directs[new_idx % 4]
else:
new_idx = idx ... |
from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
from openmdao.api import Group
class PowerSplit(ExplicitComponent):
"""
A power split mechanism for mechanical or electrical power.
Inputs
------
power_in : float
Power fed to the splitter. (vect... |
import cv2
import numpy as np
from copy import deepcopy as dp
aqua=(255,255,0)
marine=(116,139,69)
banana=(87,207,277)
blue=(255,0,0)
almond=(205,235,255)
brown=(64,64,255)
blue1=(255,245,152)
green=(0,100,0)
orange=(0,140,255)
orchid=(139,34,104)
pink=(147,20,255)
gold=(0,215,255)
gray=(127,127,127)
indigo=(130,0,75)... |
"""Example of running a policy server. Copy this file for your use case.
To try this out, in two separate shells run:
$ python cartpole_server.py
$ python cartpole_client.py
"""
import os
from gym import spaces
import numpy as np
import ray
from ray.rllib.agents.dqn import DQNTrainer
from ray.rllib.env.exter... |
# Copyright 2020 ByteDance 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 writin... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
from __future__ import absolute_import
import sys
from builtins import range
from .Mixins import _ConfigureComponent, PrintOptions
from .Mixins import _Labelable, _Unlabelable
from .Mixins import _ValidatingParameterListBase
from .ExceptionHandling import *
from .OrderedSet import OrderedSet
class _HardDependency(obj... |
n=int(input("enter the size"))
a=[]
for i in range(n):
b=input("enter")
a.append(b)
for i in range(n):
count=a.count(i)
if(count==1):
print(i) |
#!/usr/bin/python
# -*- encoding=utf-8 -*-
# author: Ian
# e-mail: stmayue@gmail.com
# description:
def list_to_dict(in_list):
return dict((i, in_list[i]) for i in range(0, len(in_list)))
def exchange_key_value(in_dict):
return dict((in_dict[i], i) for i in in_dict)
def main():
pass
if __name__ == ... |
# -*- coding: utf-8 -*-
"""datapackage model"""
import os.path as osp
from typing import List, Tuple, Dict, Union, Callable
import attr
import json
from itertools import product
from collections import OrderedDict
from tqdm import tqdm
import pandas as pd
from .ddf import DDF, Concept, EntityDomain, Entity, DaskDat... |
#!/usr/bin/python
import noise
import numpy as np
from PIL import Image
size = (2000, 2000)
ratio = 16
bb_col = Image.open("../resources/bb-scale.jpg", 'r')
out_img = Image.new('RGBA', size, (0, 0, 0, 0))
for y in range(0, size[1]):
if y % 100 == 0:
print y
for x in range(0, size[0]):
val = noise.snoise2(flo... |
# -*- coding:utf-8 -*-
#@Time : 2020/9/20 14:48
#@Author: 赵雯
#@File : main.py
from flask import Blueprint
from flask import render_template
from app.models import Tbl_Video_Game_Sales
from app import create_app
from app.extensions import db
# 创建蓝图
main_print = Blueprint('main_print',__name__)
# 图像切换
@main_print.rout... |
# Generated by Django 3.1 on 2020-09-25 16:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0010_auto_20200923_0246'),
]
operations = [
migrations.AddField(
model_name='signature',
name='status',
... |
#!/usr/bin/python
"""
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.