content stringlengths 5 1.05M |
|---|
import numpy as np
import pytest
from sklearn.model_selection import train_test_split
from sklearn.utils import estimator_checks
from sklearn.utils.estimator_checks import check_transformers_unfitted
from sklego.common import flatten
from sklego.preprocessing import RandomAdder
from tests.conftest import nonmeta_check... |
# -*- coding: utf-8 -*-
import unittest
from nose.tools import raises
import os
import torch
import tempfile
from kraken.lib import vgsl
class TestVGSL(unittest.TestCase):
"""
Testing VGSL module
"""
def test_helper_train(self):
"""
Tests train/eval mode helper methods
"""
... |
""" Define a Check monad and corresponding functions.
"""
from functools import (reduce, partial)
class Check:
""" This super class is not really necessary but helps make the structure
clear.
data Check a = Pass a | Fail Message
"""
pass
class Pass(Check):
def __init__(self, value):... |
from django.db import models
# Create your models here.
class Device(models.Model):
name = models.SlugField(default="Unknown", max_length=100)
ip = models.GenericIPAddressField()
mac = models.CharField(max_length=17)
netmask = models.CharField(max_length=15, default="255.255.255.0", blank=False, null=... |
# -*- coding: utf-8 -*-
"""utils.py: Django datatableview_advanced_search"""
from __future__ import unicode_literals
from __future__ import print_function
import logging
__author__ = 'Steven Klass'
__date__ = '3/1/18 9:22 AM'
__copyright__ = 'Copyright 2018 IC Manage. All rights reserved.'
__credits__ = ['Steven Kla... |
from flask_migrate import Migrate
from app import create_app
from config import config_options
from app.commands import photo_config, db_config, login_config, mail_config, db
app = create_app('development')
app.config.from_object(config_options['development'])
# print(app.config['SQLALCHEMY_TRACK_MODIFICATIONS'])
phot... |
from .complement import complement
def positive(x):
return x > 0
def complement_nocurry_test():
assert complement(positive, 0)
assert complement(positive, -5)
assert not complement(positive, 5)
def complement_curry_test():
nonpositive = complement(positive)
assert nonpositive(0)
assert... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils import *
class OWLClass():
def __init__(self, category, symbol):
self.uri_fragment = symbol
self.uri = make_uri(category, symbol)
self.category = category
self.type = RDFTriple(self.uri, "rdf:'type'", make_uri('owl', 'Class'... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: plp/proto/Vad.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.p... |
from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from .forms import ContactForm
from django.shortcuts import render, get_object_or_404
from django.views.generic.base import TempleteView
from django.Views.generic.list import listView
from .models import Usuarios, Experi... |
import numpy as np
from lie_learn.spectral.SO3FFT_Naive import SO3_FT_Naive
def conv_test():
"""
Compute the convolution of two functions on SO(3).
Let f1 : SO(3) -> R and f2 : SO(3) -> R, then the convolution is defined as
f1 * f2(g) = int_{SO(3)} f1(h) f2(g^{-1} h) dh,
where g in SO(3) and d... |
import os, errno, sys, time, shutil
import shlex, subprocess, math
import multiprocessing as mp
import numpy as np
def median(list):
return np.median(np.array(list)).tolist()
def get_stats(data, Z=1.96):
mean = np.mean(data , dtype=np.float32)
std = np.std(data, dtype=np.float32, ddof=1)
CI = Z * (std... |
'''
FIBER WALK DEMO
This class generates the growing lattice.
It expands the lattice around every reached point.
The demo uses:
- the networkX package (http://networkx.lanl.gov/)
- the numpy package (http://sourceforge.net/projects/numpy/)
- the scipy package (http://www.scipy.org/SciPy)
- the classes Lattice and Fi... |
'''
Hallar potenciación y factorial de manera recursiva
Power:
1. Debidarle el caso para cuando pwr es 0, todo numero elevado a la 0 es 1.
Factorial,
Recibe un solo argumento, peor el comportamiento es igual
'''
def power(num, pwr):
if pwr == 0:
return 1
else:
return num * power(num, pw... |
#!/usr/bin/env python
# coding: utf-8
# # 01-Quantopian Research Basics
# **Please remember that this notebook will only work on Quantopian! Make an account and upload this notebook file.
# These commands and functions won't work except on the Quantopian trading platform!**
# Note a lot of the written markdown text in ... |
#!/usr/bin/env python
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# Name - Thilakarathna W M D U
# Email - dtdinidu7@gmail.com
# Date - 08/04/2020
tm = int(input()) # number of test cases
for t in range(1, tm+1):
lis = [int(i) for i in list(input())] # taking the input as list
strg = '('*lis[0] + str(lis[0]) # final string to be displayed
prev = lis[0] ... |
# -*- coding: utf-8 -*-
import Config
class Agent:
def __init__(self, name, number, autonomy_time, speed, minimum_image_size, position, environment_matrix):
self.__status = 'start'
self.__model = None
if not Config.GLOBAL_MODEL:
import numpy as np
input_matrix = np... |
#!/usr/bin/env python
"""A tool which pretends to be bash, and reports entered
commands to a logger instead of executing them"""
import cookielib
import datetime
import os
import signal
import urllib
import urllib2
logaddr = "http://127.0.0.1:8011"
def prompt_and_post():
cookies = cookielib.CookieJar()
ope... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# author: adiyoss
import json
import logging
from pathlib import Path
import os
import time
import torch
import torch.nn.f... |
#!/usr/bin/env python
##
# @file
# This file is part of SeisSol.
#
# @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)
#
# @section LICENSE
# Copyright (c) 2015, SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... |
"""Metrics-based utilities for computing important information.
"""
from sklearn.metrics import (accuracy_score, f1_score, precision_score,
recall_score)
def compute_metrics(preds):
"""Computes a set of metrics (accuracy, f1-score, precision and recall).
Args:
preds (tra... |
'''
A&B.png
.intersection()
The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.
The set is immutable to the .intersection() operation (or & ... |
import os
import logging
from flask import Flask
from flask_security import Security
from flask_security.utils import encrypt_password, verify_password
from flask_jwt import JWT, jwt_required, current_identity
from flask_sqlalchemy import SQLAlchemy
from . import db, ma
from models import *
from config import *
logg... |
"""
Notifications are primarily used when defining Launch Plans (also can be used when launching executions) and will trigger
the Flyte platform to send emails when a workflow run reaches certain stages (fails or succeeds, etc.).
.. note::
Notifications require some setup and configuration on the Flyte platform s... |
import getopt
import sys
from webnlg_gcnonmt_input import input_files, SEEN_CATEGORIES
def main(argv):
usage = 'usage:\npython3 webnlg_gcnonmt_relexicalise.py -i <data-directory> -f <prediction-file> [-p PARTITION] [-c CATEGORIES] [-g GPUID]' \
'\ndata-directory is the directory where you unzipped th... |
# 2018-9-10
import numpy as np
import os
import cv2
from func import *
from detector import *
import math
def main(test_image, data_path, data_path2, simple_size, label):
svm, extractor, exist = car_detector(data_path, data_path2, simple_size, label)
# if exist:
# svms = cv2.ml.SVM_create()
# svms.load(svm)
# s... |
from __future__ import division
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.externals.six.moves import xrange as range
from ..features import as_features
class MeanMapKernel(BaseEstimator, TransformerMixin):
'''
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from course.course_model import Subject, Course
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
fro... |
from django.contrib import admin
from .models import Experiment, Site, Metadata, BinnedData
admin.site.register(Experiment)
admin.site.register(Site)
admin.site.register(BinnedData)
admin.site.register(Metadata)
|
"""
find combinations of flights
https://gist.github.com/martin-kokos/7fb98650c66bd8d93767da6627affffa
"""
from __future__ import print_function
import argparse
import sys
from flight_paths import FlightPaths
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Find flights paths from flights ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import click
@click.command()
@click.option('--hash-type', default=False, type=click.Choice(['md5', 'sha256']))
def digest(hash_type):
click.secho("%s hash" % hash_type, fg='red')
if __name__ == '__main__':
digest()
## References
# http://click.pocoo.org/5/optio... |
import torch
from torch import nn, Tensor
from torch.nn import functional as F, BCEWithLogitsLoss
from torch.nn.modules.loss import _Loss
class DiceLoss(nn.Module):
def __init__(self):
super(DiceLoss, self).__init__()
def forward(self, output, target):
prediction = F.sigmoid(output)
i... |
from __future__ import division
import numpy as np
__all__ = ['input_m1', 'mixture', 'santner', 'santner_mixture']
def input_m1(P, samples, m=4, var=4, corr1 = 3.5, corr2 = 3.5):
"""
Input model one: generate samples independently and identically distributed as multivariate normal with mean and
covarianc... |
from BaseControlPlots import BaseControlPlots
# Requirements:
# event.muons
# event.electrons
class LeptonControlPlots(BaseControlPlots):
"""A class to create control plots for leptons"""
def __init__(self, dir=None, dataset=None, mode="plots"):
# create output file if needed. If no file is given, it m... |
import os, sys
import random
class Colors(object):
RED = 31
GREEN = 32
YELLOW = 93#33
BLUE = 34
PINK = 35
LIGHT_BLUE = 36
WHITE = 37
GRAY = 90
CYAN = 96
DISABLED = False
@staticmethod
def colorize(message, color, bold=False):
if Colors.DISABLED:
return message
else:
if isinstance(color, list):
... |
# Copyright 2019-present Kensho Technologies, LLC.
"""Create Cypher query objects from partially-lowered IR blocks, for easier manipulation."""
from collections import namedtuple
from .blocks import (
Backtrack,
CoerceType,
ConstructResult,
EndOptional,
Filter,
Fold,
GlobalOperationsStart,... |
import os
import json
from pprint import pprint as pp
from pygnmi.client import gNMIclient
ARISTA_HOST = os.getenv("ARISTA_HOST", "198.51.100.105")
ARISTA_PORT = os.getenv("ARISTA_PORT", "6030")
ARISTA_USERNAME = os.getenv("ARISTA_USERNAME", "arista")
ARISTA_PASSWORD = os.getenv("ARISTA_PASSWORD", "arista")
host = (... |
import urllib2
# Base class for image finders.
class ImageFinder(object):
# This method must be implemented in the derived class.
def find(self, search_terms):
raise NotImplementedError("ImageFinder::find not implemented!")
# Download the file at the specified URL and save it.
def download(sel... |
"""
utilites to read the linemod dataset to numpy types
@author Pavel Rojtberg <https://github.com/paroj>
"""
import numpy as np
def _parse_ply_header(f):
assert f.readline().strip() == "ply"
vtx_count = 0
idx_count = 0
for l in f:
if l.strip() == "end_header":
break
elif... |
import numpy as np
import elem
def test_helper(A, M, N, R, sketch, measures, MPI, num_repeats=5, direction="columnwise"):
"""
Test if the singular values of the original (M x N) and sketched matrix
(R x N) are fulfilling some measurement criteria. The test is repeated
num_repeats times.
"""
res... |
"""The main module for the v1 notebook format."""
# -----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this softwa... |
from .codedeploy import *
from .elasticbeanstalk import *
|
# Script for generating test files
curr_line = []
for i in range(2000):
curr_line.append(str(i))
curr_line.append(" The quick brown fox jumped over the lazy dog.")
curr_line.append("\n")
test_string = ''.join(curr_line)
print test_string
|
from pybricks.pupdevices import Motor
from pybricks.tools import wait
from pybricks.parameters import Port, Direction
from pybricks.robotics import DriveBase
from pybricks import version
print(version)
# Initialize default "Driving Base" with medium motors and wheels.
left_motor = Motor(Port.C, Direction.COUNTERCLOCK... |
"""Test the log date widget."""
import os
import unittest
from unittest.mock import patch
import healthhelper.interface as interface
from PyQt5.QtTest import QTest
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
# Directory containing this file
this_dir = os.path.abspath(os.path.dirname(__file__)... |
# Task: open web search results for keyword in .xlsx, .txt, .csv format in new tabs
# Step 0: imports
import pandas as pd
import webbrowser
import time
# Step 1: get list of keywords
keywords = pd.read_csv(r'filepath/file.txt')
print(keywords.shape)
print(keywords.head)
# Step 2: duckduckgo search operators - https:... |
"""Read and write lumps in Source BSP files.
"""
import contextlib
from io import BytesIO
from enum import Enum, Flag
import itertools
from zipfile import ZipFile
from srctools import AtomicWriter, Vec, Angle, conv_int
from srctools.vmf import VMF, Entity, Output
from srctools.tokenizer import escape_text
from srct... |
from django.core.exceptions import ValidationError
from rest_framework import exceptions, serializers
from lego.apps.email.models import EmailAddress, EmailList
from lego.apps.users.fields import AbakusGroupListField, PublicUserField, PublicUserListField
from lego.apps.users.models import User
from .fields import Ema... |
## FormEncode, a Form processor
## Copyright (C) 2003, Ian Bicking <ianb@colorstudy.com>
"""
Wrapper class for use with cgi.FieldStorage types for file uploads
"""
import cgi
def convert_fieldstorage(fs):
if fs.filename:
return fs
else:
return None
|
import os
import typing
import uuid
from d3m import container, utils as d3m_utils
from d3m.base import utils as base_utils
from d3m.metadata import base as metadata_base, hyperparams
from d3m.primitive_interfaces import base, transformer
__all__ = ('DatasetToDataFramePrimitive',)
Inputs = container.Dataset
Outputs =... |
#!/usr/bin/env 2.
# -*- config: utf-8 -*-
# В строке могут присутствовать скобки как круглые, так и квадратные скобки. Каждой
# открывающей скобке соответствует закрывающая того же типа (круглой – круглая,
# квадратной- квадратная). Напишите рекурсивную функцию, проверяющую правильность
# расстановки скобок в этом слу... |
# AI for Business - Minimize cost with Deep Q-Learning
# Building the Environment
# Importing the libraries
import numpy as np
# BUILDING THE ENVIRONMENT IN A CLASS
class Environment(object):
# INTRODUCING AND INITIALIZING ALL THE PARAMETERS AND VARIABLES OF THE ENVIRONMENT
def __init__(self, optim... |
from urlreader import URLReader
from urlreader.utils import callback
reader = URLReader(wait_until_done=True)
reader.fetch("https://www.apple.com/", callback)
|
"""
🎅
--- Day 6: Universal Orbit Map ---
You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often
involves transferring between orbits, the orbit maps here are useful for finding efficient routes
between, for example, you and Santa. You download a map of the local orbits (your pu... |
#
# Copyright (c) 2015 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
from django.core.management.base import BaseCommand
from todo.models import ToDoListItem
from django.utils import timezone
class Command(BaseCommand):
"""This command triggers exchane update process"""
def handle(self, *args, **options):
"""Handle command"""
ToDoListItem.objects.filter(dead... |
import visdom
from scipy.misc import imresize
import numpy as np
from torchvision.utils import make_grid
class VisFunc(object):
def __init__(self, config=None, vis=None, enval='hproto',port=8097):
self.config = config
self.vis = visdom.Visdom(env=enval, port=port)
self.win = None
s... |
"""kowikitext dataset."""
from typing import List
import tensorflow_datasets as tfds
_DESCRIPTION = """
Wikitext format Korean corpus
한국어 위키의 덤프 데이터를 바탕을 제작한 wikitext 형식의 텍스트 파일입니다.
"""
_CITATION = """
@misc{kowikitext20
title={Ko-wikitext},
author={Hyunjoong Kim},
howpublished={https://github.com/lovi... |
import hashlib
from os import path
from django.db.models import Model
# This method allows for file uploads to live in segmented folders,
# instead of placing all uploads in a single folder.
# noinspection PyUnusedLocal
def segmented_upload_to(instance: Model, file_name: str) -> str:
"""
:param instance:
... |
from Calculator.Calculator import Calculator
from PopulationSampling.CochransFormula import cochran
class PopSampling(Calculator):
data = []
def __init__(self):
super().__init__()
def cochran(self, z, p, q, e):
self.result = cochran(z, p, q, e)
return self.result |
"""
ArchTrexZ0Plan.py - Services for importing, exporting, and formatting data.
Using this thesarus a producer or consumer can locate a common field to process.
It can, with a few appropriate changes, connect to anyEnv Uci driven.
It knows about ArchEdenZ0Plan Uci so covers much of the processing.
Copyright (c) 2020,... |
import numpy as np
from datahandler.data_sampling import create_train_and_valid
class BaseClassifier(object):
"""
BaseClassifier from which all classifier objects inherit from
"""
def __init__(self, classifier_name="Classifier", data=None, labels=None, ids=None):
"""Initializaes BaseClassifier
... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
from pycorenlp import StanfordCoreNLP
from .Token import Token
class Tokenizer():
def __init__(self):
self.nlp = StanfordCoreNLP('http://localhost:9000')
# if the token is $100.0 or some number
# then replace it with NUMBER
def tokenGetWord(self, token):
if token['ner'] in set(['MON... |
"""Internal functions"""
import json
import logging
from time import time
from slack_sdk.socket_mode.client import BaseSocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_bolt.app import App
from slack_bolt.request impor... |
'''
Created on Aug 8, 2018
@author: kjnether
A python wrapper around the kirk rest api.
'''
# pylint: disable=invalid-name
# pylint: disable=logging-format-interpolation
from __future__ import unicode_literals
import logging
import os.path
import urllib
import requests
from . import constants
... |
"""
Functions and classes for parsing and representing complete programs.
"""
import re
import os
import sys
import copy
import logging
from .UCInstructions import UCInstructionCollection
from .UCState import UCProgramVariable
from .UCState import UCProgramVariableCollection
from .UCState import UCVarStrings
from .... |
def execute_decorator(func):
def wrapper(*args, **kwars):
print('Ingresa tu nombre ')
func(*args, **kwars)
print('Gracias por visitarnos')
return wrapper
@execute_decorator
def ingreso_nombre():
nombre = input(' ')
print (f'Hola {nombre} bienvenido')
ingreso_nombre() |
# -*- coding: utf-8 -*-
from scipy import stats
from numpy import *
'''
Referencia para implementacao do calculo de tamanho de efeito
https://www.researchgate.net/profile/Helena_Espirito_Santo/publication/273143169_Calcular_e_apresentar_tamanhos_do_efeito_em_trabalhos_cientificos_1_As_limitacoes_do_p_005_na_analise_de... |
"""Initial 8
Revision ID: de84556d9e2a
Revises: a8810e4a9ace
Create Date: 2021-11-14 02:57:59.511295
"""
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision = 'de84556d9e2a'
down_revision = 'a8810e4a9ace'
branch_labels = None
depends_on = None
def upgra... |
import requests
from bs4 import BeautifulSoup
from dateutil.parser import parse
from collections import Counter
import datetime
url = 'https://netzpolitik.org/author/chris-koever/page/'
filename = 'chris.csv'
with open(filename, 'w') as f:
i = 1
allText = ""
while i < 9:
r = requests.get(url + st... |
# -*- coding: utf-8 -*-
import pyvistaqt as pv
def plot_mesh(self, indices=[]):
"""Plot the mesh using pyvista plotter.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
Returns
-------
"""
mesh = self.... |
from utils.logger import setup_custom_logger
import numpy as np
import itertools
import h5py
import os
log = setup_custom_logger(os.path.basename(os.path.basename(__file__)))
class BufferedWriter(object):
def __init__(self, output_filename, chunk_size=256, required_keys=()):
self._output_filename = outp... |
from sqlalchemy.exc import IntegrityError
import pytest
from app.dao.emails_dao import dao_create_email_to_member
from app.dao.members_dao import (
dao_update_member, dao_get_member_by_id, dao_get_members_not_sent_to
)
from app.models import EmailToMember, Member
from tests.db import create_member
class WhenUsi... |
import ugfx
def main():
from netconfig import manager
global app
ugfx.init()
app = manager.Status()
app.main()
|
from __future__ import print_function
import os
import torch
import torch.backends.cudnn as cudnn
# import numpy as np
from utils.timer import Timer
import glob
import PIL.Image as Image
import random
from interface import compare_vector, Detect, Reid
import cv2
# import multiprocessing
from multiprocessing import Proc... |
# QUESTION
"""
First Reverse
HIDE QUESTION
Have the function FirstReverse(str) take the str parameter being passed and
return the string in reversed order. For example: if the input string is
"Hello World and Coders" then your program should return the string sredoC
dna dlroW olleH.
Use the Parameter Testing feature ... |
# Generated by Django 3.2.4 on 2021-06-22 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('my_weather_api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='weatherforecastday',
name='avera... |
import pandas as pd
def atr(df):
ar = []
for i in range(0,len(df)):
if i==0:
ar.append(df['high'][i]-df['low'][i])
else:
hl=(df['high'][i]-df['low'][i])
hc=abs(df['high'][i]-df['close'][i-1])
lc=abs(df['low'][i]-df['close'][i-1])
ar.ap... |
# DO NOT USE THIS TO SPAM EXAMINATIONS.IE WITH REQUESTS; USE RESPONSIBLY.
from PyPDF2 import PdfFileMerger, PdfFileReader
from pathlib import Path
import requests
### MODIFY THESE VALUES ###
lang = "EV"
subjects = {"Physics": 21, "Chemistry": 22}
max_year = 2010
min_year = 2007 # 2007 is the lowest possible
### MODIF... |
import hashlib
import json
import time
from urllib.parse import urlparse
from uuid import uuid4
import requests
from flask import Flask,jsonify,request
from typing import Any,Dict,List,Optional #数据结构
class NewBlockChain:
def __init__(self):
self.current_trans = [] #当前的交易
self.chain = [] #区块链管... |
import argparse
import glob
import os
import sys
import numpy as np
import scipy.ndimage.measurements as measurements
import scipy.ndimage.morphology as morphology
import torch
import torch.nn as nn
import torch.optim
from torch.utils.data import DataLoader
from util.util import enumerateWithEstimate
from p2ch13.ds... |
#!/usr/bin/env python3
from captum.robust._core.fgsm import FGSM # noqa
from captum.robust._core.metrics.attack_comparator import AttackComparator # noqa
from captum.robust._core.metrics.min_param_perturbation import ( # noqa
MinParamPerturbation,
)
from captum.robust._core.perturbation import Perturbation # n... |
"""Environment for training the acceleration behavior of vehicles in a loop."""
import numpy as np
from flow.core import rewards
from flow.envs.loop.loop_accel import AccelEnv
from flow.multiagent_envs.multiagent_env import MultiEnv
class MultiAgentAccelEnv(AccelEnv, MultiEnv):
"""Adversarial multi-agent env.
... |
# Copyright 2018 TVB-HPC contributors
#
# 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 applicab... |
import dataclasses
import re
import typing as tp
import jax
import jax.numpy as jnp
import numpy as np
import typing_extensions as tpe
A = tp.TypeVar("A")
B = tp.TypeVar("B")
key = jax.random.PRNGKey
_pymap = map
_pyfilter = filter
OpaquePredicate = tp.Callable[["Opaque", tp.Any], bool]
@tpe.runtime_checkable
cla... |
# SPDX-License-Identifier: MIT
"""App-specific URL configuration."""
# Django imports
from django.urls import path # noqa: F401
app_name = "t3mpl4t3"
"""Define an application namespace for reversing URLs.
See :djangodoc:`URL namespaces <topics/http/urls/#url-namespaces>`.
"""
urlpatterns = []
|
from __future__ import print_function
import json
import sys
from shared.common import parse_arguments
from shared.public import get_public_nodes
__description__ = "Find publicly exposed services and their ports"
def public(accounts, config):
all_accounts = []
for account in accounts:
public_nodes... |
"""
Author: Axel Robbe
Version: 0.1
This script checks given ip or domain names against online blacklists.
Minimal required Python version 3.3
"""
import argparse # Doesn't seem to be used?
import ipaddress
import json
import requests
class userInput:
def __init__(self, userInput):
self.lo... |
# -*- coding: utf-8 -*-
# make_data.py
# General Imports
import pandas as pd
from .pandas_operators import drop_df_columns, insert_df_column
def test_make_data():
print("In make_data")
pass
# stubs for cleaning and feature engineering
def clean_data(df):
""" Stub to clean data:
:param: df : datafram... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Author: Simon.Zhao@microsoft.com
#
# This demo is based on the Azure Cognitive Services Face API Quick Start
from mlhub.pkg import mlask, mlcat, get_private
mlcat("Face Services","""
Welcome to a demo of the pre-built mode... |
import zmq
context = zmq.Context()
client = context.socket(zmq.REQ)
client.connect("tcp://localhost:5555")
nameSong = "olvidala"
client.send_string(nameSong)
hashSong = client.recv_string()
print(hashSong)
|
#!/usr/bin/python
#
# 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 restriction, including without limitat... |
from settings import *
MIDDLEWARE_CLASSES = (
("django.middleware.cache.UpdateCacheMiddleware",)
+ MIDDLEWARE_CLASSES
+ (
"django_mobile.cache.middleware.CacheFlavourMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
)
)
|
#!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
"""
`Unit tests for cargo.statements.Raw`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
2016 Jared Lunde © The MIT License (MIT)
http://github.com/jaredlunde
"""
import pickle
from cargo import *
from cargo.expressions import _e... |
from typing import NoReturn
from ...base import BaseEstimator
import numpy as np
class GaussianNaiveBayes(BaseEstimator):
"""
Gaussian Naive-Bayes classifier
"""
def __init__(self):
"""
Instantiate a Gaussian Naive Bayes classifier
Attributes
----------
self.c... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import sys, os
import os.path as osp
import os
from args import get_parser
import numpy as np
from PIL import Image
from misc.config_kittimots import cfg
from utils.utils import make_dir
import json
import time
from torchvision import transforms
def get_dict(seq_name):
dict_root_dir = cfg.PATH.ANNOTATIONS
pa... |
"""
CutPlan contains code to process LaserOperations into CutCode objects which are spooled.
CutPlan handles the various complicated algorithms to optimising the sequence of CutObjects to:
* Sort burns so that travel time is minimised
* Do burns with multiple passes all at the same time (Merge Passes)
* Sort bur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.