content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
HDF5 database module.
Store the traces in an HDF5 array using pytables.
Implementation Notes
--------------------
This version supports arbitrary objects through ObjectAtom and VLArray
constructs. Ordinary numerical objects are stored in a Table. Each chain
is stored in an individual group called ``chain#``.
Add... | python |
def getAllCompaniesWithoutBusinessSummary():
return """SELECT uuid, long_name, sector, industry, address, city, state, country, phone, website, logo_url
FROM companies;"""
def getFullCompanyById(companyId):
return f"SELECT * FROM companies C WHERE C.uuid = '{companyId}';"
def getCompa... | python |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2016-2017 GiovanniMCMXCIX
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 us... | python |
import json
import unittest
from django.contrib.auth.models import User
from django.test import Client
def get_user(username):
try:
user = User.objects.get(username=username)
return user
except Exception:
user = User.objects.create_user(username, password='pass')
return user
... | python |
#!/usr/bin/env python
from pathlib import Path
from setuptools import setup
def get_version():
"""
retreive gars_field version information in version variable
(taken from pyproj)
"""
with open(Path("gars_field", "_version.py")) as vfh:
for line in vfh:
if line.find("__version_... | python |
import json
from collections.abc import Mapping
import pytest
import snug
import quiz
from .example import Dog, DogQuery
from .helpers import MockAsyncClient, MockClient
_ = quiz.SELECTOR
def token_auth(token):
return snug.header_adder({"Authorization": "token {}".format(token)})
class TestExecute:
def ... | python |
import pandas
from modin.engines.base.axis_partition import BaseAxisPartition
from modin.data_management.utils import split_result_of_axis_func_pandas
from .remote_partition import DaskRemotePartition
class DaskAxisPartition(BaseAxisPartition):
"""Dask implementation for Column and Row partitions"""
def __i... | python |
#! atenção obrigatorio instalar esta biblioteca
# ! pip install FPDF
#
from fpdf import FPDF
from PIL import Image
local_das_imagens='C:\\Users\\dougl\\Desktop\\projetos\python\\fotos-20210624T144130Z-001\\sapato\\'
class Imagem :
def localizar_imagens (nome_da_imagem,local_das_imagens, numero_de_image... | python |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | python |
from django.urls import re_path
from collector import views
urlpatterns = [
re_path(r'^log/$', views.log, name='log'),
]
| python |
import numpy as np
import open3d as o3d
from src.FrameProcessor import process_frame
from src.metrics.CompositeBenchmark import CompositeBenchmark
from src.output.LabelPrinter import LabelPrinter
from src.output.PointCloudPrinter import PointCloudPrinter
from src.parser import create_input_parser, loaders, annotators,... | python |
from .default import * # noqa
# use postgresql so we test database transactions correctly
DATABASES["default"] = {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "localhost",
"NAME": "oscar_docdata_sandbox",
"USER": "postgres",
"PASSWORD": "",
}
| python |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import json
import typing as t
from dataclasses import dataclass, field
from hmalib.common.logging import get_logger
from hmalib.models import MatchMessage, Label
from hmalib.common.actioner_models import (
ActionLabel,
ThreatExchangeReact... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright... | python |
from Transaction import Transaction
from Block import Block
from datetime import date
class Blockchain:
def __init__(self):
self.chain = [self.createGenisisBlock()]
self.difficulty = 2
self.pendingTransactions = []
self.miningReward = 100
def __str__(self):
chainHistory... | python |
import os
import pandas_gbq
from google.cloud import bigquery
import google.cloud
class pythonbq:
def __init__(self, bq_key_path, project_id, dialect='standard'):
self.credentials=google.oauth2.service_account.Credentials.from_service_account_file(bq_key_path)
self.project_id=project_id
sel... | python |
import dockertarpusher
import sys
def main():
if(len(sys.argv) < 3):
print("Arguments required: {REGISTRYURL} {TARPATH} [LOGIN] [PASSWORD] --noSslVerify")
print("Example: http://localhost:5000 tests/busybox.tar")
sys.exit(1)
url = sys.argv[1]
tarpath = sys.argv[2]
login = None
... | python |
# Copyright 2016 Yogesh Kshirsagar
# 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 require... | python |
"""
Test the GWT with initial concentration of 0 in the model domain and right-hand
side GWT boundary conditions. Versions 6.2.1 and earlier failed because of a
divide by zero error in IMS. This test confirms the fix implemented as part
of the version 6.2.2 release that addressed Issue 655.
"""
import os
import numpy... | python |
"""
Parses files containing urls to product pages
"""
def parse_file(file_path):
"""Parse file with lines: retailer url
Args:
file_path: The path to the url file
Returns:
dict: {'retailer1': 'url1', 'retailer2': 'url2'...}
"""
file = open(file_path)
retailer_dict = {}
f... | python |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
import sys
import os
from onnxruntime.capi import _pybind_state as C
cl... | python |
import term, orientation, system, time, uos, json, badge
system.serialWarning()
term.header(True, "Services")
print("Loading...")
apps = uos.listdir('/lib')
services = []
for app in apps:
if "ledsrv.py" in uos.listdir('/lib/'+app):
services.append(app)
current = badge.nvs_get_str('splash', 'ledApp', None)
while T... | python |
from flask import Blueprint, request, render_template, \
flash, g, session, redirect, url_for, \
jsonify, make_response
from btsapi.modules.vendors.models import Vendor, VendorSchema
from btsapi.extensions import db
import datetime
from sqlalchemy import text
from flask_login import ... | python |
#74270524
"""[32m>> [39m[1m[42mTOTAL: tested 1 platforms, 0/142 tests failed[0m"""
#62977969
"""PASS Coding Rules :: List Actions :: Deactivate (6 tests)
Test file: src/test/js/coding-rules-page-quality-profile-facet.js
PASS coding-rules-page-quality-profile-facet (6 tests)
PASS Coding Rules :: Facets :: Language ... | python |
from .models.type_validator import TypeValidator
from .models.typed_list import TypedList
from utils.star_class_map import spectral_class_map, oddity_map
from config import NMSConfig
class StarClass(object):
config = TypeValidator(dict)
spectral_class_str = TypeValidator(str)
spectral_class = TypeValidat... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Tier IV, 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/LIC... | python |
# import environ
from .settings import *
env = environ.Env(
DEBUG=(bool, False)) # false default
environ.Env.read_env(env_file='./.env')
ALLOWED_HOSTS += [
'kromm.info',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGGING['handlers']['file']['level'] = 'WARNING'
LOGGING['handlers']['file']['filename... | python |
app_set_debug_mode = 0 # 0 = off, 1 on, 2 in/out. 3 all
def weasel_act(valid_answer,response,runquery=True):
return None
| python |
""" Defines project for JPEG library """
Import("*")
from scons_symbian import *
Import("TARGET_NAME UID3 PACKAGE_NAME CAPABILITIES")
# Built as dll because needed by SDL and the application
target = TARGET_NAME
targettype = "dll"
libraries = C_LIBRARY + ['euser']
# Static libs
libraries += []
... | python |
class HydraNotFoundException(Exception):
pass
class MissingKeyParametersError(Exception):
pass
class HydraRunTimeoutException(Exception):
pass
class HydraError(Exception):
pass
| python |
import io
import os
import pandas as pd
import numpy as np
import subprocess
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
import random
try:
api
except NameError:
class api:
class Message:
... | python |
from .data_augmentation_preprocessor import (
DataAugmentationPreprocessor,
DataAugmentationPreprocessor2,
DataAugmentationPreprocessor3,
) # NOQA
from .nchw_preprocessor import NCHWPreprocessor # NOQA
from .normalization_preprocessor import NormalizationPreprocessor # NOQA
from .sequential_preprocessor ... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-12 04:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('newsletter_signup', '0001_i... | python |
import os
import os.path
def normpath(path):
"""Shorthand for os.path.normpath()
Normalizes path variables for your OS"""
return os.path.normpath(path)
def get_most_recent_file(path, key_string = "loss"):
"""File names must end with date formated as DD_MM_YYYY"""
for (dirpath, dirnames, filenames) in os... | python |
from emojitations.emojitypes import EmojiAnnotations
emoji = [
EmojiAnnotations(emoji='😀', codepoints=(128512,), name='față încântată', slug='față_încântată', annotations=frozenset({'încântare', 'față'})),
EmojiAnnotations(emoji='😁', codepoints=(128513,), name='față încântată cu ochi zâmbitori', slug='față_încânt... | python |
import argparse
import datetime
import gym
import numpy as np
import itertools
import torch
from sac import SAC
from cbsac import CBSAC
from torch.utils.tensorboard import SummaryWriter
import pickle
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--env-name', defau... | python |
"""
Copyright (c) 2020 VMware, Inc.
This product is licensed to you under the Apache License, Version 2.0 (the "License").
You may not use this product except in compliance with the License.
This product may include a number of subcomponents with separate copyright notices
and license terms. Your use of these subcomp... | python |
import time
import re
import random
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from app.src.showdownai.exceptions import *
class Selenium():
BASE_URL="http://play.pokemonshowdown.com"
def __init__(self, url=B... | python |
"""
Functions for retrieving strings from files
"""
import os
def string_from_file(string, strip=True):
"""
Return an unaltered string or the contents of a file if the string
begins with @ and the rest of it points at a path.
If 'strip' is True, remove leading and trailing whitespace
(default be... | python |
from ape import plugins
from .explorer import Etherscan
NETWORKS = {
"ethereum": [
"mainnet",
"ropsten",
"rinkeby",
"kovan",
"goerli",
],
"fantom": [
"opera",
"testnet",
],
}
@plugins.register(plugins.ExplorerPlugin)
def explorers():
for ec... | python |
import numpy as np
from .common import Node
from .search import dfs
class findTrails(object):
"""
This class imlpemets a method to find trails
between nodeA and nodeB
"""
def __init__(self, rootNode, nodeA, nodeB, type='BN'):
"""
rootNode: rootnode of a graph
... | python |
import json
from datetime import datetime
from difflib import Differ
from sys import exit, stderr
from typing import Any, Dict, Iterator, List
from github import Github
from loguru import logger
from notifiers.logging import NotificationHandler
from utils import Utility
class SitRep:
"""
SitRep is an automa... | python |
import re
from datetime import datetime
from typing import List
import discord
from PIL import ImageColor
from d4dj_utils.master.card_master import CardMaster
from d4dj_utils.master.event_specific_bonus_master import EventSpecificBonusMaster
from d4dj_utils.master.skill_master import SkillMaster
from miyu_bot.bot.bot... | python |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from orders.views import OrderSuccessView
urlpatterns = patterns('',
# Examples:
url(r'^(?P<id>\d+)/$', 'orders.views.auth_checkout', name='auth_checkout'),
url(r'^add_info/(?P<id>\d+)$', 'orders.views.add_info', name='add... | python |
from dataclasses import dataclass
from blacksheep.server.controllers import Controller, get
from app.configuration import config
@dataclass
class IndexModel:
development: str
url: str
class Welcome(Controller):
@get("/")
def index(self):
return self.view(model=IndexModel(str(config.show_err... | python |
# This code takes a movie title, searches for it in the json file and returns the year if it is present
import json
# Defining the search method
def search(search):
with open("Movies.json") as file:
data = json.loads(file.read())
# Iterating through the json array
for movie in data:
# Fin... | python |
import hashlib
import os
path='fileList.txt'
file_list = open(path,'w')
lists_files_old = []
lists_files_new = []
lists_files_new = os.listdir('new/')
lists_files_old = os.listdir('old/')
for filename in lists_files_new:
for filecompare in lists_files_old:
if filecompare == filename:
hasher ... | python |
from sabueso.tools.file_mmtf import download
| python |
from .DataDecoder import DataDecoder
import h5py
import logging
from pybind_nisar.products.readers import Base
import numpy as np
import pyre
import pybind_isce3 as isce
import re
# TODO some CSV logger
log = logging.getLogger("Raw")
PRODUCT = "RRSD"
def find_case_insensitive(group: h5py.Group, name: str) -> str:
... | python |
"""
LstGen generates php, python, go, or java code from PAP XML
"""
import re
import ast
from lxml import etree
# matches java-like long or double numbers, e.g.
# 123L or 3.12354D
NUMS_WITH_SIZE_RE = re.compile(r'([0-9]+)([LD]{1})')
J2PY_REPLACEMENTS = {
'new BigDecimal': 'BigDecimalConstructor',
'&&': 'and',
... | python |
import unittest
import numpy as np
import tensorflow as tf
import torch
from fastestimator.backend import squeeze
class TestSqueeze(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_np = np.array([[[[1], [2]]], [[[3], [3]]]])
cls.test_output_np = np.array([[1, 2], [3, 3]])
... | python |
from enum import Enum
import configparser
import constants as c
class Server(str, Enum):
NA = 'americas'
EU = 'europe'
ASIA = 'asia'
SEA = 'sea'
class Setting():
def __init__(self):
self.config = configparser.ConfigParser()
self.port = c.PORT_IP
# self.config.read('config... | python |
LOG_LOCATION = '/opt/log/road_collisions/road_collisions.log'
| python |
import os, sys
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import csv
from slicer.util import VTKObservationMixin
import platform
import time
import urllib
import shutil
from CommonUtilities import *
from packaging import version
def _setSectionResizeMode(head... | python |
"""
Support for Neato Connected Vaccums sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.neato/
"""
import logging
import requests
from homeassistant.helpers.entity import Entity
from homeassistant.components.neato import (
NEATO_ROBOTS... | python |
import os
import datetime
from friends_analyzis import *
#import codecs
s = "fb_id:\nmail:\nplec:\nimie:\nnazwisko:\ndata_urodzenia_fb:\ndata_urodzenia_znana:\nnumer_tel:\nmiasto_urodzenia:\nmiejsce_zamieszkania:\nzwiazek:\nnauka:\nprofile_img_src:\n"
def person_in_base(fbid): #if there is no person i base
f = o... | python |
import json
import requests
class ScyllaREST():
def __init__(self, ip='127.0.0.1', port=10000):
self.ip = ip
self.port = port
self.url = 'http://{}:{}'.format(ip, port)
self.headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
... | python |
from events import *
import os
from events import *
from localisation import *
from ideologies import *
from countries import *
class mod_file(game_object):
def __init__(self, directory):
self.directory = directory
self.event_files_dict = {}
self.ideology_dict = {}
self.country_dic... | python |
# Cyclical figurate numbers
# Problem 61
# Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are
# generated by the following formulae:
# Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
# Square P4,n=n2 1, 4, 9, 16, 25, ...
# Pentagonal P5,n=n(3... | python |
#coding:UTF-8
import discord
from datetime import datetime
from discord.ext import tasks
import os
TOKEN = os.environ['DISCORD_BOT_TOKEN']
CHANNEL_ID = 874242284844122172 #チャンネルID
# 接続に必要なオブジェクトを生成
client = discord.Client()
# 60秒に一回ループ
@tasks.loop(seconds=60)
async def loop():
# 現在の時刻
now = datetime.now().str... | python |
try:
from unittest.mock import patch
except ImportError:
# for python 2.7
from mock import patch
| python |
from typing import Callable, Dict
from ..typing import ASGIFramework
from ..utils import invoke_asgi
class DispatcherMiddleware:
def __init__(self, mounts: Dict[str, ASGIFramework]) -> None:
self.mounts = mounts
async def __call__(self, scope: dict, receive: Callable, send: Callable) -> None:
... | python |
# proxy module
from __future__ import absolute_import
from mayavi.scripts.util import *
| python |
import pytest
from computer.adders import half_adder, full_adder, ripple_carry_adder
@pytest.mark.parametrize(
"a, b, sum, carry",
[
("0", "0", "0", "0"),
("0", "1", "1", "0"),
("1", "0", "1", "0"),
("1", "1", "0", "1")
]
)
def test_half_adder(a, b, sum, carry):
s, c =... | python |
"""
Get size of population from width of node
"""
import math
def GetSize(width):
if isinstance(width, str):
width = float(width)
return 100 ** (width/0.3)
def GetWidth(size):
if isinstance(size, str):
size = float(size)
return math.log(size, 100) * 0.3
if __name__ == "__main__":... | python |
import os
from datetime import datetime
import pandas
from sklearn.externals import joblib
from util.data.data_tools import preprocess_load_data_forec
'''
Utility methods to load, clean, select relevant information, and save clean data for load forecasting data
'''
def load_uci_load():
load_processed_path = '.... | python |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... | python |
'''
A simple explicit position prediction script, this time with actions included.
'''
uniform_width = 500
cfg_0 = {
'hidden_depth' : 6,
'hidden' : {
1 : {'num_features' : uniform_width},
2 : {'num_features' : uniform_width},
3 : {'num_features' : uniform_width},
4 : {'num_features' : uniform_width},
5 : ... | python |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import json
import logging
import os
import random
import tempfile
import urlparse
import zipfile
from tempfile import TemporaryFile
impor... | python |
from django.shortcuts import render
from django.views.generic import CreateView
from django.shortcuts import redirect
from django.contrib import messages
from .models import Question
from .forms import AnswerForm
class ReceivedQuestionsView(CreateView):
template_name = "question/received_questions.html"
def... | python |
'''
9. Write a Python program to list all files in a directory in Python.
'''
from os import listdir
from os.path import isfile, join
list_files = [f for f in listdir('C:\\Users\\fortune\Desktop\Hash Analytics\KPMG\Day6 Tasks Solutions')]
print(list_files) | python |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | python |
from datetime import datetime
from enum import Enum, unique
from sqlalchemy.dialects.postgresql import UUID
from . import db
@unique
class Permission(Enum):
FOLLOW = 1
BLACK = 2
WRITE = 4
MODERATE = 8
ADMIN = 16
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(UUID(as_uuid... | python |
class PaymentInitiateFailed(Exception):
pass
class WalletCreationFailed(Exception):
pass
class ChannelCreationFailed(Exception):
def __init__(self, message, wallet_details=None):
super().__init__(message)
self.wallet_details = wallet_details
def get_wallet_details(self):
re... | python |
import pytest
from cattr import BaseConverter, Converter
@pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
def test_unstructure_int(benchmark, converter_cls):
c = converter_cls()
benchmark(c.unstructure, 5)
@pytest.mark.parametrize("converter_cls", [BaseConverter, Converter])
def test_... | python |
# write_FBS_activity_set_EIA_CBECS_Land.py (scripts)
# !/usr/bin/env python3
# coding=utf-8
"""
Write the csv called on in flowbysectormethods yaml files for land use
related EIA CBECS
"""
import flowsa
from flowsa.settings import flowbysectoractivitysetspath
datasource = 'EIA_CBECS_Land'
year = '2012'
if __name__ =... | python |
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import make_pipeline
from sklearn.metrics import silhouette_score
fr... | python |
from .clip import ClipTab
from .compile import CompileTab
from .download import DownloadTab
from .video import VideoPlayer
| python |
# -*- coding:utf-8 -*-
"""
Created on 8/20/2018
Author: wbq813 (wbq813@foxmail.com)
"""
class StrUtil:
# 字符串是否为空
@staticmethod
def is_empty(str_in):
return str_in is None or len(StrUtil.trim(str_in)) == 0
# 去除空格和换行符
@staticmethod
def trim(str_in):
if len(str_in... | python |
import uuid
import json
from flask.ext.redis import FlaskRedis
db = FlaskRedis()
class BadFieldException(BaseException):
pass
class NotFoundException(BaseException):
pass
class TTLDBaseModel(object):
__key_pattern__ = 'nothing'
__fields__ = []
__blacklist__ = ['_meta']
_doc = {}
de... | python |
"""View managment for account and main pages."""
from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models... | python |
# MIT License
#
# Copyright (c) 2019 Tskit Developers
#
# 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, me... | python |
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import random
import string
import logging
# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
from tests.s... | python |
import os
import numpy as np
from lonia.utils import get_config_yaml, normalize, normalize_df
__mapping__ = {
'macro_news': 'MACRO_NEWS',
'international_news': 'INTERNATIONAL_NEWS',
'stock_market': 'VN_STOCK_MARKET',
'banking': 'BANKING',
'oil_and_gas': 'OIL_AND_GAS'
}
class TFRanking(object)... | python |
from flask_restful import Resource
from flask import request, make_response
from app.common.exceptions import StatusCodeException
from app.common.auth import auth
class Token(Resource):
ENDPOINT = '/auth/token'
def post(self):
try:
email = request.data.get('email', None)
pass... | python |
from utils.EarthQuake import EarthQuake
from utils.weiboHS import getWeiboHotSearch
from WechatBot.plugins.ToolsManager import ToolsManager
from apscheduler.schedulers.background import BackgroundScheduler
from .BaiduSignin import BaiduSignIn
import logging
class AutoLaunch(object):
def __init__(self, **utilities)... | python |
"""Minimal test that our parameter derivation logic does what we
expect.
"""
import struct
from hypothesis import given
import hypothesis.strategies as st
from Crypto.Cipher import Salsa20
from umash import C, FFI
@given(
bits=st.integers(min_value=0, max_value=2 ** 64 - 1),
key=st.none() | st.binary(min_size... | python |
# -*- coding: utf-8 -*-
import sys
from UI.element import Element
from IO import Terminal
class Button(Element):
"""A usable Button for user interface
Arguments:
Element {UI.element.Element} -- An Element
"""
def __init__(self, position, label, name="", alignement="left"):
"""Crea... | python |
from typing import Dict, List
from django.contrib.auth import get_user_model
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
User = get_user_model()
def send_html_to_email(
to_list: List,
subject: str,
template_nam... | python |
import os
import unittest
import unittest.mock
from programy.bot import Bot
from programy.clients.polling.twitter.client import TwitterBotClient
from programy.clients.polling.twitter.config import TwitterConfiguration
from programy.storage.config import FileStorageConfiguration
from programy.storage.factory import Sto... | python |
import random
from enum import Enum
from math import factorial
from threading import Thread
OFFSETS = [
(0, -1),
(1, 0),
(0, 1),
(-1, 0),
]
SOLUTION_COUNTER = 0
RNG = random.Random()
DEFAULT_BOARD_WIDTH = 15
DEFAULT_BOARD_HEIGHT = 7
POINTS_PER_COLUMN = [5, 3, 3, 3, 2, 2, 2, 1, 2, 2, 2, 3, 3, 3, 5]
... | python |
import os
import errno
from shutil import copyfile
# os crawler
output_root = '../output'
target = 'to_here'
for path, directory, files in os.walk('../scaffolder/default_folder'):
# path = root.split(os.sep)
print(path, directory, files)
root_directory = path.split('/', 3)[-1]
print('root directory:... | python |
from flask import Flask, request, jsonify
from flask_cors import CORS
from tensorflow import keras
import numpy as np
import math
model = keras.models.load_model('../kulo_model')
app = Flask(__name__)
CORS(app)
# https://www.raspberrypi.org/forums/viewtopic.php?t=149371#p982264
def valmap(value, istart, istop, ostart... | python |
"""
Find more at: https://github.com/l-farrell/isam-ob/settings
"""
import logging
import uuid
from pyisam.util.model import DataObject
from pyisam.util.restclient import RESTClient
NET_INTERFACES = "/net/ifaces"
logger = logging.getLogger(__name__)
class Interfaces(object):
def __init__(self, base_url, use... | python |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
first, second, third = float('-inf'), float('-inf'), float('-inf')
for num in nums:
if num > first:
first, second, third = num, first, second
elif first > num and num > second:
second,... | python |
"""
Python mapping for the CoreLocation framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
import sys
import objc
import Foundation
from CoreLocation import _metadata
from CoreLocation._CoreLocation import *
... | python |
"""
Copyright (c) 2013-2014, Christine Dodrill
All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
inclu... | python |
from torchvision import datasets, transforms
from base import BaseDataLoader
from typing import Optional
import torch
from .wrapped_datasets import CIFAR10WithIndex, CIFAR100WithIndex
import os
import numpy as np
import math
class MnistDataLoader(BaseDataLoader):
"""
MNIST data loading demo using BaseDataLoade... | python |
#!/usr/bin/env python
import os
import sys
from collections import defaultdict
from goatools import obo_parser
def make_go_term_dict(obo):
go_terms = obo_parser.OBOReader(sys.argv[1])
go_term_dict = {}
for go in go_terms:
go_term_dict[go.id] = go.name
if go.alt_ids:
for id in g... | python |
"""
ASGI config for main project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import g... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.