text stringlengths 3.07k 12.6k |
|---|
import os
import json
from typing import Dict
import lmdb
import cv2
import numpy as np
class Dataset:
def __init__(self, data_dir: str, jpg_quality: int = 100):
self.data_dir = data_dir
if not os.path.exists(data_dir):
os.makedirs(data_dir)
self.jpg_quality = jpg_quality
... |
# TODO reorganise and document
import pytest
import numpy as np
from StructuralCausalModels.dag import DirectedAcyclicGraph
_small_adj_matrix = np.asarray([
[0, 1, 1, 1],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 1, 1, 0]
])
_small_adj_matrix_causal_orders = [[0, 3, 1, 2]]
_large_adj_matrix = np.asarray([
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# **************************************************************************
# Copyright © 2016 jianglin
# File Name: serializer.py
# Author: jianglin
# Email: <EMAIL>
# Created: 2016-10-28 19:52:57 (CST)
# Last Update: Thursday 2018-10-25 13:34:30 (CST)
# By:
# De... |
import numpy as np
from scipy.spatial.distance import cdist
from pymoo.model.survival import Survival
from pymoo.rand import random
from pymoo.util.misc import normalize_by_asf_interceptions
from pymoo.util.non_dominated_rank import NonDominatedRank
class ReferenceLineSurvival(Survival):
def __init__(self, ref_p... |
#! /usr/bin/env python
#
# Support module generated by PAGE version 4.8.9
# In conjunction with Tcl version 8.6
# Apr 10, 2017 01:27:02 PM
# Apr 14, 2017 04:19:25 PM
import os
from tkinter import filedialog
from tkinter import messagebox
import logging
import glob
import support_functions
from WorkbookDocumentat... |
from re import search, findall, split, match
def valid(line):
if any(i in line for i in INVALID) or line == '':
return False
return True
def rathena_db_parse(table, schema, file, db):
# Parse any *db.txt from rAthena
# table - table's name
# schema - [('id', 'INTEGER PRI... |
import builtins
import math
import random
from time import sleep
import clismo.exceptions as excpt
from clismo.lang.type import Instance, Type
__BUILTINS = {}
cs_float = Type.get("float")
cs_int = Type.get("int")
cs_str = Type.get("str")
cs_bool = Type.get("bool")
cs_none = Type.get("none")
cs_list = Type.get("list"... |
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, FloatType, DoubleType
from pyspark.sql.functions import monotonically_increasing_id, row_number, lit
from pyspark.sql.window import Window
import pyspark.sql.functions ... |
# coding=utf-8
# Copyright 2022 The Uncertainty Baselines 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 ap... |
import numpy as np
import pickle
from project.utils import add_beat, padding
def generator(batch_size, subdivision, timesteps, step, dataset,
phase='train', percentage_train=0.8,
constraint=False
):
if("jazz" in dataset):
Y, X_metadatas = pickle.load(open(dataset... |
#!/usr/bin/env python
"""
Copyright 2010-2018 University Of Southern California
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 appli... |
__source__ = 'https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/k-th-smallest-in-lexicographical-order.py
# Time: O(logn)
# Space: O(logn)
#
# Description: 440. K-th Smallest in Lexicographical Order
#
# Given integers n and k, find the lex... |
import numpy as np
import neutrons
class TopologyError(Exception):
pass
class Uranium:
"""Generates Uranium Object, can be 1D or 3D based on 'cubey'.
arg: l: float: length of 1D strip, side lengths of U-235 object in 'm',
radius of sphere.
kwarg: shape="line": string: defined which of the ... |
# vim: set encoding=utf-8
#
# Copyright (c) 2015 Intel Corporation
#
# 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 requi... |
#-*- coding: utf-8 -*-
#
# LLLogWindowController.py
# LoginLog
#
# Created by Pelle on 2013-03-05.
# Copyright (c) 2013 Göteborgs universitet. All rights reserved.
#
from objc import YES, NO, IBAction, IBOutlet
from Foundation import *
from AppKit import *
class LLLogViewDataSource(NSObject):
"""Data so... |
import datetime
from unittest.mock import MagicMock
import pytest
from ts_sdk.task.__util_datalake import Datalake, InvalidPathException
from ts_sdk.task.__util_metadata import FIELDS
def test_datalake_update_metadata_tags():
d = Datalake('http://localhost:4569/')
d.s3.head_object = MagicMock(return_value={... |
import unittest
class Node:
""" A Node of an UnorderedList. Holds data provided by the user. """
def __init__(self,initdata):
self._data = initdata
self._next = None
def get_data(self):
return self._data
def get_next(self):
return self._next
def set_data(self... |
from digsandpaper.sandpaper_utils import load_json_file
import requests
from etk.extractors.glossary_extractor import GlossaryExtractor
from etk.crf_tokenizer import CrfTokenizer
import uuid
__name__ = "ConstraintReMapping"
name = __name__
class ConstraintReMapSimilarity(object):
name = "ConstraintReMapSimilarit... |
#!/usr/bin/env python3
from io import StringIO
import numpy as np
import rxcclib.file.Gaussian as rxfile
class DihdFunction(object):
def __init__(self, periodicity, phase, forceconst, npaths, dihd):
self.periodicity = periodicity
self.forceconst = forceconst
self.phase = phase
self... |
#!/usr/bin/env python
"""
A simple function to compute rot13 encoding
ROT13 encryption
Applying ROT13 to a piece of text merely requires examining its alphabetic
characters and replacing each one by the letter 13 places further along in
the alphabet, wrapping back to the beginning if necessary
"""
# note: the strin... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import re
import json
import datetime
from logging import getLogger
from restclients_core.exceptions import (
InvalidNetID, InvalidRegID, DataFailureException)
from uw_sws.models import Person
from uw_sws.enrollment import enrol... |
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
import scipy as sp
def normalize(X):
t = X.shape
Y = X
mean = np.mean(X,axis=0)
std = np.std(X,axis=0)
for i in range(t[0]):
for j in range(t[1]):
if std[j... |
import torch
import matplotlib.pyplot as plt
import torchvision.transforms as T
import torch.nn.functional as F
import numpy as np
import os
import json
import tqdm
import shutil
from PIL import Image, ImageFont, ImageDraw
from models.build_model import PrepareModel
from config import get_classify_config
############... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout, get_user_model
from chat.forms import LoginForm, RegisterForm, ComposeForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models i... |
# -*- coding: utf-8 -*-
import sys
import numpy as np
import os
from PIL import Image
import cv2
from matplotlib import pyplot as plt
def main():
#Gray image load
img = cv2.imread(sys.argv[1]) #circles.jpg #lim6.jpg
imgOriginal = img.copy()
# Check if image is loaded fine
if img is None:
... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# Rogue Access Point Detector
# version: 2.0
# author: anotherik (<NAME>)
##################################
# Scanners Module #
# Network monitor using scapy #
##################################
# Supress Scapy IPv6 warning
import logging
logging.getLogger... |
import numpy as np
import networkx as nx
from scipy.spatial.distance import cdist
from networkx.algorithms.dag import dag_longest_path
def compute_similarities(query_features, refer_features):
"""
用于计算两组特征(已经做过l2-norm)之间的相似度
Args:
query_features: shape: [N, D]
refer_features: shape: [M,... |
"""A high-level client that can open, close, and pay across many channels."""
import os.path
import collections
import logging
from . import walletwrapper
from . import database
from . import blockchain
from . import paymentchannel
from two1 import TWO1_CHANNELS_FEE
logger = logging.getLogger('channels')
PaymentCh... |
# -*- coding: utf-8 -*-
import re
from threading import Timer
import sublime
import sublime_plugin
from .console_logging import getLogger
from .daemon import ask_daemon
from .utils import get_settings, is_python_scope, is_repl
logger = getLogger(__name__)
FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}"... |
"""Functions for writing Jinja templates to string and thus to file"""
from jinja2 import Template
import re
import madflow.custom_op.constants as op_co
import madflow.custom_op.classes as op_cl
import madflow.custom_op.generation as op_gen
import madflow.custom_op.global_constants as op_gc
def template_with_string... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
xmind.core.comments implements encapsulation of the XMind comments.xml.
"""
import random
from .. import utils
from . import Document, const, Element
class CommentsBookDocument(Document):
""" `CommentsBookDocument` as central object correspond XMind comment file.... |
import data_generator as dg
from data_generator import DenoisingDataset
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import time, os
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
from torch.nn.modules.loss import _Loss
from torch.autograd ... |
from templates import *
template_list = [
("lexical_overlap", "ln_subject/object_swap", "non-entailment", lex_simple_templates),
("lexical_overlap", "ln_preposition", "non-entailment", lex_prep_templates),
("lexical_overlap", "ln_relative_clause", "non-entailment", lex_rc_templates),
... |
"""
Some test to make sure the GPU algorithms return the same answers
as the CPU algorithms
"""
import pycuda.autoinit
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.io as sio
import pkg_resources
import sys
from Alignment.Align... |
# This file is directly taken from code implementation by <NAME> al., authors of the paper https://arxiv.org/abs/2002.09564
# ----------------------------------------------------------
#This file was modified from implementation of [Auto-Augment](https://github.com/DeepVoltaire/AutoAugment/blob/master/autoaugment.p... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import pytest
import popart
import popart._internal.ir as _ir
def check_graph_inputs(graph, graph_inputs):
""" Helper function, graph inputs are what we expect. """
assert graph.getInputIds() == graph_inputs, \
f"Expected Graph {graph.getGraphS... |
import argparse
import json
import math
import os
import shutil
from pprint import pprint
from collections import namedtuple
import tensorflow as tf
from tqdm import tqdm
import numpy as np
import sys
from trainers.bidaf_trainer import BiDAFTrainer
from models.bidaf_model import BiDAFModel
from models.bidaf_model impor... |
from math import ceil, floor
import numpy as np
import math
import plotly.express as px
import plotly.graph_objects as go
from my_project.global_scheme import template, mapping_dictionary, month_lst
def custom_heatmap(df, global_local, var, time_filter_info, data_filter_info):
"""Return the customizable heatmap.... |
# Built-in
import os
import unittest
from unittest.mock import patch, MagicMock, Mock
# Package
from emqxlwm2m.cmd2loop import ispath
import emqxlwm2m.cmd2loop
import emqxlwm2m.__main__ as cli
EP = "urn:imei:123"
TIMEOUT = 60
class TestIsPath(unittest.TestCase):
def test_ispath(self):
self.assertTrue(is... |
import tempfile
from io import BytesIO
from os import path
from pathlib import Path
from unittest import mock
import apsw
import pytest
from common.tests import factories
from exporter.sqlite import plan
from exporter.sqlite import tasks
from exporter.sqlite.runner import Runner
from workbaskets.validators import Wor... |
import contextlib
import os
import pathlib
import platform
import shutil
import stat
import sys
import time
import typing
from os import PathLike
from pathlib import Path
from typing import IO, Iterator, Optional, Union
import appdirs
import click
import requests
is_windows = platform.system() == "Windows"
site_path ... |
'''
Hello, {{cookiecutter.Your_Name}}! Welcome to {{cookiecutter.Event}}.
Let's get started with your challenge.
IMPORTANT NOTE: When you run the script, it may take a while for
results to show depending on the network connection. Don't worry.
If the program fails on intial run, try again. Sometimes the remote
ope... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Test for smoothing with kernels """
import numpy as np
from numpy.random import random_integers as randint
from ... import load_image
from ..kernel_smooth import LinearFilter, sigma2fwhm, fwhm2sigma
fr... |
import os
import sys
import requests
import hashlib
import argparse
def check_hash(filename, checksum):
algorithm, value = checksum.split(':')
if not os.path.exists(filename):
return value, 'invalid'
h = hashlib.new(algorithm)
with open(filename, 'rb') as f:
while True:
dat... |
import argparse
import sqlite3
from flask import Flask, jsonify, send_from_directory
from flask_cors import CORS
# http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
from werkzeug.utils import redirect
app = Flask(__name__)
CORS(app)
def read_calling_points(all_points):
points = [... |
"""Tools to run device commands."""
import inspect
from types import MethodType
from .. import devices
from ..managers.scene_manager import async_trigger_scene_off, async_trigger_scene_on
from .tools_base import ToolsBase
def _convert_val(val):
if '"' not in val and "'" not in val:
try:
retu... |
# The MIT License (MIT)
#
# Copyright (c) 2017, <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi... |
from torch import Tensor
from typing import List, Optional, Tuple
from torch import Tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
class Boom(nn.Module):
def __init__(self, input_dim, hidden_dim=int(2048*2), dropout=0, shortcut=False):
... |
"""
Interfaces for everest.
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Oct 14, 2011.
"""
from zope.interface import Attribute # pylint: disable=E0611,F0401
from zope.interface import Interface # pylint: disable=E0611,F0401
from zop... |
import argparse
import logging
import torchvision.utils
from tqdm import tqdm
from typing import Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from utils.eval import AverageMeterSet
from utils.train import get_random_block_mask, get_random... |
# Copyright 2019 Graphcore Ltd.
# coding=utf-8
from io import BytesIO
import numpy as np
from PIL import Image
import tensorflow as tf
_BINARISED_MNIST_TR = 'http://www.cs.toronto.edu/~larocheh/public/datasets/binarized_mnist/binarized_mnist_train.amat'
_BINARISED_MNIST_TEST = 'http://www.cs.toronto.edu/~larocheh/publ... |
"""helper functions for the dash app
"""
import sfm
import base64
import numpy as np
def pdf_plot(model, reference_frame, vox_ecc, vox_angle):
"""Create plotly plot showing response of a single voxel
Parameters
----------
model : sfm.model.LogGaussianDonut
single instance of the spatial frequ... |
import numpy as np
import time
import json
import os
import torch
import slowfast.utils.checkpoint as cu
import slowfast.utils.logging as logging
import slowfast.datasets.utils as utils
from slowfast.models.build import MODEL_REGISTRY
from slowfast.datasets.extractor import Extractor
from torch import multiprocessing... |
#!/usr/bin/env python3
#Author: <NAME> (<EMAIL>)
import sys
import subprocess
import os
from commonStuff import *
import parseObjdump as pars
import traceback
import aapg
import time
seedFile=open('randomSeed.txt','r')
seeds=seedFile.readlines()
count=1
try:
makeType=sys.argv[1]
testname=sys.argv[2]
except:
ma... |
import io
import os
import platform
from unittest import mock
import pytest
from bplustree.node import LeafNode, FreelistNode
from bplustree.memory import (
FileMemory, open_file_in_dir, WAL, ReachedEndOfFile, write_to_file
)
from bplustree.const import TreeConf
from .conftest import filename
from bplustree.seria... |
import math
from bisect import bisect, insort
from cocos.batch import BatchNode
from cocos.euclid import Vector2, Matrix3
class Picker(object):
""" A picker to find your children quickly """
def __init__(self):
self.xChildren = {}
self.yChildren = {}
self.xs = []
self.ys = []
... |
#!/usr/bin/env python
# coding=utf-8
import logging
from handlers.base import BaseHandler
from handlers.kbeServer.Editor.Interface import interface_sms
from methods.DBManager import DBManager
import json
import uuid
class SmsPayRequest(BaseHandler):
def get(self):
pdata = self.get_argument("str")
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 15:13:34 2020
@Author: <NAME>, <NAME>
@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China
@Homepage: http://www.scbdd.com
@Mail: <EMAIL>; <EMAIL>
@Blog: https://blog.iamkotori.com
♥I love Princess Zelda forever♥
"""
from rdkit import Chem
... |
import pandas as pd
import requests
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from requests.adapters import HTTPAdapter
from urllib3 import Retry
import json
"""
Read google sheet as dataframe
If you read with API, you need to use spreadsheet... |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""End-to-end speech recognition model decoding script."""
import configargparse
import logging
import os
import random
import sys
import numpy as np
from espnet.u... |
"""
codes for MMD-GAN
based on "MMD-GAN: Towards Deeper Understanding of Moment Matching Network"
based on: https://github.com/OctoberChang/MMD-GAN
"""
import torch
import torch.nn as nn
###########################################################################
# base_module
####################################... |
# -*- coding: utf-8 -*-
import math
import os
import torch
import random
import wandb
import pandas as pd
import numpy as np
from timeit import default_timer as timer
from sklearn.utils import shuffle
def build_nfs_scenarios(n_s: int, x: np.array, y_scaler, flow, conditioner_args, max:int=1, gpu:bool=True, tag:str... |
from django.db import models
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User, Group, Permission
from django.forms import ModelForm, TextInput
from django.http import HttpRespons... |
from flask import Flask, request
from structs import Player, PlayerInfo, Tile, TileContent, Point
import json
from Queue import Queue
# from search import Search
# import numpy as np
import networkx as nx
app = Flask(__name__)
def print_map(m):
# for i in range(len(m)):
# print([(tile.x, tile.y) for tile... |
import imp, numpy, glob, shutil
imp.load_source('common_functions','common_functions.py')
import common_functions as cf
def noise_est(config,logger):
"""
Makes an estimate of the theortically expected noise level for each science target.
Input:
config = The parameters read from the configuration ... |
# This module is adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py
import init_paths
import argparse
import os
import time
import sys
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import torchvision.transforms as transforms
import torchvision.data... |
#!/usr/bin/python
from bs4 import BeautifulSoup
import os
import sys
import string
import re
BASE_JAVADOC_URL = "https://docs.oracle.com/javase/8/docs/api/index.html?"
BASE_LOCAL_JAVADOC_DIR = "./docs/api/"
def collectDocFilesFrom(dir):
docFiles = []
for (path, dirs, files) in os.walk(dir):
if 'class-use' not... |
#coding=utf-8
#author@alingse
#2016.08.19
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Activation
from keras.optimizers import SGD, Adadelta, Adagrad,RMSprop
from keras.utils import np_utils, generic_utils
from utils import activations
... |
# Copyright 2019-2020 The Kale 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 i... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
from .. import db
from datetime import datetime
post_tag = db.Table('post_tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
db.Column('post_id', db.Integer, db.ForeignKey('posts.id'))
)
post_file = db.Table('post_files',
... |
#!/usr/bin/env python
# coding: utf-8
import sys
from time import time
from time import sleep
import xarray as xr
import boto3
import os
import rioxarray
import rasterio
import argparse
def _split_full_path(bucket_full_path):
if 's3://' in bucket_full_path:
bucket_full_path=bucket_full_path.replace('s3:/... |
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Types which provide many builds and composite them into a single binary."""
import logging
import pathlib
import subprocess
import zmake.build_config a... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from imdb import IMDb
from cinemanio.core.models import Movie, Person, Genre, Language, Country
from cinemanio.sites.exceptions import PossibleDuplicate, NothingFound, WrongValue
from cinemanio.sites.models import SitesBaseModel
cla... |
# -*- coding: utf-8 -*-
# Version 0.1a11
import re
from collections import Counter
import dash
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
import iso3166
import pandas as pd
import plotly.graph_objs as go
from sklearn import preprocessing
df = pd.read_pickle('brand24... |
from flask import jsonify, request, current_app, send_file, abort
from polzybackend.antrag import bp
from polzybackend.utils.import_utils import antrag_products, antrag_factory
from polzybackend import auth
from polzybackend.models import AntragActivityRecords
from polzybackend.utils.import_utils import import_class
im... |
import numpy as np
import tensorflow as tf
import keras.backend as K
def calculateIdx1D(vol_length, cube_length, stride):
one_dim_pos = np.arange(0, vol_length-cube_length+1, stride)
if (vol_length - cube_length) % stride != 0:
one_dim_pos = np.concatenate([one_dim_pos, [vol_length-cube_length]])
r... |
import torch
from torch.nn.utils.clip_grad import clip_grad_norm_, clip_grad_value_
from maml.utils import accuracy
def get_grad_norm(parameters, norm_type=2):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p.grad is not None, parameters))
no... |
#!/usr/bin/env python2.7
"""opencachelib.py: Core OpenCache functionality shared between controller and node."""
import httplib
import json
import os
import shutil
import urllib2
import logging
import logging.handlers
TAG = "lib"
def setup_logger(log_path, name, verbosity):
"""Setup logging functionality ... |
from PIL import Image, ImageFilter;
import matplotlib.pyplot as plt;
import AppleOrBackgroundCategorizer;
import glob;
import os;
import errno;
def FindBlobs(image, activePixelClassifier):
discoveredBlobs = [];
# First, I'll create a giant list of all pixels that are
# considered "active" by the categorizer. In ot... |
import gym
import numpy as np
import sys
import os
import time
import pandas
import random
import pickle
import itertools
from collections import defaultdict
import matplotlib.pyplot as plt
from sklearn.model_selection import ParameterGrid
#from utils import plotting
# Deterministic environment FrozenLake-v0
def prin... |
# Copyright 2019 DeepMind Technologies Ltd. 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 appl... |
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from parse_config import ConfigParser
class dilated_conv(nn.Module):
""" same as original conv if dilation equals to 1 """
def __init__(self, in_channel, out_channel, kernel_size=3, dropout_rate=0.0, a... |
#!/usr/bin/env python
'''
build co-expression network
method: WGCNA
'''
import logging
import os
import sys
from copy import deepcopy
import networkx as nx
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
os.environ["OMP_NUM_THREADS"] = "1" # export OMP_NUM_THREADS=1
os.envi... |
"""
TWEET ANALYZER 1.0
Author: <NAME>
See README.txt for more inforation about the usage of this script. Export all
the environment variables before running the script.
"""
import os
import sys
import geocoder
import tweepy
import json
import csv
import re
from matplotlib import pylab as plt
import numpy
import math
f... |
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# Revised BSD License, included in this distribution as LICENSE
"""
Functions for converting Jupyter notebooks
"""
import nbformat
from metapack import MetapackDoc
from metapack.cli.core import prt, err
from metapack_jupyter.core import... |
"""Test the functions provided by mirage.psf.deployments
Authors
-------
- <NAME>
Use
---
>>> pytest test_deployments.py
"""
import glob
import os
import shutil
import numpy as np
import pytest
import webbpsf
from .utils import parametrized_data
from mirage.psf.deployments import generate_random_ote_deploym... |
"""Clean Wikipedia dumps for use as a training corpus."""
import re
import argparse
import html
import bz2
import logging
from .utensils import log_timer
from multiprocessing import cpu_count
logging.basicConfig(format='[{levelname}] {message}', style='{', level=logging.INFO)
cores = int(cpu_count() / 2)
@log_timer
d... |
import speech_recognition as sr
import re
import philips_hue as ph
import soundclassify as sc
import pyaudio
import wave
from jesica4 import create_dashboard
from jesica4 import command_light
from jesica4 import command_SoundSystem
from jesica4 import command_Door
from jesica4 import command_detectsound
command_light... |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
from wiremock._compat import add_metaclass
from wiremock.base import BaseEntity, JsonProperty, BaseAbstractEntity, BaseEntityMetaType
class HttpMethods(object):
ANY = "ANY"
GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
DELETE = "DELETE"
OPTIONS = "OPTIONS"
HEAD = "HEAD"
class... |
# plotComparison.py
import numpy as np
import matplotlib.pyplot as plt
import tools
def plotData(input_file, output_file, plot_dir, title, column_indices, xlim, ylim, drawMean):
verbose = False
tools.makeDir(plot_dir)
data = tools.getData(input_file)
output_png = "{0}/{1}.png".format(plot_dir, output_... |
import itertools
from random import Random
import sys
import time
import yaml
import gym
import numpy as np
from argparse import Namespace
from RandomSampling import RandSampling
from pyglet.gl import GL_POINTS, GL_LINES, GL_LINE_STRIP
class PurePursuitPlanner:
"""
Example Planner
"""
def __init__(sel... |
"""
Copyright (c) 2017-2018 Starwolf Ltd and <NAME>. 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.
A copy of the License is located at http://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying... |
import tensorflow as tf
import scipy.io as scio
import pylab
import numpy as np
import os
import time
import utils.preprocess as preproc
import modules.base_modules as basic_blocks
from utils.model_utils import l1_loss
from utils.feat_utils import shuffle_feats_label
def classifier_model(input_mfc, reuse=False, sco... |
#!/usr/bin/env python2.7
import sys
from collections import defaultdict
def surface_check_var(s):
if s[0] < 'a' or s[0] >'z':
return False
if len(s) == 1:
return True
for i in xrange(1, len(s)):
if s[i] < '0' or s[i] > '9':
return False
return True
def from_AMR_line(... |
from re import compile, escape
FILL_NONE_VALUES = '[параметр]'
DEFAULT_ERROR_GENERATION_PREFIX = 'Произошла ошибка,' \
' возможно вы имели ввиду: '
class RegularExpression:
def __init__(self, expr, match_type="match",
flags=0):
self.regex = compile(expr... |
"""
Further work:
1. This homography calculation will fail for matrix with large condition number
Rectify this
2. Implement algorithm to find the convex hull. Currently using matplotlib
3. Implement the SVD solver - currently using at the one from numpy for homograhy
"""
"""
Caveats:
Python I... |
# encoding: utf-8
# author: BrikerMan
# contact: <EMAIL>
# blog: https://eliyar.biz
# file: test_processor.py
# time: 2019-05-23 17:02
import os
import time
import logging
import tempfile
import unittest
import numpy as np
import random
from kashgari import utils
from kashgari.processors import ClassificationProcesso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.