text stringlengths 2 999k |
|---|
# Copyright 2012, Nachi Ueno, NTT MCL, 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... |
import sys
from skmultiflow.lazy import KNN
from skmultiflow.drift_detection import ADWIN
from skmultiflow.utils.data_structures import InstanceWindow
from skmultiflow.utils.utils import *
class KNNAdwin(KNN):
""" K-Nearest Neighbors Classifier with ADWIN Change detector
This Classifier is an improvemen... |
from collections import deque
from typing import Deque, Dict, List, Optional, Tuple
from twisted.internet import defer
from twisted.internet.base import ReactorBase
from twisted.internet.defer import Deferred
from twisted.internet.endpoints import HostnameEndpoint
from twisted.python.failure import Failure
from twiste... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from os import getenv
from decorator import decorator
from language_formatters_pre_commit_hooks.utils import run_command
_DEFAULT_MESSAGE_TEMPLATE = '{required_tool} is requir... |
import hashlib
import json
from copy import copy
from datetime import datetime
from itertools import product
from logging import getLogger
from threading import Thread, Event
from time import time
from typing import Union, Any, Sequence, Optional, Mapping, Callable
from .job import TrainsJob
from .parameters import Pa... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import math
import cv2 as cv
import matplotlib.pyplot as plt
circleAreas = []
circleCenters = []
circles = {}
coins = {"500": 0, "100": 0, "50": 0, "10": 0, "5": 0, "1": 0}
original = cv.imread("coins.jpg")
img = original.copy()
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img = cv.medianBlur(img, 5)
ret, thresh = cv... |
import os
import torch
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True) # first position is score; second position is pred.
pred = pred.t() # .t() is T of m... |
from util.tipo import tipo
class S_RESET_CHARM_STATUS(object):
def __init__(self, tracker, time, direction, opcode, data):
print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
count = data.read(tipo.uint16)
offset = data.read(tipo.uint16)
t... |
import os
import re
from pathlib import Path
from setuptools import setup, find_packages #type: ignore
HERE = Path(__file__).parent
_version_file_contents = (HERE / "approvaltests" / "version.py").read_text()
matched = re.search(r'"(.*)"', _version_file_contents)
VERSION = matched.group(1) if matched is not None else... |
#coding: utf-8
'''
MITライセンス このプログラムについては、改変・再配布可能です
著作者: Tomohiro Ueno (kanazawaaimeetup@gmail.com)
Usage: ddqn-multiple-inputディレクトリから実行する。
python main_price_prediction.py
注意:評価する場合は、正解データのリークが起きないようにする。Train,Validation,Testの分割方法に気をつける
このプログラムは、リークを厳密に回避していません!
実行を早くするため、test_term=120000 epochs=1 となっていますが、実際に評価する場合はt... |
# Copyright (c) Facebook, Inc. and its affiliates.
import itertools
import math
from collections import defaultdict
from typing import Optional
import torch
from torch.utils.data.sampler import Sampler
from detectron2.utils import comm
class TrainingSampler(Sampler):
"""
In training, we only care about the "... |
from .downloadQueueItem import DownloadQueueItem
from .vsMetaInfoGenerator import VsMetaInfoGenerator |
"""Contains methods for building XML structures for interacting with IDE
The methods from this file are used for the debugger interaction. Please note
that Python console now uses Thrift structures with the similar methods
contained in `pydevd_thrift.py` file.
"""
import sys
import traceback
from _pydev_bundle import... |
import numpy as np
import tensorflow as tf
from .module import Module
from .dense import Dense
class Embedding(Module):
def __init__(self, n_embeddings, dim,
embedding_init=None,
trainable=True,
name=None):
self._n_embeddings = n_embeddings
self.... |
#
# Copyright 2018 Analytics Zoo 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... |
# -*- coding: utf-8 -*-
"""
pagarmecoreapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
from pagarmecoreapi.api_helper import APIHelper
from pagarmecoreapi.configuration import Configuration
from pagarmecoreapi.controllers.base_controller import BaseController... |
from concurrent.futures import ProcessPoolExecutor
import math
import random
AMOUNT_OF_MATHS = 8
MAX_WORKERS = 8
def do_maths():
for i in range(random.randint(1000000, 3000000)):
final_sqrt = math.sqrt(i)
return final_sqrt
def main():
# Context manager defaults to waiting for all procs to comp... |
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Object templates module."""
from sqlalchemy import orm
from ggrc import db
from ggrc.data_platform import base
class ObjectTemplates(base.Base, db.Model):
"""Object Templates model."""
__tablename... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^store/$', views.store_details, name='store_details'),
url(r'^create/$', views.create, name='store_create'),
]
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.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.protobuf ... |
#!/usr/bin/python
import simple_test
simple_test.test("test5", ["-b", "asdf", "-c", "fdas", "-g", "asdf", "-j", "homer", ])
|
import sys
from textwrap import fill
from shutil import get_terminal_size
from fac.utils import match_game_version
from fac.commands import Command, Arg
class SearchCommand(Command):
"""Search the mods database."""
name = 'search'
arguments = [
Arg('query', help="search string", default=(), na... |
# Copyright (c) 2020 PaddlePaddle 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 applic... |
'''Tests about locks'''
import redis
from common import TestQless
class TestLocks(TestQless):
'''Locks tests'''
def test_malformed(self):
'''Enumerate malformed inputs into heartbeat'''
self.assertMalformed(self.lua, [
('heartbeat', 0),
('heartbeat', 0, 'jid'),
... |
# Import the tests module
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.heisenberg import heisenberg
class TestMyManifold(geomstats.tests.TestCase):
# Use the setUp method to define variables that stay constant
# during all tests. For example, here we test the
# 4-dimensi... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import math
import json
import tensorflow as tf
from lstm_common import *
from sklearn import metrics
from sklearn.base import BaseEstimator
NUM_LAYERS = 2
LSTM_HIDDEN_DIM = 60
LEMMA_DIM = 50
POS_DIM = 4
DEP_DIM = 5
DIR_DIM = 1
EMPTY_PATH = ((0, 0, 0, 0),)
MAX_PATH_... |
# %%
import matplotlib.pyplot as plt
import numpy as np
import warnings
def fftPlot(sig, dt=None, block=False, plot=True):
# here it's assumes analytic signal (real signal...)- so only half of the axis is required
if dt is None:
dt = 1
t = np.arange(0, sig.shape[-1])
xLabel = 'samples'... |
from ._core import make_figure
from ._doc import make_docstring
import plotly.graph_objs as go
_wide_mode_xy_append = [
"Either `x` or `y` can optionally be a list of column references or array_likes, ",
"in which case the data will be treated as if it were 'wide' rather than 'long'.",
]
_cartesian_append_dict... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//h1[@itemprop='name']",
'price' : "//span[@itemprop='price']",
'category' : "//div[@id='breadcrumb']/ul/li/a/span",
'descript... |
import re
from enum import Enum
from .common import PostProcessor
class MetadataParserPP(PostProcessor):
class Actions(Enum):
INTERPRET = 'interpretter'
REPLACE = 'replacer'
def __init__(self, downloader, actions):
PostProcessor.__init__(self, downloader)
self._actions = []
... |
import torch
import random
def create5Dimages(images):
# images : 4D tensor with shape [BT,C,H,W]
T = 16
B = images.size(0) // T
C = images.size(1)
H = images.size(2)
W = images.size(3)
image = torch.tensor([]).cuda()
for b in range(B):
bimage = images[b * T:(b + 1) * T, :, :, ... |
from src import add as ad
from src import sub as sb
import main
from src import add
print("This take two numbers, add them then find the difference between them")
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
result_1 = ad.add(x,y)
print("The sum of the two figures is: ",res... |
# -*- coding: utf-8 -*-
"""
Eve
~~~
An out-of-the-box REST Web API that's as dangerous as you want it to be.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
.. versionchanged:: 0.5
'SERVER_NAME' removed.
'QUERY_WHERE' added.
'QUERY_SO... |
from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class User(AbstractUser):
"""Default user for RealzHub."""
#: First and last name do not cover name patterns around the globe
n... |
import sys
import os
import subprocess
#Read the docs
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
#if read_the_docs_build:
subprocess.call('cd ../; doxygen config.doxy', shell=True)
# -- General configuration ------------------------------------------------
# Add any paths that contain templa... |
"""
Provide a mock cover platform.
Call init before using it in your tests to ensure clean test data.
"""
from homeassistant.components.cover import (
SUPPORT_CLOSE,
SUPPORT_CLOSE_TILT,
SUPPORT_OPEN,
SUPPORT_OPEN_TILT,
SUPPORT_SET_POSITION,
SUPPORT_SET_TILT_POSITION,
SUPPORT_STOP,
SUPPO... |
"""Support for Tinkerforge Remote Switch."""
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP
from tinkerforge.bricklet_remote_switch_v2 i... |
from objects.modulebase import ModuleBase
from utils.formatters import cleanup_code
API_URL = 'http://rextester.com/rundotnet/api'
LANG_CODES = {
'c#': 1,
'cs': 1,
'vb': 2,
'visualbasic': 2,
'f#': 3,
'java': 4,
'python2': 5,
'py2': ... |
import unittest
from drunken_python import int_to_str, str_to_int
class Test(unittest.TestCase):
def test_int_to_str(self):
self.assertEqual(int_to_str("4"), 4)
self.assertEqual(int_to_str("-4"), -4)
def test_str_to_int(self):
self.assertEqual(str_to_int(4), "4")
self.assertEqu... |
def get_span(spans, row, column):
"""
Gets the span containing the [row, column] pair
Parameters
----------
spans : list of lists of lists
A list containing spans, which are lists of [row, column] pairs
that define where a span is inside a table.
Returns
-------
span : ... |
r"""Integral condition.
This short example demonstrates the implementation of an integral boundary
condition
.. math::
\int_\Gamma \nabla u \cdot \boldsymbol{n} \, \mathrm{d}s = 1
on a part of the boundary of the domain :math:`\Gamma \subset \partial \Omega`
for the Laplace operator. In this example, :math... |
import math, random
class MCTSNode:
def __init__(self, state = None, parent = None):
self.state = state
self.visits = 0
self.score = 0.0
self.children = {} # dict of actions to successor nodes
self.parent = parent
self.is_terminal = state.is_terminal()
self.i... |
import os
import datetime
import uuid
import logging
from time import sleep
import gevent
from gevent.wsgi import WSGIServer
from flask import Flask, jsonify
from kazoo.client import KazooClient, EventType
from kazoo.exceptions import NodeExistsException, NoNodeException
logging.basicConfig()
zoo_hosts = os.getenv('... |
from libnum import *
# 以下为rsa加密,signature需要调换公钥与私钥的位置
p = 137
q = 131
n = p * q
e = 3 # public key (n , e)
d = 11787 #private key (n, d)
m = 513
# # # 加密 # # #
# # # directly # # #
# encrypt dir
c = pow(m, e, n)
print("encrypt", c)
# decrypt
m = pow(c, d, n)
print("decrypt", m)
# # # undirectly # # #
# dP = e-1... |
"""
新增功能:
1.自动排序,根据基金的估值自动从涨幅大到小排序
2.显示上一分钟的跟这一分钟的涨幅比较的上升(或下降)箭头
"""
import requests, openpyxl, base64, json, sys,re
import os, shutil, hmac, hashlib, urllib
from time import sleep
import ast, threading, _tkinter
import tkinter as tk
from tkinter import ttk
import datetime, time
from d... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
#
# Author: Mark Olesen <mark.olesen@esi-group.com>
#
# Legal Notice
# ------------
# OPENFOAM is a trademark owned by Ope... |
# -*- coding: utf-8 -*-
#
# Karl Keusgen
#
# 2019-11-24
# the firts gRPC protobuf based application of mine
#
# 2019-12-06
# put into a new structure
#
# 2019-12-31
# detached the LANWAN Check funtionality from the multusLAN process
#
import sys
import time
import subprocess
import os
import configparser
sys.path.appe... |
#!/usr/bin/env python
import os
import sys
from setuptools import find_packages, setup
from flat_json_widget import get_version
if sys.argv[-1] == 'publish':
# delete any *.pyc, *.pyo and __pycache__
os.system('find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf')
os.system('python setup.py sdis... |
MACS_VERSION = "3.0.0a7"
MAX_PAIRNUM = 1000
MAX_LAMBDA = 100000
FESTEP = 20
BUFFER_SIZE = 100000 # np array will increase at step of 1 million items
READ_BUFFER_SIZE = 10000000 # 10M bytes for read buffer size
N_MP = 2 # Number of processers
|
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
import requests
app = Flask(__name__)
# model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For ... |
import unittest
from asq.queryables import Queryable
from asq.test.test_queryable import infinite, TracingGenerator
class TestSelectManyWithCorrespondence(unittest.TestCase):
def test_select_many_with_correspondence(self):
a = ['Alice', 'Bob', 'Chris']
b = Queryable(a).select_many_with_corresponde... |
# -*- coding: utf-8 -*-
# type: ignore
# copyright: (c) 2020 by Jesse Johnson.
# license: Apache 2.0, see LICENSE for more details.
'''Provide documentation task-runner.'''
import textwrap
from invoke import task
from . import config
@task
def lint(ctx):
'''Check code for documentation errors.'''
ctx.run('... |
#!/usr/bin python3
"""
<Description of the programme>
Author: Pouria Hadjibagheri <pouria.hadjibagheri@phe.gov.uk>
Created: 06 Dec 2020
License: MIT
Contributors: Pouria Hadjibagheri
"""
# Imports
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Python:... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, EngLandGR and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class ContextofOrganization(Document):
pass
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/collectible/collectible_parts/shared_sculpture_goldinlay_02.iff... |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function
import io
import os
import tarfile
import pytest
from pipenv.patched import pipfile
from pipenv.project import Project
from pipenv.utils import temp_environ
from pipenv.vendor.vistir.path import is_in_path
from pipenv.vendor.delegator impor... |
from flask import Flask, flash, render_template, send_file, request
from flask_bootstrap import Bootstrap
from werkzeug.datastructures import MultiDict
from xml.etree import ElementTree
import requests
import config
import io
from forms import PcapForm
app = Flask(__name__)
app.secret_key = config.secret_key
app.confi... |
"""
Precomputers IO
---------------
Module which groups all the functions related with input-output precomputation
of useful data from raw, or just clean data.
"""
import os
import shelve
import datetime
def generate_namefile(pathfolder, methodvalues):
"""Generate a namefile from other information."""
date... |
from . import api
from flask import jsonify
@api.app_errorhandler(404)
def page_not_found(e):
response = jsonify({
'code': -100404,
'error': 'page not found'
})
response.status_code = 404
return response
@api.app_errorhandler(403)
def forbidden(e):
response = jsonify({
'cod... |
# -*- coding: utf-8 -*-
# Copyright 2016 Dravetech AB. All rights reserved.
#
# The contents of this file are 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/LI... |
import numpy as np
import pandas as pd
def hampel_filter_df(df: pd.DataFrame, vals_col: str, time_col=None, win_size=30, num_dev=3, center_win=True) -> pd.DataFrame:
"""
This function takes in dataframe containing time series of values, applies Hampel filter on
these values, and returns dataframe consisti... |
from django.contrib.auth.models import User
from django.http import FileResponse, Http404
from django.shortcuts import render, get_object_or_404
from os.path import splitext
from .models import (Certification, Education, Focus, ProfessionalSkill,
Profile, Project, ProjectCategory, Recommendation,
... |
# Copyright (c) 2003-2005 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, o... |
from django.shortcuts import render
from django.views.generic import ListView
# Create your views here.
class Posts(ListView):
pass |
def get_additional_group_ids(username):
return [g.gr_gid for g in grp.getgrall() if username in g.gr_mem]
|
class Parameter(object):
"""A continuous variable with optional constraints.
Args:
name: Name of the parameter.
lower_bound: Minimum value of the parameter.
upper_bound: Maximum value of the parameter.
"""
def __init__(self, name: str, lower_bound: float,
... |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... |
from instruction import Instruction
from program import Program
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from span import Span
op_set = set(['+', '-', '<', '>', '[', ']', '.', ','])
class Op(Instruction):
def __init__(self, op: str, span: 'Span'):
assert op in op_set, 'Invalid operation ' ... |
from .schema import Base, User
import uuid
import json
from datetime import datetime
import os
from sqlalchemy import create_engine, distinct, or_
from sqlalchemy.orm import sessionmaker
class DbStore(object):
def __init__(self, **kwargs):
if kwargs.get('db_type', 'postgresql') == 'mysql':
hos... |
import sys, os
with open(sys.argv[1], 'r') as fd:
content = '\n'.join(line.strip() for line in fd if line.strip())
if len(sys.argv) == 3:
content = content.replace('Win32', sys.argv[2]).replace('x64', sys.argv[2])
with open(sys.argv[1], 'w') as fd:
fd.write(content)
|
def calculate_differential(data,m,c):
error1 = calculate_differential(m + acuracy,c,data)
error2 = calculate_differential(m + acuracy * ((3 ** (1 / 2)),c - acuracy * ((3 ** (1 / 2))),data)
error3 = calculate_differential(m - acuracy * ((3 ** (1 / 2)),c - acuracy * ((3 ** (1 / 2))),data)
print("iterati... |
import os
from copy import deepcopy
import toml
CONFIG_FILES = ["/etc/fas2ipa/config.toml", "config.toml"]
DEFAULT_CONFIG = {
# We batch our queries (groups, users, memberships, etc).
# How many objects maximum should be in each request?
"chunks": 30,
# Record and replay requests to FAS (for testing... |
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Builder the prepare diff in special format between current
instance state and proposed content."""
import collections
from flask import g
from ggrc.utils.revisions_diff import meta_info
def get_lates... |
from typing import Union, List
from .workers_cheapening import * # noqa
from ..base import OptionsGroup
from ..typehints import Strlist
from ..utils import listify
class MuleFarm:
"""Represents a mule farm."""
def __init__(self, name: str, mule_numbers: Union[int, List[int]]):
"""
:param na... |
# coding=utf-8
# Copyright 2022 The Uncertainty Baselines 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 ap... |
"""
Submit an existing TVQA model on the leaderboard
ipython -i submit_to_leaderboard.py -- ../../pretrain/configs/base.yaml ${ckpt}
ipython -i submit_to_leaderboard.py -- ../../pretrain/configs/large.yaml ${ckpt}
"""
import sys
sys.path.append('../../')
import yaml
from datetime import datetime
import pytz
import j... |
#!/usr/bin/env python
"""
A module containing enums for use in picklist-style fields for the sonata archive
"""
from enums.key_enums import RelativeKey
class SonataType(object):
"""
An enum for a sonata type
"""
TYPE_1 = "Type 1"
TYPE_2 = "Type 2"
TYPE_3 = "Type 3"
TYPE_4 = "Type 4"
T... |
def func_2(input):
if input == 0:
x = 1
y = 2
z = 3
else:
x = 4
y = 5
z = 6
|
#!/usr/bin/env python
# Run with SPRING environment
import sys
import argparse
import numpy as np
import scipy.sparse
sys.path.append("./SPRING")
import preprocessing_python
parser = argparse.ArgumentParser()
parser.add_argument("-e", dest="expr", type=str, required=True)
parser.add_argument("-d", dest="dist", type... |
"""
@brief test log(time=3s)
"""
import unittest
import warnings
from tkinter import TclError
from tkinterquickhelper.funcwin.default_functions import test_regular_expression, file_grep, file_head
from tkinterquickhelper.funcwin.main_window import main_loop_functions
class TestMakeWindow2 (unittest.TestCase):
... |
import pytest
from sanic import Blueprint
from sanic.constants import HTTP_METHODS
from sanic.response import text
from sanic.views import CompositionView, HTTPMethodView
METHODS = [method.lower() for method in HTTP_METHODS]
class SimpleView(HTTPMethodView):
def get(self, request):
return text("I am get ... |
#! /usr/bin/python
import numpy as np
import rospy
import roslib
from std_msgs.msg import String, Int32, Float32, Float64
from fiducial_msgs.msg import FiducialTransform, FiducialTransformArray, FiducialArray
from geometry_msgs.msg import Transform, Quaternion, Vector3
from nav_msgs.msg import Odometry
import math as ... |
# -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def domainToLevels(self, domain):
parts = domain.split('.')
if len(parts) == 3:
return ['.'.join(parts[-3:]), '.'.join(parts[-2:]), parts[-1]]
elif len(parts) == 2:
return ['.'.join(parts[-2:]... |
import socket
import msgpack
import resource
from async_generator import asynccontextmanager
from async_generator import async_generator, yield_
import anyio
from anyio.exceptions import ClosedResourceError
import outcome
from .result import SerfResult
from .util import ValueEvent
from .exceptions import SerfError, Se... |
#!/usr/bin/env python3
import DeepFried.util as _u
import numpy as _np
import theano as _th
import theano.tensor as _T
class StreaMiniOptimizer(object):
"""
This is an optimizer that works through minibatches of the dataset, each
minibatch being uploaded onto the GPU each time.
This is slower than ... |
# (C) 2020, Schlumberger. Refer to package LICENSE.
'''
CommandFactory - governs the use of commands in distpy
for processing and plotting
# There is a special command at the head-node - where data is loaded
'''
import numpy
import types
import distpy.calc.extra_numpy as extra_numpy
import distpy.ca... |
import math
from collections import Counter
from pathlib import Path
from typing import List, Dict, Any, Tuple
import torch
import tqdm
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.tensorboard import SummaryWriter
from dp.model.model import Model
from dp.model.u... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
import os
import xml.etree.ElementTree as ET
import pytest
from amg import fgdcmetadata as fgdc
@pytest.fixture
def fgdc_metadata_equi(datadir):
return fgdc.FGDCMetadata(os.path.join(datadir, 'fgdc_template.xml'), proj='equirect')
@pytest.fixture
def fgdc_metadata_ortho(datadir):
return fgdc.FGDCMetadata(os... |
import os
import json
import urllib
import ssl
def parse_cell_ids(nb_json_data):
cell_ids = []
for cell in nb_json_data['cells']:
if 'metadata' in cell and 'nbgrader' in cell['metadata'] and 'grade_id' in cell['metadata']['nbgrader']:
cell_ids.append(cell['metadata']['nbgrader']['grade_id']... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: stream_alert_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.... |
# Python Standard Library
import sys
import os
import threading
import time
import datetime
import json
import logging
# Dialogs Python Bot SDK
import grpc
from dialog_bot_sdk.bot import DialogBot
from DictPersistJSON import DictPersistJSON
def handle_relevant_comment(data, pull_author_username):
# There's a bu... |
from flask import Flask, jsonify
from api.smogonapi import smogonapi
app = Flask(__name__)
app.register_blueprint(smogonapi, url_prefix = '/api/v1')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80) |
import os, shutil
from walt.common.tools import failsafe_makedirs, failsafe_symlink
from walt.server.threads.main.images.image import get_mount_path
NODES_PATH='/var/lib/walt/nodes/'
def update(db):
# create dir if it does not exist yet
failsafe_makedirs(NODES_PATH)
# list existing entries, in case some o... |
from Block import Block
class Blockchain:
def __init__(self):
self.difficulty = 4 # number of leading 0's needed for proofed hash
genesis_block = Block(["Genesis Block"], "0", self.difficulty)
self.chain = [genesis_block]
print(f"Genesis Block created!\nHash: {genesis_block.genera... |
import time
import cgi
import oauth2 as oauth
from django.test import Client
from oauth_provider.tests.auth import BaseOAuthTestCase
from oauth_provider.models import Token, Consumer, Scope
from oauth_provider.compat import get_user_model
User = get_user_model()
class ProtocolExample(BaseOAuthTestCa... |
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
import re, os, json, threading, time, socket, sys, subprocess, sys, logging
from json import dumps
directories=['stati... |
import numpy as np
import tensorflow as tf
from MLib.Core.layers import LinearLayer, ConvLayer
from tensorflow.keras.layers import MaxPooling2D, Flatten
from tensorflow.keras import Model
class SimpleCNNModel(Model):
def __init__(self, num_units):
super(SimpleCNNModel, self).__init__()
# Define the architecture... |
import torch
import argparse
import shutil
import os
import re
import importlib
import numpy as np
def run_config(args, config):
run_path = 'runs/{}'.format(config['run_id'])
# fail early, if we should train, and dir exists #######################################
if args.train:
if args.force:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.