content stringlengths 5 1.05M |
|---|
import pytest
from eth_utils import (
to_bytes,
)
from ens import ENS
from ethpm import (
ASSETS_DIR,
)
from web3.exceptions import (
InvalidAddress,
)
from web3.pm import (
SimpleRegistry,
)
def bytes32(val):
if isinstance(val, int):
result = to_bytes(val)
else:
raise TypeEr... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 00:31:41 2018
Problem 2
- Even Fibonacci numbers
@author: zeroam
"""
def fibonacci(limit):
first = 1
second = 2
cur = 0
total = 2
while cur < limit:
if(cur%2 == 0):
total += cur
cur = first + second
first = second... |
#!/usr/bin/env python
# $Id: make_language_equivalence_test.py 538 2009-11-09 14:51:19Z hat $
"""
Check whether two automata recognize the same language.
"""
import sys
# Make sure the installed version is used (is in the Python path).
site_packages = "%SITEPACKAGES%"
if not site_packages.startswith("%SITE") an... |
import logging
logger = logging.getLogger(__name__)
# ....
|
import importlib
from .. import Deconstructor, STR
class TypeDeconstructor(Deconstructor):
name = u"type"
def deconstruct(self, obj):
return None, {u"name" : STR(obj.__name__),
u"module" : STR(obj.__module__)}
def construct(self, args, kwargs):
class_name, module_n... |
"""
The loader imports the AST visitor from the parser directory - this directory is autogenerated by the
utils/parser appropriate scripts, and should not be manually modified.
"""
import copy
import logging
from antlr4 import FileStream, CommonTokenStream, InputStream
from antlr4.error.ErrorListener import ErrorLis... |
import subprocess
import os
import re
import shutil
import xml.etree.ElementTree as ET
# loaded rules list:
rules= []
from Rule1 import *
rules.append(Rule1())
#import Rule2
#rules.append(Rule2())
#import Rule3
#rules.append(Rule3())
# configurations
sources='C:/Users/fgrando/Downloads/cppcheck-rules/'
workspace=... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from datetime import datetime, timedelta
import pytest
from aspen.http.response import Response
from gratipay import utils
from gratipay.testing import Harness, D
from gratipay.utils import i18n, pricing, encode... |
from myia.models.person_models import Person
from django.shortcuts import render, redirect, reverse
#from django.core.files.storage import FileSystemStorage
from django.template.loader import render_to_string
from myia.forms.person_form import PersonForm
from django.http import HttpResponse
#from weasyprint import... |
import json
from telethon import TelegramClient
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.functions.channels import InviteToChannelRequest
import os
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from config.provider import TelegramConfig, ChannelTravelConfig
class... |
import warnings
from numpy.testing import TestCase
class TestWarn(TestCase):
def test_f(self):
warnings.filterwarnings("ignore", message="another warning")
warnings.warn("another warning!")
|
# Copyright 2019 Extreme Networks, 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 applicable law or agreed to i... |
import urllib3
import certifi
# It is absolutely CRITICAL that you use certificate validation to ensure and guarantee that
# 1. you are indeed sending the message to *.hanatrial.ondemand.com and
# 2. that you avoid the possibility of TLS/SSL MITM attacks which would allow a malicious person to capture the OAuth token
... |
import pytest
from dbdaora import DatastoreGeoSpatialRepository, KindKeyDatastoreDataSource
@pytest.fixture
def fallback_data_source():
return KindKeyDatastoreDataSource()
@pytest.fixture
def fake_repository_cls(fake_entity_cls):
class FakeGeoSpatialRepository(DatastoreGeoSpatialRepository):
name =... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distribut... |
c = get_config()
c.InteractiveShellApp.exec_lines = [
"from pyspark import SparkConf",
"from pyspark.sql import SparkSession",
"from pyspark import SparkContext",
"from dask.distributed import Client",
"import h2o",
"conf = SparkConf()",
"conf.set('spark.driver.port','29413')",
"conf.set... |
# Modified PointNetVLAD code: https://github.com/mikacuy/pointnetvlad
# Modified by: Kamil Zywanowski, Adam Banaszczyk, Michal Nowicki (Poznan University of Technology 2021)
import pandas as pd
import numpy as np
import os
import pandas as pd
from sklearn.neighbors import KDTree
import pickle
#####For training and te... |
from model.group import Group
def test_add_group(app):
app.group.create(Group(name="gpojkpkjda", header="ka lcac", footer="lknmclskncs"))
def test_add_empty_group(app):
app.group.create(Group(name="", header="", footer=""))
|
def populate_country_list(country_list):
"""Some currency is used by multiple country codes, this will populate the appropriate countries
for these scenarios so that missing countries are not populated incorrectly.
Arguments:
country_list: A list of country codes from your collection.
Returns:... |
import copy
configs = dict()
config = dict(
env=dict(
id="Safexp-PointGoal0-v0",
obs_prev_cost=True,
obs_version="default",
),
sampler=dict(
batch_T=128,
batch_B=104, # Might bust memory limits.
max_decorrelation_steps=1000,
),
algo=dict(
di... |
[]# -*- coding: utf-8 -*-
from google.protobuf.json_format import MessageToDict
from spaceone.core import pygrpc
from spaceone.core import utils
from spaceone.core.transaction import Transaction
from spaceone.api.core.v1 import handler_pb2
class EventGRPCHandler(object):
def __init__(self, config):
self... |
# https://www.codewars.com/kata/54c1bf903f0696f04600068b/train/python - 4kyu
# Test
class Machine(object):
REGISTERS = ['a', 'b', 'c', 'd']
def __init__(self, cpu):
self.cpu = cpu
# self.cpu.read_reg(self, name): Returns the value of the named register.
# self.cpu.write_reg(self,... |
#! /usr/bin/python
import socket
import RPi.GPIO as gpio
import time
listensocket =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
port = 16662
IP = "192.168.88.225"
pin=7
gpio.setmode(gpio.BOARD)
try:
listensocket.bind((IP,port))
listensocket.listen(999)
connectionStatus =False
print("server star... |
# Copyright 2016 Red Hat, 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 applicable law or agreed to in writing, so... |
# Author: Nate K
# Date of Creation: 09/16/2019
# Date of Last Edit: 09/16/2019
# If-Statement Grading Homework
# SOURCES:
# On my honor, I have neither given nor received unauthorized aid.
# Signed: NK 09/16/2019
# *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*
grade_UR = ... |
import re
mySent = 'This book is the best book on Python or M.L. I have ever laid eyes upon.'
print(mySent.split())
regEx = re.compile('\W*')
listOfTokens = regEx.split(mySent)
print(listOfTokens)
print([tok for tok in listOfTokens if len(tok) > 0])
print([tok.lower() for tok in listOfTokens if len(tok) > 0])
email... |
"""
juxtapy nose tests
project : juxtapy
version : 0.1.0
status : development
modifydate : 2015-05-11 19:03:00 -0700
createdate : 2015-04-26 04:45:00 -0700
website : https://github.com/tmthydvnprt/juxtapy
author : tmthydvnprt
email : tmthydvnprt@users.noreply.github.com
maintainer : tmthydvnprt
l... |
"""
Verify that AUC only depends on separability of the two classes.
This was the motivation of the pinned AUC metric in
Measuring and Mitigating Unintended Bias in Text Classification
"""
import fire
from sklearn.metrics import roc_curve
import torch
import torch.nn.functional as F
from swissknife import utils
... |
import collections
import ctypes
import logging
from .generated.vega10_pptable import *
LOG = logging.getLogger(__name__)
class UnknownRevId(KeyError):
pass
def parse_table(buffer, offset, type_select):
header = Vega10_PPTable_Generic_SubTable_Header.from_buffer(buffer, offset)
return type_select(hea... |
import time, threading, select, json, socket
import stratum
from cryptography.fernet import Fernet
def encrypt(message, key):
return Fernet(key).encrypt(message.encode())
def decrypt(token, key):
return Fernet(key).decrypt(token).decode()
class Communications(threading.Thread):
def __init__(self):
self.... |
"""
Models
"""
from django.db import models
# pylint: disable=R0903
class NewsCategory(models.Model):
"""
News categories
"""
name = models.CharField("Kategorie", max_length=200)
def __str__(self):
return self.name
# pylint: disable=C0111
class Meta:
verbose_name = 'Nachr... |
import json
import sys
def main():
if len(sys.argv) < 2:
print >>sys.stderr, 'usage: json2gephi.py <jsonfile>'
jsonfile = sys.argv[1]
with open(jsonfile) as f:
data = json.loads(f.read())
for edge in data['edges']:
print '{},{}'.format(*edge)
return 0
if __name__ == '... |
#!/usr/bin/python2
'''
This is a python module to create sbatch files for job submission on a cluster
'''
import argparse
import sys
class CommandLineParser(argparse.ArgumentParser):
'''
To check the input arguments
'''
def error(self, message):
sys.stderr.write("error: %s\n" % message)
... |
import glob
import importlib
import inspect
from pathlib import Path
from flask import Flask
from flask_next.HTMLView import HTMLView
class DynamicSetup:
modules: dict = {}
secure_routes = {}
public_routes = {}
route_count: int = 0
option_append_slash = False
allowable_methods = ["GET", "PUT... |
"""
Capstone Project. Code to run on the EV3 robot (NOT on a laptop).
Author: Your professors (for the framework)
and Zichen Tan.
Winter term, 2018-2019.
"""
import rosebot
import mqtt_remote_method_calls as com
import time
import shared_gui_delegate_on_robot
def main():
"""
This code, which must r... |
from requests.models import Response
from app.api_models import ExtractResponse
import requests
import newspaper, re
# simple language detector
from langdetect import detect as detect_language
class Extractor(object):
"""
Class for extracting text etc (ExtractResponse) for URLs.
"""
def __init__(sel... |
#from DreamDiff import DreamDiff as ad
from DreamDiff.DreamDiff import DreamDiff as ad
import numpy as np
import matplotlib.pyplot as plt
class Optimize:
'''
Class containing a suite of root-finding, optimization, and
animation tools for Newton's method, gradient descent, and
Nesterov's accelerated g... |
#
# 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, software
# ... |
import codecs
import StringIO
from django.utils.importlib import import_module
csv = import_module('csv')
import jsonpath
from ..settings import CSV_EXPORT_EXTRA_JSON_PATHS
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
... |
# TODO:
from ordered_set import OrderedSet
from miniworld.log import log
from miniworld.model import StartableObject
from miniworld.model.network.backends.bridged.iproute2 import IPRoute2Commands
from miniworld.model.singletons.Singletons import singletons
from miniworld.util import NetworkBackendUtil
# TODO: move to... |
import datetime
from django.core.exceptions import ObjectDoesNotExist
from selvbetjening.core.events.models import Attend, AttendState
from selvbetjening.core.user.models import SUser
"""
A unit must expose the following properties
`label` A name identifying the source data.
`qs` A queryset of the source dat... |
from glob import glob
from setuptools import setup
setup (name = 'logsrv',
version = '0.1',
description = 'A simple logging server working over websockets',
package_dir = {'logsrv': 'src'},
packages = ['logsrv'],
install_requires=['websockets'])
|
from mayan.apps.acls.models import AccessControlList
from mayan.apps.documents.models.document_models import Document
from mayan.apps.documents.permissions import permission_document_view
from mayan.apps.rest_api import generics
from .models import DocumentCheckout
from .permissions import (
permission_document_ch... |
try:
from . import generic as g
except BaseException:
import generic as g
class BoundsTest(g.unittest.TestCase):
def setUp(self):
meshes = [g.get_mesh(i) for i in ['large_block.STL',
'featuretype.STL']]
self.meshes = g.np.append(meshes, list(g.get... |
"""
songsheet
====
Author: Joshua Fung
2019-08-08
We assume the the first block is a data block, all the metadata will be
there, seperated by a newline. Then each song section will be seperated
by a newline, first the tag then a ":" follow by the song. A newline is
nessary, things following the ":" will be discarded.... |
import flask
from flask import Flask, request
app = Flask(__name__)
import datetime
import pymongo
import os
import sys
from delorean import parse
from struct import *
MONGO_DB_URI = os.environ.get('MONGO_DB_URI', 'mongodb://localhost:27017/')
db = pymongo.MongoClient(MONGO_DB_URI).sensorgrid
PROTOCOL_VERSIONS = {
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import binascii
import collections
import copy
import getopt
import json
import os
import random
import re
import string
import subprocess
import sys
import xmltodict as xmltodict
from evernote.api.client import EvernoteClient, NoteStore
from evernote.edam.error import tty... |
from .imgur_scraper import main
|
from __future__ import print_function
import csv
import logging
import os
from faker import Faker
from progress.bar import Bar
from project.lib.data_generator import DataGenerator
log = logging.getLogger("CsvGenerator")
class CsvGenerator:
def __init__(self):
pass
@staticmethod
def generate_... |
import turtle
def square():
for n in range(4):
turtle.forward(100)
turtle.left(90)
for n in range(6):
square()
turtle.forward(100)
turtle.right(60)
|
import turtle
def string_art(x, y, size, quad, color):
turtle.penup()
turtle.goto(x,y)
turtle.color(color)
width = 10
height = size
lines = height//10
if quad == 2:
width = -width
elif quad == 3:
width = -width
height = -height
elif quad == 4:
heig... |
"""Encoding DIMSE messages for use in testing."""
################################### C-STORE ####################################
# MCH Byte: 0x03
# MessageID: 7
# AffectedSOPClassUID: '1.1.1'
# AffectedSOPInstanceUID: '1.2.1'
# Priority: 0x02
# MoveOriginatorApplicationEntityTitle: 'UNITTEST'
# MoveOriginatorMessageI... |
# -*- coding: utf-8 -*-
# @Time : 21-7-25 10:15
# @Author : MingZhang
# @Email : zm19921120@126.com
import glob
import os
import cv2
import sys
import tqdm
import json
import shutil
sys.path.append('.')
from config import opt
label_map = {'pedestrian': 1, 'people': 2, 'bicycle': 3, 'car': 4, 'van': 5, 'truck':... |
import os
import pandas
ymdt = '2021-05-09 08:30'
yt_concurrent = 2
ss_live = 0
ss_same_day = 0
ss_on_demand = 0
yt_same_day = 0 - yt_concurrent
yt_on_demand = 0
# standardize file name
path = os.getcwd()
for files in os.listdir(path):
if os.path.isfile(os.path.join(path, files)):
if '-unique-viewers' i... |
from __future__ import annotations
from datetime import datetime, date, timezone, timedelta
from django.contrib.auth.models import User
from django.db import models
class Account(models.Model):
user = models.ForeignKey(to=User, on_delete=models.CASCADE)
state = models.IntegerField()
name = models.CharFi... |
"""
owtf.selenium.selenium_handler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Launch and browse URLs using Selenium
"""
from pyvirtualdisplay import Display
from selenium import webdriver
from owtf.selenium import url_launcher
from owtf.dependency_management.dependency_resolver import BaseComponent
from owtf.dependency_manageme... |
import mock
import pytest
from pyetcd import EtcdKeyNotFound
from etcdb import InternalError
from etcdb.lock import Lock
def test_release_raises_internal(etcdb_connection):
mock_delete = mock.Mock()
mock_delete.side_effect = EtcdKeyNotFound
etcdb_connection.client.delete = mock_delete
lock = Lock(et... |
# Copyright 2020 Makani Technologies 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://github.com/mozman/svgwrite/blob/master/examples/mandelbrot.py
# pip install svgwrite
import svgwrite
from svgwrite import rgb
# SOURCE: http://code.activestate.com/recipes/577111/
def create_svg(name):
# Mandelbrot fract... |
'''O mesmo professor quer sortear a ordem da apresentação dos alunos, faça um programa que leia o nome dos quatro alunos e mostre
a ordem sorteada'''
import random
a1 = str(input('Digite o aluno 1:'))
a2 = str(input('Digite o aluno 2:'))
a3 = str(input('Digite o aluno 3:'))
a4 = str(input('Digite o aluno 4:'))
lista =... |
from skimage.segmentation import quickshift, mark_boundaries
import numpy as np
import matplotlib.pyplot as plt
from IPython.core.display import display, HTML
import cv2
def show_vis_explanation(explanation_image, cmap=None):
"""
Get the environment and show the image.
Args:
explanation_image:
... |
# -*- encoding: utf-8 -*-
"""
hio.help.timing module
"""
import time
from .. import hioing
class TimerError(hioing.HioError):
"""
Generic Timer Errors
Usage:
raise TimerError("error message")
"""
class RetroTimerError(TimerError):
"""
Error due to real time being retrograded before ... |
#
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Lead Developers: Dan Lovell and Jay Baxter
# Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka
# Research Leads: Vikash Mansinghka, Patrick Shafto
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may... |
from vstreamer_utils.networking.Request import \
Request, DirectoryInfoRequest, AdditionalEntryPropertiesRequest
from vstreamer_utils.networking.Response import \
Response, DirectoryInfoResponse, AdditionalEntryPropertiesResponse, ErrorResponse
from vstreamer_utils.networking.CommunicationService import Communi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from selenium.webdriver.common.by import By
from behave import *
import time
#driver = webdriver.Chrome("D://Workspace//Browser Automation//browser-automation-1//chromedriver.exe")
##### Steps
@given('que acessei o site OrangeHRM')
def step_impl(context):
context.d... |
import unittest
from linkedlist import ListNode
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
lo = dummy
for _ in range(n):
h... |
# importing flask and other dependencies
from flask import Flask,request,jsonify
from mutagen.mp3 import MP3
#configurations and environment setup
from dotenv import load_dotenv
load_dotenv()
from firebase import config
import os
# importing other modules from the app for functionalities
from app.users import UserMa... |
TLS_VERSIONING = "1.0.29"
TLS_DATE = "19 August 2021"
|
import attr
import textwrap
import functools
from pprint import *
from pathlib import *
from jinja2 import *
from copy import *
from .has_settings import HasSettings
from .has_dir_path import HasDirPath
from .document import Document
from exam_gen.util.versioned_option import add_versioned_option
from exam_gen.util.... |
import pandas as pd
import json
import math
import time
import matplotlib.pyplot as plt
import datetime
from numba import jit
filename_arr = ["reverse_microwave.tsv", "reverse_hair_dryer.tsv","reverse_pacifier.tsv"]
filename_NLP_arr = ["NLP1_microwave.tsv", "NLP1_hair_dryer.tsv","NLP1_pacifier.tsv"]
time_pin = time.ti... |
# Generated by Django 2.0.6 on 2018-11-02 09:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0003_coachingcourse'),
]
operations = [
migrations.AlterField(
model_name='coachingcourse',
name='username'... |
import setuptools
#print(setuptools.find_packages(where='src'))
#exit()
with open("Readme.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='coderz',
version='0.1.14',
author="CoderZ",
author_email="app@gocoderz.com",
python_requires='>3.0',
description="CoderZ External ID... |
ALT = '\ue00a'
BACKSPACE = '\ue003'
BACK_SPACE = BACKSPACE
CANCEL = '\ue001'
CONTROL = '\ue009'
CLEAR = '\ue005'
DELETE = '\ue017'
DOWN = '\ue015'
ARROW_DOWN = DOWN
INSERT = '\ue016'
ENTER = '\ue007'
END = '\ue010'
ESCAPE = '\ue00c'
HELP = '\ue002'
NULL = '\ue000'
RETURN = '\ue006'
TAB = '\ue004'
SHIFT = '\ue008'
LEFT_... |
# This sample tests the handling of class specialization expressions
# that provide signatures for ParamSpecs.
from typing import Callable, Concatenate, Generic, ParamSpec, TypeVar
T = TypeVar("T")
P1 = ParamSpec("P1")
P2 = ParamSpec("P2")
class X(Generic[T, P1]):
f: Callable[P1, int]
x: T
def x1(x: X[in... |
# functions to convert iterable of iterables to html table
def head(elems):
out = []
for elem in elems:
out.append(f'<th>{elem}</th>')
out = ''.join(out)
return f'<tr>{out}</tr>'
def row(elems):
out = []
for elem in elems:
if type(elem) is float:
out.append(f'<td... |
# ******************************************************************************
# Copyright 2017-2018 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.apa... |
import sysv_ipc
import utils
params = utils.read_params()
try:
mq = sysv_ipc.MessageQueue(params["KEY"])
mq.remove()
s = "message queue %d removed" % params["KEY"]
print (s)
except:
print ("message queue doesn't exist")
print ("\nAll clean!") |
import time
import math
def facc(label, pred):
pred = pred.ravel()
label = label.ravel()
return ((pred > 0.5) == label).mean()
def time_since(start):
now = time.time()
s = now - start
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
|
# Import modules
import os
import csv
# Define variables
votes = 0
vote_count = []
candidates = []
csv_reader = ['1','2']
# Define path and open csv
csvpath = os.path.join("C:/Users/George Aziz/Desktop/case-homework/python-challenge/Pypoll/Resources/election_data.csv")
with open(csvpath, 'r', newline='') as csvfile:... |
from glob import glob
import yaml
from poping.model import Problem
import os
from pymongo import MongoClient
from bson import ObjectId
client = MongoClient()
db = client["po-ping"]
for filename in glob("problems/*.yaml"):
with open(filename) as file:
name = os.path.basename(filename).replace(".yaml", "... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from astropy import units as u
from astropy.visualization import quantity_support
from gammapy.utils.array import array_stats_str
from ..core import IRF
class PSF(IRF):
"""PSF base class"""
def normalize(self):
"""Norm... |
from tqdm import trange
def validate(model, val_iterator, criterion):
val_loss = 0.0
num_correct, num_total = 0, 0
model.eval()
for batch in val_iterator:
x, l = batch.text
y = batch.label
output = model(x, l)
loss = criterion(output, y)
loss.backward()
... |
from typing import Any, List, Dict, Iterator, Callable
import torch
import torch.nn as nn
import numpy as np
import apex
from apex.parallel import DistributedDataParallel, Reducer
# from torch.nn.parallel import DistributedDataParallel
from torchfly.metrics import CategoricalAccuracy, Average, MovingAverage, Speed
fro... |
import tensorflow as tf
import tensorflow.keras.layers as layers
def Actor_Continuos_Default(state_dimension, action_dimension, action_bound):
inputs = layers.Input((state_dimension, ))
dense_1 = layers.Dense(32, activation='relu')(inputs)
dense_2 = layers.Dense(32, activation='relu')(dense_1)
out_mu... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Log'
db.create_table(u'logging_log', (
(u'id', self.gf('django.db.models.fields.... |
# -*- coding:utf-8 -*-
"""
@Author:Charles Van
@E-mail: williananjhon@hotmail.com
@Time:2019-07-31 16:28
@Project:InterView_Book
@Filename:basicDataType3.py
@description:
使用二进制求解最大公约数
"""
'''
题目描述:
两个整数x、y,它们的最大公约数d必须满足d|x,而且d|y.其中符号“|”表示整除
'''
def gcd(a,b):
# 如果a能被b整除,那么b就是两个数的最大公约数
if a % b == 0:
return ... |
class Account:
account_list = []
def __init__(self, account_name, account_userName, account_password):
self.account_name = account_name
self.account_userName = account_userName
self.account_password = account_password
def save_account(self):
Account.account_list.ap... |
import unittest
from microsim.person import Person
from microsim.test.test_risk_model_repository import TestRiskModelRepository
from microsim.education import Education
from microsim.outcome import Outcome, OutcomeType
from microsim.test.do_not_change_risk_factors_model_repository import (
DoNotChangeRiskFactorsMo... |
from setuptools import setup, Extension
import numpy as np
ext = Extension('_module2', ['_module2.c'],
extra_compile_args=['-std=c99'],
include_dirs=[np.get_include()])
setup(name='example', py_modules=['module1', 'module2'], ext_modules=[ext])
|
# Redis数据库的地址和端口
HOST = 'localhost'
PORT = 6379
# 如果Redis有密码,则添加这句密码,否则设置为None
PASSWORD = None
# 代理池数量界限
POOL_LOWER_THRESHOLD = 40
POOL_UPPER_THRESHOLD = 200
# 检查周期
VALID_CHECK_CYCLE = 50
POOL_LEN_CHECK_CYCLE = 30
# 测试API,用百度来测试
TEST_API='https://www.amazon.com/dp/059035342X'
|
#!/usr/bin/env python3
'''
Create a function that takes a string and returns True if the sum of index
(position) on every letters in word (in English alphabet) is even or return False if the sum is odd
'''
def in_alpha(word):
chars = [i for i in word]
clean = ''.join(e for e in chars if e.isalnum())
aval =... |
import sys
from os import chdir, getcwd
from solar_siblings_functions import *
from scipy.stats import kde
def metrices_to_investigate(all_cols):
metrices = all_cols[1:] # remove first sobject_id col
remove_metrices = np.array(['C', 'Ce', 'Co', 'Eu', 'K', 'La', 'Li', 'Mo', 'Nd', 'Ru', 'Sm', 'Sr', 'Zr',
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Cluste... |
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_d... |
# -*- coding: utf-8 -*-
from crawlib.tests.dummy_site_crawler.mongo_backend.s1_movie import (
ListPage, MoviePage, )
# HomePage.smart_insert(HomePage(_id=1))
# HomePage.start_all()
indent = 0
unfinished_filters = {"_id": {"$lte": 2}}
n_unfinished = ListPage.count_unfinished(filters=unfinished_filters)
left_count... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Marker(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "pie"
_path_str = "pie.marker"
_valid_props = {"colors", "colorssrc", "line"}
# colors
... |
# https://github.com/tensorflow/models/blob/master/research/deeplab/deeplab_demo.ipynb
# Mostly taken from ^ but cleaned and modified a bit to be easier for me to use.
import multiprocessing
import os
import tarfile
from collections import Counter
import numpy as np
import tensorflow as tf
from PIL import Image
os.e... |
from __future__ import unicode_literals
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from ..permissions import permission_template_sandbox
class DocumentTemplateSandboxViewTestMixin(object):
def _request_document_template_sandbox_view(self):
return self.get(
viewna... |
from tensorflow.keras import Model
from tensorflow.keras.layers import Activation, Concatenate, Conv2D, UpSampling2D
from src.models.layers.common_layers import conv_bn_relu
from src.models.layers.shared_kernels import KSAConv2D
def decoder(fmap1, fmap2, filters):
"""[summary]
Args:
fmap1 ([type]): ... |
from django.contrib.gis.db import models
from core.models import TimeStampedModel
from autoslug import AutoSlugField
from versatileimagefield.fields import PPOIField
from versatileimagefield.fields import VersatileImageField
class Motel(TimeStampedModel):
town = models.ForeignKey('towns.Town', related_name='tow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.