text stringlengths 3.07k 12.6k |
|---|
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
from matplotlib.ticker import StrMethodFormatter, ScalarFormatter
from read_file import select_original_breakpoints
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcPar... |
''''
This file contains all the crud methods of the blog app like creating blog posts, blog posts categoty and the comments.
'''
from django.shortcuts import render
# Create your views here.
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
f... |
#!/usr/bin/python
# vim:fileencoding=utf-8:noet
# (C) 2017 <NAME> <<EMAIL>>
# Released under the terms of the 2-clause BSD license.
import codecs
import locale
import os
import os.path
import sys
from portage import create_trees
from portage.dbapi.dep_expand import dep_expand
from portage.dep import Atom
from portage... |
"""Tasks for managing virtualenv environments."""
from paver.easy import task, options, dry, debug, BuildFailure
from paver.release import setup_meta
VIRTUALENV_MISSING_ERROR = "`virtualenv` is needed to use paver's virtualenv tasks, please install the package."
try:
import virtualenv as venv
except ImportError:
... |
from __future__ import print_function
import numpy as np
from itertools import izip
from matplotlib import pyplot as plt
"""
Provides a number of useful evaluation metrics
And helper-routines to compute the metrics
"""
__version__ = '0.2'
#---------------------------------------------------------------------------... |
import json
import requests
import os
import time
import sys
## Pair: BTCUSD, USDBTC, DASHUSD, etc
class PriceRetriever:
def __init__(self):
self.localbitcoins = None
self.gemini = None
self.bitinka = None
self.ripio = None
self.cexio = None
self.coinbase = None
def ask(self):
# print(... |
# -*- coding: utf-8 -*-
import pathlib
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Configure directories
BASE_DIR = pathlib.Path(__file__).resolve().parent # Base project folder
IMGS_DIR = BASE_DIR.joinpath('imgs') # Image resources subfolder (../imgs)
RESULTS_DIR = BASE_DIR.joinpath(... |
# Copyright (c) 2015 Mirantis, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
"""
This script connects to https://empleos.gob.mx and checks each state in Mexico for new listings.
The job listings are downloaded into their respective state folder.
"""
import os
import time
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
STATES_URLS = [
"1-busqueda-de-... |
import logging
import onnx
import onnx.numpy_helper
from onnx.numpy_helper import to_array
import torch
import glob
import os
modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [
os.path.basename(f)[:-3]
for f in modules
if os.path.isfile(f) and not f.endswith('__init__.py')
]... |
from menu import screen, full_quit, Button, inf_font
from constants import *
import level_editor
class Level:
empty_text = inf_font.render("Empty", 0, BLACK)
def __init__(self, image, x, y, number):
self.image = image
self.x = x
self.y = y
self.number = number
... |
# from itertools import izip
import traceback
from heapq import heappush, heappop
import numpy as np
import networkx as nx
# import matplotlib.pyplot as plt
# from networkx.drawing.nx_pydot import write_dot
def follow_path(start, stop, graph, width, virtuals):
weight = 0
destination = start
if graph.get... |
import glob
import os
import shutil
import rasterio as rio
from PIL import Image
import numpy as np
import pandas as pd
import geopandas as gpd
import json
from ipyleaflet import Marker, GeoJSON
import math
from pathlib import Path
def get_path_rename_gsv(folder_dwl_name):
"""
Args:
... |
#!/usr/bin/env python3
import tables as h5
import numpy as np
import gvar as gv
import sys
'''
This file reads the data from an hdf5 file and prepares it into a correlated
gvar data set.
It also handles reading/writing yaml files containing prior width studies
'''
def sort_ens(ensembles):
# sort ensembles in a ... |
def doCalendar(calendarFrame):
from Tkinter import *
# Clear and replace calendarFrame
for widget in calendarFrame.winfo_children():
widget.destroy()
label_8 = Label(calendarFrame, text = " 8:00 AM")
label_9 = Label(calendarFrame, text=" 9:00 AM")
label_10 = Label(calendarFrame, text="10:00 AM")
label_11... |
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
from core.modules.ker2mat import Kernel2MatrixConvertor
class ADMMSolverBlock(nn.Module):
def __init__(self,shape,mask,rho,lamb,eta,T=1):
super(ADMMSolverBlock, self).__init__()
self.T = T
self.... |
import torch
from pytorch_metric_learning import losses
from .loss import JsdCrossEntropy, EntropyLoss
from typing import Dict, List
from overrides import overrides
from transformers import get_linear_schedule_with_warmup
from allennlp.nn.util import get_text_field_mask
class SentimentModel(torch.nn.Module):
def... |
import numpy as np
import tensorflow.compat.v1 as tf
import random
from functools import reduce
def max_pool_2x2(x, kernel_shape, name):
ksize = [1, *kernel_shape, 1]
strides = [1, *kernel_shape, 1]
return tf.nn.max_pool(x, ksize, strides, padding='SAME', name=name)
def conv2d(x, output_dim, kernel_shap... |
import torch
from torch.nn import functional as F
from collections import OrderedDict
from ..utils import ConvNdTorch, PoolingNdTorch, NormNdTorch
from ..basic_networks import BaseClassificationTorchNetwork
class _DenseLayerTorch(torch.nn.Sequential):
def __init__(self, num_input_features, growth_rate, bn_size, d... |
#python 2/3 compatibility
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import super
import json
from wtforms.fields import (Field, TextAreaField, StringField, HiddenField,
SelectField)
from wtforms.compat import ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2019 <NAME> National Tsing Hua University
# Distributed under terms of the MIT license.
import numpy as np
import unicodedata
import os
import tensorflow as tf
class OneHot(object):
def __init__(self, be, nclasses):
self.be = be
... |
#! /usr/bin/env python
"""
Model based control with shooting method example in turtlebot crib environment
Navigate towards preset goal
Author: LinZHanK (<EMAIL>)
Inspired by: https://bair.berkeley.edu/blog/2017/11/30/model-based-rl/
"""
from __future__ import absolute_import, division, print_function
import numpy... |
# -*- coding: utf-8 -*-
"""Generalized algorithm for plotting contour and/or scatter plots.
Adapted from open source method: scatter_contour.py
https://github.com/astroML/astroML/blob/master/astroML/plotting/scatter_contour.py
Parameters
----------
plot_flag : style of plot (scatter, contour, line, etc.)
plot_type : ... |
import numpy as np
import unittest as ut
import itertools as it
import cell
from cell import R, G, B, rot, dot, cell_to_rgb, rgb_to_cell, iterate_cell
import bbworld
from bbworld import board_from_pic, pic_from_board, _get_neighbours, iterate_board, save_pic, load_pic
from PIL import Image
class CellsTest(ut.TestCase)... |
from scale_lidar_io_debug import LidarScene, Transform
import os
import json
import yaml
import numpy as np
from glob import glob
"""
Documentation for this file is in :
https://fieldengineering.gitbook.io/lidar-conversion/load-raw-lidar-data/intro
"""
###############
## CHANGE ME ##
###############
LOCAL_INPUT_PATH ... |
from copy import deepcopy
from typing import Dict, NamedTuple, Optional
import bmds
from bmds.bmds3.constants import DistType
from bmds.bmds3.sessions import BmdsSession
from .transforms import (
PriorEnum,
build_dataset,
build_model_settings,
remap_bayesian_exponential,
remap_exponential,
)
# ex... |
import atexit
import json
import logging
import re
import shlex
from os import path
from subprocess import Popen
from threading import Timer
logger = logging.getLogger(__name__)
from .common_executors import BaseExecutor
from .rpc import ExecutionTargetRPCClient
from .._compat import with_metaclass, raise_from
from .... |
# -*- coding: utf-8 -*-
"""This module defines functions for fetching and parsing files in the PDB
for the Biologically Interesting Molecule Reference Dictionary (BIRD_).
.. _BIRD: https://www.wwpdb.org/data/bird
The chemical information is stored in Peptide Reference Dictionary (PRD) files,
whereas the biologica... |
""" I/O operations to save and load embeddings. """
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
import json
import csv
from typing import List, Tuple, Dict
import numpy as np
INVALID_FILENAME_CHARACTERS = [',']
def _is_valid_filename(filename: str) -> bool:
"""Returns False if t... |
from abc import ABC, abstractmethod
import numpy as np
from parcels.interaction.neighborsearch.distanceutils import spherical_distance
class BaseNeighborSearch(ABC):
"""Base class for searching particles in the neighborhood.
The data structure of the class (and subclasses) only contain spatial
informati... |
"""
Content Provider: PhyloPic
ETL Process: Use the API to identify all CC licensed images.
Output: TSV file containing the image, their respective meta-data.
Notes: http://phylopic.org/api/
No rate limit specified.
"""
from modules.etlMods i... |
#!/usr/bin/env python3
'''
booksdatasource.py
<NAME>, <NAME>, <NAME> 21 September 2021
For use in the "books" assignment at the beginning of Carleton's
CS 257 Software Design class, Fall 2021.
'''
import csv
class Author:
def __init__(self, surname='', given_name='', birth_year=None, death_year=N... |
from mws import mws
from mws.utils import next_token_action
from .utils import enumerate_dict, enumerate_list
class InboundShipments(mws.MWS):
URI = "/FulfillmentInboundShipment/2010-10-01"
VERSION = '2010-10-01'
NAMESPACE = '{http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/}'
NEXT_TOK... |
#!/usr/bin/python
# Copyright 2020 Hewlett Packard Enterprise Development LP
#
# 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 ... |
import numpy as np
import cv2
from tqdm import tqdm
from ..datasets import get_dataset
from ..datasets.utils.homographies import warp_points
from ..utils.geometry_utils import get_lisrd_desc_dist_numpy
def run_descriptor_evaluation(config):
models_name = config['models_name']
H_estimation = {m: [] for m in m... |
# import sys
# Color lib for pretty output
class bcolors:
GREEN = '\033[92m'
PINK = '\033[95m'
PURPLE = '\033[94m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def red(string):
return bcolors.RED + string + bcolors.ENDC
def green(strin... |
# Creation of a Sentinel-2 Canadian Dataset
"""
# Note: before running this code, create a new conda env named : gee
# conda install -c anaconda pandas
# conda install -c conda-forge pysimplegui
# conda install openpyxl
# conda install -c conda-forge earthengine-api
# Then, authenticate yourself to Google ... |
###########################
# 6.00.2x Problem Set 1: Space Cows
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file conte... |
#nmigen: UnusedElaboratable=no
import unittest
from nmigen import *
from nmigen.utils import log2_int
from nmigen.back.pysim import *
from nmigen_soc.wishbone import CycleType, BurstTypeExt
from ._wishbone import *
from ..periph.sram import SRAMPeripheral
def simulation_test(dut, process):
with Simulator(dut,... |
"""
Calling preprocessing.start_schedule() will scrape all videos from svtplay and begin the preprocessing process inbetween the allocated time window defined in constants.
"""
import logging
import multiprocessing
import os
import time
from datetime import date, datetime
import db.video_repo as video_repo
impor... |
import argparse
import logging
import os
import sys
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from data_processing import datasets
from pointnet import attacks
from pointnet.model import PointNet
from util import rotati... |
# -*- coding: utf8 -*-
# license: WTFPL version 2, or whatever is closest to "no license" and "public domain" (like Unlicense or CC0)
from __builtin__ import AssertionError
from __builtin__ import exit
from __builtin__ import int
from __builtin__ import ord
from __builtin__ import range
from __builtin__ impo... |
import math
from math import sin, cos, sqrt, atan2, radians
from datetime import datetime, timedelta
import pytest
from sklearn.cluster import KMeans
from sklearn import metrics
import numpy as np
from numpy.core.umath import deg2rad
from sqlalchemy import create_engine
from flask import Flask, render_template, request... |
from __future__ import unicode_literals, print_function
from ansible.module_utils.basic import AnsibleModule, return_values
napalm_found = False
try:
from napalm import get_network_driver
from napalm.base import ModuleImportError
napalm_found = True
except ImportError:
pass
# Legacy for pre-reunificat... |
##################################################
# MIT License
#
# Copyright (c) 2019 Learning Equality
#
# 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 with... |
# Copyright 2014 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.
"""This module uprevs Mojo for cbuildbot.
If a new version of Mojo is found, a stable ebuild for the new version
is created and older stable ebuilds will... |
puzzle = [[0, 0, 0, 2, 6, 0, 7, 0, 1],
[6, 8, 0, 0, 7, 0, 0, 9, 0],
[1, 9, 0, 0, 0, 4, 5, 0, 0],
[8, 2, 0, 1, 0, 0, 0, 4, 0],
[0, 0, 4, 6, 0, 2, 9, 0, 0],
[0, 5, 0, 0, 0, 3, 0, 2, 8],
[0, 0, 9, 3, 0, 0, 0, 7, 4],
[0, 4, 0, 0, 5, 0, 0, 3, 6],
... |
#create folder list to feed emby
import os, re
import sys
from os.path import exists
import re
from shutil import copyfile
import xml.etree.ElementTree as ET
from functions_scan import list_creation
def List_filter(folderlist, patternName):
if folderlist is None:
return None
else:
newlist=[]
... |
"""
An IPython extension for generating and displaying asymptote figures within
an IPython notebook. Refer to examples directory for usage examples.
"""
import os
import shutil
import subprocess
import tempfile
from IPython.core.magic import (
magics_class, line_magic, line_cell_magic, Magics)
from IPython.core.ma... |
#!/usr/bin/env python3
import csv
import logging
import os
import subprocess
import sys
from pathlib import Path
import click
import coverage
from flask import current_app
from flask.cli import FlaskGroup
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from project.server.app import creat... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ###... |
__all__ = [
'UNSET',
'Diff',
'Slotinit',
'get_closest_parent',
'get_document_type',
'document_type_to_class_name',
'get_index_name',
'normalize_index_fields_spec'
]
import inspect
from typing import Type, Iterable, Optional, NamedTuple, Any, Union, Iterator, Tuple, Dict
from mongoengin... |
#!/usr/bin/python
#
# Copyright 2018 Red Hat, Inc.
#
# This file is part of ansible-nmstate.
#
# ansible-nmstate is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your o... |
from __future__ import with_statement
import unittest
from datetime import datetime
import flask
from flaskext import sqlalchemy
def make_todo_model(db):
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column('todo_id', db.Integer, primary_key=True)
title = db.Column(db.String(60))
... |
#
#
# 0=================================0
# | Project Name |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Implements: Support Vector Machine
#
# --------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Pysilhouette.
#
# Copyright (c) 2009 HDE, Inc.
#
# 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, in... |
import datetime
class Status:
OPEN_FOR_DELETE = "OPEN_FOR_DELETE"
NEED_SYNC = "NEED_SYNC"
DEPOT_ONLY = "DEPOT_ONLY"
OPEN_FOR_ADD = "OPEN_FOR_ADD"
OPEN_FOR_EDIT = "OPEN_FOR_EDIT"
UNTRACKED = "UNTRACKED"
MOVED = "MOVED"
UP_TO_DATE = "UP_TO_DATE"
UNKNOWN = "UNKNOWN"
class P4File(obj... |
from matplotlib import pyplot as plt
import numpy as np
import librosa
from librosa import display
import os
from utils import load_spectrograms
from hyperparams import Hyperparams as hp
# import the necessary packages
from skimage.measure import compare_ssim as ssim
from sklearn.metrics import r2_score
import num... |
# Lint as: python2, python3
# 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 l... |
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
def find_element_centroid_pacman(img, colour, coord):
y,x = np.where(np.all(img == colour, axis=2))
pairs = []
for i in range(len(x)):
pairs.append([x[i],y[i]])
if(len(x) != 0 and len(y) != 0):
# calculate cent... |
import json, re
from .util import id_len
max_name_len = 42
team = {
"_type": dict,
"name": {
"_type": str,
"_re": r"^.+$",
"_maxLen": max_name_len,
},
"isisName": {
"_optional": True,
"_type": str,
"_re": r"^.*$",
"_maxLen": max_name_len,
},
"type": {
"_type": str,
"_re": r"^(jumpSturdy|racin... |
import numpy as np
import argparse
import pickle
import gzip
import sys
def str2bool(v):
if isinstance(v, bool): return v
if v.lower() in ['yes', 'true', 't', 'y', '1']: return True
elif v.lower() in ['no', 'false', 'f', 'n', '0']: return False
else: raise argparse.ArgumentTypeError('Boolean value expected.')
#
... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from tqdm import trange
from time import sleep
import numpy as np
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
class Net(nn.Module):
"""
Image2... |
# Copyright (c) 2018 <NAME>. MIT license, see LICENSE file.
import sys
from .keys import *
from .printer import flush
class _ConsoleUnix:
_unixkeycodes = {
"\x1BOP": F1,
"\x1BOQ": F2,
"\x1BOR": F3,
"\x1BOS": F4,
"\x1B[15~": F5,
"\x1B[17~": F6,
"\x1B[18~": F7... |
import copy
import pytest
import numpy as np
from cotk.dataloader import LanguageGeneration, MSCOCO
from cotk.metric import MetricBase
from cotk.wordvector import WordVector, Glove
import logging
def setup_module():
import random
random.seed(0)
import numpy as np
np.random.seed(0)
class TestWordVector():
def ba... |
from tornado.httpclient import HTTPRequest, HTTPError
import abc
import socket
import hashlib
import ujson
from urllib import parse
from .. import admin as a
from .. social import APIError
from . steam import SteamAPI, SteamPrivateKey
class MailRuAPI(SteamAPI, metaclass=abc.ABCMeta):
"""
MailRu API pretty ... |
"""Methods for normalizing dpayd post metadata."""
#pylint: disable=line-too-long
import math
import ujson as json
from funcy.seqs import first
from hive.utils.normalize import bbd_amount, rep_log10, safe_img_url, parse_time, utc_timestamp
def post_basic(post):
"""Basic post normalization: json-md, tags, and fl... |
import base64
import glob
import itertools
import logging
import os
import re
from hashlib import sha256
import yaml
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from jinja2.exceptions import TemplateNotFound, TemplateSyntaxError, UndefinedError
from k8s_handle import settings
from k8s_handle.exc... |
#!/usr/bin/env python
#
# <NAME> 2020
# Portions Copyright 2007 <NAME>
# Portions Copyright 2007 Google 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/lic... |
import torch
from torch import nn
import torch.nn.functional as F
from .bt_backbone import BasicBlock, Bottleneck
class Upsample_layer(nn.Module):
def __init__(self, in_ch, out_ch, size):
super(Upsample_layer, self).__init__()
self.deconv = nn.ConvTranspose2d(in_ch, out_ch, size, stride=size, bias=... |
# Copyright 2019 by Raytheon BBN Technologies Corp.
# All Rights Reserved.
import os, sys, logging
logger = logging.getLogger(__name__)
import argparse
import json, codecs
import os
import sys
import random
import pickle
from collections import Counter
def load_map(relation_pattern_map_file, final_map, unique_ids):
... |
#!/usr/bin/env python
r"""Test runner for typeshed.
Depends on pytype being installed.
If pytype is installed:
1. For every pyi, do nothing if it is in pytype_blacklist.txt.
2. Otherwise, call 'pytype.io.parse_pyi'.
Option two will load the file and all the builtins, typeshed dependencies. This
will also disc... |
import openvino_args
import datetime
import logging
import os
from os import path
import subprocess
import shutil
import shlex
import tempfile
import time
import cv2
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)
def get_parser():
parser = openvino_args.parser('Test movidius')
pa... |
import sys
import os
import traceback
import time
import zuds
zuds.init_db()
#db.DBSession().autoflush = False
#db.DBSession().get_bind().echo = True
__author__ = '<NAME> <<EMAIL>>'
__whatami__ = 'Make the subtractions for ZUDS.'
MAX_DETS = 50
class TooManyDetectionsError(Exception):
pass
class PredecessorErr... |
import numpy as np
import scipy as sp
import scipy.interpolate as spi
import gym
import gym.wrappers
import random
import time
import keras
class QfnNN(object):
def __init__(self, state_dim, action_dim, learning_rate, optimism, optimism_decay):
self.state_dim = state_dim
self.action_dim = action_di... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (C) 2013-2015 <NAME>
#
# This file is part of 'open-tamil' package tests
#
# setup the paths
import codecs
import re
from opentamiltests import *
from tamil.regexp import make_pattern, match
from tamil.utils.santhirules import joinWords
class SantheeRules(unittest.T... |
import os
import sys
from utils.util import get_timestamp
# print to file and std_out simultaneously
class PrintLogger(object):
def __init__(self, log_path):
self.terminal = sys.stdout
self.log = open(os.path.join(log_path, 'print_log.txt'), 'a')
def write(self, message):
self.termina... |
import os
import sys
import cv2
import imagesize
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from yolo_tf2.utils.common import LOGGER, get_abs_path
if sys.platform == 'darwin':
plt.switch_backend('Qt5Agg')
def save_fig(title, save_figures=True):
"""
Save ... |
# -*- coding: utf-8 -*-
# @Author: UnsignedByte
# @Date: 18:37:12, 28-Jan-2020
# @Last Modified by: UnsignedByte
# @Last Modified time: 2021-07-18 22:54:34
import csv
import json
import base64
import os.path
import traceback
import re
import markdown2
import shutil
# Colored terminal text for python
class bcolors... |
import threading
import time
class ThreadGateException(Exception):
pass
class ThreadGate(object):
""" A class which works as a FIFO 'gate' for threads. By
default the gate is open and any thread calling on the
'enter' method returns immediately.
A thread can 'close' the gate by calling the method... |
"""A unit convertor"""
import sys
from pathlib import Path
from typing import Any, Dict, List
from networkx.algorithms.shortest_paths.generic import shortest_path
from varname import argname
from qiyas.graph import UnitGraph, load_unit_graph
from qiyas.generator import get_unit_types, read_unit_table
# ===============... |
#!/usr/bin/env python
# coding=utf-8
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, login_required, logout_user, current_user
from app.email import send_email
from . import auth
from .forms import LoginForm, RegistrationForm, ChangePasswordForm, PasswordRe... |
from colorama import init
from colorama import Style
from colorama import Fore
import os
import datetime
import pip
import platform
from subprocess import Popen
from subprocess import PIPE
from subprocess import STDOUT
from collections import defaultdict
from itertools import chain
import glob
import functools
init()... |
""" Database functionality through SQLAlchemy """
import re
import shutil
import tempfile
import sqlalchemy as sa
import psycopg2
import pandas as pd
from . import local
__all__ = ["open_db_metadata", "create_db_tables",
"execute_db_statement", "execute_db_statements",
"read_dframe", "write_df... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Distributed under the terms of the MIT License.
"""
Module for plotting functions.
Author: <NAME>
Date Created: 15 Sep 2018
"""
import matplotlib.pyplot as plt
import matplotlib.colors as colors
def EC_descriptions():
"""
Dictionary of EC descriptions + co... |
from skbio.diversity._util import _vectorize_counts_and_tree
from skbio.diversity.beta._unifrac import _setup_multiple_unweighted_unifrac, \
_setup_multiple_weighted_unifrac, \
_get_tip_indices
import biom
import numpy as np
import skbio
from time import time
import tempfile
def _map_observations(table: biom.... |
#!/usr/bin/python3
"""
Offers support for WS2812 LED LEDs via the hardware SPI MOSI
Uses py-spidev:
```
git clone https://github.com/doceme/py-spidev.git
cd py-spidev
make
make install
```
"""
import time
import datetime
import socket
import math
import re
import random
from izaber import initialize, config
from... |
from typing import TYPE_CHECKING
from pyramid.httpexceptions import HTTPError, HTTPInternalServerError, HTTPUnprocessableEntity
from cowbird.api import exception as ax
from cowbird.api import schemas as s
from cowbird.utils import CONTENT_TYPE_JSON, get_logger
if TYPE_CHECKING:
# pylint: disable=W0611,unused-imp... |
import logging
import socket
import time
import types
import typing
from threading import Thread, Lock
from .ctrl_enum import EnumDevice
from .dao import Room, AirCon, AirConStatus, get_device_by_aircon
from .decoder import decoder, BaseResult
from .display import display
from .param import Param, HandShakeParam, Hear... |
import common
SUDOKU_WIDTH = 9
SUDOKU_HEIGHT = 9
AVAILABLE_CELL = 0
class variables:
"""Class for counter"""
counter = 0
def sudoku_backtracking(sudoku):
""" Main forward checking function
"""
# Initialize counter
variables.counter = 0
recursive_backtracking(variables... |
# -*- coding: utf-8 -*-
'''cmd line argument and ENV parser'''
import logging
import os
from argparse import ArgumentParser, ArgumentTypeError
from nibe_modbus_mqtt.version import __version__, app_name, get_runtime_info
LOG_LEVEL_STRINGS = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']
LOG_LEVEL_DEFAULT = 'INFO'
L... |
# coding: utf-8
#用於獲取該目錄下得所有txt檔案,忽略掉資料夾及裡面的
import glob
#主要是一些路徑的操作
import os
#對句子進行分詞或關鍵詞提取
from jieba import analyse
import jieba
jieba.set_dictionary('/home/test/linebot_project/linebot_project/dict.txt.big')
# 獲取當前pyhtho檔案所在的目錄:當前是:C:\gongoubo\python-work\direc\files
dir_path = os.path.dirname(os.path.abspath(__f... |
# Copyright 2021 Adap GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# from __future__ import absolute_import
import threading
from time import sleep
import os
import sys
# import signal
from daemonize import Daemonize
import ipdb
from alpha_tech_tracker.alpaca_engine import DataAggregator
from alpha_tech_tracker.strategy import SimpleStrategy
from alpha_tech_tracker.nvda_strategy ... |
# -*- coding: utf-8 -*-
#
# 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
#... |
from hematite.serdes import (
content_range_spec_from_bytes,
content_range_spec_to_bytes,
content_header_from_bytes,
accept_header_from_bytes,
items_header_from_bytes,
list_header_from_bytes,
retry_after_from_bytes,
retry_after_to_bytes,
range_spec_from_bytes,
range_spec_to_bytes... |
import yaml
import os
import sys
import httplib2
import socket
#import string
#import random
from docassemble.base.generate_key import random_string
dbtableprefix = None
daconfig = dict()
s3_config = dict()
S3_ENABLED = False
gc_config = dict()
GC_ENABLED = False
hostname = None
loaded = False
in_celery = False
def l... |
# todo: comment
import math
from scripts import (physics,
door)
def segment(start, end, y, h, r):
dx = end[0] - start[0]
dy = end[1] - start[1]
length = (dx ** 2 + dy ** 2) ** .5
nx = (dx * r) / length
ny = (dy * r) / length
vertices = [start[0] + nx, start[1] + ny,
... |
import ast
import dataclasses
from typing import (
Any, Dict, Generic, Protocol, Set, Tuple, TypeVar, List, Optional
)
from typing_extensions import TypeAlias
import textwrap
T = TypeVar("T")
class ReadOnlyEnv(Generic[T], Protocol):
def __call__(key: str, dependency: str) -> T:
...
class EnvTabl... |
import numpy as np
from dcll.npamlib import spiketrains
input_shape = [28,28,1]
import numpy as np
from torchvision import datasets, models, transforms, utils
import torch
from torch.utils.data.dataloader import _DataLoaderIter, DataLoader
import tqdm
def to_one_hot(t, width):
t_onehot = torch.zeros(*t.shape+(w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.