content stringlengths 5 1.05M |
|---|
# Copyright (c) 2020 Vishnu J. Seesahai
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
import subprocess
import os, sys, rpcworker
from PyQt5.QtCore import *
from config import MIN_CONF, MAX_CONF
from rpcworker import progress_fn, thread_complete
_translate = QCoreAppl... |
from __future__ import absolute_import
from .s3 import S3Backend
|
# Copyright (c) 2008 Mikeal Rogers # lint-amnesty, pylint: disable=missing-module-docstring
#
# 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... |
import werkzeug
from werkzeug.exceptions import HTTPException
_version = werkzeug.__version__.split('.')[0]
if _version in ('0', '1'):
class _HTTPException(HTTPException):
def __init__(self, code, body, headers, response=None):
super(_HTTPException, self).__init__(None, response)
s... |
# Copyright © 2016-2021 Medical Image Analysis Laboratory, University Hospital Center and University of Lausanne (UNIL-CHUV), Switzerland
#
# This software is distributed under the open-source license Modified BSD.
"""Module for the super-resolution reconstruction pipeline."""
import os
import sys
import platform
im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" 学堂在线课程下载 """
import re
import os
import sys
import json
import requests
from bs4 import BeautifulSoup
# 基本 URL
BASE_URL = 'http://www.xuetangx.com'
# 定义一个全局的会话
CONNECTION = requests.Session()
CONNECTION.headers.update({'User-Agent': 'Mozilla/5.0'})
# 连续两个以上的空白字符正则表达式
RE... |
import torch
import torch.nn as nn
class Embedding(nn.Module):
def __init__(self, dataset, parameter):
super(Embedding, self).__init__()
self.device = parameter['device']
self.ent2id = dataset['ent2id']
self.es = parameter['embed_dim']
num_ent = len(self.ent2id)
se... |
import nltk
import re
import pandas as pd
import numpy as np
from collections import Counter
from nltk.tokenize.api import TokenizerI
from nltk.corpus import words
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor
from ... |
"""helfeedback URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
# Python Program to find the area of triangle
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print("The area of the... |
from math import asin,sin
from matplotlib import pyplot as plt
from pylab import linspace
from qc import Calc
#构建点集
h = linspace(0.01, 17, 10000)
#初始化函数
a = Calc()
a.set_raw_values(u1=0, hm=17)
#计算h/hm
y = []
for i in linspace(0.01, 17, 10000):
y.append(i/a.get_raw_values('hm'))
#计算D光
... |
""" Class for IGMSurvey
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import json
from abc import ABCMeta
import warnings
import pdb
from collections import OrderedDict
from astropy import coordinates as coords
from astropy.io import ascii
from astropy imp... |
'''
Created on Feb 19, 2011
Use this module to start Arelle in windowing interactive UI mode
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from arelle.XPathParser import parser_unit_test
parser_unit_test() |
from functools import update_wrapper
import re
class Predicate(object):
"""A Predicate class that represents combining predicates with & and |"""
def __init__(self, predicate):
self.pred = predicate
def __call__(self, obj):
return self.pred(obj)
def __copy_pred(self):
return ... |
import os
import sys
from itertools import product
filename = __file__[:-5] + '-input'
with open(filename) as f:
lines = f.read().splitlines()
player_positions = list(map(lambda line: int(line[-1]), lines))
turn_rolls = product([1,2,3], repeat=3)
turn_sums = list(map(sum, turn_rolls))
turn_sum_set = set(t... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as dist
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from torchvision import datasets, transforms
import math
from numpy import prod
from .vae import VAE
from pvae.utils import Constants
f... |
from django.db.models import Q, Manager
from locking import LOCK_TIMEOUT
import datetime
"""
LOCKED
if (now() - self.locked_at).seconds < LOCK_TIMEOUT:
self.locked_at < (NOW - TIMEOUT)
"""
def point_of_timeout():
delta = datetime.timedelta(seconds=LOCK_TIMEOUT)
return now() - delt... |
from bases import point, vector, EPSILON
from ray import ray
from sphere import sphere
class Intersection:
def __init__(self, time, object):
self.t = time
self.object = object
# def __str__(self):
# return 'time = {} object = {}'.format(self.t, self.object)
def pre... |
#!/usr/bin/env python
""" Refine 2D triangulation
"""
import argparse
import pymesh
import numpy as np
from numpy.linalg import norm
def parse_args():
parser = argparse.ArgumentParser(__doc__);
parser.add_argument("--engine", help="Triangulation engine",
choices=("triangle_refiner", ... |
import unittest
import sys
import StringIO
import __builtin__
import os
from distutils import log
# Reload module to run its global section under coverage supervision
import distcovery.coverage_wrapper
reload(distcovery.coverage_wrapper)
from distcovery.coverage_wrapper import _DummyCoverage, Coverage, \
... |
# Code is from: https://github.com/interaction-dataset/interaction-dataset.
DELTA_TIMESTAMP_MS = 100 # similar throughout the whole dataset
class MotionState:
def __init__(self, time_stamp_ms):
assert isinstance(time_stamp_ms, int)
self.time_stamp_ms = time_stamp_ms
self.x = None
... |
import torch
from torch import nn
import functools
from adaptor.basic_adaptor import NormalizeLayer
from models.test_model import Flatten
import numpy as np
from numba import jit, njit
class FlattenConv2D(nn.Module):
"""
Transforms the 2D convolutional layer to fully-connected layer with fixed ... |
import collections
import itertools
from typing import Callable, Iterable, Sequence, Union
concat = itertools.chain.from_iterable
def identity(x):
return x
def nth(n):
"""Returns the nth element in a sequence.
>>> nth(1, 'ABC')
['B']
"""
def nth(seq):
if isinstance(seq, (tuple, li... |
import torch
from .Criterion import Criterion
class MarginRankingCriterion(Criterion):
def __init__(self, margin=1, sizeAverage=True):
super(MarginRankingCriterion, self).__init__()
self.margin = margin
self.sizeAverage = sizeAverage
self.gradInput = [torch.Tensor(), torch.Tensor(... |
"""
This module contains various contants and utilities for both internal and external use.
"""
import aiohttp
import asyncio
import datetime
import typing
#: This constant is used in the various ``edit()`` methods.
#: It's used to indicate that there should be no change to the value of a field,
#: in the cases wher... |
from __future__ import print_function
from flask import Flask, jsonify, request
from flask.ext.pymongo import PyMongo
from sh import git, sh, sudo, ErrorReturnCode
import config, os, sys
app = Flask(__name__)
app.config.from_object(config)
mongo = PyMongo(app)
if app.config.get('ALLOWED_RANGES', None):
ALLOWED_RA... |
# Copyright (c) 2017 OpenStack Foundation
#
# 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 ... |
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp>
#
# 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
#
# h... |
import discord
from discord.ext import commands
import urllib
import urllib.parse
import json
import asyncio
import random
import asyncio
import psutil
import pybithumb
from discord.ext import commands
from datetime import datetime
class _help(commands.Cog):
def __init__(self, bot: commands.Bot):
... |
# AUTOGENERATED FROM "edb/api/types.txt" WITH
# $ edb gen-types
from __future__ import annotations
from typing import *
import uuid
from edb.common import uuidgen
UUID: Type[uuid.UUID] = uuidgen.UUID
TYPE_IDS = {
'anytype': UUID('00000000-0000-0000-0000-000000000001'),
'anytuple': UUID('00000000-000... |
from django.conf.urls import url
from . import api_views
urlpatterns = [
url(r'login/$', api_views.LoginAPIView.as_view(), name='login'),
url(r'social-auth/$', api_views.SocialAuthAPIView.as_view(), name='social-auth'),
url(r'sign-up/$', api_views.SignupAPIView.as_view(), name='sign-up'),
url(r'change... |
import numpy as np
random = np.random.RandomState(2016)
std_list = np.array(range(2,10))/100
print(std_list)
def gaussian_stds_generater(random,num=4):
candid_list = []
candid_list.append(random.uniform(0.01, 0.1))
while len(candid_list)<num:
std_add = np.random.choice(std_list)
candid_lis... |
import math
import models
import tensorflow as tf
import utils
from tensorflow import flags
import tensorflow.contrib.slim as slim
FLAGS = flags.FLAGS
class MeanModel(models.BaseModel):
"""Mean model."""
def create_model(self, model_input, **unused_params):
"""Creates a logistic model.
model_input: 'ba... |
import hashlib
import os
import re
def find_files(directory, regex):
for root, dirs, files in os.walk(directory):
for basename in files:
if re.search(regex, basename):
fq_path = os.path.join(root, basename)
yield fq_path, root, basename
def _get_md5_hash(filenam... |
# The MIT License (MIT)
#
# Copyright (c) 2015-2018 Niklas Rosenstein
#
# 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
# rights to use, ... |
import base64
import json
import unittest
from wk_client import create_app, db
from wk_client.config import TestConfig
class AppTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app(TestConfig)
self.app_context = self.app.app_context()
self.app_context.push()
db.crea... |
import enum
from typing import Union
class InvalidCallableValue(Exception):
pass
class Result:
def __init__(self, pre_subst, post_subst, variables):
self.pre_subst = pre_subst
self.post_subst = post_subst
self.variables = variables
def __repr__(self):
return "Result('{}'... |
# This is a sample program that shows downloading and dynamically importing a module.
__author__ = 'David Manouchehri (david@davidmanouchehri.com)'
try: # Python 3
import urllib.request as urllib2
from urllib.parse import urlparse
except ImportError: # Python 2
import urlparse
import urllib2
def g... |
#
# Copyright (c) 2016 GigaSpaces Technologies Ltd. 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 requ... |
### como leer archivos en python ###
file_open = open("lorem_ipsum.txt", "r")
file_read = file_open.read()
file_open.close()
print(file_read)
### como escribir archivos en python ###
file_write = open("demo.txt", "w")
file_write.write(file_read)
file_write.close()
### como utilizar el with en archivos usando python... |
import sqlite3
def add_variableName(variable):
banco = sqlite3.connect('bancoDeDados.db')
cursor = banco.cursor()
cursor.execute("""
INSERT INTO tbl_opcua_data (variableName) VALUES (?)
""", (variable, ))
banco.commit()
banco.close()
def get_variabl... |
import pytest
def test_claim(user, lp_3crv, vault, accounts):
three_gauge = accounts.at("0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A", force=True)
lp_3crv.transfer(vault, "1000 ether", {"from": three_gauge})
before = lp_3crv.balanceOf(user)
vault.claim({"from": user})
assert lp_3crv.balanceOf(user)... |
import csv
import datetime
import shutil
import os
from tempfile import NamedTemporaryFile
#file_item_path = os.path.join(os.getcwd(), "data.csv")
file_item_path = os.path.join(os.path.dirname(__file__), "data.csv")
def read_data(user_id=None, email=None):
filename = file_item_path
with open(filename, "r") ... |
#!/usr/bin/env python3
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn import init
from tqdm import tqdm
import random
import math
import operator
import matplotlib.pyplot as plt
import numpy as np
use_cuda = torch.cuda.is_available()
cla... |
from strategies.strategy import Strategy
from utils.formats import get_usable, pretty_format_fa
from androguard.core.bytecodes.dvm import ClassDefItem
cfs = (
(lambda f: f.get_access_flags_string(), 4),
(lambda f: f.get_size(), 5),
)
class FieldStrategy(Strategy):
def get_types_to_match(self):
f... |
from __future__ import division
import numpy as np
from cea.optimization.constants import ACT_FIRST, HP_SEW_ALLOWED,T_LAKE, HP_LAKE_ALLOWED, CC_ALLOWED, BOILER_MIN, ACT_SECOND, ACT_THIRD, ACT_FOURTH
from cea.constants import HEAT_CAPACITY_OF_WATER_JPERKGK
from cea.technologies.heatpumps import GHP_op_cost, HPSew_op_cos... |
import hashlib
import uuid
import requests
from behave import step
from tenacity import retry, wait_fixed, stop_after_delay
from acceptance_tests.utilities.exception_manager_helper import quarantine_bad_messages_check_and_reset
from acceptance_tests.utilities.pubsub_helper import publish_to_pubsub
from acceptance_tes... |
"""A framework for restful APIs."""
# -----------------------------------------------------------------------------
# Module: dpa.restful
# Author: Josh Tomlinson (jtomlin)
# -----------------------------------------------------------------------------
# ---------------------------------------------------------------... |
import tensorflow as tf
import os
import horovod.tensorflow as hvd
config = {
'rank_size': 1,
'shard': False,
# ======= basic config ======= #
'mode':'train', # "train","evaluate","train_and_evaluate"
# modify here for train_and_evaluate mode
'epochs_... |
import connexion
import logging
import datetime
from connexion import NoContent
# our memory-only pet storage
PETS = {}
def get_pets(limit, animal_type=None):
return {'pets': [pet for pet in PETS.values() if not animal_type or pet['animal_type'] == animal_type][:limit]}
def get_pet(pet_id):
pet = PETS.get(pet_i... |
#!/usr/bin/env python
# This is written with python3 syntax
import csv
import os
import json
INPUT_FILE_NAME = 'lookup.csv'
INPUT_FILE_PATH = os.path.join(os.getcwd(), INPUT_FILE_NAME)
CSV_DELIMITER = ','
OUTPUT_FILE_NAME = 'lookup.json'
OUTPUT_FILE_PATH = os.path.join(os.getcwd(), OUTPUT_FILE_NAME)
LOOKUP_COL = "... |
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2018/12/8 下午3:02
# 6.3 使用门函数和激励函数
# 1. 导入必要的编程库,初始化一个计算图会话。对于学习在TensorFlow中如何设置随机种子而言,这也是一个很好的例子。这里将使用TensorFlow和Numpy模块和随机数生成器。对于相同的随机种子集,我们应该能够复现
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
sess = tf.Session(... |
#!/usr/bin/env python3
from aws_cdk import core
import os
from serverless_pipeline.serverless_pipeline_stack import ServerlessPipelineStack
app = core.App()
ServerlessPipelineStack(app, "serverless-pipeline", env=core.Environment(
account=os.getenv('AWS_CDK_DEFAULT_ACCOUNT'),
region=os.getenv('AWS_CDK_DEFAU... |
from pathlib import Path
examples_folder = Path(__file__).parent.parent.parent / "examples" / "etl"
examples = {
file.stem: open(file).read()
for file in examples_folder.iterdir()
if file.suffix == ".py"
}
print(list(examples.keys()))
template = open(Path(__file__).parent / "README.template.md").read()
op... |
#!/usr/bin/env python3
#
# SMNCopyNumberCaller
# Copyright 2019-2020 Illumina, Inc.
# All rights reserved.
#
# Author: Xiao Chen <xchen2@illumina.com>
#
# 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 Lic... |
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
# MIT License
#
# Copyright (c) 2021 Nathan Juraj Michlo
#
# 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 Softwar... |
# ===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# 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:/... |
from django.shortcuts import render
def main_view(request):
return render(request, 'main/main.html')
|
# Generated by Django 2.1.7 on 2019-02-16 10:25
import django.contrib.auth.models
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
('... |
#!/usr/local/bin/python3.4
# encoding: utf-8
'''
@author: Itay Moav
@copyright: 2014 organization_name. All rights reserved.
@license: license
@contact: user_email
@deffield updated: Updated
'''
import sys
import os
import traceback
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/..... |
import sys
sys.path.append("..")
from common.data_models import Taxon
print(Taxon())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import datetime
from collections import namedtuple
import git
from github.AuthenticatedUser import AuthenticatedUser
from github.Repository import Repository
from bincrafters_conventions.bincrafters_conventions import Command as BincraftersConventionsComma... |
#--- Exercicio 5 - Variávies e impressão com interpolacão de string
#--- Imprima os dados de 5 papeis cotatos na bolsa de valors de SP
#--- Os dados dos papeis devem estar em variáveis
#--- Papel: Nome, Tipo, Cotação Atual e Valores Min e Max do dia
#--- A tela deve conter cabeçalho e rodapé |
#!/usr/bin/env python3
import os
from textwrap import dedent
def wait_for_enter():
input("\nPress enter to continue...")
os.system('clear')
def add_wifi_network(context):
msg = """
Add Wifi Network
================
Add wifi network for the 4G router (if using one), or known wifi address.
... |
# -*- coding: utf-8 -*-
# imports
import cv2, helper, imutils;
import numpy as np;
# This filter does the average filtering on the image
# using the cv2.blur(frame, kernel_size = (5,5)).
def avgFilter(frame, kernel_size = (5,5)):
return cv2.blur(frame, kernel_size);
#end
# This function does the Gaussian Blurrin... |
from PIL import Image, ImageDraw
from os import listdir, chdir
from sys import exit
from time import sleep
from CONFIG import *
from textwrap import wrap
from FUNC import *
#Читем текст для демотиватора
with open('text.txt', encoding='utf-8') as file:
try:
N = int(file.readline())
text = file.read... |
#!/usr/bin/env python
"""The ReadLowLevel client action."""
import hashlib
import io
from typing import AnyStr, Optional
import zlib
from grr_response_client import actions
from grr_response_client import comms
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.rdfvalues import client as rdf_client... |
import os
import json
import math
import torch
import torch.distributions as distributions
from daphne import daphne
from tests import is_tol, run_prob_test,load_truth
import matplotlib.pyplot as plt
# Useful functions
from utils import _hashmap, _vector, _totensor
from utils import _put, _remove, _append, _get
from ut... |
import pathlib
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from mirumon.settings.config import get_app_settings
project_root_dir = pathlib.Path(__file__).resolve().parents[3]
sys.path.append(str(project_root_dir))
config = context.conf... |
# TODO Find what RPi returns and change the condition to work on all systems other than RPi
import platform
from gpiozero.pins.mock import MockFactory
from gpiozero import Device
def checkSimulate():
if platform.system() == "Darwin" or platform.system() == "Windows":
Device.pin_factory = MockFac... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `dwglasso` package."""
import unittest
import numpy as np
from matplotlib import pyplot as plt
import seaborn
from .context import dwglasso
from dwglasso import var
from .random_var_generators import random_var, iid_gaussian_var, iid_ber_graph
class Test... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from typing import Optional, Dict, Tuple, Union
from copy import deepcopy
# type Aliases
#
SDRNodeType = Tuple[str, str]
""" SDRNodeType is a tuple of strings (node_type and node_uid) """
SDREdgeType = Tuple[str, Optional[str]]
""" SDREdgeType is a tuple (edge_type edg... |
from .cameron import cameron_prediction
from .exceptions import DistanceOutOfBoundsError
from .purdy import purdy, purdy_prediction
from .riegel import riegel_prediction
from .vo2max import VO2Max, VO2Max_prediction
name = 'running_performance'
__all__ = [
cameron_prediction,
DistanceOutOfBoundsError,
nam... |
from application.infrastructure.error.errors import VCFHandlerBaseError
class AuthenticationError(VCFHandlerBaseError):
message = 'Authentication Error.'
error_type = 'AuthenticationError'
class AuthorizationError(VCFHandlerBaseError):
message = 'Authorization error.'
error_type = 'AuthorizationErro... |
# standard library imports
import os
import math
from math import sqrt, pi
# package imports
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from torch.distributions.gamma import Gamma
from torch.distributions.multivariate_normal impor... |
import pygame
import numpy as np
import time
import random
# Generate some test data
data = np.arange(200).reshape((4,5,10))
print(data)
# Write the array to disk
# outfile = open('test.txt', 'w')
# I'm writing a header here just for the sake of readability
# # Any line starting with "#" will be ignored by numpy.loa... |
import pytest
import numpy as np
import os
from collections import namedtuple
from ProcessOptimizer import dummy_minimize
from ProcessOptimizer import gp_minimize
from ProcessOptimizer.benchmarks import bench1
from ProcessOptimizer.benchmarks import bench3
from ProcessOptimizer.callbacks import TimerCallback
from Pr... |
from .models import CreatedDocument, CreatedVersionedDocument, SplashMetadata, VersionedSplashMetadata
|
a = raw_input()
a = list(a)
for j in range(1,len(a)):
key = a[j]
i = j-1
while i>=0 and a[i]>key:
a[i + 1]=a[i]
i-=1
a[i+1] = key
print(a)
|
/usr/lib64/python3.6/genericpath.py |
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(name='check_workspace',
version='0.1',
description='utilities for plotting in ROOT',
url='https://github.com/xju2/check_workspace',
... |
def goodbye():
print("Thank you for visiting") #not working right now, will fix later
quit()
|
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
"""
Open implementation of MonoLoco / MonoLoco++ / MonStereo
"""
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
# guess the number
import random
def parse_int_from_input(input_question):
while True:
try:
return int(input(input_question))
except ValueError:
print("Pick A Valid Integer")
def play_game(max_number):
random_number = random.randint(0, max_number)
guess = parse_int... |
# coding=utf-8
# TestBenchmarkSwiftDictionary.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# S... |
import random
import string
import os
import sys
import requests
import httpx
import time
import colorama
from colorama import *
os.system("title Discord Account Creator - Kings Cheats")
os.system("CLS")
global captchakey
f = open("2cap.txt", "r")
captchakey = f.read()
init()
def useragent():
file = open('user... |
from mpl_toolkits.mplot3d import Axes3D
import scipy.io as sio
import matplotlib.image as img
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from numpy.linalg import svd
def feature_normalize(X):
means = np.mean(X, axis=0)
X_norm = X - means
stds = np.std(X_norm,... |
"""
Extra HTML Widget classes
"""
import datetime
import re
from django.forms.widgets import Widget, Select
from django.utils import datetime_safe
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe
from django.utils.formats import get_format
from django.conf import settings
__all__ =... |
from rest_framework import serializers
from authors.apps.articles.models import Articles
from authors.apps.highlights.models import Highlights
from .models import Profile, CustomFollows
class GetProfileSerializer(serializers.ModelSerializer):
"""
serializers for user profile upon user registration.
"""
... |
import test_common
from spartan.examples.sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_digits
N_TREES = 50
class TestRandomForest(test_common.ClusterTest):
def test_forest(self):
ds = load_digits()
X = ds.data
y = ds.target
rf = RandomForestClassifier(n_estimators ... |
from infosystem.common import exception
operation_after_post_registry = dict()
def do_after_post(manager, operation):
'''
Decorator for register action after post based on manager operation
Parameters:
manager(cls): The Manager class reference
operation(cls): The Operation class referen... |
import re
import json
import logging
import queue
import threading
from importlib import import_module
import asyncio
from lxml import etree
class Farmer(object):
def __init__(self, steam, appids=[], scheduler="simple"):
self._state = "running"
self.mutex = threading.RLock()
self.steam = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <coherence@beebits.net>
# upnp-tester.py
#
# very basic atm
#
# provides these functions:
#
# list - display all devices
# extract <uuid> - extract ... |
from django.db import models
# Create your models here.
class BookModel(models.Model):
bookname = models.CharField(max_length=50)
subject = models.CharField(max_length=50)
price = models.IntegerField()
class Meta:
db_table = "books"
class Bankaccount(models.Model):
accountno = models.... |
import sys
import unittest
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
import botocore
##############
# Parameters #
##############
# Define the default resource to report to Config Rules
DEFAULT_RESOURCE_TYPE = 'AWS::ElastiCache::CacheCluster'
#############
# Main... |
# Copyright 2020 Tensorforce 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/LICENSE-2.0
#
# Unless required by applicable la... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing,svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X=[10, 15, 20, 25, 30, 35, 40, 45, 50, 55,60,65,70,75,80]
y=[20, 25, 30, 35, 40, 45, 50, 55, 60, 65... |
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from getpaid.backends.payu import PaymentProcessor
class Command(BaseCommand):
help = 'Display URL path for PayU Online URL configuration'
def handle(self, *args, **op... |
from flask import Flask
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.