content
stringlengths
0
894k
type
stringclasses
2 values
import mysql.connector from mysql.connector import errorcode from flask import flash try: # Establish a connection with the MySQL database # Password here is hardcoded for simplicity. # For all practical purposes, use environment variables or config files. cnx = mysql.connector.connect(user='test_user'...
python
""" Django template tags for configurations. """
python
from services import user_service from viewmodels.shared.viewmodelbase import ViewModelBase class IndexViewModel(ViewModelBase): def __init__(self): super().__init__() self.user = user_service.get_user_by_id(self.user_id) def validate(self): if not self.user_id: self.error...
python
# coding: utf-8 # In[1]: from flask import Flask,render_template,session,url_for,request,redirect from flask_pymongo import PyMongo from flask_bcrypt import Bcrypt from flask import jsonify,json import os import gspread from oauth2client.service_account import ServiceAccountCredentials import pprint import datetime...
python
# Copyright (c) The Diem Core Contributors # SPDX-License-Identifier: Apache-2.0 from typing import List, Callable, Optional import requests from .models import ( User, Address, Transaction, Transactions, RequestForQuote, Quote, CreateTransaction, AccountInfo, OffChainSequenceIn...
python
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 14:05:38 2019 @author: ico """ import numpy as np class MyNeuron: def training(self,X,Y): self.W=np.random.random((X.shape[1]+1,1)) X=np.append(np.ones((X.shape[0],1)),X,axis=1) for j in range(1,21): i=0 ...
python
#!/usr/bin/env python3 import argparse import random import sys from mpmath import mp from common import print_integral_single_input from common.randomgen import generate_basis_function parser = argparse.ArgumentParser() parser.add_argument("--filename", type=str, required=True, help="Output file name") parser.add...
python
# coding: utf-8 r"""Distance conversions""" from corelib.units.base import create_code distances = {"mm": 1e-3, "millimeter": 1e-3, "millimeters": 1e-3, "millimetre": 1e-3, "millimetres": 1e-3, "cm": 1e-2, "centimeter": 1e-2, "centimeters": 1e-2, "centimetre": 1e-2, "centimetres": 1e-2, "m"...
python
kOk = 0 kNoSuchSession = 6 kNoSuchElement = 7 kNoSuchFrame = 8 kUnknownCommand = 9 kStaleElementReference = 10 kElementNotVisible = 11 kInvalidElementState = 12 kUnknownError = 13 kJavaScriptError = 17 kXPathLookupError = 19 kTimeout = 21 kNoSuchWindow = 23 kInvalidCookieDomain = 24 kUnexpectedAlertOpen = 26 kNoAlertOp...
python
# Copyright 2018 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
# terrascript/arukas/d.py
python
# Simple NTP daemon for MicroPython using asyncio. # Copyright (c) 2020 by Thorsten von Eicken # Based on https://github.com/wieck/micropython-ntpclient by Jan Wieck # See LICENSE file try: import uasyncio as asyncio from sys import print_exception except ImportError: import asyncio import sys, socket, str...
python
import re import random TOOBIG = -1 TOOSMALL = -2 NOTNEW = -3 EMPTY = -1 class NameJoiner: def __init__(self, str1, str2): words = [str1, str2] random.shuffle(words) self.fullStartName = words[0] self.fullEndName = words[1] self.initVariables() def in...
python
import sys from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QTextBrowser, QMainWindow, QTextEdit from PySide2.QtCore import QFile, Slot from ui_mainwindow import Ui_MainWindow class MainWindow(QMainWindow): def __init__(self, filename : str): super(MainWindow, self).__init__() ...
python
#! usr/bin/activate """AstroThings library: imagination and Universe.""" def main(): pass if __name__ == '__main__': main() __version__ = '0.1.0.dev1'
python
from unittest import TestCase from tilapia.lib.provider.chains.btc.sdk import transaction class TestTransaction(TestCase): def test_calculate_vsize(self): self.assertEqual(79, transaction.calculate_vsize(["P2WPKH"], [])) self.assertEqual(176, transaction.calculate_vsize(["P2WPKH"], ["P2WPKH", "P2...
python
from applauncher.event import EventManager, KernelReadyEvent, ConfigurationReadyEvent class TestClass: def test_events(self): em = EventManager() class KernelCounter: c = 0 @staticmethod def inc(event): KernelCounter.c += 1 @static...
python
from flask_wtf import FlaskForm from wtforms import BooleanField, SelectField, IntegerField from wtforms.validators import Required, Optional from .vcconnect import get_main_area_dropdown, get_service_dropdown, get_client_group_dropdown class OrgSearchForm(FlaskForm): main_area_id = SelectField('Area', ...
python
from airflow.hooks.base_hook import BaseHook def get_conn(conn_id): # get connection by name from BaseHook conn = BaseHook.get_connection(conn_id) return conn
python
import sys import torch.nn as nn from net6c import ClusterNet6c, ClusterNet6cTrunk from vgg import VGGNet __all__ = ["ClusterNet6cTwoHead"] class ClusterNet6cTwoHeadHead(nn.Module): def __init__(self, config, output_k, semisup=False): super(ClusterNet6cTwoHeadHead, self).__init__() self.batchn...
python
import webbrowser import click from ghutil.types import Repository @click.command() @Repository.argument('repo') def cli(repo): """ Open a repository in a web browser """ webbrowser.open_new(repo.data["html_url"])
python
from __future__ import print_function import os import json from typtop.dbaccess import ( UserTypoDB, get_time, on_wrong_password, on_correct_password, logT, auxT, FREQ_COUNTS, INDEX_J, WAITLIST_SIZE, WAIT_LIST, pkdecrypt, NUMBER_OF_ENTRIES_TO_ALLOW_TYPO_LOGIN, logT, auxT, call_check ) import ty...
python
#!/usr/bin/env python import argparse import os import sys from functools import partial from glob import iglob as glob from itertools import chain from dautil.IO import makedirs from dautil.util import map_parallel PY2 = sys.version_info[0] == 2 if PY2: import cPickle as pickle else: import pickle __versi...
python
# -*- coding: utf-8 -*- from scrapy import signals from scrapy.exporters import CsvItemExporter class CompanyListStorePipeline: exporter = None @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) ...
python
""" :mod:`cookie` ------------- This is a cookie authentication implementation for Pando. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime from .. import auth from ..utils import to_rfc822, utcnow ...
python
from query_generator.query import Query from utils.contracts import Operator, Schema class UnionOperator(Operator): def __init__(self, schema: Schema, leftSubQuery: Query, rightSubQuery: Query): super().__init__(schema) self._leftSubQuery = leftSubQuery self._rightSubQuery = rightSubQuery ...
python
#!/usr/bin/python3 from flask import request from modules import simple_jwt from modules.database import get_db_conn # ---------------------------------------- # Check Auth Token before execute request # ---------------------------------------- from server_error import server_error def logged_before_request(): t...
python
import os import tempfile import re import shutil import requests import io import urllib from mitmproxy.net import tcp from mitmproxy.test import tutils from pathod import language from pathod import pathoc from pathod import pathod from pathod import test from pathod.pathod import CA_CERT_NAME def treader(bytes)...
python
import zipfile import pandas as pd from datanator_query_python.util import mongo_util from datanator_query_python.config import config as q_conf import os class proteinHalfLives(mongo_util.MongoUtil): def __init__(self, MongoDB, db, collection, username, password, path): super().__init__...
python
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) h = int(readline()) cnt = 0 if h == 1: print(1) elif h == 2: print(3) else: for i in range(h): if h < 2 ** i: print(cnt) exit() ...
python
_SCRIPT_VERSION = "Script version: Nuthouse01 - 6/10/2021 - v6.00" # This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause. ##################### try: # these imports work if running from GUI from . import nuthouse01_core as core from . import nuthou...
python
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name="sio2puppetMaster", version="0.3", packages=find_packages(), install_requires=[], scripts=['scripts/sio2pm-spawndocker'], license="MIT", author="Mateusz Żółtak", author_email="zozlak@zozlak.org" )
python
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import re, os if not hasattr(__builtins__, 'cmp'): def cmp(a, b): return (a > b) - (a < b) from collections import OrderedDict, namedtuple as NamedTuple from functools import wraps from pkg_resources import parse_version as p...
python
#!/usr/bin/env python ## # omnibus - deadbits # fullcontact.com ## from http import get from common import get_apikey class Plugin(object): def __init__(self, artifact): self.artifact = artifact self.artifact['data']['fullcontact'] = None self.api_key = get_apikey('fullcontact') s...
python
NAME='console_broadcast' GCC_LIST=['broadcast']
python
from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql import SparkSession from pyspark.sql import Row import numpy as np import seaborn as sns import matplotlib.pyplot as plt from pyspark.ml.fpm import FPGrowth if __name__ == "__main__": sc = SparkContext('local', 'arules') s...
python
#coding:utf-8 #KDD99数据集预处理 #共使用39个特征,去除了原数据集中20、21号特征 import numpy as np import pandas as pd import csv from datetime import datetime from sklearn import preprocessing # 数据标准化处理 #定义KDD99字符型特征转数值型特征函数 def char2num(sourceFile, handledFile): print('START: 字符型特征转数值型特征函数中') data_file=open(handle...
python
import matplotlib.pyplot as plt import os from pathlib import Path from typing import Union import bilby import redback.get_data from redback.likelihoods import GaussianLikelihood, PoissonLikelihood from redback.model_library import all_models_dict from redback.result import RedbackResult from redback.utils import lo...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v4/proto/errors/conversion_action_error.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobu...
python
#!/usr/bin/env python3 import sys import os import time import docker def error(msg): print(msg, file=sys.stderr) exit(1) def main(): if len(sys.argv) != 2: error(f"{sys.argv[0]} <container_name>") container_name = sys.argv[1] client = docker.from_env() try: container = c...
python
# ------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ----------------------------------------------------------------------...
python
import json from carla.driving_benchmark.results_printer import print_summary with open('../_benchmarks_results/outputs-27/metrics.json') as json_file: metrics_summary = json.load(json_file) train_weathers = [1, 3, 6, 8] test_weathers = [4, 14] print("Printing Data\n") print_summary(metrics_summa...
python
import json import os.path as osp from glob import glob import numpy as np from nms_cpu import nms_cpu as nms ''' load annotation from BDD format json files ''' def load_annos_bdd(path, folder=True, json_name='*/*_final.json'): print("Loading GT file {} ...".format(path)) if folder: jsonlist = sorted...
python
import context import sys import pytest from dice import dice from score import scoreCalculate from game.Player import Player from game.score_bracket import score_bracket @pytest.fixture(scope='session') def load_normal_player(): one = score_bracket(250,350,4) two = score_bracket(400,500,3) three = score_b...
python
import os import random import re import sys DAMPING = 0.85 SAMPLES = 10000 def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRank Results from Sampling (n = {SAMPLES})") ...
python
import logging import pandas as pd import numpy as np import glob_utils.file.utils logger = logging.getLogger(__name__) ################################################################################ # Save/Load csv files ################################################################################ def sa...
python
# Generated by Django 3.1.4 on 2021-05-07 01:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TFS', '0002_auto_20210507_0656'), ] operations = [ migrations.AlterField( model_name='customerdetail', name='email',...
python
#-*-coding:utf-8-*- import sys import time from flask import Flask,jsonify app = Flask(__name__) appJSON={ "controller":{ "title":"Speed Dial Squared Up", "rightButton":{ "title":"请求", "click":"${()=>{$dispatch('fetchData')}}" } }, "lifeCircle":{ "vi...
python
import tensorflow as tf import numpy as np interpreter = tf.lite.Interpreter('models/mobilefacenet.tflite') interpreter.allocate_tensors() def set_input_tensor_face(input): input_details = interpreter.get_input_details()[0] tensor_index = input_details['index'] input_tensor = interpreter.tensor(tensor_ind...
python
from typing import Sequence from torch import nn class Model(nn.Module): def __init__( self, n_features: int, n_classes: int, units: Sequence[int] = [512], dropout: float = 0.5, ): super().__init__() sizes = [n_features] + list(units) self.hidd...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2019-02-12 23:07 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): def forwards_func(apps, schema_editor): Menu = apps.get_model("das", "Menu") db_alias = schema_editor.connectio...
python
"""Unit tests for the `cf_predict` package."""
python
import torch import argparse from Transformer import Transformer parser = argparse.ArgumentParser(description='Test transformer') parser.add_argument('--src_len', '-s', type=int, default=5, help='the source sequence length') parser.add_argument('--batch_size', '-bs', type=int, default=2, help='batch size') parser.add...
python
import FWCore.ParameterSet.Config as cms # # #------------------ #Preshower clustering: #------------------ from RecoEcal.EgammaClusterProducers.multi5x5SuperClustersWithPreshower_cfi import * # producer for endcap SuperClusters including preshower energy from RecoEcal.EgammaClusterProducers.correctedMulti5x5SuperClus...
python
# Process PET from worldclim temperature # Peter Uhe # 25/3/2019 # # This script uses python3, set up using conda environment gdal_env2 import os,sys,glob import gdal import numpy as np import datetime,calendar import netCDF4 sys.path.append('/home/pu17449/gitsrc/PyETo') import pyeto inpath = '/home/pu17449/data2/wo...
python
""" Created on Wed Nov 7 13:06:08 2018 @author: david """ import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn.preprocessing import PolynomialFeatures import pandas as pd #from astropy.convolution import Gaussian2DKernel...
python
import autodisc as ad from autodisc.gui.gui import DictTableGUI, BaseFrame import collections try: import tkinter as tk except: import Tkinter as tk import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class StatisticTableGUI(DictTableGUI): @staticmethod def...
python
from gf.models.account import Account from time import time from uuid import uuid4 import multiprocessing as mp import gf.lib.db.db_utils as db #db.get_row_by_id("users", uuid4()) #db.get_row_by_id("shit", uuid4()) Account(id=uuid4(), username= "hello", name="John", email="shit").commit() quit() init_id = uuid4() acc ...
python
from collections import deque import json from kafka import KafkaProducer, KafkaConsumer from anonymizer import Anonymizer consumer = KafkaConsumer(bootstrap_servers="localhost:9092", value_deserializer=json.loads) consumer.subscribe(["unanon"]) producer = KafkaProducer(bootstrap_servers="localhost:9092") def anony...
python
import click import pprint @click.command() @click.argument('type', default='all') @click.option('--check/--no-check', help="Just check (no changes)", default=False) @click.option('--update/--no-update', help="Update if exists", default=False) @click.option('--push/--no-push', help="Push update (when specifed wit...
python
import pytest import yaml from utils import utils class TestConvertReiwaToYear: @pytest.fixture(scope="function") def data_fixture(self): return ((1, 2019), (2, 2020), (3, 2021)) def test_convert(self, data_fixture): for reiwa, actual in data_fixture: assert utils.convert_re...
python
""" FactSet ESG API FactSet ESG (powered by FactSet Truvalue Labs) applies machine learning to uncover risks and opportunities from companies' Environmental, Social and Governance (ESG) behavior, which are aggregated and categorized into continuously updated, material ESG scores. The service focuses on company...
python
#SPDX-License-Identifier: MIT from augur.application import Application from augur.augurplugin import AugurPlugin from augur import logger class FacadePlugin(AugurPlugin): """ This plugin serves as an example as to how to load plugins into Augur """ def __init__(self, augur): self.__f...
python
from .currencies import Currencies from .rates import Rates
python
import pandas as pd import numpy as np import datetime import time import requests from splinter import Browser from bs4 import BeautifulSoup as bs from selenium import webdriver from flask import Flask, render_template import pymongo def Scraper(): executable_path = {'executable_path': 'chromedriver.exe'} ...
python
import os, matplotlib class FileSaver: def save_figure(self, selected_month, plt, charttype): DIR = (selected_month) CHECK_FOLDER = os.path.isdir(f"output/{DIR}") # If folder doesn't exist, then create it. if not CHECK_FOLDER: os.makedirs(f"output/{DIR}") plt.s...
python
from django.apps import AppConfig class books_repoConfig(AppConfig): name = 'books_repo'
python
import discord from discord.ext import commands, tasks import os import pickle import config import asyncio import typing import re import traceback from enum import Enum from collections import OrderedDict import datetime import pytz from apiclient import discovery from google.oauth2 import service_account class G...
python
''' Created on 16 de nov de 2020 @author: klaus ''' import jsonlines from folders import DATA_DIR, SUBMISSIONS_DIR import os from os import path import pandas as pd import numpy as np import igraph as ig from input.read_input import read_item_data, get_mappings, NUM_DOMS from nn import domain_string_identifier from n...
python
import sys import torchvision import torch from torch.utils.data import Dataset from .episodic_dataset import EpisodicDataset, FewShotSampler import json import os import numpy as np import numpy import cv2 import pickle as pkl # Inherit order is important, FewShotDataset constructor is prioritary class EpisodicTiered...
python
# Test the difference in computation time between a set of functions that calculate all prime numbers in a given range import time import math import matplotlib.pyplot as plt # Methods for finding all prime numbers up to max value 'n' # Slow method using a basic check def slow_method(n: int) -> list[int]: results...
python
from typing import List, Optional from fastapi.datastructures import UploadFile from pydantic.main import BaseModel from enum import Enum class TextSpan(BaseModel): text: str start: int end: int class NamedEntity(TextSpan): label: str # The (predicted) label of the text span definition: Optiona...
python
import numpy as np from sklearn.metrics import confusion_matrix def test_data_index(true_label,pred_label,class_num): M = 0 C = np.zeros((class_num+1,class_num+1)) c1 = confusion_matrix(true_label, pred_label) C[0:class_num,0:class_num] = c1 C[0:class_num,class_num] = np.sum(c1,axis=1) C[class_num,0:class_num] ...
python
l=input() n=len(l) f=0 prev=0 found=0 for i in range(n-1): if l[i:i+2]=='AB': if f==0: prev=i+1 f=1 else: continue elif l[i:i+2]=='BA': if f==1: if i!=prev: found=1 else: continue prev=0 f=0 for ...
python
""" A Python library for generating Atom feeds for podcasts. Uses the specification described at http://www.atomenabled.org/developers/syndication/ """ from xml.etree import ElementTree as ET from xml.dom import minidom import copy from datetime import datetime, timedelta from uuid import UUID def parse_datetime(dt)...
python
from datetime import timedelta import json import sys import click from humanize import naturaldelta from . import __version__ from .click_timedelta import TIME_DELTA from .watson_overtime import watson_overtime def _build_work_diff_msg(diff: timedelta) -> str: msg = f"You are {naturaldelta(diff)} " if diff...
python
def dump_locals(lcls): print('|' + ('='*78) + '|') print("|Locals:".ljust(79) + '|') print('|' + ('- -'*(79//3)) + '|') for (k, v) in lcls.items(): print("| {} => {}".format(k, v).ljust(79) + '|') print('|' + ('='*78) + '|') def dump_obj(name, obj): print('|' + ('='*78) + '|') pri...
python
""" Settings file You can set the database settings in here at DATABASES['default'] You can also set the supported languages with SUPPORTED_LANGUAGES Before you launch the site, you should probably set DATABASE password and the SECRET_KEY to something that is not in a public git repository... """ from random i...
python
# From any external file our program counts the number of lines # thanks to Stackoverflow # @program 3 # @author unobatbayar # @date 03-10-2018 num_lines = sum(1 for line in open('out.txt')) print(num_lines)
python
#!/usr/bin/env python import requests import traceback import sys from bs4 import BeautifulSoup import csv ## getHTML def getHTML(): url = "http://mcc-mnc.com/" html = "" try : r = requests.get(url) html = r.text.encode("utf-8") except: traceback.print_exc() return htm...
python
from user import User from db import Base, Session from sqlalchemy import * from sqlalchemy.orm import relation, sessionmaker from datetime import datetime, date from attendee import Attendee from werkzeug.security import generate_password_hash, check_password_hash from flask import json from sqlalchemy import exc from...
python
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. import random import time # Using the Python Device SDK for IoT Hub: # https://github.com/Azure/azure-iot-sdk-python # The sample connects to a device-specific MQTT en...
python
# -*- coding: utf-8 -*- # Copyright: (c) 2018, www.privaz.io Valletech AB # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # OpenNebula common documentation DOCUMENTATION = r''' options: api_url: description: ...
python
#!/usr/bin/env python3 import os from electroncash.util import json_decode from tkinter import filedialog from tkinter import * Tk().withdraw() wallet = filedialog.askopenfilename(initialdir = "~/.electron-cash/wallets",title = "Select wallet") coins = os.popen("electron-cash -w "+wallet+" listunspent").read() coin...
python
from unittest import mock from django.conf import settings from django.contrib.auth.models import User from django.test import Client, TestCase from .models import Lamp from .views import LampControlForm class LoginTests(TestCase): def setUp(self): self.client = Client() def test_login_view(self):...
python
# -*- coding: utf-8 -*- # Copyright © 2018 by IBPort. All rights reserved. # @Author: Neal Wong # @Email: ibprnd@gmail.com from setuptools import setup setup( name='scrapy_autoproxy', version='1.0.0', description='Machine learning proxy picker', long_description=open('README.rst').read(),...
python
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
python
def bin_count(x): return bin(x).count('1') def logic(n, m, y): print(2) print(n, 1) if n == 0: print(1) print(1) for i in range(m): print(-1.0, end=' ') print(-1.0) return for idx in range(n): for binary in range(m): if idx ...
python
import remi.gui as gui import remi.server import collections class DraggableItem(gui.EventSource): def __init__(self, container, **kwargs): gui.EventSource.__init__(self) self.container = container self.refWidget = None self.parent = None self.active = False self.ori...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'EA.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") ...
python
from flask_appbuilder.security.sqla.apis.permission import PermissionApi # noqa: F401 from flask_appbuilder.security.sqla.apis.permission_view_menu import ( # noqa: F401 PermissionViewMenuApi, ) from flask_appbuilder.security.sqla.apis.role import RoleApi # noqa: F401 from flask_appbuilder.security.sqla.apis.use...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013-2016 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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 c...
python
# # The XBUILD builder. # # (c) 2012 The XTK Developers <dev@goXTK.com> # import datetime import os import stat import sys import subprocess import config from _cdash import CDash from _colors import Colors from _jsfilefinder import JSFileFinder from _licenser import Licenser # # # class Builder( object ): ''' '...
python
import logging from src.backup.datastore.backup_finder import BackupFinder from src.restore.list.backup_list_restore_service import \ BackupListRestoreRequest, BackupItem, BackupListRestoreService from src.restore.status.restoration_job_status_service import \ RestorationJobStatusService class TableRestoreSe...
python
class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: # 初始化dp[i][j] 当成二维的01背包问题 dp=[[0]*(n+1) for _ in range(m+1)] for str in strs: zeroNum = 0 oneNum = 0 #获得每个str下有几个0 和几个1 相当于物品价值 for i in str: if i ==...
python
import sys assert sys.version_info >= (3,9), "This script requires at least Python 3.9" world = { "uuid": "1A507EF7-87D8-4EBA-865E-C5D36673C916", "name": "YELLOWSTONE", "creator": "Twine", "creatorVersion": "2.3.14", "schemaName": "Harlowe 3 to JSON", "schemaVersion": "0.0.6", "createdAtMs": 163121052117...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # See: https://docs.python.org/2/library/string.html#format-specification-mini-language import math def main(): # "{field_name:format_spec}".format(...) # # format_spec ::= [[fill]align][sign][#][0...
python
import uuid from yandex_checkout.domain.common.http_verb import HttpVerb from yandex_checkout.client import ApiClient from yandex_checkout.domain.request.webhook_request import WebhookRequest from yandex_checkout.domain.response.webhook_response import WebhookResponse, WebhookList class Webhook: base_path = '/w...
python
from .cache import LRUCache
python
from kasa_device_manager import KasaDeviceManager if __name__ == "__main__": kasa_device_manager = KasaDeviceManager() # Print all the discovered devices out to the console devices = kasa_device_manager.get_all_devices() print(devices) # Toggle a devices power state # kasa_device_manager.tog...
python