text stringlengths 3.07k 12.6k |
|---|
"""
Original of this code is from "https://github.com/pemami4911/deep-rl".
Brought for study, and re-create to tensorflow-only version.
"""
import tensorflow as tf
import numpy as np
import gym
from collections import deque
import argparse
import pprint as pp
from gym import wrappers
from agent import ActorNetwork, C... |
from types import SimpleNamespace
import numpy as np
import pytest
from fastai.core import T, V, to_np, to_gpu
from numpy.testing import assert_allclose
from quicknlp.modules import EmbeddingRNNDecoder, RNNAttentionDecoder, Projection, AttentionProjection
from quicknlp.modules.basic_decoder import select_hidden_by_in... |
import json
from _decimal import Decimal
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.utils import timezone
from django.views import View
from goods.models imp... |
import json
import numpy as np
import os
def batch_data(data, batch_size):
'''
data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client)
returns x, y, which are both numpy array of length: batch_size
'''
data_x = data['x']
data_y = data['y']
# randomly shuffle data
np.... |
###################################################################################################
## SDI TAPAS python demo application - communication module
##
## Revisions:
## 1.0 - Initial version
##
## Copyright (c) 2017 Siemens AG
# Redistribution and use in source and binary forms, with or without
# modifica... |
from autodiff.utils import check
from autodiff.ops import *
from inspect import signature
import numpy as np
# Helper Util
class Tensor:
def __init__(self, value, _children = [], requires_grad = True):
self.value = np.atleast_2d(value)
self.requires_grad = requires_grad
self.grad = np.zer... |
from __future__ import absolute_import
import zipfile
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import os
from datetime import datetime, timedelta
import requests
from contextlib import contextmanager
from .collection_tools import merge
import math
from .math_tools import round_float
impor... |
"""This module implements various logging facilities for the PyGears framework.
It is a wrapper around standard Python `logging
<https://docs.python.org/library/logging.html>`__ but provides some additional
features like:
- automatic exception raising when logging at any level
- customized stack trace printing
- loggi... |
"""
prepare_data.py
===================================
Some pre-model data preparation functions.
"""
from definitions import *
import signatory
import numpy as np
from src.features.signatures.functions import get_augmentation_pipeline
from src.features.scaling import TrickScaler
from src.data.make_dataset import Time... |
"""
Function to exercise infrastructure from the inside.
Query parameters:
* `run_azure` (default: true) - if 'false' we won't try to interact with the storage account or key vault
Headers:
* `Accept` if 'text/plain' we'll return a plaintext response, otherwise it'll be JSON
""" # noqa: E501
import collections
imp... |
import os
from typing import Any, Optional
import intake
import xarray as xr
import zarr
from .autodetect import autodetect as _autodetect
from .source.klb import save_klb as _save_klb
from .source.nifti import save_nifti as _save_nifti
from .source.nrrd import save_nrrd as _save_nrrd
from .source.tif import save_tif... |
#!/usr/bin/env python3
# Copyright 2019 RaptorRants
from itertools import groupby
from operator import itemgetter
# Global Variables
#RollHistory = [] # Global variable used to keep Dthe history of rolls
# RollHistory data format: [DiceType, Roll Result, The Roll Count (ie roll 1 / roll 2 etc), the set count (ie: R... |
class BinNode:
def __init__(self, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def isLeaf(self):
if self.left is None and self.right is None:
return True
... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import numpy as np
import torch
# Import local dependencies
import sys
sys.path.insert(0, "src")
from collection import Collection
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
class UnNormalize(object):
def __init__(self, mean, std):
self.mean = mean
self.... |
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
from infi.pyutils.contexts import contextmanager
from logging import getLogger
from .. import PyPI, DjangoPyPI, DistributionNotFound, UnsupportedArchive, InvalidArchive
try:
from ConfigParser import ConfigParser
from urlparse import urlparse
from urllib import urlretrieve
except ImportError:
# Python 3... |
""" Tests for the DBManager """
import unittest
import shutil
import os.path
import tempfile
import doto.model
import doto.model.timerecord
import doto.model.task
import doto.model.apmt
import doto.model.repeat
TEST_DB_FILE = ""
TEST_CACHE_FILE = "./test/store/cache"
TEST_LAST_FILE = "./test/store/last"
class TestD... |
#!/usr/bin/env python3
import argparse
import certifi
import os
import queue
import re
import threading
import urlextract
import urllib3
from multiprocessing import Pool
from tqdm import tqdm
'''
High level algorithm
List all files with a certain pattern, excluding some files
Extracts all urls and associated file p... |
# coding=UTF-8
import os, argparse
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import... |
"""Servlet factory for unknown file types."""
import os
from mimetypes import guess_type
import HTTPExceptions
from HTTPServlet import HTTPServlet
from MiscUtils.Configurable import Configurable
from ServletFactory import ServletFactory
debug = False
try:
from mimetypes import init as init_mimetypes
except I... |
# searching.py
# Copyright (c) 2020 Applied Research Associates, Inc.
# SPDX-License-Identifier: https://spdx.org/licenses/MIT.html
"""Utility classes for searching directories and archives.
Note:
Though documentation may say "match" when referring to searching for patterns,
the method ``re.match`` is not use... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
from django.conf import settings as django_settings
from django.db import models
from django.db.models import signals
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_la... |
import json
from datetime import datetime
from time import sleep
import luigi
from luigi.contrib.bigquery import BigqueryTarget, BigqueryClient
from common.gbq import GbqConnector
from common.luigi_extensions import accepts_exception
from common.postgres import default_postgres_target
from common.simple_gs import get... |
#!/usr/bin/env python3
"""Administer the PairXlate database table."""
from collections import namedtuple
# PIP3
from sqlalchemy import and_
# Pattoo PIP3 libraries
from pattoo_shared import log
# Import project libraries
from pattoo.db import db
from pattoo.db.models import PairXlate, Language, PairXlateGroup
from ... |
"""
Implementation of the ICDE 2019 paper
iFair: Learning Individually Fair Data Representations for Algorithmic Decision Making
__url__: https://ieeexplore.ieee.org/abstract/document/8731591
__author__: <NAME>
__email__: <EMAIL>
"""
from __future__ import division
from numba.decorators import jit
import numpy as np
fr... |
from tkinter import *
from tkinter import messagebox
from PIL import ImageTk, Image
from sys import exit
import smtplib, ssl
import time
root = Tk()
root.title('Customer Review')
root.iconphoto(True, PhotoImage(file = 'images/python.png'))
root.geometry("400x200")
def SendEmail(grade):
port = 465 # Fo... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Crypto related wrapper functions."""
import logging
import pyswitcheo.crypto_utils as cutils
from neocore.Cryptography.Crypto import Crypto
from pyswitcheo.datatypes.fixed8 import Fixed8
from pyswitcheo.datatypes.transaction_types import (
TransactionInput,
Tra... |
#!/usr/bin/env python3
import torch
from typing import Optional, List, Tuple
from pathlib import Path
from algorithms.PPO import HyperparametersPPO, PPO
from algorithms.actor_critic import ActorCriticParams
from algorithms.action_chooser import ActionChooser
from algorithms.buffer import PPOExperienceBuffer
... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# (https://github.com/sandorex/extract-browser-data.py)
# extract-browser-data
#
# Copyright 2020 <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/l... |
import json
import flask
from flask import Flask, render_template, request, session, redirect, jsonify, url_for, Response
import pymongo
from flask_cors import CORS,cross_origin
import requests
app = flask.Flask(__name__)
CORS(app)
app.config["DEBUG"] = True
app.config["SECRET_KEY"] = "OCML3BRawWEUeaxcuKHLpw"
# Creat... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
#import matplotlib.pyplot as plt
import time
import os
import copy
import torch.nn.functional as F
from PIL import Image, ExifTag... |
import py2700 as RM
import CoolingSystem as CS
import time
from datetime import datetime
import os
import sys
import subprocess
import argparse
import webbrowser
import atexit
from pathlib import Path
import json
# Important Info
__version__ = "1.0.0"
# Functions
def InvalidFilename(input_str) -> bool:
if (inpu... |
# this project is licensed under the WTFPLv2, see COPYING.wtfpl for details
from logging import getLogger
import os
import re
import sys
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import QThread, pyqtSlot as Slot
from pexpect import spawn, EOF
from lierre.credentials import get_credential, list_credentials... |
from __future__ import print_function
from get_csv_data import HandleData
import numpy as np
import tensorflow as tf
data = HandleData(total_data=880,data_per_angle=110,num_angles=8)
antenna_data,label_data = data.get_synthatic_data(test_data=False)
def get_predicted_angle(pred_class):
return "angle = " ... |
#!/usr/bin/env python3
''' Script to precompute image features using a Pytorch ResNet CNN, using 36 discretized views
at each viewpoint in 30 degree increments, and the provided camera WIDTH, HEIGHT
and VFOV parameters. '''
import os
import sys
import MatterSim
import argparse
import numpy as np
import jso... |
from prophyc.generators import word_wrap
from prophyc.generators.base import GeneratorBase, TranslatorBase
libname = u"prophy"
primitive_types = {x + y: u"%s.%s" % (libname, x + y) for x in u"uir" for y in ["8", "16", "32", "64"]}
primitive_types['byte'] = u'%s.u8' % libname
def _make_list(repr_function, members):
... |
from collections import namedtuple
import torch
import torch.nn as nn
from model.pointnet2.pointnet2_paconv_modules import PointNet2FPModule
from util import block
class PointNet2SSGSeg(nn.Module):
r"""
PointNet2 with single-scale grouping
Semantic segmentation network that uses feature propogat... |
import os
from collections import defaultdict, OrderedDict
from enum import Enum
import torch
from torch import nn
from torch.nn import functional as F
from anomaly_detection.dpa.feature_extractor import PretrainedVGG19FeatureExtractor
class L2Loss(nn.Module):
def __init__(self, reduction='mean'):
super(... |
import time
import numpy as np
import os
from collections import namedtuple
from keras.utils import np_utils
from keras.models import load_model
from keras.layers import (Dense, Conv2D, MaxPooling2D,
Reshape, Dropout, Flatten)
from keras.models import Sequential
from keras.opti... |
#!/usr/bin/env python3
import argparse
import os
import os.path as path
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import *
from tensorflow.keras.models import load_model
from tensorflow.keras.optimizers.schedules import PiecewiseConstantDecay
from mobile... |
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import pandas as pd
import random
import numpy as np
import cv2
import os
from models import *
import json
import seaborn as sns
def classes(y_test,pred):
"""
:param y_test: true_labels
:param pred: predicted output
... |
import os
from libs import config_bot as config
from peewee import *
from playhouse.apsw_ext import APSWDatabase
import logging
# if be.DEBUG_MODE:
# cleaner = logging.getLogger('peewee')
# cleaner.addHandler(logging.StreamHandler())
# cleaner.setLevel(logging.DEBUG)
db_bot = APSWDatabase(os.... |
"""
utils.py
Functions to be used by other optimization routines
"""
from __future__ import print_function, division
import cplex
import scipy.io
import pandas as pd
import numpy as np
from .globals import MODEL_DIR
import os
import anndata
def get_steadystate_constraints(model):
"""
Uses the s_mat to define... |
import pandas as pd
import datetime as dt
import numpy as np
from enum import Enum
from typing import List, Tuple
class Community(Enum):
ESPANA = 'Spain', 47026208, 'ES'
ANDALUCIA = 'Andalucía', 8414240, 'AN'
ARAGON = 'Aragón', 1319291, 'AR'
ASTURIAS = 'Asturias', 1022800, 'AS'
BALEARES = 'Baleare... |
'''
XlPy/Link_Finder/crosslinks
___________________________
Calculates the theoretical crosslinker combinations from a given
fragment composition and peptide count.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.... |
# written by kylesim
from argparse import ArgumentParser
# for directories of text files where the name of each directory is the name of each category and each file inside of each directory corresponds to one sample from that category
from sklearn.datasets import load_files
from sklearn.model_selection import train_tes... |
import random
import numpy as np
import pandas as pd
from copy import copy
from datetime import datetime
from tqdm import tqdm, tqdm_notebook
def generate_solution(problem,
alpha=1.0,
betta=0.5,
patience=50,
verbose=False) -> np.... |
from typing import (
Union, Optional, Sequence, Iterable, Callable, List, Tuple, Sized,
TypeVar, NewType,
)
from functools import wraps
from rich.progress import (
_TrackThread,
Task,
track as _track,
Progress as _Progress,
Column,
BarColumn,
TextColumn,
SpinnerColumn,
Prog... |
# Copyright 2022 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 rev
import wpilib
import wpiutil
import wpiutil.log
from enum import Enum
from magicbot import tunable, feedback
class CargoColour(Enum):
NONE = wpilib.DriverStation.Alliance.kInvalid
RED = wpilib.DriverStation.Alliance.kRed
BLUE = wpilib.DriverStation.Alliance.kBlue
def is_opposition(self) ->... |
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
import torch
import torch.nn as nn
import torch.optim as optim
import visdom
import cv2
from img_dataset import test_dataloader, train_dataloader
from FCN import FCN8s, FCN16s, FCN32s, FCNs, VGGNet, FusionNet
from ... |
from __future__ import print_function
import argparse
import logging
import os
import sys
from importlib import import_module
from multiprocessing import freeze_support
from rdkit import Chem
from . import Calculator, __version__, descriptors
from ._base import get_descriptors_in_module
from ._util import PathType, ... |
import os
from arcgis_satellite_api.satellite.arcgis_satellite_api import Satellite_data
ARCGIS = Satellite_data()
def test_convert_base64_to_np_array():
"""Tests the base64 image to np array function.
Tests the buffer_to_bgr function which is supposed to convert
a base64 string to a numpy BGR array. A... |
import os
import requests
from config import (
API_ID,
API_HASH,
BOT_TOKEN,
UNSPLASH_ACCESS_KEY
)
from pyrogram import Client,filters,types
access_key = UNSPLASH_ACCESS_KEY
api = 'https://api.unsplash.com/photos?client_id={}'
random_photos = 'https://api.unsplash.com/photos/random/?count={}&client_i... |
import spectra
def get_digital_standards():
"""
Return a dictionary holding the City of Philadelphia's
color palette as defined in the Digital Standards.
Notes
-----
See https://standards.phila.gov/guidelines/design-development/brand-elements/color-palette/
"""
palette = {}
palett... |
# Copyright 2018 Alibaba Group. 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 applicable law o... |
import cv2
import math
import numpy as np
import torch
import random
import string
import torchvision.transforms as transforms
from copy import deepcopy
from torch.autograd import Variable
import os
from config import system_configs
from utils import crop_image, normalize_, color_jittering_, lighting_, \
get_affine... |
import numpy as np
from scipy.optimize import minimize
class portfolioManager:
#n number of assets available for investment, assets is an array of names for each available assets
def __init__(self, n, trading_fee=0):
#self.portfolio = np.ones(n)/n
self.portfolio = np.zeros(n)
self.portfolio[0] = 1
self... |
from __future__ import division
import numpy as np
from .recspeed import local_maxima, _filter_peaks
from dipy.core.geometry import unique_edges
#Classes OdfModel and OdfFit are using API ReconstModel and ReconstFit from .base
class OdfFit(object):
pass
class OdfModel(object):
"""An abstract class to be sub-... |
"""Tests for DockerSpawner class"""
import asyncio
import json
import docker
import pytest
from jupyterhub.tests.mocking import public_url
from jupyterhub.tests.test_api import add_user
from jupyterhub.tests.test_api import api_request
from jupyterhub.utils import url_path_join
from tornado.httpclient import AsyncHTTP... |
import numpy as np
import segyio as so
from scipy.signal import butter, sosfilt
import time
# Simple timer with message
def timer(start, message):
end = time.time()
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
info('{}: {:d}:{:02d}:{:02d}'.format(message, int(hours), int(min... |
from app import app
import json
from flask import jsonify
from modules.twitter_user import TwitterUser
from app.models import ActorReport, TweetReport, Actor, RelationReport, TLRelationReport
from app import db
@app.route('/test')
def test_route():
return "hello world"
@app.route('/api/actors')
def api_get_actors():... |
"""
MAIN FILE in the "BA" Neuronal Network Repositoy
CALL BY: <main.py>
RETURN: -
INFO: This Git-Repository holds all the Code written for my Bachelor Thesis at the Chair of Automatic Control at TF Uni Kiel.
The Programming Language is Python.
In this Main-Function, modules are ... |
from __future__ import division, print_function, absolute_import
from six.moves import xrange as range
import os, sys, re, codecs
import tensorflow as tf
import numpy as np
from seq2seq.seq_module import Seq2seq
sys.path.append("../")
from text_cnn.train_cnn import Cnn_Graph
from misc.data_prep import *
from hyperpara... |
from django.shortcuts import render, redirect
from django.utils.timezone import now
from apps.petit.models import Product, Customer, Orderbill, Orderbilldetail
from apps.petit.util import obtenerIP, obtenerFechaExpiracion
from apps.petit.apiTPaga import ApiTPaga
from django.contrib import messages
from django.con... |
import sqlite3
import pandas as pd
import sys
from pprint import pprint
import soccerAnalysis1
import sqlite3
import pandas as pd
from sklearn.manifold import TSNE
from scipy.spatial import distance
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
fr... |
# -*- coding: utf-8 -*-
# Copyright 2011 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
from collections import Counter
from itertools import combinations
from Game.utils import Chosen_Card_Info
# gets the most common element from a list
def Most_Common(lst):
data = Counter(lst)
return data.most_common(1)[0]
# gets card value from a hand. converts A to 14, is_seq function will convert the 14... |
import numpy as np
from collections import defaultdict
def insert_value(ii, jj, z, room_up_down, room_len, num_x, num_y):
r_number = int(np.ceil(jj / room_len) + num_x * np.floor(ii / room_len)+ (num_x*num_y) * np.floor(z / 2))
if r_number in room_up_down:
return r_number
else:
return 'w'
... |
# encoding: utf-8
"""
@author: whou
@contact: <EMAIL>
@version: 1.0
@file: viewpoint_mining.py
@time: 2019-08-09 19:39
这一行开始写关于本文件的说明与解释
"""
import sys
sys.path.append("../")
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
from typing import List, Tuple
# import finance... |
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import urllib.request
import time
from... |
import numpy as np
from sklearn.decomposition import PCA
import csv
import pandas as pd
import matplotlib.pyplot as plt
def load_data():
"""
Load embedding information and corresponding words from generated LSHWE embedding.
"""
word_dict = {}
words = []
x = []
with open("./generated_embs/lshwe_embedding.cs... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
sys.path.append('.')
import os
import h5py
import argparse
import tensorflow as tf
from PIL import Image
from model import VAEModel
from utils import im... |
import os
import random
import string
import tempfile
from pathlib import Path
import pytest # type: ignore
from google.cloud import storage
from google.api_core.exceptions import NotFound
from replicate.exceptions import DoesNotExistError
from replicate.repository.gcs_repository import GCSRepository
from replicate.h... |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional
from pydantic import BaseModel
from starlette.responses import RedirectResponse
import time
import re
from math import floor
import webvtt
from io import StringIO
from indicTrans.inference.engine import Model, ... |
import logging
import sys
from pathlib import Path
from datetime import datetime
import json
import sqlite3
from zensols.persist import (
persisted,
resource
)
from zensols.garmdown import (
ActivityFactory,
Backup,
)
logger = logging.getLogger(__name__)
class connection(resource):
def __init__(s... |
"""
Module for performing Promiscuity Index
calculations for the Hetaira web tool.
"""
import numpy as np
from .util import process_data
from string import ascii_lowercase
def calculate_results(file):
"""
Working function to be called by main view function.
"""
data = process_data(file)
promiscui... |
# -*- coding: utf-8 -*-
"""
1. Replicate some of the sanity checks in tybalt_vae.ipynb
2. Extracting decoder weights as in extract_tybalt_weights.ipynb
Note that Tybalt uses python version 3.5
The associated environment can be activated via:
conda activate tybalt
"""
import os
import csv
import h5py
import numpy... |
# Copyright (C) 2006-2011, University of Maryland
#
# 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,... |
"""utils.py
A few useful objects which do not naturally fit anywhere else.
"""
import ast
import difflib
import uuid
import pure_eval
from . import debug_helper
from .ft_gettext import no_information, internal_error
class RuntimeMessageParser:
"""Used to collect message parsers and cycle through them in
an ... |
import os
from external_cmd import TimedExternalCmd
from defaults import *
from utils import *
FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s'
logFormatter = logging.Formatter(FORMAT)
logger = logging.getLogger(__name__)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)... |
import sys
import numpy as np
import pandas as pd
num_of_shards = 0
num_of_nodes = 0
algorithm = ''
def shard_allocator(shards, nodes, algorithm_name):
global num_of_shards, num_of_nodes, algorithm
num_of_shards = shards
num_of_nodes = nodes
algorithm = algorithm_name
print("Shard allocation st... |
"""
All database related methods are in DatabaseHelper() class.
"""
import app as near_buy
import bcrypt
from pymongo import MongoClient
from pymongo import errors
class DatabaseHelper(object):
def __init__(self):
try:
self.client = MongoClient()
self.db = self.client.production
... |
__copyright__ = '''
The MIT License (MIT)
Copyright (c) 2021 <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... |
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
import argparse
import sys
import numpy as np
import torch.nn.functional as F
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
def parse_args():
parser = argparse.ArgumentParser(descrip... |
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import seaborn as sns
from networkx import *
import matplotlib.pyplot as plt
sns.set()
def distance(s_lat, s_lng, e_lat, e_lng):
# approximate radius of earth in km
r = 6373.0
s_lat = s_lat * np.pi / 180.0
s_lng... |
from ..utils import einstr
from string import ascii_letters as chars
import numpy as np
import scipy.linalg as la
def einsumsvd_implicit_rand(backend, subscripts, *operands, rank, niter, orth_method, absorb_s):
if orth_method == 'qr':
orthogonalize = orthogonalize_qr
elif orth_method == 'local_gram':
... |
'''
深度优先算法求解八数码问题;
'''
import numpy as np
class State:
'''
状态图
'''
def __init__(self, state, directionFlag=None, parent=None):
self.state = state # 当前状态
self.depth = parent.depth+1 if parent is not None else 1
self.boarder = len(self.state) - 1 # 在八数码问题中,该值等于2,即九空格行索引的上界。
... |
import sys
import math
sys.path.append('..')
import codestudio.gamegrids as gg
from nose.tools import eq_,ok_
class TestXYGrid():
def setup(self):
self.grid = gg.XYGrid()
def defaults_test(self):
eq_(self.grid,[[]])
def init_test(self):
eq_(self.grid.init(3,2,'~'), self.grid)
... |
import var
import img
import const
import pygame
import physics
class UI():
title_text = [8, 8]
rect = [160, 160, 960, 400]
name = [240, 240, 800, 80]
name_text = [248, 260]
exit_button = [1080, 160, 40, 40]
done_button = [1080, 520, 40, 40]
def loop():
display()
def display():
var.sc... |
# -*- coding: utf-8 -*-
import os, sys, pdb
import shutil
from torchvision import models
import torch.backends.cudnn as cudnn
import torch
import torch.optim as optim
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from visdom import Visdom
from loader import train_loader, va... |
# -*- coding: utf-8 -*-
# Name: <NAME>
# NUSP: 9778985
# Course Code: SCC0251
# Semester: 2019/1
# Assignment: 4 - Colour image processing and segmentation
# %%
import numpy as np
import random
import imageio
# %%
# * Defining functions for assignment
def init_centroids(dataset, k, S):
"""Returns k random centro... |
from datetime import datetime, date
from dateutil.tz import tzutc
from django.conf import settings
from django.http import HttpResponseRedirect
from django.test import RequestFactory
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.sessions.middleware import SessionMiddleware
fr... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import getpass
import os
import sys
from github import GithubException
from git import git_clone
from github_util import GithubUtil
from i3helper import TemporaryDirectory
from mantis_converter import MantisConverter
def add_arguments(par... |
# Copyright 2022 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... |
"""
Creates a MobileNetV1 Model as defined in:
<NAME>. <NAME> <NAME>, et.al. (2017 CVPR).
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications.
Copyright (c) <NAME>, 2017
"""
import torch.nn as nn
import torch.nn.functional as F
import models.ops as ops
from models.imagenet.utils import... |
from api import os
from api.os import path
dockerfile_tpl = """
FROM gplane/pnpm:{version}
WORKDIR /app
{pm_copy}
{inject_prepare}
{pm_install}
COPY . .
{inject}
{pm_start}
ENTRYPOINT ["docker-entrypoint.sh"]
"""
dotfile_config_tpl = """
location ~ /\\. {
deny all;
access_log off;
log_not_found ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.