text stringlengths 3.07k 22.1k |
|---|
# Copyright 2017 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... |
from flask import Flask, flash, redirect, render_template, request, url_for, send_file, Blueprint
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, current_user
from sqlalchemy import create_engine
from marshmallow import fiel... |
#! /usr/bin/env python3
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(current_dir, '..'))
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import torch
from torch.optim import SGD
from torch.utils.data import DataLoade... |
import load_data
from ete3 import Tree, faces, TreeStyle, COLOR_SCHEMES, TextFace
import numpy as np
schema_names = COLOR_SCHEMES.keys()
def abbreaviate_name(name):
names = name.split(' ')
abr_name = names[0][0]+'.'
if len(names) > 1:
for i in range(1,len(names)):
abr_name += ' '+nam... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
import numpy as np
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
from veriloggen import *
import veriloggen.thread... |
# -*- coding: utf-8 -*-
"""SuperDARN data support for grdex files(Alpha Level!)
Parameters
----------
platform : string
'superdarn'
name : string
'grdex'
tag : string
'north' or 'south' for Northern/Southern hemisphere data
Note
----
Requires davitpy and davitpy to load SuperDARN files.
Uses environment v... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Imports
import signal
import argparse
import logging
import socket
import re
import time
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from influxdb_client.rest import ApiException
# Logging
logging.basicCo... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as stats
from statsmodels.stats.proportion import proportions_ztest as z_test
from statsmodels.stats.proportion import proportion_effectsize
from statsmodels.stats.power import tt_ind_solve_power
def show_available_functions()... |
# -*- coding: utf-8 -*-
# Copyright 2017-2018 Orbital Insight Inc., all rights reserved.
# Contains confidential and trade secret information.
# Government Users: Commercial Computer Software - Use governed by
# terms of Orbital Insight commercial license agreement.
"""
Created on Tue Jun 25 20:55:47 2019
Everything ... |
# This is a script that analyses the multimode simulation results.
# This simulates a RZ multimode periodic plasma wave.
# The electric field from the simulation is compared to the analytic value
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pywarpx import picmi
const... |
"""
This module defines a token.
A token is made of a type and a lexeme. The lexeme is considered immutable, and
we use here an Enum to describe the types.
"""
from __future__ import annotations
from enum import Enum
from typing import Optional
from lyth.compiler.error import LythError
from lyth.compiler.error impor... |
"""
Support for Hyperion remotes.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.hyperion/
"""
import json
import logging
import socket
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR... |
import json
import math
from collections import defaultdict
from datetime import datetime
import random
import boto3
import requests
def single_regression(x, y):
n = len(x)
x_sum = sum(x)
y_sum = sum(y)
xy_sum = sum(x * y for x, y in zip(x, y))
sqx_sum = sum(x ** 2 for x in x)
slope = (n * xy... |
#!/usr/local/bin/python
import codecs
import glob
import os
import platform
import subprocess
import sys
import jinja2
# Utility functions
def log(txt):
print(txt, file=sys.stderr)
def error(txt):
log(txt)
sys.exit(2)
def convert(src, dst, environ):
"""Generate a file from a template
Args:
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# Copyright (c) 2009-2021 fem2ufo
# Python stdlib imports
from array import array
from collections.abc import Mapping
from math import isclose, dist
from typing import NamedTuple, Tuple, List, Iterator, Iterable, Union, Dict
# package imports
#from steelpy.process.units.main import Units
from steelpy.f2uModel.mesh.op... |
#!/usr/bin/env python3
## Installation instructions: https://github.com/nobodysu/zabbix-mini-IPMI ##
checkStandby = 'no' # whether to check disks in STANDBY mode or not, 'yes' or 'no'
# if 'Update interval' is less than OS setting for STANDBY disks - it will never enter this state
ctlPath = r... |
import logging
import numpy as np
import dill
from collections import defaultdict
from skipthought import utils
class Batch:
def __init__(self, data, pad_value, go_value, eos_value):
"""Class which creates batch from data and could be passed into
SkipthoughtModel._fill_feed_dict_* methods.
... |
import torch
from torch_geometric.data import DataLoader
import torch.optim as optim
import torch.nn.functional as F
from gnn import GNN
import argparse
import time
import numpy as np
### importing OGB
from ogb.graphproppred import PygGraphPropPredDataset, Evaluator
multicls_criterion = torch.nn.CrossEntropyLoss()
... |
from contextlib import closing
from pathlib import Path
from typing import Dict, List, Tuple, Type, Union
# from sqlalchemy_utils import create_view
import pandas as pd
import sqlalchemy as sa
from sqlalchemy import (
BigInteger,
Column,
Date,
DateTime,
ForeignKey,
Integer,
Numeric,
Str... |
"""
(2+1)D Navier-Stokes equation + Galerkin Transformer
MIT license: Paper2394 authors, NeurIPS 2021 submission.
"""
from .utils import *
from .utils_ft import *
from .ft import *
from .layers import *
from .model import *
import h5py
class NavierStokesDatasetLite(Dataset):
def __init__(self,
d... |
from __future__ import annotations
import asyncio
import code
import functools
import os
import sys
from importlib import import_module
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, TYPE_CHECKING
import click
from .__about__ import __version__
from .helpers import get_debug_fla... |
#!/usr/bin/env python3
from myXml import Xml
def cleanCoords(sCoords:str="") -> str:
sCoords = sCoords.replace(":","")
sCoords = sCoords.replace("°","")
sCoords = sCoords.replace("'","")
sCoords = sCoords.replace("’","")
sCoords = sCoords.replace("\"","")
sCoords = sCoords.replace(" N","N")
... |
#!/usr/bin/env python3
# Copyright 2019 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
# See License in the project root for license information.
# To be able to easily parse command-line arguments
import argparse
# To be able to easily pass around the available endpoints and parameters
from... |
#!/usr/bin/env python
"""Test NIRSpec transformations internally and against the test dataset delivered by IDT.
Authors
-------
<NAME>
"""
import os
from astropy.io import fits
from astropy.table import Table
import copy
import numpy as np
import pylab as pl
# import pytest
from ..constants import JWST_TEMP... |
from math import cos, pi, sin, sqrt
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from orbsim.r3b_2d import *
def orbitplot2d(completed_path, psi=None, filepath=".", title=None, multi_mode=False):
"""
input: output of launch_sim, its launch parameters, and an op... |
import numpy as np
import matplotlib.pyplot as plt
import sys
import scipy.spatial as sp
import shapely.geometry as sg
from matplotlib import colors as mcolors
color_dict = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# colors = [x for x in color_dict if x not in {"w",'aliceblue','antiquewhite','azure','beige','bis... |
import json
import logging
import os
try:
from urllib2 import HTTPError
except ImportError:
from urllib.error import HTTPError
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.core.paginator import Paginator, EmptyPage, PageNotAnIn... |
import os
import sys
from argparse import ArgumentParser
from glob import glob
from . import stylefx
from . import jtplot
# path to local site-packages/jupyterthemes
package_dir = os.path.dirname(os.path.realpath(__file__))
modules = glob(os.path.dirname(__file__) + "/*.py")
__all__ = [os.path.basename(f)[:-3] for f i... |
from django.core.exceptions import ImproperlyConfigured
from django.db.models import F, fields
from django.db.models.functions import Cast, Coalesce
from django.utils.translation import gettext_lazy as _
from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting
from .utils import (
Fallbac... |
from wpc import db, app, login_manager
from wpc.utils import requests_get_with_retries
from flask.ext.login import UserMixin, current_user
from sqlalchemy.orm.properties import ColumnProperty
import humanize
from datetime import datetime, timedelta
@login_manager.user_loader
def load_user(reddit_username):
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
import json
import os
import pickle
import tensorflow as tf
from tensorflow.gfile import Exists as exists
from tensorflow.gfile import MakeDirs as makedirs
from vocabulary import Vocab
... |
# -*- coding: utf-8 -*-
"""
Script to perform nuisance regression and timeseries extraction on CBS data
USAGE: python3 nuisRegr.py [--mask] folder
The script first lists all functional runs for which we have EPI data
and truncated confounds file. Then it applies
nilearn's NiftiMasker to each which calls signal.clean ... |
"""
Utility functions for
- building and importing modules on test time, using a temporary location
- detecting if compilers are present
"""
import os
import sys
import subprocess
import tempfile
import shutil
import atexit
import textwrap
import re
import pytest
from numpy.compat import asbytes, asstr
from numpy.te... |
"""
The link resolution is as follows:
We always have two components: the base and the link
If the link is a url or absolute path it is what is used to fetch the data.
If the link is a relative path it is combined with the base and that is what is
used to fetch data
"""
# Copyright (c) 2020 <NAME>. See LICENSE
impo... |
#! /usr/bin/env python
"""Strain whitening script to be used for development of submission to the
MLGWSC-1 mock data challenge. Written by <NAME>.
"""
# Import modules
from argparse import ArgumentParser
import logging
import h5py
from tqdm import tqdm
import os.path
import numpy as np
from pycbc.psd import ... |
from copy import copy
import numpy as np
import pymc as pm
np.seterr(divide="ignore")
from sys import stdout
import hddm
from scipy.stats import scoreatpercentile
from time import time
from operator import attrgetter
def check_model(model, params_true, assert_=False, conf_interval=95):
"""calculate the posterio... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import http
import re
import infra.e2e_args
import infra.network
import infra.consortium
import ccf.proposal_generator
from infra.proposal import ProposalState
import suite.test_requirements as reqs
from loguru impor... |
# This file is part of the CERN Indico plugins.
# Copyright (C) 2014 - 2021 CERN
#
# The CERN Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License; see
# the LICENSE file for more details.
import json
import requests
from sqlalchemy.orm import joinedload,... |
#!/usr/bin/env python
# wujian@2018
import logging
import math
import os
import warnings
import librosa
import numpy as np
import scipy.signal as ss
# using wf to handle wave IO because it support better than librosa
import soundfile as sf
MAX_INT16 = np.iinfo(np.int16).max
EPSILON = np.finfo(np.float32).eps
default... |
"""
File input
==========
File input is handled by the *Load new system* box on the *Input* tab of the main toolbar.
Initially the file format will try to be determined automatically, however in the case of
ambiguity a dialog will popup asking the user for input.
File formats are defined in the *file_formats.IN* file... |
# -*- coding: utf-8 -*-
from cms.exceptions import NoHomeFound
from cms.models import Title, Page, PageModerator
from cms.models.moderatormodels import MASK_PAGE, MASK_CHILDREN, \
MASK_DESCENDANTS, PageModeratorState
from cms.utils.permissions import get_user_sites_queryset
from django.conf import settings
from dja... |
from __future__ import print_function
from pixell import sharp
import matplotlib
matplotlib.use('Agg')
from pixell import enmap,curvedsky,wcsutils,reproject
import numpy as np
import itertools,yaml,pickle,os,sys
import matplotlib.pyplot as plt
"""
This script generates a set of reference values against which
pixell t... |
import unittest
import time
from collections.abc import Iterable
import numpy as np
import openmdao.api as om
from openmdao.utils.mpi import MPI
from openmdao.utils.array_utils import evenly_distrib_idxs, take_nth
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
try:
from parameterized i... |
"""
powerful time, date, and datetime module
useful in development of programs that
work with the concept of time
upgraded version of time.py and datetime.py
%Y - year: 2022
%m - month: [01, 12]
%d Day of the month as a decimal number [01,31].
%H Hour(24-hour clock) a... |
# -*- coding: utf-8 -*
'''
匹配content、comment并初步清理数据
用于作词云wc.py、地图graph.py、Tf-idf文本聚类cluster_tfidf、Word2Vec文本聚类cluster_w2v
将每个分类关键词形式变为:
[
[url1, content1原文, [content1分词],[comment1],...,[comment_n]],
[url2, content2原文, [content2分词],[comment1],...,[comment_m]],
...
]
'''
import codecs
import json
import pandas as ... |
"""
parameter_store.py
AWS Parameter Store help methods - currently extending boto3
Note:
Credentials are required to communicate with AWS.
aws cli profile can be passed in using --profile, or
the following ENVIRONMENT VARIABLES can be set before
running this script:
AWS_ACCESS_KEY_ID
... |
# -*- coding: utf-8 -*-
#
# test_basics.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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, or... |
import json
import logging
import math
import nlp
_CITATION = """\
@ONLINE {wikidump,
author = {Wikimedia Foundation},
title = {Wikimedia Downloads},
url = {https://dumps.wikimedia.org}
}
"""
_DESCRIPTION = """\
Wikipedia version split into plain text snippets for dense semantic indexing.
"""
_LICE... |
"""
Adaptation of the chainerRL DQN example
"""
import argparse
import os
import sys
import shutil
from chainer import optimizers
from gym import spaces
import numpy as np
import chainerrl
from chainer.optimizer_hooks import GradientClipping
from chainerrl.agents.double_dqn import DoubleDQN as DDQN
from chainerrl imp... |
'''
支持ai因子,只能做多,不支持多颗粒度时间混合
'''
import backtrader as bt
from .import sizerutil as su
import importlib
# import time
# import backtrader.indicators as btind
class iStrategyBase(bt.Strategy):
params = dict(rule=dict(), sct=0, htrade=dict())
def __init__(self):
# # todo 传进来的数据分成,{'datas':[], 'middle':[],... |
import time
import sys
import datetime
import copy
from mongoengine import DoesNotExist
from requests import RequestException
from requests.auth import HTTPBasicAuth
from issueshark.backends.basebackend import BaseBackend
import logging
import requests
import dateutil.parser
from pycoshark.mongomodels import *
log... |
import json
import requests
from tqdm import tqdm
import os
def get_file_from_modac(fname, origin):
""" Downloads a file from the "Model and Data Clearning House" (MoDAC)
repository. Users should already have a MoDAC account to download the data.
Accounts can be created on modac.cancer.gov
Parame... |
# -*- coding: utf-8 -*-
"""Transforming arrays of Mantarray data throughout the analysis pipeline."""
from typing import Any
from typing import Dict
from typing import List
from typing import Union
import uuid
from nptyping import NDArray
import numpy as np
from scipy import signal
from .constants import ADC_GAIN
fro... |
# -----------------------------------------------------
# -*- coding: utf-8 -*-
# @Time : 8/9/2018 4:34 PM
# @Author : sunyonghai
# @Software: ZJ_AI
# -----------------------------------------------------
import xml.etree.ElementTree as ET
import os
import prettytable as pt
import numpy as np
def add_label_dict(xm... |
# from spikeforest import spikewidgets as sw
import mlprocessors as mlpr
import json
import spikeextractors as si
import spiketoolkit as st
import pandas as pd
from .sfmdaextractors import SFMdaSortingExtractor
from .sortingcomparison import SortingComparison
# new method (in progress) that uses spiketoolkit
class G... |
import torch
import argparse
import triplet_utils
import random
import numpy as np
import json
import typing
import os
from torch.utils.data import DataLoader
import sys
from tqdm import tqdm
from triplet_evaluation import ranking_and_hits
from TRIPLET_CONSTANTS import DATA_DIR, BERT_IDS
# import contextlib
from torch.... |
from __future__ import division, print_function, unicode_literals
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import cocos
from coco... |
# Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
"""
Functions to process tweet meta data
expand URLs, add counts of urls/hashtags/mentions, and list of hashtags/mentions.
"""
import sys
from datetime import datetime, timedelta
import time
from email.utils import parsedate_tz
import simplejson
import re
import hashlib
import string
from collections import de... |
# -*- coding: utf-8 -*-
import logging
import sys
import crochet
import fido.exceptions
import requests.structures
import six
import twisted.internet.error
import twisted.web.client
import typing
from bravado_core.operation import Operation
from bravado_core.response import IncomingResponse
from yelp_bytes import to_b... |
'''
Module to compute threshold type policies
'''
import pickle
import numpy as np
import multiprocessing as mp
import datetime as dt
from collections import defaultdict
from interventions import create_intLevel, form_interventions
from itertools import product
from SEIYAHRD import fix_policy, simulate_p
from vacci... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import math
import time
import json
import sqlite3
from werkzeug.wrappers import Response
from werkzeug.exceptions import PreconditionFailed
if sys.version_info < (2, 7):
import __builtin__
class Float(float):
def __new__(self, x, i):
... |
"""
tdop.py - Library for expression parsing.
"""
from _devbuild.gen.id_kind_asdl import Id, Id_t
from _devbuild.gen.syntax_asdl import (
arith_expr, arith_expr_e, arith_expr_t,
arith_expr__VarRef, arith_expr__Binary, arith_expr__ArithWord,
sh_lhs_expr, sh_lhs_expr_t,
word_t,
)
from _devbuild.gen.types... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
... |
import pulp
import torch
from addnn.controller.proto.controller_pb2 import Node
from addnn.profile.layer_profile import LayerProfile
from addnn.serve.placement.placement import NodeIndex, Placement, get_throughput_matrix, get_latency_matrix
from addnn.serve.placement.strategy import Strategy
from typing import Dict, Li... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import itertools
import math
from collections import defaultdict
import numpy as np
import torch
from PIL import Image
from toolz import compose, curry
from toolz import partition_all
from torch.utils.data import Dataset
from torchvision.dataset... |
"""
In large part lifted from
https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py
but with 1d convolutions and arbitrary kernel sizes
"""
from typing import Callable, List, Literal, Optional
import torch
import torch.nn as nn
from torch import Tensor
def convN(
in_planes: int,... |
#!/usr/bin/env python
"""utils.py: module is dedicated to utility methods to simulate algorithms."""
__author__ = "<NAME>."
__copyright__ = "Copyright 2020, SuperDARN@VT"
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "<NAME>."
__email__ = "<EMAIL>"
__status__ = "Research"
import matplotl... |
#!/usr/bin/env python3
import logging
import sys
from . util import Settings, Stats, timeout, parse_settings, format_program
from . asp import ClingoGrounder, ClingoSolver
from . tester import Tester
from . constrain import Constrain
from . generate import generate_program
from . core import Grounding, Clause
class O... |
import json
import shutil
from pathlib import Path
from distutils.version import StrictVersion
def parse_new_types(release, item_type):
new_items = []
if release.get(item_type):
for key,value in release[item_type].items():
if value["Type"] == 'New':
new_items.append(f"- [{k... |
# Copyright 2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# -*- coding: utf-8 -*-
import requests as r
import mimetypes
from werkzeug import secure_filename
from flask.ext.login import login_required, current_user
from flask import Response, Blueprint, render_template, url_for, redirect, make_response, request, jsonify, flash, current_app
from .forms import NewSiteForm, Uplo... |
import pickle
import random
from collections import defaultdict
from pathlib import Path
from datasets.dataset_dict import DatasetDict
from loguru import logger
from natsort import natsorted
from textsearch import TextSearch
import datasets
import utils
from temporal_text_dataset import TemporalText
def iterdir_one... |
"""
製作者:TODA
学習スクリプト
設定パラメーターの意味はsetting_loader.pyを参照
"""
import os
import shutil
import wave
import chainer
import numpy as np
from vrc_project.model import Discriminator, Generator
from vrc_project.seq_dataset import SeqData
from vrc_project.updater import CycleGANUpdater
from vrc_project.voice_to_dataset_cycle impor... |
from kafka import KafkaProducer
from kafka import KafkaConsumer
from kafka import KafkaAdminClient
from operator import itemgetter
import json
from json import dumps
from json import loads
import time
import requests
import GE_GSCH_most_define as mostDefine
'''
{'requestID': 'req-f6720a0e-e3df-455a-825d-f8c80cedc2d9... |
"""Script to compare different methods to extract profiles:
calc flux
AG, April 9, 2013
AG, April 25, 2013
AG, Jan 11, 2016"""
import numpy as np
import mcdiff
from mcdiff.outreading import read_F_D_edges, read_Drad
from mcdiff.utils import construct_rate_matrix_from_F_D
import matplotlib.pyplot as plt
##### UNITS ##... |
import json
from django import forms
from django import urls
from django.template import RequestContext, loader
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_to_login
from django.views.generic import... |
from typing import List, Dict
from overrides import overrides
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import DatasetReader, Instance
from allennlp.data.tokenizers import SpacyTokenizer
from allennlp.models import Model
from allennlp.predictors.predictor import Predictor
from allennlp.da... |
# Grupo:
# Nome: <NAME> NUSP: 10692012
# Nome: <NAME> NUSP: 10734387
# Nome: <NAME> NUSP: 10294943
# Nome: <NAME> NUSP: 10801169
from __future__ import print_function
import numpy as np
from ortools.linear_solver import pywraplp
import matplotlib.pyplot as plt
# A galaxy, with name and position in... |
import sys
import os
import re
from collections import defaultdict
TK_RE = re.compile(
r"""[\s,]*(~@|[\[\]{}()'`~^@]|"(?:[\\].|[^\\"])*"?|;.*|[^\s\[\]{}()'"`@,;]+)"""
)
INT_RE = re.compile(r"-?[0-9]+$")
FLOAT_RE = re.compile(r"-?[0-9][0-9.]*$")
class Symbol(str):
pass
class State:
def __init__(self):
... |
import numpy as np
from numba import njit
from scipy import sparse
from sklearn.utils import check_array
def solver_path(X, y, datafit, penalty, eps=1e-3, n_alphas=100, alphas=None,
coef_init=None, max_iter=20, max_epochs=50_000,
p0=10, tol=1e-4, use_acc=True, prune=0,
... |
# Bots&Player.py
import pygame
import numpy as np
import random as rd
import Colisao as C
from tkinter import *
FPS = 60
Angle = (np.pi / 4)
def Randc(): # Randomiza uma Cor
""" Randomiza uma Cor """
return rd.uniform(0, 255)
#### Classes ####
... |
# Unit test case for testing interfaces and adaptation.
#
# Written by: <NAME>
#
# Date: 4/10/2007
#
# Copyright (c) 2007, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the... |
""" Functional modules for various deep network architectures."""
import numpy as np
from torch import nn
from .core import Block
from ..layers import Conv, BatchNorm, Combine
from ..utils import get_shape, get_num_dims, get_num_channels
class PyramidPooling(nn.Module):
""" Pyramid Pooling module
<NAME>. et ... |
"""
MultiContainerInterface
========================
This is a guide to creating custom API classes with the ``MultiContainerInterface`` class.
"""
###############################################################################
# Introduction
# ------------
# The :py:class:`~hdmf.container.MultiContainerInterface` c... |
import time
from retrying import retry
import pytest
from cosmo_tester.framework.test_hosts import Hosts, VM
BASE_DN = 'dc=cloudifyad,dc=test'
def test_ad_with_aio(windows_ldap_tester, logger):
mgr, ad_host = windows_ldap_tester
users = {
'DefUser': {'password': '<PASSWORD>!',
... |
# -*- coding: utf-8 -*-
from common.base_test import BaseTest
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import check_that, greater_than_or_equal_to, has_entry, is_integer
SUITE = {
"description": "Method 'get_asset_holders_count'"
}
@lcc.prop("main", "type")
@lcc.prop("positive", "type")
@... |
import os
import sys
import argparse
from pprint import pprint
from tabulate import tabulate
def calculate_table_size(input_dir):
case_table_size = {}
for fname in os.listdir(input_dir):
if fname.endswith('.rkt') and (not fname.startswith("__")):
case_name = fname.split(".")[0]
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# PythonTidyWrapper.py
# 2007 Mar 06 . ccr
# 2010 Sep 08 . ccr . Add JAVA_STYLE_LIST_DEDENT.
# 2010 Mar 16 . ccr . Add KEEP_UNASSIGNED_CONSTANTS and PARENTHESIZE_TUPLE_DISPLAY.
# 2007 May 25 . ccr . Changed MAX_SEPS. Add WRAP_DOC_STRINGS and DOC_TAB_REPLACEMENT.
# 2007 May 0... |
# -*- coding:utf-8 -*-
import datetime
import hmac
import os
import base64
from hashlib import sha1 as sha
import random
import re
import time
from flask import request
from advancer.models.base import db
__author__ = 'bliss'
OSS_HOST_LIST = ["aliyun-inc.com", "aliyuncs.com", "alibaba.net", "s3.amazonaws.com"]
SELF_... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Quest and Execution for running a test in Swarming.
This is the only Quest/Execution where the Execution has a reference back to
modify the Quest.
"""
i... |
import sqlite3
import argparse
import trueskill
import subprocess
import pdb
import os
##############
# Parameters #
##############
class GlobalParameters:
def __init__(self, localPathToGame=r"/test-game.sh", localPathToDB=r"./mathecamp-games.sqlite",
localPathForOutputs=r"/output/"):
se... |
'''
FILENAME: train_cgan.py
AUTHORS: <NAME>
START DATE: 2022.02.16/23:52
CONTACT: <EMAIL>
'''
import argparse
import os
from sqlite3 import Row
from tqdm import tqdm
import torch
import torchvision
import torch.nn as nn
from torch.nn.functional import one_hot
from torch.optim import Adam
fr... |
import io
import numpy as np
import pytest
from pandas.compat._optional import VERSIONS
from pandas import (
DataFrame,
date_range,
read_csv,
read_excel,
read_feather,
read_json,
read_parquet,
read_pickle,
read_stata,
read_table,
)
import pandas._testing as tm
from pandas.util... |
import json
from typing import Tuple
import torch
from spert import util
from spert.input_reader import BaseInputReader
def convert_predictions(batch_entity_clf: torch.tensor, batch_rel_clf: torch.tensor,
batch_rels: torch.tensor, batch: dict, rel_filter_threshold: float,
... |
import torch.nn as nn
import numpy as np
import math
from torch.nn.utils import spectral_norm
class Generator(nn.Module):
"""Generator.
deconv -> BN -> Relu -> ... deconv -> Tanh
"""
def __init__(self, image_size=64, z_dim=100, channel=3, conv_dim=64):
super(Generator, self).__init__()... |
import json
import os
from flask import Flask
from flask import request
from aog import conv
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/', methods=['POST'])
def fullfillment():
req = request.get_json(silent=True, force=True)
print("Reques... |
import sys
import os
import sys
import re
import os.path
import platform
import subprocess
def replace(filename, pattern, replacement):
f = open(filename)
s = f.read()
f.close()
s = re.sub(pattern, replacement, s)
f = open(filename, 'w')
f.write(s)
f.close()
dbms_cfg = ["config-std.h", "c... |
#! /usr/bin/python3
"""
Datastreams are identified by the address that publishes them, and referenced
in transaction outputs.
For CFD leverage, 1x = 5040, 2x = 10080, etc.: 5040 is a superior highly
composite number and a colossally abundant number, and has 1-10, 12 as factors.
All wagers are in XCP.
"""
import str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.