text stringlengths 3.07k 12.6k |
|---|
import chardet
import copy
import io
import json
import ldap_peoples.ldif as ldif
import logging
from django.apps import apps
from django.conf import settings
from django.db import connections
from django.utils import timezone
from collections import OrderedDict
from ldap import modlist
from . ldap_utils import (form... |
import cherrypy
import json
from bson import json_util
from girder import events
from girder.api import access, rest
from girder.api.v1.folder import Folder as FolderResource
from girder.constants import AccessType, TokenScope, SortDir
from girder.exceptions import ValidationException, RestException
from girder.models.... |
"""
Prepare vocabulary and initial word vectors.
"""
import json
import pickle
import argparse
import numpy as np
from collections import Counter
from utils import vocab, constant, helper
# python3 prepare_vocab.py dataset/wiki80 dataset/vocab --glove_dir dataset/glove
def parse_args():
parser = argparse.Argumen... |
"""
the file contains all instrument class
"""
import time
"""
DSO class
"""
class OScope:
def __init__(self, IAddr): # make local var for DSO
self.DSO = IAddr
def chk(self):
self.DSO.query('*IDN?')
print("test complete")
return print("complete")
# Take screenshots of t... |
"""
Created by: apenasrr
Source: https://github.com/apenasrr/zipind
Compresses a folder into independent parts.
Works in hybrid mode:
- Compact folder dividing into independent parts, grouping your files in
alphanumeric order.
- Respects the ordering of folders and files.
- Respects th... |
from __future__ import absolute_import
import numpy as np
from autograd.core import (Node, FloatNode, primitive, cast,
differentiable_ops, nondifferentiable_ops, getval)
from . import numpy_wrapper as anp
from .use_gpu_numpy import use_gpu_numpy
@primitive
def take(A, idx):
return A[idx... |
from __future__ import unicode_literals
import os.path
from pyquery.pyquery import PyQuery
from qiller.utils import q_enc
from qiller.what_api import WHAT_CD_DOMAIN
WHAT_UPLOAD_URL = 'https://{0}/upload.php'.format(WHAT_CD_DOMAIN)
WHAT_RELEASE_TYPES = (
(1, 'Album'),
(3, 'Soundtrack'),
(5, 'EP'),
(6... |
from yunionclient.common import base
from yunionclient.common import utils
"""
价格查询接口
"""
class PriceManager(base.MeterManager):
keyword = 'price'
keyword_plural = 'prices'
_columns = []
'''
输入参数:
provider // 云厂商
region // 区域ID example: cn-north-1
zone // 可用区ID example: cn-north-1a
... |
import re
from typing import List, Union, Dict, Text, Any, Tuple, Optional
from kfp import dsl
ItemList = List[Union[int, float, str, Dict[Text, Any]]]
class LoopArguments(dsl.PipelineParam):
"""Class representing the arguments that are looped over in a ParallelFor loop in the KFP DSL.
This doesn't need to ... |
from collections import defaultdict
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.shortcuts import prompt
import click
import click._bashcomplete
import click.parser
import os
import shlex
import sys
import six
from .exceptions import ... |
from abc import ABCMeta, abstractproperty, abstractmethod
from contextlib import contextmanager
import io
import os
import shutil
import uuid
import six
from dagster import check
from dagster.utils import mkdir_p
from dagster.core.types.decorator import dagster_type
from .temp_file_manager import TempfileManager
fro... |
import werkzeug
werkzeug.cached_property = werkzeug.utils.cached_property
from flask import Flask, request, abort
from flask_restplus import Api, Resource, fields, marshal
from functools import wraps
import logging, json
app = Flask(__name__)
api = Api(app, version='v1', title='Envoy Service API',
descriptio... |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
from pyknow import *
import sys
"""
Sistema experto para detectar si una persona sufre de diabetes
@author: <NAME> Cod:1113624878.
Grupo: 90169_21
Material Consultado
* http://www. Cod.org/quoi-faire-si-mon-enfant-a-le-diabete/
* h... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
import argparse
import json
import multiprocessing as mp
import operator
import time
import sys
import mergelife
import ml_evolve as ev
import numpy as np
bestGenome = None
evalCount = 0
startTime = 0
timeLastUpdate = 0
totalEvalCount = 0
runCount = 1
noImprovement = 0
waitingCount = 0
population = []
def subproces... |
import kerberos
import os
import requests
import sys
import pytest
username = os.environ.get('KERBEROS_USERNAME', 'administrator')
password = os.environ.get('KERBEROS_PASSWORD', '<PASSWORD>')
realm = os.environ.get('KERBEROS_REALM', 'example.com')
hostname = os.environ.get('KERBEROS_HOSTNAME', 'hostname.example.com')
... |
###################################################
# pyDtsTool #
# Copyright 2021, Altium, Inc. #
# Author: <NAME> #
# E-Mail: <EMAIL> #
###################################################
import re
import typing... |
import asyncio
import pickle
import pytest
from pytest_toolbox.comparison import CloseToNow
from arq import Worker, func
from arq.connections import ArqRedis, RedisSettings, create_pool
from arq.constants import default_queue_name, in_progress_key_prefix, job_key_prefix, result_key_prefix
from arq.jobs import Deseria... |
import os
import platform
import shutil
import subprocess
import sys
def get_platform_compilers():
if platform.system() == 'Windows':
return [ 'vs2015', 'vs2017', 'vs2019', 'vs2019-clang' ]
elif platform.system() == 'Linux':
compilers = []
if shutil.which('g++-5'):
compilers.append('gcc5')
if shutil.which... |
import json
from django.contrib.admin.utils import quote
from django.core.exceptions import ObjectDoesNotExist
from django.forms import widgets
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
import requests
from wagtail impor... |
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import itertools
import collections
import matplotlib.pyplot as plt
# Read in data
df = pd.read_csv("Chinese_Names_Corpus_Gender(120W).txt", header=2)
df = df[df.sex != "未知"]
names = df["dict"].values
# Compute charact... |
from PyQt5.QtCore import QDateTime, Qt, QTimer, pyqtSignal, QObject
from PyQt5.QtWidgets import (QDialog, QApplication, QLabel, QCheckBox, QHBoxLayout, QVBoxLayout,
QPushButton, QLineEdit, QSpinBox, QFormLayout, QGridLayout,
QStyleFactory)
import os
import sys
im... |
import pytest
import os
import os.path
from collections import namedtuple
import logging
import pandas as pd
import numpy as np
import lk_test_utils as lktu
from lenskit.algorithms.basic import Bias, TopN
import lenskit.batch as lkb
MLB = namedtuple('MLB', ['ratings', 'algo'])
_log = logging.getLogger(__name__)
@... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
from matplotlib.colors import Normalize
class _MidpointNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
Normali... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import platform
from math import exp
#########################################################################
# TDSpectrum #
# Made by: <NAME> (LeoLugoF) ... |
from operator import or_
from flask import request
import json as Json
from sqlalchemy import or_
from . import itemRouter
from app import db, itemIdPool
from app import comerrs as ErrCode
from app.models import Admin, AdminRequest, LongTimeRsv, User, Item, Reservation
import app.checkargs as CheckArgs
from app.auth ... |
class CNode:
def __init__(self, ntype, name, depth, parent=None):
self.node_type = ntype
self.name = name
self.children = []
self.depth = depth
self.parent = parent
def __str__(self):
return self.name+": "+str(len(self.children))+" leaves at " + str(self.depth)
... |
# tools.py
#
# Utility functions
from netaddr import IPAddress
from netaddr import IPNetwork
import struct
import six
import binascii
def EncodeString(str):
if len(str) > 253:
raise ValueError('Can only encode strings of <= 253 characters')
if isinstance(str, six.text_type):
return str.encode(... |
import json
import logging
import urllib
from cryptojwt.jwk.jwk import key_from_jwk_dict
from cryptojwt.jwk.rsa import RSAKey
from django.http import JsonResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.urls import reverse
from oidcmsg.message import Message
logger = l... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import tg
from tg.controllers import TGController
from tg.decorators import expose, validate, https, variable_decode, with_trailing_slash, \
without_trailing_slash, with_engine
from tg import expose, redirect, config
from tg.controllers import TGContr... |
import numpy as np
import warnings
warnings.filterwarnings("ignore")
import sys
from PIL import Image, ImageDraw, ImageFilter
def koch_line(start, end, factor):
"""
Segments a line to Koch line, creating fractals.
:param tuple start: (x, y) coordinates of the starting point
:param tuple end: (x, y)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import os
import time
# pip install python-telegram-bot
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext, ConversationHandler
from te... |
#!/usr/bin/python
# Copyright (c) 2017 <NAME>
#
# 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, copy, modify, merge, pu... |
# -*- coding: utf-8 -*-
import feedparser
import time
import main_instagram
from w3lib.html import replace_entities
import facebook_post
counter_of_articles=0
list_of_articles = []
list_of_links= []
if_need_to_post = False
if_list_refreshed = False
image_error = False
rss_link = 'http://autoconsulting.com.ua/rss.html'... |
#Copyright (c) 2017 <NAME>
#
#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, copy, modify, merge, publish, distribute, subl... |
from resnet import resnet_v2_50, resnet_arg_scope
import tensorflow as tf
import tensorflow.contrib.slim as slim
from ops import conv, swish, bifpn_layer, batchnorm
from config import *
def class_subnet(inputs, is_training):
with tf.variable_scope("class_subnet", reuse=tf.AUTO_REUSE):
for i in ra... |
import json
import os
import random
import time
from urllib import request
import requests
from bs4 import BeautifulSoup
cache_json_path = os.getcwd() + "/json/PictureList"
url_host = 'http://moe.005.tv/'
test_url = 'http://moe.005.tv/78464.html'
test_url_no_next = 'http://moe.005.tv/80483.html'
file_name = 'test'
p... |
import math
from typing import Dict
RBSTATE = "TAGame.RBActor_TA:ReplicatedRBState"
rbstate = "rigid_body_state"
RB_STATE_DICT_PAIRS = {
'pos_x': (RBSTATE, rbstate, 'location', 'x'),
'pos_y': (RBSTATE, rbstate, 'location', 'y'),
'pos_z': (RBSTATE, rbstate, 'location', 'z'),
'rot_x': (RBSTATE, rbstate,... |
import numpy as np
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from astropy.io import fits
from .models import DB, Visual_Table
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
from astropy.io import fits
# dataproducts = pd.read_csv('dataproduct... |
from django.db import models
class CaudexerBook(models.Model):
isbn_13 = models.CharField(null=True, blank=True, max_length=300, unique=True)
title = models.CharField(null=True, blank=True, max_length=300)
authors = models.CharField(null=True, blank=True, max_length=300)
categories = models.TextField(... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
%prog csvfile
Draw heatmap based on the data in the csv file. In a microarray setting, the
rows represent genes, and columns represent conditions. Some conditions can be
grouped which the script expect to see on the first row when --groups is on::
,WT+BL,,,,irx8+BL,,... |
'''Load the documents table (documents_table.csv) and extracts the XMLs of each conseil d'etat decisions in the file.
Then saves it to disk, right next to the decision .doc file.
We are mainly interested on the "corrigé" decisions, i.e., those that were corrected because due to a mistake of the
annotation system. So t... |
from typing import List
class Visitable:
def accept(self, visitor):
pass
class Callable(Visitable):
def verify_arguments(self, arguments):
pass
class ExpressionInParenthesis(Visitable):
def __init__(self, expression):
self.expression = expression
def accept(self, visitor):... |
import sys, time, pickle
import itertools
import numpy as np
if len(sys.argv) > 1:
import cupy as cp
cp.cuda.Device(sys.argv[1]).use()
else:
import numpy as cp
### GPU utilities
def to_gpu(x):
""" Move numpy arrays (or dicts of arrays) to GPU """
if type(x) == dict:
retur... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
import requests
import re
import binascii
class Scraper():
def __init__(self, url, failedDir):
self.url = url
self.failedDir = self._set_failed_dir(failedDir)
self.session = None
self.tempFiles = set()
self.headers = {
"User-Agent":"Mozilla/5"
... |
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render
from django.core.mail import send_mail,EmailMultiAlternatives
from .models import NewsletterUser
from .forms import NewsletterUserSignUpForm
from django.template.loader import get_template
from searchBarApp.m... |
u"""
Fixer for standard library imports renamed in Python 3
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, is_probably_builtin, Newline, does_tree_import
from lib2to3.pygram import python_symbols as syms
from lib2to3.pgen2 import token
from lib2to3.pytree import Node, Leaf
from libfuturize.fi... |
#!/usr/bin/env python
"""Module to keep track of paths and versions of other software used within the workflow at various intervals."""
import Bio
import argparse
import getpass
import logging
import os
from subprocess import Popen, PIPE, check_call
import sys
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, N... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''sm2p.py <NAME> 2019 <<EMAIL>
Usage: sm2p.py [options]
Options:
-v --videos=INT Number of videos to output [default: 500]
-c --channels=INT Number of channels to parse per input [default: 1000]
-b --bitchute=FILE HTML save of bitchute subscriptions pa... |
import time
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import *
from lemoncheesecake.matching.matcher import Matcher, MatchResult
MULTI_LINE_TEXT = "- first line\n- second line\n- third line"
class MultipleOf(Matcher):
def __init__(self, value):
self.value = value
def build_des... |
import random
import logging
import pyglet
from .astar import AStar
WORLD_SIZE = 98
ROOM_MAX_SIZE = 16
ROOM_MIN_SIZE = 8
ROOM_MAX_ATTEMPTS = 30
TILE_SIZE = 64
TILE_FLOOR = 10
TILE_WALL = 50
TEXTURE_FLOOR = pyglet.resource.texture('rock_floor.png')
TEXTURE_WALL = pyglet.resource.texture('wall.gif')
class Room:
... |
from io import StringIO
import math
from typing import List, Tuple, Union
from hdlConvertorAst.hdlAst import HdlValueId
from hdlConvertorAst.hdlAst._defs import HdlIdDef
from hdlConvertorAst.to.vhdl.vhdl2008 import ToVhdl2008
from hdlConvertorAst.translate.verilog_to_basic_hdl_sim_model.utils import hdl_call
from hwt.... |
from __future__ import print_function
import argparse
import disasmlib
import difflib
class DiffAsmTree(object):
def __init__(self, elf1, elf2):
self.elf1 = elf1
self.elf2 = elf2
self._correspond_funcs()
self._correspond_blocks()
self._generate_diff()
def _correspond_f... |
import json
import os
import shutil
from datetime import datetime
from pick import pick
from time import sleep
user_names_by_id = {}
user_ids_by_name = {}
dry_run = None
def get_history(pageable_object, channel_id, page_size=100):
messages = []
last_timestamp = None
while True:
response = pagea... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.http.response import StreamingHttpResponse
import cv2
import numpy as np
import datetime
import time
import core.utils as utils
import tensorflow as tf
fro... |
import io
import json
import os
from datetime import date, datetime, time
from types import MappingProxyType
import pytest
import atoml
from atoml import dump, dumps, load, loads, parse
from atoml.exceptions import (
InvalidCharInStringError,
InvalidControlChar,
InvalidDateError,
InvalidDateTimeErro... |
# Minimal classes for loading a 16bpp Grayscale TIF and TFW files
# Allows pixel level sampling and basic (somewhat inaccurate) pixel to world coordinate transformations
#
# Author: <NAME>
# https://github.com/djfurie/GeoTIFF2Rhino
from struct import unpack
class TFWFile:
""" Loads TFW world files and performs c... |
'''
fetch_data.py
python script for fetching velocity and Q models from IRIS. If fetch is succesful,
will process the files and save as .mat files.
Required libraries: xarray, scipy, numpy (all are easily installed with pip)
Works with Python 2 or 3.
'''
try:
import urllib.request as urlrequest
except ImportEr... |
from indra.databases import mesh_client
def test_mesh_id_lookup_from_web():
mesh_id = 'D003094'
mesh_name = mesh_client.get_mesh_name_from_web(mesh_id)
assert mesh_name == 'Collagen', mesh_name
def test_invalid_id():
mesh_name = mesh_client.get_mesh_name_from_web('34jkgfh')
assert mesh_name is N... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import gettext
import multiprocessing
import time
import datetime
from ikabot.config import *
from ikabot.web.session import *
from ikabot.helpers.gui import *
from ikabot.function.donate import donate
from ikabot.function.update import update
from i... |
import re
import statistics
import time
from datetime import datetime, timedelta
from typing import List
from bubbles.config import PluginManager, reddit
SUGGEST_FILTER_RE = r"suggest filter (r\/|\/r\/)?([a-z_-]+)$"
def avg(mylist: List) -> int:
return sum(mylist) / len(mylist)
def balance_queue_modifier(coun... |
from model_seq2seq import *
import numpy as np
from preprocess import *
import matplotlib.pyplot as plt
import random
import os
config = {
'input_shape': (64, 64, 3),
'point_batch_size': 200,
'en_n_layers': 2,
'ef_dim': 32,
'de_n_layers': 2,
'df_dim': 32,
'z_dim': 128,
'partae_file': 'M... |
# init
import lvgl as lv
lv.init()
class driver:
def init_disp_drv(self, flush, hor_res, ver_res, buf_size = 0):
disp_buf1 = lv.disp_buf_t()
if not buf_size: buf_size = (hor_res*ver_res)//4
buf1_1 = bytearray(buf_size)
lv.disp_buf_init(disp_buf1,buf1_1, None, len(bu... |
import sys
IS_PYTHON3 = sys.version_info[0] >= 3
if IS_PYTHON3:
exec("from ._edit_descriptors import *")
exec("from ._exceptions import *")
else:
exec("from _edit_descriptors import *")
exec("from _exceptions import *")
# Some lexer tokens to look out for
DIGITS = ["1", "2", "3", "4", "5", "6", "7", ... |
import os
import sys
import re
import torch
from PIL import Image
from torchvision import transforms
import io
#import asyncio
import time
class TransformerNet(torch.nn.Module):
def __init__(self):
super(TransformerNet, self).__init__()
self.conv1 = ConvLayer(3, 32, kernel_size=9, stride=1)
... |
# Copyright 2020-2021 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 agre... |
import numpy as np
import pandas as pd
from scipy import signal, interpolate
def calculate_itervals_forwards(points):
"""
Similar to numpy.gradient. Acts in forward direction. Adds a Nan at the end to maintain shape.
:param points: A numpy array of sorted fiduciary positions
:return: The beat to beat i... |
import os
import sys
import time
import traceback
import socket
import json
from rflint import RfLint
class RedRfLint(RfLint):
def __init__(self, client, project_location, excluded_paths):
super(RedRfLint, self).__init__()
self._client = client
self._to_exclude = set([os.path.normpath(os... |
# -*- coding: utf-8 -*-
import unicodedata
from aqt import mw
from aqt.utils import showInfo
from aqt.qt import *
_ignore = set(
u"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
u"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
u"abcdefghijklmnopqrstuvwxyz" +
u"12345678901234567890" +
u"あいうゔえおぁぃぅぇぉかきくけこがぎぐげ... |
"""Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Portions of the source code are from the OLTR project which
notice below and in LICENSE in the root directory of
this source tree... |
from django.test import SimpleTestCase, TestCase
from jsonobject.exceptions import BadValueError
from corehq.apps.domain.models import Domain
from corehq.apps.userreports.dbaccessors import (
delete_all_report_configs,
get_all_report_configs,
)
from corehq.apps.userreports.exceptions import BadSpecError
from ... |
# -*- coding: utf-8 -*-
"""
Written by <NAME> and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
import popupcad
import numpy
import shapely.geometry as sg
import popupcad
from popupcad.filetypes.laminate import Laminate
def cleanup3(ls1, value, res):
ls2 = ls1.buffer(-value, re... |
# -*- coding: utf-8 -*-
#
# Copyright 2016 Capital One Services, LLC
#
# 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 xml.etree.ElementTree as ET
import glob
import cv2
from pathlib import Path
import os, errno
import numpy as np
import shutil
from itertools import combinations
import random
from PIL import Image
import copy
#start at 687,3240
#id starts at 672
def firemaker_preprocessing():
base = 'C:/Users/omars/Documen... |
"""
ARA_star 2D (Anytime Repairing A*)
@author: <NAME>
@description: local inconsistency: g-value decreased.
g(s) decreased introduces a local inconsistency between s and its successors.
"""
import os
import sys
import math
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../../Search_... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
""" ALGORITHMS - Low level algorithms module
Description:
algorithms.py contains a number of useful algorithms that are used
throughout the code, but don't nec... |
# Copyright (c) 2006-2019 <NAME>, 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:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and th... |
# -*- coding: utf-8 -*-
import random
from typing import Dict, List, Tuple
from PIL import Image
from torchvision.transforms import transforms
from dataset.base_dataset import _BaseSODDataset
from utils.builder import DATASETS
from utils.io.genaral import get_datasets_info_with_keys
class RandomHorizontallyFlip(obj... |
from datetime import datetime, timedelta, date
from django.shortcuts import render, get_object_or_404
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse, reverse_lazy
from django.utils.safestring import mark_safe
from django.views import generi... |
'''
Using the global view
=====================
The `addresses` view provides access to all the addresses registered in the DB,
as well as methods to create and remove them::
eth0 = ndb.interfaces['eth0']
# create an address
(ndb
.addresses
.create(address='10.0.0.1', prefixlen=24, index=eth0[... |
"""
Sbanken accounts sensor
For more details about this platform, please refer to the documentation at
https://github.com/toringer/home-assistant-sbanken
"""
import asyncio
import logging
import datetime
import voluptuous as vol
from random import randrange
import homeassistant.helpers.config_validation as cv
fro... |
#!/usr/bin/env python
'''
order_milp.py
Implementation of MILP for ordering scalar adjective
from DeMelo & Bansal 2013 (follows DeMelo code RankerILP.java)
'''
import os, sys
import numpy as np
import argparse
import itertools
from ortools.linear_solver import pywraplp
def load_terms(tf):
terms = set()
with... |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
from keras.layers import Dense
from keras.models import Sequential
from keras.losses import binary_crossentropy, mean_squared_error
from keras.optimizers import SGD
from keras.callbacks i... |
"""Record simulated exposures and collect per-tile statistics.
"""
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy.io.fits
import desiutil.log
import desisurvey.config
import desisurvey.tiles
class ExposureList(object):
"""Record simulated exposures and colle... |
# -*- coding: utf-8 -*-
#
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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... |
def is_output_parameter(parameter):
return "out" in parameter["direction"]
def is_input_parameter(parameter):
return "in" in parameter["direction"]
def is_array(dataType):
return dataType.endswith("[]")
def is_enum(parameter):
return "enum" in parameter or "mapped-enum" in parameter
def is_struct(parame... |
"""Config flow for Plugwise integration."""
import logging
from plugwise.exceptions import InvalidAuthentication, PlugwiseException
from plugwise.smile import Smile
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
CONF_BASE,
CONF_HOST,
C... |
# coding: utf-8
from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, Integer, String, Table, Text, text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
t_active_clients_last_year = Table(
'active_client... |
import dataclasses
import math
from typing import Union
import pytest
from pycertainties.val import Real, Val
@pytest.mark.parametrize(
"val1, val2, expected",
(
(Val(10, math.sqrt(7)), Val(5, math.sqrt(2)), Val(5, 3)),
(Val(10, 3.21), 2, Val(8, 3.21)),
(10, Val(5, 3.21), Val(5, 3.21... |
"""
Tools for interacting with soundfiles.
"""
import hashlib
import os
import pathlib
import shlex
import subprocess
import uqbar.strings
import supriya
from supriya.system import SupriyaObject, SupriyaValueObject
try:
import wavefile # type: ignore
except ImportError:
pass
class Say(SupriyaValueObject):... |
# !/usr/bin/env python
# Converts a single colour to primary, secondary and tertiary colours.
# Primary Colour - The colour given
# Secondary Colour - Lightens the primary colour by .8
# Tertiary Colour - Darkens the primary colour by .2
#
# Copyright 2012 Google LLC
#
# Licensed under the Apache License, Versi... |
from Environment import Environment
import os
import numpy as np
from QTableAgent import QTableAgent
import pickle
from random import randint
from matplotlib import pyplot as plt
SOURCE_DEMAND_STATE = 'demand'
SOURCE_SMART_LOADS = 'smart_load'
SOURCE_LEARNING_RATE = 'slr'
SOURCE_DISCOUNT_FACTOR = 'sdf'
SOURCE_NUM_LOA... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import calendar
from frappe import _
from frappe.utils import flt, getdate
from datetime import datetime
from dateutil import relativedelt... |
"""
"""
import began
import numpy as np
import tensorflow as tf
from six.moves import range
FLAGS = tf.app.flags.FLAGS
def load_vectors():
"""
Load 4 vectors specified by parameters. Use uniform random vectors if the
path is invalid.
"""
vectors = []
for i in range(4):
path = FLAGS... |
# 201006 TGE: add finding computation that is missing a termination in the last job as ERR - this was previously only found if this happened in the first=only job in a log file
import os,shutil
import pathlib as pl
import re
ligname = re.compile("[0-9]{8}")
def copy_other():
cwd = pl.Path.cwd()
files... |
from django.db import models
from django.utils import timezone
class GeoLocation(models.Model):
latitude = models.FloatField()
longitude = models.FloatField()
elevation = models.FloatField(null=True, blank=True)
class Site(models.Model):
'''An installation of Chain API, usually on the scale of sever... |
import sys
import numpy as np
from pandas import DataFrame
import pdb
class Product(object):
def __init__(self, name, demand_dist,
lead_time_dist, initial_inventory, price):
self.name = name
self.demand_dist = demand_dist
self.lead_time_dist = lead_time_dist
self.... |
#IMPORTING IMPORTANT MODULES
import tensorflow as tf
from tensorflow.keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras import layers
import time
from tensorflow.keras.models import Sequential, load_model
#LOADING DATASET (check dataset pat... |
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.keras.layers import Layer, BatchNormalization, Conv2D
from tensorflow.keras import Model
tfd = tfp.distributions
tfb = tfp.bijectors
class NN(Layer):
def __init__(self,
input_shape,
n_hidden=[512, 512],... |
# Copyright 2017 PerfKitBenchmarker 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 appli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.