text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: jsuter
Project: STIMPY - Sentence Transformative Infernece Mapping for Python
<NAME>, 2019
---
EVALUATE_dev_samples.py
- Load development samples
- Evaluate samples
- Print performance results
"""
# Import statements
import copy
import sys
import time
impor... |
import gzip
import os
import shutil
import tarfile
import traceback
from concurrent.futures.thread import ThreadPoolExecutor
from pprint import pprint
from random import shuffle
import requests
from tqdm import tqdm
def download_data(url="https://object.pouta.csc.fi/OPUS-100/v1.0/opus-100-corpus-v1.0.tar.gz",
... |
"""
python train_PA-100K_hiarchical.py -m hiarBayesGoogLeNet -b 64 -g 0 -c 26
python train_PA-100K_hiarchical.py -m hiarGoogLeNet -b 64 -g 0 -c 26
"""
from network.hiarGoogLenetSPP import hiarGoogLeNetSPP
from network.hiarGoogLenetWAM import hiarGoogLeNetWAM
from network.hiarGoogLenet import hiarGoogLeNet
from network.... |
import asyncio
import typing as t
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
import discord
from discord.ext import commands
from bot import ModmailBot
from core import checks
from core.models import PermissionLevel, getLogger
from core.thread import Thread
from .utils i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 12:28:37 2020
@author: lilianschuster
some helper functions to minimize the bias, optimise std_quot and tos
compute performance statistics
"""
import scipy
import matplotlib.pyplot as plt
import numpy as np
from oggm import entity_task
from oggm... |
#!/usr/bin/env python
# encoding: utf-8
class Stack(object):
"""Docstring for Stack """
def __init__(self):
"""@todo: to be defined1 """
self.items = []
def pushFromList(self, list):
"""Push the list in the stack
:param list: a list
"""
for i in list[::-1... |
# -*- coding: utf-8 -*-
"""
@file
@brief This programs solves `Einstein's riddle <http://en.wikipedia.org/wiki/Zebra_Puzzle>`_ ou en
Français `Intégramme <http://fr.wikipedia.org/wiki/Int%C3%A9gramme>`_. The algorithm is based
on logic and its `clause <http://en.wikipedia.org/wiki/Clause_(logic)>`_.
"""
import copy
#... |
import re
import tkinter
# Uncomment when cx_Freeze'ing.
# from lxml import etree
# from xml.etree import ElementTree as etree
# Uncomment when used as is.
try:
from lxml import etree
except ImportError:
# See: http://lxml.de/compatibility.html
from xml.etree import ElementTree as etree
import s2s_runtime_s... |
"""
webpack is a module bundler for modern JavaScript applications.
Options:
* mode : str, None
: Enable production optimizations or development hints.
: values: development, production, none
: If not set it'd be inferred from environment variables.
* config_file : ... |
from enum import Enum, unique
from random import randint
from math import sqrt
import pygame
import tkinter
import tkinter.messagebox
def screen():
flag = True
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', "Hello World") if flag else (
'Blue',... |
from hailtop.utils import (partition, url_basename, url_join, url_scheme,
url_and_params, parse_docker_image_reference, grouped)
from hailtop.utils.utils import digits_needed, unzip, filter_none, flatten
def test_partition_zero_empty():
assert list(partition(0, [])) == []
def test_par... |
"""
CDMS cache management and file movement objects
"""
import cdurllib
import urllib.parse
import tempfile
import os
import time
import cdmsobj
import sys
import errno
import shelve
from .error import CDMSError
MethodNotImplemented = "Method not yet implemented"
SchemeNotSupported = "Scheme not supported: "
LockError ... |
#!python3
"""
A wallet that uses MDP to make optimal (?) payment decisions.
Alice is the decision-maker. Each time, with probability p she has to send A coins to Bob.
Then her wallet has to decide between:
* Sending directly through the blockchain and paying the mining fee;
* Sending through the channel (if her balan... |
import torch
from torchvision import datasets, transforms
import pathlib
import os
import argparse
import models
# Train the given net on the data
def train(args, net, data, device, optimizer, loss_fn):
sched = torch.optim.lr_scheduler.ExponentialLR(optimizer, .985, last_epoch=-1)
net.train()
for epoch in... |
"""Simple file encoding & image format converter"""
if __name__ == "__main__":
from PySide2.QtCore import QCoreApplication
QCoreApplication.setLibraryPaths([r"E:\ProgramData\Anaconda3\envs\ezworkera\Lib\site-packages\PySide2\plugins"]) # Write your QT_PLUGIN_PATH
import sys
import os
import chardet
from PIL im... |
import json
import pytest
from pathlib import Path
from django.conf import settings
from snoop.data import models, filesystem
from snoop.data.analyzers import archives
from snoop.data.utils import time_from_unix
pytestmark = [pytest.mark.django_db]
STOCK_PHOTO = {
'blob_pk': 'f7281c8a9cc404816f019382bd121c5fff28e... |
"""
Script to evaluate importance of the input variables.
It relies on adding random normal noise to the input variables and evaluating
the model performance [1]_. The idea is that if large degradation of
performance is occurred when noise is added to a given input then that input
was important.
References
----------... |
from matplotlib import pyplot as plt
import pandas as pd
from scipy.interpolate import BSpline, make_interp_spline
import numpy as np
import config as cfg
import os
import seaborn as sns
from pathlib import Path
def smooth(x, y, num_of_datapoints):
'''
Takes x and y values and a number of datapoints the data s... |
"""Connect to a Samsung printer with SyncThru service."""
import asyncio
from enum import Enum
from typing import Any, Dict, Optional, cast
import aiohttp
import demjson3
from .htmlparsers import ENDPOINT_HTML_PARSERS
ENDPOINT_API = "/sws/app/information/home/home.json"
class ConnectionMode(Enum):
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.optim as optim
import common.images
import common.metrics
import mode... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The module responsible for getting the code that this extension displays."""
import collections
import functools
import inspect
import os
import bs4
import six
from six.moves import urllib
from . import error_classes
from . import helper
_OBJ_TAG = "obj"
APPLICATION... |
from __future__ import division, generators, print_function
import sys
import random
import macarico
from collections import deque
from macarico.data.vocabulary import EOS
class Seq2Seq(macarico.Env):
LENGTH_FACTOR = 4
def __init__(self, example):
macarico.Env.__init__(self, example.n_labels, example... |
# ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... |
import argparse
import json
import os
import pdb
import sys
import time
import string
import torch
from torch.utils.data import DataLoader
sys.path.append('.')
from config import special_toks, train_conf
from dataset import FastDataset
from models import BlindStatelessLSTM, MultiAttentiveTransformer
from tools.simmc... |
"""
Code illustration: 9.06
Weather reporter
Tkinter GUI Application Development Blueprints
"""
import sys
import json
import datetime
from tkinter import Tk, Canvas, Entry, Button, Frame, Label, StringVar, ALL
from tkinter import ttk
from tkinter import messagebox
import urllib.request
import urllib.parse
class ... |
import os
import yaml
import argparse
from torch import nn
import torch
from collections import OrderedDict
import pytorch_lightning as pl
import torch.nn.functional as F
from pytorch_lightning.logging import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from torch.utils.data ... |
"""
Utilities to make crumbs
"""
import fnmatch
import itertools
import operator
import os
import re
from collections import Mapping, OrderedDict
from functools import partial, reduce
from typing import Any, Iterator, List, Callable, Tuple
from hansel._utils import _check_is_subset, _is_crumb_arg
CrumbArgsSequence = ... |
from mathutils import Vector, Quaternion
from collections import Counter
from ...tools import xml as Xml
from .utils import find_bone_by_tag
from .Channel import ChannelConst, ChannelStaticFloat, ChannelQuantizeFloat, ChannelIndirectQuantizeFloat, ChannelCachedQuaternion1, ChannelStaticVector, ChannelStaticQuaternion
... |
# =============================================================================
# This module defines some functions in order to create a fuzzy control system.
# =============================================================================
# =============================================================================... |
from restclients.pws import PWS
from restclients.sws import encode_section_label
from restclients.dao import SWS_DAO
from restclients.exceptions import DataFailureException
from restclients.models.sws import GradeRoster, GradeRosterItem
from restclients.models.sws import GradeSubmissionDelegate
from lxml import etree
i... |
from __future__ import print_function
import json
import os.path
import pickle
import queue
import socket
import sys
import threading
import time
import uuid
from threading import Thread
import socks # pip install PySocks
from apiclient import errors
from google.auth.transport.requests import Request
from google.oau... |
from exceptions.exceptions import AmbiguousNGSIIdError
from translators.base_translator import BaseTranslator
from translators.benchmark import benchmark
from translators.crate import NGSI_TEXT
from conftest import crate_translator as translator
from utils.common import *
import statistics
def test_db_version(transla... |
#!/usr/bin/env python3
import requests
import json
import sys
#get the secrets from your Google Cloud project, use the Oauth2 Playground for your refresh token
client_id=sys.argv[1]
client_secret=sys.argv[2]
refresh_token=sys.argv[3]
credentials=sys.argv[4]
def get_list_from_file(filename):
try:
# open and... |
from typing import Any, Union, ClassVar, NoReturn, Optional
from pathlib import Path
from urllib.parse import urlparse
import configparser
import attr
from omnipath.constants import License
from omnipath._core.cache._cache import Cache, FileCache, NoopCache, MemoryCache
from omnipath.constants._pkg_constants import D... |
import requests
import urllib
import inspect
import pprint
import datetime
hn_url = "http://hn.algolia.com/api/v1/"
item_url = "{}items/".format(hn_url)
user_url = "{}users/".format(hn_url)
search_url = "{}search".format(hn_url)
date_url = "{}_by_date".format(search_url)
pp = pprint.PrettyPrinter(indent=4)
max_hits_... |
from abc import ABCMeta, abstractmethod
import numpy as np
from joblib import Parallel, delayed
from sklearn.base import is_classifier
from sklearn.utils import check_X_y, check_scalar, check_random_state
from sklearn.ensemble import BaseEnsemble
from sklearn.utils.validation import check_is_fitted
from .base import ... |
import tensorflow as tf
import numpy as np
import tensorflow_addons as tfa
import heapq
def accuracy(predictions, values):
correct = 0.0
for prediction, value in zip(predictions, values):
if prediction - value == 0.0:
correct += 1
return correct / len(predictions)
def create_FFN(l... |
#!/usr/bin/env python3
from sp_utils import *
import sys
import os
import time
import spotipy
import datetime
import traceback
import mysql.connector
sys.path.append('../')
# Functions
# Gets the current time
def get_curr_time():
t = datetime.datetime.now()
return t.strftime("%Y-%m-%d-%X")
# Prints inform... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import os
import logging
from typing import Dict
from crhelper import CfnResource
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
personalize = boto3.client('personalize')
appcon... |
from __future__ import print_function
from __future__ import division
from . import _C
from ..datascience import statistics as fstats
from . import colors as cc
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import math
import pandas as pd
DPI = _C.DPI
PERCENTILE = 95
######... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Spotify AB
#
# 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 websockets, asyncio, json
from threading import Thread
from abc import ABC, abstractmethod
ADDRESS = '127.0.0.1'
PORT = 4202
class OscillatorClient:
def __init__(self, *,
server_address=ADDRESS,
server_port=PORT):
self.uri = f'ws://{server_address}:{server_po... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 9 00:38:54 2021
@author: alankar
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.animation as animation
import sys
import h5py
from scipy.interpolate import interp1d
mp = 1.67e-24
p... |
import pandas as pd
import numpy as np
import logging
import pygame
from time import sleep
import pygameMenu
import copy
from tictacAI.minimax import MiniMax
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(message)s',
handlers=[logging.FileHandler("log.log"),
... |
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from functools import parti... |
from datetime import datetime, timedelta
import gzip
import json
import logging
from queue import Queue, Empty
import random
import re
import struct
import time
from coapthon.messages.message import Message
from coapthon import defines
from coapthon.client.coap import CoAP
from coapthon.messages.request import Request... |
# Android Device Testing Framework ("dtf")
# Copyright 2013-2016 <NAME> (@jake_valletta)
#
# 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
#
# Unl... |
import re
import json
from itertools import count
import datetime
from collections import defaultdict
from rdflib import Graph, Namespace, OWL, Literal, URIRef, BNode, XSD, RDFS, RDF
from rdfalchemy import rdfSubject, rdfSingle, rdfMultiple
bio = Namespace("http://purl.org/vocab/bio/0.1/")
schema = Namespace('http://... |
"""
Copyright 2020 InfAI (CC SES)
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... |
from vitruncate import GT
from numpy import *
import matplotlib
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as patches
pyplot.rc('font', size=16) #set defaults so that the plots are readable
pyplot.rc('axes', titlesize=16)
pyplot.rc('axes', labelsize=16)
pyplot.rc('x... |
import tensorflow as tf
import tensorflow.keras.backend as K
from .layers import *
# The following losses assume the input:
# y = [ quaternion, translation, shape3D ]
# y = [ q0,q1,q2,q3, t0,t1,t2, sx0,sy0,sz0,...,sxN,syN,szN ]
# y.shape = [ 1, 4 + 3 + 3*Points3D]
#
# multiview_reprojection_loss: Require rando... |
#!/usr/bin/env python
"""
This module contains the core Composable subclasses that we made to handle SchemaTables and Fields.
SchemaTables will always be unquoted and thus directly extend Composable while Fields will always be quoted
and thus
"""
from typing import Union, List, Tuple, Dict, Any
from psycopg2 import s... |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.vision.models import vgg16
from ppcd.models.layers import CAM, SAM
class Vgg16Base(nn.Layer):
# Vgg16 feature extraction backbone
def __init__(self, in_channels=3):
super(Vgg16Base, self).__init__()
features = vg... |
import pytz
import pandas as pd
from pandas.testing import assert_index_equal
from pandas.tseries.offsets import CustomBusinessDay
from pandas_market_calendars.exchange_calendar_cme_globex_energy_and_metals import CMEGlobexEnergyAndMetalsExchangeCalendar
cal = CMEGlobexEnergyAndMetalsExchangeCalendar()
def test_t... |
#!/usr/bin/env python3
import subprocess
import os
import sys
import winreg
import argparse
import typing
import enum
import shutil
class FoundStudio:
def __init__(self, name: str, vcvars: str, root:str):
self.name = name
self.root = root
self.vcvars = vcvars
def __str__(self):
... |
# coding=utf-8
# Copyright (c) 2015-2017, UT-BATTELLE, LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list... |
# Copyright 2011 <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 writing, softw... |
import numpy as np
import os
import pickle
import ra
import fft
import argparse
import cv2
from scipy.misc import imresize
from cgls import cgls
from filterplot import filterplot
from gaussian2d import gaussian2d
from hashkey import hashkey
from math import floor
from matplotlib import pyplot as plt
from scipy import i... |
import time
import random
import argparse
import json
import os
import sys
import cv2
import warnings
import numpy as np
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
warnings.filterwarnings('ignore')
from tqdm import tqdm
from thop import profi... |
import os
import gc
import time
import torch
import random
import argparse
import numpy as np
import pandas as pd
from glob import glob
from trains import *
from config import *
from utils.log import *
from utils.metricsTop import *
from utils.functions import *
from utils.gpu_memory_log import gpu_memory_log
from mod... |
from flask import abort, escape, Flask, render_template, request, session
from functools import wraps
import json
import sys
import uuid
app = Flask(__name__, static_folder="static")
# Decorators
def requires_admin(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "team_id" not in session or... |
"""
1896. Minimum Cost to Change the Final Value of Expression
Hard
You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.
For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|... |
import cv2 as cv
import numpy as np
import sys
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
video = cv.VideoCapture('ptest.avi')
sys.setrecursionlimit(2000)
backgroundSubtractor = cv.createBackgroundSubtractorMOG2(varThreshold=100, detectShadows = True)
#Initializ... |
"""
Read from some formats and write to some formats.
Author: <NAME>
"""
import os
import subprocess
import traceback
from pkg_resources import resource_filename
from typing import List
import pretty_midi
from sinethesizer.io import (
convert_events_to_timeline,
convert_tsv_to_events,
create_instruments... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
class SearchableKernelMaker:
def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor,
... |
import datetime
import hashlib
import textwrap
import uuid
import itertools
import json
import logging
import pathlib
import pprintpp
import time
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing impor... |
"""
Common basis set manipulations
This module contains functions for uncontracting and merging basis set
data, as well as some other small functions.
"""
import copy
def merge_element_data(dest, sources, use_copy=True):
"""
Merges the basis set data for an element from multiple sources
into dest.
... |
from datetime import datetime
from decimal import Decimal
import logging.config
from numpy import array, min, max, percentile
import os
from pandas import DataFrame
from perfsize.perfsize import Condition, Config, gte, lt, Result, ResultManager, Run
from pprint import pprint
from typing import Dict, List, Optional, Uni... |
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
from array import array
from math import exp, log, ceil
import logging
from sys import maxsize
import os
#from eulerlib.prime_numbers import is_prime
#from sympy.ntheory import legendre_symbol, is_quad_residue, quadratic_residues
#from gmpy2 import divm, i... |
from types import MethodType
import os
import numpy as np
import cv2
from pointsmap import invertTransform, combineTransforms
from h5dataloader.common.structure import *
from h5dataloader.common.create_funcs import NORMALIZE_INF
from h5dataloader.pytorch import HDF5Dataset
from h5dataloader.pytorch.structure import CON... |
import gc
import six
import numpy as np
from abc import ABCMeta, abstractmethod
from .base import BaseEstimator
class BaseSVM(six.with_metaclass(ABCMeta, BaseEstimator)):
def __init__(self, kernel='linear', degree=3, C=1.0, epsilon=1e-3, max_iter=100):
self.max_iter = max_iter
self._kernel = kern... |
# -*- coding: utf8 -*-
import sys
from traceback import format_exception
from tuttle.error import TuttleError
from tuttle.report.dot_repport import create_dot_report
from tuttle.report.html_repport import create_html_report
from pickle import dump, load
from tuttle.workflow_runner import WorkflowRunner, TuttleEnv
from... |
import _nx
import warnings
from .utils import bit, cached_property
AUTO_PLAYER_1_ID = 10
def refresh_inputs():
"""Refreshes inputs.
Should normally be called at least once
within every iteration of your main loop.
"""
_nx.hid_scan_input()
def _determine_controller_type(player):
# TODO det... |
from functools import wraps
import importlib
import logging
import queue
import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from core.config import cfg
from model.pcl.pcl import PCL
from model.pcl.oicr_momentum import O... |
#!/usr/bin/env python
import glob
import multiprocessing as mp
from multiprocessing import shared_memory
import argparse
import numpy as np
import xarray as xr
import os
import time
pool = None
data_vars = None
def load_file(file_name,var_mems):
'''Load a netcdf dataset into memory'''
d = xr.open_dataset(f... |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import os
from torch.utils.data import DataLoader, sampler
from pytorchtools import EarlyStopping, Encoder, Decoder, InferenceDecoder
torch.manual_seed(1)
USE_CUDA = torch.cuda.is_availabl... |
"""
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
//_/
//_/ CopyRight(C) K.Tsunoda(AddinBox) 2001 All Rights Reserved.
//_/ ( http://www.h3.dion.ne.jp/~sakatsu/index.htm )
//_/
//_/ この祝日判定コードは『Excel:kt関数アドイン』で使用しているものです。
//_/ この関数では、2007年施行の改正祝日法(昭和の日)までを
//_/ サポートしています(9月の国民の休日を含む)。
//_/... |
# -*- coding: utf-8 -*-
"""Holds the zazu repo subcommand."""
import zazu.imports
zazu.imports.lazy_import(locals(), [
'click',
'functools',
'git',
'os',
'semantic_version',
'socket',
'zazu.config',
'zazu.git_helper',
'zazu.github_helper',
'zazu.util',
])
__author__ = '<NAME>'
_... |
"""Models that provide foil section geometry and coefficients."""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable
import numpy as np
if TYPE_CHECKING:
from pfh.glidersim.airfoil import (
AirfoilCoefficientsInterpolator,
AirfoilGeometryInterpolator,
)
__all__ ... |
import pygame as pg
import os
import constants as c
class GameStatesManager:
"""
Control class for managing game states.
"""
def __init__(self):
self.state_dict = {}
self.state_name = None
self.state = None
def setup(self, state_dict, start_state):
... |
from FEMur import *
import sys
import sympy as sy
import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import scipy.interpolate
from math import ceil
class Solver(object):
'''
2-dimensional solver top class.
Provides common initialization to all child solver... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import torch
import cv2
import numpy as np
import torch.nn as nn
import pixel_link.pixel_link_config as config
def mask_filter(pixel_mask, link_mask, neighbors=8, scale=4):
"""
pixel_mask: batch_size * 2 * H * W
link_mask: batch_size * 16 * H * W
"""
batch_size = link_mask.size(0)
mask_height =... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
# -*- coding: utf-8 -*-
import enum
import time
import sys, os
sys.path.append('../')
from pathlib import Path
import fire
import numpy as np
import torch
from google.protobuf import text_format
import torchplus
from second.builder import target_assigner_builder, voxel_builder
from second.protos import pipeline_pb2
fro... |
import asyncio
import itertools
import functools
import math
import re
from attr import __description__
import discord
import os
from discord.ext import tasks, commands
from discord.ext.commands.errors import MissingPermissions
from discord.user import Profile
from discord.utils import get
from dns.message ... |
# -*- coding: utf-8 -*-
"""
This module handles breaking down text into Sequence objects, which are
collections of at most four words.
The SequenceProcessor requires a database reader/writer to be initialized.
The most interesting method to the user is the process() method. This method
expects a single Sentence object... |
# -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))+'/../node_bridge/node_bridge/')
import protocol as nbprotocol
import bridge as nbbridge
import autoaim
from toolz import curry, pipe
from queue import Full
import time
def miao(val, minval, maxval):
return m... |
from copy import deepcopy
from .kana_mapping import transform, get_subtree_of, create_custom_mapping
# NOTE: not exactly kunrei shiki, for example ぢゃ -> dya instead of zya
# to avoid name clashing
BASIC_KUNREI = {
"a": "あ",
"i": "い",
"u": "う",
"e": "え",
"o": "お",
"k": {"a": "か", "i": "き", "u": ... |
# -*- coding: utf-8 -*-
"""
Match Control
"""
import sys
# import os
# import numpy as np
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MatcherDialog(QMainWindow):
params_update_signal = pyqtSignal(object, name="params_update_signal")
def __init__(self, par... |
import logging
import spotipy
from spotmover.providers.spotify.util import obtain_token_localhost
from spotmover.providers.base import Provider, ProviderAuthError
from spotmover.dump import Dump
from spotmover.cache import DiskCache
logger = logging.getLogger(__name__)
def confirm(msg):
answer = input(msg + " "... |
"""
The number of event per FCS file is different, however
for later processing each FCS file should be represented by a fixed
number of features.
This module implements two scikit-learn compatible transformer
that cluster FCS events. HistogramTransform cluster the events
using a fixed grid while the decision tree cl... |
import numpy as np
from astropy.wcs import WCS
from ._det_spatial import get_shadowed_pix_mask_for_urddata, DL, F, multiply_photons
from .time import get_gti, GTI, tGTI, emptyGTI, deadtime_correction
from .atthist import hist_orientation_for_attdata
from .planwcs import make_wcs_for_attdata
from .caldb import get_energ... |
import numpy as np
from numpy import linalg
from numpy import random
from scipy import integrate
from scipy.optimize import curve_fit
##########################################################
#gauusian_weight
#compute a gaussian weight matrix W, given a vector x
#the reference observation point i (index) and a bandwi... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import resnet12
###### --- Conv4-64 --- ######
# This arch is the same as Spyros's works: https://github.com/gidariss/FewShotWithoutForgetting/blob/master/architectures/ConvNet.py
###### --- ResNet12 --- ######
# ResNet1... |
import numpy as np
from GPmodel import GaussianProcess
import os
from singlemes import MaxvalueEntropySearch
from scipy.optimize import minimize as scipyminimize
from platypus import NSGAII, Problem, Real
import sobol_seq
from pygmo import hypervolume
from design_space_bounds import parameter_bounds_small_design, param... |
#Based on routines originally written by <NAME>, University of Florida
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
import astropy.units as u
import astropy.constants as constants
from hyperion.dust import IsotropicDust
import os
def find_nearest(array,value):
idx = (np.abs(n... |
import config
import os
import time
import sys
import torch
import pickle
import numpy as np
# from tqdm import tqdm
from PIL import Image
from xml.etree import ElementTree
from torchvision import transforms
from torchvision.datasets import CocoDetection
from torch.utils.data.dataloader import default_collate
import im... |
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from libs import model_common
def placeholder(Batch_Size, P, Q, N, F_in, F_out):
labels = tf.compat.v1.placeholder(shape = (Batch_Size, Q, N, F_out), dtype = tf.float32,name="lables")
samples = tf.compat.v1.placeholder(shape = (Batch_Size, P, N, F_in),... |
# coding=utf8
from pyecharts import Bar, Kline, Map, Pie, WordCloud
class ChartFactory:
def __init__(self):
self._func = {}
self._charts = {}
def collect(self, name):
def _inject(func):
self._func[name] = func
return func
return _inject
def crea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.