text stringlengths 3.07k 22.1k |
|---|
import re
import numpy as np
from pymatgen.core import Structure
from .core import LammpsBox
from .inputs import LammpsData
def fields_view(array, fields):
return array.getfield(np.dtype(
{name: array.dtype.fields[name] for name in fields}
))
class LammpsRun(object):
""" Parse Lammps Run
... |
from __future__ import print_function
import sys
# following two must remain in the same order
print('lexer is running.......................................')
tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \
tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, t... |
# @author : <NAME>
import os
import math
import time
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
from fcn_model import FCN
from fcn_utils import init, read_config_file, get_data, preprocess_images, get_train_test_split
param_config_file_name = os.path.join(os.getcwd(), "fcn_config.js... |
import atexit
import threading
from datetime import datetime
from queue import Queue
from typing import Dict, List, Union, Optional
from kafka import KafkaConsumer
from kafka.errors import NoBrokersAvailable
from file_writer_control.CommandStatus import CommandStatus, CommandState
from file_writer_control.InThreadSta... |
#!/usr/bin/env python3
from olctools.accessoryFunctions.accessoryFunctions import make_path, MetadataObject, SetupLogging, run_subprocess
from argparse import ArgumentParser
from glob import glob
import statistics
import warnings
import json
import os
# Import all the Biopython modules
from Bio import BiopythonParserW... |
# 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 numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from torch_scatter import scatter_mean
import torch_geometric.transforms as T
from torch_geometric.utils import normalized_cut, to_dense_batch
from torch_geometric.nn import MetaLayer, SplineConv... |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
# Dataset for generating sequences, with labels predicting whether the cumulative sum
# is odd/even.
class Dataset:
def __init__(self, sequences_num, sequence_length, sequence_dim, seed, shuffle_batches=True):
sequences = np.zeros(
... |
import numpy as np
import operator
def calcshannonEnt(dataset):
# 香农熵计算
numEntries = len(dataset)
labelCounts = {}
for featVec in dataset:
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel]=1
else:
labelCounts[... |
"""
Brief: Genetic algorithm demo for eight queens game.
Author: <NAME>
Date: 2020/3/22
"""
import argparse
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpt
def calc_conflict(location_0, location_1):
if abs(location_0[0] - location_1[0]) != abs(location_0[1] - locat... |
import numpy as np
def defaultMotionPlanners():
return {
'home': HomeMotionPlanner,
'search': SearchMotionPlanner,
'aboveTarget': AboveTargetMotionPlanner,
'approach': ApproachMotionPlanner,
'target': TargetMotionPlanner,
# 'clean': CleanMotionPlanner,
# 'ri... |
# -*- encoding: utf-8 -*-
'''
Model Managers RexChain
BlockManager
RXmanager
TXmanager
'''
import json
import logging
from datetime import timedelta
from django.db import models
from django.apps import apps
from django.conf import settings
from django.utils import timezone
from django.core.cache import cache
from core... |
from .Extract import (is_bearish_engulfing, is_bullish_engulfing, is_dark_cloud_cover,
is_doji, is_evening_star, is_falling_three_methods, is_hammer, is_hanging_man,
is_inverse_hammer, is_morning_star, is_piercing_line, is_rising_three_methods,
is_shooti... |
import pandas as pd
import plotly.graph_objs as go
from hidrocomp.statistic.normal import Normal
from hidrocomp.statistic.bootstrap import Bootstrap
from hidrocomp.eflow.exceptions import *
from hidrocomp.eflow.graphics import GraphicsCha
class Era:
def __init__(self):
self._point = None
self._as... |
"""
Multi purpose stuff used by both clients and servers (URI etc)
Pyro - Python Remote Objects. Copyright by <NAME> (<EMAIL>).
"""
import re
import logging
import contextlib
import ipaddress
import socket
import random
import serpent
from typing import Union, Optional
from . import config, errors, socketutil, seria... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 app... |
from pandas import read_csv
from datetime import datetime
from matplotlib import pyplot
from datetime import datetime
from statsmodels.tsa.arima.model import ARIMA
import statsmodels.api as sm
# from statsmodels.tsa.statespace.sarimax.SARIMAX import SARIMAX
from sklearn.metrics import mean_squared_error
from math impor... |
#!/usr/bin/env python3
"""
Solution for ISTA 421 / INFO 521 Fall 2015, HW 2, Problem 1
Author: <NAME>, 12 September 2015
<NAME> (Sept 2018)
"""
import argparse
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
# --------------------------------------------------
def get_a... |
"""Submodule to handle the model parameterization and randomization."""
import logging
from functools import partial
from os import listdir, path # pylint: disable=no-name-in-module
import yaml
from ..numerical_libs import sync_numerical_libs, xp
from ..util import distributions, dotdict
from ..util.distributions im... |
# -*- coding: UTF-8 -*-
"""
EIO user registration webapp :: Flask views.
Copyright 2014-2021, EIO Team.
License: MIT
"""
from datetime import datetime
import traceback
from flask import render_template, flash, Markup, request, session, redirect, url_for, jsonify, make_response
from flask_wtf import FlaskForm as Form
... |
import sys
import math
import numpy
import random
import pygame
from scipy.spatial import distance
from shapely.geometry import box, Polygon
BLUE = (0, 0, 230)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
SIZE = (1500, 800)
width = 50
height = 50
pygame.init()
screen = pygame.display.set_mode(SIZE)
class... |
import argparse
import os
import tarfile
import urllib
import numpy as np
import pyprind
import utils
"""
次の理由から、本家の```create_ubuntu_dataset.py```の代わりにこちらを使う。
- ubuntu_dialogs.tgzはサイズが莫大で、また今回に関してはそのすべては必要ではないため、解凍せずに条件にあうものだけを抽出する
- 今回に関しては (context, response, label) のtripletsの生成までは不要であり、条件にあうdialogだけが必要
"""
URL... |
import torch
from torch import nn
import torch.nn.functional as F
__all__ = ['_conv3x3', '_bn_no_affine', 'GroupNorm']
def _conv3x3(in_channels, channels, stride):
return nn.Conv2d(in_channels, channels, kernel_size=3, stride=stride, padding=1,
bias=False)
# for darknet
def _conv2d(in_chan... |
"""Integration test: run experiments with some small & fast configs.
Only cursory 'smoke' checks -- there are plenty of errors this won't catch."""
import os
import shutil
import tempfile
import numpy as np
import pytest
import ray
from ray import tune
from aprl.activations.density.pipeline import density_ex
from a... |
import os
import sys
import random
import argparse
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
from utils.utilities import (mkdir, write_lst)
random.seed(1234)
instr_tags = "vn,vc,va,fl,cl,sax,tpt,tbn,bn,hn,tba,db,ob"
instrs = "Violin,Cello,Viola,Flute,Clarinet,Saxophone,Trumpet,Trombone,Bassoon,Horn,Tuba... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import os
from six import iteritems
import logging
from werkzeug.wrappers import Request
from werkzeug.local import LocalManager
from werkzeug.exceptions... |
#!/usr/bin/env python
"""
The mosaic QGraphicsView. This is QGraphicsView in the mosaic
UI tab.
Hazen 10/18
"""
import os
from PyQt5 import QtCore, QtGui, QtWidgets
#import storm_control.steve.qtMultifieldView as multiView
import storm_control.steve.coord as coord
import storm_control.steve.steveItems as steveItems
... |
# coding=utf-8
"""namesubscriber.py - implements a combobox with extra information
"""
import platform
import wx
def align_twosided_items(
parent, items, min_spacing=8, left_texts=None, right_texts=None
):
"""Find spacing for a list of pairs of text such that the left texts are
left justified and the ri... |
#!/usr/bin/python3
# coding=utf8
#from datacube.storage import netcdf_writer
#from datacube.model import Variable
import datacube
import numpy as np
from datacube.drivers.netcdf import writer as netcdf_writer
from datacube.utils.geometry import CRS
from datacube.utils import geometry, data_resolution_and_offset
from r... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn import preprocessing, cross_validation
import csv
import string
from collections import Counter
from tqdm import tqdm
import collections, re
import random
from random import randint
from sklearn.metrics import average_precision... |
import logging
import os
import sys
import numpy as np
from hexrd import config
from hexrd import constants as cnst
from hexrd import instrument
from hexrd.fitgrains import fit_grains
from hexrd.transforms import xfcapi
descr = 'Extracts G vectors, grain position and strain'
example = """
examples:
hexrd fit-gr... |
import os
import sys
import click
from typing import Iterable, Tuple, Optional
import networkx as nx
import matplotlib.pyplot as plt
# Read PPI content
def read_ppis(ppi_file_path: str) -> Iterable[Tuple[str]]:
"""Reads a file of PPIs.
Parameters
----------
ppi_file_path : str
Path to the P... |
import sys,os
import argparse
import numpy as np
import json
import heapq
import random
import numbers
# utils
def flatten(l):
""" Merges a list of lists into a single list. """
return [item for sublist in l for item in sublist]
class AveragePrecisionCalculator(object):
"""Calculate the average precision and av... |
"""
File: show_results.py
Author: <NAME>
TFG
"""
import argparse
import os
import keras
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
from keras.models import load_model
from keras.preprocessing.ima... |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.models.mode.mode_unit_test.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing failure Mode algorithms and models."""
# Thi... |
# -*- coding: utf-8 -*-
""" Report subcommands for HLSCLT.
Copyright (c) 2017 <NAME>
"""
### Imports ###
import click
import os
import subprocess
from glob import glob
from hlsclt.helper_funcs import find_solution_num
### Supporting Functions ###
# Function to check if project exists
def check_for_project(ctx):
... |
import logging
import logging.config
import os
import signal
import sys
from collections import namedtuple
from configparser import SafeConfigParser
from typing import Optional
from xmlrpc.server import SimpleXMLRPCServer
import appdirs
import click
import coloredlogs
import pkg_resources as pkg_rs
from openvisualize... |
"""ParametricJobs Table."""
# Py2/3 compatibility layer
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import * # pylint: disable=wildcard-import, unused-wildcard-import, redefined-builtin
import os
import json
import logging
from abc import ... |
"""
SGA.html
========
Code to generate HTML output for the various stages of the SGA analysis.
"""
import os
import numpy as np
def get_layer(onegal):
if onegal['DR'] == 'dr6':
layer = 'mzls+bass-dr6'
elif onegal['DR'] == 'dr7':
layer = 'decals-dr5'
else:
print('Unrecognized data ... |
import pytest
from parsita import ParseError
import roll.exceptions as rollerr
from roll.parser import parse_program
SIMPLE_TEST_CASES = [
# Literals
(r"1", 1),
(r"200123500000000", 200123500000000),
(r"-99", -99),
(r"--999", 999),
(r"---9999", -9999),
(r"------------------99... |
# legacy app: mic pos calibration with a 40kHz ultrasonic distance sensor
import numpy as np
import math
import time
import cv2
import copy
import nidaqmx
import nidaqmx.stream_readers
import nidaqmx.constants
import pyrealsense2 as rs
from cv2 import aruco
import h5py
import platform
if platform.system() == "Win... |
from django.shortcuts import render,redirect
from django.http import HttpResponse
# Create your views here.
from .tasks import *
import pymongo
import datetime
from bson.objectid import ObjectId
from .local1 import *
from .regular1 import *
from django.http import JsonResponse
class vars():
grid_var = 0
zel_... |
import os
import numpy as np
from PIL import Image
class Calibration:
def __init__(self, calibs):
self.P0 = calibs['P0'] # 3 x 4
self.P1 = calibs['P1'] # 3 x 4
self.P2 = calibs['P2'] # 3 x 4
self.P3 = calibs['P3'] # 3 x 4
self.R0 = calibs['R0_rect'] # 3 x 3
se... |
# bi-directional srnn within pkg
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import StepLR,MultiStepLR
import math
import torch.nn.functional as F
from torch.utils import data
from SRNN_layers.spike_dense import *#spike_dense,readout_integrator
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
implement the cnn network with tensorflow
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import xt.model.impala.vtrace_tf as vtrace
from tensorflow.python.util import deprecation
from xt.framework.register import Registers
from... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from model_submission.model.base_network import BaseNetwork
from model_submission.model.utils import gen_conv, gen_deconv
from model_submission.model.splitcam import ReduceContextAttentionP1, ReduceContextAttentionP2
class TwostagendGenerator(BaseNetw... |
from lxml import etree as ET
from ..Common import Settings, Print
'''
Notes on duplicated extension IDs:
X4 will load extensions with duplicate ids, but gets buggy on
how it handles them.
These IDs are used for two things:
1) Dependency references will only point to the first (alphabetical folder
... |
import opendbpy as odb
import os
def createSimpleDB():
db = odb.dbDatabase.create()
tech = odb.dbTech.create(db)
L1 = odb.dbTechLayer_create(tech, 'L1', 'ROUTING')
lib = odb.dbLib.create(db, "lib")
odb.dbChip.create(db)
#Creating Master and2 and or2
and2 = createMaster2X1(lib, 'and2', 1000... |
def convertCoordToDistAngles(rN, rCa, rCb, mask=None):
'''
data should be coordinate data in pnet format, meaning that each amino acid is characterized
by a 3x3 matrix, which are the coordinates of r1,r2,r3=N,Calpha,Cbeta.
This lite version, only computes the angles in along the sequence
(upper o... |
"""
Process the raw data to generate the tables we will use to..
implement the estimation.
"""
import numpy as np
import pandas as pd
from bld.project_paths import project_paths_join as ppj
# Prepare the original dataset.
raw_dict = {}
for dataset in 'pop_9314', 'pop_1517', 'gross_claims', 'gross_premiums', \
... |
##############################################################################
#
# Kennedy Institute of Rheumatology
#
# $Id$
#
# Copyright (C) 2015 <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Fr... |
"""
Build: parse and add user-supplied files to store
"""
import os
import re
from shutil import rmtree
from .const import DEFAULT_TEAM, PACKAGE_DIR_NAME
from .core import FileNode, RootNode, TableNode, find_object_hashes
from .package import Package, PackageException
from .util import BASE_DIR, sub_dirs, sub_files, ... |
import numpy as np
from astropy.io import ascii, votable
from astropy.time import Time
import os, requests, sys, warnings
from io import StringIO
# global variables
# convert units from radians to degree
r2d = 180/np.pi
# convert units from degree to radians
d2r = np.pi/180
def getmultiwave(dataset, url='http://hla.... |
import abc
import numpy as np
import six
import os
import tensorflow as tf
@six.add_metaclass(abc.ABCMeta)
class NeuralNetwork(object):
"""Abstract base class for Neural Network used in
policy-value net.
Details can be found in https://www.nature.com/articles/nature24270
'Mastering the game of Go wi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 17:59:11 2020
@author: yaoleixu
"""
# ============================================================================
# Import libraries
import numpy as np
from tensorflow.keras import activations, initializers, constraints
from tensorflow.keras im... |
""" Analysis code for IGMSurvey objects
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import glob
import json
import pdb
from astropy.table import Table
from linetools import utils as ltu
def calc_slgrid_atan(surveys, Agrid, Bgrid, Cgrid, C2grid):
""... |
#
# Access to public web APIs
#
import bs4
import datetime
import http
import json
import os
import requests
import traceback
from api import app
ALLTHEBLOCKS_REQUEST_INTERVAL_MINS = 15
COLD_WALLET_ADDRESSES_FILE = '/root/.chia/machinaris/config/cold_wallet_addresses.json'
COLD_WALLET_CACHE_FILE = '/root/.chia/machi... |
#%%
import os
import sys
import joblib
from numpy.lib.function_base import select
import sklearn
import warnings
import tarfile
import urllib
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pandas.plotting import scatter_matrix
from... |
import string,os,sys
import logs
header_string = '''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>CHIPCHIP regfile </title>
</head>
<body>
<center>
<h1>CHIPCHIP regfile </h1>
</center> <left>
<table border>
'''
table_header_string = '''
<tr>
... |
import sys
import cPickle as pickle
if __name__ == '__main__':
sys.path = pickle.loads(sys.argv[3])
import logging
import traceback
import time
import threading
import os
import Queue as Queue
import test_looper.core.ManagedThread as ManagedThread
import test_looper.core.SubprocessRunner as SubprocessRunner
impo... |
"""Video Super-resolution dataset."""
import os
import random
from PIL import Image
import numpy as np
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import common.modes
import datasets._isr
def update_argparser(parser):
datasets._isr.update_argparser(parser)
parser.ad... |
import pytest
from rhc.httphandler import HTTPHandler
from rhc.resthandler import RESTRequest
@pytest.fixture
def handler():
class _network(object):
def _unregister(self, sock):
pass
class _context(object):
def __init__(self):
self.context = {}
class _handler(... |
#!/usr/bin/python3
import abc
import datetime
import argparse
import sqlite3
import sqlalchemy
from sqlalchemy import exc, create_engine, and_, or_
from sqlalchemy import ForeignKey, UniqueConstraint
from sqlalchemy import Column, DateTime, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_ba... |
# Copyright 2021 <NAME>
# A small demo-program illustrating basic usage of the associated third-person camera-controller.
#
# Specifically, this program creates and loads a simple player-object and environment, with the
# camera-controller attached to the player-object. The user can then drive the player-object around,... |
# Copyright (C) 2005 Joint Institute for VLBI in Europe
# Copyright (C) 2007,2019 Associated Universities, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,... |
"""
===============================================================================
| process_data.py |
===============================================================================
| A collection of scripts to read data from exodus files using the yt librar... |
# Copyright 2017 Battelle Energy Alliance, 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 t... |
# Quark Runtime
# Usage: from quark_runtime import *
# This brings in the stuff mentioned in __all__ below.
# The wrong way to do this, but minimizes the code change.
from __future__ import absolute_import
from __future__ import unicode_literals
__version__ = '0.4.2'
__all__ = str(
"""os sys time _Map _List _pri... |
#!/usr/bin/python3
import csv
import http.client
import urllib
import json
import argparse
import ssl
import datetime
class Utils:
def __init__(self, debug_mode=False):
self.debug_mode = debug_mode
def debug_callout_block(self, *args):
self.debug_print_separator()
for arg in args:... |
from torchvision.transforms.functional import InterpolationMode
import os
from PIL import Image
import numpy as np
from collections import OrderedDict
from tqdm.auto import tqdm
import torchvision
import torch
def to_numpy(x):
x_ = np.array(x)
x_ = x_.astype(np.float32)
return x_
def get_image_transfo... |
# -*- coding: utf-8 -*-
"""主模块
包含该项目的主函数
"""
import argparse
import json
import logging
import os
import sys
from typing import Callable, Dict, List, Optional, Union
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from oss import AliyunOssBucket, QcloudCosBucket
from utils import FileManager, OSSSync... |
from . import _
from Screens.Screen import Screen
from Plugins.Plugin import PluginDescriptor
from Components.Button import Button
from Components.ActionMap import ActionMap
from Components.config import config, configfile, ConfigSubsection, getConfigListEntry, ConfigSelection, ConfigSlider
from Components.ConfigList i... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.figure import Figure
import glob
import os
from typing import Tuple
from scipy.stats import wasserstein_distance
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist, square... |
import random, os, glob, sys, shutil
import numpy as np
import torch
import logging
import json
import transformers
def add_filehandler_for_logger(output_path, logger, out_name="train"):
logFormatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s')
fileHandler... |
# coding=utf-8
#
"""
Copyright (c) 2019, <NAME>. All rights reserved.
license: BSD 3-Clause License, see LICENSE for more details.
"""
from zm.error import ZenMakeConfError, ZenMakeConfTypeError, ZenMakeConfValueError
from zm.pyutils import maptype, stringtype
from zm.utils import toList
from zm.autodict import Aut... |
# The app identifier has been successfully created.
# Client Id: os.environ["client_id"]
# Client Secret: os.environ["client_secret"]
# Title: python_api_2020_11_13
# App Domain: localhost
# Redirect URI: https://localhost
import datetime
import logging
import os
import sys
from pathlib import Path
fro... |
# import the necessary packages
from imports import *
charNames = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "T", "U", "A", "D"]
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 7))
# initialize the list of reference character names, in the same
# order as they appear in the reference image where t... |
import os
from numpy import pi, seterr, linspace
from skyfield.api import load
from skyfield.constants import GM_SUN_Pitjeva_2005_km3_s2 as GM_SUN
from skyfield.data import mpc
from skyfield.elementslib import OsculatingElements
from skyfield.keplerlib import _KeplerOrbit as KeplerOrbit, propagate
from skyfield.tests.... |
import itertools
import dask.dataframe as dd
import dask.dataframe.groupby as ddgb
import numpy as np
import pandas
import toolz
from pandas import isnull
import ibis
import ibis.expr.operations as ops
from ibis.backends.pandas.core import integer_types, scalar_types
from ibis.backends.pandas.execution.strings import... |
# HAT: Hardware-Aware Transformers for Efficient Natural Language Processing
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>
# The 58th Annual Meeting of the Association for Computational Linguistics (ACL), 2020.
# Paper: https://arxiv.org/abs/2005.14187
# Project page: https://hanruiwang.me/project_pages/h... |
import time
from itertools import product
from loggers import CSVLogger, PrintLogger, FileLogger, multi_logger
import torch
from torch.optim import Adam
import os
import networkx as nx
import pickle
import numpy as np
import logging
from model_runner import ModelRunner,execute_runners
import cProfile
Data... |
import numpy
import random
import math
import qConstants as qc
import qUtilities as qu
import qBitStrings as qb
import qAlgorithms as qa
def power(stateOrGate, m):
assert m > 0, "m must be positive"
'''Assumes n >= 1. Given an n-qbit gate or state and m >= 1, returns the
mth tensor power, which is an (n * ... |
'''
智校园的targetAPI是16, 使用极其蛋疼
所以就参照'QZAPI_Archive'和手动抓包分析, 使用python重新封装了API
2019, chen_null
'''
import requests
import time
class QzapiExecption(Exception):
pass
class Qzapi:
'''
将强智教务系统的API封装成类,以方便调用
'''
session = requests.Session()
session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# get_ipython().run_line_magic('matplotlib', 'inline')
# get_ipython().run_line_magic('load_ext', 'tensorboard')
# In[2]:
from __future__ import print_function
from __future__ import division
import itertools
from PIL import Image
import torch
import torch.nn as nn... |
import os
import numpy as np
from array import array
from sklearn.metrics import mean_absolute_error
from skmultiflow.data import RegressionGenerator
from skmultiflow.trees import HoeffdingTreeRegressor
from difflib import SequenceMatcher
def test_hoeffding_tree_regressor():
stream = RegressionGenerator(n_samples... |
import warnings
warnings.filterwarnings("ignore")
import csv
import ast
import numpy as np
import pandas as pd
import statsmodels.api as sm
import math
#gem column codes: 0 = latitude, 1 = longitude, 2 = altitude, 3 = accuracy, 4 = department, 5 = municipality, 6 = household salary, 7 = JG2, 8 = age, 9 = JG6, 10 = ge... |
import argparse
import random
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
from mario.tokens import REPLACE_TOKENS
from mario.level_image_gen import LevelImageGen
from mario.special_mario_downsamplin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import json
import time
import shlex
import shutil
import argparse
from subprocess import Popen, DEVNULL, PIPE
from datetime import datetime
from threading import RLock
import watchdog.observers
import watchdog.events
default_input_args ='-loglevel... |
"""UniProps."""
from __future__ import unicode_literals
from . import unidata
import sys
PY3 = sys.version_info >= (3, 0) and sys.version_info[0:2] < (4, 0)
if PY3:
binary_type = bytes # noqa
else:
binary_type = str # noqa
def get_posix_property(value, uni=False):
"""Retrieve the posix category."""
... |
import numpy as np
from vimms.Evaluation import evaluate_simulated_env, EvaluationData
from vimms_gym.common import METHOD_RANDOM, METHOD_FULLSCAN, METHOD_TOPN, METHOD_PPO, METHOD_DQN
from vimms_gym.env import DDAEnv
from vimms_gym.policy import random_policy, fullscan_policy, topN_policy, get_ppo_action_probs
class... |
"""Kea Control Channel - socket"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_msg
import srv_control
from forge_cfg import world
def _send_cmd(cmd, extra_param=None, exp_result=0):
cmd = dict(command=cmd, arguments={})
if isinstance(extra_param, dict):
cmd["ar... |
from __future__ import print_function
from dogpile.cache import make_region
import dogpile_backend_redis_advanced
import msgpack
from dogpile.cache.api import CachedValue
from dogpile.cache.region import value_version
import psutil
import redis
import json
import sys
import os
import pdb
import pprint
import subproc... |
from __future__ import unicode_literals
import datetime
import hashlib
from django.contrib import messages
from django.contrib.auth import login as auth_login, authenticate, get_user_model
from django.db import IntegrityError
from django.shortcuts import redirect, render
from django.views.generic import View
from djan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import time
import importlib
import ipywidgets as widgets
from .py3js_renderer import Py3JSRenderer
found_forte = importlib.util.find_spec("forte") is not None
if found_forte:
import forte
else:
from .cube_file import *
def list_cubes(path='.'):
"... |
import argparse
from timeit import default_timer
from typing import Tuple
import numpy as np
from dgl import DGLGraph
from dgl.data import RedditDataset
from ogb.nodeproppred import DglNodePropPredDataset
from sklearn.metrics import accuracy_score, log_loss
from torch import Tensor
from xgboost import XGBClassifier
f... |
from __future__ import print_function, division
#import os
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#import tensorflow
#tensorflow.logging.set_verbosity(tensorflow.logging.WARN)
from tensorflow.python.keras import backend as k
import scipy
from scipy.misc import imsave
from tensorflow.python.keras.layers import Inp... |
import configparser
from selenium import webdriver
from requests import *
from Functions import *
import re
import time
import json
import os
header_dd373_save=\
{
'content-type': 'application/json; charset=utf-8',
'date': 'Thu, 24 Feb 2022 08:21:58 GMT',
'ohc-cache-hit': r"mzun60 [1], bduncache82 [... |
# -*- coding: utf-8 -*-
# Copyright 2019 ICON Foundation
#
# 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 ... |
#!/usr/bin/env python3
import os
import sys
from itertools import zip_longest
from platform import release
import yaml
from jinja2 import Environment, FileSystemLoader, Template, TemplateNotFound
from git import Repo, GitConfigParser, Remote, Blob, Object
class RestrictedFileSystemLoader(FileSystemLoader):
def ... |
import sys
if "" not in sys.path: sys.path.append("")
import os
from glob import glob
import warnings
import numpy as np
from PIL import Image
from util.general import printProgressBar, print_result, print_warning
def generate_paired_lists(cxr_paths, mask_paths, subset_n, split_masks=False):
"""
This functio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.