text stringlengths 3.07k 12.6k |
|---|
import json
import logging
import os
import sys
import signal
import socket
import time
import datetime
import inspect
from collections import OrderedDict
SIMAPP_VERSION="1.0"
SIMAPP_SIMULATION_WORKER_EXCEPTION = "simulation_worker.exceptions"
SIMAPP_TRAINING_WORKER_EXCEPTION = "training_worker.exceptions"
SIMAPP_S3_... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Tracing agent that captures periodic per-process memory dumps and other
# useful information from ProcFS like utime, stime, OOM stats, etc.
import json
im... |
from __future__ import absolute_import
from .i18n import _
from . import (
pycompat,
registrar,
templatekw,
util,
)
def tolist(val):
"""
a convenience method to return an empty list instead of None
"""
if val is None:
return []
else:
return [val]
class namespaces... |
# -*- coding: utf-8 -*-
#############################################################################
# #
# <NAME> GMBH #
# STUTTGART ... |
import json
import os
from copy import deepcopy
import traceback
from typing import OrderedDict
import commentjson
hostcwd = os.environ.get("HOSTCWD")
from .debugmode import docker_container
launch_json_py = {
#"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
... |
'''
Created on 24-May-2018
@author: <NAME>
'''
#Import all the packages we will going to use
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#Initialize the random number generator for reproducible results
np.random.seed(41)
tf.set_random_seed(41)
#Number of Sample points
n = 400
#Proba... |
# Made with python3
# (C) @FayasNoushad
# Copyright permission under MIT License
# All rights reserved by FayasNoushad
# License -> https://github.com/FayasNoushad/Translator-Bot-V2/blob/main/LICENSE
import os
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
fr... |
# mysql/mysqlconnector.py
# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
r"""
.. dialect:: mysql+mysqlconnector
:name: MySQL Connector/Python
... |
import pygame
import math
import sys
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os
screen = pygame.display.set_mode((800, 800))
class Spot:
def __init__(self, x, y):
self.i = x
self.j = y
self.f = 0
self.g = 0
self.h = 0
self... |
# https://github.com/kuangliu/pytorch-cifar/blob/master/main.py
'''Train CIFAR10 with PyTorch.'''
import json
import plotly.graph_objects as go
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
from tqdm im... |
# Copyright 2015 Google Inc. 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 or ag... |
# coding: utf-8
# In[1]:
#i would recommend you to read algorithm and data structure before messing with hashtable
# http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html
#this script features the hash function described in the book, which is mod eleven %11
#we apply hash function to all the... |
import os
import sys
from collections import defaultdict
this_dir = os.path.realpath(os.path.dirname(__file__))
sys.path.append(os.path.realpath(os.path.join(this_dir, os.pardir, os.pardir)))
from geodata.encoding import safe_encode, safe_decode
ADDRESS_EXPANSIONS_DIR = os.path.join(this_dir, os.pardir, os.pardir, ... |
# %% import library
import pathlib
import sys
from glob import glob
import numpy as np
import pandas as pd
# import residual_node2vec as rv
import utils_link_pred
from scipy import sparse
from sklearn.metrics import roc_auc_score
from tqdm import tqdm
# Helper Functions
def get_params(filename):
params = pathli... |
#!/usr/bin/env python
#
# Copyright 2019 Espressif Systems (Shanghai) PTE 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 req... |
#!/usr/bin/python3
import argparse
import json
import pexpect
import logging
import os
import subprocess
import time
logging.basicConfig(level=logging.DEBUG)
class remoteslurmkernel:
def __init__(
self,
account,
time,
kernelcmd,
connection_file,
partition="batch",
... |
'''
costs.py: contains all cost functions (and related helper functions) for spectral and siamese nets
'''
from keras import backend as K
import numpy as np
from keras.backend.tensorflow_backend import expand_dims
from sklearn.neighbors import NearestNeighbors
import tensorflow as tf
def squared_distance(X, Y=None, W... |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2020 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from pathlib import Path
import pytest
from datacube.model import DatasetType
from datacube.utils.document... |
from aerosandbox.numpy import sin, cos, linalg
from aerosandbox.numpy.array import array
import numpy as _onp
from typing import Union, List
def rotation_matrix_2D(
angle,
as_array: bool = True,
):
"""
Gives the 2D rotation matrix associated with a counterclockwise rotation about an angle.
... |
from __future__ import print_function
import json
import sys, traceback
import warnings
import braintreehttp
from flask import request, jsonify, url_for, g, Blueprint
from .. import app, strings, database, mail
from ..database import db
from ..database.models import Transaction
from ..validator import validate_donati... |
# Copyright 2021 The Cirq Developers
#
# 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 ... |
import sys
import logging
import os
import os.path
import requests
import re
import ConfigParser
def success(val): return val,None
def error(why): return None,why
def get_val(m_val): return m_val[0]
def get_error(m_val): return m_val[1]
class GetCaoliuPic(object):
"""docstring for ClassName"""
def __init__(se... |
# -*- coding: utf-8 -*-
# encoding: utf-8
'''
Created on 2015年3月1日
@author: kane
'''
import six
from billiards.pay import Pay
import alipay
from billiards.views.transaction import getIdFromTradeNum,\
transactionSuccessNotification, TRANSACTION_TIME_FORMAT
from xml.etree import ElementTree
if six.PY3:
from urll... |
"""
Code to support database helper scripts (create_db.py, manage_db.py, etc...).
"""
import argparse
import logging
import os
import sys
from migrate.versioning.shell import main as migrate_main
from galaxy.util.path import get_ext
from galaxy.util.properties import find_config_file, get_data_dir, load_app_propertie... |
import sys
import time
import pygame
import random
from pygame.locals import *
PIX = 80
SCRPIX = 60
SIZ = 0
class _2048Map(object):
def __init__(self, siz):
self.siz = siz
self.scr = 0
self.mp = [[0 for i in range(siz)] for i in range(siz)]
self.add()
self.add()
def add(self):
f = False
for i in rang... |
# --- Day 18: Snailfish ---
import copy
import math
import re
class snail_fish_number:
def __init__(self, number_str):
self.representation = number_str
def reduce_number_once(self, also_split=False):
rep = copy.deepcopy(self.representation)
i = 0
index_leftmost = -1
in... |
import decimal
from collections import defaultdict
from datetime import timedelta
from django.utils import timezone
from django.db import models
from .models import MarketAttributeType,\
MarketAttributeTypeData,\
Simulator,\
Policy,\
PolicyStrategy,\
Team,\
Strategy,\
Price,\
Mar... |
from django.db import models
from PIL import Image as PIL_Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from apps.content.models import Event
def resize(img, max_height, ... |
# Deadline : 6:00 pm
from atlassian import Confluence
from pprint import pprint
import json
cf = Confluence(
# url= '''' atlassian wwebsite of teh end-client,
# username='''' registered email-id of the end client,
# password=''''' access token to access the project pages of the end client
)
# Defi... |
# SevenBot.py
import os
import io
import re
import random
import discord
import datetime
import pytz
from discord.ext import commands
import json
from apscheduler.schedulers.asyncio import AsyncIOScheduler
f = open("config.json", "r")
config = json.load(f)
f.close()
TOKEN = config["DISCORD_TOKEN"]
GUILD = config["DI... |
from __future__ import absolute_import
import linecache
import re
import tokenize
import weakref
from functools import partial
from os.path import basename
from os.path import exists
from os.path import splitext
from threading import current_thread
from .const import SITE_PACKAGES_PATHS
from .const import SYS_PREFIX_... |
"""Finetuning methods."""
import logging
import os
import torch
from collections import OrderedDict
from espnet.asr.asr_utils import get_model_conf
from espnet.asr.asr_utils import torch_load
from espnet.nets.asr_interface import ASRInterface
from espnet.nets.mt_interface import MTInterface
from espnet.utils.dynam... |
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk, Toplevel, scrolledtext, messagebox
from tksheet import Sheet
import datetime
from proc_mem_monitor.proc_mem_handler import get_mem_usages
from proc_mem_monitor.proc_mem_plot import ProcMemPlot
from proc_mem_monitor import VERSION, LABEL_WIDTH, COMB... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import hashlib
import datetime
import xmltodict
import dicttoxml
import requests
import random
import string
from time import time
from dateutil.relativedelta import relativedelta
from code import PayError
from shop_enum import RechargeStatus
from order_... |
# ******************************************************************************
# Copyright (c) 2020, Intel Corporation
#
# 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 mus... |
from __future__ import absolute_import, unicode_literals
import logging
import logging.config
import logging.handlers
import platform
LOG_LEVELS = {
-1: dict(root=logging.ERROR, mopidy=logging.WARNING),
0: dict(root=logging.ERROR, mopidy=logging.INFO),
1: dict(root=logging.WARNING, mopidy=logging.DEBUG),... |
import praw
import configparser
import time
import datetime
from praw.models import MoreComments
cp = configparser.RawConfigParser()
configFilePath = './client.config'
cp.read(configFilePath)
current_client_id = cp.get('client-config', 'client_id')
current_client_secret = cp.get('client-config', 'client_secret')
... |
# -*- coding: utf-8 -*-
"""Format adapter for the tabulate module."""
from __future__ import unicode_literals
from cli_helpers.utils import filter_dict_by_key
from cli_helpers.compat import Terminal256Formatter, StringIO
from .preprocessors import (
convert_to_string,
truncate_string,
override_missing_val... |
#-*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
import sonnet as snt
from model.DAM_test import dam
from model.DNC import dnc
from loader import BAbITestBatchGenerator, BAbIData
F... |
# -*- coding: utf-8 -*-
"""
Helpers and Functions to make WCSAxes work in SunPy
"""
import matplotlib.pyplot as plt
import astropy.units as u
try:
from astropy.visualization import wcsaxes
except ImportError:
raise ImportError("Astropy >= 1.3 is required to use SunPy")
# Force is put here to enable disablin... |
# -*- coding: utf-8 -*-
import collections
import ctypes
import dataclasses
import decimal
import datetime
import enum
import ipaddress
import json
import pprint
import re
import sys
import urllib.parse
import pandas
###############################################################################
# data classes
@da... |
import sys
import unittest
import datetime as dt
from dataclasses import dataclass, field
from typing import List
from argparse_dataclass import ArgumentParser
class NegativeTestHelper:
"""Helper to enable testing of negative test cases.
On error parse_args() will call sys.exit().
this will hijack that ... |
# swift_build_support/toolchain.py ------------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... |
"""
sample config module
run "cp config.sample.py config.py" to create local config
edit config.py functions to override default bot behavior
"""
import boto3
import re
import os
__name__ = 'localConfig'
__package__ = 'ringcentral_bot_framework'
region = 'us-east-1'
try:
region = os.environ['AWS_REGION']
except:
... |
# -*- coding: utf-8 -*-
from socket import gethostbyaddr
from functools import wraps
from redis.exceptions import ConnectionError
from time import sleep
# rediscluster imports
from .exceptions import (
RedisClusterException, ClusterDownError
)
# 3rd party imports
from redis._compat import basestring, nativestr
d... |
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(ROOT_DIR)
import numpy as np
from embedding_net.models import EmbeddingNet, TripletNet, SiameseNet
from tensorflow.keras.callbacks import TensorBoard, LearningRateScheduler
from tensorflow.k... |
#!/usr/bin/env python
from fs.errors import FSError
from fs.opener import opener
from fs.path import pathsplit, abspath, isdotfile, iswildcard
from fs.commands.runner import Command
from collections import defaultdict
import sys
class FSls(Command):
usage = """fsls [OPTIONS]... [PATH]
List contents of [PATH]"""
... |
"""Calculate elasticity coefficients.
Functions to calculate elasticity coefficients for various community
quantities.
"""
from functools import partial
import pandas as pd
import numpy as np
from cobra.util import get_context
from micom.util import reset_min_community_growth
from micom.problems import regularize_l2_... |
#!/usr/bin/python3.6
# Copyright (c) 2020, cPanel, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of co... |
#!/usr/bin/env python
""" Index PubChem Bioassay json files with Elasticsearch or MongoDB"""
from __future__ import print_function
import argparse
import gzip
import json
import os
import struct
import sys
import time
from zipfile import ZipFile
from nosqlbiosets.dbutils import DBconnection
# Document type name for ... |
import os
import LogMerge
#### TODO: SHOULD TAKE IT AS A PARAMETER INSTEAD TO AVOID READING THE SAME FILE OVER AND OVER
#### TODO: MAIN METHOD SHOULD CALL getUsersDictionary AND THEN CREATE A USER OBJECT
# our usersdictionary is a dictionary consisting of usernames as keys and dictionaries as values
# the valu... |
import os
from typing import List, NamedTuple
import numpy as np
import torch
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from mcp.config.evaluation import BestWeightsMetric
from mcp.data.dataloader.dataloader import DataLoader, FewShotDataLoader
from mcp.model.base import Mode... |
import numpy as np
from math import ceil
def deriveSizeFromScale(img_shape, scale):
output_shape = []
for k in range(2):
output_shape.append(int(ceil(scale[k] * img_shape[k])))
return output_shape
def deriveScaleFromSize(img_shape_in, img_shape_out):
scale = []
for k in range(2):
s... |
shopping = [{"id": 1001, "Name": "HP-AE12", "Available": 100, "Price": 25000, "Original_Price": 24000},
{"id": 1002, "Name": "DELL", "Available": 100, "Price": 35000, "Original_Price": 34000},
{"id": 1003, "Name": "ASUS", "Available": 100, "Price": 28000, "Original_Price": 27000},
... |
import math
import random
import matplotlib.pyplot as plt
import numpy as np
from collections import deque, namedtuple
from PIL import Image
from th10.game import TH10
from config import *
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as ... |
import argparse
import logging
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset, TensorDataset
import torchattacks
from advertorch.defenses import MedianSmoothing2D, BitSqueezing, JPEGFilter
from clus... |
import unittest
from nose.tools import assert_equals
from robotide.editor.gridbase import GridEditor
from resources import PYAPP_REFERENCE as _ #Needed to be able to create wx components
# wx needs to imported last so that robotide can select correct wx version.
import wx
from robotide.context import IS_WINDOWS
DAT... |
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import asyncio
from collections.abc import Iterable
from functools import partial
import zmq
from aiozmq import create_zmq_connection
from .base import (
NotFoundError,
ParametersError,
Service,
ServiceClosedError,
_BaseProtocol,
_BaseServerProtocol,
)
from .log import logger
async def conn... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, <NAME>, Inc.
# Copyright (c) 2013, PAL Robotics SL
# 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 so... |
from pathlib import Path
import pytest
from RPA.PDF import PDF
RESOURCE_DIR = Path(__file__).resolve().parent / ".." / "resources"
TEMP_DIR = Path(__file__).resolve().parent / ".." / "temp"
imagesandtext_pdf = RESOURCE_DIR / "imagesandtext.pdf"
invoice_pdf = RESOURCE_DIR / "invoice.pdf"
vero_pdf = RESOURCE_DIR / "vero... |
import logging
import json
from io import StringIO
from cliff.command import Command
from cliff.lister import Lister
from cliff.show import ShowOne
from prataiclient import utils
urllib3_logger = logging.getLogger('requests')
urllib3_logger.setLevel(logging.CRITICAL)
logging = logging.getLogger(__name__)
class Fu... |
from __future__ import unicode_literals
import json
from django.db import models
from django.utils.six import text_type as str
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from django.utils import timezone
from django.contrib.auth.models import (AbstractBaseUser, Permissions... |
""" Teradata ibis client implementation """
# from typing import Optional, Tuple
import pandas
import teradatasql
import ibis.expr.lineage as lin
import ibis.expr.operations as ops
import ibis.expr.schema as sch
from ibis.client import Database, Query, SQLClient
from . import compiler # TODO non local import ie fr... |
# Copyright 2020 Google Inc. 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 or a... |
import abc
import os
import re
import sys
import tempfile
if sys.version_info[:2] < (3, 2):
from xml.sax.saxutils import escape
else:
from html import escape
def main():
if len(sys.argv) > 1 and sys.argv[1] == "-P": # For regression testing
print(create_login_form(HtmlFormBuilder()))
pri... |
# Copyright 2020 The SQLFlow 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 applicable law o... |
from collections.abc import Iterable, Iterator, Set
from typing import ClassVar, Generic, TypeVar, Union, overload
# TODO: rename to mutable and clean everything
_T1 = TypeVar('_T1')
_T2 = TypeVar('_T2')
_K = Union[_T1, _T2]
_V = tuple[_T1, _T2]
class BijectiveMapValuesView(Set[_K]):
__slots__ = '_source'
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
SERVER_IP = '0.0.0.0'
SERVER_PORT = 8777
STATS_GAUGE_APPNAME = 'app.html5player'
from gevent import monkey; monkey.patch_all()
from ws4py.websocket import WebSocket
import dns.resolver
import time
import socket
import statsd
from gevent.coros import RLock
class Stats()... |
"""
desispec.quicklook.palib
Low level functions to be from top level PAs
"""
import numpy as np
from desispec.quicklook import qlexceptions,qllogger
qlog=qllogger.QLLogger("QuickLook",20)
log=qlog.getlog()
def project(x1,x2):
"""
return a projection matrix so that arrays are related by linear interpolation
... |
import re
from typing import Any, Dict, Optional, Set, Type
from sqlalchemy.sql import sqltypes as types
from metadata.ingestion.api.source import SourceStatus
def register_custom_type(
tp: Type[types.TypeEngine], output: str = None
) -> None:
if output:
_column_type_mapping[tp] = output
else... |
# %% IMPORTS
# Package imports
from astropy.units import Quantity
from astropy.time import Time
from astropy.coordinates import Angle, SkyCoord
import astropy.constants as apc
from astropy.table import Table
import numpy as np
from py.path import local
# hickle imports
import hickle as hkl
# Set the current working d... |
# Copyright 2019 The Cirq Developers
#
# 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 ... |
from __future__ import print_function
import argparse
import os
import numpy as np
import torch
from torchvision import transforms
import dataset
from darknet import Darknet
from utils import get_all_boxes, nms, read_data_cfg, logging, map_iou
# etc parameters
use_cuda = True
seed = 22222
eps = 1e-5
FLAGS = None
de... |
import os,sys
#Please specify the mask_rcnn directory [todo: using json for specify the folder]
#github:https://github.com/matterport/Mask_RCNN
#MASKRCNN_DIR="/home/kiru/common_ws/Mask_RCNN_Mod/"
#sys.path.append(MASKRCNN_DIR)
#sys.path.append(".")
#sys.path.append("./bop_toolkit")
import numpy as np
from mrcnn.confi... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# #*** <License> ************************************************************#
# This module is part of the package CNDB.OMP.
#
# This module is licensed under the terms of the BSD 3-Clau... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms, datasets
import time, os, argparse
from torch.autograd import Variable
from modules import *
class MNIST:
def __init__(self, bs=1):
dataset_transform = transforms.Compose([
... |
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from torch.autograd import Variable
import os
import cv2
import numpy as np
from torchvision import datasets, models, transforms
label_len = 36
# vocab="<,.+:-?$ <aAàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬbBcCdDđĐeEèÈẻẺẽẼéÉẹẸêÊềỀểỂễỄếẾệỆfFgGhHiIìÌỉỈĩĨí... |
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow.python.keras.layers import Flatten
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.layers import Dropout
from tensorflow.python.keras.... |
# Author: <NAME> <<EMAIL>>
# License: BSD (3-clause)
import queue
import time
import socket
import socketserver
import threading
import numpy as np
from ..utils import logger, verbose, fill_doc
class _ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
"""Create a threaded TCP server.
... |
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn import metrics
import numpy as np
import pickle
import cv2 as cv
from tensorflow import keras
from keras import optimizers
from tensorflow.keras import layers
from feature_extractor import get_pos_neg_samples_from_pickle
from an... |
# -*- coding: utf-8 -*-
"""Tests for core application."""
from __future__ import unicode_literals
import httmock
from dateutil.relativedelta import relativedelta
from six import StringIO
from django.core import management
from django.test import TestCase
from django.urls import reverse
from django.utils import time... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Adds N number of rows of dummy data to the manifest table specified
"""
from __future__ import unicode_literals, print_function
import random
import boto3
import logging
import sys
import json
import time
from datetime import datetime
logger = logging.getLogger()
logg... |
import numpy as np
import json
from turorials.perlin_noise.obstacle_generation import flood_grid
class EnvironmentRepresentation:
def __init__(self):
self.obstacle_map = None
self.terrain_map = None
self.start_positions = None
self.nb_free_tiles = 0
self.dim = (8, 8)
... |
import asyncio
import os
import socket
import ssl
import sys
from hashlib import md5, sha256
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import mock
from uuid import uuid4
import pytest
from aiohttp.test_utils import loop_context
try:
import trustme
TRUSTME = True
except Im... |
"""
Authors: The Vollab Developers 2004-2021
License: BSD 3 clause
Calculate the local volatility surface for given characteristic function in three steps:
1. For a given characteristic function use Fast Fourier Transform to get call price surface.
2. Uses the Lets Be Rational function for ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import csv
import json
from json import JSONDecodeError
from flask import current_app as app
import dateutil.parser
import requests
from wk_client import db
from wk_client.constants import REPAYMENT_TYPE
from wk_client.models import User, CashFlow
from wk_client.settings import BANK_HOST, BANK_PASSWORD, BANK_PORT, BA... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
determine_ext,
int_or_none,
parse_iso8601,
parse_duration,
)
class NHLBaseIE(InfoExtractor):
def _real_extract(self, url):
site, tmp_id = re.match(sel... |
#!/usr/bin/env python3
#
# generate-thumbnails.py 1.1.3
#
# Copyright 2018–2021 <NAME>.
#
# 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 option) a... |
#!/usr/bin/env python3
# Povolene knihovny: copy, math, collections
# Z knihovny collections se vam muze hodit datova struktura deque:
from collections import deque
# IB002 Domaci uloha 11.
#
# Tento tyden bude vasim ukolem implementovat dva grafove algoritmy.
# Ukoly jsou zamereny na aplikace pruchodu grafem.
#
# ... |
import numpy as np
from tqdm import tqdm
# setup rpy2 on Windows
# edit the path here according to your machine
import platform
if platform.system() == 'Windows':
import os
os.environ['PATH'] = 'C:/Program Files/R/R-3.6.0/bin/' + os.pathsep + 'C:/Program Files/R/R-3.6.0/bin/x64/' + os.pathsep + os.environ['PAT... |
# noinspection PyUnresolvedReferences,PyPackageRequirements
import factory
import random
from django.conf import settings
from django.contrib.gis.geos import Point
from django.utils import timezone
from django.db.models import signals
from django.contrib.auth.models import Permission, Group
from django.contrib.contentt... |
"""
Represent a templated email message.
<NAME> <<EMAIL>>
"""
import future.backports.email as email
import future.backports.email.mime
import future.backports.email.mime.application
import future.backports.email.mime.multipart
import future.backports.email.mime.text
import future.backports.email.parser
import future... |
#-*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
import logging
import random
import string
import datetime
import json
from google.appengine.api import users
from google.appengine.ext import deferred
import httplib2
from ardux.tasks import sync_resources
from flask import redirect, g, session, request, make_resp... |
# Draw 3d plots of LUT cube file.
# Usage: python plot_cube.py [lut file] [skip(optional)]
# -Only LUT_3D type of cube format is supported.
# -If the generated plot is too messy, try larger skip value (default 4) to generate sparse meshgrid.
import sys
import os.path
import re
from mpl_toolkits.mplot3d import Axes... |
from sklearn import neural_network
import numpy as np
from sklearn.metrics import accuracy_score, precision_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from plots import makeAndPlotLearningCurve, plotConfusionMatrix, plotPerformance, plotValidationCurve
from load_data im... |
#!/usr/bin/env python3
""" Contact tracing beacon transmitter """
__copyright__ = """
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.apac... |
# -*- coding: utf-8 -*-
"""
Tests for the audiotsm.io.array package.
"""
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from audiotsm.io.array import ArrayReader, ArrayWriter, FixedArrayWriter
@pytest.mark.parametrize("data_in, read_out, n_out, data_out", [
([[]], [[]], 0, [[]])... |
from typing import List, Dict, DefaultDict
from pathlib import Path
import joblib
import collections
from tqdm import trange
import yaml
import datetime
import numpy as np
from scipy import stats
from poker_ai.games.short_deck.state import ShortDeckPokerState, new_game
from poker_ai.poker.card import Card
def _calc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.