text stringlengths 3.07k 12.6k |
|---|
import time
import math
from dronekit import connect, VehicleMode, LocationGlobal, Command
from pymavlink import mavutil
from dronekit.test import with_sitl
from nose.tools import assert_not_equals, assert_equals
@with_sitl
def test_empty_clear(connpath):
vehicle = connect(connpath)
# Calling clear() on an e... |
# Copyright 2018 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, s... |
"""Datamatrix renderer"""
__revision__ = "$Rev$"
from io import BytesIO
from PIL import Image
def repr_matrix(matrix):
return "\n".join(repr(x) for x in matrix)
class DataMatrixRenderer:
"""Rendering class - given a pre-populated datamatrix.
it will add edge handles and render to either to an image
... |
"""Contains all players spreadsheet settings commands related to Tosurnament."""
from discord.ext import commands
from bot.modules.tosurnament import module as tosurnament
from common.databases.tosurnament.spreadsheets.players_spreadsheet import PlayersSpreadsheet
from common.api import spreadsheet as spreadsheet... |
import logging
import warnings
import pandas as pd
import xarray as xr
from .metrics import Metric
from .options import OPTIONS
from .utils import convert_cftime_to_datetime_coords, convert_time_index
def _mean_bias_removal_quick(hind, bias, dim):
"""Quick removal of mean bias over all initializations.
Arg... |
# 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... |
from mcpi.minecraft import Minecraft, Vec3
from minecraftstuff import MinecraftDrawing
from vecIterator import vecItereator
from random import randint, choice
from splitIntoHouses import splitIntoHouses
rpiIp = "192.168.1.182"
mc = Minecraft.create(address=rpiIp)
mcdraw = MinecraftDrawing(mc)
def makeRoad(posA: Vec... |
import scrapy
import os.path
from NBA_Scrapy.items import NBANewsItem
from scrapy.loader import ItemLoader
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
team_urls = [
'https://www.nba.com/hawks/news',
'https://www.nba.com/celtics/news',
'https://www.nba.c... |
import os
#os.environ['KERAS_BACKEND']='plaidml.keras.backend'
import time
import numpy as np
import sys
import json
import argparse
if 'KERAS_BACKEND' in os.environ:
import keras as kr
from keras.models import Sequential
import keras.layers as layers
from keras.utils import to_categorical
from ke... |
from wtforms import (
StringField,
FloatField,
HiddenField,
SelectField
)
from wtforms.validators import (
InputRequired,
Optional,
Regexp
)
from wtforms.widgets import TextArea
from webapp.home.custom_validators import (
valid_min_length, valid_latitude, valid_longitude
)
from webap... |
import pickle
from datetime import datetime
from bs4 import BeautifulSoup
from .crawler import AbstractCrawler
from . import models
def parse_paid(value):
"""
Parses a specific portuguese word "Sim"(=Yes) to a bool.
"""
if value == 'Sim':
return True
else:
return False
def pars... |
def calc(expression):
result = 0
op = '+'
current = 0
for c in expression+'\uffff':
if c >= '0' and c <= '9':
# accumulate current number
current = current * 10 + int(c)
elif c == '+' or c == '-' or c == '\uffff':
# start next operator, calculate curre... |
import argparse
import json
import os
import warnings
import zipfile
from collections import OrderedDict
from importlib import import_module
from parser import get_args
import numpy as np
import torch
import torch.cuda.amp as amp
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn... |
#!/usr/bin/python
'''
Author: <NAME> <<EMAIL>>
Purpose: Convert Splunk Security Content detections to CAR analytics
'''
import argparse
import yaml
from datetime import datetime
from pyattck import Attck
from jinja2 import Environment, FileSystemLoader
import re
from os import path
def generate_car_object(detection... |
#!/usr/bin/env python3
from __future__ import annotations
from typing import (
Type as _Type,
)
from collections.abc import (
Generator as _Generator,
Iterable as _Iterable,
Iterator as _Iterator,
)
from zlib import (
compress as _compress,
decompress as _decompress,
)
from ..utils import f... |
import numpy as np
from sklearn.preprocessing import StandardScaler
import pandas as pd
from sklearn.model_selection import train_test_split, KFold
from sklearn.metrics import accuracy_score
def get_data(column_names):
data_frame = pd.read_csv('./data/spambase.txt', header=None, sep=',', dtype=np.float)
data_... |
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (c) 2016, <NAME> <<EMAIL>>
# All rights reserved.
# See LICENSE.txt
# Copyright (c) 2004 <NAME> (http://www.owlfish.com/)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are pe... |
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.db.models import F
from .models import Product, Post, Point, Order, Category, Cart
from django.core.paginator import Paginator, EmptyP... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Convenience functions for photometric data."""
from __future__ import division
import math
import numpy as np
from astropy.utils import OrderedDict as odict
from astropy.table import Table
from .spectral import get_magsystem, get_bandpass
_photdata_al... |
import os
import sys
from core import *
from torch_backend import *
batch_norm = partial(BatchNorm, weight_init=None, bias_init=None)
def res_block(c_in, c_out, stride, **kw):
block = {
'bn1': batch_norm(c_in, **kw),
'relu1': nn.ReLU(True),
'branch': {
'conv1': nn.Conv2d(c_in,... |
#!/usr/bin/env python3
"""Recursively generate an HTML index page for each directory."""
from __future__ import print_function
import os
from os.path import join as pjoin
import stat
import json
import argparse
from base64 import b64encode
IGNORES = set("""
.git
.gitignore
__pycache__
index.html
Thumbs.db
Desktop.i... |
from generic_operations import get_frequent_ngrams
import pandas as pd
from nltk.util import ngrams
from generic_operations import print_to_file
import math
import global_parameters as p
import global_variables as v
# save file of frequency n-grams
def ngram_detection(text_list):
ngrams = get_frequent_ngrams(text_... |
import argparse
import torch
import cv2
import numpy as np
from PIL import Image
from tqdm import tqdm
from tracking import load_feature_extractor
from tracking.sort.tracker import DeepSORTTracker
from tracking.utils import *
import sys
sys.path.insert(0, 'yolov5')
from yolov5.models.experimental import attempt_load
... |
import os
from arg_extractor import get_shared_arguments
from util import get_processing_device
import numpy as np
from torchvision import transforms
from PIL import Image
import torch
from DenseNetParameters import DenseNetParameters
from AutoEncoder import Autoencoder
from ExperimentBuilderAE import ExperimentBuil... |
# $Filename$$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... |
"""
maketopo:
make some 'artificial' topo surrounding the flume area.
make an initialization file of the water elevation in the flume hopper
"""
import numpy as np
from pyclaw.geotools import topotools as gt
import pylab
import os
def maketopo():
"""
output topography for entire domain
"""
#pad
... |
from dataclasses import dataclass
from functools import total_ordering
from random import Random
from typing import Union, Tuple, List, Iterable, Sequence
from tsppso.datatypes import FloatMatrix, Position
from tsppso.utilities import distances_matrix, lshift, neighborhood_inversion
class Problem(object):
def __... |
import operator
from typing import List
from pypika import Query, Table, JoinType, Order
from pypika import functions as fn
from pypika.queries import QueryBuilder
from watchmen.common.parameter import Parameter
from watchmen.common.utils.data_utils import build_collection_name
from watchmen.pipeline.single.stage.uni... |
#!/usr/bin/env python3
""" Parse command line arguments, configure root loggers and initialise the note conversion process """
import argparse
import logging
import logging.handlers as handlers
from pathlib import Path
import sys
import config
from config_data import ConfigData
from helper_functions import find_worki... |
import os
import pickle
import numpy as np
import pytest
import elfi
from elfi.store import ArrayPool, ArrayStore, NpyArray, NpyStore, OutputPool
def test_npy_array():
filename = 'test.npy'
original = np.random.rand(3, 2)
append = np.random.rand(10, 2)
ones = np.ones((10, 2))
append2 = np.rando... |
"""
Based loosely on admin filterspecs, these are more focused on delivering controls appropriate per field type
Different filter controls can be registered per field type. When assembling a set of filter controls, these field
types will generate the appropriate set of fields. These controls will be based upon what is... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# earliest possible start and end dates in both datasets: "2017-07-01 11:00:00", "2018-03-12 19:00:00"
def pct_change(df, start, end, hours_offset):
px_change_li = []
t = 0
for px_at_t in df.loc[start:end].iloc[:, 0]:
if t < ho... |
"""
Date: 05/05/2020
Author: <NAME>
"""
__all__ = ['Uniform', 'VectorLangevin', 'map_vL', 'MatrixLangevin']
import numpy as np
import scipy.stats as st
import scipy.special as sp
class Uniform(object):
_dim = None
_frame = None
"""docstring for Uniform"""
def __init__(self, frame, dim):
assert isinstanc... |
"""Simple text log pattern using local sub-directory.
"""
import logging
import os
import sys
import fileinput
import re
from time import strptime
import datetime
import ast
import queue_app.utils
import json
import socket
from logging.handlers import SysLogHandler
def initialize_logger(output_dir='logs',
... |
#
# Original work Copyright (c) 2014 <NAME>
# Modified work Copyright (c) 2017 <NAME>, <NAME>
#
# Licensed under the MIT license. See the LICENSE file for details.
#
import re
from serial.tools.list_ports import comports
import struct
import binascii
import threading
import serial
BLE_RESPONSE_PKT = 0x00
BLE_EVENT_PK... |
from torchtools import *
from collections import OrderedDict
import math
#import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from torch.nn.parameter import Parameter
class GraphConvolution(nn.Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __in... |
import numpy as np
from fractions import Fraction
import pick_midi
import preprocess
import postprocess
import deep_piano_model
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.layers as tfl
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensor... |
# Copyright 2012 Nebula, Inc.
#
# 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 agree... |
# Copyright 2018-2019 <NAME>
#
# This file is part of WarpX.
#
# License: BSD-3-Clause-LBNL
'''
This script loops over 3D plotfiles plt*****, generates a 3D rendering
of the data with fields and particles, and saves one image per plotfile to
img_*****.png. It was written for a beam-driven wakefield acceleration
simula... |
import os
import tables
from extremefill2D.dicttable import DictTable
import pylab
import numpy as np
from sumatra.projects import load_project
class BaseViewer(object):
def __init__(self, basedatafile=None, datafiles=None, labels=None, times=None, colors=None):
self.times = times
self.data = []... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Financial functions used to calculate net present value and internal rates of
return.
"""
import datetime as dt
from functools import partial
from scipy.optimize import root
import pandas as pd
import plotly.graph_objects as go
def calc_npv(df_in, discount):
"""On inpu... |
# Copyright (c) 2013, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, erpnext
from frappe import _
from frappe.utils import flt
from frappe.model.meta import get_field_precision
from frappe.utils.xlsxutils import handle_html
from erpnext.... |
import os
import random
import shutil
import string
from PIL import Image
from sqlalchemy.event import listen
# Extensions that will be converted
CONVERT_EXTENSIONS = [('jpeg', 'jpg')]
# Extensions that are allowed
ALLOWED_EXTENSIONS = ['jpg', 'png', 'gif']
# Actual file types that are allowed, should correspond to... |
import re
import discord
import asqlite
import time
from dataclasses import dataclass
from discord.ext import commands, menus
__all__ = ['embed_create', 'CustomBot', 'TimeConverter', 'MentionedTextChannel', 'CustomMenu', 'seconds_to_str']
def embed_create(user, **kwargs):
color = kwargs.get('color',... |
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
from robobo.base import Robobo
import os
import time
import rospy
import cv2
import numpy as np
from std_msgs.msg import String, Int8, Int16, Int32
from robobo_msgs.srv import MoveWheels, MovePanTilt, SetEmoti... |
import random
from random import uniform
from collections import deque
from openpyxl import Workbook
class Vertice:
def __init__(self, IDpessoa):
self.id = IDpessoa
self.vizinhos = list()
def acrescentar_Vizinho(self, v):
if v not in self.vizinhos:
self.vizinhos.append(v)
... |
# The read and write methods for SpectralCube, StokesSpectralCube, and
# LowerDimensionalObject are defined in this file and then added to the classes
# using UnifiedReadWriteMethod. This makes it possible to dynamically add the
# available formats to the read/write docstrings. For more information about
# the unified ... |
#!/usr/bin/env python3
"""make meta dir from meta file"""
import argparse
import itertools
import os
import re
import shutil
import pandas as pd
import scipy.spatial.distance
from geopy.distance import vincenty
# --------------------------------------------------
def get_args():
"""argparser"""
parser = argp... |
"""
BSD 2-Clause License
Copyright (c) 2020, justchenhao
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 condit... |
import numpy as np
import h5py
from sparta import sparta
from scipy.interpolate import interp1d
from scipy.integrate import quad, cumtrapz
from numba import njit
import matplotlib.pyplot as plt
from sys import argv
def profile(r,mass,bins=None):
# radial bins
if bins is None:
rmin = np.sort(r)[100]/10
rm... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2021 Pincer
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 20:20:15 2020
@author: david
Bishop Chapter 8
Image de-noising using
iterated conditional models (ICM)
"""
import imageio
import matplotlib.pyplot as plt
import numpy as np
def get_energy(img_noisy, img_den,
h, beta, eta,
... |
import re
class Entity:
def __init__(self, start, end, entity_id=None, quote_id=None, quote_eid=None, proper=None, ner_cat=None, in_quote=None, text=None):
# print("creating")
self.start=start
self.end=end
self.entity_id=entity_id
self.quote_id=quote_id
self.proper=proper
self.ner_cat=ner_cat
self.in_... |
"""Implementation of the Orientated Bins filter.
Used to compute the strength and orientation of linear features in an image.
Reference: <NAME>, <NAME>, and <NAME>.
"Finding Orientated Line Patterns in Digital Mammographic Images." BMVC. 1996.
"""
import itertools
import math
import numpy as np
from scipy.ndimage i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 10:35:20 2020
@author: p20coupe
"""
import argparse
import sys
import joblib
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import os
import math
import statistics
import torch
from torch import nn... |
import base64
import requests
DEFAULT_REGISTRY = 'registry-1.docker.io'
DEFAULT_TAG = 'latest'
def image_str_to_dict(image_s):
image_dict = {}
parts = image_s.split('/', 1)
if len(parts) > 1:
if '.' in parts[0] or ':' in parts[0]:
# highly likely this is a DNS name in the form examp... |
from scapy.all import *
import signal
import time
from scipy import stats
import http.client as httpc
import modules.sdnpwn_common as sdnpwn
def signal_handler(signal, frame):
#Handle Ctrl+C here
print("")
sdnpwn.message("Stopping...", sdnpwn.NORMAL)
exit(0)
def info():
return "Attempts to fingerprint the ... |
import sys
import logging
import itertools
import operator
import gc
import math
from sys import getsizeof, stderr
import random
from difflib import SequenceMatcher
from operator import itemgetter
from collections import defaultdict
from itertools import chain, groupby
import statistics
def map_index_to_pop(popfile):... |
#!/usr/bin/python3
from __future__ import print_function, absolute_import
import argparse
import os
import logging
from woldrnaseq.common import (
add_default_path_arguments,
add_debug_arguments,
add_version_argument,
configure_logging,
get_seperator,
validate_library_file_existance,
)
from wol... |
from __future__ import division
import logging
import glob
import os
from PIL import Image, ImageFont, ImageDraw
from watermark.logutils import log_start
from watermark.validator import FontValidator
from watermark.color import Color
from watermark.constants import (
Size, Position,
IMAGE_FORMATS, MASK_AVAILA... |
import aiohttp
from aenum import IntEnum, Enum
from discord import Embed, User, Color, Member
import discord
from http import HTTPStatus
from typing import Optional, Union
from copy import deepcopy
import datetime
import os
import time
from config import log_channel, main, staff, testing, manager_key, site_url, ag_role... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Speciallan
import logging
import torch.nn as nn
from mmdet.models.utils import build_conv_layer, build_norm_layer
from mmcv.cnn import constant_init, kaiming_init, normal_init, xavier_init
from mmcv.runner import load_checkpoint
from ..registry import BACKBONES
de... |
#
# Copyright 2016 The BigDL 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 or agreed to in ... |
import json
from fractions import Fraction
from datetime import timedelta
from psycopg2 import sql
from bs4 import BeautifulSoup
from jinja2 import Markup
from pint import UnitRegistry
from simple_recipes.db import get_connection, get_cursor
from simple_recipes.db.recipes.extra import get_measurements
from simple_rec... |
import base64
import hashlib
import hmac
import http.client
import os
import random
import re
import secrets
import time
import urllib.request
from urllib.parse import quote
from html.parser import HTMLParser
class InfoMoneyHTMLParser(HTMLParser):
def __init__(self):
self.daily_change = None
self... |
import numpy as np
import torch as th
from rlkit.torch.core import PyTorchModule
import rlkit.torch.pytorch_util as ptu
from rlkit.torch.distributions import (
Delta
)
from rlkit.torch.networks.stochastic.distribution_generator import DistributionGenerator
import random
from sklearn.svm import LinearSVR
class Enc... |
from typing import List, Dict
from enum import Enum
from collections import OrderedDict
import re
class SymbolTabEntry:
def __init__(self, name, is_live=False, next_use=None):
self.name = name
self.is_live = is_live
self.next_use = next_use
class SymbolTable:
def __init__(self, entries... |
"""
Defines functions used to construct basis vectors, convert between coordinate systems, build meshes, etc.
"""
import miepy
import numpy as np
def sph_to_cart(r, theta, phi, origin=None):
"""convert spherical coordinates (r, theta, phi) centered at origin to cartesian coordinates (x, y, z)"""
if origin is ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" iam-switchrole-org-policies """
import re
from os import environ
import logging
import json
import boto3
from troposphere import (
Template,
)
from troposphere.iam import (
ManagedPolicy
)
from ozone.handlers.template_manage import create_template_in_s3
from... |
# -*- coding: utf-8 -*-
"""
<NAME>
October 28, 2019
CodingBat Solutions (Python)
This is a python file containing my own solutions to the
different Python Logic-1 exercises on codingbat.com
"""
"""
Logic-1 > cigar_party:
When squirrels get together for a party, they like to have cigars.
A squirrel part... |
import logging
import sys
import uuid
from copy import deepcopy
from joblib import hash as hashy
import graphviz
import ipywidgets as ipy
import networkx as nx
import pandas as pd
from IPython.display import display
from pipy.interactive import InteractiveDict
from pipy.parameters import Iterable, PandasParam
logge... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from typing import Iterable, List
class InvalidPathError(Exception):
pass
class NotARelativePathError(InvalidPathError):
pass
class NotAnAbsolutePathError(InvalidPathError):
pass
_valid_path_chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_.'
def _validate_and_shorten(is_absolute: bool, elements: It... |
# Import pygame module
import pygame
# Setting up the display for the game
# Screen title
screen_title = 'Obstacle Game'
# Screen size
screen_width = 800
screen_height = 800
# Screen color in RGB
white_color = (255, 255, 255)
black_color = (0, 0, 0)
# Initialize all imported pygame modules
pygame.init()
#... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# DESCRIPTION
"""
FLASK APPLICATION: SHOCKWAVE (SHK)
Cryptocurrency in python.
app.py is main program.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Shockwave"
__credits__ = ["<NAME>"]
__developers__ = ["willassad"]
__license__ = "GPL"
__version__ = "1.0.1"
__mai... |
import pytest
from pathlib import Path
import numpy as np
import h5py
import time
import yaml
from shepherd.shepherd_io import DataBuffer, VirtualSourceData
from shepherd import ShepherdDebug
from shepherd import LogWriter
from shepherd import LogReader
from shepherd import Emulator
from shepherd import emulate
from ... |
import os, sys
from typing import Type
sys.path.insert(0, os.path.abspath(".."))
import pandas as pd
import pytest
import pycaret.regression
import pycaret.datasets
from mlflow.tracking.client import MlflowClient
import uuid
@pytest.fixture(scope="module")
def boston_dataframe():
return pycaret.datasets.get_dat... |
import asyncio
import getopt
import logging
import os
import signal
from enum import Enum
from sys import argv
import yaml
from voluptuous import Required, Schema, MultipleInvalid, All, Any, Optional, Coerce
from wb_hass_gw.homeassistant import HomeAssistantConnector
from wb_hass_gw.wirenboard import WirenConnector
... |
from contextlib import contextmanager
from datetime import datetime
import json
import os
from pathlib import Path
from shutil import copy
import signal
from subprocess import check_output, check_call, Popen, PIPE
import time
from typing import NamedTuple, ContextManager, Optional
import pytz
from integration_test im... |
from models import (db, Dealer, LocalDealer, Company, Org, Records, VehicleReferencePrice,
FairEstimatedValue, SomeRecord, Vehicle, AdsData, NewsData, PredictedResidual,
FairEstimatedValueB, VehicleReferencePriceSource, BMWVehicles)
class TestBaseInitializer:
def test_poly... |
'''
File name: x509Storage.py
Author: ZeroPass - <NAME>
License: MIT lincense
Python Version: 3.6
'''
from database.storage.storageManager import Connection
from pymrtd.pki.x509 import CscaCertificate, DocumentSignerCertificate
import logging
logger = logging.getLogger(__name__)
class CSCAStorageError... |
import numpy as np
import os
from PIL import Image
from joblib import Parallel, delayed
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils import data
import torch.nn.functional as F
from torchvision import transforms, utils
from PIL import Image, ImageFilter, ImageDraw, ImageChops
from model ... |
'''
@author: Team12
Declaration: This classifier is an improved version based on the following sources
http://www.360doc.com/content/16/0725/19/15165994_578332920.shtml
https://github.com/abromberg/sentiment_analysis_python/blob/master/sentiment_analysis.py
http://streamhacker.com/2010/06/16/text-classification-senti... |
try:
from tensorflow_estimator import estimator
except ImportError:
from tensorflow import estimator
import tensorflow.compat.v1 as tf
from tensorflow.python.framework import ops
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import basic_session_run_hooks
from ten... |
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import FormView, RedirectView, TemplateView
from users.permissions import APIPermissionMixin
from utils.api.client import MarketAccessAPIClient
from utils.exceptions import APIHttpException
from utils.metadata import... |
import os
import psutil
import time
import pickle
import random
import base64
import unittest
from tokentree import TokenTree
def merge_fn1(seq, i, ht, key, count):
"""Merges new extra data to existing extra data in a node."""
if ht is None:
return {key: count}
if key in ht:
ht[key] += co... |
"""
Sequencer wrapper for QWERTY keyboard input.
We allow the synth to be played via string information,
with sources being live keyboard input, text files, and more!
We utilise the current default control scheme:
q,a,w,s,e,d,r,f,t,g,y,h,u,j,i,k,o,l,p - All play musical notes, q being the lowest and p being the high... |
from statsmodels.tools.eval_measures import rmse
from copy import deepcopy
import numpy as np
import shlex
import os
from config import SPEC_DIR
import respy
def get_est_log_info():
""" Get the choice probabilities.
"""
with open('est.respy.info') as in_file:
for line in in_file.readlines():
... |
import hashlib
import random
import time
import urllib
import logging
from typing import List, Dict
from math import pi, sqrt, sin, cos, atan2
#from const import routeData
import requests
import utils
host = 'http://api.map.baidu.com'
my_ak = '<KEY>'
my_sk = '9gbIMAXlvUYuSOZdY2qsxiLlyOmtu9Ry'
def get_sn(url: str):
... |
## Name: Sonify N-gram Drawing 2
## Description: Uses learned n-grams from all of the sketches
## in the sketchy dataset to make an n-gram image
## this first makes a portion of the image as a
## vector until it can start making a 2D ngram
## where the probabili... |
# -*- coding: utf-8 -*-
import glob
import os
import logging
import string
try:
import builtins
except ImportError:
import future_builtins as builtins
from .parser import parse
from .ast import Extends, Priority, Global, Snippet
_ALL = 'all'
# Global snips cache.
# ft -> SnipInfo
cache = {}
ident_chars = ... |
import os
import json
from squid_py.ddo.authentication import Authentication
from squid_py.ddo.public_key_hex import PublicKeyHex, PUBLIC_KEY_TYPE_HEX, AUTHENTICATION_TYPE_HEX
from squid_py.keeper.utils import (
get_fingerprint_by_name,
get_contract_abi_and_address,
hexstr_to_bytes,
get_network_name)
f... |
#%tensorflow_version 1.x
import tensorflow as tf
#tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
# Log name of device used for execution
#tf.debugging.set_log_device_placement(True)
import argparse
from tensorflow.python.client import device_lib
from enum import Enum
import timeit
import run... |
from flask import (Flask, render_template, redirect, url_for, g, flash, abort)
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import (LoginManager, current_user, login_user,
logout_user, login_required)
import forms
import models
DEBUG = True
PORT = 8000
HOST = '0... |
#!/usr/bin/env python
###########################################################################
#
# Copyright 2021 Samsung Electronics 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 ... |
from itertools import product
from typing import Dict, Iterable, List, Optional, Set, Tuple
from aoc import AOC, manhattan, flatten
from dataclasses import dataclass
aoc = AOC(year=2021, day=19)
data = aoc.load()
@dataclass
class ScannerPosition:
absolute_offset: Tuple[int, int, int]
offset: Tuple[int, int, ... |
from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import time
import io
import os
import sys
import struct
class ITMDWTPacket():
pass
class SynchroPacket(ITMDWTPacket):
def __repr__(self):
return "SynchroPacket"
class OverflowPacket(ITMDWTPacket):
def __repr__(self):
... |
import cvxpy as cp
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils import check_X_y
from sklearn.metrics.pairwise import euclidean_distances
from wdwd.utils import pm1
from wdwd.linear_model import LinearClassifierMixin
class WDWD(BaseEstimator, LinearClassifierMixin):
def __init__... |
import torch
import torchvision
import numpy as np
import torch.utils.data as data
import torchvision.transforms as transforms
import pandas as pd
import h5py
import os
# Pytorch custom dataset for JMA Radar data
# The class assumes the data to be in h5 format
class JMARadarDataset(data.Dataset):
def __init__(s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.