text stringlengths 2 999k |
|---|
import tensorflow as tf
"""convolution2d层与tf.nn.conv2d逻辑相同,但还包括权值初始化,偏置初始化,
可训练的变量输出,偏置相加,以及添加激活函数的功能"""
image_input = tf.constant([
[
[[0., 0., 0.], [255., 255., 255.], [254., 0., 0.]],
[[0., 191., 0.], [3., 108., 233.], [0., 191., 0.]],
[[254., 0., 0.], [255., 255., 255.], [0., 0., 0.]]
... |
from crontab import CronTab
from sys import argv
argument = None
time = None
command = None
comment = None
user = None
tab_file = None
delete_all = False
def fail(prompt):
print(prompt)
exit(1)
def get_args():
global argument
global time
global command
global comment
global user
g... |
import graphene
from ..core.fields import FilterInputConnectionField
from ..decorators import permission_required
from .filters import PluginFilterInput
from .mutations import PluginUpdate
from .resolvers import resolve_plugin, resolve_plugins
from .sorters import PluginSortingInput
from .types import Plugin
class E... |
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchvision import datasets, transforms
import numpy as np
from collections import OrderedDict
import os.path
import matplotlib.pyplot as plt
torch.manual_seed(7)
class Layer(nn.Module):
def __init__(self):
super().__init__()... |
import os
from logging.config import dictConfig
import flask_talisman
from flask import Flask
from flask_healthz import healthz
from flask_mail import Mail
from flask_wtf.csrf import CSRFProtect
from whitenoise import WhiteNoise
from noggin.controller import blueprint
from noggin.l10n import babel
from noggin.middlew... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
from pathlib import Path
import pytest
from linkify_it import LinkifyIt
from .utils import read_fixture_file
FIXTURE_PATH = Path(__file__).parent / "fixtures"
def dummy(_):
pass
@pytest.mark.parametrize(
"number,line,expected",
read_fixture_file(FIXTURE_PATH.joinpath("links.txt")),
)
def test_links(... |
import argparse
from greent.rosetta import Rosetta
from greent.annotators.annotator_factory import annotator_class_list
from builder.question import LabeledID
from builder.buildmain import run
from multiprocessing import Pool
from functools import partial
def grab_all(node_type, rosetta):
"""
Grabs... |
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config,Csv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
#BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start deve... |
__author__ = 'Bohdan Mushkevych'
from datetime import datetime, timedelta
from synergy.system.repeat_timer import RepeatTimer
TIME_OF_DAY_FORMAT = "%H:%M"
EVERY_DAY = '*' # marks every day as suitable to trigger the event
TRIGGER_INTERVAL = 30 # half a minute
class EventTime(object):
def __init__(self,... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#program file and text file both are at same place means in one Folder
import string
text = open("a1.txt", "r") #Open the file in read mode
a = dict() #Create dictionary
for line in text: #loop through each line of the file
line = line.strip() #Remove the leading ... |
import re
from typing import Tuple, List, Iterator, Dict, Any
import numpy as np
from PIL import Image
from numpy.core.fromnumeric import resize
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.applications as tensorflow_models
from tensorflow.keras import layers
import thingsvision.cor... |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import re
import matplotlib.pyplot as plt
import numpy as np
import subprocess
import sys
__author__ = "David Thierry" #: @2018
def main():
permuted = True
vanilla_name = "vanilla" #: change accordingly
vani... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-26
Last_modify: 2016-02-26
******************************************
'''
'''
Given an absolute path for a file (Unix-st... |
import unittest
from unittest.mock import Mock, patch
from skygear.transmitter.encoding import deserialize_record
from ..conversation import (Conversation, SkygearChatException,
handle_conversation_before_save)
class TestHandleConversationBeforeSave(unittest.TestCase):
def setUp(sel... |
ASYNCIO = "asyncio"
MULTITHREADING = "multithreading"
|
#!/usr/bin/env python
"Setuptools params"
from setuptools import setup, find_packages
from os.path import join
# Get version number from source tree
import sys
sys.path.append( '.' )
from mininet.net import VERSION
scripts = [ join( 'bin', filename ) for filename in [ 'mn' ] ]
modname = distname = 'mininet'
setup... |
import re
import sys
import PySide2
from PySide2 import QtWidgets
from PySide2.QtCore import Slot
from UiMainWindow import Ui_MainWindow
def string_index_replacer(previous: str, incoming: str, index: int) -> str:
result = previous[:index]
result = result + incoming + previous[index + 1:]
return result
... |
import scrapy
import re
import json
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
DAY_MAPPING = {
1: 'Mo', 2: 'Tu', 3: 'We', 4: 'Th', 5: 'Fr', 6: 'Sa', 7: 'Su',
'Mo': 1, 'Tu': 2, 'We': 3, 'Th': 4, 'Fr': 5, 'Sa': 6, 'Su': 7
}
class AlnaturaSpider(scrapy.Spider):
n... |
def if_gpu(if_true, if_false = []):
"""Shorthand for select()'ing on whether we're building with gpu enabled
Returns a select statement which evaluates to if_true if we're building
with use_gpu enabled. Otherwise, the select statement evaluates to
if_false.
"""
return select({
"//tools/p... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
# Copyright 2020 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
# Copyright (c) 2021, Ethan Henderson
# 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 conditions and... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: toit/api/sdk.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.pr... |
# this script is provided as a basic guide
# most parts can be run by uncommenting them
# InMoov now can be started in modular pieces
# limits for the eyes x axis Min 93 Max 110
# Limits for Jaw Min 70 Max 125
leftPort = "COM15"
rightPort = "COM3"
i01 = Runtime.createAndStart("i01", "InMoov")
# s... |
import sys
from sentry_sdk.hub import Hub, _should_send_default_pii
from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
from sentry_sdk._compat import PY2, reraise
from sentry_sdk.integrations._wsgi_common import _filter_headers
if False:
from typing import Callable
from typing impo... |
"""
Settings for django-raster tests.
"""
from __future__ import unicode_literals
import os
SECRET_KEY = 'testkey'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles... |
import random
from eth2spec.utils.ssz.ssz_impl import hash_tree_root
from eth2spec.test.context import MINIMAL, spec_state_test, with_all_phases, with_presets
from eth2spec.test.helpers.attestations import (
next_epoch_with_attestations,
next_slots_with_attestations,
state_transition_with_full_block,
s... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Supernova remnant (SNR) source models"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from astropy.units import Quantity
import astropy.constants as const
from astropy.utils import lazyproperty
fr... |
import sys
import logging
from logging import getLogger
from flask import Flask, request, flash, make_response, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, current_user
from flask_socketio import SocketIO
from sqlalchemy import event
from sqlalchemy.engine import Engine
from... |
from collections.abc import MutableSequence
from typing import Union, Iterable, Tuple, Sequence
import numpy as np
from ...helper import typename
from ...logging import default_logger
try:
# when protobuf using Cpp backend
from google.protobuf.pyext._message import (
RepeatedCompositeContainer as Re... |
'''
Projected Split related tests
'''
__author__ = 'Elisha Yadgaran'
import unittest
import pandas as pd
import numpy as np
from unittest.mock import MagicMock, patch, PropertyMock
from abc import ABCMeta, abstractmethod
from simpleml.datasets.base_dataset import Dataset
from simpleml.datasets.dataset_splits impor... |
#
# 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 us... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pu... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "Integration", sigma = 0.0, exog_count = 100, ar_order = 12); |
# import argparse
import collections
from functools import partial
import pathlib
import sys
import time
import numpy as np
from scipy.interpolate import interpn
import xarray as xr
from Utilities import Utilities # optional, see printProgressBar below
π = np.pi
db_path = './Data/Zhang_rho_db.mat'
#Groups in db.mat... |
# Copyright 2020 The TensorFlow Authors. 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 applica... |
import csv
import codecs
import os
from libs.catch_execption import catch_exceptions_util
from libs.db_context import DBContext
from libs.web_logs import ins_log
from models.prowler_data import ProwlerData
@catch_exceptions_util
def prowler_sync_cmdb():
"""亚马逊CIS合规性检查数据入库"""
# name = list(os.walk("/var/www/c... |
"""
ESP32 Micropython RTC memory.
Author WG 2019 The MIT License (MIT)
Version 20200902
Usage:
import mem
obj = mem.MEM()
"""
class MEM:
def __init__(self):
pass
# float32 (s+e+m)(1+8+23bits) -> float16 (1+5+10bits)(0.004..16773119)
def f2b(self, x):
from struct import pack, unpa... |
import argparse
import json
import csv
import sys
import time
import numpy
from pymongo import MongoClient
import archon.orders as orders
import archon.broker as broker
import archon.exchange.exchanges as exc
abroker = broker.Broker()
abroker.set_active_exchanges([exc.BITMEX])
client = abroker.afacade.get_client(exc... |
# -*- coding: utf-8 -*-
import scrapy
from conf_speeches.items import ConfSpeechesItem
from bs4 import BeautifulSoup
class ConfSpeechesSpider(scrapy.Spider):
name = "conf"
allowed_domains = ["www.britishpoliticalspeech.org"]
start_urls = (
'http://www.britishpoliticalspeech.org/speech-archive.htm?q... |
"""
created on 14/8/2014
@author: victor
"""
class ExactlyThisLengthFilter(object):
def __init__(self):
pass
@classmethod
def filter(cls, alignments, seq_len):
return [alignment_info for alignment_info in alignments if len(alignment_info["query_seq"]) == seq_len]
class NoGapsF... |
# The MIT License (MIT)
#
# Copyright (c) 2016 Charles Armstrap <charles@armstrap.org>
# If you like this library, consider donating to: https://bit.ly/armstrap-opensource-dev
# Anything helps.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... |
from azureml.core import Workspace
from azureml.exceptions import ComputeTargetException
from azureml.core.compute import ComputeTarget, DatabricksCompute, AmlCompute
def get_compute_aml(
workspace: Workspace,
compute_name: str,
vm_size: str
):
try:
if compute_name in workspace.compute_targets... |
# -*- coding: utf-8 -*-
from model.contact import Contact
import pytest
import random
import string
from data.contacts import testdata
# @pytest.mark.parametrize("contact", testdata, ids=[repr(x) for x in testdata])
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
old_contacts =... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('cert.views',
url(r'^(?P<slug>[\w_-]+)/$',
'certificate',
name='cert',
),
)
|
# Auto generated by 'inv collect-airflow'
from airfly._vendor.airflow.models.baseoperator import BaseOperator
class ComputeEngineBaseOperator(BaseOperator):
zone: "str"
resource_id: "str"
project_id: "typing.Union[str, NoneType]"
gcp_conn_id: "str"
api_version: "str"
impersonation_chain: "typi... |
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from simpleapi import Route
from handlers import MyAPI
def main():
application = webapp.WSGIApplication(
[('/api/', Route(MyAPI, framework='appengine'))]
)
util.run_wsgi_app(application)
i... |
def get_users(passwd: str) -> dict:
"""Split password output by newline,
extract user and name (1st and 5th columns),
strip trailing commas from name,
replace multiple commas in name with a single space
return dict of keys = user, values = name.
"""
output = {}
for line in passwd... |
from __future__ import print_function
import argparse
import sys
import pkg_resources
import six
from .download import download
distribution = pkg_resources.get_distribution('gdown')
class _ShowVersionAction(argparse.Action):
def __init__(self, *args, **kwargs):
kwargs['nargs'] = 0
self.versi... |
class User:
'''
Class that generates new instances of users.
'''
users_list = []
def __init__(self, username, password):
'''
__init__ method helps define our objects properties
Args:
username: login's username for a new user
password: login:s ... |
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 requi... |
num = int(input("Digite um numero de 0 a 9999: "))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print("Analisando o número {}".format(num))
print('Unidade: {}'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}'.format(c))
print('Milhar: {}'. format(m)) |
# -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import CashbillService, PopbillException
cashbillService = CashbillService(testValue.LinkID, te... |
import lattice
import pygame
pygame.init()
fpsClock = pygame.time.Clock()
screen_size = (640,640)
window = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Ising Model')
screen = pygame.display.get_surface()
|
import logging
from os.path import splitext
from discord import Embed, Message, NotFound
from discord.ext.commands import Cog
from bot.bot import Bot
from bot.constants import AntiMalware as AntiMalwareConfig, Channels, STAFF_ROLES, URLs
log = logging.getLogger(__name__)
class AntiMalware(Cog):
"""Delete messa... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from numpy import array, ndarray
def GetBJD(iJD=0, iRA=0, iDEC=0, iLAT=0, iLON=0, iALT=0, FF=False):
"""
Gets BJD from returned r... |
import argparse
import torch
import warnings
from argformat import StructuredFormatter
from .preprocessor import Preprocessor
from .tiresias import Tiresias
if __name__ == "__main__":
########################################################################
# Parse arguments ... |
# This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
#
# 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 ... |
#! /usr/bin/env python3
import os
import argparse
import json
import decimal
import sys
import logging
import unicodedata
import time
import dateutil.parser
import calendar
import configparser
from threading import Thread
import binascii
from fractions import Fraction
import requests
import appdirs
from prettytable im... |
from django.db import models, migrations
import mayan.apps.common.validators
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Transformation',
fields=[
... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""gitea-ldap-team-sync.py: Sync Gitea team members with LDAP groups"""
import json
import ldap
import requests
from requests.exceptions import HTTPError
import sys
__author__ = "Lukas Brocke"
__license__ = "MIT"
class GiteaAPI:
"""Gitea API wrapper"""
def __i... |
'''
Задача «Длина отрезка»
Условие
Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). Считайте четыре действительных числа и выведите результат работы этой функции.
Если вы не знаете, как решить эту задачу, то вы, возможно,... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import http_helper as http
'''
'''
_kPaths = {
# get
'getBlock': '/api/blocks/get',
# get
'getFullBlock': '/api/blocks/full',
# get
'getBlocks': '/api/blocks',
# get
'getHeight': '/api/blocks/getHeight',
# get
'getFee': '/api/blo... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 14:45:26 2022
@author: sam-b
"""
"""Imports the following modules to be used in the code - matplotlib.pyplot,
time. Import the agentframework module created by the user"""
import matplotlib.pyplot
import time
import agentframework
"""Start the timer for the code"""... |
from setuptools import setup, find_packages
setup(name='cmsplugin-instagrabber',
version='0.1.1',
description='Django CMS plugin providing instagram social wall',
url='https://github.com/atiberghien/cmsplugin-instagrabber',
author='Alban Tiberghien',
author_email='alban.tiberghien@gmail.c... |
#!/usr/bin/env python
# coding=utf-8
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2017-11-24 21:10:35 +0100 (Fri, 24 Nov 2017)
#
# https://github.com/harisekhon/nagios-plugins
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on Linke... |
"""
Module providing read and write functionality towards hex files with data intended for target device memories
"""
import copy
import os
from array import array
from collections import namedtuple
from intelhex import IntelHex
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path # pyth... |
"""
Support for SCSGate components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scsgate/
"""
import logging
from threading import Lock
import voluptuous as vol
from homeassistant.const import (CONF_DEVICE, CONF_NAME)
from homeassistant.core import ... |
# -*- coding: utf-8 -*-
from __future__ import division
import itertools
import os
import threading
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
from subprocess import CalledProcessError
from poetry.core.packages.file_dependency import FileDependency
from poetry.core.packages... |
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.setProperty('rate', 175)
def speak():
engine.say("Hello, My name is David")
engine.runAndWait()
if engine._inLoop:
engine.endLoop()
speak()
|
"""
Math vector 2d and 3d.
.. module:: vector
:platform: Unix, Windows
:synopis: math vector 2d and 3d.
.. moduleauthor:: Thomas Lehmann <thomas.lehmann.private@googlemail.com>
=======
License
=======
Copyright (c) 2017 Thomas Lehmann
Permission is hereby granted, free of charge, to any pe... |
# Copyright 2017 Bo Shao. 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 agre... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the pruning code.
WARNING:
This test uses 4GB of disk space.
This test takes 30 mins or more (up ... |
# -*- coding: utf-8 -*-
import numpy as np
from numpy.linalg import norm
from scipy.spatial.ckdtree import cKDTree
def streamlines_to_segments(streamlines):
"""Split streamlines into its segments.
Parameters
----------
streamlines : list of numpy.ndarray
List of streamlines.
Returns
... |
''' A reproduction of Mike Bostock's `Les Misérables Co-occurrence`_ chart.
This example example demonostrates a basic hover tooltip.
.. bokeh-example-metadata::
:sampledata: les_mis
:apis: bokeh.plotting.Figure.rect
:refs: :ref:`userguide_tools` > :ref:`userguide_tools_hover_tool`
:keywords: hover, re... |
import os
import json
import argparse
import math
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.multiprocessing as mp
import torch.distributed as dist
from apex.parallel import Distribu... |
class ArithmeticError:
''
class AssertionError:
''
class AttributeError:
''
class BaseException:
''
class EOFError:
''
Ellipsis = None
class Exception:
''
class GeneratorExit:
''
class ImportError:
''
class IndentationError:
''
class IndexError:
''
class KeyError:
'... |
import sys
def DP(n):
global count
if(n==0):
count +=1
if(n >= 1):
DP(n-1)
if(n >= 2):
DP(n-2)
if(n>=3):
DP(n-3)
t = int(sys.stdin.readline().rstrip("\n"))
for _ in range(t):
n = int(sys.stdin.readline().rstrip("\n"))
count = 0
DP(n)
print(count)
... |
from __future__ import division, print_function
import os
import sys
from os.path import join
from Cython.Build import cythonize
import Cython.Compiler.Options
Cython.Compiler.Options.annotate = True
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... |
import numpy as np
import math
import random
import gudhi
from sklearn.neighbors import KDTree
from sklearn.metrics.pairwise import euclidean_distances
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def DTM(X,query_pts,m):
'''
Compute the values of the DTM (with exponent p=2) of the e... |
#!/usr/bin/env python
"""setup.py file for a GRR API client library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import shutil
import sys
from setuptools import find_packages
from setuptools import setup
from setuptools.command.sdist impo... |
import os
import pytest
from click.testing import CliRunner
from great_expectations import DataContext
from great_expectations.cli import cli
from tests.cli.utils import (
VALIDATION_OPERATORS_DEPRECATION_MESSAGE,
assert_no_logging_messages_or_tracebacks,
)
try:
from unittest import mock
except ImportErr... |
from custom_src.NodeInstance import NodeInstance
from custom_src.Node import Node
# USEFUL
# self.input(index) <- access to input data
# self.outputs[index].set_val(val) <- set output data port value
# self.main_widget <- access to main widget
# self.exec_output(index) ... |
"""
This test will initialize the display using displayio and draw a solid green
background, a smaller purple rectangle, and some yellow text.
"""
import displayio
import terminalio
from adafruit_display_text import label
from adafruit_gizmo import tft_gizmo
# Create the TFT Gizmo display
display = tft_gizmo... |
"""Utility function for the PPO-based safe explorer.
"""
import numpy as np
import torch
import torch.nn as nn
from gym.spaces import Box
from safe_control_gym.math_and_models.neural_networks import MLP, CNN, RNN, init_
from safe_control_gym.math_and_models.distributions import Normal, Categorical
import safe_contro... |
from .CW_attack import AttackCarliniWagnerL2
__all__ = ["AttackCarliniWagnerL2"] |
import torch
from abc import ABC, abstractmethod
class Sampler(ABC):
def __init__(self, device):
self._device = device
@abstractmethod
def sample(sample_size):
pass
class SphereSampler(Sampler):
def __init__(self, shape, device, epsilon=1e-7):
super().__init__(device)
... |
"""Python protoc plugin for Envoy APIs."""
import cProfile
from collections import namedtuple
import io
import os
import pstats
import sys
from tools.api_proto_plugin import traverse
from google.protobuf.compiler import plugin_pb2
OutputDescriptor = namedtuple(
'OutputDescriptor',
[
# Output files a... |
# Modified from:
# https://www.pyimagesearch.com/2017/02/06/faster-video-file-fps-with-cv2-videocapture-and-opencv/
# Performance:
# Python 2.7: 105.78 --> 131.75
# Python 3.7: 15.36 --> 50.13
# USAGE
# python read_frames_fast.py --video videos/jurassic_park_intro.mp4
# import the necessary pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=39
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... |
import asyncio
import json
import os
import shutil
import threading
import zipfile
import aiohttp
import requests
from Util import Configuration, GearbotLogging, Emoji
LANGS = dict()
BOT = None
def on_ready(bot_in):
global BOT
BOT = bot_in
load_translations()
def load_translations():
directory = os... |
import os,glob
files=glob.glob('AIS_DATA_2016/*.dat')
for name in files:
new_name=name.replace(' ','_')
os.rename(name,new_name)
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 18:02:27 2020
@author: Christopher Cheng
"""
def is_prime(n):
prime = True
for i in range(2,n):
if n%i == 0:
prime = False
return prime
def abs_val (n):
if n< 0:
return -n
else:
return n
|
# Miscellaneous cim classes
ACLINE = "cim:ACLineSegment"
CNODE_CONTAINER = "cim:ConnectivityNode.ConnectivityNodeContainer"
EQUIP_CONTAINER = "cim:Equipment.EquipmentContainer"
GEO_REG = "cim:SubGeographicalRegion"
ID_OBJ = "cim:IdentifiedObject"
TC_EQUIPMENT = "cim:Terminal.ConductingEquipment"
TC_NODE = "cim:Termina... |
import logging
from controller.controller import MAIN_APP
from controller.ajax import AJAX_APP
from flask import Flask
if __name__ == "__main__":
# set up logging
# https://docs.python.org/3/howto/logging-cookbook.html
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
FH =... |
nome = input("Digite seu nome: ")
print("Bem vinde {}".format(nome)) |
from UE4Parse.BinaryReader import BinaryStream
class Int8Property:
position: int
Value: int
def __init__(self, reader: BinaryStream, readType):
self.position = reader.base_stream.tell()
if readType.value == 3:
self.Value = 0
else:
self.Value = int.from_byte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.