text stringlengths 3.07k 12.6k |
|---|
import click
import arrow
import os
import csv
import configparser
from tabulate import tabulate
from nuget import PackageManager
from nuget import Package
from tempfile import gettempdir
from github import Github
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
@clic... |
import os
import sys
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
import shutil
import json
import ustrings
from . import session
from .. import lib
def ils_output_to_entries(stdout):
raw = stdout.strip().split('\n')
collection = raw[0]
entries = [entry.strip(... |
import os
from collections import namedtuple
from eg import color
from eg import config
from mock import patch
from nose.tools import assert_equal
# Some hardcoded real colors.
_YELLOW = '\x1b[33m'
_MAGENTA = '\x1b[35m'
_BLACK = '\x1b[30m'
_GREEN = '\x1b[32m'
# The flags in the test file marking where substitutions... |
from __future__ import print_function # Python 2/3 compatibility
from botocore.vendored import requests
import json
import uuid
import os
def lambda_handler(event, context):
print("Event:", event)
signal = event.get('signal', {})
channel = event.get('channel')
if channel:
signalId = event.get... |
import os
import pickle
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import cm
NUM_EDGES = [2, 4, 8, 16, 32]
AGENT_TYPES = ['Greedy-max-capacity', 'Greedy-max-routeness', 'Greedy-max-degree', 'LPP-max-capacity',
'LPP-max-routeness', 'LPP-max-degree', 'Random']
COLORS = ['da... |
# -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
"""core user interface
:mod:`pcapkit.interface.core` defines core user-oriented
interfaces, variables, and etc., which wraps around the
foundation classes from :mod:`pcapkit.foundation`.
"""
import io
import sys
from pcapkit.foundation.analysis import analys... |
import torch
from torch import nn
from .blocks import ConvTanh, ConvLReLU, ConvBnLReLU, UpConvBnReLU
class Generator(nn.Module):
'''
ROI Generator
Args:
map_channels (default: int=3): Number of Map input channels
point_channels (default: int=3): Number of Point input channels
hid... |
#!/usr/bin/env python3
"""Split long sequences into chunks."""
import logging
import math
import statistics
from collections import defaultdict
from pathlib import Path
from docopt import docopt
from tolkein import tofile
docs = """
Window stats.
Usage: ./window_stats.py [--in TSV] [--window FLOAT...] [--min-window... |
"""Extracts indices from html-derived files for vandam
Expects input files with two entries per line (lines are marked '<br>' tags).
Entries are cleaned up and filtered, notably to remove page numbers and discard titles and comments.
Entries that have comma-separated parts are reordered, and alternative forms (marked ... |
import sys
import pickle
def indexVCF(vcfFile):
infile = open(vcfFile,'r')
depthDict = {}
for line in infile:
if line[0] != '#':
lineSplit = line.split('\t')
info = lineSplit[7]
infoSplit = info.split(';')
dp = infoSplit[0]
if dp[0:3] == 'D... |
from ctapipe.core.factory import Factory
from ctapipe.core.component import Component
from traitlets import Int, TraitError
import pytest
from traitlets.config.loader import Config
import warnings
class ExampleComponentParent(Component):
value = Int(123, help="").tag(config=True)
def __init__(self, config, p... |
from glob import glob
import pytest
import tempfile
from datetime import datetime
from src.Downloader import RinexDownloader
@pytest.mark.parametrize('test_input,expected', [
(['nybp', datetime.now(), datetime.now()], True),
(['p589', datetime.now(), datetime.now()], True),
(['NYBP', datetime.now(), datet... |
from tkinter import *
import socket, random
import sys
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
isEstablished = False
#pirnt
#initializing part
root = Tk()
root.geometry('800x400+200+100')
root.resizable(False, False)
#connection block BEGIN
connectTo = LabelFrame(text = "Connect to")
par... |
import sys, os
from sklearn.metrics import roc_auc_score, recall_score, precision_score, roc_curve
import pandas as pd
import numpy as np
from evaluation.evaluateScoresList import evaluateScoresLists
DO_ROC_CURVE= False
#DO_SEQ_AVERAGING=True
DO_SEQ_AVERAGING=False
#BINDING_CMAPS_PATH="/home/rsanchez/Tesis/rriPredMe... |
# backend.py
# handles all (merged) transactions once a day
import sys
import os
import glob
# Inputs:
# - Transaction summary file (merged from several)
# - Previous instance of Master Account List
# AAAAAAA MMMMM NNNN
# acctNum money name
# Outputs:
# - New instance of Master Account List
# A... |
import cv2
import torch
import torch.nn as nn
from torch.nn import functional as F
from util import *
class CAM(object):
def __init__(self,
img_path,
label_path,
model_name,):
self.img_path = img_path
self.save_dir = "./results/cam"
self.l... |
from behave import given, when, then
import speech_recognition as sr
import asyncio
import re
import sqlite3
from os import path
# #######TEST RECORDED SPEECH########## #
get_file = lambda f: path.join(path.dirname(path.realpath(__file__)), "/materials/" + f.lower() + ".wav")
test_file = lambda f: path.join(path.dirna... |
from abc import ABC, abstractmethod
import numpy as np
import random
import librosa
import pyroomacoustics as pra
class DataAugmenter(ABC):
"""
Abstract class for data augmentations
"""
@abstractmethod
def augment(self, recording):
pass
class DanSpeechAugmenter(DataAugmenter):
"""... |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os, sys, re
import logging
import TGraph
import TNode
import Node_alignment
import Topological_sort
from Compact_graph_whole import Compact_graph_whole
from Com... |
#!/usr/bin/env python3
import os
import re
import sys
import base64
import argparse
import subprocess
import collections
class ParanoidDeobfuscator:
def __init__(self):
pass
def _is_correct_encrypted_string(self, string):
# Minimun count of \\u is 2
if string.count('\\u') < 2:
... |
from .imports import *
from .utils import normalize, denormalize
def create_dict(data, timestamps):
# Function that creates a dictionary with inflow (_End) or outflow (_Start) matrix for each timestamp.
ny_dict = {}
for index in range(len(data)):
ny_dict[timestamps[index] + '_Inflow'] = data[in... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Pretrain MLM dataset
"""
import random
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
from toolz.sandbox import unzip
from cytoolz import concat
import horovod.torch as hvd
import copy
from .data ... |
"""Benchmark for `cdjs`
Benchmark compares:
- standard `json` with `bson.json_util.default` handler
- `orjson` with `bson.json_util.defaul` handler
- `orjson` with `cdjs.serialize` handler
- `orjson` with `cdjs.do_nothing` handler as a baseline
"""
from datetime import timedelta
from random import ran... |
"""
Copyright (C) 2010-2022 Alibaba Group Holding Limited.
"""
import torch
def skew(x):
"""
Args:
x (torch.Tensor): shape (*, 3)
Returns:
torch.Tensor: (*, 3, 3), skew symmetric matrices
"""
mat = x.new_zeros(x.shape[:-1] + (3, 3))
mat[..., [2, 0, 1], [1, 2, 0]] = x
mat[... |
# <Copyright 2019, Argo AI, LLC. Released under the MIT license.>
"""Utilities used in evaluation of performance."""
import copy
from typing import Any, Dict, List, Tuple
import numpy as np
from argoverse.utils.transform import quat2rotmat
# Label dictionary should be of the form {"center": {"x": 0.0, "y": 0.0, "z"... |
#!/usr/bin/env python3
'''
This script sparsifies the deepspline activations in a network.
It takes a trained model from a checkpoint (.pth)
and a tolerance "acc_drop_threshold" (in (-1, 0)) corresponding to the
training accuracy drop w.r.t. the original model that is tolerated.
The script then looks for the highest k... |
"""
This is an AWS Lambda function that watches specific files of a public GitHub
repository since a given date, if it detects new changes, it notifies the user
via Telegram (using a Telegram bot).
"""
from __future__ import annotations # https://www.python.org/dev/peps/pep-0563/
import json
import os
import urllib.e... |
import collections.abc
from crims2s.training.util import find_checkpoint_file
import torch
import torch.nn as nn
import numpy as np
from typing import Mapping, TypeVar, Callable, Iterable, Hashable
from ...util import ECMWF_FORECASTS
class PytorchMultiplexer(nn.Module):
"""Model multiplexer that only works on ... |
import random
import torch.utils.data
import copy
from collections import defaultdict
def filter_kcore(ratings, user_k=5, item_k=5):
while True:
item_count, user_count = defaultdict(int), defaultdict(int)
for user_id, item_id, rating, timestamp in ratings:
item_count[item_id] += 1
... |
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import f1_score, precision_score, recall_score, \
accuracy_score, confusion_matrix, c... |
import torch
from torch.nn import functional as F
from torch.nn import Linear, Parameter, Conv1d
class AttentionBase(torch.nn.Module):
"""Abstract attention class.
Arguments:
representation_dim -- size of the hidden representation
query_dim -- size of the attention query input (probably d... |
import lxml.etree, logging
_NSMAP = { 'cppa': 'http://docs.oasis-open.org/ebcore/ns/cppa/v3.0',
'pycppa3' : 'https://pypi.python.org/pypi/cppa3'}
_NSMAP2 = { 'cppa': 'http://docs.oasis-open.org/ebcore/ns/cppa/v3.0' }
def cppa(el):
return '{{{}}}{}'.format(_NSMAP['cppa'], el)
cppa3_content_model = ... |
#!/usr/bin/env python3
import argparse
import numpy as np
from osgeo import gdal
import pandas
import os
def cmdLineParse():
'''
Command line parser.
'''
parser = argparse.ArgumentParser(description='SBAS analysis')
parser.add_argument('--input', dest='infile', type=str,
... |
# Copyright (c) 2017 <NAME>
# https://alexsocha.github.io/pynode
import sys
import time
import traceback
import json
from threading import Thread
from threading import Timer as ThreadingTimer
from pynode.src import pynode_graphlib
from pynode.src import communicate
class PynodeCoreGlobals():
GLOBAL... |
import datetime
import json
import time
from urllib.parse import urlencode
import requests
from meican.commands import get_dishes, get_restaurants, get_tabs
from meican.exceptions import MeiCanError, MeiCanLoginFail, NoOrderAvailable
from meican.models import TabStatus
class RestUrl(object):
""" 用来存储 MeiCan Res... |
import collections
EPSILON = '<empty>'
END_OF_INPUT = '<$>'
class Production(object):
"""Represents a grammar production rule."""
def __init__(self, rule, func):
items = rule.split(':', 1)
self.lhs = items[0].strip()
self.rhs = items[1].strip().split() or [EPSILON]
self.func ... |
import logging
import html
import random
import re
import sys
from bs4 import BeautifulSoup
from argparse import ArgumentParser
from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer
from socketserver import ThreadingMixIn
from urllib.request import urlopen
log = logging.getLogger(__name_... |
# ----------------------------------------------------------------------
# Project: KalmanApp
# Title: gen.py
# Description: Generation of C code for Kalman
#
# --------------------------------------------------------------------
#
# Copyright (C) 2010-2020 ARM Limited or its affiliates. All rights... |
from sklearn.metrics import f1_score, confusion_matrix, classification_report
from tqdm import tqdm
import torch.nn as nn
import numpy as np
import torch
from typing import Tuple
import time
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapse... |
from mycroft import MycroftSkill, intent_file_handler
from . import reddit
from typing import Any
from pathlib import Path
def get_data_type(data_type: str) -> Any:
if data_type in ["video", "videos", "film", "films", "movie", "movies"]:
return reddit.Reddit.DataTypes.VIDEO
elif data_type in ["image", ... |
import csv
import glob
import os
import xml.etree.ElementTree as ET
from nltk import sent_tokenize, word_tokenize, ngrams
def set_directory():
"""Specify where the xml and txt files are located on the user's computer."""
os.chdir('/home/eddie/Downloads/nsf_awards2')
def retrieve_search_terms():
"""Open ... |
## usage
# at a level above emmer/
# python3 -m emmer.test.test_bifurication
from ..bake import BakeCommonArgs
from ..posthoc.stats.bifurication import BifuricationArgs, linearRegressionPVal, DifferentiatingFeatures
from ..posthoc.visual.viewer import Projection
from ..troubleshoot.err.error import ErrorCode12, ErrorC... |
from __future__ import print_function,division
import numpy as np
import torch
import torch.utils.data
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
#from matplotlib import pyplot as plt
'''
def plot(weight):
weight = weight.detach().cpu().numpy()
a = np.max(weight,... |
import pygame
import sys
from pygame.locals import *
class Node:
def __init__(self, x=None, y=None, parent=None):
self.parent = parent
self.g = self.f = 0
self.x = x
self.y = y
def heuristic(n1, end):
return weight*(abs(n1.x - end.x) + abs(n1.y - end.y))
def drawGrid():
fo... |
import json
from typing import Dict, List
import os
import struct
from collections import defaultdict
import numbers
class Register:
def __init__(self):
super().__init__()
self.identifer = ''
self.type = None
self.size = 16
class Operation:
def __init__(self):
super()... |
import json
import type_checker
class DTODescriptor:
__slots__ = "_immutable", "_type", "_field", "_validator", "_dto_class_name", "_coerce"
def __init__(self, dto_class_name: str, field: str, type_: type, immutable: bool = True,
validator: callable = None, coerce: callable = None):
... |
import numpy as np
import pandas as pd
import itertools
from functools import partial
from scipy.linalg import block_diag
def get_diag_index(d_, l):
idx = d_[d_.Class == d_.Class.value_counts().index[l]].index
return idx
def row_feature_rep(rows_, features_):
r_1 = rows_.mean(axis=1).values
f_1 = fea... |
import torch
import torchvision
import numpy as np
import time
def get_batch(bs=1):
loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('./../data/MNIST/', train=False, download=True,
transform=torchvision.transforms.ToTensor()),
batch_size=bs, shuffle=Tru... |
# -*- coding: utf-8 -*-
# Pretty ~ Useful ~ Python
from contextlib import contextmanager
from datetime import datetime
from inspect import stack
from os import environ
from os import makedirs
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from time import time
from typing import Any
from typ... |
import tensorflow as tf
import numpy as np
import time
def relu(inputs):
return tf.nn.relu(inputs)
class model():
def conv2d(self, inputs, name, out_channels, act=relu, ksize=3):
with tf.variable_scope(name):
in_channels = inputs.get_shape()[-1]
filter = tf.get_variable('weig... |
"""
byceps.blueprints.site.user.settings.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 <NAME>
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
from babel import Locale
from flask import abort, g, request
from flask_babel import force_locale, gettext
fro... |
"""
Variational Autoencoder for sequential data.
<NAME> (SURF), January 2021.
"""
import tensorflow as tf
class Reparameterize(tf.keras.layers.Layer):
""" Identity transform layer that adds KL divergence
to the final model loss.
"""
def __init__(self, kl_beta=0.001, *args, **kwargs):
se... |
#!/usr/bin/env python
import argparse
import datetime as dt
import os.path
import sys
import ait.core.log as log
'''
Convert MPS Seq files to AIT formatted sequence files
'''
VALID_HEADER_KEYS = [
'gap',
'on_board_filename',
'on_board_path',
'upload_type'
]
def extract_seq_header(input_file):
'... |
import asyncio
import json
from live2p.start_live2p import start_live2p
import logging
from datetime import datetime
from glob import glob
from pathlib import Path
import websockets
ip = 'localhost'
port = 6000
# folder = 'e:/caiman_scratch/ori_20210209_seed'
# data_folder = 'e:/caiman_scratch/ori_20210209'
init_fold... |
import numpy as np
import os
import pandas as pd
from pandas.api.types import CategoricalDtype
import plotly.express as px
import app_rais.dicts_constants as dc
modulepath = os.path.dirname(__file__)
def concentration_level(year, list_ufs, granular_level='sub_category'):
df = pd.read_feather(os.path.j... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Any, Mapping, Optional, Union, List, Iterator
from collections import OrderedDict
import logging
import time
import itertools
import yaml
import os
import shutil
import pathlib
TItems = Union[Mapping, str]
# do... |
import math
blockStart=[0,0]
def addBlock(x,y):
global blockStart
blocks.append({"x1":blockStart[0], "y1":blockStart[1], "x2":x, "y2":y, "exitVelX":0, "exitVelY":0, "accX":0, "accY":0, "blkTime":0})
blockStart = [x,y]
def bisector(p1, p2):
x1, y1 = p1
x2, y2 = p2
if (y1 == y2):
return... |
#!/usr/bin/env python3
"""Mock smbus module
Requirements
python (3.5)
"""
import sys
import os
import json
import array
__version__ = '0.8.2'
__author__ = '<NAME>'
__copyright__ = 'Copyright 2022, Spukhafte Systems Limited'
# Constants ====================
# Functions ====================
# Classes ========... |
from abc import ABC
from itertools import islice
from typing import TypeVar
from pytest import mark, fixture, raises
from graph_examples.linked_lists import (
BaseCircularLinkedList,
BaseDoublyLinkedList,
BaseLinkedList,
BaseLinkedNode,
CircularDoublyLinkedNode,
DoublyLinkedNode,
)
# pytestma... |
# Python imports.
import os
import math as m
import numpy as np
# Misc. imports.
from pysolar import solar, radiation #capitalize to get it to work?
CLOUD_DIFFUS_FACTOR = 1.0 #0.85 # 10% of light is blocked
#
def _write_datum_to_file(mdp_name, agent, datum, datum_name):
out_file = open(os.path.join("..", "result... |
import requests
import argparse
import sys
import os
import bs4
import csv
import re
import enum
from datetime import datetime
class LogType(enum.Enum):
crime = "crime"
noncrime = "noncrime"
def _process_html(string, output_writer, log_type):
soup = bs4.BeautifulSoup(string, features="lxml")
table = s... |
import random
cores = {"restart": '\033[m',
"default": '\033[1;7;30m',
"azul": '\033[1;7;34m',
"ciano": '\033[1;7;36m',
"vermelho": '\033[1;7;31m',
"verde": '\033[1;7;32m'}
def validar_int(numero):
try:
numero = int(numero)
return entrada_scop(numero)
... |
"""
Context-dependent integration task, based on
Context-dependent computation by recurrent dynamics in prefrontal cortex.
<NAME>, <NAME>, <NAME>, & <NAME>, Nature 2013.
http://dx.doi.org/10.1038/nature12742
"""
from __future__ import division
import numpy as np
from pyrl import tasktools
# Inputs
inputs = ... |
from selenium import webdriver
import time
from datetime import datetime
import os
import warnings
import yaml
from win10toast import ToastNotifier
from os.path import exists
#TODO: Automatically install correct chromedriver version and delete old versions if they exist in directory
version = "1.2.1"
# Di... |
#!/usr/bin/env python3
#
# Copyright (c) 2016 <NAME>
#
# 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... |
from charms.reactive import is_state, remove_state, set_state, when, when_any, when_none, when_not
from charmhelpers.core import hookenv
from charms.layer.apache_bigtop_base import Bigtop, get_hadoop_version
@when('hadoop-plugin.joined')
@when_not('namenode.joined')
def blocked(principal):
hookenv.status_set('blo... |
# Copyright (C) 2020 Assured Information Security, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#!/usr/bin/env python
"""
This program builds shell scripts that define the ISIS environment
variables that are sourced during conda environment activation and
removed at deactivation.
If the directories don't exist, they are created. If their path is
not specified, they are placed in $CONDA_PREFIX (which is $ISISROO... |
'''
hub-port-controller
Copyright (c) 2020 <NAME>, @GuriTech
Released under the MIT License
'''
import usb
import argparse
import json
import sys
from pprint import pprint
PORT_POWER_FEATURE = 8
# Device Handler Function
def get_device(id_vendor, id_product, serial_number = None):
for bus in usb.busses():
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Implementation for Windows. Based on `qstandardpaths_win.cpp`.
"""
import ctypes
import os.path
import pathlib
import tempfile
from .base import Config, Location, LocationError, _append_org_and_app
__all__ = ['get_writable_path', 'get_standard_paths']
c_bytes_8 = c... |
import random
import os
import sys
import numpy as np
import subprocess as sub
from functools import partial
from base import Sim, Env, ObjectiveDict
from networks import CPPN, DirectEncoding
from softbot import Genotype, Phenotype, Population
from tools.algorithms import ParetoOptimization
from tools.checkpointing im... |
#!/usr/bin/env python
import logging
import os
import runpy
import sys
import subprocess
import warnings
import codecs
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
NAME = "jira"
here = os.path.dirname(__file__)
if here not in sys.path:
sys.path.inse... |
#!/usr/bin/env python
# Copyright 2019 <NAME>
import os
import boto3
import argparse
from botocore.exceptions import ClientError
from boto3.s3.transfer import TransferConfig
import zipfile
import shutil
import threading
from queue import Queue
import time
s3 = boto3.client('s3')
s3_resource = boto3.resource('s3')
dat... |
import logging
from django.conf import settings
from django.db import connection, transaction
from django.utils import timezone
from pontoon.administration.vcs import CommitToRepositoryException
from pontoon.base.models import ChangedEntityLocale, Project, Repository
from pontoon.base.tasks import PontoonTask
from po... |
import sys
import numpy as np
from scipy.special import erfc, erfcinv, expm1
def trandn(l,u):
## truncated normal generator
# * efficient generator of a vector of length(l)=length(u)
# from the standard multivariate normal distribution,
# truncated over the region [l,u];
# infinite values for 'u' a... |
# Coded By: <NAME>
# Date: 07-04-2022
# Github: Tom-Sumner / https://github.com/Tom-Sumner
# Discord: TSumner#5215
# License: MIT
# Note: If you use this code, you MUST credit me in your project.
import aiohttp
import nextcord, os, sys, colorama, time, asyncio
from colorama import init, Fore, Back, Style
from termco... |
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from .network import network
#custom ops
from ..ops import roi_pool, loss_ops, proposal_decode, proposal_encode, bbox_delta
from ..py_ops import common, proposal
def nan_check( mat, st ):
if np.isnan( mat ).any() :
print( '... |
"""
The connection pool implementation is heavily borrowed from `aioredis`
"""
import asyncio
import collections
import sys
from .connection import create_connection
from .log import logger
from .util import async_task
from .errors import PoolClosedError
PY_35 = sys.version_info >= (3, 5)
@asyncio.coroutine
def cre... |
# Maks 1 linje mellomrom
# Rekkefølge skal ikke ha noe å si
# Trenger ikke skrive i all caps, den blir omgjort til .upper() automatisk
# INPUT() for inputs som kommer fra "ingensted"
# FLIPFLOP() for flipflops
# AND() eller OR() for gates
# Inne i parantesene putter du alle "variabler" som går som DIREKTE input
# NB!!... |
"""
OpenID Connect relying party (RP) views
=======================================
This modules defines views allowing to start the authorization and authentication process in
order to authenticate a specific user. The most important views are: the "login" allowing to
authenticate the users using ... |
import pathlib
import os
import sys
import unittest
import numpy as np
from .tools import debug_on
from numpy.polynomial.legendre import Legendre
import matplotlib.pyplot as plt
import time
try:
from gsplines.basis import BasisLegendre
from gsplines.basis import BasisLagrange
from gsplines import Interpolat... |
# !/usr/bin/env python3
# -*-coding:utf-8-*-
# @file: tf_vs_pt_ResnetV2_50.py
# @brief:
# @author: <NAME>, <EMAIL>, <EMAIL>
# @version: 0.0.1
# @creation date: 30-10-2019
# @last modified: Wed 30 Oct 2019 07:33:42 PM EDT
from __future__ import absolute_import
from __future__ import division
from __future__ import prin... |
# vim: set ts=8 sts=2 sw=2 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild 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 option) any later version.
#
# ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
dropout_value = 0.05
class DownSize(nn.Module):
def __init__(self,inchannels,outchannels):
super(DownSize, self).__init__()
self.conv1 = nn.Conv2d(inchannels, outchannels, kernel_size=3, stride=2, padding=1, bias=False)
self.c... |
import pandas as pd
import numpy as np
def getDailyVol(close,
span0=100):
"""SNIPPET 3.1 DAILY VOLATILITY ESTIMATES
Daily vol reindexed to close
"""
df0=close.index.searchsorted(close.index-pd.Timedelta(days=1))
df0=df0[df0>0]
df0=(pd.Series(close.index[df0-1],
... |
# Copyright 2020 Huawei Technologies Co., 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-2.0
#
# Unless required by applicable law or agreed to... |
#一,准备数据
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import layers, models
dftrain_raw = pd.read_csv('./data/titanic/train.csv')
dftest_raw = pd.read_csv('./data/titanic/test.csv')
dftrain_raw.head(10)
ax = dftrain_raw['Survived'].value_counts().... |
import os, io
from multiprocessing import Pool
try:
import cPickle as pickle
except:
import pickle
import numpy as np
import h5py
import pandas as pd
import sklearn.svm as svm
from sklearn.model_selection import GridSearchCV
import sklearn.metrics as sk_metrics
import scipy.stats as stats
import matplotlib.pypl... |
from collections import defaultdict
RELATIVE_BASE = 0
CURRENT_X = 0
CURRENT_Y = 0
MAP = defaultdict(int)
COLOR_STEP = True
DIRECTION = "U"
def reset_globals():
global CURRENT_X, CURRENT_Y, COLOR_STEP, DIRECTION
CURRENT_X = 0
CURRENT_Y = 0
COLOR_STEP = True
DIRECTION = "U"
def run_intcode():
... |
# Software License Agreement (Apache 2.0 License)
#
# Copyright (c) 2021, The Ohio State University
# Center for Design and Manufacturing Excellence (CDME)
# The Artificially Intelligent Manufacturing Systems Lab (AIMS)
# All rights reserved.
#
# Author: <NAME>
from typing import Union
import numpy as np
from ..utils... |
'''
File to produce following similarity measures:
- Adjacency Matrix A
- Laplacian P=D^−1A
- Deep Walk / Symmetric, Normalized Laplacian D^(−1/2)AD^(−1/2)
- NetMF
- Personalized Page Rank
- Sum of Power of Transitions
Input: Adjacency Matrix of a Graph (Dataset), NxN Matrix
Initialize: None
Output: Similarity Measure,... |
# 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... |
# Copyright (c) 2022 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# https://github.com/catenax-ng/product-data-integrity-demonstrator
#
# SPDX-License-Identifier: Apache-2.0
import base64
import os
import hashlib
import json
from urllib.parse import urlparse
from pyda... |
from .hook import HOOKS, Hook
from .lr_updater import annealing_cos
class MomentumUpdaterHook(Hook):
def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, warmup_ratio=0.9):
if (warmup is not None):
if (warmup not in ['constant', 'linear', 'exp']):
raise ValueError('... |
# _*_ coding:utf-8 _*_
# https://docs.python.org/zh-cn/3/library/pickle.html
import copyreg
import io
import os
import pickle
# 用处: 可以吧训练好的数据进行dump到file,其它机器直接load运行!!!
print("------------------常量")
# 整数,可用的最高 协议版本,3.8 是5
print(pickle.HIGHEST_PROTOCOL)
# 整数,用于 pickle 数据的默认 协议版本 3.8是4
print(pickle.DEFAULT_PROTOCOL)
... |
# -*- coding: utf-8 -*-
"""
sphinx.ext.warnings
~~~~~~~~~~~~~~~~~~~
Collect all warnings
:copyright: Copyright 2007-2009 by the <NAME>, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from sphinx.locale import _
from sphinx.environment import NoUri
from sphinx... |
'''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from .attention_best import *
import logging
from mmcv.cnn import (VGG, xavier_init, constan... |
from __future__ import division
import torch
import torch.nn as nn
class Detect(nn.Module):
"""At test time, Detect is the final layer of SSD. Decode location preds,
apply non-maximum suppression to location predictions based on conf
scores and threshold to a top_k number of output predictions fo... |
from pyspark import SparkContext, Row, SQLContext
from pyspark.ml.linalg import Vectors
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import patches as patches
__author__ = 'topsykretts'
def find_bmu(row_t, net):
"""
Find the best matching unit for a given vector, row_t... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from hierarkey.forms import HierarkeyForm
from i18nfield.fields import I18nFormField, I18nTextarea
from i18nfield.forms import I18nFormMixin, I18nModelForm
from pretalx.common.mixins.forms import ReadOnlyFlag
from pretalx.common.phrases i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.