content stringlengths 5 1.05M |
|---|
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
# Import core packages
import os
# Import Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# Inject Flask magic
app = Flask(__name__)
# Load configuration
app.config.from_object('app.... |
import click
from koapy.cli.utils.credentials import get_credentials
from koapy.cli.utils.verbose_option import verbose_option
@click.group(short_help="Update openapi module and metadata.")
def update():
pass
@update.command(short_help="Update openapi TR metadata.")
@verbose_option()
def trinfo():
from koa... |
from collections import defaultdict
import tensorflow as tf
import numpy as np
import csv
import hashlib
from pathlib import Path
import re
FOLDER_LOCATION = 8
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def bytes_feature(value):
return tf.train.Feature(bytes_lis... |
"""Coin change Problem"""
"""
EX:
Change for $51 using ($1, 2, 5, 10, 20)
Greedy Approach
Subtract largest bills
51 -20 = 31 - 20 = 11 - 10= 1 - 1= 0
20, 20, 10, 1 = 5 bills
What if bills to use were (3, 5, 7, 11)?
Smallest # bills for $13?
13 - 11 = 2 Can't go further
C dollars want to use 1 d dolla... |
from typing import Any
class BinaryNode:
value: Any
left_child: 'BinaryNode'
right_child: 'BinaryNode'
def __init__(self,val: Any):
self.value=val
self.left_child=None
self.right_child=None
def min(self):
if self.left_child!=None:
return self.left_child... |
"""
INTERNAL FUNCTIONS FOR XViewMiddleware and ViewPanel
"""
import sys
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
if sys.version_info[0] >= 3:
string_types = str
else:
string_types = basestring
def track_view_name(reques... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mERRO: por favor, digite um número inteiro válido.\033[m')
continue
except(KeyboardInterrupt):
print('\033[31mUsuário preferiu não di... |
from pckg1 import A
|
import numpy as np
def polynomial_interpolate(x, y):
M = [[x_i ** i for i in range(len(x))] for x_i in x]
a = np.linalg.solve(M, y)
def p(t):
return sum(a_i * t ** i for i, a_i in enumerate(a))
return p
def linear_curve_fit(x, y):
x = np.array(x)
y = np.array(y)
n = len(x)
... |
#!/usr/bin/env python3
"""
Author : Christian Ayala <[email protected]>, Viviana Freire <[email protected]>
Date : 2021-04-19
Purpose: Generate jobs scripts to be submitted to the UA HPC clusters
"""
import argparse
import subprocess
import os
import glob
import pandas as pd
# -----------... |
#!/awips2/python/bin/python
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. ... |
#!/usr/bin/env python3
# encoding: utf-8
"""
insertion_sort.py
Created by Jakub Konka on 2011-11-01.
Copyright (c) 2011 University of Strathclyde. All rights reserved.
"""
import sys
import random as rnd
def insertion_sort(array):
'''This function implements the standard version of the
insertion sort algorithm.
... |
"""Collect from Phoenix Contact SOLARCHECK String Monitor and send the data to your cloud using Ardexa
See:
https://github.com/ardexa/solarcheck-strings
"""
from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README... |
# Generated by Django 4.0.2 on 2022-02-13 10:29
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('todoapp_backend', '0003_alter_task_options_alter_task_created_at'),
]
operations = [
m... |
#!/usr/bin/env python
"""General demonstrations /w set start and goal
"""
import os
import numpy as np
import yaml
# pylint: disable=invalid-name
# pylint: disable=import-error
# pylint: disable=wrong-import-position
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
traj_path = os.path.join(pare... |
from athena import ndarray
from athena import gpu_links as gpu_op
from athena import gpu_ops as ad
import numpy as np
import argparse
import six.moves.cPickle as pickle
import gzip
import os
import pdb
import time
import logging
from athena import gpu_memory_manager
channel_axis = 1
variable_list = []
... |
"""
Manages the displaying of the characters.
--
Author : DrLarck
Last update : 18/10/19 (DrLarck)
"""
# dependancies
import asyncio
# icons
from configuration.icon import game_icon
from configuration.color import game_color
# config
from configuration.bot import Bot_config
# utils
from utility.cog.character.get... |
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
#NAME_FILE = "demo/cat.jpg"
model = tf.keras.models.load_model("modelo/model.h5")
def convertir_imagen_para_modelo(nombre_imagen):
img = image.load_img(nombre_imagen, target_size=(150, 150))
x = image.img_to_array(img... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenMiniInnerversionAuditstatusModifyModel(object):
def __init__(self):
self._app_version = None
self._audit_memo = None
self._audit_result = None
self._mini... |
from flask.json import jsonify
from db import Database
from flask import Flask, render_template, make_response
class Api:
def __init__(self) -> None:
self.app = Flask(__name__)
self.db = Database()
def set_route(self):
self.app.add_url_rule('/', 'index', self.index)
self.a... |
# fileName : Plugins/dm/txt2pdf.py
# copyright ©️ 2021 nabilanavab
import os
from fpdf import FPDF
from pdf import PROCESS
from pyrogram import filters
from Configs.dm import Config
from pyrogram import Client as ILovePDF
from pyrogram.types import InlineKeyboardButton
from pyrogram.types import InlineKeyboardMarkup
... |
from . import NamedEndpoint
from .urls import LeagueApiV3Urls
class LeagueApiV3(NamedEndpoint):
"""
This class wraps the League-v3 Api calls provided by the Riot API.
See https://developer.riotgames.com/api-methods/#league-v3/ for more detailed information
"""
def __init__(self, base_api):
... |
"""
Copyright (C) 2018 University of Massachusetts Amherst.
This file is part of "coref_tools"
http://github.com/nmonath/coref_tools
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.... |
import numpy as np
from numpy.testing import assert_array_almost_equal
import pandas as pd
from pandas.testing import assert_series_equal
import pytest
from rcbm import htuse
def test_calculate_heat_loss_kwh():
"""Output is approx equivalent to DEAP 4.2.0 example A"""
delta_t = pd.Series(
[12.42, 12.... |
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import matplotlib.pyplot as plt
import time
import os
import copy
import sys
import psutil
import shutil
import numpy as np
import GPUtil
import cv2
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell =... |
# Generated by Django 3.2.5 on 2021-07-03 07:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("pages", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Com... |
import astropy.io.fits as fits
FolderNameInputs = '../data/'
blind = 'A'
cat_version = 'V1.0.0A_ugriZYJHKs_photoz_SG_mask_LF_svn_309c_2Dbins_v2_goldclasses_Flag_SOM_Fid'
name_tag = 'with_m_bias' # with_m_bias # no_m_bias # bmodes
filename = FolderNameInputs+'/kids/fits/xipm_sys_corrected_KIDS1000_Blind'+blind+'_... |
from functools import wraps
from flask import session, redirect
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def error(errorCod... |
#! single-point UHF/cc-pVDZ on NH2
import os
import qcdb
from ..utils import *
def check_uhf_hf(return_value):
ref = -55.566057523877
nre = 7.580905897627
assert compare_values(ref, qcdb.variable("HF TOTAL ENERGY"), 5, "scf")
assert compare_values(nre, qcdb.variable("NUCLEAR REPULSION ENERGY"), 5,... |
from domain.MedicineException import MedicineException
class MedicineController:
def __init__(self, repo):
self._repo = repo
def addMedicine(self, medicine):
"""
Add a new medicine
Input: medicine - the medicine that will be added
Raises MedicineException in case of... |
from django.test import SimpleTestCase
from mock import patch
from corehq.apps.app_manager.const import AUTO_SELECT_USERCASE
from corehq.apps.app_manager.models import (
AdvancedModule,
AdvancedOpenCaseAction,
Application,
AutoSelectCase,
CaseIndex,
LoadUpdateAction,
Module,
ReportAppC... |
from flask import Blueprint, current_app, jsonify, request
from euroscipy_dataviz.prediction_plot import generate_plot
api = Blueprint("api", __name__, url_prefix="/api")
@api.after_request
def add_cors_header(response):
response.headers["Access-Control-Allow-Origin"] = "*"
return response
@api.route("/s... |
import os
import shutil
import keras
import numpy as np
# we are not augmenting the biggest class of 'nv'
class_list = ['mel','bkl','bcc','akiec','vasc','df']
for item in class_list:
aug_dir = 'aug_dir'
os.mkdir(aug_dir)
img_dir = os.path.join(aug_dir, 'img_dir')
os.mkdir(img_dir)
img_class ... |
# [Silent Crusade] Unpleasant Meeting
CROW = 9073002
sm.setSpeakerID(CROW)
sm.sendNext("You're the new guy?")
sm.completeQuest(parentID) |
from core.processor import Processor
from utils.OSUtils import OSUtils
class FILE_DELETEProcessor(Processor):
TPL: str = '{"file_path":"path/to/folder/file"}'
DESC: str = f'''
To delete the file associated with given absolute file_path
{TPL}
'''
def process(self):
... |
from api_commons.common import BaseController
class ExampleController(BaseController):
pass |
from functools import partial
from typing import List, Optional
from wai.annotations.core.component import ProcessorComponent
from wai.annotations.core.stream import ThenFunction, DoneFunction
from wai.annotations.core.stream.util import ProcessState, RequiresNoFinalisation
from wai.annotations.domain.image.object_det... |
import os
import pytest
from HUGS.LocalClient import RankSources
from HUGS.Modules import ObsSurface
from HUGS.ObjectStore import get_local_bucket
# Ensure we have something to rank
@pytest.fixture(scope="session", autouse=True)
def crds():
get_local_bucket(empty=True)
dir_path = os.path.dirname(__file__)
... |
newyear = df.loc["2013-12-31 12:00:00": "2014-01-01 12:00:00", ["north", "south"]] |
from config_local import ES_PRIVATE_HOST, ES_HTTP_AUTH
from web.handlers import EXTRA_HANDLERS
from biothings.web.settings.default import QUERY_KWARGS
# *****************************************************************************
# Elasticsearch Settings
# *************************************************************... |
import numpy as np
import os
from azureml.core.run import Run
from scipy.stats import entropy
from ..utils.tfrecords import resize, parse_tfrecord
from .kmeans import *
from ..models import *
run = Run.get_context()
class ClusterFeatureMap(tf.keras.Model):
""""
This is a clustering class with methods to all... |
from django.db import models
class Stat (models.Model):
name = models.CharField(max_length=15, primary_key=True)
def __str__(self):
return self.name
class Pokemon (models.Model):
name = models.CharField(max_length=30, primary_key=True)
id = models.PositiveIntegerField(unique=True)
heigh... |
"""Handlers for the app's v1 REST API."""
from __future__ import annotations
from typing import List
from fastapi import APIRouter, Depends
from semaphore.broadcast.repository import BroadcastMessageRepository
from semaphore.config import config
from semaphore.dependencies.broadcastrepo import broadcast_repo_depend... |
import os
if os.environ['CONFIGURATION'] == 'dev':
DB_URL = "postgresql://postgres:@postgres/priceticker"
elif os.environ['CONFIGURATION'] == 'prod':
DB_URL = "postgresql://postgres:@postgis/priceticker"
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple':... |
import contextlib
import itertools
import math
import os.path
import pickle
import shutil
import sys
import tempfile
import warnings
from contextlib import ExitStack
from io import BytesIO
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
import pytest
from pandas.errors impor... |
from datetime import datetime, timedelta
from flask import Flask, render_template, redirect, url_for, request, make_response
import os
import ConfigParser
import logging
from logging.handlers import RotatingFileHandler
import re
import werkzeug
import operator
import time
#import ledz
#http://stackoverf... |
import uuid
import datetime
from django.db import models
from users.models import User
from typing import List, Dict
from django.db.models.functions import Lower
"""
Models for the meetups
"""
class Tag(models.Model):
"""
Database Model for meetup tags
"""
id = models.UUIDField(primary_key=True, defau... |
# Copyright 2012 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 l... |
from cppstats.main import run_cppstats
from cppstats.main import get_results
from cppstats.main import write_report
from cppstats.main import create_report |
import glob
import os
import subprocess
from multiprocessing import cpu_count
from typing import List
import h5py
import numpy as np
import open3d as o3d
import tabulate
import tqdm
import trimesh
from joblib import Parallel, delayed
from scipy.interpolate import RegularGridInterpolator
def load_sdf(sdf_file, sdf_re... |
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import logging
import tensorflow as tf
log = logging.getLogger(__name__)
def main():
fashion_mnist = k... |
from hendrix.experience import crosstown_traffic
from hendrix.mechanics.concurrency.decorators import _ThroughToYou
def crosstownTaskListDecoratorFactory(list_to_populate):
class TaskListThroughToYou(_ThroughToYou):
def __init__(self, *args, **kwargs):
self.crosstown_task_list = list_to_popul... |
""" Generate model spectra, add model attribute """
def draw_spectra(md, ds):
""" Generate best-fit spectra for all the test objects
Parameters
----------
md: model
The Cannon spectral model
ds: Dataset
Dataset object
Returns
-------
best_fluxes: ndarray
T... |
__author__ = 'Rolf Jagerman'
import roslib; roslib.load_manifest('aidu_gui')
from PySide import QtGui, QtCore
from PySide.QtGui import QApplication
from time import sleep
from window import Window
from ros_thread import ROSThread
class Manager:
"""
The manager for the application GUI. This internally handles... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
import unittest
#from test import test_diff
if __name__ == '__main__':
SeTestSuite = unittest.defaultTestLoader.discover(start_dir='./')
unittest.TextTestRunner(verbosity=2).r... |
from django.contrib import admin
from megasena.models import Draw
admin.site.register(Draw)
|
# -*- coding: utf-8 -*-
import os
import sys
import json
import argparse
from types import SimpleNamespace
from urllib.parse import urlparse
from gitlab import Gitlab, GitlabAuthenticationError, GitlabGetError
def last_good_pipeline(client, project_name, branch):
pipelines = client.projects.get(project_name).pi... |
# Generated by Django 3.1.4 on 2020-12-07 21:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CustomerApps', '0003_auto_20201207_1922'),
]
operations = [
migrations.RemoveField(
model_name='customerapp',
name='... |
import pandas as pd
import numpy as np
import os
import json
from datetime import datetime
# Load config.json and get input and output paths
with open('config.json', 'r') as f:
config = json.load(f)
input_folder_path = os.path.join(os.getcwd(), config['input_folder_path'])
output_folder_path = os.path.join(os.get... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division, print_function
import unittest
from adsmutils import ADSFlask
class TestUpdateRecords(unittest.TestCase):
def test_config(self):
app = ADSFlask(u'test', local_config={
u'FOO': [u'bar', {}],
... |
# coding=utf8
# Copyright 2018 JDCLOUD.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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
from collections import OrderedDict, namedtuple
from itertools import count
from typing import Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
import numpy.random as nr
from numba import njit
import pandas as pd
from pandas import DataFrame
Prob = float
def as_array(s: Union[np.array, pd.Series]):
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='home'),
path('post/<int:pk>/', views.post_detail, name='post-detail'),
path('post/create/', views.post_create, name='post-create'),
path('post/<int:pk>/update/', views.post_update, name='post-update'),
... |
#!/usr/bin/env python3
from setuptools import setup, Command as _Command
from pathlib import Path
from shutil import rmtree
import os
import sys
HERE = Path(__file__).absolute().parent
sys.path.insert(0, str(HERE / 'src'))
import httpx_html # noqa: E402
# Note: To use the 'upload' functionality of this file, you m... |
from __future__ import division
from __future__ import print_function
import os
import socket
import sys
import time
from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
flags.DEFINE_string('name', os.getenv('MINECRAFT_SERVER_NAME'), 'Server name.')
flags.DEFINE_integer('port', o... |
import argparse
from testing.TestGenerator import TestGenerator
from testing.agents.AgentTestGenerator import AgentTestGenerator
from constants import NUM_CHUNKS
from featnames import VALIDATION
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--byr', action='store_true')
parser.add_arg... |
from datetime import datetime
from elasticsearch_dsl import DocType, String, Date, Integer, Float
from elasticsearch_dsl.connections import connections
# Define a default Elasticsearch client
connections.create_connection(hosts=['192.168.1.122:9876'])
WEEKDAYS = ('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.INFO)
from notepad import main
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import scrapy
from scrapy_demo.items import POIItem
from scrapy.selector import Selector
class PoiSpider(scrapy.Spider):
name = "poi"
allowed_domains = ["poi86.com"]
start_urls = ['http://www.poi86.com/poi/district/1289/1.html']
def parse(self, response):
i = 0
... |
import numpy as np
from utils.environ import env
from utils.helpers import *
from utils.db import SqclDB
from utils.mlogging import mlogging
from utils.exception import ExceptiontContainer
from utils.batch import iter_block_batches, iter_merged_block_batches
from models.dssm import DSSM, DSSMConfig
import os
from m... |
import numpy as np
import random
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
from plotdot.plotLog.figures import square, line_trace, add_points, line_trace_from_p
from plotdot.svgDraw.main import group_elements, polylines
from plotdot.svgDraw.transform import translate, transform_allmeths... |
"""
当前包封装的异步任务函数
"""
from celery_tasks.main import celery_app
from celery_tasks.yuntongxun.ccp_sms import CCP
@celery_app.task(name='send_sms')
def send_sms(mobile, sms_code):
result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
return result |
"""
amicus main: a friend to your python projects
Corey Rayburn Yung <[email protected]>
Copyright 2020-2021, Corey Rayburn Yung
License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0)
"""
from __future__ import annotations
import sys
from typing import (Any, Callable, ClassVar, Dict, Hashable, Iter... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from django.apps import apps
from django.urls import reverse
from django.views.decorators.csrf import csrf_protect
from order.models import Dish, Order
from menu.models import SubMenu
from order.... |
from __future__ import print_function, division
import numpy as np
import pandas as pd
from os.path import *
from os import getcwd
from os import listdir
from nilmtk.datastore import Key
from nilmtk.measurement import LEVEL_NAMES
from nilmtk.utils import check_directory_exists, get_datastore
from nilm_metadata import c... |
bl_info = {
'name': 'BlendNet - distributed cloud render',
'author': 'www.state-of-the-art.io',
'version': (0, 4, 0),
'warning': 'development version',
'blender': (2, 80, 0),
'location': 'Properties --> Render --> BlendNet Render',
'description': 'Allows to easy allocate resources in cloud a... |
"""Configuration for engines and models"""
import os
POOL_RECYCLE = int(os.environ.get("POOL_RECYCLE", 300))
DB_POOL_MIN_SIZE = int(os.environ.get("DB_POOL_MIN_SIZE", 2))
DB_POOL_MAX_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", 10))
|
from pandas import DataFrame as Pandas_DataFrame
class Pandas_MicrostatesDataFrame(Pandas_DataFrame):
def __init__(self):
from openktn.native.microstate import attributes as microstate_attributes
super().__init__(columns=microstate_attributes.keys())
|
"""
Most of the logic/ heavy-lifting is based off of:
github.com/facebookresearch/detectron2/blob/master/detectron2/evaluation/coco_evaluation.py#L225
"""
################################################################################
## Import packages. ... |
'''
Provides basic and utility classes and functions.
'''
import os
os.environ["QT_MAC_WANTS_LAYER"] = "1"
import sys, threading
from PySide2 import QtGui, QtCore, QtWidgets
__author__ = "Yuehao Wang"
__pdoc__ = {}
class Object(object):
'''
Base class of other classes in `pylash`, providing fundamental interfa... |
n = int(input("Digite um número inteiro: "))
ant = n-1
suc = n+1
print("O número antecessor é: {}" .format(ant))
print("O numero sucessor é: {}" .format(suc))
|
"""
Preprocess the XSUM dataset
There are several noisy training instances which do not contain any words in pre-defined vocabulary of NTM.
We remove these instances.
Here are the details about these removed instance:
- instance #37993:
input: Here are our favourites:
target: On Monday, we ask... |
#
# Copyright (c) Ionplus AG and contributors. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for details.
#
setCycleEnableNT = '''
create procedure _legacy_.setCycleEnableNT($state int, $run varchar(10), $cycle int)
main:
begin
declare $machine_run_number int;... |
import unittest
import os
from sklearn import datasets
from sklearn.utils.validation import check_random_state
from stacked_generalization.lib.stacking import StackedClassifier, FWLSClassifier
from stacked_generalization.lib.stacking import StackedRegressor, FWLSRegressor
from stacked_generalization.lib.joblibed impor... |
# Copyright IBM Corp. 2016 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 ag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""百度个人云存储(PCS)Python SDK"""
__title__ = 'baidupcs'
__version__ = '0.3.2'
__author__ = 'mozillazg'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2014 mozillazg'
from .api import PCS, InvalidToken
|
import json
import sqlite3
import sys
FILE = sys.argv[1]
QUERY = """
SELECT name n, admin1 a, country c, round(latitude, 4) lat, round(longitude, 4) lon
FROM geoname
WHERE fcode like 'PPL%'
AND population > 5000;
"""
db = sqlite3.connect(FILE)
cur = db.cursor()
cur.execute(QUERY)
r = [dict((cur.description[i][0], v... |
from config import CRYPTO_TIMESERIES_INDEX_NAME, DYNAMODB_TABLE_NAME
from infrastructure.dynamodb import CryptoMarketDataGateway
def create_market_data_gateway():
return CryptoMarketDataGateway(DYNAMODB_TABLE_NAME, CRYPTO_TIMESERIES_INDEX_NAME) |
from controllers.login_controller import LoginController
class AppController():
def __init__(self,app,user) -> None:
self.app=app
self.user=user
self.login_controller=LoginController(app)
self.app.login_view.login_btn.fbind("on_press",self.on_login)
def on_login(self, *args):... |
# Link --> https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem
# Code:
def insert(self, val):
if self.root is None:
self.root = Node(val)
else:
current = self.root
while True:
if current.info > val:
if cu... |
import os
from typing import Type
from gps import *
from time import *
import time
import threading
from collections import namedtuple
#from flask import Flask
#from flask_restplus import Api, Resource
#
#flask_app = Flask(__name__)
#app = Api(app=flask_app)
gpsd = None # setting the global variable
gd = None
# os... |
"""Holds the genetic approach for the solution of the problem.
Classes:
GeneticAlgorithm
"""
import copy
import random
import statistics
from timeit import default_timer as timer
import delivery.algorithm.operation.mutation as mutations
from delivery.algorithm.algorithm import Algorithm
from delivery.algorithm.... |
from gevent import monkey; monkey.patch_all()
import bottle
from bottle import request, response
from datetime import datetime
from multiprocessing import Queue
from queue import Empty
import os
import gevent
import json
TEMPLATE_ROOT = os.path.join(os.path.dirname(__file__), 'client')
class WebServer(object):
... |
# Copyright (c) 2013 - 2019 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
from unittest import TestCase
import requests
import requests_mock
from yawast.scanner.plugins.htt... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name="allreverso",
version="1.2.7",
description="A simple package to handle allreverso.net services (translation, voice, dictionary etc.).",
long_description=long_description,
long_d... |
import train
while True:
t = train.Train(1)
t.main() |
from django.apps import AppConfig
class AsynctasksConfig(AppConfig):
name = 'asyncTasks'
|
# -*- coding: utf-8 -*-
from timeset.timeset import TimeSet, TimeInterval
__all__= [
'TimeInterval',
'TimeSet'
]
|
import logging
# Just sets up logging, nothing to do with the networking aspect of this library
logger = logging.getLogger("Penguin")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%I:%M:%S")
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(... |
# Copyright 2021
#
# 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 in writing, software
# distr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.