text stringlengths 3.07k 22.1k |
|---|
# test_auth.py
# tests authentication and authorization functions, including decorators.
# uses the error messages from api.controllers.errors to validate that the correct error messages
# are being thrown.
import unittest
import pytest
import os
import jwt
import pandas as pd
from datetime import datetime, timedelta
f... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import pickle
import pandas as pd
from flask import Flask, jsonify, request
from flask_cors import CORS
from schema import Schema, And, Or, SchemaError
app = Flask(__name__)
CORS(app)
model = pickle.load(open('model.pkl', 'rb'))
PREDICT_SCHEMA = Schema({
'CHARGE_COUNT... |
from datetime import datetime
from datetime import timedelta
import requests
from time import sleep
from oauth2client.service_account import ServiceAccountCredentials
import gspread
import re
import Main
# pass our gspread credentials as global variables
credentials, header, SPREADSHEET, SHEET_NAME, SHOP_URL = Main.G... |
import os
import numpy as np
from dm_control.suite import common
from dm_control.utils import io as resources
import xmltodict
_SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
_FILENAMES = [
"./common/materials.xml",
"./common/skybox.xml",
"./common/visual.xml",
]
def scale_recursive(obj, field, scale):
i... |
from matrix import *
import random
def draw_matrix(m):
array = m.get_array()
for y in range(m.get_dy()):
for x in range(m.get_dx()):
if array[y][x] == 0:
print("□", end='')
elif array[y][x] == 1:
print("■", end='')
else:
... |
"""Unit tests for compaction."""
from io import StringIO
import numpy as np # type: ignore
import pandas # type: ignore
from pytest import approx, mark, raises # type: ignore
from compaction import compact
from compaction.cli import load_config, run_compaction
def test_to_analytical() -> None:
c = 3.68e-8
... |
# Copyright © 2015-2022 <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, modify, merge, publish,... |
import re
from tqdm import tqdm
from IPython.core.debugger import set_trace
import copy
from transformers import BertTokenizerFast
import torch
class WordTokenizer:
def __init__(self, word2idx = None):
self.word2idx = word2idx
def tokenize(self, text):
return text.split(" ")
d... |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import sys
import os.path as osp
import OpenGL
import torch
from torchvision.transforms import Normalize
import numpy as np
import cv2
import argparse
import json
import pickle
from datetime import datetime
from demo.demo_options import DemoOptions
from bod... |
import argparse
import csv
import json
import os.path
import sys
# --Description-- #
# Prisma Cloud General Helper library. Used to contain the general useful shared functions.
# --End Description-- #
# --Configuration-- #
# Settings file name
DEFAULT_SETTINGS_FILE_NAME = "pc-settings.conf"
DEFAULT_SETTINGS_FILE_V... |
import datetime
# import io
import json
import logging
import os
import random
from itertools import cycle
import discord
from discord.ext import commands, tasks
# from dotenv import load_dotenv
from quart import Quart
original_dir = os.getcwd()
jsons = ['applications.json', 'counts.json', 'economy.json', 'guilds_dat... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import textwrap
from sklearn.metrics import (
auc,
precision_score,
recall_score,
f1_scor... |
#!/usr/bin/env python
############################# HOW TO RUN IN TERMINAL
# python download_from_NOAOarchive.py 2>&1 | tee download_from_NOAOarchive.out
#############################
# Clear after use
usrname = 'XXX'
pw = 'XXX'
#############################
save_dir = '/fred/oz100/NOAO_archive/KNTraP_Project... |
# A small manager program for QEMU. Tested on Windows
# https://github.com/yeppiidev/qemu-manager
import os
import tkinter as tk
import atexit
from subprocess import PIPE
from subprocess import Popen, CalledProcessError
from tkinter.messagebox import showinfo as alert
from tkinter.messagebox import askyes... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
import os
import secrets
from io import StringIO
from typing import Tuple
import datetime
import json
import github
import requests
import jinja2
import pytz
import common
from researchseminarsdotorg import publish_to_researchseminars
from host_key_rotation import host_key
EMAIL_TEMPLATE = jinja2.Template(
"""Dear {... |
#-*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import datetime as dt
import os
from Modules import Read
from Modules import Graphs
from Modules.Utils import Listador, FindOutlier, Cycles
from Modules.ENSO import SOIdata, MEIdata, ONIdata, SSTregions
# Est_path = os.path.abspath(os.path.join(os.path.... |
import logging
import os
import numpy as np
import torch
import random
import datetime
import subprocess
import csv
from mmcv.runner import get_dist_info
import torch.nn as nn
np.seterr(divide='ignore', invalid='ignore')
import torch.distributed as dist
import torch.multiprocessing as mp
from mmcv.runner... |
from neuronmi.mesh.shapes.utils import circle_points, unit_vector, link_surfaces
from neuronmi.mesh.shapes.baseshape import BaseShape
from math import sqrt
import numpy as np
class Box(BaseShape):
'''Box is specified by min X, Y, Z coordinates and extents'''
def __init__(self, minlim, maxlim):
super(... |
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import cnn_setting
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.view_size = int(math.pow(((cnn_setting.image_size - 4) / 2 - 4) / 2, 2)) * 50 # ... |
import sys
import os
import unittest
import shutil
from io import StringIO
sys.path.append(".")
from mock_gff3 import Create_generator
from mock_helper import gen_file
import annogesiclib.plot_PPI as pp
class Mock_func(object):
def mock_add_node(self, G, nodes):
pass
def mock_add_edge(self, G, ppi, ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import argparse
import json
import logging
import re
import sys
import textwrap
import os.path
import yaml
from collections import OrderedDict
from sysl.util import debug
from sysl.util import writer
from sysl.proto import sysl_pb2
OPENAPI_FORMATS = {'int32', 'int64'... |
### EXERCISE 3
### BIGMART SALES
# import some useful things
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import t... |
#!/usr/bin/env python3
from __future__ import annotations
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
from typing import Any, Dict, List, Set
from urllib.request import urlretrieve
import pcpp # type: ignore
BITSIZE, LINKAGE = plat... |
import os
import random
import re
import warnings
from collections import defaultdict
import cv2
import numpy as np
import pandas as pd
import tqdm
from torch.utils.data import Dataset
CARVANA_W = 1918
CARVANA_H = 1280
TRAIN_IMAGE_PATH = 'input/train'
TEST_IMAGE_PATH = 'input/test'
MASKS_DECODED_PATH = 'input/train_m... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from aldryn_apphooks_config.fields import AppHookConfigField
from aldryn_categories.models import Category
from aldryn_categories.fields import CategoryManyToManyField
from aldryn_translation_tools.models import TranslatedAutoSlugifyMixin, Transla... |
"""Module to load the elements of the machine from csv files.
The csv files are stored in one directory with specified names:
* elements.csv
* devices.csv
* families.csv
* unitconv.csv
* uc_poly_data.csv
* uc_pchip_data.csv
"""
import collections
import contextlib
import copy
import csv
from pathlib import Path... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
report.py
Generates report on Bot Framework issues.
See README.md for details on installing/using.
"""
import os
import sys
import copy
import requests
from github import Github, Label, GithubObject
from colorama import... |
import os
import numpy as np
import cv2
from typing import Union
from scipy.io import loadmat
from image import Image
from multispectral_object import MSObject
#from b_Segmentation.RoI_selection import RoI
import pandas as pd
import pickle
import argparse
def get_parser():
"""Parse input arguments"""
parser =... |
# coding: utf-8
import unittest
import os
import time
import datetime
import argparse
import mock
import concorde
import concorde.command_line
CUR_DIR = os.path.dirname(__file__)
TESTSITE = os.path.join(CUR_DIR, 'testsite')
class TestGetSources(unittest.TestCase):
def setUp(self):
os.chdir(TESTSITE)
... |
import asyncio
import contextlib
import inspect
import io
import itertools
import random
import re
import textwrap
import traceback
from functools import partial
import discord
from discord.ext import commands
from ..utils import disambiguate
from ..utils.context_managers import temp_attr
from ..utils.examples import... |
import sys
import pprint
import copy
# "... For each display, you watch the changing signals for a while,
# make a note of all ten unique signal patterns you see ..."
def get_signals(fh):
for line in fh:
signals = line.strip().split()
input_signals.append(list(map(set,signals[0:10])))
out... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
VGG16_NPY_PATH = 'vgg16.npy'
WD = 5e-4
data_dict = np.load(VGG16_NPY_PATH, encoding='latin1').item()
def activation_summary(var):
tensor_name = var.op.name
... |
# *****************************************************************************
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... |
# -*- coding: utf-8 -*-
from common.base_test import BaseTest
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import (
check_that, check_that_in, equal_to, greater_than_or_equal_to, has_entry, is_none, not_equal_to
)
SUITE = {
"description": "Method 'set_subscribe_callback'"
}
@lcc.prop("mai... |
import logging
from typing import Dict
from django.contrib.auth.models import User
from django.core import signing
from django.db import transaction
from django.http import HttpResponseRedirect
from django.utils import timezone
from drf_yasg.utils import swagger_auto_schema
from rest_framework import serializers
from ... |
import getpass
import os
import time
from tkinter import *
from threading import Thread
from tkinter import messagebox
from PIL import ImageTk, Image
import tkinter as tk
import socket
from plyer import notification
from tkinter import filedialog
import os
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
user32 = ... |
import argparse
import numpy as np
import os
import sys
import models as arch_module
import torch
import torch.nn as nn
sys.path.append('..')
from data_loader import TinyImageNet
from torch.autograd import Variable
from torchvision import datasets, transforms
# Prune settings
parser = argparse.ArgumentParser(descri... |
import cv2
import os
import numpy as np
from PIL import Image
def scalling_factor():
img = cv2.imread('C://users//ateeb//desktop//GoogleImages//53.jpg')
# draw a rectangle
cv2.rectangle(img, (579,293),(870,487), (255,0,0), 2)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# resizing the image
... |
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV,calibration_curve
from sklearn.model_selection import StratifiedKFold,cross_val_score
from sklearn.metrics import plot_roc_curve,plot_confusion... |
from abc import abstractmethod
import numpy as np
from tqdm import tqdm
from typing import List, Iterable, Iterator, Any, Tuple
from .doc import BiText, EncodedBiText, BatchDocs
from .applicator import Applicator
@Applicator.register('encoder')
class Encoder(Applicator):
def __init__(self,
bat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import sys
import argparse
import os
import re
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
try:
# For Python 3.0 and ... |
# Regular Module Imports
from os import path, sys
# Discord API Imports
import discord
from discord.ext import commands
# Google Docs/Sheets API Imports
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
# Assistance Files Imports
from media imp... |
from enum import Enum
from typing import (List, Mapping, Sequence, Optional, MutableSequence,
TypeVar, Any, FrozenSet, MutableSet, Set, MutableMapping,
Dict, Tuple, _Union)
from ._compat import lru_cache, unicode, bytes, is_py2
from .disambiguators import create_uniq_field_dis_fu... |
# === Start Python 2/3 compatibility
from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# === End Python 2/3 compatibility
import pytest
impo... |
from typing import Optional, Union, Tuple
from torch._C import device
from torch_geometric.typing import OptTensor, Adj
import math
import torch
from torch import Tensor
import torch.nn.functional as F
from torch.nn import Parameter as Param
from torch.nn import Parameter
from torch_scatter import scatter
from torch_... |
from pprint import pformat
import datetime
import random
from time import sleep
import uuid
from collections import Counter
import tator
from ._common import assert_close_enough
def wait_for_parity(tator_api, project, patch, expected_ids):
attribute_filter = [f"test_string::{patch['attributes']['test_string']}"]... |
import h5py
import numpy as np
import pytest
import json
# We generate mock data files for different versions of the Bluelake HDF5 file
# format:
class MockDataFile_v1:
def __init__(self, file):
self.file = h5py.File(file, 'w')
def get_file_format_version(self):
return 1
def write_meta... |
"""Vehicle detector"""
import collections
import cv2
import glob
import numpy as np
import os.path
import time
from sklearn import svm
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.utils import shuffle
from scipy.ndimage.measurements import label
f... |
"""
MODFLOW 6 Autotest
Test to confirm that the sum of rate-actual and maw-reduction observations
is equal to the specified MAW extraction or injection pumping rate when
reported using the MAW_FLOW_REDUCE_CSV option. Injection and extraction
are tested for both MAW HEAD_LIMIT and RATE_SCALING options to reduce MAW
flow... |
import os.path as osp
import cv2
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
from ..registry import PIPELINES
@PIPELINES.register_module
class LoadImageFromFile(object):
def __init__(self, to_float32=False, color_type='color'):
self.to_float32 = to_float32
self.color_type... |
from progress.bar import IncrementalBar
from vk_module.vk_importer import VkImporter
from vk_module.vk_constants import *
import db.stud_networkdb as db
from analysis.interest_management.text_interest import TextInterestManager
from analysis.data_parsing.word_vectorizer import WordVectorizer
from common.timestamp imp... |
import logging
import click
from itertools import chain
from collections import namedtuple
import asyncio
from tornado.platform.asyncio import AsyncIOMainLoop
from streamz import Stream, union, combine_latest, zip_latest
import attr
from .events import PriceUpdate
from .collectors import Collector
from .feeds import ... |
#!/usr/bin/env python3
"""
Test the fancy iterator.
"""
import sys
import numpy as np
from ..api import ProgressWithDots, ZgyReader, ZgyWriter, SampleDataType
from ..test.utils import SDCredentials
from ..iterator import readall
def _test_consume(iterator):
ncalls = 0
nvoxels = 0
maxconsumed = [0, 0, 0]... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# -*- coding: utf-8 -*-
"""
Functions for working with network modularity
"""
import bct
import numpy as np
from sklearn.utils.validation import check_random_state
from . import cluster
try:
from numba import njit, prange
use_numba = True
except ImportError:
prange = range
use_numba = False
def cons... |
# -*- encoding:utf-8 -*-
"""示例ump边裁价格波动特征模块"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from ..TradeBu.ABuMLFeature import AbuFeatureWave
from ..MLBu.ABuMLPd import AbuMLPd
from .ABuUmpBase import ump_edge_make_xy, BuyUmpMixin
from .ABuUmpEdgeBase im... |
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from statsmodels.api import *
from IPython.display import display , Markdown
import matplotlib.pyplot as plt
import statsmodels as sm
from patsy import dmatrix
import scipy as sp
import plotly.plotly as py
import plotly.graph_objs ... |
import os
import json
import h5py
import numpy as np
import jittor as jt
from jittor.dataset import Dataset
from argparse import ArgumentParser
from utils.config import add_data_args
import utils.util as util
"""
dataset config
preload
occ
data_path
subsample
voxel_res
train/valdt_split
py... |
import json
import logging
import os
import re
import sys
import pygraphviz as pgv
from text_to_4lang import TextTo4lang
from flask import Flask
from flask import jsonify
from corenlp_wrapper import CoreNLPWrapper
from dep_to_4lang import DepTo4lang
from lexicon import Lexicon
from magyarlanc_wrapper import Magyarlanc... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from threshold import binarize_with_threshold
from perspective_transform import perspective_transform
def viz1(binary_warped, ret, save_file=None):
"""
Visualize each sliding window location and predict... |
"""
Code borrowed/reproduced from kjchalup's 'A fast conditional independence test'
Reference: <NAME> and <NAME>, 2017.
@author: roshanprakash
"""
import pandas as pd
from joblib import Parallel, delayed
import numpy as np
import time
from scipy.stats import ttest_1samp
from sklearn.preprocessing import StandardScale... |
import torch
import torch.nn.functional as F
import torch.optim as optim
import torchvision.models as models
from tqdm import tqdm
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def gram_matrix(x):
"""Computes the gram matrix of the input
Parameters
----------
input : tensor
... |
#! /usr/bin/env python
import sys
import numpy as np
from mayavi import mlab
import networkx as nx
def draw_bonds_color(coords, bonds, scale_factor=.1, resolution=2):
'''
color by coordination number
'''
nn = bonds
G = nx.Graph()
G.add_edges_from(nn)
deg = np.array([G.degree(i) for i in G... |
from __future__ import print_function
import numpy as np
import os, sys
sys.path.append(os.path.abspath(''))
from custom_clients import tf_serving_client#, graph
# from custom_clients import image_preprocessor_dlib
from custom_clients import image_preprocessor
from custom_clients import simple_graph
from custom_clients... |
"""
File that involves dataloaders for the Visual Genome dataset.
"""
import json
import os
import sys
from os.path import join, basename, dirname, exists
import h5py
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from torch.utils.data import Dataset
from torchvision import datasets, tran... |
from math import pi
import torch
from functools import wraps
from torch import acos, atan2, cos, sin
from einops import rearrange, repeat
# constants
THRES = 7e-2
# helper functions
def exists(val):
return val is not None
def to(t):
return {'device': t.device, 'dtype': t.dtype}
def taylor(thres):
def ... |
from functools import lru_cache
from random import randint
from imageio import imread
import numpy as np
import cv2
import torch
import h5py
class CachedImageReader():
@staticmethod
@lru_cache(maxsize=6)
def _read(path):
return imread(path)
def __init__(self, keys=['img','mask','dep... |
#!/usr/bin/env python
# # Practical PyTorch: Playing GridWorld with Reinforcement Learning (Actor-Critic with REINFORCE)
# ## Resources
# ## Requirements
import numpy as np
from itertools import count
import random, math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim... |
#!/usr/share/ucs-test/runner /usr/bin/py.test -slvv --cov --cov-config=.coveragerc --cov-append --cov-report=
# -*- coding: utf-8 -*-
#
# Copyright 2021 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero Gener... |
import socket
import sys
from SPARQLWrapper import SPARQLWrapper, JSON
import sys
from lxml import etree
def print_example_queries():
#examples of queries that are possible with this program
print("Dit programma kan diverse vragen beantwoorden. \n")
print("Mogelijke vragen over personen: \n")
print("Wat is de leng... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import random
import argparse
if sys.version[0] == '2': input = raw_input
class Shape:
def __init__(self, up = False, down = False, left = False, right = False):
self.up = up
self.down = down
self.left = left
self.right = r... |
# LIGGGHTS packing density, mean and RMS diamter calculator
import numpy as np
import pandas as pd
from random import uniform
# Enter the input filenames in this array separating with comma
fname = 'test'
filenames = [fname+'.particles']
# initializing the output table
output = pd.DataFrame(columns=['Total_Density',... |
"""
factorial: This module contains tools for designing factorial experiments. Full factorial
experiments (where every combination of treatments is explored) and partial factorial (where only a
fraction of combinations are explored). Partial factorial experiments are sometimes referred to as
fractional factorial experi... |
#!/usr/bin/env python3
#
# Script to analyze results of our branch prediction heuristics
#
# This file is part of GCC.
#
# GCC 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, or (at your opti... |
# SPDX-License-Identifier: MIT
"""Provides data exchange formats."""
# Python imports
import datetime
from functools import total_ordering
# external imports
from dateutil import parser
# app imports
from calingen.constants import EventCategory
from calingen.exceptions import CallingenInterfaceException
SOURCE_INT... |
#<NAME> - 10770579
#<NAME> - 9784401
# %% imports
import time
import numpy as np
from numba import vectorize, njit, stencil
#Este arquivo contém os métodos importados do EP1
# %% define he_solver (Heat Equation Solver)
class crank_nicolson:
''''Classe que resolve o problema de distribuicao de calor atrav... |
import subprocess
import yaml
import requests
import json
import copy
import os
def load_yaml(yaml_file_name):
try:
with open(yaml_file_name, "r") as yaml_file:
try:
loaded_data = yaml.safe_load(yaml_file)
except Exception as yaml_reading_fault:
pri... |
#m.space Standard imports
import copy
import itertools
# Scientific computing imports
import numpy
import matplotlib.pyplot as plt
import networkx
import pandas
import seaborn
class Person(object):
"""
Person class, which encapsulates the entire behavior of a person.
"""
def __init__(self, model,... |
# Copyright 2018 DeepMind Technologies Limited. 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 ... |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# 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, modify, merg... |
import xml.sax
from pathlib import Path
from multiprocessing import Pool
from functools import partial
from collections import deque
from articlenizer import articlenizer
from articlenizer.util import chunk_list
PARAGRAPH_TAGS = ['title', 'p', 'sec', 'abstract']
LINEBREAK_TAGS = ['list-item']
LINK_TAGS = ['ext-link'... |
#!/usr/bin/env python
#
# tabular_to_wikitable.py
#
# Script to convert plain text tab-separated tables to MediaWiki-compatible
# wikitable markup, preserving headers and titles where possible.
#
# USAGE: tabular_to_mediawiki.py [-h] [-o OUTFILENAME] [-i INFILENAME] [-v]
# [--header HEADE... |
import streamlit as st
import pandas as pd
import altair as alt
from box import Box
from investr.views.register import declare_view
from investr.common.mortgage import get_loan_summary
def make_sidebar(sidebar):
with st.sidebar.expander("Property", True):
sidebar.plot_value = st.number_input(
... |
## todos
## vectorize arith_mean and trimmed_mean
import numpy as np
from numpy.random import default_rng
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# plt.style.use('aistats2022')
## ----------------------------------------------------------------------
## given Monte Carlo samples, how... |
import random
import numpy as np
import settree.operations as ops
OPERATIONS = [ops.Min(), ops.Max(), ops.Sum(), ops.Mean(), ops.SecondMomentMean(), ops.HarmonicMean(), ops.GeometricMean()]
OPERATIONS_BASIC = [ops.Min(), ops.Max(), ops.Sum(), ops.Mean()]
DTYPE = np.float32
class SetDataset():
"""
Object for ... |
from itertools import chain
import Bio.Data.CodonTable as ct
from scipy.stats import gmean
from collections import Counter
# get rid of Biopython warning
import warnings
from Bio import BiopythonWarning
warnings.simplefilter("ignore", BiopythonWarning)
def _synonymous_codons(genetic_code_dict):
# invert the ge... |
from __future__ import print_function
import urllib
import os
import shutil
import datetime
import boto3
import botocore
import zlib
import gzip
import sys
import json
# Non standard libraries packaged in ./lib directory
lib = os.path.abspath('lib/')
sys.path.append(lib)
# Non standard libraries
from BeautifulSoup i... |
# -*- coding: utf-8 -*-
import os
import numpy as np
from numpy.testing._private.utils import assert_equal
import pytest
import pandas as pd
import sliceoptim.samples as sp
import sliceoptim.core as core
__author__ = "<NAME>"
__copyright__ = "<NAME>"
__license__ = "mit"
test_stl_first_layer = "./assets/first_layer.... |
from scipy.spatial.distance import euclidean
import numpy as np
import imutils
import time
import cv2
'''
来自于:Lya
(from:Lya)
大四在学校太无聊做的
(I did it in college because I was bored)
'''
def delay(content):
print('--------' + str(content) + '--------')
time.sleep(0.5)
def set_camera_type():
delay('设置相机调用')... |
__source__ = 'https://github.com/kamyu104/LeetCode/blob/master/Python/count-of-smaller-numbers-after-self.py'
# https://leetcode.com/problems/count-of-smaller-numbers-after-self/#/description
# Time: O(nlogn)
# Space: O(n)
#
# Description: Leetcode # 315. Count of Smaller Numbers After Self
#
# You are given an intege... |
from time import sleep
import socket
import sys
from time import sleep
import re
sys.path.append('./')
import clients.metasploit
def strip_whitespaces(str):
return ' '.join(str.split(''))
def host_table(client):
hosts = []
response = str(client.console_execute('hosts -c address,mac,os_name,os_flavor')) ... |
#!/usr/bin/env python
# %%
# create dataset for NGNN
import os
import numpy as np
import torchutils
from sklearn.metrics import roc_auc_score
# %%
# load polyvore maryland dataset
inputDir = "maryland-polyvore/release"
outputDir = "maryland-polyvore/processed"
dataDir = "maryland-polyvore/ngnn"
trainOutfits = torc... |
# -- coding: utf-8
""" Classes which provide scoping rules and enforce limits for the crawler framework """
import utils
import urlhelper
import collections
import datetime
import urlparse
import os
from eiii_crawler.crawlerevent import CrawlerEventRegistry
# Default logging object
log = utils.get_default_logger()
... |
#!/usr/bin/env python
import barrel
import os
import subprocess
import hermes
import sys
import time
import argparse
ANDROID_DISTRIBUTION_MODES = ["google", "huawei"]
IOS_DISTRIBUTION_MODES = ["apple"]
def generate_entry_file(file_name, environ, distribution_mode):
with open(file_name, "w") as f:
f.write... |
# Copyright 2021 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, ... |
#!/usr/bin/env python
#-*- coding: us-ascii -*-
'''
setup.py
Installation script for Python-LLFUSE.
Copyright (c) 2010 <NAME> <N<EMAIL>>
This file is part of Python-LLFUSE. This work may be distributed under
the terms of the GNU LGPL.
'''
from __future__ import division, print_function, absolute_import
import sys
... |
from utils import *
from libs import *
import argparse
def validate_theta():
pass
def validate_phi():
pass
def get_next_cam_loc(obj_cam_loc, far_corner):
if far_corner[0] > IMG_H*0.6:
if far_corner[1]< IMG_W*0.3:
# decreace phi
# increace theta
obj_cam_loc.... |
# Copyright 2011 Viewfinder Inc. All Rights Reserved.
"""Viewfinder web application server.
Sets up logging, server command line variables, the list of primary
request handlers.
The "cookie_secret" value in the application settings is a long string
of randomly generated bytes and is used to store a secure cookie wit... |
# Description:
# Functions that deal with data generation/manipulation
# Imports:
import game_mechanics as gm
import GUI
import numpy as np
from keras.utils.np_utils import to_categorical
from _collections import deque
import os
# Constants:
board_len = 30
# Functions:
def moves_to_board(moves... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.