text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf8 -*-
"""
.. module:: lesscpy.scripts.compiler
CSS/LESSCSS run script
http://lesscss.org/#docs
Copyright (c)
See LICENSE for details
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from __future__ import print_function
import os
import sys
import glob
import copy
import argparse
sys.path.ap... |
import gym
from gym.spaces import Box, Discrete, Tuple
import numpy as np
import unittest
import ray
from ray.rllib.models import ModelCatalog, MODEL_DEFAULTS, ActionDistribution
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.tf.tf_action_dist import TFActionDistribution
from ray.rllib.mode... |
from __future__ import print_function
import datetime
from decimal import Decimal, getcontext, ROUND_HALF_DOWN
import os
import os.path
import re
import time
import numpy as np
import pandas as pd
from fxcarranza import settings
from fxcarranza.event.event import TickEvent
class PriceHandler(object):
"""
P... |
from argparse import ArgumentParser
from typing import Optional, List, Tuple
import numpy as np
from numpy.random import RandomState
from rlai.environments.mdp import MdpEnvironment
from rlai.meta import rl_text
from rlai.models import FunctionApproximationModel
from rlai.states.mdp import MdpState
from rlai.utils im... |
#This file plots the positivity rate(=true positives) of many models in a Violin PLot
import sparsechem as sc
import numpy as np
import argparse
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import math
import scipy.stats as sci
import matplotlib.gridspec as gridspec
from datetime import datetime
da... |
""" PEP 610 """
import json
import re
import urllib.parse
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Any, Dict, Iterable, Optional, Type, TypeVar, Union
T = TypeVar("T")
DIRECT_URL_METADATA_NAME = "direct_url.json"
ENV_VAR... |
from numbers import Number
import numpy as np
from mygrad.operation_base import BroadcastableOp, Operation
__all__ = ["GetItem", "SetItem"]
def _is_int_array_index(index):
""" Returns True if `index` contains any array-like integer-valued sequences
Parameters
----------
index : Tuple[A... |
from collections import namedtuple
import re
NodeType = namedtuple('NodeType', ['name', 'has_children'])
r_empty = re.compile(r"^\s*$")
r_comment = re.compile(r"^\s*(//.*$)")
r_assignment = re.compile(r"^\s*([!#%*\s]*)\s*([$\w]+)\s*(=)\s*(.+$)")
r_block = re.compile(r"^\s*([!#%*\s]*)\s*(\w+)\s*(\()\s*(.*... |
# coding: utf-8
# In[62]:
# import data:
from numpy import corrcoef, mat, shape, nonzero, logical_and
import numpy.linalg as la
def loadExtData():
# mat A
return [[4,4,0,2,2],
[4,0,0,3,3],
[4,0,0,1,1],
[1,1,1,2,0],
[2,2,2,0,0],
[1,1,1,0,0],
... |
# This script is used to calculate some statistics for the Green View Results
# Copyright(C) <NAME>, <NAME>, <NAME>, Senseable City Lab, MIT
def Read_GSVinfo_Text(GVI_Res_txt):
'''
This function is used to read the information in text files or folders
the fundtion will remove the duplicate sites and only ... |
from __future__ import unicode_literals
import os
import os.path
import unittest
from flask import Flask, Blueprint, render_template_string
from flask.ext.cdn import CDN
class DefaultsTest(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.app.testing = True
CDN(self.... |
import numpy as np
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
from scipy.sparse.linalg import eigsh
from sklearn.decomposition import PCA
def compile_resp(dat, nskip=4, npc=20, normalize = True):
istim = dat['istim']
# split stims into test and train
itest = np.zeros((i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess as sp
import argparse
import os
import sys
def e(command):
if os.environ.get('verbose', False):
sys.stderr.write(command+'\n')
sp.run(command, shell=True) #ejecuta el comado en la consola.
DOCKER='docker run --rm -w /out -v $PWD:/out ... |
# encoding: utf-8
r"""
Functions for intializing q
"""
import numpy as np
# Get locations in the aux array of pertinent quantities
from aux import kappa_index,h_hat_index
def set_riemann_init_condition(state,jump_location,q_left,q_right):
r"""Set a Riemann type initial condition"""
x = state.grid.dimension... |
#!/usr/bin/python
"""
Created on Thu Oct 27 2016
@author: colinrathbun
Script file to contain all the moving parts for a multithreaded orthogonal
set search to be used on the computational cluster or by other users.
"""
# imports
import pandas as pd
import numpy as np
from numpy import mean, sqrt, eye
from numpy.lin... |
#Pycharm için pip install PyQt5 yapılmalıdır.
import sys
from PyQt5.QtWidgets import *
from textSearchGui import TextEdit
class Regex(QWidget):
def __init__(self):
super(Regex, self).__init__()
#Arka plan renklerini, kutuların şeklini ayarlar.
self.setStyleSheet(("""background-color:
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from input_functions import get_input_fn
from models import get_model_fn as CustomRNNEstimator
import tensorflow as tf
from tensorflow.contrib.keras.python.keras.datasets import imdb
import ran... |
import sys
import numpy
import time
from py_stringmatching import JaroWinkler
from active_learning.ensemble_learner import EnsembleLearner
from active_learning.iterative_active_learner import IterativeActiveLearningAlgorithm
from active_learning.metrics import Metrics
from active_learning.multiple_metrics_plotter i... |
import unittest
from fluent.runtime import FluentBundle, FluentResource
from fluent.runtime.errors import FluentFormatError, FluentReferenceError
from ..utils import dedent_ftl
class TestParameterizedTerms(unittest.TestCase):
def setUp(self):
self.bundle = FluentBundle(['en-US'], use_isolating=False)
... |
# Certification Project by <NAME>
#
# ## Part 1 - Data Exploration, Feature Selection
# In this module we use Spark in conjunction with some popular Python libraries
# to explore data and select features we will use in the next module which is model training,
# scoring and evaluation.
# ## Setup
# Import some useful ... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
"""
Copyright (c) 2019 <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
to use, copy, modify, merge, publish, distribute, sublic... |
import torch
import numpy as np
import utils.utils_geom
import utils.utils_basic
np.set_printoptions(suppress=True, precision=6, threshold=2000)
def merge_rt_py(r, t):
# r is 3 x 3
# t is 3 or maybe 3 x 1
t = np.reshape(t, [3, 1])
rt = np.concatenate((r,t), axis=1)
# rt is 3 x 4
br = np.reshape... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : utils.py
@Time : 2020/10/26 17:29
@Author: Tao.Xu
@Email : <EMAIL>
"""
import os
import re
import subprocess
import inspect
from storagetest.libs.log import log
from storagetest.libs.retry import retry_call
"""utils"""
logger = log.get_logger()
def subproces... |
from snsql.reader.base import Reader
from snsql.sql.reader.engine import Engine
import importlib
from snsql.sql.reader.probe import Probe
class SqlReader(Reader):
@classmethod
def get_reader_class(cls, engine):
prefix = ""
for eng in Engine.known_engines:
if str(eng).lower() == eng... |
""" Defines the backend connection class for PostgreSQL databases. """
import logging
import orb
import re
import threading
from projex.text import nativestring as nstr
from ..sqlconnection import SQLConnection
from ..sqlstatement import SQLStatement
log = logging.getLogger(__name__)
try:
import sqlite3 as sql... |
import torch
from torch.utils.data import Dataset
# this class transforms data in required training format and inference for text and tokens
class SelectionDataset(Dataset):
def __init__(self, contexts, candidates, context_transform, candidate_transform, labels=None, mode='train'):
self.context_transform ... |
import torch
from torch2trt.torch2trt import *
from torch2trt.module_test import add_module_test
from .size import IntWarper
@tensorrt_converter('torch.nn.functional.interpolate')
def convert_interpolate(ctx):
input = ctx.method_args[0]
try:
scale_factor = get_arg(ctx, 'scale_factor', pos=2, default=... |
"""
Basic wheel tests.
"""
import os
import pkg_resources
import json
import sys
from pkg_resources import resource_filename
import wheel.util
import wheel.tool
from wheel import egg2wheel
from wheel.install import WheelFile
from zipfile import ZipFile
from shutil import rmtree
test_distributions = ("complex-dist"... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
def PrintTFGrid(G, truetext = 'T', falsetext = 'F'):
"""
```True``` 또는 ```False``` 로 이루어진 행렬 값을 받아 쉘에 정사각형으로 출력하는 함수
Parameters
----------
G : numpy.ndarray ... |
import discord
from discord.ext import commands
import wikipedia, asyncio, textwrap, aiohttp
import googletrans
from unit_convert import UnitConvert
def to_emoji(c):
base = 0x1f1e6
return chr(base + c)
class utilityCog(commands.Cog):
"""Utility commands"""
def __init__(self, bot):
self.bot ... |
# Copyright (c) 2017 Facebook, Inc. All rights reserved.
# BSD 3-Clause License
#
# Script adapted from: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py
# ==============================================================================
# imports
import os
im... |
import numpy as np
from .utils import calc_distances
from scipy.spatial.distance import squareform
class DistanceFeature(object):
"""DistanceFeature
feature is \sum_{i<j} \|x_i-x_j\|^{-n}
"""
def __init__(self, n):
self.n = int(n)
def __call__(self, x, d=None):
"""
E... |
from pathlib import Path
from rerssoconnector import RERSSOConnector
from utils import CorpusUtils
import re
# Reads the alphabet mapping from a file
def _read_alphabet_mapping(mapping_path):
alphabet_mapping = {}
try:
with Path(mapping_path).open('r') as file:
for line in file.readlines():... |
#!/usr/bin/python2.4
#
# Copyright 2008 Google 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 o... |
# coding=utf-8
# Copyright 2021 The SLOE Logistic 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... |
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets as sk_data
import sklearn.neighbors as neighbors
import sys
from sklearn.cluster import KMeans
np.set_printoptions(suppress=True, precision=4)
import sklearn.neighbors as neighbors
def iqr_threshold_method(scores, margin):
q1 = np.percent... |
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2019, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... |
"""
This module can parse a Delphi Form (dfm) file.
The main is used in experimenting (to find which files fail
to parse, and where), but isn't useful for anything else.
"""
__version__ = "1.0"
__author__ = "<NAME>' Griffith <pythondev - dang at lazytwinacres . net>"
from pyparsing import (
Literal,
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, 9T9IT and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, enqueue
from frappe.model.document import Document
from frappe.model.naming import make_autoname
from frappe.utils.data impo... |
import numpy as np
import os
from pickle import dump
import string
from tqdm import tqdm
from utils.model import CNNModel
from keras.preprocessing.image import load_img, img_to_array
from datetime import datetime as dt
# Utility function for pretty printing
def mytime(with_date=False):
_str = ''
if with_date:
_str... |
#!/bin/python3
from aws_helpers.s3 import S3Bucket, S3Client
import argparse
from boto3.session import Session
import json
import os
import subprocess
BUCKET_NAME = 'ellen-zehra.me'
BUCKET_REGION = 'eu-west-1'
def create_parser():
"""Create parser object used for defining all options for locust-nest.
Return... |
import random
import datetime
from collections import Counter
from functools import partialmethod
from mesa import Agent, Model
from mesa.time import BaseScheduler
from mesa.datacollection import DataCollector
from utils.metrics import *
from utils.agents import *
class Reality(Agent):
def __init__(self, unique... |
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
os.chdir("D:/github/Paper/YOLO")
from pascal import pascal_voc
def add_variable_summary(tf_variable, summary_name):
with tf.name_scope(summary_name + '_summary'):
mean = tf.reduce_mean(tf_variable)
tf.su... |
"""
Репозитории проекта
===================
"""
from __future__ import annotations
import asyncio
import json
from dataclasses import dataclass
from operator import attrgetter
from pathlib import Path
from typing import List, TYPE_CHECKING
from memrise.core.modules.actions.base import Actions
from memrise.core.modul... |
import boto3
import hashlib
import logging
import math
import os
import xxhash
from botocore.exceptions import ClientError
from itertools import repeat
from multiprocessing import Manager, Pool, Queue
from random import randrange
from supersync.metadatastore import MetaDataStore
from supersync.s3wrapper import S3Wrapp... |
import traceback
from typing import Optional, List, Dict
from src.types.condition_var_pair import ConditionVarPair
from src.types.spend_bundle import SpendBundle
from src.types.coin_record import CoinRecord
from src.types.name_puzzle_condition import NPC
from src.types.blockchain_format.program import SerializedProgra... |
#import libraries
from pyramid.view import (
view_config,
view_defaults
)
import logging
from jaeger_client import Config
from gpiozero import OutputDevice, Servo, PWMOutputDevice, LED
from gpiozero.pins.pigpio import PiGPIOFactory
from os import getenv
# Define the factories
factory = PiGPIOFactory(host='... |
# Copyright 2021 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, ... |
#!/usr/bin/env python3
import argparse
import datetime
import glob
import json
import os.path
import pathlib
import re
import sqlite3
import subprocess
import sys
import zipfile
# Paths to various files
approot = os.path.expanduser("~/Library/Group Containers/9K33E3U3T4.net.shinyfrog.bear")
dbpath = os.path.join(appro... |
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
from .reference_points import create_references
from .clust_color import assign_colors
from .misc import process_result_list
def parameters(results, ax=None, free_indices_only=True, lb=None, ub=None,
size=None,... |
import datetime
try:
import psycopg2
except ImportError:
# Fall back to psycopg2cffi
from psycopg2cffi import compat
compat.register()
from sqlalchemy import Column, Integer, String, BigInteger, DateTime, ForeignKey, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.diale... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Building damage inference script."""
import argparse
import os
import numpy as np
import rasterio
import rasterio.mask
import rasterio.warp
import torch.nn.functional as F
import torch
from models import SiamUnet
from tor... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
import torch
from fairseq import metrics, utils
from fairseq.criterions import FairseqCr... |
"""
Test unit for the fol.py module
"""
from unittest import TestCase
from srl_nlp.analysers.boxer import BoxerLocalAPI, BoxerWebAPI
from srl_nlp.logical_representation.fol import FOL
# Local API
from nose.tools import assert_equals
class TestBoxerLocalAPI(TestCase):
def test_parse_sentence_to_fol(self):
... |
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
DEVICE = 'cuda'
import copy
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=True):
"""
given a sklearn confusion matrix (cm), make a nice p... |
import logging
from typing import Tuple, Dict
from common.model.net import Net
from common.util.constants import TIMETABLE_HOUR_TO_CONSIDER, TIMETABLE_SECTION_HEADER, TIMETABLE_INDEX_HEADER, \
TIMETABLE_DEPARTURE_HEADER, TIMETABLE_JOURNEY_NUMBER_HEADER, TIMETABLE_LINE_NAME_HEADER, \
TIMETABLE_LINE_DIRECTION_HE... |
'''Train a simple deep CNN on the CIFAR10 small images dataset.
GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatx=float32 python cifar10_cnn.py
It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs.
(it's s... |
import pytest
import random
import string
import session3
import os
import inspect
import re
import math
README_CONTENT_CHECK_FOR = [
'int',
'encoded_from_base10',
'digit_map',
'ValueError',
'math',
'isclose',
'absolute',
'relative',
'tolerance',
'bin(',
'hex(',
'round',... |
""" An example showing how to use DEAP optimization (http://pythonhosted.org/deap/).
DEAP can be combined with *pypet* to keep track of all the data and the full trajectory
of points created by a genetic algorithm.
Note that *pypet* adds quite some overhead to the optimization algorithm.
Using *pypet* in combination ... |
"""Encrypter utility functions"""
import logging
# cf. https://gist.github.com/YannBouyeron/c5367809904a682767669b6a51f03aa3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
import nvp.core.utils as utl
logger = lo... |
#!/usr/bin/env python3
from __future__ import annotations
import asyncio
import json
import sys
import enum
import random
LEFT = b'Left\n'
RIGHT = b'Right\n'
FORWARD = b'Forward\n'
class Direction(enum.Enum):
"""A cardinal direction."""
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
def right(self... |
# pretty printing for stage 2.
# put "source /path/to/stage2_gdb_pretty_printers.py" in ~/.gdbinit to load it automatically.
import re
import gdb.printing
class TypePrinter:
no_payload_count = 4096
# Keep in sync with src/type.zig
# Types which have no payload do not need to be entered here.
payload_t... |
from django.contrib.admin.utils import NestedObjects
from django.core.exceptions import FieldDoesNotExist
from django.db import models, router, transaction
from django.db.models import Q
from django.db.models.sql import DeleteQuery
from django.db.models.sql.where import WhereNode
from django.utils.translation import ge... |
from awrams.utils.messaging.robust import PollingChild, SharedMemClient, Chunk, to_chunks
import netCDF4 as nc
#from awra import db_open_with
#+++ Need to use NCD (as opposed to h5py) when writing to LSD compressed datasets
db_opener = nc.Dataset#db_open_with()
FILL_VALUE = -999.
class MultifileChunkWriter(PollingCh... |
import os
import sys
import time
import json
import logging
import threading
import multiprocessing as mp
from ..utils import save, load, AutoTorchEarlyStop
import distributed
from distributed import Queue, Variable
from distributed.comm.core import CommClosedError
logger = logging.getLogger(__name__)
__all__ = ['Dis... |
import sys
from dataclasses import dataclass
import random
import time
from functools import partial
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
from path_planning.tree import Node, Pose
from path_planning.obstacle import Obstacle
from path_planning import pg_utils
@dataclass
cl... |
# -*- coding: utf-8 -*-
# Written by <NAME> (<EMAIL>)
import sys
import os.path as osp
from skimage import transform
import numpy as np
import math
import time
import torch
from PIL import Image
def increase_bbox(bbox, scale, image_size, type='xyhw'):
"""Increase the size of the bounding box
Input:
bb... |
import numpy as np
import cv2
import cv2.aruco as aruco
import math
# import matplotlib.pyplot as plt
import os
import time
import pprint
'''
Use this script to receive live feed and find aruco patterns on it.
Requires a callibrated camera matrix and distortion vector.
DEPS: RedmiNote9Pro.nz: a file from which to loa... |
################################################################################
# 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... |
import math
import torch
import torch.nn as nn
from collections import OrderedDict
from torchvision.models.resnet import BasicBlock
from .base import Backbone
class SpatialCrossMapLRN(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, k=1, ACROSS_CHANNELS=True):
super(SpatialCrossMapLRN, s... |
# -*- coding: utf-8 -*-
import crypton.http
from django.utils.translation import ugettext
from django.template import Context, loader
from django.core.cache import get_cache
import logging
import main.models
import json
from crypton import settings
from crypton import my_messages
import hashlib
import random
# def ... |
'''
Models for associations
'''
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class AssociationKindManager(models.Manager):
def define(self, name, left, right):
left_type = ContentType.objects.get_f... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. 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
#
#... |
import os
import re
import logging
import binascii
import hashlib
import json
import datetime
import decimal
from repoze.lru import lru_cache
from pycoin import encoding
from counterblock.lib import config, util
D = decimal.Decimal
decimal.getcontext().prec = 8
logger = logging.getLogger(__name__)
def round_out(num... |
# 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 agreed to in... |
import os
import nipype.interfaces.utility as util
from CPAC.utils.interfaces.function import Function
from CPAC.pipeline import nipype_pipeline_engine as pe
def run_surface(post_freesurfer_folder,
freesurfer_folder,
subject,
t1w_restore_image,
atlas_spa... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
"""
Maintain database models regarding various regression tests, categories, storing output of tests.
List of models corresponding to mysql tables:
[
'Category' => 'category',
'RegressionTest' => 'regression_test',
'RegressionTestOutput' => 'regression_test_output'
]
"""
from typing im... |
import numpy as np
import cv2
class Net(object):
def __init__(self, model_path, use_cpu=False, prefix='prefix',
pad=52, max_mp=5, gpu_fraction=None):
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
self.pad = pad
self.max_megapixels = max_mp if max_mp is... |
#!/usr/bin/env python
# coding: utf-8
"""
MicaSense Image Processing Utilities
Copyright 2017 MicaSense, Inc.
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 withou... |
# Copyright 2020 The Cirq Developers
#
# 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# -*- coding: utf-8 -*-
"""Core module."""
import json
import shutil
import subprocess
from pathlib import Path
import ccxt
_CHROME_LIKE_BROWSERS = ['brave-browser', 'chromium', 'chromium-browser', 'google-chrome', 'chrome']
_BROWSERS = ['firefox', 'firefox-esr', 'mozilla', 'epiphany', 'konqueror', 'safari', 'opera',... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from tipi import tipi as _tipi
tipi = lambda s: _tipi(s, lang='en')
def test_ascii_plain():
assert tipi('ascii') == 'ascii'
def test_unicode_html():
assert tipi('řeřicha') == 'řeřicha'
s = (
'<p>Její číslo je <strong class="tel... |
import pdb
import numpy as np
from abc import abstractmethod
from rl.tools.online_learners.base_algorithms import MirrorDescent
from rl.tools.utils.mvavg import ExpMvAvg
from rl.tools.online_learners.prox import MvpQuad
class SecondOrderUpdate(MirrorDescent):
"""
The decision is computed
h_new = h - s... |
from discord.ext import commands
import asyncio
import traceback
import discord
import inspect
import textwrap
import time
import os
from datetime import datetime
from contextlib import redirect_stdout
import io
from geeksbot.imports.utils import run_command, format_output, Paginator, Book
import logging
repl_log = lo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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 ... |
"""
Functions for calculating geometry.
"""
from arcade.sprite import Sprite
from arcade.sprite_list import SpriteList
from typing import List
from arcade.arcade_types import PointList
from arcade.arcade_types import Point
PRECISION = 2
def are_polygons_intersecting(poly_a: PointList,
... |
# ************************************************************
# Copyright (c) 2020, <NAME> - All Rights Reserved.
# You may use, distribute and modify this code under the
# terms of the BSD-3 license. You should have received a copy
# of the BSD-3 license with this file.
# If not, visit: https://opensource.org/license... |
import pandas as pd
import numpy as np
from subprocess import CalledProcessError, run
import sys, os
from os import path
from tqdm import tqdm
from glob import glob
from joblib import Parallel, delayed
import eval_gradient as eg
import argparse, itertools
import uuid, json
# grab next adjacent
def split_adj(dbytes):
... |
import copy
import logging
import sys
import time
import os
import six
import pickle
import json
import numpy as np
import pdb
import re
import io
import random
from collections import Counter
from nltk.util import ngrams
import torch
import torch.utils.data as Data
from tqdm import tqdm
from data.dataset import *
f... |
import dataset
import logging
from lxml import etree
from pprint import pprint
from datetime import datetime
from monnet.util import engine, walk_path
from monnet.experts.util import exp_group, exp_sub_group, exp_group_type
from monnet.experts.util import exp_group_task, exp_group_associated_dg
from monnet.experts.uti... |
# 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
from ... import _utilities, _tables
__a... |
''' Copyright 2021 <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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... |
""" Defines the vocabulary object and extraction procedure used by all of IDGAN's subsystems.
Some of the code has been adopted from the pyTorch NLP tutorial and adjusted as needed. """
import re
import string
import pandas as pd
class Indexer(object):
""" Translates words to their respective indices and vice ve... |
import os
import sys
import glob
import toml
from importlib import import_module
import re
import math
import colorsys
import webcolors
from pathlib import Path
from robosat_pink.tiles import tile_pixel_to_location, tiles_to_geojson
#
# Import module
#
def load_module(module):
module = import_module(module)
... |
import json
from csv import DictReader as cdr
"""
# Data processing steps
This script was used to process a few xlsx files to look at expediture data
based on income and region
- source: http://www.bls.gov/cex/
- files under Region of residence by income before taxes:
- xregnmw.xlsx
- xregnne.xlsx
- xregns.xls... |
# <NAME> 6/2/2022 - ShapiroWilk normality test
# Based on https://scistatcalc.blogspot.com/2013/10/shapiro-wilk-test-testing-for-normality.html
from typing import List, Tuple
import math
def _norm_dist_cdf(x: float, mean: float, stddev:float) -> float:
""" Fast, accurate way to calculate cdf"""
return... |
"""
Start an IPython Qt console connected to the python session running in Excel.
This doesn't work with an IPython notebook as it's not possible to connect
a notebook to an existing kernel, the notebook app always creates its own.
This version is intended to work with IPython versions 6.x only.
This example require... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
"""
Testing SsdBuffer and SsdTensorHandle modules.
"""
import tempfile
import numpy as np
import pytest
import torch
import fairscale.exper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.