content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from argparse import Namespace, ArgumentParser
import os
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import datasets
import torchvision.transforms as transforms
from utils import datautils
import models
from utils import utils
import numpy as np
import PIL
from tqdm import t... | python |
from flask import Flask , request , jsonify , make_response
from flask_cors import CORS
import pymysql
#import config
from config import db_host, db_user, db_passwrd, db_db, config_domain
from check_encode import random_token, check_prefix
from display_list import list_data
from auth import auth
shorty_api = Flask(__... | python |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from beanmachine.ppl.experimental.gp.kernels import all_kernels
from beanmachine.ppl.experimental.gp.likelihoods import all_likelihoods
__... | python |
# 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 u... | python |
from django.urls import path
from . import views
app_name = 'search'
urlpatterns = [
path('theorem', views.SearchTheoremView.as_view(), name='index'),
]
| python |
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.authentication import BasicAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from databa... | python |
from django.urls import path
from . import views
urlpatterns = [
path('config-creator/', views.config_creator, name='config_creator'),
path('data-generator/', views.data_generator, name='data_generator'),
]
| python |
# 导入需要的包文件
from flask import Blueprint, request
from flask_restx import Api, Resource
"""
创建一个蓝图,相当于创建项目组成的一部分,主要是方便我们管理自己的项目;
比如你的项目由很多个子项目构成,那么把为每一个子项目创建一个蓝图来创建对应的接口,好过于
把所有的接口都放在同一个.py文件吧!
这里创建蓝图Blueprint类还有很多其他的参数可选,大家可以看Blueprint类的源码,里面介绍的很清晰,英文不好的童鞋
请自觉学习英文;
"""
app_one_api = Blueprint('app_one_api', __name__)... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... | python |
import numpy as np
import statistics
import pandas as pd
import time
import os
from sklearn.metrics import f1_score, accuracy_score
from sklearn.multiclass import OneVsRestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.svm import SVC
from sklearn... | python |
#!python3
a = (x for x in range(3))
print(next(a))
print(next(a))
print(next(a))
try:
print(next(a)) # -> raises StopIteration
except StopIteration:
print("StopIteration raised")
| python |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
class FFNet(nn.Module):
def __init__(self, input_size, output_size, hidden_size=64):
super(FFNet, self).__init__()
# one hidden layer
self.fc1 = nn.Linear(input_s... | python |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 解法一:44 ms 13.9 MB
import queue
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
... | python |
from __future__ import annotations
import typing as t
from functools import wraps
from graphql import GraphQLArgument
from graphql import GraphQLBoolean
from graphql import GraphQLEnumType
from graphql import GraphQLField
from graphql import GraphQLFloat
from graphql import GraphQLID
from graphql import GraphQLInputF... | python |
# this_dict={
# "brand":'Ford',
# "model":'Mutang',
# "year": 1964
# }
# print(this_dict)
# ####
# # Access items
# x=this_dict['model']
# print(x)
# ## Access items with get method
# x=this_dict.get('model')
# print(x)
# ###########
# # Change value in dictionary
# this_dict['year']=2019
# print(this_d... | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import sys
from echomesh.util.registry.Registry import Registry
def register_module(class_path, *modules, **kwds):
module = sys.modules[class_path]
registry = Registry(class_path, class_path=class_path, **kwds)
... | python |
# Copyright 2020 Akamai Technologies, 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... | python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# =========================================================================== #
# Project : MLStudio #
# Version : 0.1.0 #
# File : regression.py ... | python |
from django import forms
from django.contrib.auth.models import User
class POSTForm(forms.Form):
username = forms.CharField(
label='Username',
max_length=30,
help_text='Enter a unique name for your login',
widget=forms.TextInput(attrs={
'required': 'required',
'title': 'Enter a unique name for your... | python |
#!/usr/bin/env python
# encoding: utf-8
#
# Stylus, Copyright 2006-2009 Biologic Institute
#
# 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.... | python |
from datetime import datetime
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from freezegun import freeze_time
from core.models import CoffeType, Harvest
from core.serializers... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# 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
#
... | python |
"""
Color definitions for various charts
https://htmlcolorcodes.com/color-chart/
"""
colors = {
'orange1': '#E74C3C',
'blue1': '#1B4F72',
'blue2': '#2874A6',
'blue3': '#3498DB',
'blue4': '#85C1E9'
}
| python |
# coding=utf-8
import time
import asyncio
import logging
from asyncio import CancelledError
import aiohttp
import async_timeout
from freehp.extractor import extract_proxies
log = logging.getLogger(__name__)
class ProxySpider:
def __init__(self, config, loop=None):
self._proxy_pages = config.get('proxy... | python |
"""open_discussions constants"""
from rest_framework import status
PERMISSION_DENIED_ERROR_TYPE = "PermissionDenied"
NOT_AUTHENTICATED_ERROR_TYPE = "NotAuthenticated"
DJANGO_PERMISSION_ERROR_TYPES = (
status.HTTP_401_UNAUTHORIZED,
status.HTTP_403_FORBIDDEN,
)
ISOFORMAT = "%Y-%m-%dT%H:%M:%SZ"
| python |
#
from apps.ots.event.signal_event import SignalEvent
from apps.ots.strategy.risk_manager_base import RiskManagerBase
class NaiveRiskManager(RiskManagerBase):
def __init__(self):
self.refl = ''
def get_mkt_quantity(self, signalEvent):
return 100 | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2018-2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# All Rights Reserved.
#
""" System Inventory Kubernetes Application Operator."""
import copy
import docker
from eventlet.green import subprocess
import glob
import grp
import fun... | python |
"""Functions for parsing the measurement data files"""
import yaml
import pkgutil
from flavio.classes import Measurement, Observable
from flavio._parse_errors import constraints_from_string, errors_from_string
from flavio.statistics import probability
import numpy as np
from math import sqrt
import warnings
def _load... | python |
# Generated by Django 2.2.13 on 2020-07-15 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("licenses", "0002_import_license_data"),
]
operations = [
migrations.AlterModelOptions(
name="legalcode",
options={"... | python |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .forms import CreateNewEvent, CreateNewParticipant
from .models import Event,Attendee
from .utils import check_event,generate_event_url, get_event_by_url
from creator.tasks import generate_certificates
def is_logged_in... | python |
import os
import numpy as np
from typing import Any, Dict
import torch
from torch.utils.data import Dataset
from core.utils.others.image_helper import read_image
class CILRSDataset(Dataset):
def __init__(self, root_dir: str, transform: bool = False, preloads: str = None) -> None:
self._root_dir = root_d... | python |
# -*- coding: utf-8 -*-
"""
Contains RabbitMQ Consumer class
Use under MIT License
"""
__author__ = 'G_T_Y'
__license__ = 'MIT'
__version__ = '1.0.0'
import pika
from . import settings
from .exceptions import RabbitmqConnectionError
class Publisher:
"""Used to publish messages on response queue"""
def _... | python |
from .jira.client import JiraClient
from .gitlab.client import GitLabClientWrapper as GitLabClient
| python |
import sys
sys.path.append("../src")
import numpy as np
import seaborn as sns
from scipy.stats import pearsonr
from scipy.special import binom
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import gnk_model
import C_calculation
import utils
... | python |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) The Lab of Professor Weiwei Lin (linww@scut.edu.cn),
# School of Computer Science and Engineering, South China University of Technology.
# A-Tune is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan ... | python |
import os
from aws_cdk import (
core,
aws_ec2 as ec2,
aws_cloudformation as cloudformation,
aws_elasticache as elasticache,
)
class ElastiCacheStack(cloudformation.NestedStack):
def __init__(self, scope: core.Construct, id: str, **kwargs):
super().__init__(scope, id, **kwargs)
se... | python |
import numpy as np
from .base import BaseLoop
from .utils import EarlyStopping
class BaseTrainerLoop(BaseLoop):
def __init__(self, model, optimizer, **kwargs):
super().__init__()
self.model = model
self.optimizer = optimizer
## kwargs assignations
self.patience = kwargs.g... | python |
# Multiple 1D fibers (monodomain), biceps geometry
# This is similar to the fibers_emg example, but without EMG.
# To see all available arguments, execute: ./multiple_fibers settings_multiple_fibers_cubes_partitioning.py -help
#
# if fiber_file=cuboid.bin, it uses a small cuboid test example (Contrary to the "cuboid" e... | python |
import random
from io import StringIO
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style("darkgrid")
def str_convert_float(df):
columns = df.select_dtypes(exclude="number").columns
for col_name in columns:
unique_values = df[col_name].unique()
... | python |
# 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 required by applicable law or agre... | python |
import json
from pyramid.view import view_config
@view_config(route_name='home')
def home(request):
# https://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html
# Response
response = request.response
response.content_type = 'application/json'
response.status_code = 200
# body
... | python |
#!/usr/bin/env python
# -*- coding: utf8 -*-
def btcSupplyAtBlock(b):
if b >= 33 * 210000:
return 20999999.9769
else:
reward = 50e8
supply = 0
y = 210000 # reward changes all y blocks
while b > y - 1:
supply = supply + y * reward
reward = int(re... | python |
import sys,os
import gdal
from gdalconst import *
# Get georeferencing information from a raster file and print to text file
src = sys.argv[1]
fname_out = sys.argv[2]
ds = gdal.Open(src, GA_ReadOnly)
if ds is None:
print('Content-Type: text/html\n')
print('Could not open ' + src)
sys.exit(1)
# Get the g... | python |
"""
Base functions and classes for linked/joined operations.
"""
from typing import Mapping, Callable, Union, MutableMapping, Any
import operator
from inspect import signature
from functools import partialmethod
EmptyMappingFactory = Union[MutableMapping, Callable[[], MutableMapping]]
BinaryOp = Callable[[Any, Any], ... | python |
import os
import re
import boto3
s3 = boto3.resource('s3')
s3_client = boto3.client('s3')
def maybe_makedirs(path, exist_ok=True):
"""Don't mkdir if it's a path on S3"""
if path.startswith('s3://'):
return
os.makedirs(path, exist_ok=exist_ok)
def smart_ls(path):
"""Get a list of files fro... | python |
from sqlalchemy import Column, TIMESTAMP, Float, Integer, ForeignKey, String
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta, declared_attr
'''SQLAlchemy models used for representing the database schema as Python objects'''
Base: DeclarativeMeta = declarative_base()
class Watered(Base):
... | python |
import math
from .settings import pi, PI_HALF, nearly_eq
from .point import Point
from .basic import GeometryEntity
class LinearEntity(GeometryEntity):
def __new__(cls, p1, p2=None, **kwargs):
if p1 == p2:
raise ValueError(
"%s.__new__ requires two unique Points." % cls.__nam... | python |
'''
This program reads the message data from an OVI backup file
(sqlite) create for a NOKIA N95 phone and writes them formated
as XML to stdout.
The backup file is usually located in:
C:\Users\<user>\AppData\Local\Nokia\Nokia Suite/ \
Messages/Database/msg_db.sqlite
Note: the exported ... | python |
import torch.nn as nn
import math
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.residual_function = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)... | python |
import unittest
from parameterized import parameterized as p
from solns.karatsubaMultiply.karatsubaMultiply import *
class UnitTest_KaratsubaMultiply(unittest.TestCase):
@p.expand([
[3141592653589793238462643383279502884197169399375105820974944592,
2718281828459045235360287471352662497757247093699... | python |
média = 0
idademaisvelho = 0
nomemaisvelho = ''
totmulher20 = 0
for p in range(1, 5):
print('-' * 10, '{}ª PESSOA'.format(p), '-' * 10)
nome = str(input('Nome: ').strip())
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ').strip())
média = (média*(p-1)+idade)/p
if p == 1 and sexo in ... | python |
import logging
import numpy as np
X1, Y1, X2, Y2 = range(4)
class ImageSegmentation(object):
"""
Data Structure to hold box segments for images. Box segments are defined by two points:
upper-left & bottom-right.
"""
def __init__(self, width, height):
self.height = height
self... | python |
# -*- coding: utf-8 -*-
from app import app, db, bbcode_parser, redis_store, mail #, q
from flask import request, render_template, redirect, url_for, send_from_directory, abort, flash, g, jsonify
import datetime
import os
from PIL import Image
import simplejson
import traceback
from werkzeug.utils import secure_filena... | python |
# Generated by Django 2.2.4 on 2019-09-10 13:37
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencies = [
('export_readiness', '0055_auto_20190910_1242'),
]
operations = [
m... | python |
import opentrons.execute
import requests
import json
import import_ipynb
import csv
from labguru import Labguru
experiment_id = 512
lab = Labguru(login='login@gmail.com', password='123password')
# get Labguru elements
experiment = lab.get_experiment(experiment_id)
plate_element = lab.get_elements_by_type(experiment_... | python |
import collections
import os
from strictdoc.helpers.sorting import alphanumeric_sort
class FileOrFolderEntry:
def get_full_path(self):
raise NotImplementedError
def get_level(self):
raise NotImplementedError
def is_folder(self):
raise NotImplementedError
def mount_folder(se... | python |
#!/usr/bin/env python2
import sys
sys.path.insert(0, '..')
from cde_test_common import *
def checker_func():
assert os.path.isfile('cde-package/cde-root/home/pgbovine/CDE/tests/readlink_abspath_test/libc.so.6')
generic_test_runner(["python", "readlink_abspath_test.py"], checker_func)
| python |
import numpy as np
import pysam
import subprocess
import argparse
import utils
import os, pdb
MIN_MAP_QUAL = 10
def parse_args():
parser = argparse.ArgumentParser(description=" convert bam data format to bigWig data format, "
" for ribosome profiling and RNA-seq data ")
p... | python |
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if k is None or k <= 0:
return
k = k % (len(nums))
end = len(nums)- 1
self.swap(nums,0,end-k)
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
使用自己的 svm 进行垃圾邮件分类。
"""
import re
import numpy as np
import scipy.io as scio
from nltk.stem import porter
from svm import SVC
def get_vocabs():
vocabs = {}
# 单词的总数
n = 1899
f = open('vocab.txt', 'r')
for i in range(n):
line = f.readl... | python |
# File: C (Python 2.4)
from direct.fsm.FSM import FSM
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from pirates.piratesgui.GuiButton import GuiButton
from pirates.piratesgui import PiratesGuiGlobals
from pirates.piratesbase import PiratesGlobals
from pirates.piratesbase import PLocalizer
from p... | python |
from .constants.google_play import Sort
from .features.app import app
from .features.reviews import reviews
__version__ = "0.0.2.3"
| python |
class memoize(object):
"""
Memoize the result of a property call.
>>> class A(object):
>>> @memoize
>>> def func(self):
>>> return 'foo'
"""
def __init__(self, func):
self.__name__ = func.__name__
self.__module__ = func.__module__
self.__doc__ = ... | python |
# -*- encoding: utf-8 -*-
# Copyright (c) 2019 Stephen Bunn <stephen@bunn.io>
# ISC License <https://opensource.org/licenses/isc>
"""
"""
import pathlib
# the path to the data directory included in the modules source
DATA_DIR = pathlib.Path(__file__).parent / "data"
# the path to the store-locations fil... | python |
"""Prometheus collector for Apache Traffic Server's stats_over_http plugin."""
import logging
import re
import time
import requests
import yaml
from prometheus_client import Metric
CACHE_VOLUMES = re.compile("^proxy.process.cache.volume_([0-9]+)")
LOG = logging.getLogger(__name__)
def _get_float_value(data, keys)... | python |
#
# DeepRacer Guru
#
# Version 3.0 onwards
#
# Copyright (c) 2021 dmh23
#
from src.personalize.reward_functions.follow_centre_line import reward_function
NEW_REWARD_FUNCTION = reward_function
DISCOUNT_FACTORS = [0.999, 0.99, 0.97, 0.95, 0.9]
DISCOUNT_FACTOR_MAX_STEPS = 300
TIME_BEFORE_FIRST_STEP = 0.2
| python |
# terrascript/provider/kubernetes.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:20:43 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.provider.kubernetes
#
# instead of
#
# >>> import terrascript.provider.hashicorp.kubernetes
#
# This is only available for 'official' and ... | python |
import os
import sys
from pathlib import Path
import win32api
from dotenv import load_dotenv
from kivy.config import Config
from loguru import logger
import stackprinter
import trio
load_dotenv()
logger.remove()
logger.add(
sys.stdout,
colorize=True,
format="[ <lr>Wallpaper</> ]"
"[<b><fg #3b3b3b>{lev... | python |
from rest_framework import serializers
from users.api.serializers import UserSerializer
from ..models import Message
class MessageSerializer(serializers.ModelSerializer):
sender = UserSerializer(read_only=True)
receiver = UserSerializer(read_only=True)
class Meta:
model = Message
fields ... | python |
from typing import List, Tuple
import difflib
from paukenator.nlp import Text, Line
from .common import CmpBase
class CmpTokens(CmpBase):
'''Algorithm that compares texts at word level and detects differences in
tokenization (splitting). Comparison works in line-by-line fashion.
USAGE:
comparer = Cm... | python |
from django.contrib import admin
from django.contrib import admin
from .models import subCategory
admin.site.register (subCategory)
# Register your models here.
| python |
import requests
import convertapi
from io import BytesIO
from .exceptions import *
class Client:
def get(self, path, params = {}, timeout = None):
timeout = timeout or convertapi.timeout
r = requests.get(self.url(path), params = params, headers = self.headers(), timeout = timeout)
return self.handle_response(r... | python |
from django.urls import reverse
from django.shortcuts import render
from django.utils import timezone, crypto
from django.core.paginator import Paginator
from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse
from django.views.decorators.http import require_http_methods
from dja... | python |
from tool.runners.python import SubmissionPy
class BebertSubmission(SubmissionPy):
def run(self, s):
positions = [line.split(", ") for line in s.splitlines()]
positions = [(int(x), int(y)) for x, y in positions]
# print(positions)
obj_less = 10000 # if len(positions) != 6 else 3... | python |
from setuptools import setup, find_packages
setup(
name='ysedu',
version='1.0',
author='Yuji Suehiro',
packages=find_packages(),
url='https://github.com/YujiSue/education',
description='Sample codes used for education.'
)
| python |
import re
text = input().lower()
word = input().lower()
pattern = rf"\b{word}\b"
valid_matches = len(re.findall(pattern, text))
print(valid_matches) | python |
import torch
def center_of_mass(x, pytorch_grid=True):
"""
Center of mass layer
Arguments
---------
x : network output
pytorch_grid : use PyTorch convention for grid (-1,1)
Return
------
C : center of masses for each chs
"""
n_batch, chs, dim1, dim2, dim3 = ... | python |
# ---------------------------------------------------------------------
# Dispose Request
# ---------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python modules
... | python |
#!/usr/bin/env python3
# This script will run using the default Python 3 environment
# where LibreOffice's scripts are installed to (at least in Ubuntu).
# This converter is very similar to unoconv but has an option to remove
# line numbers, it is also simpler by being more tailored to the use-case.
# https://github.c... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 23 18:53:28 2019
@author: Rajas khokle
Code Title - Time Series Modelling
"""
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.statto... | python |
if __name__ == '__main__':
import BrowserState
else:
from . import BrowserState
from PyQt5 import QtCore, QtWidgets, QtWidgets
# The Sort dialog, with a grid of sorting buttons
class SortDialog(QtWidgets.QDialog):
# Constant giving the number of search keys
MaxSortKeyCount = 6
############# Signa... | python |
# This script generates the scoring and schema files
# Creates the schema, and holds the init and run functions needed to
# operationalize the Iris Classification sample
# Import data collection library. Only supported for docker mode.
# Functionality will be ignored when package isn't found
try:
from azureml.dat... | python |
#Calculates the median, or middle value, of a list of numbers
#The median is the middle value for an odd numbered list, so median of 1,2,3,4,5
# is 3, and the average of the two center values of an even numbered list
#median of 1,2,3,4 is (2+3)/2 = 2.5
def median(numbers):
med = 0.0
numbers = sorted(numbe... | python |
from .gyaodl import *
__copyright__ = '(c) 2021 xpadev-net https://xpadev.net'
__version__ = '0.0.1'
__license__ = 'MIT'
__author__ = 'xpadev-net'
__author_email__ = 'xpadev@gmail.com'
__url__ = 'https://github.com/xpadev-net/gyaodl'
__all__ = [GyaoDL]
| python |
import torch
from torch.nn import Module
from functools import partial
import warnings
from .kernel_samples import kernel_tensorized, kernel_online, kernel_multiscale
from .sinkhorn_samples import sinkhorn_tensorized
from .sinkhorn_samples import sinkhorn_online
from .sinkhorn_samples import sinkhorn_multiscale
from... | python |
import pytest
from cookietemple.list.list import TemplateLister
"""
This test class is for testing the list subcommand:
Syntax: cookietemple list
"""
def test_non_empty_output(capfd):
"""
Verifies that the list command does indeed have content
:param capfd: pytest fixture -> capfd: Capture, as text, o... | python |
import scrapy
class ImdbImageSpiderSpider(scrapy.Spider):
name = 'imdb_image_spider'
allowed_domains = ['https://www.imdb.com/']
file_handle = open("url.txt", "r")
temp = file_handle.readline()
file_handle.close()
temp += "/mediaindex?ref_=tt_ov_mi_sm"
tmp = list()
tmp.append(temp)
... | python |
'''
伽马变化
'''
import numpy as np
import cv2
from matplotlib import pyplot as plt
# 定义伽马变化函数
def gamma_trans(img, gamma):
# 先归一化到1,做伽马计算,再还原到[0,255]
gamma_list = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]
# 将列表转换为np.array,并指定数据类型为uint8
gamma_table = np.round(np.array(gamma_list)).astype(np... | python |
def findSubstring( S, L):
""" The idea is very simple, use brute-force with hashing.
First we compute the hash for each word given in L and add them up.
Then we traverse from S[0] to S[len(S) - total_length], for each index, i
f the first substring in L, then we compute the total hash for that partiti... | python |
from dagger.input.from_node_output import FromNodeOutput
from dagger.input.protocol import Input
from dagger.serializer import DefaultSerializer
from tests.input.custom_serializer import CustomSerializer
def test__conforms_to_protocol():
assert isinstance(FromNodeOutput("node", "output"), Input)
def test__expos... | python |
"""This is a Python demo for the `Sphinx tutorial <http://quick-sphinx-tutorial.readthedocs.org/en/latest/>`_.
This demo has an implementation of a Python script called ``giza`` which
calculates the square of a given number.
"""
import argparse
def calc_square(number, verbosity):
"""
Calculate the square o... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from sumy.parsers.html import HtmlParser
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer as Summa... | python |
from django.db import models
from searchEngine.models import InternetResult
from search.models import SearchParameters
class TwitterUser(models.Model):
id = models.CharField(max_length=128, primary_key=True)
username = models.CharField(max_length=60)
link = models.URLField()
avatar = models.TextField... | python |
'''
hist_it.py - GPUE: Split Operator based GPU solver for Nonlinear
Schrodinger Equation, Copyright (C) 2011-2015, Lee J. O'Riordan
<loriordan@gmail.com>, Tadhg Morgan, Neil Crowley. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that th... | python |
from unittest import TestCase
from ..mock_ldap_helpers import DEFAULT_DC
from ..mock_ldap_helpers import group
from ..mock_ldap_helpers import group_dn
from ..mock_ldap_helpers import mock_ldap_directory
from ..mock_ldap_helpers import person
from ..mock_ldap_helpers import person_dn
class TestPerson(TestCase):
... | python |
#
# DeepRacer Guru
#
# Version 3.0 onwards
#
# Copyright (c) 2021 dmh23
#
import tkinter as tk
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.axes import Axes
from matplotlib.ticker import PercentFormatter
from src.action_space.action import Action
from src.analyze... | python |
#
# Copyright (c) 2013, Digium, Inc.
# Copyright (c) 2018, AVOXI, Inc.
#
"""ARI client library
"""
import aripy3.client
import swaggerpy3.http_client
import urllib.parse
from .client import ARIClient
async def connect(base_url, username, password):
"""Helper method for easily connecting to ARI.
:param base... | python |
import argparse
import os.path
import shutil
import fileinput
import re
import subprocess
import sys
import time
import os
import glob
import codecs
from pathlib import Path
from typing import Dict, List
from pyrsistent import pmap, freeze
from pyrsistent.typing import PMap, PVector
from typing import Ma... | python |
# -*- coding: utf-8 -*-
import os
import setuptools
PACKAGE = 'dockerblade'
PATH = os.path.join(os.path.dirname(__file__),
'src/{}/version.py'.format(PACKAGE))
with open(PATH, 'r') as fh:
exec(fh.read())
setuptools.setup(version=__version__)
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.