text stringlengths 2 999k |
|---|
from Tkinter import *
def center_gui(gui):
"""
Centers a Tkinter GUI.
:param gui: A Tkinter GUI.
"""
gui.update_idletasks()
x_pos = (gui.winfo_screenwidth()/2) - (gui.winfo_width()/2)
y_pos = (gui.winfo_screenheight()/2) - (gui.winfo_height()/2)
gui.geometry("+%d+%d" % (x_pos, y_pos))... |
import os
import sys
import re
import json
import logging
###from pylons import request, response, session, app_globals, tmpl_context, url as c, config
from pylons import request, response, session, app_globals, tmpl_context as c, config, url
from pylons.controllers.util import abort, redirect
from pylons.decorators ... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/detr.py
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import kombu_fernet
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'kombu_fernet',
'kombu... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: stream_metric_states.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google... |
from time import sleep
import sys
from touchberrypi import TouchberryPi
from touchberrypi import Color
from touchberrypi import Colors
from touchberrypi import Led
from touchberrypi import TouchKey
from simplemqttclient import SimpleMqttClient
def message_handler(client, userdata, msg):
print("Received: " + msg.pa... |
# [START import]
from nitric.api import Queues, Task
# [END import]
async def queues_send():
# [START snippet]
# Construct a new queue client with default settings
queues = Queues()
payload = {"content": "of task"}
# Publish a task to a queue
await queues.queue("my-queue").send(Task(id="uniqu... |
import h5py as h5
from datetime import datetime as dt
import logging
_xrayImageAttributes = [
"Date",
"Time",
"datetime",
"Comment",
"PatientSupport",
"PatientSupportAngle",
"PatientSupportPosition",
"Detector",
"ImageSize",
"PixelSize",
"ROI",
"AcquisitionTime",
"AcquisitionPeriod",
"Wiggl... |
import pandas as pd
import numpy as np
import tempfile
import argparse
from itertools import takewhile
from operator import itemgetter
variant_consequences = {"transcript_ablation": 1,
"splice_acceptor_variant": 2,
"splice_donor_variant": 3,
"sto... |
from sklearn.datasets import load_iris
import pandas as pd
iris_dataset = load_iris()
iris_data = iris_dataset['data'] # objetos
iris_features = iris_dataset['feature_names'] # atributos
iris_targets = iris_dataset['target'] # atributos / classes
iris_target_names = iris_dataset[... |
"""
Collection of style transformations.
Think of it as a kind of color post processing after the rendering is done.
This could be used for instance to change the contrast/saturation; swap light
and dark colors or even change certain colors for other colors.
When the UI is rendered, these transformations can be appli... |
#
# Copyright 2019 Joshua Maglione
#
# Distributed under MIT License
#
from frameClass import TensorFrame as _TensorFrame
from globalVars import _FUNCTION
def _print_tensor_exp(v):
dom = reduce(lambda x, y: x + "U%s x " % (y), range(v-1, 0, -1), "")
arrow = ">-> "
if v > 1:
return dom[:-2] +... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018 CNRS
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... |
# Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import pathlib
from powerrelay.controllers import RelayController
PROJECT_ROOT = pathlib.Path(__file__).parent
#
# Global routes setup
#
def setup_routes(app, lines):
relaycontroller = RelayController(lines)
app.router.add_get('/relays/', relaycontroller.relays)
app.router.add_get('/relays/count', relayco... |
#!/usr/bin/env python
#
# Copyright (c) 2014 Chris Jerdonek. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rig... |
import keras.backend as K
import numpy as np
from keras.initializers import Ones, Zeros
from keras.layers import Input, Conv2DTranspose
from keras.models import Model
from keras_explain.deep_viz_keras.saliency import SaliencyMask
class VisualBackprop(SaliencyMask):
"""A SaliencyMask class that computes saliency ... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import uuid
import sys
import warnings
from collections import namedtuple
from datetime import datetime, timezone
from redis import WatchError
from .compat import as_text, string_type... |
import ctypes
class GD32VF1xxCrc:
class Type(ctypes.Structure):
""" cyclic redundancy check calculation unit
"""
_fields_ = [
("DATA" , ctypes.c_uint32), # Address offset: 0x0, Data register
("FDATA", ctypes.c_uint32), # Address offset: 0x04, Free data register
... |
from visual import *
from math import sin,cos
initialHeight = 4.6
initialVelocity = 10
initialVelocity2 = 10
Angle = 65
Angle2 = 75
bounce_effect = -2
# Set up the display window
scene1 = display(title="Projectile motion zach miller", x=0, y=0, width=800, height=600, range=10, background=color.white, center=(10,init... |
#!/usr/bin/env python3
# Copyright 2021 Broadcom. All Rights Reserved.
##########################################################################################
#
# 20_create_users.py - create new Jira users in a testn Jira Data Center instance
#
#
####################################################################... |
from pathlib import Path
import pytest
from poetry.core.factory import Factory
from poetry.core.toml import TOMLFile
fixtures_dir = Path(__file__).parent / "fixtures"
def test_create_poetry():
poetry = Factory().create_poetry(fixtures_dir / "sample_project")
package = poetry.package
assert package.n... |
#
# 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... |
#!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import functools
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
impor... |
import sys
sys.path.insert(0,"../")
import falco
import proper
import numpy as np
import matplotlib.pyplot as plt
inputs = {}
inputs["Nbeam"] = 1000
inputs["magfacD"] = 1.
inputs["wStrut"] = 0.01
pupil = falco.mask.falco_gen_pupil_LUVOIR_A_final(inputs)
plt.imshow(pupil); plt.colorbar(); plt.pause(0.1)
plt.imshow(... |
import torch
import numpy as np
from .BaseIndex import BaseIndex
from ..container import CellContainer
from ..codec import PQCodec, VQCodec
from ..fn import IVFPQTopk
from ..fn import Topk
from .. import util
from .. import metric
class IVFPQIndex(CellContainer):
def __init__(
self,
d_vector,
n_sub... |
from geminipy.gemini import Gemini
import httpretty
client = Gemini()
TICKER_URL = 'https://api.gemini.com/v1/pubticker/'
ORDERS_URL = 'https://api.gemini.com/v1/book/'
TRADES_URL = 'https://api.gemini.com/v1/trades/'
SYMBOLS_URL = 'https://api.gemini.com/v1/symbols'
def test_should_have_correct_url():
g = Gemi... |
from django.http import HttpResponseForbidden, HttpResponse
from constance import config
import json
def login_required_401(function=None, redirect_field_name=None):
"""
Just make sure the user is authenticated to access a certain ajax view
Found here: https://stackoverflow.com/questions/1003100... |
import six
from nose import SkipTest
from nose.tools import *
from spec.plugin import SpecPlugin
from spec.cli import main
from spec.utils import InnerClassParser, hide
from spec.trap import trap
class Spec(six.with_metaclass(InnerClassParser, object)):
"""
Parent class for spec classes wishing to use inner... |
import torch
from torch_geometric.data import Data, DataLoader, Dataset, InMemoryDataset
import numpy as np
import networkx as nx
import os.path as osp
import os
import pandas as pd
import pickle
import itertools as it
from omegaconf import DictConfig, OmegaConf
import warnings
import datetime
warnings.filterwarnings("... |
from cipher_lmd2231 import cipher_lmd2231
import pytest
@pytest.mark.parametrize('example,expected',[
('OneSingleWord','TsjXnslqjbtwi'),
('lowercase','qtBjwhfxj'),
('UPPERCASE','ZUUJWHFXJ'),
('A sentence with spaces.','F xjsyjshj Bnym xufhjx.')
])
def test_cipher_multiple_values(example, expected):
... |
#!/usr/bin/env python3
import getpass
import smtplib
import socket
import sys
import threading
import time
from email.message import EmailMessage
sys.path.append('.')
from logger.utils.formats import Text
from logger.writers.writer import Writer
#####################################################################... |
from argparse import ArgumentParser, Namespace
from typing import Any, Dict, Generator, Tuple
import numpy as np
from torchvision.datasets import CIFAR100
from wurlitzer import pipes
from composer.datasets.webdataset import create_webdataset
def parse_args() -> Namespace:
args = ArgumentParser()
args.add_ar... |
from ._base_encoder import _BaseEncoder
from .multiclass_encoder import MultiClassEncoder
from .ordinal_encoder import OrdinalEncoder
from .onehot_encoder import OneHotEncoder
from .target_encoder import TargetEncoder
from .woe_encoder import WOEEncoder
from .regression_encoder import RegressionEncoder
__all__ = [
... |
import os
import sys
import glob
import time
import random
import numpy as np
import torch
sys.path.append('../../ProbeParticleModel')
from pyProbeParticle import oclUtils as oclu
from pyProbeParticle import fieldOCL as FFcl
from pyProbeParticle import RelaxOpenCL as oclr
from pyProbeParticle import AuxMap ... |
import pytest
from django.urls import reverse
users = (
('owner', 'owner'),
('manager', 'manager'),
('author', 'author'),
('guest', 'guest'),
('api', 'api'),
('user', 'user'),
('site', 'site'),
('anonymous', None),
)
view_questionset_permission_map = {
'owner': [1, 2, 3, 4, 5],
... |
import asyncio
import functools
from types import FunctionType
from typing import Callable
from weakref import WeakValueDictionary
Decorator = Callable[[FunctionType], FunctionType]
def argument_lock(arg_index: int) -> Decorator:
"""Decorator locking the function to the given argument index."""
def decorato... |
# -*- coding: utf-8 -*-
#BEGIN_HEADER
import sys
import traceback
from biokbase.workspace.client import Workspace as workspaceService
import requests
requests.packages.urllib3.disable_warnings()
import subprocess
import os
import re
from pprint import pprint, pformat
from datetime import datetime
import uuid
## SDK Ut... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.FaceAbilityExtInfo import FaceAbilityExtInfo
class ZolozAuthenticationCustomerFaceabilityIdentifyResponse(AlipayResponse):
def __init__(self):
super(Zolo... |
from flask import Flask, g
from .db import RedisClient
__all__ = ['app']
app = Flask(__name__)
def get_conn():
"""
Opens a new redis connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'redis_client'):
g.redis_client = RedisClient()
return g.re... |
#---------------------------------------------------------------------------
# QR Factorization Using Gram-Schmidt Orthogonalization v.0.0.1
#
# Q,R = qr_gram_schmidt(A)
#
# The worst-case complexity of full matrix Q factorization:
#
# In real case: p = O(5MNlog2(N))
# ... |
from core.advbase import *
from slot.a import *
from slot.d import *
def module():
return Mikoto
class Mikoto(Adv):
a1 = ('cc',0.10,'hp70')
a3 = ('cc',0.08)
conf = {}
conf['slots.a'] = Primal_Crisis()+The_Wyrmclan_Duo()
conf['acl'] = """
`dragon, s=2
`s3, x=5 and not self.... |
from seisflows.tools.config import SeisflowsParameters, SeisflowsPaths, \
ParameterError
PAR = SeisflowsParameters()
PATH = SeisflowsPaths()
import preprocess
class test_preprocess(object):
""" Preprocess integration test
Not yet implemented. The following is just a sketch. None of the
me... |
'''@file score.py
contains functions to score the system'''
import numpy as np
from IPython.core.debugger import Tracer; debug_here = Tracer();
def CER(nbests, references):
'''
compute the character error rate
Args:
nbests: the nbest lists, this is a dictionary with the uttreance id as
... |
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required
from sqlalchemy.exc import IntegrityError
from ..extensions import db
from ..decorators import admin_required
from ..user import User, FailedLogin
from .forms import UserFor... |
import numpy as np
from numpy.testing import (assert_, assert_approx_equal,
assert_allclose, assert_array_equal, assert_equal,
assert_array_almost_equal_nulp, suppress_warnings)
import pytest
from pytest import raises as assert_raises
from scipy import signal
from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read functionality for OGR PDF driver.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
######################... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Read the content of an audio wave file (.wav)
# See: https://docs.python.org/3/library/wave.html
import wave
with wave.open("./test.wav", mode="rb") as wr:
print(wr.readframes(20)) # Read the 20 first frames
print("Num channels:", wr.getnchannels())
pr... |
from ninja import Form, Schema
class Item(Schema):
name: str
description: str = None
price: float
quantity: int
@api.post("/items")
def create(request, item: Item = Form(...)):
return item
|
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.stanza import Error
from sleekxmpp.xmlstream import register_stanza_plugin
from sleekxmpp.plugins import BasePlu... |
import tensorflow as tf
import cfg
import loss
from net import resnet
from net.layers import _conv, upsampling, _conv_nn
import numpy as np
class CenterNet():
def __init__(self, inputs, is_training):
self.is_training = is_training
try:
self.pred_hm, self.pred_wh, self.pred_reg = self._bu... |
import re
import pymc3 as pm
__all__ = [
"Dataset"
]
class Dataset:
def __init__(self, input_specs):
"""
Dataset represents the specs about the input data
Parameters
-------------
input_spec: specification about the distributions of the input given as a lis... |
from flask import render_template, Blueprint
recepies_blueprint = Blueprint('recepies',__name__,template_folder='templates')
@recepies_blueprint.route('/')
def index():
return render_template('index.html') |
sys.path.append("g:/.shortcut-targets-by-id/1as1j06Ce9KOwHXHd8ujnPqBpqZGP503z/backup/Desktop/programs/eye_tools/src/eye_tools")
from analysis_tools import *
# test out Layer object using a stored image file
img = Layer("./002.jpg")
img.load_memmap()
# test by importing directly from a numpy array
img_arr = np.copy(i... |
import mpl_toolkits.mplot3d
from numpy import *
from pylab import *
u = loadtxt("density0.dat")
N = int(sqrt(u.shape[0]))
print("N=%d" % N)
u.shape = (N,N)
fig = figure()
x,y = mgrid[-1:1:N*1j, -1:1:N*1j]
pcolormesh(x,y,u)
colorbar()
show()
fig.savefig('density0000.png')
fig = figure()
u = loadtxt("density1000.dat... |
import random
def gen_pos_numbers_inc_dec(n, up_chance=0.5, start=None):
if not start:
start = int(n/2)
returned = []
for i in range(n):
up = random.random()
if up<up_chance or start < 1:
start += 1
else:
start -= 1
returned.append(start)
... |
from django.contrib.contenttypes.models import ContentType
from django.db.models import signals
from django.conf import settings
from django.utils.translation import ugettext_noop as _
from pirate_forum.templatetags.blobtags import get_models
if "pirate_badges" in settings.INSTALLED_APPS:
from pirate_badges.models... |
"""
Copyright 2016-2017 Peter Urda
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, softwar... |
import nibabel as nib
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import os
import math
import struct
import csv
import time
def gpu_usage():
print('gpu usage (current/max): {:.2f} / {:.2f} GB'.format(torch.cuda.memory_allocated()*1e-9, torc... |
from lib.common import helpers
import base64
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'GetNetLocalGroup',
'Author': ['@harmj0y'],
'Description': ('GetNetLocalGroup'),
'Background' : False,
'OutputExtension... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="xhp_flow", # Replace with your own username
version="0.0.2",
author="xiaohaipeng",
author_email="307153814@qq.com",
description="This is a mini but function competed neur... |
# ---------------------------------------------------------------------
# EventClassificationRule model
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# P... |
class Solution:
def validPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return self._validPalindrome(s, l + 1, r) or self._validPalindrome(s, l, r - 1)
l += 1
r -= 1
return True
... |
"""Run "python setup.py install" to install pyjsonq."""
from setuptools import setup
try:
with open('README.md') as f:
long_description = f.read()
except Exception:
long_description = """
`pyjsonq` is a simple, elegant Python package to Query over any
type of JSON Data. It'll make your life e... |
'''
Command line args
no filtering
sink: run ls in a dir
'''
'''
Created by Paul E. Black and William Mentzer 2020
This software was developed at the National Institute of Standards and Technology
by employees of the Federal Government in the course of their official duties.
Pursuant to title 17 Section 105 of the Un... |
# Copyright (c) 2017, Djaodjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
import os
from glob import glob
from setuptools import setup
package_name = 'respeaker_node'
setup(
name=package_name,
version='1.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_nam... |
import logging
import inspect
import astroid
from ._base_node import NodeEntityBase
class EnumNode(NodeEntityBase):
"""Enum node represents any Enum value
"""
def __init__(self, namespace, parent_node, obj):
super().__init__(namespace, parent_node, obj)
self.name = obj.name
self.... |
# coding: utf-8
from __future__ import unicode_literals
from hashlib import md5
from base64 import b64encode
from datetime import datetime
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_urlencode,
compat_str,
compat_itertools_count,
)
from ..utils impo... |
# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
from enum import Enum
import logging as log
import os.path as osp
import random
import re
import pycocotools.mask as mask_utils
from datumaro.components.extractor import (Transform, AnnotationType,
RleMask, Polygon, Bbox,
LabelCategorie... |
from __future__ import division
from abc import ABCMeta
from collections import OrderedDict, Iterable
from copy import deepcopy
from math import sqrt, floor
from numbers import Real, Integral
from xml.etree import ElementTree as ET
from six import add_metaclass, string_types
import numpy as np
import openmc.checkval... |
from django.urls import path
from . import views
urlpatterns = [
path("<type_>/<ID>/vote",views.voteSolution,name="voteSolution"),
path('delete/<type_>/<ID>', views.deleteIssueSolution, name="deleteIssueSolution"),
path('<ID>/issues/<status>', views.projectIssues, name='projectIssues'),
path('<ID>/solut... |
# -*- coding: utf-8 -*-
from models import NeighborClassifier, NodeClassifier
from node_attack_gcmc import NodeAttackGCMCRunner
class NeighborAttackGCMCRunner(NodeAttackGCMCRunner):
def __init__(self, args):
super().__init__(args)
def num_adversaries(self):
return 2
def get_ordered_adve... |
import pyclesperanto_prototype as cle
import numpy as np
def test_merge_touching_labels():
gpu_input = cle.push(np.asarray([
[
[1, 1, 0, 0, 0],
[0, 2, 2, 0, 3],
[0, 0, 2, 0, 3],
]
]))
gpu_output = cle.create_like(gpu_input)
gpu_reference = cle.push(... |
import socket
import langfile
def ex(args, message, client, invoke):
args_out = ""
if len(args) > 0:
args_out = "\n\n*Attatched arguments %s*" % args.__str__()[1:-1].replace("'", "")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addr = ('185.249.199.220', 1338)
c... |
import utils.util.compute_road_attributes as cra |
import time
from dataclasses import dataclass, field
from flask import Blueprint, current_app
from remote.wrapper import success
# Please keep the blueprint definition at the top uniformly.
index_bp = Blueprint("index", __name__)
_started = time.time()
@index_bp.route("/")
def home():
return success({})
@da... |
# -*- coding: utf-8 -*-
# Copyright © 2019 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... |
import pygame
import time
import sys
import os
class Plane(pygame.sprite.Sprite):
'''
基类plane类:共有数值和数据
'''
def __init__(self,plane_image,screen,plane_pos,health,speed):
'''plane类_init'''
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.image=plane_image[0] ... |
# Visualização Gráfica de Dados
## A biblioteca *seaborn*
A biblioteca *seaborn* foi construída em cima do *matplotlib* e fornece essencialmente duas coisas:
* estilo aos gráficos, o que os torna tipicamente muito mais bonitos visualmente;
* "agrupa" diversos comandos gráficos do *matplotlib* dentro de um único coma... |
# Copyright (c) 2017-present, Facebook, 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 os
import re
import cgi
import time
import traceback
import urllib
import datetime
import StringIO
from supervisor.medusa import producers
from supervisor.medusa.http_server import http_date
from supervisor.medusa.http_server import get_header
from supervisor.medusa.xmlrpc_handler import collector
import meld3... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 14:01:31 2017
@author: hexo
"""
import numpy as np
import matplotlib.pyplot as plt
#配置每次生成的随机数相同
np.random.seed(0)
mu = 200
sigma = 25
x = np.random.normal(mu, sigma, size=500)
print(x)
ax0 = plt.gca()
ax0.hist(x, 20, normed=1, histtype='stepfilled', facecolor='g... |
# TODO: Break this module up into pieces. Maybe group by functionality tested
# rather than the socket level-ness of it.
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool
from urllib3.poolmanager import proxy_from_url
from urllib3.exceptions import (
MaxRetryError,
ProxyError,
ReadTim... |
#!/usr/bin/python3
# import sys
# import time
# from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox
# from PyQt5.QtCore import pyqtSignal, QThreadPool, pyqtSlot, QRunnable, QObject
# class Signals(QObject):
# return_signal = pyqtSignal(str)
# class Thread(QRunnable):
# signal = pyqtSignal(str)
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2018 Edgewall Software
# Copyright (C) 2003-2005 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2005-2006 Matthew Good <trac@matt-good.net>
# Copyright (C) 2005-2006 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is li... |
"""
对 training load data 改写
按比例删除某 label 下的数据
"""
from __future__ import print_function
from PIL import Image
import os
import os.path
import numpy as np
import sys
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
import torch.utils.data as data
from torchvision.datasets.utils import ... |
# coding=utf-8
# Copyright 2022 The Trax 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 a... |
import _plotly_utils.basevalidators
class TickcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="tickcolor",
parent_name="scattersmith.marker.colorbar",
**kwargs,
):
super(TickcolorValidator, self).__init__(
plotly_... |
import os
from datetime import datetime, timedelta
import openpyxl
import xlwt
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management import call_command
from django.shortcuts import reverse
from django.test import Client, TestCase
from django.test.utils import override_settings
from... |
"""
User management form classes
"""
# django
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# library
from bootstrap_datepicker_plus import DatePickerInput
# app
from photos.forms import PhotoForm
from userprofile.models import Photo, Profil... |
import pickle
import pytest
from torchnlp.encoders.text import StaticTokenizerEncoder
@pytest.fixture
def input_():
return 'This is a sentence'
@pytest.fixture
def encoder(input_):
return StaticTokenizerEncoder([input_])
def test_static_tokenizer_encoder(encoder, input_):
tokens = encoder.encode(inp... |
# Support code for cem.py
class BinaryActionLinearPolicy(object):
def __init__(self, theta):
self.w = theta[:-1]
self.b = theta[-1]
def act(self, ob):
y = ob.dot(self.w) + self.b
a = int(y < 0)
return a
class ContinuousActionLinearPolicy(object):
def __init__(self, ... |
"""
Creates a MobileNetV3 Model as defined in:
Andrew Howard, Mark Sandler, Grace Chu, Liang-Chieh Chen, Bo Chen, Mingxing Tan, Weijun Wang, Yukun Zhu, Ruoming Pang, Vijay Vasudevan, Quoc V. Le, Hartwig Adam. (2019).
Searching for MobileNetV3
arXiv preprint arXiv:1905.02244.
"""
# --------------------------------------... |
import os
import imghdr
import cv2
def get_image_file_list(img_file):
imgs_lists = []
if img_file is None or not os.path.exists(img_file):
raise Exception("not found any img file in {}".format(img_file))
img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}
if os.path.is... |
import os,sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import skimage
import numpy as np
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import edge_detection
from skimage import io
from skimage.draw import circle
from scipy.signal import find_peaks
from skimag... |
"""This module defines utilities for reading, writing, and modifying different types of files"""
##################################################
# Import Own Assets
##################################################
from hyperparameter_hunter.settings import G
##################################################
# Im... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the MIT license
# from https://github.com/yukimasano/self-label.
from .htnet import *
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.