text
stringlengths
3.07k
12.6k
import torch import numpy as np from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, TrainingArguments, Trainer, AutoConfig, set_seed, ) from datasets import load_dataset set_seed(42) MODEL = "distilgpt2_for_generation" #load tokenizer tokenizer = AutoTokenizer.from_p...
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal from math import floor # Calculations are based off of https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d # under the Shape section def calc_convout_shape(image_size, kernel_size, stri...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import streamlit as st import plotly.express as px import plotly.figure_factory as ff @st.cache def read_data(): data = pd.read_csv('meat_consumption_2.csv') return data data = read_data() def main(): st.title('Meat Con...
#!/usr/bin/env python3 import sys import os import logging from collections import defaultdict from string import punctuation from argparse import ArgumentParser from common import longest_increasing_subsequence from loadfreki import load_freki_document logging.basicConfig() logger = logging.getLogger(os.path.base...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Revisions import requests import hashlib import pymongo import pickle import bson.binary from functools import wraps from datetime import timedelta, datetime try: from unittest import mock except ImportError: import mock class RevisionCollection(object): '''Dict...
""" lotsizing_lazy.py: solve the single-item lot-sizing problem. Approaches: - sils: solve the problem using the standard formulation - sils_cut: solve the problem using cutting planes Copyright (c) by <NAME> and <NAME>, 2012 """ from pyscipopt import Model, Conshdlr, quicksum, multidict, SCIP_RESULT, SCIP_P...
''' Generates patch-to-patch impulse responses (in frequency domain) database for an array of CMUT membranes. ''' import numpy as np import multiprocessing from itertools import repeat from tqdm import tqdm import os, sys, traceback from scipy.sparse.linalg import lgmres from timeit import default_timer as timer from...
import random from sklearn.metrics import pairwise_distances import pygame from math import degrees, atan2, cos, sin, radians import numpy as np pygame.init() clock = pygame.time.Clock() BLUE = (0, 0, 255) RED = (255, 0, 0) WHITE = (255, 255, 255) class Odin(object): G = 6.674 * 1e-1 BigBang = False max...
"""Provides ESMF representations of grids/UGRID meshes and a modified regridder.""" import ESMF import numpy as np from numpy import ma import scipy.sparse from ._esmf_sdo import GridInfo __all__ = [ "GridInfo", "Regridder", ] def _get_regrid_weights_dict(src_field, tgt_field): regridder = ESMF.Regrid(...
#!/usr/bin/env python3 # encoding: utf-8 # Modified from https://github.com/Wangyixinxin/ACN import torch from torch.nn import functional as F import numpy as np import numpy as np from matplotlib import cm import matplotlib.pyplot as plt import numpy as np import cv2 from PIL import Image import cv2 import torch.nn a...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class MappingNetwork(nn.Module): """Some Information about MappingNetwork""" def __init__(self, dim, num_layers=8, activation=nn.LeakyReLU): super(MappingNetwork, self).__init__() self.seq = nn.Sequen...
#import statements from flask import Blueprint, render_template, request, flash, redirect, url_for from . import db from flask_login import login_required, current_user from .models import Entry from .form import entryform from .form import EditEntryForm main = Blueprint('main', __name__) #route to ma...
# -*- coding: utf-8 -*- #MxZ_PUC import numpy import time import magdynlab.instruments import magdynlab.controllers import magdynlab.data_types import threading_decorators as ThD import matplotlib.pyplot as plt @ThD.gui_safe def MyPlot(Data): f = plt.figure('ZxH', (5,4)) if not(f.axes): ...
import logging from openstack import connection from openstack import resource from openstack.compute.v2 import server as _server #from keystoneclient.auth.identity import v2 from keystoneauth1.identity import v2, v3 from keystoneauth1 import session from pytz import timezone import pytz class MyServer(_server.Server)...
import argparse from cbuild.utils import create_dir from cbuild.utils import write_string_to_file from cbuild.utils import read_string_from_file from cbuild.utils import store_url from cbuild.utils import unzip from cbuild.buildutils import create_env from cbuild.buildutils import load_defaults from cbuild.buildutils i...
from base64 import b64encode import requests from json import loads as parse_json import os import datetime class ShopifyAPI: token = os.environ['SHOPIFY_AUTH_TOKEN'] headers = { 'Authorization': 'Basic {token}'.format( token=b64encode(token.encode()).decode('ascii')) } shop_addre...
import os import stat import tempfile import yaml from google.cloud import storage _BUCKET_URL_PREFIX = 'gs://' def get_bucket_name_from_url(url: str): if _BUCKET_URL_PREFIX not in url: return None url = url.replace(_BUCKET_URL_PREFIX, '') if '/' in url: url = url[:url.index('/')] r...
from pyb import UART #导入UART串口 uart = UART(3,500000)#初始化串口 UART3波特率 500000 class Receive(object): uart_buf = [] _data_len = 0 _data_cnt = 0 state = 0 R=Receive() #接收数据缓存对象 # WorkMode=1为寻点模式 # WorkMode=2为寻线模式 包括直线 转角 class Ctrl(object): WorkMode = 0 #工作模式 IsDebug = 1 #不为调试状态时关闭某些图形显示等,有利...
# examples/invoice_app.py """ This app provides an example posting child relations with a parent class through the example of an invoice. """ # initialize from os import path from flask import Flask from flask_cors import CORS from flask_restful import Api, Resource from flask_restful_dbbase import DBBase from flask_...
import re import json import os from scrapy.spiders import Rule, CrawlSpider from scrapy.crawler import Crawler, CrawlerProcess from scrapy.linkextractors import LinkExtractor from w3lib.html import remove_tags from crawler.utils import APIItem, nice_dump, process_code_info class DplyrSpider(CrawlSpider): name = ...
"""Functioned related to configuration of houdini_package_runner.""" # Future from __future__ import annotations # Standard Library import abc import importlib.resources import os import pathlib from typing import TYPE_CHECKING, Dict, List, Tuple # Third Party import deepmerge import toml # Imports for type checkin...
""" FOMO (Moving Avg) strategy class. Buy when market is greedy, sell when it is fearful. Not expected to make money. Inherits base_strategy. Takes in how often you want to trade (in days) as an input. Fear and Greed data is daily so this should be 1 day or greater. """ from datetime import datetime, timezone import t...
import os import re from datetime import datetime from google.appengine.api import users from google.appengine.api import urlfetch import webapp2 from google.appengine.ext.webapp import template from google.appengine.ext.webapp import util import json as simplejson from model import get_current_youtify_user_model from ...
# coding: utf-8 # # Capítulo 3 # # ## Números, datas e horas # In[2]: print(round(1.27, 1)) print(round(-1.24, 1)) print(round(1.32564675, 3)) # In[3]: # O comportamento do arrendondamento consiste em aarrendondar para o dígito mais próximo print(round(1.5)) print(round(2.5)) # Porque não arrendondou para 3 ?...
""" calculate camera distortion matrix saves matrix to camera_matrix.pickle press s to save image from camera, and q to close camera and start calibration usage: pyvr calibrate-cam [options] Options: -c, --camera <camera> Source of the camera to use for calibration [default: 0] -fov, --f...
import codecs import datetime import json import os.path import sys import re import traceback try: import logger import helpers import pil except ImportError: from . import logger from . import helpers from . import pil try: from instagram_private_api import ( Client, ClientError,...
from __future__ import absolute_import, division, print_function import numbers from datetime import date, datetime from toolz import first from ..compatibility import basestring from ..expr.core import Expr from ..expr import TableSymbol, eval_str, Union from ..dispatch import dispatch __all__ = ['compute', 'compute...
""" 難病(指定難病, 小児特定慢性疾病)とMondoを紐付ける """ import json from pathlib import Path from typing import List from pymondo.mondo import Mondo, MondoNode, Scope from pynando.nando import Nando, NandoNode from cnorm.chain import Chain from .config import Config from .utils.chain import chain from nltk.tokenize import word_tokeni...
# Copyright 2020 Google LLC. 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 applicable law or a...
import linecache as lc import fileinput import os """ Parse_File creates functionality for opening and parsing file within a with statment block automatically closing file at the end of the block. Inclues: TODO """ class Parse_File: #constructor for class #opens sets filename to private class isntance variable ...
from flask import Flask, flash, request, redirect, url_for from flask import render_template, jsonify from werkzeug.utils import secure_filename import pandas as pd import redis import io import ujson import collections import scipy.stats as stats import numpy as np app = Flask(__name__) ALLOWED_EXTENSIONS = {'txt'...
from typing import List, Any, Union import unittest from ..splitter import ( SplitterTile, Portal, Tile, TileFactory, SPLIT_HORIZONTAL, SPLIT_VERTICAL, ) from ..portal import ( POSITION_FAVOR_FILL, ) from .....core.platform.api import ScreenArea class SplitterTileTest(unittest.TestCase): def test_no_...
import os, glob, shutil, argparse import numpy as np import matplotlib.pyplot as plt from PIL import Image,ImageDraw,ImageFont from skimage.transform import resize def make_dir(path, refresh=False): try: os.mkdir(path) except: if(refresh): shutil.rmtree(path) os.mkdir(...
import sys, os, time, math, random, argparse, glob import numpy as np from constants import Constants ''' Prepare data (WMT en_fr) for translation from English to French using byte pair encoding. https://arxiv.org/pdf/1508.07909.pdf ''' def get_paths(path_source, path_target, constants, hyperparams): fold...
import os import logging import shutil logger = logging.getLogger(__name__) def get_des_info_file(medsconf, tilename, band): """ get the path to the pizza cutter info file for a DES tile Paramters --------- medsconf: string The name for the pizza cutter meds dir under $MEDS_DIR tilen...
from tensorflow.python.ops import gen_nn_ops import tensorflow.nn as nn import tensorflow as tf import tensorflow_probability as tfp import numpy as np tfd=tfp.distributions class Relu(object): """Relu activation function""" def __init__(self): self.numTensors=0 self.numHyperTensors=0 ...
from sqlalchemy.orm import Session from nonbonded.backend.database import models from nonbonded.backend.database.crud.authors import AuthorCRUD from nonbonded.backend.database.utilities.exceptions import ( DataSetExistsError, DataSetNotFoundError, QCDataSetExistsError, QCDataSetNotFoundError, Unabl...
import logging from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core import validators from django.core.exceptions import ValidationError from django.db i...
import pytest from aiocouch.database import Database from aiocouch.document import Document # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio async def test_update_docs_on_empty(database: Database) -> None: async with database.update_docs([]) as bulk: pass assert bul...
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accom...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
# This module loads and prepares the data import torch, time, sys, re import pandas as pd from torch.nn import functional as F from torch.utils.data import DataLoader import numpy as np ALPHABET = 'ACDEFGHIKLMNPQRSTVWXYZ-' SEQ2IDX = dict(map(reversed, enumerate(ALPHABET))) def compute_weights(data): ...
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import plistlib import os import re import subprocess import sys import tempfile import shlex # Xcode substitutes variables like ${PRODUCT_...
import logging import os import threading from queue import Queue from typing import Tuple from confluent_kafka import Consumer, Message, TopicPartition class _StoppableThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._stop_event = threading.Ev...
import numpy as np import h5py import copy #import images (train and test) from dataset def load_dataset(): train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features train_set_y_orig = np.array(train_dataset...
import os import sys try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import argparse import functools import subprocess LZOP_BIN = 'lzop' PV_BIN = 'pv' S3_CONNECTION_HOSTS = { 'us-east-1': 's3.amazonaws.com', 'us-west-2': 's3-us-west-2.amazonaws.com', 'us-wes...
import os # windows bug os.system("") class Cologger: def __init__(self): self.color = None self.bg_color = None self.fmt = None def set_fmt(self, fmt): if fmt == "bold": self.fmt = Formaters.BOLD elif fmt == "italic": self.fmt = Formaters.ITAL...
from mooquant import plotter, strategy from mooquant.analyzer import drawdown, returns, sharpe, trades from mooquant.broker.backtesting import TradePercentage from mooquant.broker.fillstrategy import DefaultStrategy from mooquant.technical import cross, ma from mooquant.tools import tushare class thrSMA(strategy.Back...
import os import string import io import sys import trace class KeywordProcessor(object): """KeywordProcessor Note: * Based on Flashtext <https://github.com/vi3k6i5/flashtext> * loosely based on `Aho-Corasick algorithm <https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm>`. """ ...
import utils from os import listdir from os.path import join import datetime as dt import copy def parseBinanceAmount(asset): ticker = '' qty = '' for c in asset: if ("" + c).isalpha(): ticker += c else: qty += c return ticker, float(qty) def parse(historical_c...
# !/usr/bin/python """ Builder Class for Level Hiring plot """ ## MIT License ## ## Copyright (c) 2017, <NAME> ## 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, includi...
import RPi.GPIO as GPIO import time from queue import Queue class Caliper: def __init__(self, pin_data, pin_clock, pin_zero, clock_bouncetime=1, pause_time=50, pin_debug=None, name="", median_filter_max_error=10, median_filter_window_size=10): """This class interfaces with the digital cal...
import numpy as np import scipy.special """ Collects functions defining and evaluating the Jolanta model potential """ def Jolanta_1D(x, a=0.2, b=0.0, c=0.14): """ default 1D potential; has a resonance just below 7 eV use for DVRs """ return (a*x*x-b)*np.exp(-c*x*x) def Jolanta_3D(r, a=0.1, b=1...
import numpy as np import random from pynvml import * import torch class ReplayMemory: def __init__(self, capacity): self.capacity = capacity self.buffer = [] self.position = 0 def push(self, state, action, reward, next_state, rnn_state, labels, done): state_cpu = state.cpu().n...
import gin import gym import numpy as np import tensorflow as tf from gym.wrappers import TransformObservation import encoder import os from causal_util.helpers import np_random_seed from functools import partial @gin.configurable class KerasEncoder(object): """Applies a keras model to observations."...
''' ' benchmark test for MNIST dataset ''' from __future__ import print_function import tensorflow as tf import sys, time # define the functions that are used in the nn # def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): init...
import argparse import logging from pathlib import Path import torch from torchvision import transforms, datasets from nni.algorithms.compression.v2.pytorch import pruning from nni.compression.pytorch import ModelSpeedup from examples.model_compress.models.cifar10.vgg import VGG logging.getLogger().setLevel(logging....
import time from unittest import mock from os.path import dirname, normpath from os.path import join as pathjoin from datetime import datetime from django.conf import settings from django.test import override_settings from django.test import TestCase from django.contrib.auth import get_user_model from django.test.cl...
import numpy as np from collections import defaultdict from collections import OrderedDict import heapq def measure_k(probs, true_ys, k_list=[1, 3, 5]): max_k = np.max(k_list) num_samples = np.size(true_ys, 0) precision_k = defaultdict(float) dgg_k = defaultdict(float) ndgg_k = defaultd...
#!/usr/bin/env python3.6 import csv import time from multiprocessing.pool import ThreadPool from typing import List, NamedTuple import click import requests import urllib3 from bs4 import BeautifulSoup urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class UrlConfig(NamedTuple): full_url: str...
""" """ __all__ = ["Value", "Attribute"] import dill import numpy as np from collections import Iterable from copy import copy from typing import Any, Dict, List, Tuple, Union from .annotation import Annotation, AnnotationResult from .invariants import invariant class Value(Annotation): """ Annotation cla...
"""Defines Ctx, a context within which an action is possible. E.g., "home" or "the store". """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import six import gflags as flags from . import auditable_object from . import common from . import con...
import pandas as pd from string import ascii_lowercase import xlrd import numpy as np import json from scipy import stats from math import isinf import sys #-------- # Returns list of drugs studied in gwas/inrich dataset # PARAMETERS: # gwas_dataset = gwas/inrich dataset containing all the drug-phenotype pairs def get...
import re import os import json import requests import sys from future.utils import raise_from class Auth: def __init__(self, url, sslcert=None, **kwargs): self._url = url self._sslcert = sslcert if sslcert is not None and not os.path.isfile(sslcert): raise FileNotFoundError( ...
import tensorrt as trt import numpy as np import pycuda.autoinit import pycuda.driver as cuda import time import cv2 import imageio import argparse import tqdm from icecream import ic import os.path as osp import sys from pathlib import Path sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from utils...
import tensorflow as tf import numpy as np def _resnet_block_v1(inputs, filters, stride, projection, stage, blockname, TRAINING): # defining name basis conv_name_base = 'res' + str(stage) + blockname + '_branch' bn_name_base = 'bn' + str(stage) + blockname + '_branch' with tf.name_scope("conv_block_st...
import csv import matplotlib.pyplot as plt from utils import WordsToLetter, extractFeatures, extractLabels, extractTokens def obtener_palabras(corpora): palabras = [] for frases in corpora: for frase in frases: chunks = [palabra[0] for palabra in frase[:-1]] palabras.append(""....
import sys import logging import socket from datetime import datetime import numpy as np from timeit import default_timer as timer from torch.utils.tensorboard import SummaryWriter from torchwi.utils.plot import perc_clip, plot_vel, plot_mig import matplotlib.pyplot as plt import yaml formatter = logging.Formatter('[%...
# -*- coding: utf-8 -*- # # Copyright (c) nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. ...
"""Most utility functions here has been adopted from: https://github.com/guillaumegenthial/sequence_tagging/blob/master/model/data_utils.py """ import numpy as np import os import math # shared global variables to be imported from model also UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # read the word importance scores ...
from category.models import Category from django.contrib import admin from django.contrib.admin import SimpleListFilter from django.db.models import Count, F from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.encoding import force_text from django.utils.safestring import ma...
""" Copyright 2018 IBM Corporation 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...
import time import numpy as np import sys sys.path.append('../sFEre') from FE_mesh.sphere_mesh import element_length_translator, create_elements, spacing, renumbering_element_pairs from FE_mesh.LSDYNA_keyword_manager import output_keyword_file def mesh_configuration(mesh_method, spacing_method, radius, element_leng...
from sklearn.tree import export_text import sklearn_json as skljson import pandas as pd from pyspark.ml.classification import RandomForestClassificationModel from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import StructType, StructField, DoubleType from pyspark.ml.feature impo...
from bson.objectid import ObjectId import time from pymongo.collation import Collation, CollationStrength from pymongo.message import query, update from pprint import pprint import secrets import mongodb.auths as auths import mongodb.users as users import mongodb.decks as decks from flask_pymongo import PyMongo from m...
#!/usr/bin/python # NOTE: use macOS default python2 # Try alternative methods rather than Ngram models to estimate the information content of sentences # <NAME> # 3/3/2017 from __future__ import print_function from nltk.probability import FreqDist from nltk.util import ngrams from random import shuffle import math im...
import logging import numpy as np import pandas as pd from toucan_data_sdk.utils.helpers import check_params_columns_duplicate def compute_evolution_by_frequency( df, id_cols, date_col, value_col, freq=1, method='abs', format='column', offseted_suffix='_offseted', evolution_col_na...
#!/usr/bin/env python """ This is a Brainfuck interpreter (not a compiler) written in Python. It is somewhat optimized for speed, as much as that is possible. By default it allows for 30000 bytes of memory, but this can be configured by passing a parameter. Some protections are in place in order to keep the progra...
import pytz from django.db import models from django.utils.html import mark_safe from django.utils.translation import gettext as _ from ..misc.models import TimeZone, StateRegion from ..astro.utils import get_limiting_magnitude from .pdf import create_pdf_form CARDINAL_DIRECTIONS = [ ('N', 'North'), ('NE', 'No...
""" Data Preprocessing """ import os import re import pandas as pd # read train data file_dir = '/Users/dnhb/PycharmProjects/SML_Ass1' file_name = "train.txt" def parse(data:list)->list: # Python Notation: https://www.python.org/dev/peps/pep-3107/ """ Prase each line of the data Return a nested list...
import cv2 import os import copy import torch import numpy as np from torch.nn import functional as F from cv2 import IMREAD_UNCHANGED # transpose FLIP_LEFT_RIGHT = 0 FLIP_TOP_BOTTOM = 1 class SemanticSegmentation(object): def __init__(self, semseg, class_ids, size, mode='poly'): self.size = size ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #### # scripts to index a completely downloaded day ### __author__ = '<NAME>' __email__ = '<EMAIL>' __copyright__ = "Copyright 2018, <NAME>" __version__ = "0.0.7" import glob import os from time import time import pandas as pd from elasticsearch import Elasticsearch fro...
import concurrent.futures import json import shutil from pathlib import Path import flickrapi import typer from flower_classifier.datasets.flickr.auth import USER_ID as FLICKR_USER_ID from flower_classifier.datasets.flickr.client import ( download_photo, get_authenticated_client, get_photo_tags, updat...
# -*- encoding: utf8 -*- from .partition_shape_experiment import PartitionShapeExperiment from .. import dataset from .. import job from .. import plot from .. import util import lue.data_model as ldm import dateutil.parser import matplotlib import matplotlib.pyplot as plt import numpy as np def post_process_raw_res...
from .validation import ValidationException # ====== # Utility definitions # Data types: see below # ====== class Result: @staticmethod def success(value): return Result(True, value) @staticmethod def fail(error): return Result(False, error) @staticmethod def ensure(requireme...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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, ...
# capitalbot/fb_capitalbot/views.py import json, requests, random, re from pprint import pprint from django.views import generic from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator # ------------------------ Fill thi...
#!/usr/bin/env python """ This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt f...
""" Test the domain splitting """ from __future__ import print_function, absolute_import, division, unicode_literals from numpy import * from numpy.random import RandomState from lizard.lizard_c import * from lizard.ngb_kernel import * from lizard.log import VerboseTimingLog from lizard import domain from os import pat...
# section and sentence tokenization for MIMIC-III discharge summaries import os import re def match_section_name(name, section_dict, nlp_parser): output = nlp_parser.annotate(name.lower(), properties={ 'annotators': 'lemma', ...
import math import numpy as np def quaternion_to_euler_angle(array): # from "Energy-Based Hindsight Experience Prioritization" w = array[0] x = array[1] y = array[2] z = array[3] ysqr = y * y t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + ysqr) X = math.atan2(t0, t1) t2...
import sys import traceback import threading from time import sleep, time try: import RPi.GPIO as GPIO except RuntimeError: print("Error importing RPi.GPIO! Use 'sudo' to run your script") import cloud4rpi from config import C4R_TOKEN, C4R_HOST from config import GPIO_PUMP from config import MIN_DISTANCE, MAX...
""" SPDX-License-Identifier: BSD-3-Clause A vendored copy of click.style() @ 4f7b255 """ import typing as t _ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red":...
import time import os import random import pygame import neat import pickle from src.params import * from src.bird import Bird from src.pipes import Pipe from src.floor import Floor def draw_window(win,birds, pipes, floor, score, alive=True, stats = False): win.blit(BG_IMAGE, (0,0)) floor.draw(win) i...
# 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 # d...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. import torch import torch.nn as nn from block_zoo.BaseLayer import BaseLayer, BaseConf from block_zoo.transformer.MLP import MLP, MLPConf from block_zoo.transformer.MultiHeadAttention import MultiHeadAttention, MultiHeadAtte...
import math import numpy as np import random class Task(object): def __init__(self, robot=None): """Init of the Task Args: desired_velocity: velocity that will achieve the maximum reward max_desired_velocity: maximum desired velocity """ self.starting_c...
""" Data ingestion logic """ import os import random import re from io import BytesIO from pathlib import Path from typing import Optional, List, Dict import numpy as np import tensorflow as tf from astropy.io import fits def fits_open(path): return fits.open(str(path))[0].data.squeeze() def transform(image, f...
# File: ecuaciones.py # Del capítulo 14 de _Algoritmos Genéticos con Python_ # # Author: <NAME> <<EMAIL>> # Copyright (c) 2017 <NAME> # # 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 # ht...