content stringlengths 5 1.05M |
|---|
from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
def init_browser():
executable_path = {"executable_path": ChromeDriverManager().install()}
return Browser("chrome", **executable_path, headless=False)
... |
import json
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from .constants import TEST_EMAIL
from .constants import TEST_FIRSTNAME
from .constants import TEST_LASTNAME
class TestAuthenticate(TestCase):
AUTHENTICATE_URL = reverse("authenticate")
FIR... |
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as metrics
def precision_recall_threshold_plot(y_true: np.ndarray, y_est_prob: np.ndarray, output_ffp: Path):
"""Creates a precision-recall (y-axis) vs threshold (x-axis) plot"""
precision, recall, thresholds =... |
target=pow(10,17)
fib=[1]
zeck=[0,1,2,3]
x_n=1
x_np=1
i=0
while x_n <= target:
x_n,x_np = x_np,x_n+x_np
fib.append(x_n)
if i>=4:
#Properties are:
#Given f(x) is the Fibonacci function:
#sum(1, f(x)) = sum(1, f(x-1)) + sum(1, f(x-2)) + f(x-2) - 1
#If f(x-1) < a < f(x):
#sum(1, a) = sum(... |
#!/usr/bin/env python2
import rospy
# MRS ROS messages
from std_srvs.srv import Trigger
from std_srvs.srv import TriggerResponse
from mtsp_msgs.msg import TspProblem
from mtsp_msgs.msg import TspPoint
from std_msgs.msg import Int32
# TSP
from mtsp_problem_loader.tsp_problem import *
class TspLoader:
def callba... |
"""
tensorflow几种常用调试方式如下:
1.通过Session.run()获取变量的值
2.利用Tensorboard查看一些可视化统计
3.使用tf.Print()和tf.Assert()打印变量
4.使用Python的debug工具: ipdb, pudb
5.利用tf.py_func()向图中插入自定义的打印代码, tdb
6.使用官方debug工具: tfdbg
tensorflow是通过先建图再运行的方式进行运行,这就使得我们写在图建立过程中的输出语句在图运行的时候并不能得到执行,从而使得调试困难.
我们想在运行过程中,对训练的一些变量进行追踪和打印,对一些错误进行输出分析,下面介绍几种在tensorflo... |
from typing import List
from config.middleware import get_current_user
from fastapi import APIRouter, Depends, status
import database
from schema import UserView, SessionView, SessionUpdate, SessionCreate, SessionAddWorkout
from sqlalchemy.orm import Session
from repository import SessionRepository
router = APIRouter(... |
import requests
from colorama import Fore
from plugin import plugin, require
@require(network=True)
@plugin("agify")
def agify(jarvis, s):
"""Tells the age of someone based on his name, powered by www.boredapi.com"""
if (s):
req = requests.get("https://api.agify.io?name=" + s)
data = req.json... |
import abc, os
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from ..core import *
__all__ = ('UnknownElement', 'Element', 'Document', 'INT', 'UINT', 'FLOAT', 'STRING', 'UNICODE', 'DATE', 'BINARY', 'CONTAINER')
INT, UINT, FLOAT, STRING, UNICODE, DATE, BINARY, CONTAINER = ran... |
class Node(object):
def __init__(self, data):
self.data = data
self._next = None
def set_next(self, next_node):
self._next = next_node
def get_next(self):
return self._next
class LinkList(object):
def __init__(self):
self._head = None
self._last= Non... |
from hashlib import sha256
from .aes import AES_CTR
class DecryptionKey:
def __init__(self, key, secret):
dec_key = sha256()
dec_key.update(key)
dec_key.update(secret)
self.key = dec_key.digest()
def __call__(self):
return self.key
class EncryptionKey:
def __ini... |
import sqlite3
import json
def dict_factory(cur, row):
d = {}
for idx, col in enumerate(cur.description):
d[col[0]] = row[idx]
return d
connection = sqlite3.connect("soakDBDataFile.sqlite")
connection.row_factory = dict_factory
cursor = connection.cursor()
cursor.execute("select * from mai... |
from typing import Dict
import pytest
from ...func_test_tools import load_result, load_result_from_path
# Under test
from go_over.goodreads.processor import process
# Test
def test_force_generate_without_initial_complementary_data(csv_one_book, json_none, results_path):
""" Force generate the file when the comp... |
import System
import Rhino
import scriptcontext
import Smart
def addRhinoLayer(layerName, layerColor=System.Drawing.Color.Black):
"""Creates a Layer in Rhino using a name and optional color. Returns the
index of the layer requested. If the layer
already exists, the color is updated and no new layer is ... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
##############################################################################
# Copyright 2020 AlexPDev
#
# 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 Lice... |
import face_recognition
#from faces import *
import cv2
import time
import glob
import numpy
known_face_encodings = []
known_face_names = []
for file in glob.glob("./profiles/*.npy"):
known_face_encodings.append(numpy.load(file))
# will break if you change directory name or file extention
known_face_names... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#!/usr/bin/python3
from distutils.core import setup
setup(
name='selkup_alphabet',
packages=['selkup_alphabet'],
version='0.1',
description='Library that helps you to work with different Selkup scripts',
author='Fyodor Sizov',
author_email='f.sizov@yandex.ru',
url='https://github.com/selkup-commu... |
import setuptools
with open('README.md') as r:
README = r.read()
setuptools.setup(
name="animalsounds",
version="0.1.0",
url="https://github.com/username/animalsounds",
author="First Last",
author_email="email@gmail.com",
description="An exploration of different animal sounds.",
long_de... |
import shutil
from glob import glob
from multiprocessing import Pool
from time import time
import numpy as np
import pandas as pd
import xarray as xr
from netCDF4 import Dataset
from cirrus.netCDFtoTIFF import nc2tiff
from cirrus.util.config import is_goias, lats, logger, lons, ormdtype, settings
from cirrus.util.db ... |
import calendar
import itertools
from django.db.models import OuterRef, Q, Subquery
import django_filters
from dalme_app.models import Attribute, Source, LocaleReference
from dalme_public import forms
from dalme_public.models import (
Collection,
Corpus,
Essay,
FeaturedInventory,
FeaturedObject,
... |
from __future__ import unicode_literals
from netaddr import IPNetwork
from django.core.exceptions import ValidationError
from django.db import models
from .formfields import IPFormField
from .lookups import (
EndsWith, IEndsWith, IRegex, IStartsWith, NetContained, NetContainedOrEqual, NetContains, NetContainsOrE... |
# -*- coding: utf-8 -*-
import click
import sys
import logging
import datetime
from cointrader import db, STRATEGIES
from cointrader.config import Config, get_path_to_config
from cointrader.exchange import Poloniex, BacktestMarket, Market
from cointrader.exchanges.poloniex import ApiError
from cointrader.bot import ini... |
import os
# *****************************
# Environment specific settings
# *****************************
# DO NOT use "DEBUG = True" in production environments
DEBUG = True |
import numpy as np
from functools import total_ordering
from abc import ABC, abstractmethod
@total_ordering
class Individual(ABC):
genes_to_numpy = lambda pop: np.array(list(map(lambda c: c.genes, pop)))
fitness_to_numpy = lambda pop: np.array(list(map(lambda c: c.fitness, pop))
... |
# Definition for a QuadTree node.
class Node(object):
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = botto... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 16:32:15 2020
@author: ZongSing_NB
"""
"""
ref:
https://www.mdpi.com/2076-3417/10/11/3667
https://link.springer.com/article/10.1007/s00521-014-1597-x
https://www.mathworks.com/matlabcentral/fileexchange/47215-chaos-theory-and-meta-heuristics?s_tid=mwa_osa_a
"""
import... |
from layer_naive import *
apple = 100
apple_num = 2
orange = 150
orange_num = 3
tax = 1.1
# layer
mul_apple_layer = MulLayer()
mul_orange_layer = MulLayer()
add_apple_orange_layer = AddLayer()
mul_tax_layer = MulLayer()
# forward
apple_price = mul_apple_layer.forward(apple, apple_num) # (1)
orange_price = mul_orange... |
from github import Github
import configparser
# Provide the location of where the config file exists
CONFIG_FILE = 'config.ini'
def parse_config():
"""Parse the configuration file and setup the required configuration."""
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
if 'github_auth' n... |
#! /usr/bin/env python3.6
from argparse import ArgumentParser
from glob import glob
from collections import OrderedDict
from gmpy2 import mpz
from metrics import euclidean, vector_dict
from multiprocessing import Pool
from sklearn import manifold
import os
import numpy as np
def dict_from_file(file):
"""
Ret... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 11:01:10 2021
@author: Simulation
"""
import os, gym
import numpy as np
import assistive_gym
from numpngw import write_png, write_apng
#from IPython.display import display, Image
import matplotlib
import matplotlib.pyplot as plt
import scipy.io as spio
... |
#
# PySNMP MIB module SUPERMICRO-HEALTH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUPERMICRO-HEALTH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
from ...db.schema import Table
from ..field import MutableField, QueryField
from .convert import convert_field
class TableBuilder:
def __init__(self):
self.processing_models = set()
def build(self, model):
if model in self.processing_models:
# TODO: This is to catch self-referenti... |
# -*- coding: utf-8 -*-
import arrow
import pytest
import tests
from etutorservice.models import (
get_current_study_year,
get_student_grade_year,
get_student_k12_grade,
K12Grade,
)
def test_get_current_study_year():
now = arrow.get('2016-01-01', 'YYYY-MM-DD')
result = get_current_study_yea... |
import numpy as np
import ops.utils
# FUNCTIONS
def correlate_channels(r, first, second):
"""Cross-correlation between non-zero pixels.
Uses `first` and `second` to index channels from `r.intensity_image_full`.
"""
A, B = r.intensity_image_full[[first, second]]
filt = A > 0
if filt.sum() ==... |
#!/usr/bin/env python
import json
from pydantic import BaseModel
from train_sklearn import train
class Hyperparams(BaseModel):
min_df: int = 5
max_ngrams: int = 1
stopwords = "english"
loss = "hinge"
learning_rate: float = 1e-4
if __name__ == "__main__":
data_path = "/opt/ml/input/data/tra... |
from ABBYY import CloudOCR
import argparse
import os
if __name__=="__main__":
parser = argparse.ArgumentParser(description='ABBYY CloudOCR')
parser.add_argument('--application_id', help='Application ID')
parser.add_argument('--password', help='Password')
parser.add_argument('--language', help='Specifies recognitio... |
from unittest import TestCase
from cli_args_system.extras import cast_list, format_args, format_flag, is_a_flag, get_flags, get_num_comparison
class FormatFlag(TestCase):
def test_infinity_identifier(self):
formatted_flag = format_flag(flag='--a',
case_sensitive=False... |
"""
Tuplas são imutáveis
arrays - listas são mutáveis
[] utilizado para declaração de lista
() utilizado para declaração de tupla
"""
"""
# declaração de uma tupla utilizando parenteses
"""
tupla1 = (1, 2, 3, 4, 5, 6)
print(tupla1)
"""
# declaração de uma tupla não utilizando parenteses
"""
tupla2 = 1... |
from hd_wallet import *
import settings
current_depth = 1
depth = 100
host_db = "localhost"
db_name = settings.BALANCE
coinid = "coinid"
Information_code = {
0: "Success",
1: "Error"
}
balance_add = {
'amount_active': 0,
'amount_frozen': 0
}
class AddNewUid():
def __init__(self):
self.c... |
import httpx
import pytest
from starlette import testclient
from authentication_service import models, settings, utils
from shared import clear_db, create_user, user_email_verification_assertion
@pytest.fixture
def mock_generate_token(mocker):
def _mocker(result="access token"):
_mock_generate... |
from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@gmail.com', password='Testpass123'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
class ModelTests(Te... |
import logging
from . import status
try:
from rest_framework.exceptions import APIException
except ImportError:
class APIException(Exception):
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = "A server error occurred."
default_code = "error"
... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# row
for row in board:
if not self.isValid(row):
return False
# col
for i in range(9):
if not self.isValid([row[i] for row in board]):
return False ... |
import os
from datetime import datetime
# pylint: disable=too-many-instance-attributes
class Stat:
default_gid = os.getgid()
default_time = datetime.timestamp(datetime.now())
default_uid = os.getuid()
def __init__(self):
self.st_atime = 0
self.st_ctime = 0
self.st_gid = 0
... |
#
# 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 unittest
import numpy as np
import openmdao.api as om
from openmdao.utils.testing_utils import use_tempdirs, require_pyoptsparse
from openmdao.utils.assert_utils import assert_near_equal
import dymos as dm
class BrachistochroneVectorStatesODE(om.ExplicitComponent):
def initialize(self):
self.opt... |
from abc import ABC, abstractmethod
from typing import List
from data.Command import Command
from robot.components.vision.IIRDistanceListener import IIRDistanceListener
class Point:
x: float
y: float
def __init__(self, x, y):
self.y = y
self.x = x
class IWorldCrawler(IIRDistanceListene... |
"""
Retrieve data metrics from all network adaptator.
This module is maintained by Mickaël Schoentgen <contact@tiger-222.fr>.
You can always get the latest version of this module at:
https://github.com/BoboTiG/trafic
If that URL should fail, try contacting the author.
"""
import os
import uuid
from abc import abs... |
import musdb
import museval
import functools
import argparse
def MIX(track, eval_dir=None):
"""Mixture as Estimate
"""
# perform separtion
estimates = {}
for name, target in track.sources.items():
# set accompaniment source
estimates[name] = track.audio / len(track.sources)
e... |
import logging
import subprocess
import math
import pysam
import os
import glob
import multiprocessing
from mincall import bioinf_utils as butil
import shutil
import tempfile
from tqdm import tqdm
from copy import deepcopy
from collections import defaultdict
CIGAR_OPS_LIMIT = 60000
def get_target_sequences(sam_path):... |
from datetime import datetime
from unittest.mock import Mock
# from telebot.types import Message, File
from csuibot.handlers import (help, zodiac, shio, yelfasilkom, compute,
board, definition, synonym, antonym, hex2rgb,
date, time, chant, top_posters, get_mes... |
# Copyright 2014
# The Cloudscaling Group, 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 ... |
import datetime
import pytest
import pytz
import time
import daylight
def epoch(year, month, day, hour=0, minute=0, second=0, tz=pytz.UTC):
dt = tz.localize(datetime.datetime(year, month, day, hour, minute, second))
return (dt - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC)).total_seconds()
def test_all_f... |
import re
from .base import RMDCommand
from json import dumps
class IrodsstatusRMDCommand(RMDCommand):
def __init__(self):
"""
Initiates the RMDCommand class object with the df command
:return: new instance of DiskRMDCommand
"""
super(IrodsstatusRMDCommand, self).__init__('... |
# Generated by Django 2.1.3 on 2018-12-10 15:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user', '0003_auto_20181210_1212'),
]
operations = [
migrations.CreateModel(
name='Upload',
... |
# Natural Language Toolkit: Corpus Reader Utilities
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Steven Bird <sb@ldc.upenn.edu>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
import os
import sys
import bisect
import re
import temp... |
print('{}ANALISADOR DE TRIANGULOS{}'.format('\033[4;31m', '\033[m'))
r1 = float(input('Digite o primeiro segmento: '))
r2 = float(input('Digite o segundo segmento: '))
r3 = float(input('Digite o terceiro segmento: '))
if r1 + r2 > r3 and r2 + r3 > r1 and r3 + r1 > r2:
print('Os segmentos acima PODEM FORMAR um trian... |
# Get list of accounts in Organization
# Assume given role in each account
# Get collection of buckets starting with PARAMETER
# Delete bucket
import sys
import json
# from urllib.parse import urlparse
import boto3
from botocore.exceptions import ClientError
# Globals
global_sts_client = boto3.cli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 10:12:43 2019
@author: amandaash
"""
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt
"""
t1 = np.arange(0,1,0.001)
t2 = np.arange(1, 1000, 0.1)
def reduced_B_funcn(t):
m = np.tanh(m/t)
return(m)
def redu... |
# coding=utf-8
import time
import copy
import numpy as np
import pandas as pd
import os
import torch
import json
from PIL import Image
import torchvision
from torchvision.datasets.utils import download_url
from torch.utils.data import random_split
from torchvision.datasets import ImageFolder
from torch.aut... |
from directory_constants.constants import cms
from wagtail.admin.edit_handlers import (
FieldPanel, ObjectList, MultiFieldPanel, FieldRowPanel
)
from wagtail.documents.edit_handlers import DocumentChooserPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtailmedia.widgets import AdminMediaChoo... |
from opserver.plugins.alarm_base import *
from opserver.sandesh.alarmgen_ctrl.sandesh_alarm_base.ttypes import *
import json
class XmppConnectivity(AlarmBase):
"""XMPP peer mismatch.
Not enough XMPP peers are up in BgpRouterState.num_up_xmpp_peer"""
def __init__(self):
AlarmBase.__init__(self, AlarmB... |
from karel import karel_skryj, domov_skryj
from browser import document, window
karel_skryj()
domov_skryj()
window.mesto.obrazky[1] = "krizek"
window.mesto.obrazky[2] = "kolecko"
def krizek(x, y):
window.mesto.pole[x][y] = 1
window.mesto.prekresli_pole({"x": x, "y": y})
def kolecko(x, y):
window.... |
import pytest
import os
from datetime import datetime, timezone
from bs4 import BeautifulSoup
from meteoclimatic import Observation, Station, Weather, Condition
class TestObservation:
_test_dict = {
'reception_time': datetime(2020, 6, 4, 10, 48,
1, 0, timezone.utc),
... |
#!/usr/bin/env python3
"""
This example constructs the LNA for the model of DNA self-regulation
introduced by Wang et al. (2010) in "Parameter inference for discretely
observed stochastic kinetic models using stochastic gradient descent."
BMC Syst. Biol., 4, 99.
Model:
======
R1: DNA + P2 --> DNA.P2
R2: DNA.P2 ... |
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
st, b = [], [0]*len(s)
for i, val in enumerate(s):
if val == '(':
st.append(i)
elif st:
b[st.pop()], b[i] = 1, 1
... |
from metadata_utils import html_attribute_escape
__VERSION__ = "0.4.1"
# ==============================================================================
_http_equivs = ("content-type", "expires", "refresh")
_link_rels = ("canonical", "link")
class HtmlMetaHub(object):
data_struct = None
def __init__(sel... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 13:17:12 2020
@author: Administrator
"""
"""
给定以非递减顺序排序的三个数组,找出这三个数组中的所有公共元素.例如,给出下面三个数组:
ar1 = [2,5,12,20,45,85] , ar2 = [16,19,20,85,200] , ar3 = [3,4,15,20,39,72,85,190].
那么,这三个数组的公共元素为[20,85].
"""
def GetMin(arr1 , arr2 , arr3 , m , n , l):
if m... |
"""Version information."""
__version__ = "2.9.0"
|
from pykg2tbl import SparqlBuilder
import os
from jinja2 import Environment, FileSystemLoader, meta
import logging
log=logging.getLogger(__name__)
class J2SparqlBuilder(SparqlBuilder):
"""
Generic class to perform templated SPARQL searches versus a given SPARQL endpoint
:param endpoint: sparql endpoint... |
# flake8: noqa
from avionix.chart import (
ChartBuilder,
ChartDependency,
ChartInfo,
ChartMaintainer,
Value,
Values,
)
from avionix.kube.meta import ObjectMeta
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
|
from django.contrib import messages
from data.models.prestatiemeting import Prestatiemeting, PrestatiemetingQuestion, PrestatiemetingGradation
def validate_prestatiemeting_import(sheet):
"""
Method to validate a prestatiemeting form filled by OG
@param sheet: Excel datasheet
@return: Error or None
... |
##########################################################################
# MediPy - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for de... |
# Copyright (c) Facebook, Inc. and its affiliates.
__all__ = ["VisualDialogTask"]
from .task import VisualDialogTask
|
import pathlib
import paramiko
from celery import Celery
# client_dir = pathlib.Path(__file__).resolve().parent.parent
# sys.path.append(f'{client_dir}')
print(__name__)
# module 이름은 cli 에서의 -A 옵션값과 무관하다.
# 즉 다르게 지정해도 상관없다.
app = Celery(__name__, broker='redis://localhost:6380/0', backend='redis://localhost:6380/0')... |
def simple(x):
y = 1
print(f"{x}{y}")
def annotations(x, y):
def g(x: f'{x}') -> f'{y}':
return x
g()
def default_value(x):
def g(x=f'{x}'):
return x
g()
def super_classes(x):
class C(f'{x}'):
pass
C()
def qualified_names():
<weak_warning descr="Loc... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from .models import Movie, Genre
# Create your views here.
class Ho... |
########################################################################
# test/xslt/ob_20000613.py
# Oliver Becker's Sieve of Eratosthenes, from
# http://www.informatik.hu-berlin.de/%7eobecker/XSLT/
import os
from amara.test.xslt.xslt_support import _run_text
xslt_path = os.path.join(os.path.dirname(__file__), "res... |
#!/usr/bin/env python3
#packages to install:
# pip install soupsieve
# pip install beautifulsoup4
# pip install bs4
# pip install dnspython
# pip install pymongo
import requests # lib to make web requests
from bs4 import BeautifulSoup
# read in url-list
try:
with open('vocab_input.txt') as vocab_input:
vocab_... |
# coding=utf-8
# Copyright 2019 The Tensor2Tensor 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 applicable... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import light
from esphome.const import (
CONF_OUTPUT_ID,
CONF_NUM_LEDS,
CONF_RGB_ORDER,
CONF_MAX_REFRESH_RATE,
)
CODEOWNERS = ["@OttoWinter"]
fastled_base_ns = cg.esphome_ns.namespace("fastled_base")
FastLEDLigh... |
from getgauge.python import step, before_scenario, Messages, data_store
from zapv2 import ZAPv2 as ZAP
import subprocess
import os
import requests
from time import sleep
import datetime
import pprint
zap_proxy = {"apikey":"apikey", "http": "http://127.0.0.1:8090", "https": "http://127.0.0.1:8090"}
zap = ZAP(proxies=z... |
string1 = input('Digite algo: ')
string2 = input('Digite algo: ')
print(f'A quantidade total de caracteres digitados foi {len(string1) + len(string2)}')
|
from setuptools import setup
setup(
name='gzuro',
version='0.1',
description='A simple Graphical User Interface framework',
license='MIT',
py_modules=['gzuro'],
)
|
#
# Copyright 2016 The BigDL 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 applicable law or agreed to in ... |
import win32process
import win32gui
import win32api
import psutil
import time
import tkinter as tk
import tkinter.ttk as ttk
from ttkthemes import ThemedTk
from tkinter import messagebox
import re
import datetime
class TimeTrackerGUI:
def __init__(self, master):
self.master = master
... |
from pycuda.compiler import SourceModule
from pycuda.tools import context_dependent_memoize
from neon.backends.cuda_templates import _ew_types
"""
CUDA kernels for lookup table layers. Kernels are only given for bprop, since
fprop is just a take operation. There is a deterministic kernel and
non-deterministic kernel ... |
# coding: utf-8
import leancloud
from leancloud import Query
from leancloud import LeanCloudError
from data import myUser
from youth_keyDB import YouthDB
import hashlib
query = leancloud.Query('myUser')
keyquery = leancloud.Query('YouthDB')
def checkin(name,password):
result = query.equal_to("name",name)
md5 ... |
from enum import Enum
class TIPO(Enum) :
DATABASE = 1
TABLE = 2
COLUMN = 3
SMALLINT = 4
INTEGER = 5
BIGINT = 6
DECIMAL = 7
NUMERIC = 8
REAL = 9
DOUBLE_PRECISION = 10
CHARACTER_VARYING = 11
VARCHAR = 12
CHARACTER = 13
CHAR = 14
TEXT = 15
TIMESTAMP = 16
... |
from typing import Union, Optional, Callable, Iterable, Any
try: # Assume we're a sub-module in a package.
from utils import (
arguments as arg,
mappers as ms,
numeric as nm,
)
from functions import basic_functions as bf
from functions import array_functions as af
except Import... |
#!/usr/bin/env python -O
"""
This is the test class for testing NHPP model algorithms.
"""
__author__ = "Doyle Rowland"
__email__ = "doyle.rowland@reliaqual.com"
__organization__ = "ReliaQual Associates, LLC"
__copyright__ = 'Copyright 2015 Doyle "weibullguy" Rowland'
# -*- coding: utf-8 -*-
#
# tests.statistic... |
__author__ = 'myersos'
|
from poodle import Object
class Type(Object):
def __str__(self): return str(self._get_value())
class Status(Object):
def __str__(self): return str(self._get_value())
class StatusPod(Object):
def __str__(self): return str(self._get_value())
class StatusNode(Object):
def __str__(self): return str(se... |
from PIL import Image
import numpy as np
import torchvision
import cv2
class MNISTColor(torchvision.datasets.MNIST):
def __init__(self, root, train=True, transform=None, target_transform=None, download=False, dataset_depth=1):
super().__init__(root, train, transform, target_transform, download)
sel... |
from leapp.models import Model, fields
from leapp.topics import SystemFactsTopic
class WhitelistedKernelModules(Model):
"""
whitelisted_modules: list of module names that are considered whitelisted
and are not going to inhibit the upgrade
"""
topic = SystemFactsTopic
whitelisted_modules = fiel... |
import unittest
from runner.render.postproc_robot import postproc_robot
class TestURDFPostProc(unittest.TestCase):
def test_texture_name_into_group(self):
robot = {
'part': {
'model': 'mesh.obj'
}
}
def load_object(name):
return {
... |
# Generated by Django 2.1.1 on 2018-10-20 10:29
import django.contrib.postgres.fields.jsonb
import django.utils.timezone
from django.db import migrations, models
from uuid import uuid4
def fill_hash(apps, schema_editor):
LogEntry = apps.get_model('common', 'LogEntry')
for entry in LogEntry.objects.filter(aut... |
from __future__ import absolute_import
from django.conf import settings
from threading import local
from cobra.core.loading import import_string
class State(local):
request = None
data = {}
env = State()
def get_instance(path, options):
cls = import_string(path)
return cls(**options)
# TODO(dcra... |
"""Tika example get metadata."""
from tika import parser
parsed = parser.from_file("temp.wav")
print(parsed["metadata"])
print(parsed["content"])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.