text stringlengths 3.07k 12.6k |
|---|
import ujson
import math
import mercantile
import mapbox_vector_tile
import logging
import aiohttp.errors
from aiohttp.web import Response
from shapely import wkb
from aiovectortiler.config_handler import Configs
logger = logging.getLogger(__name__)
generic_headers = {
'Cache-Control': 'max-age=86400'
}
class ... |
from shakenfist.exceptions import (NoURLImageFetchTaskException,
NetworkNotListTaskException,
NoInstanceTaskException,
NoNetworkTaskException,
NoNetworkInterfaceTaskException
... |
from __future__ import division
import os
import urllib
import pymongo as pm ## first establish ssh tunnel to server where database is running
import base64
import numpy as np
from numpy import *
import PIL
from PIL import Image
import base64
import matplotlib
from matplotlib import pylab, mlab, pyplot
from IPython.cor... |
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.optim as opt
from torch.nn.utils import clip_grad_norm_
from models import judge, intelligence
import matplotlib.pyplot as pl
import numpy as np
from data import get_dataloaders
import os
def train(... |
import abc
import os
from utils.csv_utils import process_data_csv
from utils.txt_utils import process_data_txt
from hypernlp.nlp.data_process.format_dataset import CSVDataset, TXTDataset
from utils.logger import logger
class Reader(object):
def __init__(self, data_folder, classes2idx):
self.data_folder =... |
import math
import decimal as dec
import numpy as np
class MethodResult:
number_of_steps = 0
root = 0
def f1(x):
return dec.Decimal(math.cos(x) * math.cosh(x))
def f1der(x):
return dec.Decimal(math.cos(x) * math.sinh(x) - math.sin(x) * math.cosh(x))
def f2(x):
if math.isclose(x, 0.0, abs_tol... |
#!/usr/bin/env python
# coding: utf-8
# ## **Importing libraries**
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Input, Conv2D, BatchNormalizat... |
import os
import pkgutil
import sys
from copy import deepcopy
from importlib import import_module
from django.apps import apps
from django.utils.module_loading import module_has_submodule
from . import documents
from . import Server
def server_setup(verbosity=0, stdout=sys.stdout):
from django.conf import setting... |
import re
from contextlib import contextmanager
from . import document
class Element:
'''
Represents a semantic component of a document.
'''
# A void element is an element that has no text content
# inside it, e.g. an <img> in HTML.
is_void = False
class Document(Element):
def __init__... |
import collections
import six
import theano.tensor as T
from neupy.utils import as_tuple
from neupy.exceptions import LayerConnectionError
from neupy.core.properties import TypedListProperty, Property
from .base import ParameterBasedLayer
__all__ = ('Convolution',)
class StrideProperty(TypedListProperty):
"""... |
#######################################################
# Script Parameters
#######################################################
scientific_library = 'OpenCV' # Set this to 'OpenCV' or 'SciPy'
input_filename = 'Greist_Building.JPG'
output_width = 1000
output_height = 850
#####################################... |
# -*- coding: utf-8 -*-
"""
Implementation of simple Euler solver and Euler solver with correction for 1D simple ODE like: y'(x) = f(x)
@author: ssklykov
"""
#%% Import section
import SampleF # (!): import module allows to import docstrings as well
import inspect
import numpy as np
import matplotlib.pyplot as plt
#%... |
#! /usr/bin/env python3.8
"""
Part of odin-api, tools to make it happen
"""
from os import environ
from time import sleep
from datetime import date, timedelta, datetime
from argparse import ArgumentParser
from psycopg2 import connect
from requests import get
from requests.exceptions import HTTPError
from dateutil impor... |
from pathlib import Path
import cv2
import numpy as np
import torch
import torch.nn as nn
from torch2trt import torch2trt
# noinspection PyUnresolvedReferences
import _init_paths
from bench import bench
# from debug2 import PostProcess
from models.model import load_model
from models.networks import mobilenetv2_center... |
import numpy as np
from mpmath import *
n = 100 # profunditat
Z1 = 0.1 + 0.5 * 1j # impedàncies
Z2 = 0.02 + 0.13 * 1j
Z3 = 0.023 + 0.1 * 1j
Zp = -10 * 1j
Y1 = 1 / Z1 # admitàncies
Y2 = 1 / Z2
Y3 = 1 / Z3
Yp = 1 / Zp
P = -1 # dades
Q = -0.1
Va = 1.1
van = 0.5 # dades de la làmpada
lam = 2 * np.sqrt(2) / np.pi... |
import time
import Letter
import fileLoader
import HangMan_Logic
import HangMan_PixelArt
import clearScreen
#This render function is used to call the pixel art rendering as well as printing the word/ spaces
def render(word, wrongAnswers):
#Print pixel art first
HangMan_PixelArt.printHangArt(wrongAnswers)
#Now we ... |
import difflib
from collections import defaultdict
from dataclasses import dataclass
from typing import Any, Dict, List, TypeVar
import numpy as np
from pydantic import BaseModel
from ...training.stemming import StemDict
from ...utils import Settings, get_logger
log = get_logger(__name__)
T = TypeVar("T")
Histogram ... |
from __future__ import print_function
from keras.layers import (Input, Dense, Conv2D, MaxPooling2D, ZeroPadding2D,
Flatten, Dropout, GlobalAveragePooling2D,
GlobalMaxPooling2D, Dropout, Activation)
from keras.engine import Layer, Model
from keras import backend as K
i... |
def get_geo(geofile_b, release, sl):
from operator import itemgetter
"""Return the geo rows, indexed to the stusab and logrecno, for a summary level"""
from collections import OrderedDict
if not hasattr(geofile_b, '_census_geo'):
geofile_b._census_geo = {}
geo = geofile_b._census_geo
... |
import os
import csv
# RedVox and Red Pandas modules
from redvox.common.data_window import DataWindow
import redpandas.redpd_datawin as rpd_dw
import redpandas.redpd_dq as rpd_dq
from redvox.api1000.wrapped_redvox_packet.station_information import OsType
import redvox.common.date_time_utils as dt
from redvox.common.s... |
import numpy as np
import os
import sys
from scipy import integrate
from math import floor
import scipy.io as sio
from thermo.math.correlate import autocorr
__author__ = "<NAME>"
__email__ = "<EMAIL>"
def __metal_to_SI( vol, T ):
'''
Converts LAMMPS metal units to SI units for thermal conductivity calculation... |
from tkintertoy import Window
import os
from functions.gsheet import GSheet
import configparser
import webbrowser
class Gui(object):
def __init__(self):
# read configuration file
self.dir_path = os.path.dirname(os.path.realpath(__file__))
self.config = configparser.ConfigParser()
s... |
from __future__ import print_function
import os
import argparse
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import models
from flops import *
# Training settings
parser = argparse.ArgumentPa... |
# coding: utf-8
# In[3]:
import random
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123)
np.random.rand()
# In[4]:
def individual(popSize):
return list(np.random.choice([0,1],popSize))
# In[5]:
def population (popSize,chromLeng):
return [individual(popSize) for x in range(chromL... |
def convert_to_nc(data_in, data_out, converter, path_to_converter=None):
'''
Import appropiate converter, which is a file in folder "converters" within
this module, or a customade file in the "path" folder
'''
import imp
try:
if path_to_converter is None:
exec('fr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# invoke with python3 -O xur.py to omit debug output
# constants
xurAPIuri = 'https://paracausal.science/xur/current.json' # props to @nev_rtheless for this fine endpoint :)
bungoAPIbaseURI = 'https://www.bungie.net/Platform/Destiny2/'
bungoXurURI = 'Vendors/?components... |
"""
Core functions for management of runs in AskAnna
This is the class which act as gateway to the API of AskAnna
"""
import click
from typing import List
from askanna.core import client, exceptions
from askanna.core.dataclasses import RunInfo, Run
from askanna.core.job import JobGateway
from askanna.core.metrics imp... |
# 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
#
# less required by applicable law or agr... |
import urllib
from urllib import request
from bs4 import BeautifulSoup as bs
import datetime
def choiceCheck(choice):
# User is prompted to enter the choice at the beginning of the program.
if choice == "1" or choice == "2" or choice == "3":
return True
else:
return False
def userChoice():
# Asking the ... |
from sqlalchemy import Column, String, Integer, SmallInteger,create_engine, ForeignKey, Float
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# Cree la clase base del objeto:
Base = declarative_base()
def normaliza(texto):
aux = texto.lower()
eliminar = { "á"... |
import json
import copy
import logging
import time
from openrouteservice import client
from itertools import groupby
import objectparams as opms
import transportmeans as trmns
import osm2geojson as o2g
logger = logging.getLogger('locationsearch')
opr_api_key = '' # put here your openrouteservice api key
opr_client ... |
#!/usr/bin/env python
# -*- python-version >= 3.4 -*-
"""
For a set of SWC neurons (subset of dendrites), load them in the model [1] and
calculate stats which can later be used for parameter estimation.
"""
import statistics
import glob
import textwrap
from pprint import pformat
from plucky import merge, plucks
from ... |
import logging
import jsonpath_rw
from jsonpointer import JsonPointer
from .stages import JsonStage, OffsetStage
from .utils import get_obj_id, init_stage_spec
from .wflownode import YadageNode
log = logging.getLogger(__name__)
class WorkflowView(object):
"""
Provides a 'view' of the overall workflow objec... |
"""Royal Mail Shipping Service Datatypes definition module."""
import attr
from typing import List
from jstruct import JList, JStruct
@attr.s(auto_attribs=True)
class Address:
building_name: str = None
building_number: str = None
address_line1: str = None
address_line2: str = None
address_line3: ... |
import os
import logging
import re
from xml.dom.minidom import parse, parseString
def write_log(log, repo, msg, level="error"):
if (log != None):
log.add_error(repo, msg)
else:
logging.debug("%s: %s" % (str(repo), msg))
def get_android_jar(android_home, version):
"""Find the right androi... |
"""
Utility methods for analysis-runner server
"""
import os
from shlex import quote
from typing import Any, Dict
from aiohttp import ClientSession, web
from cpg_utils.auth import check_dataset_access, get_user_from_headers
from cpg_utils.deploy_config import get_deploy_config, get_server_config
from cpg_utils.storage... |
from typing import Type, Dict, Callable, Union, List, Sequence
from webdnn.backend.code_generator.templates.elementwise import RegisteredItem
from webdnn.backend.webgl.generator import WebGLDescriptorGenerator
from webdnn.backend.webgl.kernel import Kernel
from webdnn.backend.webgl.kernel_code import KernelCode, Globa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The clients module
This module provides special subclasses of the JobManager_Client
"""
import os
import sys
import traceback
from .jobmanager import JobManager_Client
from . import ode_wrapper
def merge_arg_and_const_arg(arg, const_arg):
"""
prepares data ... |
import json
import requests
from pleroma_bot.i18n import _
from pleroma_bot._utils import spinner
def _get_twitter_info(self):
"""Updates User object attributes with current Twitter info
This includes:
* Bio text
* Profile image url
* Banner image url
* Screen name
:return: None
"... |
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import ctypes
from .headers import *
#This header file contains private interfaces to obtain process information.
#These interfaces are subject to change in future releases.
PROC_ALL_PIDS = 1
PROC_PGRP_ONLY = 2
PROC_TTY_ONLY = 3
PROC_UID_ONLY = 4
PROC_RUID_ONLY = 5
PROC_PPID_ONLY = 6
"""
@define PROC_LISTPIDSP... |
"""
This script is used to calculate the Algebraic connectivity of the analysed
cities.
"""
from itertools import chain
import networkx as nx
import numpy as np
import pandas as pd
import bikeshare as bs
def eigenvalues(laplacian):
"""
Calculates the Algebraic connectivity of a graph
Parameters
----... |
from enum import Enum
from typing import List
from school.asset_types.content import Item, Section
from school.asset_types.news import News
from school.asset_types.ufora import ContentTree, Module, Topic
from school.asset_types.zoom import Recordings
from school.utils import timeparser
from school.utils.path import Pa... |
# server.py
# main script that runs on the server side, handles clients and game
# FDbomb
#
# to do
# - add in command to place face up cards
import concurrent.futures
import json
import logging as log
import socket
from game.game import Game
from common.data import Move, Data
# CONSTANTS #
#HOST = '192.168.43.169'... |
import math
import torch
import torch.distributions as td
from nitorch.core.utils import unsqueeze, ensure_shape
from nitorch.core.constants import pi
from nitorch.core.kernels import smooth
from ..modules.base import Module
class RandomFieldSample(Module):
"""Sample a smooth random field.
The field is gener... |
from datetime import datetime
from .. import ColumnValueError, DATE_FORMAT
from .base import ComplexNullValue
from .objects import *
from .constants import COMPLEX_NULL_VALUE
class CheckboxValue(ComplexNullValue):
"""A checkbox column value."""
native_type = bool
native_default = False
allow_cas... |
import argparse
import logging
import os
import pkg_resources
import sys
import time
from . import __version__
from qtpy.QtCore import QDateTime
from qtpy.QtWidgets import (
QApplication,
QWidget,
QMainWindow,
QHBoxLayout,
QVBoxLayout)
from .search import SearchWidget, SearchState
from .summary imp... |
#!/usr/bin/env python3
import logging
import logging.config
import os
import signal
import subprocess
import traceback
from configparser import ConfigParser
import time
import json
import argparse
import sys
import subprocess
from subprocess import Popen,PIPE,STDOUT
# custom ConfigParser to keep case sensitivity
class... |
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import sys
import smtplib,time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pymongo
app = QtWidgets.QApplication([])
signup=uic.loadUi("signup.ui")
login=... |
"""
Copyright (C) 2019-2020 <NAME>
This project uses an MIT style license - see LICENSE for details.
A Color Computer Assembler - see the README.md file for details.
"""
# I M P O R T S ###############################################################
from cocoasm.virtualfiles.virtualfile import VirtualFile, CoCoFile
f... |
import pytest
import mock
from descarteslabs.common.proto.widgets import widgets_pb2
from descarteslabs.workflows import cereal
from ...identifier import parameter
from ...primitives import Str, Int
from ...containers import List
from .. import widget
@pytest.fixture
def StrWidget():
"Fixture providing a fake W... |
"""Contact prediction task.
In this task two red balls fall into a box. They bounce elastically off the
walls of the box, ultimately disappearing off the top of the screen because
there is no gravity. The subject's goal is to predict whether they will contact
each other. There is an occluder covering the bottom portio... |
import classifySpectrum as cs
import pandas as pd
import numpy as np
import math
import pickle
def loadidx(openfilename):
'''
Deal with the best-group-list data and find the best one.
:param openfilename: "best-group-info1.txt"
:return: Length and group of each list.
'''
f = open(openfilename, ... |
#!/usr/bin/env python3
import io
import os
import stat
import sys
import typing
from datetime import datetime
import click
from age import __version__ as age_version
from age.file import Decryptor, Encryptor
from age.keyloader import load_aliases, load_keys_txt, load_ssh_keys, resolve_public_key
from age.keys.agekey... |
from amuse.test.amusetest import TestWithMPI
import os
import sys
import numpy
import math
from amuse.community.aarsethzare.interface import AarsethZareInterface, AarsethZare
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.ic import plummer
try:
from matpl... |
# PBNT: Python Bayes Network Toolbox
#
# Copyright (c) 2005, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... |
from copy import deepcopy
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
from pixell import colorize
from . import ps_tools
colorize.mpl_setdefault("planck")
# Default SO attribution for tiles
so_attribution = '© <a href="https://simonsobservatory.org/">Simons Observatory</a>... |
from ctypes import *
from . import client
from . import control
from . import symbols
from .probe_process import probe_state
from .utils import *
class STARTUPINFOA(Structure):
_fields_ = [
('cb', c_ulong),
('lpReserved', c_char_p),
('lpDesktop', c_char_p),
('lpTitle', c_char_p),
('dwX... |
# Sheepdog
# Copyright 2013 <NAME>
#
# Released under the MIT license. See LICENSE file for details.
import os
import socket
import tempfile
from nose.tools import assert_equal, assert_raises, assert_true
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
from sheepdo... |
import numpy as np
import os, sys
import itertools
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from scipy.io import wavfile as wf
def load_data(feats_path, file, k):
max = 0
f= ... |
import serial
import struct
import numpy as np
import matplotlib.pyplot as plt
import time
import argparse
import sys
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--map-size', type=int, default=16,
help="Number of grids for the force map.")
parse... |
#########################
## Imports
#########################
import googleapiclient
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from httplib2 import Http
from io import StringIO
import pandas
import datetime
#########################
## Helper Functions
###... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import wget
import os
import math
from PIL import Image
from random import randint
from time import sleep
import random
# A set of tools to get data from Zwift power.
"""
################################
Individual tools
####################... |
#!/usr/bin/env python3
from __future__ import print_function
import json
import math
import sys
# as per the metadata file, input and output directories are the arguments
[_, reference_file, submission_file] = sys.argv
submission = json.load(open(submission_file, 'r'))
truth_values = json.load(open(reference_file, '... |
import _init_paths
import os.path as osp
# import sys
# import logging
import cv2
import numpy as np
# get config
from config.config import config, update_config
from utils.tictoc import tic, toc
from demo import FCISNet, FCISBase
# ros stuff
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvB... |
# -*- coding: utf-8 -*-
#
# @reference:
#
import json
import base64
"""cms_data
/ali/cms/webhook?im=slack,bearychat,wechat&slackin=xxxxxxxx&at_mobile=18600000000,18500000000&channel=temp
/ali/cms/webhook?appgroup=ap-test
Content-Length: 544
User-Agent: Apache-HttpClient/4.4.1 (Java/1.7.0_65)
Connection: Keep-Alive
H... |
#!/usr/local/bin/python
import requests
import pandas as pd
import matplotlib.pyplot as plt
import argparse
import time
headers = {
'Origin': 'https://juejin.im',
'Referer': 'https://juejin.im/books',
'Sec-Fetch-Mode': 'cors',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) Apple... |
"""
Functions related to validating configuration files such as helm chart values and our
cluster.yaml files
"""
import functools
import json
import os
import subprocess
import sys
from pathlib import Path
import jsonschema
from cluster import Cluster
from file_acquisition import find_absolute_path_to_cluster_file
fro... |
#!/usr/bin/env python
from http.server import SimpleHTTPRequestHandler, HTTPServer
from urllib import parse
from urllib.request import *
import argparse
import re
import json
import os
import requests
import xml.etree.ElementTree as ET
import base64
# Configuration
coolServerUrl = "http://localhost:9980"
solrServerU... |
import sys
import requests
from bs4 import BeautifulSoup
import sys
from datetime import datetime
import platform
import subprocess
import csv
import banner as banner
news = []
coin = [] # scrape coin name
abbrv = [] # scrape abbrv
price = [] # scrape price
rank = []
low_high = []
supply = [] # circulating supply,... |
from PyQt5.QtCore import Qt
from PyQt5.Qt import QObject
import PyQt5.QtCore as QtCore
import inspect
import datetime
import time as tim
'''
Model/Helper-Classes
'''
class MessageType:
def __init__(self, id, description):
self.typeId = id
if(id == -1): # DockElementConsole.ALL
se... |
from __future__ import print_function, division
from .accelerators_stat import get_good_sections_fast
import numpy as np
import pandas as pd
from numpy import diff, concatenate
import gc
from .goodsectionsresults import GoodSectionsResults
from ..timeframe import TimeFrame
from ..utils import timedelta64_to_secs
from .... |
from collections import defaultdict
from nltk import ngrams
from nltk.tokenize import sent_tokenize
from search_backend.text_processing.tokenizer_stemmer import process_dir, Tokenizer
LETTERS= 'abcdefghijklmnopqrstuvwxyz'
class NGramModel:
def __init__(self, n, language):
self.frequences = defaultdict(... |
import re
import shlex
import subprocess as sp
from resources.utils import readElf
# globals
objdump_name = "objdump"
# example output
"""
./build/rtos_test.xMR/rtos_test.xMR.elf: file format elf32-littlearm
SYMBOL TABLE:
00100000 l d .text 00000000 .text
00000000 l df *ABS* 00000000 build/rtos_test.... |
import xarray as xr
import DUST
from netCDF4 import num2date, date2num
import numpy as np
def create_timeseries(path, lon0=None,lon1=None,lat0=None,lat1=None):
ds = xr.open_dataset(path)
with xr.set_options(keep_attrs=True):
ds = DUST.utils.utils.region_slice(ds, lon0, lon1, lat0,lat1)
ems=ds.Emiss... |
# Noughts and crosses
from dataclasses import dataclass, field
from typing import Tuple, Literal, Optional, cast, Generator
from rl_games.core.game import Game, PlayerIndex
Marker = Literal['X', 'O']
Square = Literal['X', 'O', '']
x_marker, o_marker, empty_square = cast(Marker, 'X'), cast(Marker, 'O'), cast(Square, ... |
from sklearn import metrics
import constant
import numpy as np
def my_metric(y_true, y_predict):
accuracy = metrics.accuracy_score(y_true=y_true, y_pred=y_predict)
r = metrics.recall_score(y_true=y_true, y_pred=y_predict, average='macro')
p = metrics.precision_score(y_true=y_true, y_pred=y_predict, ... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
"""Function implementation"""
import calendar
import logging
import time
from datetime import datetime
from resilient_circuits import ResilientComponent, function, handler, StatusMes... |
import os
import pytest
from piecrust.app import PieCrust
from piecrust.sources.pageref import PageRef, PageNotFoundError
from .mockutil import mock_fs, mock_fs_scope
from .pathutil import slashfix
@pytest.mark.parametrize('fs_fac, expected_paths, expected_slugs', [
(lambda: mock_fs(), [], []),
(lambd... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import csv
from collections import namedtuple, defaultdict
from nephele2.pipelines import pipeline_error
Sample = namedtuple('Sample', ['SampleID',
'ForwardFastqFile',
'ReverseFastqFile',
... |
# import discord py library
import discord
# Imports commands
from discord.ext import commands
import math
import datetime
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024))... |
"""Contains base classes for generic Tensorflow model and trainer.
Both classes adapted from https://github.com/MrGemy95/Tensorflow-Project-Template/tree/master/base (Apache 2.0 license).
"""
import os
import shutil
from timeit import default_timer as timer
import numpy as np
import tensorflow as tf
class BaseModel... |
import discord
from discord import guild
from discord.ext import commands
import random
import asyncio
import datetime
import os
import base64
from discord.commands import \
slash_command
class Fun(commands.Cog):
def __init__(self, client):
self.client = client
g_id = os.getenv("GUILD_ID")
g... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = 'zd'
import jieba
import math
import random
import os
import numpy as np
def check_bio(tags):
"""
检测输入的标签是否为bio标签
如果不是bio标签
那么错误类型为:(1)编码不在BIO中(2)第一个编码是I(3)当前编码不是B,前一个编码不是O
:param tags:
:return:
"""
for i, tag in enumerate(tags):... |
import click
from maskcam.settings import *
from pathlib import Path
from attentive import quitevent
from json import dumps, JSONDecodeError
from maskcam.common_fns import data_generator, session_with_retry_policy, set_verbosity
from base64 import b64encode
import RPi.GPIO as GPIO
from time import time, sleep
from mask... |
import socket
import time
import json
from hashlib import sha1
import math
import os
os.chdir("../")
nodes = {}
nodes_p = {}
total_keys = {}
with open("config/params.json") as f:
params = json.load(f)
def buildTable(data):
leftTopCorner = "╔"
leftBottomCorner = "╚"
rightTopCorner = "╗"
rightBo... |
"""Functions for detecting and patrolling RfD'd pages.
When a redirect is nominated for discussion at RfD, it is placed in the
articles queue of Special:NewPagesFeed. These functions identify such
"articles", double-check that they've been filed to RfD, and, if so,
patrol them. After 30 minutes of not being filed to... |
import argparse
import multiprocessing
import torch
import torch.utils.data
import torch.nn as nn
import torch.autograd
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as dset
import torchvision.utils as vutils
import models.dcgan as dcgan
from utils import visualize_... |
import logging, pandas as pd
from datetime import datetime
from .pygraphistry import util
logger = logging.getLogger(__name__)
node_id_key = u'_bolt_node_id_key'
node_type_key = u'type'
node_label_prefix_key = u'_lbl_'
start_node_id_key = u'_bolt_start_node_id_key'
end_node_id_key = u'_bolt_end_node_id_key'
relations... |
# Copyright (c) 2017 Sony Corporation. 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 applicabl... |
from django.conf import settings
from django.http import Http404
from django_filters.rest_framework import DjangoFilterBackend
from oauth2_provider.contrib.rest_framework.permissions import IsAuthenticatedOrTokenHasScope
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_frame... |
from typing import List, Tuple
from random import shuffle
from unittest import TestCase, main
from algorithms_refined.greedy_algorithms.stable_matching import (
PersonBase, Man, Woman, stable_matching)
class PersonTestCase(TestCase):
def test_is_single(self):
w = PersonBase(id_number=111,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import os
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import time
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from torchvision.models.segmentation import lraspp_mobilenet_v3_large, deeplabv3_... |
from notion.client import NotionClient
from datetime import datetime
import os
from slugify import slugify
import re
import hashlib
import shutil
import sys
NOTION_TOKEN = os.getenv('NOTION_TOKEN')
NOTION_ROOT_PAGE_ID = os.getenv('NOTION_ROOT_PAGE_ID')
if NOTION_TOKEN is None:
sys.exit("The NOTION_TOKEN is missin... |
import math
import torch
from torch import nn
import torch.nn.functional as F
class GlobalLuongAttention(nn.Module):
def __init__(
self,
attention_dim: int,
):
'''
Luong Attention from Effective Approaches to Attention-based Neural Machine Translation
https://arxiv.org/p... |
# -*- coding=utf-8 -*-
import os
import pytest
import six
from packaging.version import Version
import pythonfinder
def test_python_versions(monkeypatch, special_character_python):
def mock_version(*args, **kwargs):
version_output = "2.7.15+ (default, Jun 28 2018, 13:15:42)\n[GCC 7.2.0]"
clas... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 15:48:56 2018
@author: kazuki.onodera
monthごとにサマる
globalに変数残さないようにした(何となく
"""
import os
import pandas as pd
import gc
from multiprocessing import Pool
from glob import glob
import utils
utils.start(__file__)
#=================================... |
# tests/test_pylotus.py
from pylotus import *
from pytest import fixture, raises
@fixture
def fissure_keys():
'''Creates a pytest fixture holding any given fissure object's keys.'''
return ['id', 'activation', 'startString',
'expiry', 'active', 'node', 'missionType',
'enemy', 'tier', 'tierNum', 'expired',
... |
import json
from signalwire.voice_response import VoiceResponse, Say, Gather
from flask import Flask, request
app = Flask(__name__)
# use a dictionary to employ a switch statement so each voicemail box is customized to the department who is
# receiving it
def choose_voicemail(args):
switcher = {
"sale_pa... |
import models.helpers as helpers
import os
import struct
import dependencies
schema = "{http://www.collada.org/2005/11/COLLADASchema}"
image_list = []
class library_image:
id = ""
filename = ""
def __init__(self):
id = ""
filename = ""
class texture_map:
filename = ""
wrap_u = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.