text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
# Copyright 2018 The TensorFlow 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 applica... |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch import optim
from torch.autograd import Variable
from torchvision import datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import os
from torchvision imp... |
import os
import logging
from collections import OrderedDict, defaultdict
import torch
import torch.utils.data
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.utils.comm import get_world_size
from maskrcnn_benchmark.data.build import make_data_sampler, make_batch_data_sampler
fr... |
# ------------------------------------------------------------
# MTLparse.py
#
# Parser for MTL formula.
# Construct observer abstract syntax tree and remove the duplicate branch
# ------------------------------------------------------------
import ply.yacc as yacc
from .MTLlex import tokens
from .Observer import *
imp... |
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
import glob, os
import matplotlib.pyplot as plt
from uncertainties import ufloat
from uncertainties.umath import exp, log10
from emcee.autocorr import integrated_time
def load_chain(chainfile):
param_file = os.path.dirname(chainfile... |
# -*- coding: utf-8 -*-
"""
This module provides the fundamental coordinate transformations between fiber
positioner (theta, phi) angles and an (x, y) cartesian space.
It is kept manually synchronized with a file of the same name in the online
instrument code:
/code/focalplane/plate_control/<some_branch>/petal/xy2... |
import pandas as pd
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure
from bokeh.palettes import Spectral5, Spectral11
from bokeh.driving import count
# ... |
import sys
import threading
import seeed_mlx9064x
from serial import Serial
from PyQt5.QtWidgets import (
QApplication,
QGraphicsView,
QGraphicsScene,
QGraphicsPixmapItem,
QGraphicsTextItem,
QGraphicsEllipseItem,
QGraphicsLineItem,
QGraphicsBlurEffect
... |
from django.conf import Settings
from django.core.exceptions import MultipleObjectsReturned
from apis_core.apis_entities.models import *
from apis_core.apis_relations.models import *
from apis_core.apis_labels.models import *
from apis_core.apis_metainfo.models import *
def dict_to_pers(pers_dict, entity=None):
... |
# ==============================================================================
# Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics
# Author: <NAME> (<EMAIL>)
# All rights reserved.
# ==============================================================================
""" """
import os, sys
from ... |
# -*- coding: utf-8 -*-
import json
import requests
from datetime import datetime
from .exceptions import ArambaAPIError, ArambaEngineError, ArambaValueError
METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options']
ERROR_CODES = [400, 401, 402, 403, 404, 409, 500]
# Aramba API URLs
API_URL = 'https://api.ar... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 11 11:28:56 2022
Original Code from Dr. <NAME>
https://www.youtube.com/watch?v=S416IbCFeEA&t=185s
"""
import numpy as np
from scipy.sparse import linalg as la
import scipy as SP
import sys
def random_hermitian(n):
#A=np.random.rand(n,n)
A = SP.spa... |
# Copyright (c) 2020 <NAME>
# Copyright (c) 2020 <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, ... |
# 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 torch
import torch.fft
import torch.nn as nn
import torch.nn.functional as F
def roll(x, shift, dim):
if isinstance(shift, (tuple,... |
import logging
import shelve
from os import getenv
import json
from urllib2 import HTTPError, URLError, Request, urlopen
from traceback import format_exc
from datetime import timedelta, datetime
from argparse import ArgumentParser
from ConfigParser import ConfigParser
from time import sleep
from vnc_api.vnc_api import... |
# 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 torch
import config as cfg
from ipeps.ipeps_c4v import IPEPS_C4V
import pdb
class ENV_C4V():
def __init__(self, chi, state=None, bond_dim=None, ctm_args=cfg.ctm_args,
global_args=cfg.global_args):
r"""
:param chi: environment bond dimension :math:`\chi`
:param state: wavefun... |
#!/usr/bin/env python
"""Module to drive ws2812 from SPI
Copyright 2021 <NAME>
SPDX Apache License 2.0
"""
import logging
import math
import re
import time
from ipaddress import IPv4Address, IPv6Address, ip_address
from pathlib import Path
from threading import BoundedSemaphore, Event, Thread
from typing import Any,... |
import os
from os.path import join as pjoin
import _pickle as cp
from random import shuffle
import numpy as np
import tensorflow as tf
from models.bnn import BNN
# command line arguments
flags = tf.flags
### TRAINING ARGS
flags.DEFINE_integer("batchSize", 32, "batch size.")
flags.DEFINE_integer("nEpochs", 4500, "n... |
# MIT License
#
# Copyright (c) [2019] [<EMAIL>]
#
# 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, ... |
import re
from matrix import ContingencyMatrix
from buffer import status_message
import concurrent.futures
from parameter import generate_sequence_set
from msa import MultipleSequenceDriver, ConsensusFilterFactory
import sequence
import warnings
class DomainSetBuilder():
'''
Given arguments relative to domain... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from cpprb import ReplayBuffer
from tf2rl.experiments.trainer import Trainer
from tf2rl.misc.get_replay_buffer import get_space_size
class DynamicsModel(tf.keras.Model):
def __init__(self, input_dim, output_dim, units=[32, 32], ... |
import datetime as dt
import statistics
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from .forms import AddProjectForm, RateProjectForm, CreateProfileForm
from .email import send_signup_email
from django.contrib.auth.model... |
"""
Batched parallel pipelining utilities. A pipeline here is defined as a
sequence of pickleable callable objects (e.g. not containing generator, a
notable type of objects that's not pickleable). Each callable object at each
time is fed with an input and should returns an output, which in turn serves
as the input to t... |
'''VGGFace models for Keras.
# Notes:
- Resnet50 and VGG16 are modified architectures from Keras Application folder. [Keras](https://keras.io)
- Squeeze and excitation block is taken from [Squeeze and Excitation Networks in
Keras](https://github.com/titu1994/keras-squeeze-excite-network) and modified.
'''
from ... |
import torch
import torch.nn as nn
class VGG_CBAM_Block(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
... |
import launch
from launch.launch_description import LaunchDescription
from launch.substitutions import Command, LaunchConfiguration
from launch_ros.actions import LifecycleNode
from launch.actions import EmitEvent, DeclareLaunchArgument
from launch_ros.events.lifecycle import ChangeState
from launch_ros.events.lifecycl... |
import argparse
import csv
import json
import sys
import locale
import dateutil.parser
import pytz as pytz
import requests
from datetime import datetime
class ArgumentValidationError(Exception):
def __init__(self, message):
super().__init__(message)
def parse_validate_arguments():
"""
Parses co... |
from itertools import zip_longest
from pathlib import PurePath
import copy
import os
from openpyxl import Workbook
from openpyxl.chart import ScatterChart, Reference, Series
from openpyxl.drawing.line import LineProperties
from bcompiler.core import Quarter, Master, Row
from ..utils import logger, ROOT_PATH, CONFIG_F... |
#! /usr/bin/env python3
# Copyright (C) 2015 <NAME>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
import argparse
import os
import subprocess
import sys
def go(arguments):
os.environ... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# coding=utf-8
# Copyright 2021 Google Health Research.
#
# 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 la... |
import os
import sys
import time
import random
import curses, curses.panel
import asyncio
from curses_tools import draw_frame, get_frame, get_frame_size, read_controls, get_colors
from physics import update_speed
from obstacles import Obstacle, show_obstacles
from explosion import explode
from game_scenario import PHR... |
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
#
# render_run.py
#
# Copyright (C) 2020 IMTEK Simulation
# Author: <NAME>, <EMAIL>
#
# 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 res... |
import mmcv
import numpy as np
from mmdet.datasets.builder import PIPELINES
from mmdet.datasets.pipelines import Normalize, Pad, RandomFlip, Resize
@PIPELINES.register_module()
class SeqResize(Resize):
def __init__(self, share_params=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.signals import (
post_delete,
post_save,
pre_delete,
pre_save,
)
from django.dispatch import Signal, receiver
from django.utils import timezone
from django_comments.mo... |
import search
from math import(cos, pi)
# A sample map problem
# sumner_map = search.UndirectedGraph(dict(
# Portland=dict(Mitchellville=7, Fairfield=17, Cottontown=18),
# Cottontown=dict(Portland=18),
# Fairfield=dict(Mitchellville=21, Portland=17),
# Mitchellville=dict(Portland=7, Fairfield=21),
# ))
# ... |
from microbit import *
from micropython import const
COLS = const(136)
ROWS = const(250)
OFFSET_X = const(0)
OFFSET_Y = const(6)
WIDTH = const(250)
HEIGHT = const(122)
DRIVER_CONTROL = const(0x01)
GATE_VOLTAGE = const(0x03)
SOURCE_VOLTAGE = const(0x04)
DISPLAY_CONTROL = const(0x07)
NON_OVERLAP = const(0x0B)
BOOSTER_... |
__all__ = ['NamingNode','NamingDict','NamingRoot','NamingRecv','a_name_valid']
from .ast import ASTNode
import warnings
def raise_error(err):raise err
keywords = {'begin','end','always','initial','generate','endgenerate','if','else','for','wait','fork','join'
'genvar','integer','wire','reg','module','endmodule... |
import sys
import time
import numpy as np
import torch
import torch.nn as nn
HYPERPARAMS = {
'bfw': {
'env_name': "Bfw-v0",
'stop_reward_player2': 100.0,
'stop_reward_player1': 100.0,
'run_name': 'bfw',
'replay_size': 100000,
'replay_initial':... |
"""
A ronda is the shortest possible complete segment of a game,
from initial deal to points calculation.
A ronda is played in the following manner:
Players play in clockwise order, starting from the left of the dealer
(the dealer always plays last). During their turn each player can either:
a) Use one of the cards ... |
import pandas as pd
from typing import Union, Any, Tuple
import os
import subprocess
import zarr
import xarray as xr
import numpy as np
from satpy import Scene
from pathlib import Path
import datetime
from satip.geospatial import lat_lon_to_osgb, GEOGRAPHIC_BOUNDS
from satip.compression import Compressor, is_dataset_... |
"""Resnet test that uses new API.
Expected result
Running with automatically selected checkpoints
Calling memsaving gradients with memory
Graph construction: 1785.14 ms
Compute time: 414.17 ms
Memory used: 567.97 MB
Running without checkpoints
Graph construction: 1234.51 ms
Compute time: 365.91 ms
Memory used: 1110.... |
"""
This module contains the Python-Cobol pic parser written by
<NAME> (https://github.com/bpeterso2000/pycobol ) and enhanced
by <NAME>sen
(https://github.com/balloob/Python-COBOL/blob/master/cobol.py ), licensed
under the GPL v3.
We slightly modified this module to:
- add python3 support
- use the pyqode log... |
# ---------------------------------------------------------------------
# Network Segment Profile
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python ... |
from pytorch_segnet import *
import numpy as np
import torch.utils.data as Data
from PIL import Image
from collections import Counter
import sys
import csv
device = torch.device("cuda " if torch.cuda.is_available() else "cpu")
f_score=np.zeros((19,1))
label = Image.open('Datasets/dataset/trainData/lab... |
from flask import Flask, url_for, redirect, json, request, make_response, Response, stream_with_context
import atp_classes, os, gzip, glob
app = Flask(__name__)
config = atp_classes.Config()
app.secret_key = config.get_config()['session_secret']
cache = atp_classes.Cache()
app_db = atp_classes.AppDB()
hive_db ... |
import requests, sys, argparse, validators, os, tldextract
from colorama import init, Fore, Style
from pyfiglet import Figlet
# INITIALISE COLORAMA
init()
# DISPLAY BANNER -- START
custom_fig = Figlet(font='slant')
print(Fore.BLUE + Style.BRIGHT + custom_fig.renderText('-------------') + Style.RESET_ALL)
pr... |
'''
Functions to calculate bandwidth-based
spectral features from neurophysiology
data (LFP and ECOG) in ReTune's B04 Dyskinesia Project
Containing:
- bandpass filter
- coherence
- Phase Amplitude Coupling (tensorpac)
'''
# Import general packages and functions
import os
import numpy as np
from scipy import signal
or... |
"""
File: tree.py
Created by ngocjr7 on 2020-08-15 21:47
Email: <EMAIL>
Github: https://github.com/ngocjr7
Description:
"""
from __future__ import absolute_import
from geneticpython.core.individual import Solution
from geneticpython.utils.validation import check_random_state
from geneticpython.utils import rset
from ... |
# pylint: disable=global-statement,redefined-outer-name
import argparse
import collections
import csv
import glob
import json
import os
import dateutil.parser
import yaml
from flask import Flask, jsonify, redirect, render_template, send_from_directory
from flask_frozen import Freezer
from flaskext.markdown import Mark... |
# -*- coding: utf-8 -*-
"""
pyinfluxql.query
~~~~~~~~~~~~~~~~
PyInfluxQL query generator
"""
import re
import six
import datetime
from copy import copy, deepcopy
from dateutil.tz import tzutc
from .functions import Func
from .utils import format_timedelta, format_boolean
UTC_TZ = tzutc()
class Query(ob... |
"""Converter that converts HTML files from the Noorlib library
to OpenITI mARkdown.
The converter has two main functions:
* convert_file: convert a single html file.
* convert_files_in_folder: convert all html files in a given folder
Usage examples:
>>> from html_converter_noorlib import convert_file
>>> fold... |
#!/usr/bin/env python
# coding: utf-8
# conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch
# wandb login XXX
import json
import logging
import os
import re
import sklearn
import time
from itertools import product
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
logging.... |
"""TOTTO table processsing.
Processing the data format in TOTTO into the HybridQA one
"""
import copy
import hashlib
import json
import multiprocessing
from multiprocessing import Pool
import re
import pprint
import nltk
def clean_cell_text(string):
"""Strip off the weird tokens."""
string = string.replace('"',... |
import sys
import numpy as np
import importlib
from PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog, QMessageBox
from PyQt5.QtCore import Qt, QTimer
from PyQt5 import QtWidgets
from PyQt5 import uic
from PyQt5.uic import loadUiType
import astropy.io.fits as pf
from datetime import datetime
from dateti... |
import numpy.testing as nt
import matplotlib.pyplot as plt
import unittest
"""
we will assume that the primitives rotx,trotx, etc. all work
"""
from math import pi
from spatialmath.twist import *
from spatialmath import super_pose # as sp
from spatialmath.base import *
from spatialmath.base import argcheck
from spatia... |
################################################################################
# The MIT License
#
# Copyright (c) 2019-2021, Prominence AI, 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 ... |
#!/usr/bin/env python3
import sys
from elftools.elf.elffile import ELFFile
from elftools.dwarf.enums import ENUM_DW_TAG
from os.path import splitext
import os
class Parameter:
def __init__(self, typ, name):
self.type = typ
self.name = name
def __str__(self):
return "%s %s" % (self.type... |
import matplotlib.gridspec as gridspec
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as mplt
from matplotlib import patheffects as mpe
from matplotlib.patches import Circle, Wedge, Rectangle
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from matplotlib.animation impor... |
from typing import (
cast,
Any,
AsyncContextManager,
Tuple,
Type,
)
from lahja import EndpointAPI
from cancel_token import CancelToken
from eth_typing import BlockNumber
from eth_utils import to_bytes
from eth_keys import keys
from eth.db.header import HeaderDB
from eth.db.backends.memory impo... |
# 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
import random
import torch
from fairseq import metrics, utils
from fairseq.criterions import FairseqCriterion, register_criterion... |
'''
Created by <NAME>
20 March 2018
This script is designed to work on the new dataset of final variant calls from the PCAWG dataset.
'''
import sys
import os
import glob
from optparse import OptionParser
from collections import OrderedDict
import time
import subprocess
from functools import wraps
import numpy as np
i... |
# coding=utf-8
from datetime import datetime
import json
from elasticsearch import Elasticsearch
from elasticsearch.client.cat import CatClient
from elasticsearch_dsl import Search
from elasticsearch.helpers import bulk
from es.analyzers import similar_candidates, similar_jobs, similarity
client = Elasticsearch('17... |
#author: yqq
#date : 2019-12
import logging
from base_handler import BaseHandler
from utils import decimal_default, get_linenumber
import json
from xrp.ripple_proxy import RippleProxy
# from .proxy import USDPProxy
from constants import XRP_RIPPLED_PUBLIC_API_URL
from constants import XRP_RIPPLED_PUBLIC_AP... |
import numpy as np
import torch
import torch.nn.functional as F
from scipy.spatial.transform import Rotation as R
from torch import nn
import spherical_sampling
from module_utils import MLP
from unet_parts import *
class UNet(nn.Module):
def __init__(self, n_channels, n_classes, bilinear=True):
super(UNe... |
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import datetime
import logging
import os
import subprocess
import thread
import click
from c7n.credentials import SessionFactory
from concurrent.futures import ProcessPoolExecutor, as_completed
from dateutil.parser import parse as parse_da... |
# Includes
import os
import numpy as np
import cv2
import glob
import math
import time
import matplotlib.pyplot as plt
from moviepy.editor import VideoFileClip
# Default HSV Binary Thresholds
_HSV_YW_THRESHOLDS = [np.array([15, 127, 127], dtype=np.uint8), # yellow_dark
np.array([25, 255, 255], ... |
#!/usr/bin/env python
# builtin
from __future__ import absolute_import, division, print_function
import glob
import logging
import numbers
import os
import socket
import socketserver
import subprocess
import sys
import tarfile
import threading
import time
# external
import xdg.BaseDirectory
# internal
from wallpapermgr... |
import math
import shutil
import tempfile
from decimal import Decimal
from fractions import Fraction
from typing import Iterable, List, Union, Tuple, Optional
import av
import numpy as np
def simple_frame_to_time(frame: int, fps: Fraction, start_pts: int) -> Fraction:
"""
Assumption: start_pts == 0
"""
... |
from datetime import date
from queue import Queue
import pywikibot
from dateutil.relativedelta import relativedelta
from pywikibot import editor as editarticle
from pywikibot.tools.formatter import color_format
class BaseCategory():
"""
基幹のカテゴリ
Returns:
str: カテゴリの名前
"""
def __init__(sel... |
#!/usr/bin/env python3
"""
This utility script allows to walk through the routing graph from a given
starting node id to a given target node id. If the target node id is not
given then it lists all available routes which start at the starting node.
"""
import sys
import argparse
import gc
from collections import named... |
import math
import sys
from itertools import islice
sys.setrecursionlimit(30000)
#define n
n=2
#Create 2D intitak List
temp = [ 0 for x in range(n)]
Matrix = [temp for x in range(n)]
#print(Matrix)
temp = [1 for x in range(n)]
routeCheck = [ temp for x in range(n)]
# 1D to 2D list convertor
def convert(lst, va... |
"""
A script to generate exon structure file for certain species and transcript
Example script:
python prepare_exon_structure_file.py -s human -ti ENST00000370418.7
python prepare_exon_structure_file.py -s mouse -ti ENSMUST00000183805
python prepare_exon_structure_file.py -s zebrafish -ti ENSDART00000177727
python pr... |
import itertools
import operator
import os
import string
from collections import deque, namedtuple
from . import data
from . import diff
def init():
data.init()
data.update_ref('HEAD', data.RefValue(
symbolic=True, value='refs/heads/master'))
def write_tree():
# Index is flat, we need it as a ... |
import numpy as np
import tensorflow as tf
from functools import partial
import cv2 as cv
import random
def gaussian_noise(img_set, mean=0, var=0.001):
ret = np.empty(img_set.shape)
for m, image in enumerate(img_set):
image = np.array(image/255, dtype=float)
noise = np.random.normal(m... |
import time as utime
import json
import socket
import time
import paho.mqtt.client as mqtt
import json
from influxdb import InfluxDBClient
import sys
from time import ctime
from datetime import datetime
from datetime import timedelta
import pytz
import math
intvl_total = {}
intvl_count = {}
last_db_update_time = {}
p... |
#!/usr/bin/env python
import os
import sys
import re
import shutil
import tempfile
import subprocess
from itertools import groupby
from datetime import datetime
from collections import Counter
__version__ = "0.0.3"
###########
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class Error (Exce... |
import os
import torch
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import numpy as np
class Actor(torch.nn.Module):
def __init__(self, state, num_actions, action_bound, batch_size, layer_1=128, layer_2=128, lr=0.0001,use_mobileNet=False, checkpt='ddpg-actor... |
import psychopy.core
import psychopy.event
import psychopy.visual
import pandas as pd
import numpy as np
import psychopy.gui
import psychopy.sound
import os
import yaml
import json
from pathlib import Path
import random
# dummy data
filename = 'only_6_sorted_BDM_mock_data.csv'
df = pd.read_csv(os.path.abspath(filename... |
from dataset import dataSet
from models import *
from keras.callbacks import *
import matplotlib.pyplot as plt
import matplotlib
import itertools
import tensorflow as tf
import os.path
from keras.utils import generic_utils
def plot_confusion_matrix(cm, classes,
normalize=False,
... |
import math
from circuits.circuit_pack import *
"""
GOA算法终止条件
GOA算法终止条件1- GOA前后两次迭代的全局最优解之间,前后两代每个x的误差 < 1%
全局最优解的最后两个list
GOA算法终止条件2- Chi-Squared在GOA前后两次迭代的全局最优解之间,将元件参数带入阻抗数据计算得到的Chi-Squared,相差 < 1e-5
**fre_list or w_list + ECM-num ==> Z-prediction
Z-Raw
GOA算法终止条件3- 超过最大迭代次数
... |
"""
Copyright 2009-2020 National Technology and Engineering Solutions of Sandia,
LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government
retains certain rights in this software.
Sandia National Laboratories is a multimission laboratory managed and operated
by National Technology and Engineering ... |
#!/usr/bin/python3
import time
import typing
from queue import Queue
from socket import socket, timeout
from threading import Lock, Thread
from data import *
from logic import *
from matchmaking import BroadcastGame
class NetworkingReceiver(Thread):
"""
Se charge de récupérer les actions des clients et de le... |
import logging
import urllib.parse
import uuid
from multiprocessing import context
from django.conf import settings
from django.contrib.auth import authenticate
from django.http import (HttpResponseForbidden,
HttpResponseRedirect)
from django.shortcuts import render
from django.utils.translati... |
import importlib
import os
import socket
import sys
import time
import numpy as np
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from datetime import datetime
from utils import provider
from Parameters import Parameters
from utils.Dataset_hdf5 i... |
import logging
import os
import re
import openpyxl
import pandas as pd
from Configs import getConfig
config = getConfig()
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
log.setLevel(getattr(logging, config.LOG_LEVEL))
def parse_targets(ttd_target_download_file):
pattern = re.compile(... |
'''
Some script functions are derived and modified based on the sample tutorials-ballons.py in the repo
Credit should be given to the Repo owner Matterport, Inc
honour the original author:
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
tutorial originally Written by <NAME>... |
import os
import shutil
import pytest
from pathlib import Path
from subprocess import check_call, check_output, CalledProcessError
import numpy as np
from pyrate.core import config as cf
from tests.common import (
assert_same_files_produced,
assert_two_dirs_equal,
manipulate_test_conf,
TRAVIS,
PYTHO... |
# Copyright
# 2019 Department of Dermatology, School of Medicine, Tohoku University
#
# 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/LICENS... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from preprocessor import Preprocessor #importing task1 file
from character import CharacterAnalyser #importing task2 file
from word import WordAnalyser #importing task3 file
from visualiser import AnalysisVisualiser # importing task4 file
import sy... |
#!/usr/bin/env python
import math
import logging
import subprocess as sp
import os
from contextlib import contextmanager
import sys
from argparse import ArgumentParser
from typing import Optional, Callable, Hashable, Tuple, Iterable
import re
import datetime as dt
from tqdm import tqdm
import networkx as nx
logger = ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from sccl.algorithm import *
from sccl.ncd_reduction import wrap_try_ncd_reduction
from z3 import *
from collections import defaultdict
def _start(chunk, rank):
return Int(f'start_{chunk}_at_{rank}')
def _end(chunk, rank):
return Int(f... |
#!/usr/bin/python
"""
Code taken from SmartMeshSDK. The origin code was modified.
Copyright (c) 2012, Dust Networks
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code m... |
def normal(): return dict(mathvariant="normal")
_ELEMENTS = [
(1, r"H", "Helium"), # ^1H
(1, r"D", "Deuterium"), # ^2H
(1, r"T", "Tritium"), # ^3H
(2, r"He", "Helium"),
(3, r"Li", "Lithium"),
(4, r"Be", "Beryllium"),
(5, r"B", "Boron"),
(6, r"C", "Carbon"),
(7, r"N", "Nitrogen"),... |
import logging
from asyncio import Future, iscoroutinefunction
from typing import Any, AsyncIterable, AsyncIterator, Awaitable, Callable, List, Optional, Tuple, TypeVar, cast
from expression.core import MailboxProcessor, TailCall, tailrec_async
from expression.system import AsyncDisposable, CancellationTokenSource, Di... |
"""
Measure node attribute
Crate: 2014/03/17
Check: 2016/05/01
@auth: <NAME>
"""
# ###
# 1.Import packages
# ###
import networkx as nx
import numpy as np
# import math
import sys
import time
# Import modules
import util.read_write_edgelist as elrw
import util.read_write_pairvalue as pvrw
import util.read_write_pos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.