text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import urllib
import plotly.graph_objects as go
from textwrap import wrap
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from navbar import Navbar
from footer import Footer
from assets.mappings import get_colors
def InteractiveGraph()... |
import os
import asyncio
from abc import ABC
from airflow.hooks.base_hook import BaseHook
from airflow.models import BaseOperator
from plugins.utils.utils import get_curve_params, get_curve, get_result
from typing import Dict
from airflow.api.common.experimental import trigger_dag as trigger
from distutils.util import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; replace-tabs on;
from __future__ import division
import os
import math
import socket
import os.path
import json
from oping import PingObj, PingError
from optparse import OptionParser
from redis import StrictRedis
from thread... |
# -*- coding: utf-8 -*-
"""\
Caelus SCons build environment
-------------------------------
Creates the base build environment used during the Caelus compilation process.
"""
import os
from collections import OrderedDict
import json
import SCons.Script
from SCons.Environment import Environment
from variables import ... |
import math
import random
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm_notebook
from torchvision.utils import save_image
import phyre
import torch
import torch.nn.functional as F
random.seed(0)
####save the data
import os
import h5py
def save_dict_h5py(array_dict, fname):
"""Save dict... |
"""
"""
# Created on 2014.08.23
#
# Author: <NAME>
#
# Copyright 2014 - 2020 <NAME>
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version... |
import logging
import random
import time
import io
import os
import datetime
import concurrent.futures
import typing as t
import discord
import discord.ext.commands as commands
from PIL import Image, ImageDraw, ImageSequence, ImageFont
from bot.consts import Colors
log = logging.getLogger(__name__)
MAX_WALDO_GRID_SI... |
from ssl import SSLError
from urllib import parse
from urllib.error import URLError
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import time
import socket
import random
import argparse
import datetime
import pandas as pd
def crawl(query, save_as, begin... |
from torch import nn
from torch.nn import functional as F
import numpy as np
from torch.autograd import Variable
import torch
from torch import optim
class deep_q_network(nn.Module):
def __init__(self, state_dim, action_dim, n_layers, hidden_size):
"""
DQN的target-net和eval-net
:param state_... |
#!/usr/bin/python3
"""Run a tensorflow model using tensorRT."""
import argparse
import os
import numpy as np
import pycuda.autoinit as _
import pycuda.driver as cuda
import tensorflow as tf
import tensorlayer as tl
import tensorrt as trt
import uff
from cv2 import imwrite
from tensorrt.parsers import uffparser
from ... |
from .hashindex import Index
import math
import random
def anneal(state, max_temp, min_temp, steps):
factor = -math.log(float(max_temp) / min_temp)
state = state.copy()
best_state = state.copy()
best_energy = state.energy()
previous_energy = best_energy
for step in xrange(steps):
temp ... |
'''
This algorithm defines a target long-only diversified portfolio and rebalances
it at a user-specified frequency (currently set to 1ce per 28 days).
Portfolio constituents & weights: (modify these by changing consituents in initialize()
and changing weights in rebalance() method.
VTI - 40... |
#!/usr/bin/python
import argparse
import sys
import json
import logging
import logging.config
from m3d import M3D
MANDATORY_ARGS = "mandatory_arguments"
OPTIONAL_ARGS = "optional_arguments"
DEFAULT_LOGGING_CONFIG = "config/logging/logging.json"
DEFAULT_LOG_FORMAT = "%(asctime)s|%(levelname)s|%(name)s|%(filename)s:%... |
import logging
import requests
import hashlib
import inspect
from collections import OrderedDict, namedtuple
from concurrent import futures
from .storedata import url_request_problem_store
from .processdata import case_data_process
logger = logging.getLogger('goapitest.apidatabases')
Thread_Max = 20
Response_Data ... |
"""
Construct projections between FE spaces.
"""
import numpy as nm
from sfepy.base.base import output, IndexedStruct
from sfepy.discrete import (FieldVariable, Integral,
Equation, Equations, Material)
from sfepy.discrete import Problem
from sfepy.terms import Term
from sfepy.solvers.ls imp... |
""" generic mechanism for marking and selecting python functions. """
import pytest, py
def pytest_namespace():
return {'mark': MarkGenerator()}
def pytest_addoption(parser):
group = parser.getgroup("general")
group._addoption('-k',
action="store", dest="keyword", default='', metavar="KEYWORDEXPR"... |
import json, os, docx, io, base64
from flask import current_app
from sqlalchemy.schema import FetchedValue
from sqlalchemy.ext.hybrid import hybrid_property
from docx.shared import Inches
from datetime import datetime
import dateutil.parser
from app.extensions import db
from app.api.utils.models_mixins import AuditMi... |
#!/usr/bin/python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
def bb_intersection_over_union(box_a, box_b):
"""
Find out how much 2 boxes intersect
:param box_a:
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
from enum import Enum
from typing import Optional
import numpy as np
import reagent.core.types as rlt
import torch
from reagent.core.dataclasses import field
from reagent.models.base import ModelBase
from reag... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copyright 2021 Toyota Research Institute. All rights reserved.
import json
import logging
import os
from collections import OrderedDict, defaultdict
import numpy as np
import torch
from detectron2.data import DatasetCatalog, MetadataCatalog
fr... |
# Functions to perform hand gesture recognition
import math
import numpy as np
import cv2 as cv
#####################################
# Distance Formula Function
#####################################
def dist(x1, x2, y1, y2):
sq1 = (x1 - x2) * (x1 - x2)
sq2 = (y1 - y2) * (y1 - y2)
return mat... |
from abc import ABC
from matplotlib import patches as ptch
import numpy as np
from typing import List, Optional, Union
from autoarray.structures.arrays.one_d.array_1d import Array1D
from autoarray.structures.grids.one_d.grid_1d import Grid1D
from autoarray.structures.arrays.two_d.array_2d import Array2D
from a... |
"""Zipfile entry point which supports auto-extracting itself based on zip-safety."""
from importlib import import_module
import zipfile
import os
import runpy
import sys
PY_VERSION = int(sys.version[0])
if PY_VERSION >= 3:
from importlib import machinery
else:
import imp
try:
from site import getsitepac... |
from typing import List, Dict, Set, Optional, TypeVar
from collections import OrderedDict
from itertools import chain
from ..types import TealType
from ..ast import SubroutineDefinition
from ..ir import TealComponent, TealOp, Op
# generic type variable
Node = TypeVar("Node")
def depthFirstSearch(graph: Dict[Node, S... |
#!/usr/bin/env python
"""Creates monthly_ice_{month}_{hemi}.png images (ASINA Figure 3) from data
obtained with the seaicetimeseries package using plotly.
"""
import calendar
import math
import os
import click
import numpy as np
import plotly.graph_objs as go
from seaice.tools.plotter.util import save_plot
import s... |
# Copyright 2018 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 agreed to in writing, ... |
"""Modul obsahující funkce týkající se online schůzek."""
import json
from datetime import datetime
from typing import cast
from bs4 import BeautifulSoup
from bs4.element import Tag # Kvůli mypy - https://github.com/python/mypy/issues/10826
from ..bakalari import BakalariAPI, Endpoint, _register_parser, _register_re... |
# conding=utf-8
import nltk
from nltk.corpus import brown
from nltk import WordNetLemmatizer
from math import log
def wordlist(in_fname):
f = open(in_fname, mode='r', encoding = 'utf-8-sig', errors='ignore')
wordls = []
for words in f.read().split(' '):
# replace \ufeff
words = words.replace(u'\ufe... |
"""
This module provides a class which implements a gateway between UDP multicast
and socket-CAN.
"""
__author__ = "<NAME>"
import time
import socket
import selectors
import logging
import ipaddress
from . import can
logging.basicConfig(level=logging.DEBUG,\
format='[%(asctime)-15s] %(module)-s: [%(levelname... |
from nlplib.core.process.parse import Parsed
from nlplib.core.model import SessionDependent
__all__ = ['Indexed']
class _AddIndexes (SessionDependent) :
def __init__ (self, session, document, parsed) :
super().__init__(session)
self.document = document
self.parsed = parsed
def __cal... |
#imports
#MACOS Version
import os
import time
import webbrowser
from colorama import Fore, Back, Style
from colorama import init
from colorama import init
#imports
#reset color
init(autoreset=True)
#reset color
#Core Def Steps
def agreement():
os.system("clear")
print(Style.BRIGHT+Back.BLACK+Fore.MAGENTA+"TERM... |
from corehq.apps.reports.standard import DatespanMixin, ProjectReportParametersMixin, CustomProjectReport
from corehq.apps.reports.datatables import DataTablesColumn, DataTablesColumnGroup, DataTablesHeader, DTSortType
from corehq.apps.reports.generic import GenericTabularReport
from dimagi.utils.couch.database import ... |
"""This module provides methods for symmetric cryptography.
The default symmetric cryptography method used is Fernet by the cryptography
library. Reference: https://cryptography.io/en/latest/fernet/
"""
import base64 as _base64
import os as _os
import logging
import six
from warnings import warn as _warn
import cryp... |
import argparse
import random
import os
# from torchvision import models
from tqdm import tqdm
from termcolor import colored
from datetime import datetime
import numpy as np
import torch
from config import create_config
from utils import get_train_dataset, get_val_dataset, get_dataloader, get_val_loader, ... |
#---------------------References---------------------------------------
# 1.https://matplotlib.org/2.1.1/gallery/shapes_and_collections/scatter.html
# 2.https://pythonspot.com/matplotlib-scatterplot/
# 3.https://jakevdp.github.io/PythonDataScienceHandbook/04.02-simple-scatter-plots.html
# 4.http://blog.mpacula.com/2011... |
# coding=utf-8
"""Funciones auxiliares de entrada y salida.
Este módulo provee diversas funciones para la entrada y salida de
datos en la cónsola, así como la validación de datos ingresados y
el procesamiento de archivos CSV.
"""
import csv
import re
import textwrap as tw
from math import ceil
def print_h1(s, newl... |
""" Special Cython extension builder.
Unfortunately, the inbuilt cython and cythonize command line utilities do no
support the generation of python extension modules out of the box. More
precisely, the cython command is able to produce a pyd/so file but does not
export a python module initializer. cythonize, on the ... |
import os
import numpy as np
import matplotlib.pyplot as plt
class ModelInfo(object):
def __init__(self, model_type, pipeline, filter_function, features):
self._model_type = model_type
self._pipeline = pipeline
self._filter_function = filter_function
self._features = features
... |
# -*- coding: utf-8 -*-
# @Time : 8/20/2018 10:46 AM
# @Author : DonaldY
# 下载数据集
# !wget http://labfile.oss.aliyuncs.com/courses/1081/course-9-syringa.csv
"""加载数据集
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
lilac_data = pd.read_csv('course-9-syringa.csv')
lilac_data.head() #... |
# coding=utf-8
# Copyright 2021 The Ravens 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... |
## benchmarks / benchmark_hmatrix_error.py ##
import numpy as np
from tqdm import tqdm
from timeit import default_timer as timer
import multiprocessing
import argparse
import sqlite3 as sql
from contextlib import closing
import traceback
import sys
import os
from cmut_nonlinear_sim.mesh import *
from cmut_nonlinear_s... |
'''
Created on Jul 20, 2017
@author: <NAME>
'''
import json
import math
from os import getcwd
from os.path import join
import sys
import time
from keras.layers.core import Dense
from keras.models import Model
from keras.models import Sequential
from keras import backend as K
import numpy as np
import random
kept_m... |
# Simple script to set a couple of metadata fields in an EPUB3.
import argparse
import datetime
import os
import tempfile
import zipfile
import dawn
import xml.etree.ElementTree as ET
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
usage="%(prog)s [OPTION] [FILE]...",
... |
import numpy as np
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
master_url_root = "https://raw.githubusercontent.com/numenta/NAB/master/data/"
df_small_noise_url_suffix = "artificialNoAnomaly/art_dai... |
print(f'Loading {__file__}...')
import bluesky.plans as bp
import bluesky.plan_stubs as bps
import time
def Shutter_in():
yield from bps.mv(Shutter_Y, 3)
def Shutter_out():
yield from bps.mv(Shutter_Y,44)
def Izero_screen():
yield from bps.mv(Izero_Y, 2)
def Izero_mesh():
yield from bps.mv(Izero_Y, -2... |
import pandas as pd
def get_replies(df):
'''Extracts the replies to the comments as well as the nested
replies to those replies, adds all of them to the orginal dataframe
and returns the dataframe.'''
if 'replyCount' in df.columns:
selected_df = df.loc[df.replyCount>0]
if selected... |
import numpy as np
import torch
nn = torch.nn
F = nn.functional
import monai.transforms as mtr
import util
def get_transforms(args):
preproc_settings = args["data loading"]
aug_settings = args["augmentations"]
val_transforms = mtr.Compose([
mtr.LoadImaged(keys=["image"]),
mtr.AddChanneld(... |
'''
Copyright (C) 2020-2021 <NAME> <<EMAIL>>
Released under the Apache-2.0 License.
Black-box Order Attack Implementation
'''
from random import random
from scipy.stats import kendalltau
from termcolor import cprint, colored
from tqdm import tqdm
from typing import *
import math
import numpy as np
import os
import sys... |
import uuid
from starlette.responses import JSONResponse
# from starlette.requests import Request
from src.apps.users.models import User
from starlette import status
from .models import *
from src.config.settings import BASE_DIR, STATIC_ROOT, MEDIA_ROOT
from src.apps.users.views import get_current_login
from src.apps.... |
import json
import logging
import re
import aiohttp
from aiogram import types
from aiogram.dispatcher import FSMContext, filters
from aiogram.dispatcher.filters.state import any_state
from aiogram.types.message import ContentTypes
from aiogram.utils.emoji import emojize
from .. import texts
from ..bot import _, bot, ... |
import datetime
import pandas as pd
from sklearn.utils import shuffle
from pandas import DataFrame
from src.coco.online_feature import OnlineFeatureHandler
from src.feature_handle.base_utils import columns_drop, to_csv
from src.model.statistic_model.classfier_model import LrClassifier, KnnClassifier, LgbmClassifier,... |
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource, fields, marshal_with
import GoogleAPI
app = Flask(__name__)
app.secret_key = "615479af3de3482bdb6ed6c5f8f15457"
api = Api(app)
# SQLAlchemy Database Configuratio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2022 <NAME>
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... |
# Copyright © 2021 to 2022 IOTIC LABS LTD. <EMAIL>
#
# 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
#
# https://github.com/Iotic-Labs/iotics-host-lib/blob/master/LICENSE
#
# Unless require... |
import os
import sys
from datetime import datetime
from sqlalchemy.sql.expression import column
import xlsxwriter
import click
from sqlalchemy import select, and_, func
from planning_system.db import DB
from planning_system.db.schema.views import get_view_class
from planning_system.db.schema.tables.finance_structure im... |
#!/usr/bin/env python
# Copyright 2011-2012 <NAME> <<EMAIL>>
# See LICENSE.txt for details.
import re, os, sys, cStringIO
WARNING = "/* This file is automatically generated by keycode.py. */"
def readTable(path):
v = []
for lineno, line in enumerate(open(path, 'r')):
if line.startswith(';'):
... |
"""
Exports one function, draw_game(), which turns a GameState into a grid of
cells.
"""
from math import floor
from .const import terrain_types, EnumFeature, EnumMonsterMode
from clubsandwich.blt.nice_terminal import terminal
from clubsandwich.draw import LINE_STYLES
from clubsandwich.geom import Rect, Point, Size
f... |
import os.path
import sys
import tempfile
import six
import pytest
from behave import configuration
from behave.configuration import Configuration, UserData
from behave.runner import Runner as BaseRunner
from unittest import TestCase
# one entry of each kind handled
TEST_CONFIG="""[behave]
outfiles= /absolute/path1
... |
""" Don't want to import everything fast.ai depends on,
so copy from https://github.com/fastai/fastai/blob/master/fastai/tabular/transform.py
"""
import calendar
from typing import List, Union, Collection, Tuple
import re
from functools import partial
from ..util import ifnone, listify
import numpy as np
import pandas ... |
import pytest
from modules.simulation.individual.hwt import HWT
import numpy as np
actions = HWT.create_action_set(-1000, 1000, 201)
# constants
water_heat_capacity = 4190 # J/(kg*K)
water_density = 997 # kg/m^3
ws_per_j = 1. # Ws/J
def test_state_manipulation():
v = 1. # m^3
hwt = HWT(900, 60, 80, v, 1., ... |
import wx
import webbrowser
from settings import settings
BLANK = 'about:blank'
COMMAND_CLOSE = 'http://close/'
COMMAND_NEXT = 'http://next/'
COMMAND_PREVIOUS = 'http://previous/'
COMMAND_FIRST = 'http://first/'
COMMAND_LAST = 'http://last/'
COMMAND_PLAY = 'http://play/'
COMMAND_PAUSE = 'http://pause/'
d... |
from __future__ import unicode_literals
from .mtv import MTVServicesInfoExtractor
from .common import InfoExtractor
class ComedyCentralIE(MTVServicesInfoExtractor):
_VALID_URL = r'''(?x)https?://(?:www\.)?cc\.com/
(video-clips|episodes|cc-studios|video-collections|shows(?=/[^/]+/(?!full-episodes)... |
import os
import gzip
from fetch.math import NDArrayDouble
from tqdm import tqdm
import random
import numpy as np
DATA_URL = 'http://yann.lecun.com/exdb/mnist/'
def load_data(one_hot=True, reshape=None, training_size=50000,
validation_size=10000):
print("loading training image data")
x_tr = ... |
"""
These tests use the following arrangement of nodes::
o --- o --- o --- o
/ / / /
o --- o --- o --- o
/ / / /
o --- o --- o --- o
This result in two bound voronoi polygons (12 total) centered on points
5 and 6.
"""
import numpy as np
from numpy.testing im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2019, <NAME> <<EMAIL>>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE file for details.
import ... |
#!/usr/bin/env python3
#Author: <NAME>
import os
import argparse
import glob
import numpy as np
import gdal
import isce
import isceobj
from isceobj.Sensor.TOPS import createTOPSSwathSLCProduct
from mroipac.correlation.correlation import Correlation
import s1a_isce_utils as ut
def createParser():
parser = argpar... |
import argparse
import hashlib
import aergo.herapy as herapy
from ethaergo_wallet.wallet import EthAergoWallet
import ethaergo_wallet.eth_utils.erc20 as eth_u
import ethaergo_wallet.eth_to_aergo as eth_to_aergo
import ethaergo_wallet.aergo_to_eth as aergo_to_eth
from aergo_wallet.exceptions import (
TxError,
)
... |
# Copyright 2020 Uber Technologies, 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 ... |
import json
import os
import shutil
import warnings
from contextlib import contextmanager
from datetime import datetime
from typing import ContextManager
from typing import Union, List
import joblib
import matplotlib.pyplot as plt
import pandas as pd
from vivid.env import get_dataframe_backend
from vivid.json_encoder... |
from enum import Enum
class Color(Enum):
W = 0 # white
B = 1 # black
E = 2 # empty
# chess board
class Board:
def __init__(self):
self.initialize()
# get color of a piece
@staticmethod
def get_color(p):
if p == '*':
return Color.E
if p.isupper(... |
from requests_html import HTMLSession
import string
def setTopicPage(url, page):
sp_url = url.split("-")
sp_url[3] = str(page)
final_url = ""
for sp in sp_url:
final_url = final_url + sp + "-"
final_url = final_url[:-1]
return final_url
def getTopicPages(url):
... |
"""
========================================================================
NamedObject_test.py
========================================================================
Author : <NAME>
Date : Dec 23, 2017
"""
from pymtl3.dsl.errors import FieldReassignError
from pymtl3.dsl.NamedObject import NamedObject
class Chi... |
import tempfile
from urllib.error import HTTPError
import click
import pandas as pd
from loguru import logger
from .. import DATA_DIR
from ..collections import *
from .scrape import *
def _get_latest_raw_pdf(cls):
"""Given an ETL class, return the latest PDF in the data directory."""
# Get PDF paths for th... |
import collections
import gc
import random
import time
from abc import ABC, abstractmethod
import numpy as np
import torch
class WandBSummaryWriter:
def __init__(self, wandb, dummy=False):
self.wandb = wandb
self.dummy = dummy
def add_scalar(self, key, value, global_step=None):
if n... |
import layerindexlib
import argparse
import logging
import os
import subprocess
from bblayers.action import ActionPlugin
logger = logging.getLogger('bitbake-layers')
def plugin_init(plugins):
return LayerIndexPlugin()
class LayerIndexPlugin(ActionPlugin):
"""Subcommands for interacting with the layer ind... |
"""
Monte Carlo Tree Search for game play
Based on: http://mcts.ai/code/python.html. Comment from original source:
This is a very simple implementation of the UCT Monte Carlo Tree Search
algorithm in Python 3.6. The function UCT(rootstate, itermax, verbose = False)
is towards the bottom of the code. It aims to have t... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal, InvalidOperation
from cms.utils.helpers import classproperty
from shop import settings as shop_settings
from iso4217 import CURRENCIES
class AbstractMoney(Decimal):
MONEY_FORMAT = getattr(shop_settings, 'MONEY_FORMAT')
... |
'''
This uses the homemade Feather Wing doubler: one of the top boards is the
Feather Wing SSD1306 OLED and the other is a homemade board that has a
play/pause button and a potentiometer.
This micropython script displays songs that are being scrobbled to the mqtt broker
running in AWS EC2 or locally (most recently loca... |
PENDING = object()
URGENT = 0
NORMAL = 1
class Event(object):
def __init__(self, env):
self.env = env
self.callbacks = []
self._value = PENDING
def __repr__(self):
return '<%s object at 0x%x>' % (self._desc(), id(self))
def _desc(self):
return '%s()' % self.__clas... |
#!/usr/bin/env python
import time
from urllib.parse import unquote
from sanic import Blueprint, response
from owllook.fetcher.extract_novels import extract_chapters
from owllook.fetcher.function import get_time, get_netloc
from owllook.fetcher.decorators import authenticator, auth_params, response_handle
from owllook.f... |
from collections import defaultdict
import numpy as np
import functools
def extract_discrete_pl(beta, xmax, xmin = 1):
'''Return an integer number between xmin-1 and xmax extracted from a power law distribution P(x)~x^(-beta).
Input
-----
xmin: (float) (>=1)
Minimum value.
xmax: (f... |
#!/usr/bin/env python
import os
import random
import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# conda install -c conda-forge imgaug
from imgaug import augmenters as iaa
from sklearn.model_selection import train_test_split
from sklearn.utils import shu... |
# Copyright 2016-2020 HP Development Company, L.P.
# SPDX-License-Identifier: MIT
#
""" Pytests for the Hippy UVCCamera.
"""
from __future__ import division, absolute_import, print_function
import threading
import pytest
import check_camera_types
import check_device_types
import check_system_types
from hippy impo... |
from os import listdir
from os.path import isfile, join
from numpy import zeros
from math import sqrt
import timeit
# Stopwords coletadas em https://github.com/stopwords-iso/stopwords-en
path = "referencias"
stopwords = set(word.replace("\n", "") for word in open("stopwords.txt", "r", encoding="utf8"))
bagOfW... |
#!/usr/bin/env python3
"""
Picture in Picture.
Usage:
pinp <background_video> <overlay_video> <new_video> [--ratio=<ratio>] [--sync=<sync>] [--position=<position>]
Options:
-h --help Show this screen.
-r --ratio=<ratio> The ratio of width of background video to use for resizing overlay_vi... |
""" script to calculate rouge scores on individual predictions
example command:
python scripts/calc_rouge.py \
predictions.txt \
gold/test-multitarget.jsonl \
--output results.csv --workers 30
"""
from argparse import ArgumentParser
import json
import tempfile
from files2rouge import files2rouge
import os
from tqdm.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python APRS KISS Module Class Definitions."""
import logging
import kiss # pylint: disable=R0801
import aprs # pylint: disable=R0801
__author__ = '<NAME> W2GMD <<EMAIL>>' # NOQA pylint: disable=R0801
__copyright__ = 'Copyright 2017 <NAME> and Contributors' # NOQ... |
import numpy as np
import logging
import os
logger = logging.getLogger(__name__)
def linterp(m0, m1, p0, p1, p):
"""Interpolates linearly dictionaries of numpy arrays m0 and m1
m0, m1 correspond to variables p0, p1
Result is a dictionary interpolated to the variable p (p0 < p < p1)
"""
s = 1.*(p... |
'''
Other Functions
This is a collection of utilities that are used throughout the python reliability library.
Functions have been placed here as to declutter the dropdown lists of your IDE.
It is not expected that users will be using any utils directly.
Included functions are:
round_to_decimals - applies different r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities file, gathering different functions used throughout the code
@author: <NAME>
October 29th, 2017
"""
import itertools
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
# Computes dimensions of the intermediate ... |
from contextlib import contextmanager
from importlib import import_module
from logging import Logger
from pathlib import Path
from subprocess import check_call # nosec
from subprocess import check_output # nosec
from sys import executable
from time import sleep
from typing import Mapping
from typing import Optional
... |
# Copyright 2021, The TensorFlow Federated 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... |
# By <NAME> (February 2018)
# with modifications by <NAME>
#
import numpy as np
from numpy import linalg as LA
import matplotlib.pyplot as plt
import os
import csv
def get_next_sample(currentSample, initSpace):
# Trick 1: Normalize the sample (rescale to map to [0,1])
# (This is all about sampler effici... |
import logging
from celery import shared_task
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
from modeltranslation import settings as mt_settings
from django.apps import apps as django_apps
from django.db.models.functions import Length
from django.db.mode... |
# -*- coding: utf8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2018 <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, including without limitation the rights
# ... |
import json
import pandas
import sys
from bmeg.emitter import JSONEmitter
from bmeg import (Aliquot, DrugResponse, Project, Compound,
Compound_Projects_Project,
DrugResponse_Aliquot_Aliquot,
DrugResponse_Compounds_Compound)
def process_screen(screen_name, ex_df, ... |
import random
import numpy as np
import pyopenjtalk
import torch
import torch.utils.data
from transformers import AutoTokenizer
import layers
from pp_symbols import pp_symbols
from utils import load_wav_to_torch, load_filepaths_and_text
from text import text_to_sequence
class TextMelLoader(torch.utils.data.Dataset):... |
import base64
import functools
import json
from klein import Klein
from twisted.internet import defer
from paradrop.base import nexus, settings
from paradrop.base.output import out
from paradrop.core.agent.http import PDServerRequest
from paradrop.core.auth.user import User
from paradrop.core.chute.chute_storage impo... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
import datetime
import operator
import os.path
import sys
import tempfile
import unittest
from d3m import container, index, utils as d3m_utils
from d3m.metadata import pipeline as pipeline_module, problem as problem_module
from ta3ta2_api import utils, problem_pb2
TEST_PRIMITIVES_DIR = os.path.join(os.path.dirname(_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.