content stringlengths 5 1.05M |
|---|
import platform
import textwrap
import unittest
from conans.test.utils.conan_v2_tests import ConanV2ModeTestCase
from conans.test.utils.tools import TestClient
class ConanfileSourceTestCase(ConanV2ModeTestCase):
""" Conan v2: 'self.cpp_info' is not available in 'package_id()' """
def test_cppinfo_not_in_pac... |
from test_ruby import TestRuby
|
""" Random comments:
- if song wasn't found it will return 404
- link should be lower-cased
- all spaces and punctuation characters should be deleted
"""
from prismriver.plugin.common import Plugin
from prismriver.struct import Song
class AZLyricsPlugin(Plugin):
ID = 'azlyrics'
def __init__(self, config):
... |
#!/usr/bin/env python
"""
Performs setup of dotfiles and some system options.
See '--help' for usage.
"""
import os
import click
import clckwrkbdgr.jobsequence as JB
setup = JB.JobSequence(
verbose_var_name='DOTFILES_SETUP_VERBOSE',
default_job_dir=[
os.path.join(os.environ['XDG_CONFIG_HOME'], 'setup.d'),
o... |
"""Module with additional types used by the index"""
from binascii import b2a_hex
from typing import TYPE_CHECKING, NamedTuple, Sequence, Tuple, Union, cast
from git.objects import Blob
from git.types import PathLike
from .util import pack, unpack
# typing -----------------------------------------------------------... |
'''
模拟多项式函数的拟合过程
'''
import tensorflow as tf
import tensorflow.keras as ks
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
# 自定义训练集、测试集、权重和偏量
n_train,n_test,true_w,true_b=100,100,[1.2,-3.4,5.6],5
features=tf.random.normal(shape=(n_train+n_test,1))
poly_features=tf.concat([featu... |
import pymongo
import json
from datetime import datetime
import time
# 建立连接
myclient = pymongo.MongoClient("mongodb://202.204.62.145:27017/", username='admin', password='afish1001')
mydb = myclient["runoobdb"]
mycol = mydb["json_data"]
def insert_json_data():
file = open('./2019-02-21-10-19.txt', 'r', encoding="... |
# -*- coding: utf-8 -*-
"""
Django settings for django_backend project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/re... |
# -*- coding: utf-8 -*-
import codecs
import os
import pickle
#import io
#from PIL import Image
import numpy as np
def im_to_cifar(image_array, class_im):
# Input: 3D array (32 x 32 x 3)
im_array_R = image_array[:, :, 0]
im_array_G = image_array[:, :, 1]
im_array_B = image_array[:, :, 2]
byte_a... |
import random
import pandas as pd
from datetime import datetime
import plotly
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Generate Data
x = pd.date_range(datetime.today(), periods=100).tolist()
y = random.sample(range(1, 300), 100)
# Plot figure
fig = go.Figure([go.Bar(x=x, y=y)])
... |
# -*- coding: utf-8 -*-
# @Time : 2020/1/14 上午10:30
# @Author : upcbdipt
# @Project : CDW_FedAvg
# @FileName: reduce_dimension
import os
import numpy as np
import random
import tensorflow as tf
from main.model.autoencoder import AutoEncoderModel
import main.metrics.writer as metrics_writer
from main.utils.model_uti... |
"""
https://www.practicepython.org
Exercise 23: File Overlap
2 chilis
Given two .txt files that have lists of numbers in them, find the numbers
that are overlapping. One .txt file has a list of all prime numbers under
1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers... |
class SellsyAuthenticateError(Exception):
pass
class SellsyError(Exception):
def __init__(self, sellsy_code_error, message):
super(SellsyError, self).__init__(message)
self.sellsy_code_error = sellsy_code_error
self.message = message
def __str__(self):
return '{} - {}'.fo... |
from datetime import datetime
import os
import logging
import numpy as np
import pandas as pd
import pystore
from decimal import Decimal
from tests.fixtures import Fixes
from src.crypto_accountant.bookkeeper import BookKeeper
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
pd.set_option("display.expand_... |
import datetime
from django.db import models
from django.db.models import signals
from django.conf import settings
from django.utils import simplejson as json
from django.dispatch import dispatcher
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
... |
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2021
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular software products
# made up of hun... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import json
import glob
import logging
import re
import pandas
import numpy as np
from collections import defaultdict
from collections import OrderedDict
data_path = './'
n = 0
class data_passport:
def __init__(self):
self.n_conf_files = 0... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import os
# In[ ]:
mydir = os.getcwd()
result = []
for file in os.listdir(mydir):
if file.endswith("-0.csv"):
result.append(os.path.join(file))
#print(os.path.join(file))
sorted_list_0 = sorted(res... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tables
======
The table generation process use a :class:`TableGenerator` to gather all the
cells of the table. The methods :meth:`TableGenerator.get_table` and
:meth:`TableGenerator.get_long_table` returns the flowable objects to add to
the story.
Those methods take ... |
from __future__ import absolute_import
import io
import json
import os
import subprocess
import sys
import uuid
from . import __version__
from .support import Popen
class CredentialProvider(object):
def __init__(self):
if sys.platform.startswith("win"):
self.exe = [
os.path.j... |
"""Build the desired software environment"""
import sys
import os
import os.path
from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '../..')))
from scripts.authentication.service_principal import ws... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Function
import numpy as np
from network import *
from loss import *
from data import DataGenerator
import match
class UniNet:
def __init__(
self,
input_w=512,
input_h=64,
... |
import re
import requests
import argparse
import sys
parser = argparse.ArgumentParser(description='Load VitaDock exports into Runalyze.com')
parser.add_argument('-k', '--key', required=True, help='The personal API for Runalyze.com')
parser.add_argument('-t', '--type', required=True, help='The type of data set to load.... |
from dubbo_client import ApplicationConfig, ZookeeperRegistry, DubboClient, DubboClientError
service_interface = 'com.truthso.monitor.service.CompareService'
registry = ZookeeperRegistry('127.0.0.1:2181')
compare_provider = DubboClient(service_interface, registry, version='1.0.0', group='gaopin')
print(compare_provid... |
# Approach 1:
def Remove_Row_with_Custom_Element(Test_list, Check_list):
for row in Test_list:
for ele in Check_list:
if ele in row:
Test_list.remove(row)
return Test_list
Test_list = [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
Check_list = [3, 10, 19, 29,... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
from japandas.io.estat import EStatReader
from pandas_datareader import data
_ohlc_columns_jp = ['始値', '高値', '安値', '終値', '出来高', '調整後終値*']
_ohlc_columns_en = ['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
def DataReader(symbols... |
#!/usr/bin/env python3
import sys
import datetime
import pytz
from traffic.core.api import getOptimalRouteTime
def main():
origin_address = "Savoy+Ct,+London+WC2R+0EZ"
destination_address = "Francis+St,+Westminster,+London+SW1P+1QW"
traffic_model = "pessimistic"
startTime = datetime.datetime(2020, ... |
# Class for a server
class fprint:
@staticmethod
def cmd(string, prefix="[$] ", suffix="", end="\n"):
print(prefix + string + suffix, end=end)
class Identifier:
def __init__(self):
self.re = __import__("re")
def is_ip(self, obj):
if self.is_string(obj):
real_ip =... |
from dataclasses import dataclass
from typing import Dict, List, Iterator, Tuple
import pandas as pd
from covid_model_seiir_pipeline.lib import (
utilities,
)
@dataclass(repr=False, eq=False)
class ODEParameters:
# Core parameters
alpha: pd.Series
sigma: pd.Series
gamma1: pd.Series
gamma2: p... |
# Generated by Django 2.1.3 on 2018-11-15 09:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='wine',
fields=[
('id', models.AutoField(aut... |
from math import sin, cos, tan, radians
angulo = float(input('Digite o angulo que você deseja: '))
seno = sin(radians(angulo))
coseno = cos(radians(angulo))
tangente = tan(radians(angulo))
print('O angulo de {} tem o SENO de {:.2f}'.format(angulo, seno))
print('O angulo de {} tem o COSENO de {:.2f}'.format(angulo, cose... |
# -- coding:UTF-8 --
"""
Python implementation of decentralized update algorithm with multi threads
author: Yue Yang (@The-chosen)
"""
import sys
sys.path.insert(0, '../')
import argparse
import yaml
from math import fabs
from itertools import combinations
from copy import deepcopy
import time
import eventlet
imp... |
#!/usr/bin/env python3
import csv
# Convert the national ELR flat file into a schema YAML
def main():
with open('PDI_fields.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count > 0:
print(f'- name... |
#!/usr/bin/env python
# coding: utf-8
#
# Code (c) 2009 Liam Cooke
# See LICENSE.txt
#
# Content (c) 2009 David Malki !
# See http://wondermark.com/554/
vocab = dict(
location_adj = u"""
neo-noir
alternate-history
ancient
post-apocalyptic
dystopian
VR-simulated
... |
import shlex
from azul import config
from azul.template import emit
emit({
"resource": [
{
"google_service_account": {
"indexer": {
# We set the count to 0 to ensure that the destroy provisioner runs.
# See https://www.terraform.io/docs/p... |
import sublime
import sublime_plugin
from .generic_shell import GenericShell
from .QuickMenu.QuickMenu import QuickMenu
from .macro import Macro
from .progress import ThreadProgress
from .settings import Settings
from .unit_collections import UnitCollections
TERMINALITY_VERSION = "0.3.10"
def plugin_loaded():
S... |
from adjunct.exceptions import (
AdjunctSyntaxError,
AdjunctAttributeError,
)
def is_valid_identifier(name):
"""
Adjunct identifiers:
1) must be valid python identifiers
2) must NOT begin with an underscore
"""
retval = name.isidentifier()
if len(name) > 1:
if name[0] == '_':
retval = False
return re... |
>>> Account = namedtuple('Account', 'owner balance transaction_count')
>>> default_account = Account('<owner name>', 0.0, 0)
>>> johns_account = default_account._replace(owner='John')
>>> janes_account = default_account._replace(owner='Jane')
|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Entrypoints for creating AutoML tasks"""
from typing import Union
from azure.ai.ml._restclient.v2022_02_01_preview.models import (
... |
from __future__ import with_statement, unicode_literals, division, print_function
WITH_STATEMENT = with_statement.compiler_flag
UNICODE_LITERALS = unicode_literals.compiler_flag
DIVISION = division.compiler_flag
PRINT_FUNCTION = print_function.compiler_flag
COMPLETE_FUTURE = WITH_STATEMENT | UNICODE_LITERALS | DIVISI... |
from pymoo.algorithms.online_cluster_nsga3 import OnlineClusterNSGA3
from pymoo.factory import get_problem, get_visualization, get_reference_directions
from pymoo.optimize import minimize
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import ... |
import numpy as np
import pytest
import blm
from tests.conftest import m_needs_pyplot
@pytest.mark.parametrize("model_param", [dict(m_lo=1.1, m_up=0.9, c_lo=0.1, c_up=0.2)])
@pytest.mark.parametrize("x_init", [None, np.array(0.0)])
def test_constructor(model_param: dict, x_init: np.ndarray):
bl_model = blm.Backl... |
# -*- coding: utf-8 -*-
import scrapy
import json
from jobs.items import JobsItem
from urllib import quote
class LagouSpider(scrapy.Spider):
name = 'lagou'
allowed_domains = ['www.lagou.com']
start_urls = ['https://www.lagou.com/jobs/']
positionUrl = 'https://www.lagou.com/jobs/positionAjax.json?'
... |
# -*- coding: utf-8 -*-
"""\
Differnt output tests.
"""
from __future__ import unicode_literals, absolute_import
import io
from nose.tools import eq_
from segno_mimos import pyqrcode
try:
from .test_eps import eps_as_matrix
from .test_png import png_as_matrix
from .test_svg import svg_as_matrix
except (Valu... |
from . import cv_processing
from .camera_opencv import Camera
import os
from flask import Flask, redirect, render_template, Response, send_from_directory
from .disc import d as discerd
from .blueprints.clocker.inout_blueprint import in_page
import psycopg2
app = Flask(__name__.split(".")[0])
app.register_blueprint(in_... |
from .followers import *
from .posts import *
from .authors import *
from .likes import *
from .inbox import *
from .comments import *
from .auth import *
|
import pkg_resources
import unittest
import gzip
import goenrich
class TestRead(unittest.TestCase):
def test_ontology(self):
G = goenrich.obo.ontology('db/go-basic.obo')
def test_ontology_from_file_obj(self):
with open('db/go-basic.obo') as f:
G = goenrich.obo.ontology(f)
... |
import pandas as pd
import numpy as np
import os
import re
# User Input
inputfile = input('What is the directory of your input file eg... D:/FILES/ALS_DRINKING-ALGAE_WATER_201807101206.xlsx: ')
seperator = input('what is the delimiter for cells output? eg: | or , : ' )
columntosplit = input('what is the heading for the... |
#!/usr/bin/python
from beem import Hive, Steem
from beem.account import Account
from beem.amount import Amount
from beem.block import Block
from beem.nodelist import NodeList
import pandas as pd
def init():
data = {'exchange_name': [],
'account_name' : [],
'trade_date':[],
'buy... |
from django.urls import path
from .views import CarView, RateView, PopularView, CarViewSet, CarsRatingsViewSet
from rest_framework.routers import DefaultRouter
app_name = "cars"
router = DefaultRouter()
router.register(r'cars', CarViewSet)
router.register(r'cars', CarsRatingsViewSet)
urlpatterns = router.urls
urlpatt... |
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
CHAT_ID = os.getenv('CHAT_ID')
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-i6o5!@e5(!*exd6xpv7-+)1p!3=k_2#fb6xhsb&*3y*&z6vknt'
DEBUG = True
ALLOWED_HOST... |
#coding=utf-8
import os
def rename():
path=input("请输入路径(例如D:\\\\Jason):")
name=input("请输入开头名:")
startNumber=input("请输入开始数:")
fileType=input("请输入后缀名(如 .jpg、.txt等等):")
endSplit = input("请输入分隔符(如 佛系小吴_01_ 01 _.ext) : ")
print("正在生成以"+name+startNumber+fileType+"迭代的文件名")
count=0
filelist... |
import setuptools
VERSION = "20.6.0"
TITLE = "aragog"
DESCRIPTION = "A better python scraper."
URL = "https://www.cameroncairns.com/"
DOC = DESCRIPTION + " <" + URL + ">"
AUTHOR = "Cameron Cairns"
AUTHOR_EMAIL = "cameron@cameroncairns.com"
LICENSE = "Apache License 2.0"
COPYRIGHT = "Copyright (c) 2020 Cameron Cairns"
... |
import requests
import pandas as pd
import ftplib
import io
import re
import json
try:
from requests_html import HTMLSession
except Exception:
print("""Warning - Certain functionality
requires requests_html, which is not installed.
Install using:
... |
import pygame
import math
import random
from pygame.locals import *
def main():
"""Main game execution
"""
game_init() # initializing game
load_resources() # loading game resources
game_loop() # looping through game
def game_init():
"""Initializing game
"""
# initializing global variab... |
from .views import IndexView
from sanic_router import Include, Url
routes = (
Url('', IndexView.as_view(), name='index'),
Url('schema/', Include('tests.example.schema.routes', namespace='schema')),
)
|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import protos.cisco_mdt_dial_in_pb2 as cisco__mdt__dial__in__pb2
class gRPCConfigOperStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Ar... |
import numpy as np
import collections
from operator import itemgetter
np.set_printoptions(linewidth=1024, edgeitems=1000)
delta = {'N': (-1, 0), 'W': (0, -1), 'E': (0, 1), 'S': (1, 0)}
inv_delta = {v: k for k, v in delta.items()}
def distance(p1, p2):
return np.array(p2) - np.array(p1)
def manhattan_distance(p... |
import binascii
from helper import dump2file
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
def hex2bin(hexStr):
return binascii.unhexlify(hexStr)
def verfiy_candidate_signature(public_address, signature, name):
"""
... |
## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
ASN.1 (Abstract Syntax Notation One)
"""
import random
from scapy.config import conf
from scapy.error import Scapy_E... |
import pymysql
# from fj_ftx import settings
#
# MYSQL_HOSTS = settings.MYSQL_HOSTS
# MYSQL_USER = settings.MYSQL_USER
# MYSQL_PASSWORD = settings.MYSQL_PASSWORD
# MYSQL_PORT = settings.MYSQL_PORT
# MYSQL_DB = settings.MYSQL_DB
MYSQL_HOSTS = 'cdb-4sj903z8.bj.tencentcdb.com'
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'andyla... |
import csv
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import time
URL = 'https://columbian.gwu.edu/2015-2016'
response = requests.get(URL)
html = response.content
soup = BeautifulSoup(html, 'lxml')
all_pages = soup.select('.menu-mlid-1117 > ul > li > a')
all_pages_rows = []
all_... |
import pytest
from rest_framework.test import APIRequestFactory
from wagtail.api.v2.utils import BadRequestError
from wagtail.core.models import Page
from django.conf import settings
from src.wagtail_rest_pack.comments.create import CreateCommentAPIView
from .factory import new_comment_data
from .help import cleanup_... |
import operator
from datetime import timedelta
from functools import reduce
import re
from itertools import chain
from typing import Union, List
import parsy
from parsy import string, Parser
from core.parse_util import lexeme, float_p, integer_p
# See https://en.wikipedia.org/wiki/Unit_of_time for reference
# The o... |
# Reference: https://note.com/agw/n/nc052420f3c37
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
r = [255,0,0]
b = [0,0,255]
i = [75,0,130]
v = [159,0,255]
e = [0,0,0]
w = [255,255,255]
imageOff = [
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class UnvalidEncodingAESKey(Exception):
pass
class AppIdValidationError(Exception):
pass
class InvalidSignature(Exception):
pass |
#!/usr/bin/python
import sys
import getopt
import jieba
jieba.dt.cache_file = 'jieba.cache.new'
input_path = 'input.txt'
output_path = 'output.txt'
def scut2word(input_path, output_path):
input_fd = open(input_path, "r")
output_fd = open(output_path, "w")
for line in input_fd:
print("[Info] Or... |
from datanodes.core.utils import dumpException
from datanodes.graphics.graphics_edge import GraphicsEdge
DEBUG = False
class SceneHistory():
def __init__(self, scene):
self.scene = scene
self.history_limit = 32
self._hostory_modified_listeners = []
self.clear()
def... |
import uuid
from datetime import datetime
from django.db import models
from apps.user.models import User
# Create your models here.
class Category_Article(models.Model):
"""
分类
"""
name = models.CharField(max_length=100)
order = models.IntegerField(default=0,verbose_name='排序')
add_time = mo... |
"""Example program that shows how to attach meta-data to a stream, and how to
later on retrieve the meta-data again at the receiver side."""
import time
from pylsl import StreamInfo, StreamOutlet, StreamInlet, resolve_stream
# create a new StreamInfo object which shall describe our stream
info = StreamInfo("MetaTest... |
from __future__ import (
absolute_import,
unicode_literals,
)
import six
from OpenSSL import crypto
from twisted.internet import (
endpoints,
reactor,
ssl,
task,
)
from twisted.web import (
resource,
server,
)
from pysoa.common.transport.http2_gateway.backend.base import BaseHTTP2Back... |
# -*- coding: utf-8 -*-
from django.db import models
class Task(models.Model):
pass
class TaskExecution(models.Model):
pass
|
#!/usr/bin/env python
import argparse
from common import Example, Fact, Rule, Theory, TheoryAssertionRepresentationWithLabel
import json
import problog
from problog.program import PrologString
from problog.core import ProbLog
from problog import get_evaluatable
from problog.formula import LogicFormula, LogicDAG
from p... |
from django.db import models
import datetime
# Create your models here.
class Player(models.Model):
nickname = models.CharField(blank=False, max_length=50)
name = models.CharField(blank=True, default='', max_length=100)
class Map(models.Model):
name = models.CharField(blank=False, max_length=50)
ver... |
import wrangle
import pandas as pd
# define the urls for data
base_url = 'https://zenodo.org/record/1215899/files/2008_Mossong_POLYMOD_'
contact_common = 'contact_common.csv?download=1'
participant_common = 'participant_common.csv?download=1'
participant_extra = 'participant_extra.csv?download=1'
household_common = '... |
import yaml
import numpy as np
from interpolation.splines import UCGrid, CGrid, nodes
from interpolation.splines import filter_cubic, eval_cubic
from mldftdat.dft.xc_models import NormGPFunctional
from sklearn.gaussian_process.kernels import RBF
from itertools import combinations
from argparse import ArgumentParser
fro... |
import typing
import json
import uuid
from copy import deepcopy
from lib.crypto.keystore import KeyStore
from ids.models import Id
def create_verifiable_presentation(
id: Id,
attribute_groups: typing.Set[str],
password: str,
entropy: str,
) -> dict:
# Initialize the keystore
keypair = id.owne... |
"""
Interactive command tool for chaperone
Usage:
telchap <command> [<args> ...]
"""
# perform any patches first
import chaperone.cutil.patches
# regular code begins
import sys
import os
import asyncio
import shlex
from docopt import docopt
from chaperone.cproc.client import CommandClient
from chaperone.cproc.v... |
from . import views
from django.urls import path
urlpatterns = [
path('', views.perfil, name='perfil-usuario'),
path('alterar-informacoes/<int:id>/', views.alterar_informacoes, name='alterar-informacoes'),
path('excluir-animal/<int:id_animal>/', views.excluir_animal, name='excluir-animal'),
path('edita... |
raise NotImplementedError("hmac is not yet implemented in Skulpt")
|
from collections import OrderedDict
from enum import Enum
import joblib
import numpy as np
from ptype.utils import project_root
TYPE_INDEX = 0
MISSING_INDEX = 1
ANOMALIES_INDEX = 2
def _get_unique_vals(col, return_counts=False):
"""List of the unique values found in a column."""
return np.unique([str(x) for... |
import numpy as np
import Op, Interface
import ISCV
from GCore import Recon
class PointsFromDetections(Op.Op):
def __init__(self, name='/Reconstruct 3D from Dets', locations='', calibration='', tiltThreshold=0.0002, x2dThreshold=0.01,
x3dThreshold=30.0, minRays=3, seedX3ds='', showContributions=True, pointSize=8... |
from etna.transforms.nn.pytorch_forecasting import PytorchForecastingTransform
|
__strict__ = True
import httpx
from core.config import Config
async def client_fetch(endpoint: str, payload: dict = None) -> dict:
payload.update({"key": Config.STEAM_API_KEY})
async with httpx.AsyncClient() as client:
result = await client.get("https://api.steampowered.com" + endpoint, params=paylo... |
from __future__ import unicode_literals
from django.db import models
class Comment(models.Model):
"""Describes the comment"""
name = models.CharField(max_length=128)
userpic = models.URLField()
url = models.URLField()
text = models.TextField()
like = models.PositiveIntegerField(default=0)
... |
from .internal import _curry1, _curry2, _curry3, _arity
from .function import empty, curry_n, lift
from .internal import _equals, _get_arity, _fix_arity, _is_function
__all__ = ["all_pass", "any_pass", "and_", "lt", "gt", "both", "complement",
"if_else", "cond", "or_", "not_", "is_empty", "until", "when"]
... |
from decimal import Decimal
from django.conf import settings
from django.utils.dateparse import parse_date
from mt940_writer import Account, Balance, Statement, Transaction, TransactionType
from . import MT940_STMT_LABEL
from .utils import (
retrieve_all_transactions, get_daily_file_uid, get_or_create_file,
r... |
# -*- coding: utf-8 -*-
"""
seasonedParser.__init__
Set module settings.
"""
from .__version__ import __version__
|
# version 2.0.0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class AttentionXCosNet(nn.Module):
def __init__(self, conf):
super(AttentionXCosNet, self).__init__()
self.embedding_net = nn.Sequential(
nn.Conv2d(32, 16, 3, padding=1),
nn.BatchNorm2d(16),
... |
from unittest import TestCase
from piccolo.columns import ForeignKey, Varchar
from piccolo.columns.base import OnDelete, OnUpdate
from piccolo.table import Table
class Manager(Table):
name = Varchar()
class Band(Table):
"""
Contains a ForeignKey with non-default `on_delete` and `on_update` values.
... |
import numpy as np
from sklearn.base import BaseEstimator
from keras_preprocessing.image import Iterator
from tensorflow.keras.utils import Sequence
from sklearn.utils.validation import indexable
class FastaIterator(Iterator, BaseEstimator, Sequence):
"""Base class for fasta sequence iterators.
Parameters
... |
import jpype
from jpype.types import *
import common
import collections.abc
class CollectionTestCase(common.JPypeTestCase):
def setUp(self):
super(CollectionTestCase, self).setUp()
def testCollection(self):
collection = jpype.java.util.ArrayList()
collection.add(1)
collection... |
import math
import xml.etree.ElementTree as ET
from optparse import OptionParser
svg_prefix = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
... |
from Games.GameLogic import InARowGameSquareBoard
import numpy as np
from Games.GameLogic import bitboard
class MnkInARow(InARowGameSquareBoard):
default_kwargs = {
"rows": 10,
"columns": 10,
"in_a_row_to_win": 6
}
def __init__(self, **kwargs):
super().__init__()
... |
# coding=utf-8
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. 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/L... |
#!/usr/bin/env python
# encoding: utf-8
import numpy as np
import tensorflow as tf
import sys
sys.path.append('..')
from models.run_net import SenseClsNet
from config import cfg
import cv2
import os
from tqdm import tqdm
import zipfile
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def accuracy(img_path, label_file, epoch)... |
""":mod:`autotweet.database` --- Database structure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides methods to get session, get answer, etc.
"""
from __future__ import unicode_literals
from sqlalchemy import (Column, Float, ForeignKey, Integer, String, Table,
UniqueCo... |
# -*- coding: utf-8 -*-
"""
Plotting methods for graphing the distribution of measured quantities such as
reference monitor pollutant concentrations (``ref_distrib()``), meteorological
conditions including temperature and relative humidity (``met_distrib()``),
and the distribution of recording intervals (i.e., the time... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
#Read image
img = cv2.imread('Photos/maimy.jpg',1)
#color vector
color = ('b','g','r')
#https://docs.opencv.org/master/d1/db7/tutorial_py_histogram_begins.html
#iterate chanels to print histogram
for i,col in enumerate(color):
histr = cv2.calcHis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.