text stringlengths 957 885k |
|---|
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.contrib.admin.helpers import AdminErrorList
from django.shortcuts import reverse
from .models import Funding
from faker import Faker
from faker.providers import internet, profile, python, currency, lorem
from time import ti... |
import logging
from packaging import version
from kube_hunter.conf import get_config
from kube_hunter.core.events.event_handler import handler
from kube_hunter.core.events.types import K8sVersionDisclosure, Vulnerability, Event
from kube_hunter.core.types import (
Hunter,
KubectlClient,
KubernetesCluster,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A module that implements the BidirectionalLayer class, a wrapper for creating
bidirectional layers.
"""
from copy import copy
import theano.tensor as tensor
from theanolm.network.grulayer import GRULayer
from theanolm.network.lstmlayer import LSTMLayer
class Bidirec... |
<reponame>joskid/vardbg
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from .config import Config
from .gif_encoder import GIFEncoder
from .opencv_encoder import OpenCVEncoder
from .text_format import irepr
from .text_painter import TextPainter
from .webp_encoder import WebPEncoder
WATERMARK = ... |
<filename>src/servitin/lib/websocket_client.py
import traceback
import asyncio
import json
import aiohttp
from async_timeout import timeout
from servitin.utils import serializable, mail_admins
class ConnectionLost(Exception):
pass
class WebsocketClient:
def __init__(self, loop, settings, log, connection_che... |
from __future__ import division
from libtbx.command_line import easy_qsub
from iotbx import pdb
import cProfile
import pstats
import iotbx.ncs
import time
import sys
import os
class null_out(object):
"""Pseudo-filehandle for suppressing printed output."""
def isatty(self): return False
def close(self): pass
de... |
<gh_stars>0
from tkinter import *
from tkinter import ttk
from BubbleSort import bubble_sort
from SelectionSort import selection_sort
from InsertionSort import insertion_sort
from QuickSort import quick_sort
from MergeSort import merge_sort
from HeapSort import heap_sort
from CocktailSort import cocktail_sort
import ra... |
# converter.py - converter module
# coding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018 <NAME>
# 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 l... |
################################################################################
# Module: archetypal.template
# Description:
# License: MIT, see full license in LICENSE.txt
# Web: https://github.com/samuelduchesne/archetypal
################################################################################
import colle... |
<filename>localized_fields/forms.py
from typing import List, Union
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms.widgets import FILE_INPUT_CONTRADICTION
from .value import (
LocalizedFileValue,
LocalizedIntegerValue,
Localize... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2015, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistri... |
<gh_stars>1-10
import numpy as np
import torch
from scipy.optimize import curve_fit
import hashlib, json
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from volsim.simulation_dataset import *
from volsim.metrics import *
plt.rcParams['pdf.fonttype'] = 42 # prevent type3 fonts in ... |
<reponame>erik-soederholm/flatland-model-diagram-editor
"""
titleblock_placement.py - Title Block Placement class modeled in the Sheet Subsystem
"""
from sqlalchemy import select, and_
from collections import namedtuple
from flatland.database.flatlanddb import FlatlandDB as fdb
from flatland.datatypes.geometry_types i... |
from django.contrib import admin
from .forms import FieldForm,CostForm,MonsterEffectForm,MonsterEffectWrapperForm,PacWrapperForm
from .models import (
EndChainEffect,
Constraint,
UserDeck,
EnemyDeck,
EnemyDeckChoice,
EnemyDeckGroup,
MonsterVariablesKind,
MonsterVariables,
Monster,
... |
from __future__ import annotations
import logging
import os
import unittest
from concurrent.futures import wait
from ..src import Client
class TestClient(unittest.TestCase):
@classmethod
def setUpClass(cls):
logger = logging.getLogger('Client')
logger.setLevel(logging.DEBUG)
formatt... |
import numpy as np
import open3d as o3d
from transformations import *
import os,sys,yaml,copy,pickle,time,cv2,socket,argparse,inspect,trimesh,operator,gzip,re,random,torch
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))
from scipy.spatial... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import argparse
plt.switch_backend('agg')
#act_funs = ['ReQU', 'ReQUr', 'tanh']
act_funs = ['ReQUr', 'ReQU', 'softplus', 'sigmoid', 'tanh']
nets = ['OnsagerNet', 'MLP-ODEN', 'SymODEN']
nActs = len(act_funs)
msg = 'Plot mean ... |
import numpy as numpy
import math
# calculate the Entropy of a dataset with label
def Entropy(Y):
# count the number of samples
n_samples = len(Y)
# calculate the entropy of the system
n_sampleszero = 0
n_samplesone = 0
for i in range(n_samples):
if (Y[i] == 0):
n_samplesze... |
"""
Auto-generate methods for PARI functions.
"""
#*****************************************************************************
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... |
<gh_stars>0
# -*- coding: utf-8 -*-
import re
FDS_MANUAL_CHAPTER_LIST_OF_INPUT_PARAMETERS = r"""
\chapter{Alphabetical List of Input Parameters}
This appendix lists all of the input parameters for FDS in separate tables grouped by namelist, these tables are in alphabetical order along with the parameters within th... |
<filename>tests/test_api.py
# -*- coding: utf-8 -*-
"""
TODO: We should document assumptions here ...
"""
import sys
import nose
import json
import requests
from mendeley import API
# from mendeley.errors import *
# TODO: We need to test if we can instatiate the API
m = API()
# Definitions
#-... |
<reponame>PlayNowKnux/urcparse<filename>urcparse/__init__.py
class URC:
def __init__(self):
self.timeChanges = []
self.sounds = []
self.events = []
self.metadata = {}
self.__soundlist__ = []
self.__offsetSounds__ = []
self.__timelist__ = [] # full of tuples (... |
<reponame>rissikess/sqlalchemy-ceodbc
from . import _fixtures
from sqlalchemy.orm import loading, Session, aliased
from sqlalchemy.testing.assertions import eq_, \
assert_raises, assert_raises_message
from sqlalchemy.util import KeyedTuple
from sqlalchemy.testing import mock
from sqlalchemy import select
from sqlal... |
<filename>prml/kernel_func.py<gh_stars>1-10
"""Kernel function
LinearKernel, GaussianKernel, SigmoidKerne, RBFKernel, ExponentialKernel, GramMatrix are implemented
"""
import numpy as np
from abc import ABC,abstractclassmethod
class BaseKernel(ABC):
def __init__(self):
pass
@abstractclassmethod
... |
# NOTE: This will not scale beyond a certain number of
# subscriptions as lambda excution is time-bound
from datetime import datetime, timedelta
import boto3
today = datetime.utcnow().date()
last_monday = today - timedelta(days=today.weekday() + 7)
last_monday_iso = last_monday.isoformat()
BODY = {
'Text': {
'... |
<reponame>deeso/service-utilities
'''
Copyright 2011 <NAME> <<EMAIL>>
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... |
<reponame>juxiangwu/image-processing
#coding:utf-8
'''
OpenCV与OpenGL结合使用
'''
import numpy as np
import cv2
from PIL import Image
import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from threading import Thread
texture_id = 0
threadQuit = 0
X_AXIS = 0.0
Y_AXIS = 0.0
Z_AXIS = 0.0
DIRE... |
import collections
import enum
import numpy as np
class Piece(enum.Enum):
"""Gomoku piece type.
none: No piece or a tie.
black: Black piece or black piece as the winner.
white: White piece or white piece as the winner.
"""
none = 0
black = 1
white = 2
Move = collectio... |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.utils.data.dataloader as dataloader
from torch.utils.data import Subset,Dataset
import torch.nn as nn
import torch.optim as optim
from torch.nn.parameter import Parameter
import numpy as np
import network as net
from random import ... |
<gh_stars>10-100
print 'Loading dependencies...'
import math, sys, time
import numpy as np
from keras import backend as K
from keras.applications import vgg16 as vgg16
from keras.layers import Dense, Dropout, Input, Flatten, LSTM, TimeDistributed, RepeatVector, Embedding, merge, Bidirectional, Lambda
from keras.model... |
<reponame>cosmocracy/qvdfile<filename>qvdfile/qvdfile.py<gh_stars>0
import os, datetime, time, re
from bitstring import BitArray, BitStream, pack
from qvdfile.xml2dict import xml2dict
class BadFormat(Exception):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class QvdFile():
... |
import torch
import numpy as np
from tqdm import tqdm
def calc_hammingDist(B1, B2):
q = B2.shape[1]
if len(B1.shape) < 2:
B1 = B1.unsqueeze(0)
distH = 0.5 * (q - B1.mm(B2.transpose(0, 1)))
return distH
def calc_map_k(qB, rB, query_L, retrieval_L, k=None):
# qB: {-1,+1}^{mxq}
# rB: {-... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
from easyai.base_name.block_name import LayerType, ActivationType
from easyai.model.base_block.utility.base_block import *
from easyai.model.base_block.utility.activation_function import ActivationFunction
from easyai.model.base_block.utility.normalization_layer i... |
# encoding: UTF-8
import time
from logging import INFO
from vnpy.trader.vtConstant import (EMPTY_STRING, EMPTY_UNICODE,
EMPTY_FLOAT, EMPTY_INT)
########################################################################
class VtBaseData(object):
"""回调函数推送数据的基础类,其他数据类继承于此"""
... |
'''
Código, funciones y clases relacionadas a la carga y lectura de
diferentes tipos de archivo (word, txt, rtf, pdf, png, jpg inicialmente).
'''
import os
from utils.auxiliares import verificar_crear_dir, adecuar_xml
# Clase lector
class Lector():
def __init__(self, ubicacion_archivo):
"""
Const... |
# common packages
from .config import config
from keras.engine import Layer
from keras.layers import SpatialDropout1D, Bidirectional, Dense, LSTM
from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, Conv1D
from keras.layers import concatenate
from keras.layers import Input, Embedding, Concatenate
from k... |
<filename>src/olympia/activity/utils.py
import datetime
import logging
import re
from django.conf import settings
from django.template import Context, loader
from email_reply_parser import EmailReplyParser
import waffle
from olympia import amo
from olympia.access import acl
from olympia.activity.models import Activi... |
#!/bin/python
from os.path import join,dirname
from vunit import VUnit, VUnitCLI
from glob import glob
from subprocess import call
import imp
def vhdl_ls(VU):
libs = []
srcfiles = VU.get_compile_order()
for so in srcfiles:
try:
libs.index(so.library.name)
except:
li... |
<reponame>cortesi/mitmproxy
#!/usr/bin/env python3
import contextlib
import glob
import os
import pathlib
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import urllib.request
import zipfile
import click
import cryptography.fernet
import parver
@contextlib.contextmanager
def chdi... |
# -*- coding: utf-8 -*-
"""
Functions related to flux calculations.
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
from scipy import interpolate
from scipy.optimize import curve_fit
from ..constants import C
from .plots import plot_redshift_peaks
from .io import read_table
def gaus... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, 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
#
# ... |
# Copyright 2020 XAMES3. 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 agree... |
"""
Preprocessor and data importer from Pair Reports data. This assumes the database has been created with the proper
models and the data exist in the project directory in /ubc-pair-grade-data.
"""
from app import create_app
from config import Config
from app.models import PAIRReportsGrade, CampusEnum, SessionEnum
imp... |
<reponame>mattmc3/my-sublime-utils
'''
SQL Tools: mattmc3
Version: 0.0.8
Revision: 20170922.4
TODO:
- Trim values
- single insert vs multiple
- values vs union all select
- Fixed width
- Tokenize strings, comments
'''
import csv
from io import StringIO
import re
class SqlUtil():
def csv_to_i... |
"""
Written by <NAME> - 2017
Class that defines the testing procedure
"""
import argparse
import re
import os
import time
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from data import ImageNetDataset
from config import Configuration
from models.alexnet import AlexNet
tfe.enable_ea... |
<reponame>mohamedattahri/python-docx<gh_stars>1-10
# encoding: utf-8
"""
Objects shared by docx modules.
"""
from __future__ import absolute_import, print_function, unicode_literals
class Length(int):
"""
Base class for length constructor classes Inches, Cm, Mm, Px, and Emu.
Behaves as an int count of E... |
"""Contains code for BUFF force field objects."""
import json
import os
from settings import global_settings
force_fields = {}
for ff in os.listdir(os.path.join(global_settings['package_path'],
'buff', 'force_fields')):
ffs = ff.split('.')
if ffs[-1] == 'json':
force... |
<filename>src/cfnlint/rules/parameters/Default.py
"""
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 restri... |
<gh_stars>0
#!/usr/bin/python3
from tkinter import Scale
from tkinter.constants import N
import PySimpleGUI as sg
from datetime import datetime
import time
import threading
from PySimpleGUI.PySimpleGUI import VStretch
# BACKGROUND_COLOR='black'
DEGREE_SIGN = u'\N{DEGREE SIGN}'
class TempControl(sg.Column):
def ... |
import copy
import math
import numpy as np
import scipy
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm
import utils.commons as commons
from utils.commons import init_weigh... |
<filename>neo/Prompt/Utils.py
import binascii
from neo.BigInteger import BigInteger
from neo.Fixed8 import Fixed8
from neo.Core.Helper import Helper
from neo.Core.Blockchain import Blockchain
from neo.Wallets.Coin import CoinState
from neo.Core.TX.Transaction import TransactionInput
from neo.UInt256 import UInt256
from... |
import json
import random
from functools import wraps
import warnings
from typing import List, Union
import numpy as np
from PyQt5.QtWidgets import QComboBox, QFileDialog
from AlgorithmParameter import AlgorithmParameter
Num = Union[int, float]
def get_max_step(sb, w):
"""
Функция-замыкание. Возвращает фу... |
import collections
import json
import os
import warnings
from typing import Union, TextIO, Dict, Tuple, Optional, List
from yaml import MappingNode
from yaml.composer import Composer
from yaml.constructor import FullConstructor, ConstructorError
from yaml.parser import Parser
from yaml.reader import Reader
from yaml.r... |
# ******************************************************************************
# pysimm.appps.zeoplusplus module
# ******************************************************************************
#
# api to zeoplusplus simulation code
#
# ******************************************************************************
# ... |
<gh_stars>0
# -*- coding: utf-8 -*-
# 1st-run initialisation
# designed to be called from Crontab's @reboot
# however this isn't reliable (doesn't work on Win32 Service) so still in models for now...
# Deployments can change settings live via appadmin
if populate > 0:
# Allow debug
import sys
# Load all... |
<filename>ols_bootstrap/auxillary/std_error.py
# Homoskedastic, HC0, HC1, HC2 and HC3 attributes' SE-s were tested with statsmodel's appropriate attributes
import numpy as np
### Heteroskedastic Standard Error Calculation Class
class HC0_1:
def __init__(self, X, residual):
self._X = X
self._residu... |
<gh_stars>1-10
#Copyright (c) 2022 <NAME>
from os import system,name
from time import sleep
from src.layout.widget import Widget
from src.layout.grid import Grid, Line
def change_suffix(num:int,base=1024,typ="B",types=["","K","M","G","T","P","E"])->str:
for i in types:
if num>base:
num/=base
... |
<gh_stars>1-10
import tensorflow as tf
import math
class Model(object):
def __init__(self, hidden_size=100, out_size=100, batch_size=100, nonhybrid=True):
self.hidden_size = hidden_size
self.out_size = out_size
self.batch_size = batch_size
self.mask = tf.placeholder(dtype=tf.float32... |
# Copyright(c) 2019-2021, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the fo... |
#!/usr/bin/python
import sys
import unittest
import os
import random
import string
from random import randint
from appium import webdriver
from time import sleep
class ScreenSharingUITest(unittest.TestCase):
baseLayout = '//android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[... |
#!/usr/bin/env python
#coding:utf-8
# Purpose: test tabl-row container
# Created: 02.02.2011
# Copyright (C) 2011, <NAME>
# License: MIT
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <<EMAIL>>"
import unittest
from ezodf2.xmlns import CN, etree
# objects to test
... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import pandas as pd
import tensorflow as tf
import sys
import metrics
class NCF(object):
def __init__(self, embed_size, user_size, item_size, lr,
optim, initializer, loss_func, a... |
<filename>motsfinder/metric/analytical/schwarzschildpg.py<gh_stars>1-10
r"""@package motsfinder.metric.analytical.schwarzschildpg
Schwarzschild slice in Painleve-Gullstrand coordinates.
Represents a slice of the Schwarzschild spacetime in Painleve-Gullstrand
coordinates based on [1].
@b References
[1] Booth, Ivan, ... |
import pickle
import os
import numpy as np
import pandas as pd
from plotnine import *
from plotnine.ggplot import ggsave
osuname = os.uname().nodename
print("osuname", osuname)
if osuname == 'MBP-von-Tilman' or osuname == 'MacBook-Pro-von-Tilman.local':
COMPOELEM_ROOT = "/Users/tilman/Documents/Programme/Python/... |
<gh_stars>1-10
#!usr/bin/env python
#-*- coding:utf-8 -*-
import time
import json
import scrapy
from ..items import NewsItem
def parse_time(ctime):
ctime = int(ctime)
time_struct = time.strptime(time.ctime(ctime), '%a %b %d %H:%M:%S %Y')
time_final = time.strftime("%Y-%m-%d %H:%M", time_struct)
retur... |
<gh_stars>10-100
# Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... |
import numpy as np
import pytest
import nengo
from nengo._vendor.npconv2d import conv2d
from nengo.exceptions import BuildError, ValidationError
@pytest.mark.parametrize("x_mul", (1, 2, 3, 4))
@pytest.mark.parametrize("k_size", (1, 2, 3, 4))
@pytest.mark.parametrize("stride", (1, 2, 3, 4))
@pytest.mark.parametrize("... |
<gh_stars>1-10
import copy
import logging
import os
from collections import Counter
import pandas as pd
import spacy
import numpy as np
import torch
from tqdm import tqdm
from wmd import WMD
from tools.config import ChainConfig
logger = logging.getLogger()
class SpacyEmbeddings(object):
def __init__(self, nlp)... |
<reponame>zhongyangni/controller
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.#
import os
from gevent import monkey
monkey.patch_all()
import socket
import subprocess
import platform
import yaml
import IPy
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns.constants im... |
from uiautomation.pages.basepage import BasePage
from uiautomation.common import Constants
from uiautomation.elements import BasePageElement
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from se... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import curses
import sys
import os.path
import copy
import numpy as np
import six
import gym
from pycolab import ascii_art
from pycolab import human_ui
from pycolab import things as plab_things
from pycolab i... |
<reponame>asr-ros/asr_state_machine
#!/usr/bin/env python
'''
Copyright (c) 2016, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
... |
from flask import Blueprint, Flask, request, send_file, abort, redirect, session
from werkzeug.security import generate_password_hash, check_password_hash
from wk.web.resources import get_template_by_name, default_static_dir
from wk.web.utils import join_path, rename_func
import uuid, os, logging, inspect, copy
from th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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-... |
#
# Copyright <NAME>, 2012-2014
#
import miner_globals
from base import *
def p_limit_command(p):
'''command : LIMIT integer'''
p[0] = LimitCommand(int(p[2]))
def p_limit_if_command(p):
'''command : LIMIT IF expression'''
p[0] = LimitIfCommand(p[3])
def p_limit_by_command(p):
'''command : LIMIT ... |
#!/usr/bin/python
import sys
import os
import signal
import time
import global_instance
from client_config import client_config
from json_utility import json_utility_instance
from file_handler import file_handler
from daemonize import daemonize
from datetime import datetime
from elasticsearch import Elastics... |
<gh_stars>1-10
import pandas as pd
import numpy as np
from sklearn.metrics import log_loss
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train... |
import pandas as pd
import numpy as np
import os
from scipy.stats import skew
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
import warnings
warnings.filterwarnings('ignore')
class TitanicData:
def __init__(self, file_path):
self.da... |
<reponame>openharmony-sig-ci/drivers_adapter
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. R... |
<reponame>calebtrahan/KujiIn_Python<filename>backup/guitemplates/helpmaindialog.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'helpmaindialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
t... |
"""Defines the class that performs the Scale database update"""
from __future__ import unicode_literals
import logging
from django.db import connection, transaction
from batch.configuration.configuration import BatchConfiguration
from batch.models import Batch
from job.deprecation import JobInterfaceSunset, JobDataS... |
import pandas as pd
from losses.losses import dice_coef, iou_seg
from utils import iou_seg
'''
# convert the history.history dict to a pandas DataFrame and save as csv for
# future plotting or use saved ones
unet_history_df = pd.DataFrame(Unet_history.history)
unet_plus_history_df = pd.DataFrame(Unet_plus_history.his... |
#!/usr/bin/env python
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
# pylint: disable=R0201
import StringIO
import base64
import functools
import json
import logging
import os
import sys
impo... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
import numpy as np
import re
from torch.utils.data import Dataset
import time
from src.dataloader_utils import AA_DICT, MASK_DICT, DSSP_DICT, NUM_DIMENSIONS
from itertools import compress
class Dataset_pnet(Dataset):
def __init__(self, file, transform=None, transform_target=None, transform_mask=None, max_seq_len=3... |
<filename>ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/rtp_template.py
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Rtp(Base):
__slots__ = ()
_SDM_NAME = 'rtp'
_SDM_ATT_MAP = {
'Version': 'rtp.header.version-1',
... |
import textwrap
from pathlib import Path
from typing import List
import pandas as pd
from tabulate import tabulate
from python import SENTENCE_IDX, TOKEN, TOKEN_IDX_FROM, TOKEN_IDX_TO, DOCUMENT_ID, TOPIC_ID, SUBTOPIC
from python.handwritten_baseline import PREDICTION, LABEL, INSTANCE, IDX_A_MENTION, IDX_B_MENTION, ID... |
# Load necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import stanza
from nltk.corpus import stopwords
import argparse
stanza.download('sv', processors='tokenize,pos,lemma,depparse')
nlp = stanza.Pipeline(lang='sv', processors='tokenize,pos,lemma,depparse')
def def... |
import cv2 as cv
import numpy as np
import random
import os
import matplotlib.pyplot as plt
os.chdir("C:\\Users\\m\\Desktop\\第三次作业")
name=["citywall","citywall1","citywall2","elain","elain1","elain2","elain3","lena","lena1","lena2","lena4","woman","woman1","woman2"]
def show(img,name="img"): #显示图像
cv... |
import pyparsing as pp
import networkx as nx
def copyAttributes(A, B):
for u in B:
if "latent" in A.nodes[u]:
B.nodes[u]["latent"] = True
def vertexFlowGraph(G):
vfG = nx.DiGraph()
for n in G.nodes():
vfG.add_edge(n, n + "#", capacity=1)
for desc in G.successors(n):
... |
<reponame>SDRAST/Data_Reduction
"""
This is supposed to be a general purpose boresight fitter but it has too many
DSS-28 dependencies.
"""
import logging
import numpy as NP
import scipy
import Astronomy.Ephem as Aeph
import Astronomy.DSN_coordinates as Adsn
import Data_Reduction.maps as DRm
import Math.least_squares ... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
<filename>modules/sfp_dnsbrute.py
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_dnsbrute
# Purpose: SpiderFoot plug-in for attempting to resolve through brute-forcing
# common hostnames.
#
# Author: <NAME> <<EMAIL>>
... |
<filename>kafkaConnector.py
#!/usr/bin/python
#coding=utf-8
import logging
from logni import log
from timeout import timeout
from timeout import TimeoutByThreads
from pykafka import KafkaClient
import pykafka
import sys
import traceback
def transformLoggerLevel(level):
lvlMap = {'DEBUG': ('DBG', 3),
'WARNING'... |
<reponame>Tim232/Python-Things
print('')
print('====================================================================================================')
print('== 문제 223. 완성된 pingpong 게임을 수행하시오.')
print('====================================================================================================')
from tkinter im... |
from iconservice import *
from .tokens.IRC2mintable import IRC2Mintable
from .tokens.IRC2burnable import IRC2Burnable
from .utils.checks import *
TAG = 'bnXLM'
TOKEN_NAME = 'Balanced Lumens'
SYMBOL_NAME = 'bnXLM'
DEFAULT_PEG = 'XLM'
DEFAULT_ORACLE_NAME = 'BandChain'
INITIAL_PRICE_ESTIMATE = 21 * 10**16
MIN_UPDATE_TIM... |
from __future__ import division
import time
import pandas as pd
import cea.config
import cea.inputlocator
from legacy.flexibility_model.electric_and_thermal_grid_planning import process_results
from cea.technologies.thermal_network import thermal_network
from cea.technologies.thermal_network import thermal_network_c... |
<reponame>patrick013/TopicSeg-
import segeval
from decimal import *
import numpy as np
'''
This script aims to do evaluation of topic segmentation;
For evaluating the segmentation algorithms, the metric of traditional windows-based measurement P_k and Windiff are applied in this script;
In addition, Boundar... |
<reponame>maxwellmattryan/cs-313e
# Given n of 1 or more, return the factorial of n,
# which is n * (n-1) * (n-2) ... 1.
# Compute the result recursively (without loops).
def factorial(n):
...
# We have a number of bunnies and each bunny has two big floppy ears.
# We want to compute the total number of ears acro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.