content stringlengths 5 1.05M |
|---|
import json
from pyex.api import PyexAPIBuilder, Exchange
if __name__ == "__main__":
with open('api.json', 'r', encoding='utf-8') as f:
obj = json.loads(f.read())
api_key = obj['api_key']
secret_key = obj['secret_key']
passphrase = obj['passphrase']
api = PyexAPIBuilder().api_key(api_key)... |
import unittest
from roadsearch.tests.abstract_test import AbstractTest
from roadsearch.generators.mutators.mutations import ListMutator, ValueAlterationMutator
from roadsearch.generators.exploiters.exploiters import FirstVariableExploiter
from roadsearch.generators.representations.kappa_generator import KappaGenerator... |
from datetime import datetime
from bson.objectid import ObjectId
from werkzeug.exceptions import InternalServerError, BadRequest, NotFound, Conflict
from bdc_oauth.users.business import UsersBusiness
from bdc_oauth.utils.helpers import random_string
from bdc_oauth.utils.base_mongo import mongo
class ClientsBusiness()... |
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
def __str__(self):
return self.get_full_name() or self.username
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Dict, List, Optional
ATTRIBUTES = "attributes"
def metadata_to_dict(
values: List[str],
ignore_columns: List[int],
ignored_values: Optional[List[str]],
keys: List[str]
) -> Dict[str, str]:
"... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from jobbing.models.base_model_ import Model
from jobbing import util
class Municipality(Model):
def __init__(self,
id_municipality:int = None,
municipality_na... |
import re
from robobrowser import RoboBrowser
def is_ascii(s):
return all(ord(c) < 128 for c in s)
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
t... |
# Gregary C. Zweigle, 2020
import fifo
import numpy as np
import pyaudio
import time
class AudioInOut:
def __init__(self, rate, chunk, downwsample_ratio, fifo_length):
#self.last_time = time.time()
#self.get_last_time = time.time()
self.fifo = fifo.Fifo(fifo_length)
self.width = 2... |
from django import test as django_test
from django.contrib.auth import get_user_model
from django.urls import reverse
from final_project.accounts.helpers import UserAndProfileData
from final_project.accounts.models import Profile
from final_project.main.models import Post
from final_project.main.tests_main.views.tests... |
from randomplushmiku import myfunctions
def test_lib():
assert myfunctions.multiplemikus(2) == 2 |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import F... |
import nicehash
# For testing purposes use api-test.nicehash.com. Register here: https://test.nicehash.com
# When ready, uncomment line bellow, to run your script on production environment
host = 'https://api2.nicehash.com'
# How to create key, secret and where to get organisation id please check:
# Production -... |
#!/usr/bin/python
"""
based on
PyAudio + PyQtGraph Spectrum Analyzer
Author:@sbarratt
Date Created: August 8, 2015
and Spectrum Analyzer with STFT see Yumi's blog
https://fairyonice.github.io/implement-the-spectrogram-from-scratch-in-python.html
as modified by waszee Oct 12, 2020
this version is using sounddevice inst... |
from karel.kareldefinitions import *
class Karel():
def __init__(self, world):
self._world = world
self._avenue, self._street = self._world.karel_starting_location
self._direction = self._world.karel_starting_direction
self._num_beepers = self._world.karel_starting_beeper_count
@property
def avenue(self... |
'''
@Author: Zhang Ruihan
@Date: 2019-10-28 01:01:52
@LastEditors : Zhang Ruihan
@LastEditTime : 2020-01-07 01:33:49
@Description: file content
'''
import numpy as np
import os
import torch
from torch.utils.data import TensorDataset,DataLoader
class ModelWrapper:
def __init__(self,model,batch_size = 128):
... |
##############################################################################
#
# Unit tests for beamsplitter operations
# Convention: The beamsplitter operation transforms
# \hat{a} -> t \hat{a} + r \hat{b}
# \hat{b} -> - r^* \hat{a} + t^* \hat{b}
# where \hat{a}, \hat{b} are the photon creation operators of the two ... |
#
# PySNMP MIB module A3Com-IPXpolicy-r3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-IPXPOLICY-R3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:08:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
import copy
from data_holder import State, Move
from simulation_data import get_sample
from utils import positive_list_difference
#SAMPLES DIAGNOSIS MOLECULES LABORATORY Start area
#SAMPLES 0 3 3 3 2
#DIAGNOSIS 3 0 3 4 2
#MOLECULES 3 3 0 3 2
#LABORATORY 3 4 3 0 2
#Start area 2 2 2 2 0
from data_holder impor... |
#!/usr/bin/env python
"""
_ListOpenByName_
MySQL implementation of Fileset.ListOpenByName
"""
__all__ = []
from WMCore.Database.DBFormatter import DBFormatter
class ListOpenByName(DBFormatter):
sql = "SELECT name FROM wmbs_fileset WHERE open = 1 AND name LIKE :name"
def format(self, results):
"""... |
#!/usr/bin/env python
# Copyright (C) 2017 Google 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 la... |
from urllib.parse import quote_plus
from typing import Optional
from re import search
from ..http import Http
from ..constants import AUTHORIZE
from ..models import PreAuthResponse, UserLoginResponse
from ..errors import InvalidCredentials, TwoFactorAccount, MsMcAuthException
__all__ = ("Xbox",)
class Xbox:
""""... |
# Copyright (c) 2015 Jonathan M. Lange <jml@mumak.net>
#
# 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... |
from optparse import IndentedHelpFormatter
from nndl.optim import sgd
import numpy as np
import matplotlib.pyplot as plt
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We... |
from pykechain.enums import Category, Multiplicity
from pykechain.exceptions import NotFoundError, MultipleFoundError, IllegalArgumentError
from pykechain.models import PartSet, Part
from pykechain.utils import find
from tests.classes import TestBetamax
class TestPartRetrieve(TestBetamax):
# 1.8
def test_get_... |
import re
base_url = 'https://sede.administracionespublicas.gob.es'
# base_url = 'http://127.0.0.1:5000' # for local simulation
no_cita_message = 'En este momento no hay citas disponibles.'
error_503_message = 'ERROR [503]'
nie_pattern = re.compile(r'^[XYZ]\d{7,8}[A-Z]$')
hidden_params_pattern = re.compile(
r'><i... |
import os
from cqlengine import connection
from cqlengine.management import create_keyspace
def setup_package():
try:
CASSANDRA_VERSION = int(os.environ["CASSANDRA_VERSION"])
except:
print("CASSANDRA_VERSION must be set as an environment variable. "
"One of (12, 20, 21)")
... |
from flask_httpauth import HTTPBasicAuth
from flask import g, request
from datetime import datetime
import pytz
from app.ext.database import db
# Tables
from app.models.tables import User as UserTable
# Integration
from app.integration.user import User
auth_api = HTTPBasicAuth()
@auth_api.verify_password
def verif... |
import pytest
from io import BytesIO
from pathlib import Path
import can_decoder
from tests.LoadDBCPathType import LoadDBCPathType
@pytest.mark.env("canmatrix")
class TestLoadDBC(object):
@pytest.mark.parametrize(
("input_type",),
[
(LoadDBCPathType.LoadDBCPathType_STR, ),
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/core/node/domain/service/request_answer_response.proto
"""Generated protocol buffer code."""
# third party
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_p... |
import asyncio
def get_loop():
return asyncio.get_event_loop()
|
import json
import gzip
import pickle
def read_lines(path):
with open(path) as f:
for line in f:
yield line
def read_json(path):
with open(path) as f:
object = json.loads(f.read())
return object
def write_json(object, path):
with open(path, 'w') as f:
f.write(js... |
#
# PySNMP MIB module BAY-STACK-IPV6-MLD-SNOOPING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-IPV6-MLD-SNOOPING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:35:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
# define: forward propagation code(python version)
# date: 2022.1.19.
# Resource: 밑바닥부터 시작하는 인공지능(사이토고키, 2017)
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size):
I, H, O = input_size, hidden_size, output_size
#initialization of weight value
W1 = np.random.randn(I, H)
b1 = np.rand... |
import board
import busio
import time
import usb_hid
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_jp import KeyboardLayoutJP
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
import board
import digitalio
import config
import displayio
... |
import sys
sys.path.append('..')
from persistence.bot_reader import BotReader
from persistence.server_writer import ServerWriter
from server.cli import CliServer
sys.path.append('..')
def start_cli():
bot = BotReader('../bots/default.json').load()
server = CliServer(bot)
ServerWriter(server).write('../s... |
# Knight On Chess Board
# https://www.interviewbit.com/problems/knight-on-chess-board/
#
# Given any source point and destination point on a chess board, we need to find whether Knight can move to the destination or not.
#
# Knight's movements on a chess board
#
# The above figure details the movements for a knight ( 8... |
from graphql import GraphQLField, GraphQLFieldMap, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema
from sqlalchemy.ext.declarative import DeclarativeMeta
from .args import (
make_args,
make_delete_args,
make_insert_args,
make_insert_one_args,
make_pk_args,
make_update_args,
ma... |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed by CFS ENGINEERING, 1015 Lausanne, Switzerland
Module to export Aeromap (or other data?) to CSV
Python version: >=3.6
| Author: Aidan Jungo
| Creation: 2021-04-07
| Last modifiction: 2021-04-08
TODO:
* export of other data...
*
"""
#==========... |
#!/usr/bin/python
#vim:fileencoding=utf-8
#参考: 「python+OpenCVで顔認識をやってみる」
# http://qiita.com/wwacky/items/98d8be2844fa1b778323
import cv2, sys
#画像を読み込む
img = cv2.imread("/home/pi/face.jpg")
#処理用に変換
gimg = cv2.cvtColor(img,cv2.cv.CV_BGR2GRAY)
#顔識別用のデータをロード
classifier = "/usr/share/opencv/haarcascades/haarcascade_front... |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
documents = client.sync \
... |
from . import consts
from .app import start_web_server
if __name__ == "__main__":
start_web_server(port=consts.WEBSERVER_PORT, host=consts.WEBSERVER_HOST)
|
# 教學: https://www.youtube.com/watch?v=YQboCnlOb6Y
# 1. 寄送email的程式
# 2. 準備訊息物件設定
import email.message
msg = email.message.EmailMessage()
msg["From"] = "georgiawang5332@gmail.com" # 寄件人
# msg["To"] = "nunumary5798@gmail.com" # 有效收件人
msg["To"] = "wleejan982@hotmail.com" # 有效收件人
msg["Subject"] = "你好,玥玥"
# 3. 寄送純文字內容
# m... |
import typing
from d3m.metadata import hyperparams, base as metadata_module, params
from d3m.primitive_interfaces import base, transformer, unsupervised_learning
from d3m import container, utils
import os
import numpy as np
__all__ = ('GRASTA',)
Inputs = container.ndarray
Outputs = container.ndarray
class GRASTAHyp... |
import scrapy
from urllib.parse import urlparse, parse_qs, urljoin
from ..items import Spot
class PlayAdvisorSpider(scrapy.Spider):
name = "play_advisor"
start_urls = [
"https://playadvisor.co/zoeken/?_sft_speelplektype=sport-fitness&_sf_s=&_sft_land=nederland",
]
def parse(self, response):
... |
"""
The mainwindow module.
"""
import os
import shutil
from multiprocessing import Process
from PyQt4.QtCore import (Qt, QDir, QFile, QFileInfo, QIODevice,
QPoint, QSize, QTextStream, QUrl)
from PyQt4.QtGui import (qApp, QAction, QCheckBox, QDesktopWidget, QDialog,
QDockWidget, QFileDialo... |
import os
import tempfile
import urllib.error
import zeit.cms.testing
import zope.app.appsetup.product
class HealthCheckTest(zeit.cms.testing.ZeitCmsBrowserTestCase):
check = 'http://localhost/++skin++vivi/@@health-check'
def setUp(self):
super().setUp()
self.browser = zeit.cms.testing.Brows... |
default_app_config = "backend.reviews.apps.ReviewsConfig" |
#!/usr/bin/python3
# author: Charlotte Bunne
# imports
import jax
import jax.numpy as jnp
import numpy as np
import optax
# internal imports
from jkonet.utils.helper import count_parameters
from jkonet.utils.optim import global_norm, penalize_weights_icnn
from jkonet.models import fixpoint_loop
from jkonet.models.los... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
from django.urls import reverse
# Create your models here.
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager... |
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import scipy.linalg
import scipy.sparse
import scipy.sparse.linalg
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_is_fitted
from datafold.dynfold.base import TransformType, TSCTransformerMix... |
import webob
from prestans import exception
from prestans.http import STATUS
from prestans.parser import AttributeFilter
from prestans import serializer
from prestans.types import Array
from prestans.types import BinaryResponse
from prestans.types import DataCollection
from prestans.types import Model
class Response... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from djangocms_link_manager import __version__
INSTALL_REQUIRES = [
'django>=1.8.0',
'django-cms>=3.0',
'phonenumberslite>=7.4,<8.0',
'attrs',
]
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIF... |
# (C) Copyright 2019 Hewlett Packard Enterprise Development LP.
# 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 ... |
__all__ = ('ResultGatheringFuture',)
import reprlib
from ...utils.trace import format_callback
from ..exceptions import InvalidStateError
from .future import FUTURE_STATE_FINISHED, FUTURE_STATE_PENDING, Future
class ResultGatheringFuture(Future):
"""
A Future subclass, which yields after it's result was s... |
from collections import defaultdict
import unicodedata
import re
ca_fr = "Montréal, über, 12.89, Mère, Françoise, noël, 889"
yo_0= "ọjọ́ìbí 18 Oṣù Keje 1918 jẹ́ Ààrẹ Gúúsù Áfríkà"
yo_1 = "Kí ó tó di ààrẹ"
def strip_accents(string):
return ''.join(c for c in unicodedata.normalize('NFD', string)
... |
import argparse
import json
import os
from datetime import datetime
from annotation_predictor.util.groundtruth_reader import GroundTruthReader
from settings import annotation_predictor_metadata_dir
evaluation_record = {}
def extract_gt(path_to_images: str, path_to_gt: str):
"""
Extracts ground truth data for... |
import numpy as np
class NeuralNetwork:
def __init__(self, layers, alpha=0.1):
"""
The constructor of the Neural Network
-----------------------------------
Each neural network consists of input nodes, at least 1 hidden layer and an output layer
:param layers: list of inte... |
Import("env")
import time, os
def before_upload(source, target, env):
print "before_upload: resetting GPIO18 for Alamode"
os.system("sudo gpio export 18 out")
os.system("sudo gpio write 18 0")
time.sleep(0.1)
os.system("sudo gpio write 18 1")
os.system("sudo gpio unexport 18")
env.AddPreAction("upload", ... |
import construct
import numpy as np
def read_tec_str(byte_list):
if not len(byte_list) == 4:
return {'Correct' : False}
check = construct.Int32ul.parse(byte_list)
if not check == 0:
return {'Correct':True, 'str': chr(byte_list[0]), 'End':False}
return {'Correct':True, 'str': '','End':T... |
"""Generic GeoJSON feed."""
import logging
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from aio_geojson_client.feed import GeoJsonFeed
from aiohttp import ClientSession
from geojson import FeatureCollection
from .feed_entry import GenericFeedEntry
_LOGGER = logging.getLogger(__name__... |
import pytest
from opera.error import ParseError
from opera.parser.tosca.integer import Integer
from opera.parser.yaml.node import Node
class TestValidate:
def test_with_int_data(self):
Integer.validate(Node(1234))
@pytest.mark.parametrize("data", ["4", (), (1, 2, 3), [], ["a", "b"], {}])
def te... |
from discord import Embed
from discord.ext import commands
from time import time
from collections import namedtuple
from src.internal.bot import Bot
from src.internal.context import Context
TimedResult = namedtuple('TimedResult', ["time", "rv"])
class Topics(commands.Cog):
"""Get topics for discussion."""
... |
"""
statistics
---------
Calculate trading statistics
"""
# Use future imports for python 3.0 forward compatibility
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
# Other imports
import pandas as pd
import numpy as n... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from absl.testing import absltest
from grr_response_server import blob_store_test_mixin
from grr_response_server import db_test_mixin
from grr_response_server.data... |
#!/usr/bin/env python3
"""
Paxos application class is part of a thesis work about distributed systems
Two main threads are created, one with an UDP socket and one with a TCP socket
UDP socket - Command exchange - ADHOC commands sent in the ether
TCP socket - Data exchange
The membership is controlled by the network ... |
from __future__ import division, print_function, absolute_import
import numpy as np
from matplotlib import pyplot as plt
def overlay_args(**kwargs):
""" convernience function for populating overlay kwargs """
args = {}
args['vmin'] = kwargs.pop('vmin', None)
args['vmax'] = kwargs.pop('vmax', None)
... |
# This code is heavily based on the code from MLPerf
# https://github.com/mlperf/reference/tree/master/translation/tensorflow/transformer
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import tensorflow as tf
from six.moves import range
from open_seq2seq.part... |
from typing import Type
from os.path import join
from importlib import import_module
from restiro import Parser, DocumentationRoot
from restiro.helpers import generate_pot
from restiro.generators import BaseGenerator
class Documentor:
def __init__(self, title: str, source_dir: str, base_uri: str=None,
... |
# Simple list of site URLs
# Import external modules
import logging
import os
import webapp2
# Import local modules
import configuration
import httpServer
import user
class SiteList( webapp2.RequestHandler ):
def get(self):
templateValues = { }
httpServer.outputTemplate( 'siteList.html', templa... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from mmcv.utils import TORCH_VERSION, digit_version
from ...dist_utils import master_only
from ..hook import HOOKS
from .base import LoggerHook
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
def log_images_to_te... |
# encoding: utf-8
"""
Shader and ShaderProgram wrapper classes for vertex and fragment shaders used
in Interactive Data Visualization
"""
import contextlib
import ctypes
import os
from collections import OrderedDict
import traitlets
import yaml
from OpenGL import GL
from yt.units.yt_array import YTQuantity
from yt.ut... |
from cemc.mcmc import Montecarlo, TooFewElementsError
from itertools import combinations_with_replacement, combinations
import numpy as np
import time
class ChemicalPotentialROI(object):
"""
Class that identifies interesting chemical potentials to study.
The algoritthm performs the following steps
"""
... |
import re
from . import Encoder
class DelimitedNumberEncoder(Encoder):
"""
This encoder can en-/decode numbers with delimiters.
While the prefix and suffix will be restored upon decoding, the delimiters will be removed.
Prefix and suffix can contain arbitrary characters. Delimiters are non-word chara... |
import feedparser
import requests
from bs4 import BeautifulSoup
import re
def get_dl(url):
r = requests.get(url)
with requests.Session() as req:
download = req.get(url)
if download.status_code == 200:
return download
return 0
def get_new_dls_(path_pods,sub_folder,new_titles):
... |
#-------------------------------------------------------------------------------
# Name: 妯″潡1
# Purpose:
#
# Author: zhx
#
# Created: 17/05/2016
# Copyright: (c) zhx 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import openpyxl
def... |
#
# PySNMP MIB module UPPHONEDOTCOM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UPPHONEDOTCOM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:21:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# encoding: utf-8
from __future__ import division, print_function, unicode_literals
###########################################################################################################
#
#
# Palette Plugin
#
# Read the docs:
# https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/Palette
#
... |
from twitchio.ext import commands
import socket
import time
from dotenv import dotenv_values
class Bot(commands.Bot):
config = dotenv_values(".env")
def __init__(self):
# Initialise our Bot with our access token, prefix and a list of channels to join on boot...
# Make sure token is non-empty
... |
"""
========================
Custom Figure subclasses
========================
You can pass a `.Figure` subclass to `.pyplot.figure` if you want to change
the default behavior of the figure.
This example defines a `.Figure` subclass ``WatermarkFigure`` that accepts an
additional parameter ``watermark`` to display a c... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: william wei
@license: Apache Licence
@contact: weixiaole@baidu.com
@file: config.py
@time: 15/01/2018 11:27 AM
"""
import toml
import os
from core import container
APP_PATH = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
... |
import unittest
import json
from sqlalchemy import Table, Column, Integer, String, MetaData
from sqlalchemy import create_engine
# from dbsync import DBSync
from dbsync.stores.rdbms import DatabaseStore
from dbsync.stores.local import LocalStore
from dbsync.syncers.pool import ThreadPoolSyncer
from datetime import da... |
"""Setup file for tensorbayes
For easy installation and uninstallation, do the following.
MANUAL INSTALL:
python setup.py install --record files.txt
UNINSTALL:
cat files.txt | xargs rm -r
"""
from setuptools import setup, find_packages
import os
setup(
name="tensorbayes",
version="0.4.0",
author="Rui Shu... |
# -*- coding: utf-8 -*-
import hmac
import hashlib
from rest_framework import permissions
from rest_framework import exceptions
from framework import sentry
from website import settings
class RequestComesFromMailgun(permissions.BasePermission):
"""Verify that request comes from Mailgun.
Adapted here from co... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Item
# Create your views here.
def index(request):
return HttpResponse(', '.join([item.name for item in Item.objects.order_by('name')]))
|
from .rsmaker import RunstatMaker
|
global type_dict
type_dict=dict()
global tmp_var
tmp_var=[]
global err_flag
err_flag=0
global bottom_flag
bottom_flag=0
def is_var(var_name):
if len(var_name)==0:
return False
if var_name[0]!='`':
return False
x=var_name[1:]
tmp_len=len(x)
if tmp_len==0:
return False
e... |
# Copyright 2022 Zilliz. 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 or agree... |
// driver function
// para editar
|
import unittest
from unittest.mock import Mock, patch
from pywoo import Api
from pywoo.models.orders_notes import OrderNote
from .tools import mock_request
class TestOrderNote(unittest.TestCase):
@patch('pywoo.pywoo.requests.api.request', side_effect=mock_request)
def test_api_post(self, func):
api... |
#################################################################
# collisionWindow.py
# Written by Yi-Hong Lin, yihhongl@andrew.cmu.edu, 2004
#################################################################
# Import Tkinter, Pmw, and the floater code from this directory tree.
from direct.tkwidgets.AppShell import *
f... |
# -* encoding: utf-8 *-
import logging
import time
from django.apps.config import AppConfig
from django.db import utils as django_db_utils
from django.db.backends.base import base as django_db_base
from django.dispatch import Signal
from typing import Union, Tuple, Callable, List # noqa. flake8 #118
_log = logging... |
"""Identify files to be moved to their final destination directories"""
import logging
import re
import shutil
from pathlib import Path
from osa.configs import options
from osa.configs.config import cfg
from osa.paths import destination_dir
from osa.utils.logging import myLogger
from osa.veto import set_closed_sequen... |
import ast
import os
import sys
from pymake3 import report
from pymake3.cli import info
from pymake3.core import makeconf
# Make configuration specified on command-line.
conf = None
# Indicates whether colors should be disabled when printing to stdout.
disable_color = False
# Whether warnings should be disabl... |
from django.conf.urls import include, url
from django_viewset import URLView
from .backend import BaseBackend
from .views.auth import LoginView, LogoutView
from .views.index import IndexView
class SiteInlineBackends(object):
def __init__(self, site_backend):
self.site_backend = site_backend
def __get... |
import numpy as np
import tikreg.utils as tikutils
def test_determinant_normalizer():
mat = np.random.randn(100,100)
mat = np.dot(mat.T, mat)
det = np.linalg.det(mat)
det_norm = det**(1.0/100.0)
ndet = np.linalg.det(mat / det_norm)
pdet = np.linalg.det(mat/tikutils.determinant_normalizer(mat))... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from haystack.views import search_view_factory
from machina.core.app import Application
from machina.core.loading import get_class
class SearchApp(Application):
name = 'forum_search'
search_view = get_class('f... |
#! /usr/bin/env python
import sys
import json
import csv
import re
import requests
import getpass
import argparse
import collections
def get_data(url, js_path):
user = input("User name for {0}: ".format(url))
passw = getpass.getpass("Password: ")
with open(js_path) as js_file:
js = js_file.read(... |
# coding: utf-8
import sys
import pandas as pd
import olap.xmla.xmla as xmla
from StringIO import StringIO
def xmlamembers2list(itrbl):
result = []
for member in itrbl:
if isinstance(member, list):
label = u''
member_it = iter(member)
s = [None]
... |
import os
import random
import shutil
import subprocess
base_dir = '/Users/ng98/Desktop/avalanche_test/'
core50_dir = '/Users/ng98/.avalanche/data/core50/'
image_dir = core50_dir + 'core50_128x128'
head = '<!DOCTYPE html><html><head><title>CoRe50</title></head><body>'
tail ='</body></html>'
def print_table_NI_DI_ca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.