text stringlengths 3.07k 12.6k |
|---|
import pytest
from common.version import InvalidVersionError, GenericVersion
from indy_common.version import NodeVersion
from indy_node.utils.node_control_utils import DebianVersion, NodeControlUtil, ShellError
# TODO
# - conditionally skip all tests for non-debian systems
generated_command = None
class UpstreamT... |
import math
from .lang import H, sig, t
#=============================================================================#
# Standard types, classes, and related functions
## Basic data types
from .Data.Maybe import Maybe, Just, Nothing, in_maybe, maybe
from .Data.Either import Either, Left, Right, in_either, either
... |
import os
import sys
from struct import *
#hex to bin
def hexf(hexfile):
try:
fin = open(hexfile)
except:
print('No file opened', hexfile)
return None
table =[]
result = b''
addr = 0
addr_flg = 0
for hexstr in fin.readlines():
#print(hexstr)
hexstr = hexstr.strip()
#print(hexstr)
size = int(hexstr[... |
# 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 warnings
import argparse
import torch
import numpy as np
from rich import print
from constants import DPAC_ATT_CAT_COUNT
from dataloader import load_data
from models.base import MultiOutputModel
# from loss import MultiTaskLoss_DPAC
from sklearn.metrics import precision_score, f1_score, recall_score, accuracy_... |
import json
from json import JSONDecodeError
import pandas as pd
from requests import post
import yaml
# General class for necessary file imports
class FileImport():
def read_app_key_file(self, filename: str = "keys.json") -> tuple:
"""Reads file with consumer key and consumer secret (JSON)
Args:... |
import urllib.request
import json
import time
import os.path
import sys
import datetime
import twitter
def getJSONFromUrl(fetch_url):
#Fetch json data from the url
with urllib.request.urlopen(fetch_url, timeout=1) as url:
data = json.loads(url.read().decode())
return data
de... |
import scanpy as sc
import numpy as np
import licorice
import matplotlib.pyplot as plt
import vinplots
def _build_plot(geneset_score_key):
fig = vinplots.Plot()
fig.construct(
nplots=5,
ncols=5,
width_ratios=[2, 2, 2, 2, 0.05],
wspace=0.15,
figsize_width=1,
)
f... |
from django.shortcuts import render, get_object_or_404
from .forms import PostForm, CommentForm
from .models import Post, Group, User, Comment, Follow
from django.utils import timezone
from django.shortcuts import redirect
from django import forms
from django.core.paginator import Paginator
from django.http import Http... |
from flask import Flask
from flask import render_template
from flask import request
from flask import session
from flask import redirect # I will learn after that will use
from flask import url_for # I will learn after that will use
from flask import flash # I will learn after that will use
import pymysql.cursors
i... |
#!/usr/local/bin/python3.6
# -*- coding:utf-8 -*-
# ========================================
# Description :
# 工具类
# 反射类、数据仓库类、路径加工、缓存
# Created : 2020.10.14
# Author : <NAME>
# ========================================
from promise import Promise
import os
import inspect
from dataclasses import dataclass
# 字典反射对... |
import pytest
pytest.importorskip('numpy')
import numpy as np
import pytest
import dask.array as da
from dask.array.utils import assert_eq
def test_linspace():
darr = da.linspace(6, 49, chunks=5)
nparr = np.linspace(6, 49)
assert_eq(darr, nparr)
darr = da.linspace(1.4, 4.9, chunks=5, num=13)
np... |
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.nn.functional as F
from torch.autograd import Variable
class ST_LSTM(nn.Module):
def __init__(self, nodes, in_channel, out_channel, out = None,
forget_bias = 1.0, ln = True, first = False):
super(ST_LSTM, self)._... |
import datetime
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import shutil
import sys
import time
import pandas as pd
import pynder
import urllib.request
from pynput import keyboard
from pylab import rcParams
from config import FACEBOOK_AUTH_TOKEN, FACEBOOK_ID, RATING_THRESHOLD
# Itera... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 15:19:40 2022
@author: turnerp
"""
import traceback
import numpy as np
from skimage import exposure
import cv2
import tifffile
import os
from glob2 import glob
import pandas as pd
import mat4py
import datetime
import json
import matplotlib.pyplot as plt
import hashli... |
#this code is the workbench for q-learning
#it consists on a lifting particle that must reach a certain height
#it is only subjected to gravity
#Force applied to the particle might be fixed 9.9 or 9.7N
import numpy as np
import math
import random
import matplotlib.pyplot as plt
#INITIALIZE VARIABLES
####... |
from unittest import TestCase, main
from preconditions import PreconditionError, preconditions
class PreconditionTestBase (TestCase):
def assertPreconditionFails(self, target, *args, **kw):
self.assertRaises(PreconditionError, target, *args, **kw)
def assertPreconditionFailsRegexp(self, rgx, target,... |
# -----------------------------------------------------------------------------------------------------------
# Funções auxiliares para predições
# -----------------------------------------------------------------------------------------------------------
import numpy as np
import pandas as pd
import matplotlib.pyplot... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from logger import setup_logger
from model import BiSeNet
from face_dataset import FaceMask
from loss import OhemCELoss
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.distributed as dist
import os
imp... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from typing import List, Optional
from p1_utils.data_type import DataType
from p1_utils.errors import EquLabelRequiredError, EquDataTypeHasAmpersandError, DcInvalidError, \
NotFoundInSymbolTableError, ZeroDuplicationLengthError
from p1_utils.file_line import Line
from p2_assembly.mac0_generic import MacroGeneric
... |
from rdflib import URIRef, Literal
from twisted.internet.defer import inlineCallbacks, returnValue
import treq
from light9 import networking
from light9.curvecalc.curve import CurveResource
from light9.namespaces import L9, RDF, RDFS
from rdfdb.patch import Patch
def clamp(x, lo, hi):
return max(lo, min(hi, x))
... |
from abc import ABC, abstractmethod
from collections import OrderedDict
import numpy as np
import pandas as pd
from .mask import mask_module
from .modules import MaskedModule
from .utils import get_params
import tempfile, pathlib
import torch
class Pruning(ABC):
"""Base class for Pruning operations
"""
... |
'''
This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: <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 cop... |
import logging
import numpy as np
from scipy.stats import nbinom, poisson, binom
from scipy.special import gamma, factorial, gammaln, logsumexp, hyp2f1, hyp1f1, hyperu, factorial
class CountModel:
error_rate=0.01
class MultiplePoissonModel(CountModel):
def __init__(self, base_lambda, repeat_dist, certain_coun... |
import random
from copy import deepcopy
# import geopandas
from math import floor
from typing import List
from Day import Day
# import gmplot
from Item import Item
from haversine import haversine
# import networkx as nx
API_KEY = '<KEY>'
# with open('../../../testing/samples/milan_trip_data.pkl', 'rb') as input:
# ... |
import io
import csv
from django.db import connections
from django.db.models import Count, Case, When, IntegerField
from capdb.models import Reporter, Jurisdiction, CaseMetadata, Snippet, Court
import json
from capweb.templatetags.api_url import api_url
from tqdm import tqdm
def update_all():
update_map_numbers()... |
import pytest
from .permissions import Permissions, parse_template, LiteralToken, PlaceholderToken, ReValidator, mkperm, Placeholder
perms = Permissions('intrustd+perm://photos.intrustd.com')
CommentAllPerm = perms.permission('/comment')
GalleryPerm = perms.permission('/gallery')
UploadPerm = perms.permission('/uplo... |
#!/usr/bin/env python3
import sys
import gzip
import argparse
import logging
import Levenshtein
def load_barcodes(args):
bcs = {}
with open(args.barcodes) as f:
for line in f:
fields = line.rstrip('\n').split('\t')
index, adapter = fields[0], fields[1]
bcs[index] = bcs.get(index, []) + [adapter]
return ... |
# ======================================================================
# Created by <NAME>, <NAME>, <NAME> 11/2021
# ======================================================================
import numpy as np
from parameters import *
from variables import *
import equations
#======================================... |
#!/usr/bin/python
"""
Name
create_ami.py - Create '.ami' file for fluxus network software
SYNOPSIS
create_ami.py [--snp] <Fasta file> <data>
DESCRIPTION
Fluxus network .ami file format:
============================================================
;1.0 <- Unknown
CH1;CH2... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import discord
from discord.ext import commands
import kiwi_config
from .scpUtils import UTC_TIME
__real_owner__ = '<mi id>'
class Info:
def __init__(self, bot):
self.bot = bot
@commands.command(description="Información sobre kcalcular")
async d... |
import argparse
import fnmatch
import os
import pathlib
import sys
import textwrap
import yaml
def write_header(output):
header='''
###
# This file is automatically generated by {}. Do not edit!
###
'''
output.write(textwrap.dedent(header.format(os.path.basename(__file__))).lstrip())
outp... |
# 5
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.layers import Dropout
import numpy as np
# sinusoidal position encoding
def get_3d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
grid_h = np.arange(grid_size)
grid_w = np.arange(grid_size)
gri... |
from enum import Enum
class SimpleEnum(Enum):
@classmethod
def keys(cls):
# remove first under line as real key
return [i.name if not i.name.startswith('_') else i.name.partition('_')[-1] for i in cls]
@classmethod
def values(cls):
return [i.value for i in cls]
# use key... |
from django.db import models
from accounts.models import User
from datetime import date
from django.utils.translation import gettext as _
from django.core.validators import RegexValidator
class Application(models.Model):
"""
this is the model for application that needs to be filled for applying for admission ... |
import hashlib
import json
import time
from urllib.parse import urlparse
from uuid import uuid4
import requests
from flask import Flask,jsonify,request
from typing import Any,Dict,List,Optional #数据结构
class NewBlockChain:
def __init__(self):
self.current_trans = [] #当前的交易
self.chain = [] #区块链管... |
# 实现PCA分析和法向量计算,并加载数据集中的文件进行验证
import os
import time
import numpy as np
from pyntcloud import PyntCloud
import open3d as o3d
def PCA(data: PyntCloud.points, correlation: bool=False, sort: bool=True) -> np.array:
""" Calculate PCA
Parameters
----------
data(PyntCloud.points): 点云,NX3的矩阵
co... |
import logging
import os
import re
import i18n
import discord
from discord.ext import commands
from .help import YLHelpCommand
intents = discord.Intents.none()
intents.emojis = True
intents.guilds = True
intents.members = True
intents.voice_states = True
intents.messages = True
intents.reactions = True
YB_BOT = com... |
from binascii import hexlify
import enum
import re
from . import bech32
PREFIXES = [
"addr",
"addr_test",
"script",
"stake",
"stake_test"
# -- * Hashes
,
"addr_vkh",
"stake_vkh",
"addr_shared_vkh",
"stake_shared_vkh"
# -- * Keys for 1852H
,
"addr_vk",
... |
import sys,os,string
import math
from ROOT import *
from PlotUtils import *
from array import array
def SyncBands2(hist):
print (hist.GetName())
theCVhisto = MnvH2D()
theCVHisto = hist.Clone()
theCVHisto.SetDirectory(0);
bandnames = hist.GetErrorBandNames();
# "Synching Error Band CV's with MnvH1D's CV" << ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##########
# IMPORT #
##########
# Systeem
import sys
from sys import platform as _platform
import time
# SQL
#import sqlite3
# GUI - TKInter
import tkinter as tk
from tkinter import ttk
from tkinter import font
from tkinter import Text
# GUI - Extensions
from gui.tkEx... |
"""
mMOSS moderately Multiplayer Online Side Scroller
Classes defined:
1. ServerProtocol
Copyright (c) 2011 by <NAME>. All rights reserved.
"""
from __future__ import division
import time
import logging
from twisted.protocols import amp
from twisted.internet import protocol
from mmoss.network import *
from mmoss.ut... |
# coding: utf-8
# 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... |
import scipy.optimize
from src.plot import *
import math
import sympy as sp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
'''This script calculates the inverse kinematics in 6dofs for a Fanuc CR-7iA robot'''
def forward_kinematics(q):
T01 = sp.Matrix([[-sp.cos(q[0]), 0, -sp.sin(q[0]),... |
import os, pprint
import numpy as np
import joblib
from utils.BaseModel import BaseModel
from utils.AwesomeTimeIt import timeit
from utils.RegressionReport import evaluate_regression
from utils.FeatureImportanceReport import report_feature_importance
from sklearn.model_selection import RandomizedSearchCV
from sklearn... |
"""
Usage:
cfgen FILE [list] [OPTIONS] [--overwrite]
Commands:
list list variables and their values
Options:
--overwrite overwrite existing file
metaconfig cache
.cfgen.cache
<variable_name> = <value>
metaconfig file
cfgen.metaconfig
<variable_name> = <shell_command>
*.template
jinja templat... |
from flask import Flask, render_template, request
from zipfile import ZipFile
import shutil
import base64
import zipfile
import os
import sys
import json
import requests
from os import path
# FLASK_APP=server.py flask run
# source gusPythonEnviroment/bin/activate
app = Flask(__name__)
@app.route('/')
def index():
... |
#!/usr/bin/env python2
#
# Strelka - Small Variant Caller
# Copyright (c) 2009-2018 Illumina, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# at your... |
"""Main module for randnames
Simple usage:
>>> import randomname
>>> randomname.full_name()
'<NAME>'
"""
import random
import json
import os
import warnings
from bisect import bisect_left
from .errors import *
_THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
_COUNTRIES_BASE = os.listdir(os.path.join(_THIS_F... |
# This is a single helper file from Excel and CSV Conversion Tools Toolbox
# ArcMap Description: This toolbox includes four tools: TableToCSV,
# TableToExcel, CSVToTable, and ExcelToTable. Both .xls and .xlsx file
# formats are supported in this toolbox. The toolbox utilizes (and includes)
# XLRD, XLWT, and OPENPY... |
# -*- coding:utf-8 -*-
import requests
import os
import openpyxl
from rrunner.common.handle_config import config
from rrunner.common.handle_path import DATA_DIR, CASE_DIR
def getByPath(path, obj):
paths = path.split(".")
for path in paths:
obj = obj.get(path, None)
if obj == None:
... |
import json
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from tqdm import tqdm_notebook
def load_data(file):
"""Загрузка входных данных из файла"""
with open(file, 'r') as f:
input_data = json.load(f)
couriers = {}
orders = {}
points = {}
fo... |
import discord
from discord.ext import commands
from bot import Bot, CustomContext
from utils.errors import ProcessError
import pathlib
import inspect
from utils.constants import General
import typing
import importlib
class Limit(commands.Converter):
def __init__(self, char_limit: int = None):
self.char_l... |
import logging
import sys
import textwrap
import unittest
from io import StringIO
try:
from unittest.mock import MagicMock, mock_open, patch
except ImportError:
from mock import MagicMock, mock_open, patch
try:
from importlib import reload
except ImportError:
from imp import reload
import sleuth.inje... |
bl_info = {
"name": "Export SMF",
"description": "Export to SMF 10 (SnidrsModelFormat)",
"author": "<NAME>",
"version": (0, 8, 0),
"blender": (2, 80, 0),
"location": "File > Export",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "https://github.com/blender-t... |
import unittest
import numpy as np
import torch
import torch.nn as nn
import torch.optim
import sys
sys.path.append('../')
from FrEIA.modules import *
from FrEIA.framework import *
class ActNormTest(unittest.TestCase):
def __init__(self, *args):
super().__init__(*args)
self.batch_size = 256
... |
def rotate(list, no_rotation):
return list[no_rotation:] + list[:no_rotation]
def message_processor(message):
message = message.upper()
message = message.replace(" ", "")
return message
def select_rotor(rotor_model):
rotor_i_list = ['E','K','M','F','L','G','D','Q','V','Z','N','T','O','W','Y','... |
# Copyright 2021 Huawei Technologies Co., Ltd.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 ap... |
import os
import shutil
from aidapy.hist import total_systematic_histogram
from aidapy.hist import hist2array
#from .style_mpl import atlas_mpl_style
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.ticker import AutoMinorLocator, MultipleLocator
import matplotl... |
import sys
import contextlib
import functools
import ir_measures
from ir_measures import providers, measures, Metric
from ir_measures.providers.base import Any, Choices, NOT_PROVIDED
class TrectoolsProvider(providers.Provider):
"""
trectools
https://github.com/joaopalotti/trectools
::
@inproceeding... |
import functools
import os
import re
import typing as tp
import xonsh.platform as xp
import xonsh.tools as xt
from xonsh.built_ins import XSH
from xonsh.completer import Completer
from xonsh.completers.tools import (
RichCompletion,
contextual_command_completer,
get_filter_function,
non_exclusive_compl... |
from __future__ import print_function
import sys, os, datetime, json
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'lib')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'env/Lib/site-packages')))
import httplib, urllib
import time
from base64 ... |
import ast
import re
from collections import defaultdict
class AbstractTreeAnalysis():
DEFAULT_REULES = {
"line_length": 79,
"forbid_semicolons": True,
"max_nesting": 1,
"indentation_size": 4,
"methods_per_class": None,
"max_arity": 2,
"forbid_trailing_whit... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function, division
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import os
import tempfile
from astropy.io import fits
from astropy.tests.helper import pytest
from astropy.units import Quantity
from... |
import re
import os
import pickle
import time
import datetime
import json
import ipdb
import requests
import pandas as pd
from bs4 import BeautifulSoup
VALID_TAGS = ['div', 'p']
def clean_tag(tag):
return re.sub('<[^<>]*>', ' ', str(tag)).strip()
def clean_html(soup):
doc = ""
for tag in soup.findAll('p... |
"""Script to download all the data we need for GPV experiments"""
import argparse
import logging
import os
import shutil
import tarfile
import tempfile
from collections import defaultdict
from os import makedirs
from os.path import exists, join, dirname
from tqdm import tqdm
from gpv2 import file_paths
from gpv2.dat... |
import torch
def add_tensor_1d(x, y):
s1 = (y.shape[-1] - x.shape[-1]) // 2
e1 = s1 + x.shape[-1]
y = y[..., s1:e1]
if x.shape[1] > y.shape[1]:
d = [int(i) for i in y.shape]
d[1] = int(x.shape[1] - y.shape[1])
y = torch.cat((y, torch.zeros(d, dtype=y.dtype, device=y.device)), -3... |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
import os.path
import sys
import site
import inspect
import types
import collections
class _DependencyResolver(object):
"""
Finds dependencies given a module object
"""
def __init__(self, topology):
self._modules = set()... |
import json
import re
from api.core.danmaku import *
class Tencent(DanmakuSearcher):
async def search(self, keyword: str) -> AsyncIterator[DanmakuMeta]:
tasks = [self.search_one_page(keyword, p) for p in range(5)] # 取前10页
async for meta in self.as_iter_completed(tasks):
yield meta
... |
import typing
from functools import partial as bind
from cohesivenet import (
data_types,
network_math,
Logger,
util,
VNS3Client,
CohesiveSDKException,
)
from cohesivenet.macros import api_operations, state
VNS3Attr = state.VNS3Attr
def create_local_gateway_route(client, local_cidr, **rout... |
# coding: utf8
import collections
import argparse
import pprint
import json
from pathlib import Path
from .score import subtaskA, subtaskB, compute_metrics
from .utils import Collection
def evaluate_scenario(submit, gold, scenario):
submit_input = submit / ("output_scenario%i.txt" % scenario)
if not submit... |
import select
import socket
import re
sock = socket.socket()
sock.bind(('0.0.0.0', 8001))
sock.listen()
sock.setblocking(False)
ep_fd = select.epoll()
ep_fd.register(sock, select.EPOLLIN)
fd_sock = {}
fd_read_data = {}
fd_write_data = {}
tasks = []
def on_read(fd):
# while True:
# try:
# d =... |
import re
from datetime import datetime
import time
import urllib
import base64
def command_encode(command):
"""
Encode the command array in a command-string
"""
return "\n".join(_command_encode(command))
def _command_encode(command):
r = []
if type(command) == int:
command = str(command)
if type(command) ... |
import enum
import pickle
import typing
from abc import ABC, abstractmethod
from pathlib import Path
import h5py
import numpy as np
from shapely.geometry import MultiPoint
from src.utils import hash_file
class PoseHashException(Exception):
pass
class PoseEstimation(ABC):
"""
abstract base class for Po... |
import os
import sys
import numpy as np
def ADD_err(gt_pose, est_pose, model):
def transform_points(points_3d, mat):
rot = np.matmul(mat[:3, :3], points_3d.T)
return rot.transpose() + mat[:3, 3]
v_A = transform_points(model, gt_pose)
v_B = transform_points(model, est_pose)
v_A = np.arr... |
import numpy as np
import torch as t
import torch.nn as nn
from typing import Tuple
class NBeatsBlock(nn.Module):
"""
N-BEATS block which takes a basis function as an argument.
"""
def __init__(self, n_inputs: int, theta_dim: int, basis: nn.Module, # n_static:int
n_layers: int, n_hidde... |
import io
import csv
import logging
import requests
import glob, os
import numpy as np
import pandas as pd
from pathlib import Path
from astropy.table import Table
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
# ["g", "r", "i", "z"... |
import sys
import codecs
import json
from nlplingo.common.utils import IntPair
from nlplingo.text.text_span import TextSpan
from nlplingo.text.text_theory import Document
from nlplingo.text.text_theory import SRL
class JSONTokens(object):
def __init__(self, text):
self.text = text
self.index = -1... |
import numpy as np
from typing import Union
def cleanup_delete(coords_list_in: np.ndarray,
eps_grid: float = 1e-4,
cyclic_points: bool = True,
check_inline: bool = True,
) -> np.ndarray:
"""
From the passed coordinate list, returns a... |
"""
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: <NAME>
"""
import tensorflow as tf
import num... |
import sys
import numpy as np
X_TRAIN_PATH = sys.argv[1]
Y_TRAIN_PATH = sys.argv[2]
print("Running the File", sys.argv[0])
print("Directory 1: ", X_TRAIN_PATH)
print("Directory 2: ", Y_TRAIN_PATH)
'''
For Testing
'''
'''
X_TRAIN_PATH = 'X_train'
Y_TRAIN_PATH = 'Y_train'
'''
X_train = np.genfromtxt(X_TRAIN_PATH, d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (
print_function,
division,
absolute_import)
from six.moves import xrange
# =============================================================================
# Imports
# =======================================================================... |
import pandas as pd
import numpy as np
import logging
logger = logging.getLogger(__name__)
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.ERROR)
################################
# wrangling methods used in:
# - income_distribution.ipyn... |
import os
from collections import namedtuple
import unittest.mock as mock
import uberfare.core as core
@mock.patch('uberfare.core.UberRidesClient')
@mock.patch('uberfare.core.Session')
def test_get_read_only_client(mock_session, mock_client):
"""It should correctly call the Uber Session and pass it to the Client.... |
import logging
from warreport.key_constants import PROCESSING_QUEUE_SET, PROCESSING_QUEUE, REPORTING_QUEUE, BATTLE_DATA_EXPIRE, \
BATTLE_DATA_KEY, KEEP_IN_QUEUE_FOR_MAX_TICKS, ROOM_LAST_BATTLE_END_TICK_KEY, ROOM_LAST_BATTLE_END_TICK_EXPIRE
try:
import rapidjson as json
except ImportError:
import json
imp... |
"""Dimensionality reduction through dimensionality selection."""
import logging
import random
import functools
import multiprocessing
import numpy as np
import entropix.core.evaluator as evaluator
__all__ = ('sample_seq', 'sample_limit')
logger = logging.getLogger(__name__)
def _init_eval_metric(metric):
if m... |
import time
import requests
from ast import literal_eval
from datetime import datetime
from multiprocessing.dummy import Pool
from elasticsearch import TransportError, ConnectionError, NotFoundError
from elasticsearch_dsl import Search
from project import app
from project.lib.sfnutils import getLatestTime, processTag... |
#!/usr/bin/python3
""" Represents a map of TransAmerica """
import queue
import features
class Board:
"""
Represent the Trans America map. The key here is to keep
an array of costs from each node to each other node.
See features for a little more description of the mathematical
representa... |
#! /usr/bin/env python
#coding=utf-8
import ply.yacc as yacc
from py_lex import *
from node import node,num_node
# YACC for parsing Python
def simple_node(t,name):
t[0]=node(name)
for i in range(1,len(t)):
if t.slice[i].type == 'slice':
t[0].add(t[i])
elif t.slice[i].t... |
# -*- coding: utf-8 -*-
from setup import *
def count_signals(gene, df_signals):
overlapping_signals = df_signals[
(df_signals.epicenter_seqid == gene.seqid) &
(df_signals.focus_start_coord <= gene.end) &
(df_signals.focus_end_coord >= gene.start)
]
# TODO this doesn't properly h... |
from json import loads
from pprint import pprint
from sys import argv
from time import time
from sqlalchemy import text
from jasmine.etl.ddl_tools import names_status_str
from jasmine.etl.materializations import materialization_resource_names_funcs
from jasmine.etl.sqla_tools import with_sqla_first_arg, with_sqla_ses... |
import requests, sys, datetime
from bs4 import BeautifulSoup
# GMT Format
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
# rss channel
class channel(object):
def __init__(self, title, author, image, link, description, language, copyright):
self.title = title
self.author = author
self.image = i... |
# RT - NickName Panel
from __future__ import annotations
from discord.ext import commands
import discord
from rtlib.common.json import loads
from rtutil.utils import is_json, replace_nl
from rtutil.content_data import ContentData
from rtutil.panel import extract_emojis
from core import Cog, RT, t
from data import... |
#!/usr/bin/env python3
# encoding=utf8
import warnings
import keyboard
import mouse
from mylib.easy import *
from mylib.ext import ostk, fstk
from mylib.gui_old import rename_dialog
from mylib.uia import module_pywinauto
pywinauto = module_pywinauto()
App = pywinauto.Application
HwndElementInfo = pywinauto.win32_ele... |
from fastapi import FastAPI, requests
from api.database.db_initialize import SessionLocal, engine
from api.model.table_models import USERS, USER_POSTS, COMMENTS, EMERGENCY_CONTACTS, Base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
Base.metadata.create_all(bind=engine)
# Creates all tables if ... |
"""Neighborhood SPIN Module."""
import numpy as np
from .utils import check_distance_matrix, spin_energy
class NeighborhoodSPIN():
"""Neighborhood SPIN clustering method.
Parameters
----------
initial_sigma : float, optional (default=2e10)
Initial sigma value. This parameter controls the weig... |
import unittest
import sys
from time import sleep
try:
import dev_appserver
except ImportError:
raise ImportError('App Engine must be in PYTHONPATH.')
sys.exit()
dev_appserver.fix_sys_path()
from google.appengine.api import memcache
from google.appengine.ext import testbed, webapp
from google.appengine.d... |
from django.shortcuts import render
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.contrib.au... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.