text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from adjustText import adjust_text
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
def accuracy(model, dataloader, batch_size, gpu=False):
if gpu and torch.... |
# -*- coding: UTF-8 -*-
"""
Copyright 2020 Esri
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... |
"""
Make folds
"""
import argparse
import copy
import json
import math
import os.path
import sys
from pathlib import Path
sys.path.append('/home/user/challenges/lyft/lyft_repo/src')
import cv2
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, train_test_split
... |
"""Various helpers for web requests."""
import asyncio
import inspect
import ipaddress
import re
from dataclasses import dataclass
from functools import wraps
from typing import Any, Callable, Dict, Optional, Tuple, Union, get_args, get_origin
import ujson
from aiohttp import web
from music_assistant.helpers.typing i... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utils for generating stats from torch tensors.
"""
from typing import Iterator, List, Tuple, Union
import numpy as np
import torch
from torch.functional import F
def calc_sample_norms(
named_params: Iterator[Tuple[s... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import transaction as db_transaction
from django.http import Http404
from django.http.response import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy, reverse
from django.views import View
f... |
# UIUC COURSE GOD
# course registration cheat for UIUC
# support multiple crn for different courses
# author: <NAME>
# usage: python go.py semester netid password crn1 crn2 ...
# use semester in this format: YYYY-spring, YYYY-summer, YYYY-fall. Example: 2021-spring
# note: do not log in into the system by yourself whil... |
import numpy as np
import math
import random
from tree import Node
def readData():
data=[]
with open("iris.data", "r") as f:
for line in f.readlines():
words = line.split(",")
words[0] = float(words[0])
words[1] = float(words[1])
words[2] = float(words[2])
words[3] = float(words[3])
words[4] = wor... |
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
__all__ = ("S3MainMenuLayout",
"S3AboutMenuLayout",
"MA",
"S3LanguageMenuLayout",
"ML",
"S3OrgMenuLayout",
"OM",
"S3PersonalMenuLayout",
"MP",
)
from gluon import current, URL, \
... |
# This file contains experimental modules
import numpy as np
import torch
import torch.nn as nn
from .common import Conv, DWConv
from detector.YOLOv5.utils.google_utils import attempt_download
class CrossConv(nn.Module):
# Cross Convolution Downsample
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcu... |
from imports import *
##############################################
#### LINEAR
##############################################
def get_model_linear(maxlen,
max_features,
embed_size,
embedding_matrix,
outp_dim=6,
... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import csv
import logging
from collections import defaultdict
from textwrap import fill, indent
from typing import cast
from pants.backend.project_info.dependees import Dependees, Depende... |
"""
Support for LG TV running on NetCast 3 or 4.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.lg_netcast/
"""
from datetime import timedelta
import logging
from requests import RequestException
import voluptuous as vol
from homeassistant... |
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
from collections import Counter
import numpy as np
from .mixin import TransformerMixin, EstimatorMixin
from .base import _set_cv
from ..io.pick import _picks_to_idx
from ..parallel import parallel_func
from .... |
#!/usr/bin/env python3
import argparse
from pathlib import Path
from botocore.exceptions import ClientError
import copy
import string
import random
import json
import math
import time
module_info = {
'name': 'guardduty__list_findings',
'author': '<NAME>',
'category': 'ENUM',
'one_liner': 'Gets the gua... |
# BSD 3-Clause License.
#
# Copyright (c) 2019-2021 <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:
#
# 1. Redistributions of source code must retain the above copyright notice, this li... |
# -*- coding: utf-8 -*-
"""
Created on May 7, 2011
@author: jake
"""
from decimal import Decimal
from django import VERSION
import pytest
from djmoney.models.fields import MoneyField
from djmoney.money import Money
from .testapp.forms import (
DefaultMoneyModelForm,
DisabledFieldForm,
MoneyForm,
Mo... |
#!/usr/bin/env python
import bcc
import time
import collections
import datetime
import os
import signal
import errno
import json
import urlparse
import threading
import socket
import BaseHTTPServer
import SocketServer
import sys
EBPF_FILE = "http-requests.c"
EBPF_TABLE_NAME = "received_http_requests"
PLUGIN_UNIX_SOCK... |
import json
import os
import sys
from argparse import ArgumentParser
from shutil import which
from subprocess import check_output
from typing import Any, Dict, Iterable, List, Optional, Tuple
from .autoscaler import autoscale_hpcpack
from hpc.autoscale import clilib
from hpc.autoscale.job.demandcalculator import Dema... |
# coding=utf-8
import tensorflow as tf
import numpy as np
import helpers
class seq2seqModel():
def __init__(self, vocabulary_size, embedding_dim, encoder_hidden_units, decoder_hidden_units):
tf.reset_default_graph()
self.vocab_size = vocabulary_size
self.embedding_dim = embedding_dim
... |
"""
Facilities to interface with the Heliophysics Events Knowledgebase.
"""
import json
import codecs
import urllib
import inspect
from itertools import chain
import astropy.table
from astropy.table import Row
import sunpy.net._attrs as core_attrs
from sunpy import log
from sunpy.net import attr
from sunpy.net.base_c... |
__author__ = 'srkiyengar'
# Significant joystick code or the basis of it comes from pygame.joystick sample code
import pygame
import serial
import sys
JOY_DEADZONE_A0 = 0.2
JOY_DEADZONE_A1 = 0.1
# Before invoking this class pygame.init() needs to be called
class ExtremeProJoystick():
def __init__( self):
... |
from collections import deque
from itertools import islice
from stable_baselines.common.vec_env import VecEnvWrapper
from aprl.policies.wrappers import NoisyAgentWrapper
from aprl.training.scheduling import ConditionalAnnealer, ConstantAnnealer, LinearAnnealer
REW_TYPES = set(("sparse", "dense"))
class RewardShapi... |
# Run 'dispycosnode.py' program to start processes to execute computations sent
# by this client, along with this program.
# This example illustrates in-memory processing with 'node_setup' to read date
# in to memory. Remote tasks ('compute' in this case) then process data in
# memory. This example works with POSIX (L... |
# coding=utf-8
# Band Conditions
# By <NAME> <<EMAIL>>
#
# This skill report current conditions on ham radio bands
import re
import requests
import logging
from collections import namedtuple
from datetime import datetime
from flask import Flask, json, render_template
from flask_ask import Ask, request, session, quest... |
# -*- coding: utf-8 -*-
# A package manager meant for Pythonista, built on StaSh.
from __future__ import print_function
import argparse
import sys
from os import getcwd, mkdir, remove, rename
from shutil import rmtree
import requests
cwd = getcwd()
documentsIndex = cwd.index("Documents")
documentsIndex += len("Docum... |
"""
Sample single vm example to convert python dsl to calm v3 api spec
"""
import sys
import json
from calm.dsl.builtins import port, ref, setvar, basic_cred
from calm.dsl.builtins import Port, Service, Package, Substrate
from calm.dsl.builtins import Deployment, Profile, Blueprint
from calm.dsl.builtins import read_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Han"
__email__ = "<EMAIL>"
"""Analysis labels F1 score with labels frequency on RMSC & AAPD dataset"""
import json
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set()
def count_rmsc_label(data_path):
with open(data_path... |
import json
text = "/\\\"\b\f\n\r\t$£ह€한𐍈🐈"
for c in text:
print("char:", c)
print("json:", json.dumps(c))
print("utf-8:", c.encode("utf-8"))
print()
"""
UTF-8 encoding
up to 7 bit or 0x00007f: 0xxxxxxx
up to 11 bit or 0x0007ff: 110xxxxx 10xxxxxx
up to 16 bit or 0x00ffff: 1110xxxx 10xxxxxx 10xxxx... |
"""Handle the details of subprocess calls and retries for a given benchmark run."""
import dataclasses
import json
import os
import pickle
import signal
import subprocess
import time
from typing import List, Optional, Union, TYPE_CHECKING
import uuid
from core.api import AutoLabels
from core.types import Label
from co... |
ATOMIC_TOURNEY_NAME = "AtomicChessBot Blitz Tourney"
def fulltourneyname(tourneyname):
return tourneyname + " Arena"
FULL_ATOMIC_TOURNEY_NAME = fulltourneyname(ATOMIC_TOURNEY_NAME)
#########################################################
LICHESS_TITLES = [
"BOT",
"GM",
"WGM",
"IM",
"WIM",
... |
# -----------------------------------------------------
# Copyright (c) Shanghai Jiao Tong University. All rights reserved.
# Written by <NAME> (<EMAIL>)
# -----------------------------------------------------
import torch
import torch.utils.data
from utils.dataset import coco
from opt import opt
from tqdm import tqdm... |
# -*- coding: utf-8 -*-
"""This module helps handle node data dictionaries."""
from typing import Any, List, Mapping, Union
from pyparsing import ParseResults
from .constants import (
CONCEPT, FRAGMENT, FRAGMENT_DESCRIPTION, FRAGMENT_START, FRAGMENT_STOP, FUNCTION, FUSION, FUSION_MISSING,
FUSION_REFERENCE, ... |
#This modified version will check for available vaccination slots every minute and alert you with a ringtone
#Note: There could be some delay of updation of data in the backend systems from which this script is pulling the data
#*************Configuration***************************
numdays=14 # No. of days to monitor... |
import argparse
import os
import json
import copy
import numpy as np
from tqdm import tqdm
import sklearn
import sklearn.metrics
import gpflow
from gpflow import Parameter
import tensorflow as tf
from graph_kernels import data_utils
from graph_kernels import time_kernels
from graph_kernels import utils_opt
from gra... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 12:25:24 2018
@author: thinkpad
"""
import skvideo.io
import skimage.color
#import skimage.io
import matplotlib.pyplot as plt
import skimage.transform
from collections import deque
import numpy as np
from base.spaces import Continuous
import os
P... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
from scipy import misc
import cv2
import numpy as np
from src import facenet
from src import detect_face_cnn
import os
import pickle
import math
import json
import threadi... |
'''
Obtain the optimal constant leverage ratio in the continuous limit assuming a given time period, volatility,
and underlying return.
'''
import numpy as np
from scipy.optimize import minimize_scalar, minimize
from modules.simulate import simulateLeveragedBoundedGBM
def computeConstantLeverageReturn(leverage_ra... |
from ..worker import config
from performanceplatform.client import AdminAPI
from .util import encode_id, group_by, is_latest_data
REQUIRED_DATA_POINTS = [
{'name': "cost_per_transaction", 'ignore': 'quarterly'},
{'name': "digital_cost_per_transaction", 'ignore': None},
{'name': "digital_takeup", 'ignore'... |
import tkinter as tk
from tkinter import font
import re
global matchingSongs
matchingSongs = []
class UserEntry(tk.Entry):
def __init__(self, master, placeholder, textvariable, songDict, *args, **kwargs):
tk.Entry.__init__(self, master, *args, **kwargs)
# placeholder function
def default... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 11:01:48 2018
@author: airos
These classes help to quickly explore what SQL databases and tables are available
as well as what type of data is inside them
It allows to quickly check for unusual data (std, range, iqr)
"""
import sqlite3
from s... |
# File: T (Python 2.4)
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from pirates.piratesgui.BorderFrame import BorderFrame
from pirates.piratesbase import PLocalizer
class Tab(BorderFrame):
def __init__(self, tabBar, name, **kw):
optiondefs = (('state', DGG.DISABLED, None), ('... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018~2999 - Cologler <<EMAIL>>
# ----------
#
# ----------
from abc import abstractmethod
from typing import Any, List
from contextlib import ExitStack, nullcontext
from threading import RLock
from types import MappingProxyType
from .err import ServiceNotFoundError
from .symb... |
import sys
from types import ModuleType
__version__ = '0.9.5'
__all__ = ('importer', 'rearrange', 'Module')
def importer(_all_, *temp):
''' Dynamic run-time importer and easy to use module import path name.
Type
_all_: Dict[str, Union[str, Iterable[str], Dict[...]]]
temp: Tuple[D... |
# Copyright 2018-2020 <NAME>. See also the LICENSE file.
import os
import shutil
# noinspection PyUnresolvedReferences
import bmesh
# noinspection PyUnresolvedReferences
import bpy
# noinspection PyUnresolvedReferences
import bpy_extras
import cv2
# noinspection PyUnresolvedReferences
from mathutils import bvhtree
# ... |
import logging
from copy import deepcopy
import numpy as np
from loqusdb.build_models.variant import get_variant_id
from loqusdb.constants import GENOTYPE_MAP, HAMMING_RANGES
from loqusdb.exceptions import ProfileError
from .vcf import get_file_handle
LOG = logging.getLogger(__name__)
def get_profiles(adapter, vcf... |
from slpp import slpp as lua
from pathlib import Path
MISSION_PATH = "C:\\Users\\<NAME>\\Saved Games\\DCS\\Missions\\dcs_dnd_campaign\\extracted_mission\\mission"
DICT_PATH = "C:\\Users\\<NAME>\\Saved Games\\DCS\\Missions\\dcs_dnd_campaign\\extracted_mission\\l10n\\DEFAULT\\dictionary"
RESULTS_PATH = "C:\\Users\\... |
import torch
import pysnooper
import pysnooper.utils
import warnings
import numpy
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
class TensorFormat:
def __init__(self... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import os
import json
import requests
import time
import datetime
from IPython.display import Markdown, display
LEETCODE = 'https://leetcode.com'
def printmd(string):
display(Markdown(string))
def get_question_solution(notebook_cells):
is_solution = lambda c: c['cell_type'] == 'code' and c['metadata'].get('i... |
from transitions.extensions import GraphMachine
import random
import time
import sys
import requests
from bs4 import BeautifulSoup
import os
import re
import urllib.parse
import urllib.request
from urllib.request import urlopen
import json
import zipfile
import imghdr
import shutil
def get_web_page(url):
resp = re... |
import argparse
import os
import torch
import torch.nn.functional as F
# Lib files
import lib.utils as utils
import lib.medloaders as medical_loaders
import lib.medzoo as medzoo
from lib.visual3D_temp import non_overlap_padding,test_padding
from lib.losses3D import DiceLoss
#
def main():
args = get_arguments()
... |
# WeedBotRefresh's comic.py - based on nekosune's comic.py
from util import hook
import os
from random import shuffle
from PIL import Image, ImageDraw, ImageFont
import base64
import requests
import json
from datetime import datetime
from io import BytesIO
api_key = None
background_file = None
font_file = None
font_s... |
# Copyright 2013 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.
from __future__ import print_function
import sys
import traceback
import module as mojom
# Support for writing mojom test cases.
# RunTest(fn) will execut... |
import base64
import logging
import time
import traceback
import requests
import rsa
# 日志基础配置
# 创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 创建一个handler,用于写入日志文件
# w 模式会记住上次日志记录的位置
fh = logging.FileHandler("./log.txt", mode="a", encoding="utf-8")
fh.setFormatter(logging.Formatter("%(message... |
import torch
import torch.nn as nn
class BasicConv3d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, stride, padding=(0, 0, 0)):
super(BasicConv3d, self).__init__()
self.conv = nn.Conv3d(in_channel, out_channel,
kernel_size=kernel_size, st... |
# Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
# Released under the MIT License. See LICENSE for details.
#
"""Functionality for the actual Entity types."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, TypeVar
from efro.entity._support import FieldInspector, BoundCompoundValue
from efro.entity._value import CompoundValue
from ... |
import argparse
import json
import os
import pickle
import numpy as np
from drqa.retriever.utils import normalize
from tqdm import tqdm
from utils.config import Config
from utils.data_reader import prediction_2_label, embed_data_set_with_glove_and_fasttext
from utils.estimator_definitions import get_estimator
from uti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from keras.layers import (Conv2D, BatchNormalization, MaxPool2D, Input, Permute, Reshape, Dense, LeakyReLU, Activation,
Bidirectional, LSTM, TimeDistributed)
from keras.models import Model
from keras.layers import ZeroPadding2D
from keras.activat... |
import sys
import glfw
import OpenGL.GL as gl
from PIL import Image
from pathlib import Path
from ctypes import c_uint, c_float, sizeof, c_void_p
CURDIR = Path(__file__).parent.absolute()
RESDIR = CURDIR.parent.parent.joinpath("resources")
sys.path.append(str(CURDIR.parent))
from shader import Shader
def Tex(fn):
... |
import tempfile
import time
import re
import uuid
import random
from nose.tools import assert_raises, assert_false, assert_is_not_none, assert_true, assert_equals, assert_in
from synapseclient.core.exceptions import *
from synapseclient import *
from tests import integration
from tests.integration import schedule_for_... |
import asyncio
import inspect
import logging
import warnings
import os
from typing import AbstractSet, Any, List, Text, Optional, Coroutine, Union
import rasa_sdk
from rasa_sdk.constants import (
DEFAULT_SANIC_WORKERS,
ENV_SANIC_WORKERS,
DEFAULT_LOG_LEVEL_LIBRARIES,
ENV_LOG_LEVEL_LIBRARIES,
)
logger ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2013, the codeeditor development team
#
# Pyzo is distributed under the terms of the 2-Clause BSD License.
# The full license can be found in 'license.txt'.
import re
from . import Parser, BlockState, text_type
from .tokens import ALPHANUM
from .tokens import (
Token,
C... |
# Written by Dr <NAME>, Marda Science LLC
# for the USGS Coastal Change Hazards Program
#
# MIT License
#
# Copyright (c) 2021, Marda Science LLC
#
# 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 Soft... |
import abc
import instaseis
from obspy.taup import TauPyModel as _TauPyModel
import obspy
from typing import Union as _Union, Tuple as _Tuple
from SS_MTI import PhaseTracer as _PhaseTracer
from SS_MTI import GreensFunctions as _GreensFunctions
from SS_MTI import PreProcess as _PreProcess
class _AbstractForward(metac... |
import relstorage.adapters.postgresql
import relstorage.storage
import relstorage.options
import ZODB
from . import search as _search
from ._adapter import Adapter
class NewtDB:
"""Wrapper for a ZODB.DB object that provides newt.db-specific connections
"""
def __init__(self, db):
self._db = db
... |
#!/usr/bin/python3
import discord, sys, asyncio
from discord.ext import commands
"""
This program is a discord bot, through which mafia can be played.
"""
BOT_PREFIX = '!'
BOT_DESCRIPTION = "Play mafia, with your friends, through discord."
JOIN_LENGTH = 10
NIGHT_LENGTH = 10
DAY_LENGTH = 20
bot = commands.Bot(comm... |
"""
Linear Lasso-PCR, outputs coefficient
"""
from sklearn.linear_model import Lasso
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
import torch
import matplotlib.pyplot as plt
import numpy as np
# read in fmri data
import os
import glob
import nibabel as nib
import nilearn as nil
from jobl... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import warnings
import numpy as np
import pandas as pd
from pycox import utils
def make_cuts(n_cuts, scheme, durations, events, min_=0., dtype='float64'):
if scheme == 'equidistant':
cuts = cuts_equidistant(durations.max(), n_cuts, min_, dtype)
elif scheme == 'quantiles':
cuts = cuts_quantiles... |
def contar_letras(lista: list):
letras_c = dict()
for l in alfabeto:
letras_c[l] = 0
for word in lista:
word = word.replace('\n', '')
for l in alfabeto:
if l in word:
letras_c[l] += 1
return letras_c
def organizar_dict(dicio):
value_key_pairs... |
import numpy as np
import random
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import model_selection
import cv2
import pathlib
import os
import pathlib
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def read_csv_data():
CENTER, LEFT, RIGHT, STEERING, THROTTLE, BRAKE, SPEED = range(7)
#driving_lo... |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
import os.path as osp
from collections import defaultdict, OrderedDict
import torch
from .base_solver import BaseSolver
from .registry import SOLVERS
from ..utils.data import transfer_data_to_cuda, transfer_data_to_cpu
from ..utils.distribute impor... |
import struct
import common.numpy_fast as np
from selfdrive.config import Conversions as CV
# *** Honda specific ***
def can_cksum(mm):
s = 0
for c in mm:
c = ord(c)
s += (c>>4)
s += c & 0xF
s = 8-s
s %= 0x10
return s
def fix(msg, addr):
msg2 = msg[0:-1] + chr(ord(msg[-1]) | can_cksum(struct... |
import requests
import json
import bs4
from whapi.exceptions import ParseError
# Everything relies on the mediawiki API and the numeric article ID
# There are fancier ways to implement the various API parameters but they seem like more work than is necessary
api = 'https://www.wikihow.com/api.php?format=json&action='
... |
import gzip
import math
import os
import time
from collections import OrderedDict, namedtuple
from datetime import datetime as dt
from datetime import timedelta
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from tqdm import tqdm_notebook
import ujson
LOGS = './logs/'
Window = namedtuple('Win... |
import os
import numpy as np
from sklearn.datasets import fetch_lfw_people
from sklearn.decomposition import PCA
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import cv2 as cv
import random
import matplotlib.pylab as plt
from sklearn.neighbors import KNeighborsC... |
# -*- coding: utf-8 -*-
import pytest
import pyqtgraph as pg
from collections import OrderedDict
pg.mkQApp()
import pyqtgraph.dockarea as da
def test_dockarea():
a = da.DockArea()
d1 = da.Dock("dock 1")
a.addDock(d1, 'left')
assert a.topContainer is d1.container()
assert d1.container().container... |
from copy import copy
import jax.numpy as jnp
import numpy as np
from jax import grad
from src.optimizers import adam
from src.utility_functions import make_batches
from jax.scipy.special import logsumexp
class HSBnn:
def __init__(self, layer_sizes, train_stats, x, y, x_test, y_test, inference_engine, classificat... |
import torch
import torch.nn.functional as F
from dgl import BatchedDGLGraph
from dgl.nn.pytorch.conv import GraphConv, RelGraphConv
from torch import nn
from models.GNN.GNNModelBase import GNNModelBase
from models.utils import TypeConditionalLinear
class GCN(GNNModelBase):
"""
Graph Convolutional Network as... |
import numpy
def interpolate2d(x, y, Z, points, mode='linear', bounds_error=False):
"""2D interpolation routine: it outputs an array with same length
as points with interpolated values.
Parameters
----------
x : array
x-coordinates of the mesh on which to interpolate
y : array
... |
#!/usr/bin/env python3
#
# kevin@Dalek ~ $ pstree -s zmq
# -+= 00001 root /sbin/launchd
# \--- 17535 kevin /usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Ve
# kevin@Dalek ~ $ kill -9 17535
#
from __future__ import print_function
# fix path for now
import sys
sys.path.append("../")
from pygecko.transport... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from torchnet.meter import ConfusionMeter
import argparse
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from dat... |
from typing import Optional
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.config.config_methods import using_exchange
from hummingbot.core.event.events import OrderType, TradeType
from hummingbot.core.utils.tracking_nonce import get_tracking_nonce
CENTRALIZED = False
USE_ETHEREUM_... |
# bot.py
import aiocron
import csv
import datetime
import os
import re
import json
import yaml
import discord
from dotenv import load_dotenv
import sheetake
import logging
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# Logging configuration
logging.basicConfig(level=logging.INFO)
client = discord.Client()
adve... |
# Copyright 2020 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, ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import tensorflow as tf
import os
import pickle
import scipy
from .utils import get_image
import pandas as pd
LR_HR_RATIO = 4
IMSIZE = 256
LOAD_SIZE... |
#!/usr/bin/env python3
#
# Generate the files necessary to kickstart a host from PXE:
#
# PXEROOT/pxelinux.cfg/{hexaddr} - PXE file for stage 1 boot
# KSROOT/<hostname>-<distro><version>.ks - Kickstart file for stage 2
#
# USAGE: gen_pxe_config.py -t <template> [-c <config>]... [-d KEY=VALUE]...
#
# INPUTS
#
# distro
#... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, getdate, formatdate, cstr
from erpnext.accounts.report.financial_statements import filter_accou... |
import numpy as np
import pandas as pd
from chapter.four import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
def question_17():
""" Misclassification error rate of QDA and LDA.
Looks like they're both the same for the Height and Weight data: 11.9%.
Returns:
None.
"""
# Get ... |
import uuid
from collections import Counter
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Count
from django.utils.translation import ... |
from __future__ import annotations
from typing import Optional, Tuple
import pytest
import torch
from torch import Tensor, nn
from torch.autograd import grad
from nnrl.nn import FullyConnected, StateActionEncoder
@pytest.fixture(params=(1, 2, 4), ids=lambda x: f"InFeatures:{x}")
def in_features(request) -> int:
... |
import sys
sys.path.append('../')
import json
import bs4
import re
from WebCrawler import airav
from bs4 import BeautifulSoup
from lxml import html
from http.cookies import SimpleCookie
from ADC_function import get_javlib_cookie, get_html
def main(number: str):
raw_cookies, user_agent = get_javlib_cookie()
... |
import math
import numpy as np
from sherlockpipe.scoring.BasicSignalSelector import BasicSignalSelector
from sherlockpipe.scoring.SnrBorderCorrectedSignalSelector import CorrectedBorderSignalSelection
class QuorumSnrBorderCorrectedSignalSelector(BasicSignalSelector):
"""
Given the same correction applied in... |
import operator
from ..abc import SequenceExpression, Expression
from ..declerror import DeclarationError
from .value.valueexpr import VALUE
from .datastructs.itemexpr import ITEM, ITEM_optimized_EVENT_VALUE
from .value.eventexpr import EVENT
from .utility.context import CONTEXT
class ComparisonExpression(SequenceE... |
"""
VK.com OpenAPI, OAuth2 and Iframe application OAuth2 backends, docs at:
https://python-social-auth.readthedocs.io/en/latest/backends/vk.html
"""
import json
from hashlib import md5
from time import time
from ..exceptions import AuthException, AuthTokenRevoked
from ..utils import parse_qs
from .base import Base... |
# -*- coding: utf-8 -*-
from math import sin, cos, log
# used to compute rays and their bounding box (bb)
BB_PADDING = 0.2
BB_HALF_SIZE = 5.0
#~defines, for readability
X = 0
Y = 1
def _segment_length_squared(line1):
xdiff = line1[0][0] - line1[1][0]
ydiff = line1[0][1] - line1[1][1]
return xdiff**2+yd... |
#!/usr/bin/env python3
# coding: utf-8
import os
import sys
from libs.zpjUtils import ZpjUtils
import logging
import json
import argparse
import csv
import xml.etree.ElementTree as ET
import shutil
def step_git(git_url):
curPath = git_base_path
path = ""
path = git_url[git_url.find(":/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.