text stringlengths 3.07k 22.1k |
|---|
import numpy as np
import pandas as pd
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from mushroom_rl.approximators.parametric.torch_approximator import TorchApproximator
from mushroom_rl.utils.torch import zero_grad
class Network_for_Reco(nn.Module):
... |
"""Order-preserved, attribute-accessible dictionary object for YAML files
"""
# -*- coding: utf-8 -*-
import yaml
import yaml.constructor
import collections
class YAMLDict(collections.OrderedDict):
'''
Order-preserved, attribute-accessible dictionary object for YAML settings
Improved from:
https:... |
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, TypeVar
from typing_extensions import final
from returns.functions import identity
from returns.primitives.container import BaseContainer
from returns.primitives.types import Immutable
if TYPE_CHECKING:
# We need this condition to make sure Pyth... |
import mido
from Queue import Queue
from threading import Thread
import logging
import sys
import pygame
import math
import random
# pygame clock init
clock = pygame.time.Clock()
# pygame init
pygame.display.init()
# pygame setup
# (6,0) = all good
print(pygame.init())
import background
import foreground
import fon... |
MAX_CONTENT_LENGTH = 1000
MAX_LINE_LENGTH = 500
MATE_SCORE = 10000
MATE_LIMIT = MATE_SCORE * 0.9
WINNING_MOVE_LIMIT = 1000
DOUBLE_EXCLAM_LIMIT = 500
EXCLAM_LIMIT = 350
PROMISING_LIMIT = 250
INTERESTING_LIMIT = 150
DRAWISH_LIMIT = 80
LICH_API_GAMES_EXPORT = "games/export"
#LICH_API_GAMES_EXPORT = "api/games/user"
def... |
from signaturelib import services
import getpass
import os.path
from os import path
user = None
def request_login():
global user
print("Welcome back!")
username = input("Please enter your username: ")
password = getpass.getpass(prompt="Please enter your password: ", stream=None)
user = services.... |
import datetime as dt
import discord
from cmdClient import cmd
from cmdClient import checks
from utils import interactive # noqa
from Timer import Timer
@cmd("history",
group="Registry",
desc="Display a list of past sessions in the current guild.",
aliases=['hist'])
@checks.in_guild()
async def cmd_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from . import solidcookies as scookies
from . import solidhttp as shttp
from . import soliddom as sdom
import re
import os
__version__ = '0.7.7'
__license__ = 'MIT'
class UserAgent:
CHROME_WIN7_64 = (
"Mozilla/5.0 (Windows ... |
## @package lstm_benchmark
# Module caffe2.python.lstm_benchmark
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import cnn, workspace, core, utils, rnn_cell
impo... |
#coding: utf-8
from __future__ import unicode_literals
import logging
import functools
import itertools
import os
import glob
import sys
import json
import unicodedata
import zipfile
from lxml import etree, isoschematron
try:
import pygments # NOQA
from pygments.lexers import get_lexer_for_mimetype
fro... |
#!/usr/bin/python
"""
create Autosupport module to enable, disable or modify
"""
# (c) 2018, NetApp, Inc
# 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 = {'metadata_ver... |
# This Python file uses the following encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import next
import re
import time as timenow
import math
from datetime import datetime, tzinfo, timedel... |
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from statsmodels.tsa.seasonal import seasonal_decompose
from io import BytesIO
from PIL import Image
from ta.volatility import BollingerBands
from ta.momentum import RSIIndicator
from ta.trend imp... |
#
# Python script to get the list of virtual addresses in an Identity Pool
#
# _author_ = <NAME> <<EMAIL>>
# _version_ = 0.1
#
#
# Copyright (c) 2018 Dell EMC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
import numpy as np
import matplotlib.pyplot as pyplot
import h5py
import scipy
from PIL import Image
from scipy import ndimage
# extras for debugging
import math
# dataset loader
import utils
# dataset parameters
training_path = './training_data' # path of training data containing class sub-directories (image file... |
"""
Create a wheel (.whl) distribution.
A wheel is a built archive format.
"""
import csv
import hashlib
import os
import subprocess
import shutil
import sys
import re
from email.generator import Generator
from distutils.core import Command
from distutils.sysconfig import get_python_version
from distutils import log ... |
# This script is the one to launch at every release to compute the full set of stats and changes between this and the previous release
# The script can also be used to compute the changes between any two releases by selecting older go-stats and OBO files
import json
import sys, getopt, os
import go_stats
import go_on... |
import collections
import glob
import logging
import os
import re
import numpy as np
import scipy.stats
import torch
NUMPY_RANDOM = np.random
class Identity(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x
def pos_inf(dtype):
return torch.finfo(dt... |
"""Completers for Python code"""
import re
import sys
import inspect
import builtins
import importlib
import collections.abc as cabc
import xonsh.tools as xt
import xonsh.lazyasd as xl
from xonsh.completers.tools import get_filter_function
@xl.lazyobject
def RE_ATTR():
return re.compile(r"([^\s\(\)]+(\.[^\s\(\)... |
import pandas as pd
from pathlib import Path
from time import perf_counter
from utils import get_document_store, get_retriever, index_to_doc_store, load_config
from haystack.preprocessor.utils import eval_data_from_file
from haystack import Document
import pickle
import time
from tqdm import tqdm
import logging
import ... |
import os
import scipy
import numpy as np
import tensorflow as tf
import scipy.misc as misc
import random
def load_mnist(batch_size, is_training=True):
path = os.path.join('data', 'mnist')
if is_training:
# fd = open(os.path.join(path, 'train-images-idx3-ubyte.gz'))#打开数据文件,这里后缀需要注意修改
fd = ope... |
## activation_functions.py
##
## Definitions of ReLU, leaky-ReLU and sigmoid family
## activation functions and their upper and lower bounds
##
## Copyright (C) 2018, <NAME> <<EMAIL>> and contributors
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
#... |
# -*- coding: utf-8 -*-
"""
Usage :
> python bsgs_hybrid_dll_gmp.py -pfile test_pubkeys.txt -b FULLbpfile.bin -bl Big5GB_dll_bloom.bin -n 80000000000000 -keyspace 800000000000000000000000000000:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
> python bsgs_hybrid_dll_gmp.py -pfile Pub50.txt -b FULLbpfile.bin -bl Big5GB_dll_bloom.b... |
# -*- coding: utf-8 -*-
"""
Functions for generating group-level networks from individual measurements
"""
import numpy as np
from scipy.sparse import csgraph
from sklearn.utils.validation import (check_random_state, check_array,
check_consistent_length)
from . import utils
def... |
# -*- coding: utf-8 -*-
'''
Junos Syslog Engine
==========================
.. versionadded:: 2017.7.0
:depends: pyparsing, twisted
An engine that listens to syslog message from Junos devices,
extract event information and generate message on SaltStack bus.
The event topic sent to salt is dynamically generated acc... |
'''It is a sligtly modified version of the official implementation of
"Scale-steerable filters for the locally-scale invariant convolutional neural network"
Paper: https://arxiv.org/pdf/1906.03861.pdf
Code: https://github.com/rghosh92/SS-CNN
MIT License
Copyright (c) 2020 <NAME>, <NAME>
'''
import math
import numpy a... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import numpy as np
import os
import cv2
import subprocess
def strokeline_lookup():
'''
the strokeline index of 68 points.
'''
Mouth = [[48, 49], [49, 50], [50, 51], [51, 52], [52, 53], [53, 54], [54, 55], [55, 56], [56, 57], \
[57, 58], [58, 59], [59,... |
import AddressMap
from ByteTools import *
import ModuleEnumerator
import PIDSearcher
import GameplayEnums
import MovelistParser
class SC6GameReader:
def __init__(self):
self.pid = -1
self.snapshots = []
self.p1_movelist = None
self.p2_movelist = None
... |
from seamless.core import (
context, cell, transformer, macro_mode_on
)
from seamless.core.structured_cell import StructuredCell
from silk import Silk
from pprint import pprint
import time
def progress(limit, delay, factor, offset):
import time
for n in range(limit):
return_preliminary(factor*n + o... |
"""Tests for sopel.cli.utils"""
from __future__ import generator_stop
import argparse
from contextlib import contextmanager
import os
import pytest
from sopel import config
from sopel.cli.utils import (
add_common_arguments,
enumerate_configs,
find_config,
get_many_text,
green,
load_settings,... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import pyro
import pyro.distributions as dist
import pyro.optim as optim
import pyro.poutine as poutine
from pyro.infer.autoguide import AutoDelta, AutoDiagonalNormal
from pyro.infer import Predictive, S... |
""" Module SQL Parser """
import csv
import sys
import parse
def aggregate_function(a, b, func):
"""Function to implement aggregate functions."""
return_val = False
if func == "max":
a[func] = max(a[func], b)
elif func == "min":
a[func] = min(a[func], b)
elif func == "sum":
... |
import hashlib
import logging as logger
import os
import zipfile
import time
from os.path import basename
from pathlib import Path
import pyminizip
import requests
from flask import Flask, request, jsonify
from src.config import Config
from src.services import (
MinioService,
FileService,
VirusTotalService,... |
"""
SCRIPT TO WRITE LAMMPS DATA FILES LMP & INP Files
FROM BOSS ZMATRIX
Created on Mon Sep 30 03:31:05 2017
@author: <NAME> <EMAIL>
@author: <NAME>
REQUIREMENTS:
BOSS (need to set BOSSdir in bashrc and cshrc)
Preferably Anaconda python with following modules
pandas
argparse
numpy
"""
from LigParGenPSP.BOSSReader imp... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2017,2018 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... |
# Copyright (C) 2013 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, ... |
from pubg_python import PUBG, Shard, Telemetry
import time, pprint, json
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from multiprocessing import Pool
import pymysql
import math
api = PUBG(apikey, Shard.PC_NA)
class PlayerPosition():
def __init__(self, ftime, position):
... |
from collections import defaultdict
import pickle
import os
import shutil
import torch
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader, SubsetRandomSampler, random_split
from torch.utils.tensorboard import SummaryWriter
import torchvision
from torchvision.models.resnet import ... |
import datetime
import numpy as np
import pandas as pd
import time
from dateutil.parser import parse
import keepa
ACCESSKEY = ''
k_api = keepa.Keepa(ACCESSKEY)
def get_info(items):
check_basic = ['asin', 'title', 'imagesCSV', 'categories','categoryTree', 'brand', 'color', 'size', 'packageLength', 'itemWidth',
... |
"""
Views
Full text search views.
"""
import logging
import math
import time
from datetime import date, datetime, timedelta
from types import SimpleNamespace
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.template import loader
from ahmia import utils
from ah... |
# *-* coding: utf-8 *-*
import sys
import operator
import hashlib
import re
from io import BytesIO
from pdfminer.pdfdocument import PDFDocument, PDFXRefStream
from pdfminer.pdfparser import PDFParser
from pdfminer.pdftypes import PDFObjRef
from pdfminer.psparser import PSKeyword, PSLiteral
from pdfminer.utils import i... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
# -*- coding: utf-8 -*-
'''
Manage LXD images.
.. versionadded:: 2019.2.0
.. note:
- `pylxd`_ version 2 is required to let this work,
currently only available via pip.
To install on Ubuntu:
$ apt-get install libssl-dev python-pip
$ pip install -U pylxd
- you need lxd installe... |
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import json
import logging
from pathlib import Path
import tempfile
import time
import threading
import boto3
import numpy as np
from PIL import Image
from pyproj import CRS, transform
import pyresample
import s3fs
import xarray as xr
from goes... |
# 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... |
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch import distributions
'''
Chapter 3. SARSA
Most code here is copied from SLM-Lab first and then modified to show a plain torch implementation.
'''
# This is a modified Categorical distribution class to... |
"""Order types used by Interactive Brokers."""
from dataclasses import dataclass, field
from typing import ClassVar, List, NamedTuple, Set
from eventkit import Event
from .contract import Contract, TagValue
from .objects import Fill, SoftDollarTier, TradeLogEntry
from .util import UNSET_DOUBLE, UNSET_INTEGER, datacl... |
# Copyright 2019 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 writing, ... |
import tempfile
import json
from unittest import TestCase, mock
from data_config import read_config_file
from keepercommander.params import KeeperParams
from keepercommander import cli, api
from keepercommander.subfolder import BaseFolderNode
class TestConnectedCommands(TestCase):
@classmethod
def setUpCla... |
# Omid55
from __future__ import print_function
import numpy as np
import pandas as pd
import math
import seaborn as sns
import sklearn as sk
import matplotlib.pyplot as plt
from time import time
#% matplotlib inline
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import AgglomerativeClustering
fr... |
#! /usr/bin/env python3
#
# Copyright 2018 California Institute of Technology
#
# 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
#
# Unle... |
import torch
import torch.nn as nn
from rich import print
from rich.prompt import Confirm
from myterial import amber_light, orange
import numpy as np
from pathlib import Path
from einops import repeat
from pyinspect import Report
from io import StringIO
from rich.console import Console
from loguru import logger
from p... |
'''
B站收藏夹saver(函数库)
By White_mu(WhitemuTeam)
'''
import requests as r
import PySimpleGUI as sg
import json,os,time
sg.theme('Reddit')
header={'User-Agent':'Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36'}
def getfav... |
import logging
from typing import Optional
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.sensor import ENTITY_ID_FORMAT, \
PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA
from homeassistant.const import (
ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, CONF_ICON_TEMPLATE,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 27 11:12:10 2018
@author: avelinojaver
"""
import sys
from pathlib import Path
dname = Path(__file__).resolve().parents[2]
sys.path.append(str(dname))
from cell_localization.models import UNet, UNetFlatter, UNetv2, UNetscSE, UNetv2B, UNetAttentio... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import func, text, Float, bindparam
from sqlalchemy.sql import select
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql.expression import false, true
from datetime import datetime, timedelta
from .startup import db
from .uptime import Up... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 12:56:04 2020
@author: scott
"""
from pathlib import Path
import json
import numpy as np
from matplotlib import pyplot as plt
from .constants import ICPMS_DIR, ICPMS_ID_FILE, ICPMS_CALIBRATION_ID_FILE
from .tools import singleton_decorator, CounterWithFile
from EC_MS ... |
import json
from collections import OrderedDict
from decimal import Decimal
from django import forms
from django.core.files.uploadedfile import UploadedFile
from django.db import IntegrityError
from django.db.models import Prefetch, QuerySet
from django.utils.functional import cached_property
from pretix.base.forms.q... |
import json, os
import math, copy, time
import numpy as np
from collections import defaultdict
import pandas as pd
from .utils import *
import math
from tqdm import tqdm
import seaborn as sb
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import dill
from functools import partial
import multiprocessing as... |
#
# Copyright (C)
#
# File: arrowLocatorManip.py
#
# Dependency Graph Node:
#
# Author: <NAME> 2.0
import sys, math
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaRender as OpenMayaRender
import maya.OpenMayaUI as OpenMayaUI
kPluginManipNodeTypeName = "arrowLocatorMan... |
from ..helpers import any_block_help, filt_block_help
from .. import ast_funcs
from .. import code_execution, conf, name_utils
from ..gen_utils import get_nice_str_list, layout_comment as layout
F_STR = 'f-string'
STR_FORMAT_FUNC = 'str_format'
SPRINTF = 'sprintf'
STR_ADDITION = 'string addition'
ASSIGN_VALUE_XPATH =... |
import datetime
import os
import random
import torchvision.transforms as standard_transforms
import torchvision.utils as vutils
# from tensorboardX import SummaryWriter
from torch import optim
from torch.autograd import Variable
from torch.backends import cudnn
from torch.optim.lr_scheduler import ReduceLROnPlateau
fr... |
import os
import colander
import deform
import dateutil
import re
import types
import uuid
import requests
from lxml import etree
from owslib.wps import WPSExecution
from pyramid.security import authenticated_userid
from phoenix.geoform.widget import BBoxWidget, ResourceWidget
from phoenix.geoform.form import BBoxVa... |
import os
import json
import traceback
from collections import OrderedDict
from .VarExtractor import VarExtractor
# compatibility with python 2/3
try:
basestring
except NameError:
basestring = str
class CrawlerError(Exception):
"""Crawler Error."""
class CrawlerInvalidVarError(CrawlerError):
"""Crawl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import uuid
import time
import json
from flask import render_template, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta
from flask_cors import CORS
from utils import *
app.config.from_object('c... |
import datetime
import io
import pathlib
import pytest
from werkzeug.exceptions import NotFound
from werkzeug.http import http_date
from werkzeug.test import EnvironBuilder
from werkzeug.utils import send_file
from werkzeug.utils import send_from_directory
res_path = pathlib.Path(__file__).parent / "res"
html_path =... |
# Lint as: python2, python3
# Copyright 2020 Google LLC. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import json
import argparse
import posixpath
import json
import requests
"""
1 Run Docker container including API endpoint for submission & Globus transfer components
docker run -p 5455:5455 \
-v /Users/mburnette... |
import numpy as np
from sklearn import linear_model
from sparse_ho.models import ElasticNet
from sparse_ho.forward import get_beta_jac_iterdiff
from sparse_ho.datasets.synthetic import get_synt_data
from sparse_ho.implicit_forward import get_beta_jac_fast_iterdiff
from sparse_ho.criterion import HeldOutMSE
from sparse_... |
# -*- coding: utf-8 -*-
"""
Various plots
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
import xarray as xr
import os
def quiver(
data,
arrScale=25.0,
threshold=None,
nthArr=1,
aspectratio="equal",
colbar=False,
colbar... |
from __future__ import unicode_literals
import re
import time
import os
from netmiko.base_connection import BaseConnection
from netmiko.scp_handler import BaseFileTransfer, SCPConn
class JuniperSSH(BaseConnection):
"""
Implement methods for interacting with Juniper Networks devices.
Disables `enable()`... |
# -----------------------------------------------------------------------------
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Copyright (c) 2015 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of th... |
#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# vim:set ft=python ts=4 sw=4 sts=4 autoindent:
'''
Server request dispatching mechanism.
Author: <NAME> <pontus is s u-tokyo ac jp>
Version: 2011-04-21
'''
from os.path import abspath, normpath
from os.path i... |
# SPDX-License-Identifier: BSD-3-Clause
import os
import logging
from collections import OrderedDict
from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap, CommentedSeq
yaml = YAML()
log = logging.getLogger(__name__)
OPERATOR_CSV_KIND = "ClusterServiceVersion"
class NotOperatorCSV(Exception)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of lplayer
#
# Copyright (c) 2017-2019 <NAME> <a.k.a. atareao>
#
# 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 r... |
import time
import torch
from torch import optim
from torch.distributions.dirichlet import Dirichlet
from common.util import sample, save_models
from common.initialize import initialize, infer_iteration
from . import model
def disc_loss_generation(data, target, eps, lp, critic1, critic2):
u = critic1(data)
v... |
# -*- coding: utf-8 -*-
import abc
import logging
from contextlib import contextmanager
from threading import RLock
from typing import Any, TYPE_CHECKING, Type, Union, TypeVar
from sceptre.helpers import _call_func_on_values
from sceptre.resolvers.placeholders import (
create_placeholder_value,
are_placeholder... |
from typing import Optional
from . import ast
from . import lexer
g_top_level_function_proto = None
g_bin_op_precedence = {
"=": 2,
"<": 10,
">": 10,
"+": 20,
"-": 20,
"*": 40,
"/": 40 # highest
}
g_block_level = 0
def reset():
global g_top_level_function_proto, g_block_level
g_t... |
import geopandas as gpd
import numpy as np
import pytest
from scipy.ndimage.morphology import binary_erosion
from shapely.geometry.linestring import LineString
from shapely.geometry.multilinestring import MultiLineString
from shapely.geometry.multipolygon import MultiPolygon
from shapely.geometry.polygon import Polygon... |
"""Tests on algebraic numbers. """
from sympy.core.containers import Tuple
from sympy.core.numbers import (AlgebraicNumber, I, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys.polytools import Poly
from sympy.po... |
from __future__ import absolute_import
import io
import json
import logging
import os
import re
import sys
from datetime import datetime
import wx
from . import units
from .config import Config
from ..dialog import SettingsDialog
from ..ecad.common import EcadParser, Component
class Logger(object):
def __init... |
from datetime import datetime
from operator import itemgetter
from dateutil.tz import tzutc
from dateutil.parser import parse
from txaws.server.exception import APIError
class SchemaError(APIError):
"""Raised when failing to extract or bundle L{Parameter}s."""
def __init__(self, message):
code = se... |
"""
Decentralized Distributed PPO (DD-PPO)
======================================
Unlike APPO or PPO, learning is no longer done centralized in the trainer
process. Instead, gradients are computed remotely on each rollout worker and
all-reduced to sync them at each mini-batch. This allows each worker's GPU
to be used ... |
### Vectors
import math
from math import sin, cos
import random
import collections
import itertools
import functools
import shapely.geometry
from scenic.core.distributions import (Samplable, Distribution, MethodDistribution,
needsSampling, makeOperatorHandler, distributionMeth... |
# Copyright 2016 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 hashlib
import struct
import os
from dataclasses import dataclass
from datetime import datetime
import requests
import tzlocal
from asn1crypto import tsp, algos, cms, x509, keys, core
from certvalidator import CertificateValidator
from oscrypto import asymmetric
from . import general
from .general import (
... |
# Copyright (c) 2021 ETH Zurich
import sys
import argparse
import configparser
import time
import pandas as pd
import numpy as np
import seaborn as sns
import warnings
from rdkit import DataStructs
from rdkit import Chem
from rdkit import rdBase
rdBase.DisableLog('rdApp.*')
sys.path.append('../src/python/scaffold_hop... |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# -*- coding: utf-8 -*-
"""
Builds CME matrix for dp/dt, broken into terms for each reaction.
"""
import itertools
import numpy
import scipy.sparse
from cmepy import model as mdl
def compute_propensity(prop, states):
"""
Returns the propensity ``prop`` evaluated over ``states``.
"""
return prop(*state... |
import streamlit as st
from iterdet.inference import inference_detector, init_detector
import numpy as np
import requests
from PIL import Image
import mmcv
import tempfile
import uuid
import pyrebase
import imutils
import cv2
import time
from config import firebaseConfig
MODEL_PATH = './yolo_model'
labe... |
from mock import Mock
import numpy
import pytest
import theano
class TestAutocrop:
# Test internal helper methods of MergeCropLayer
def test_autocrop_array_shapes(self):
from lasagne.layers.merge import autocrop_array_shapes
crop0 = None
crop1 = [None, 'lower', 'center', 'upper']
... |
import os
import spacy
import language_check
import logging
import time
from subprocess import call
from quasimodo.inflect_accessor import DEFAULT_INFLECT
from quasimodo.parameters_reader import ParametersReader
parameters_reader = ParametersReader()
CACHE_DIR = parameters_reader.get_parameter("question-cache-dir") o... |
import csv
import os
import logging
import gzip
import pickle
import random
import time
import json
import pandas as pd
from google.cloud import bigquery
import google.api_core
from fourtytwo.bqtools import conversions
DEBUG = False
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
def load(filename):
if ... |
import pickle
#import types
import inspect
import logging
#import warnings
import numpy as np
import cloudpickle
log = logging.getLogger('shap')
class Serializable():
""" This is the superclass of all serializable objects.
"""
def save(self, out_file):
""" Save the model to the given file stream.... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.php
~~~~~~~~~~~~~~~~~~~
Lexers for PHP and related languages.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, defa... |
'''
====================================================================
Copyright (c) 2003-2009 <NAME>. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
======================================================... |
import os
import shlex
import shutil
import threading
import time
from subprocess import check_call, CalledProcessError
from pymediainfo import MediaInfo
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
VIDEO_CRF = int(os.environ.get('VIDEO_CRF'))
VIDEO_MAX_B... |
# -*- coding: utf-8 -*-
import logging
import random
import re
import ssl
import subprocess
import copy
import time
import os
from base64 import b64encode
from collections import OrderedDict
from requests.sessions import Session
from requests.adapters import HTTPAdapter
from requests.compat import urlparse, urlunpars... |
#!/usr/bin/env python
import math
import pyproj
import shapefile
import pprint
import math
import json
from collections import defaultdict, Counter
CC_CODES = {
'Taiwan': 'tw',
'Western Sahara': 'eh',
}
EXTRA_BRIDGES = []
def calc_area(pts):
n = len(pts) # of corners
area = 0.0
for i in range(n... |
import os
from io import BytesIO
from typing import IO, Generator, Optional, Set, Type
from .. import blte, cdn
from ..archive import ArchiveGroup
from ..armadillo import ArmadilloKey
from ..blte import verify_blte_data
from ..configfile import BuildConfig, CDNConfig, PatchConfig
from ..encoding import EncodingFile
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.