content stringlengths 5 1.05M |
|---|
###########################################
# Suppress matplotlib user warnings
# Necessary for newer version of matplotlib
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
from IPython import get_ipython
get_ipython().run_... |
"""
Standard algorithms for graphs with networkx library
"""
from scipy.io import mmread # only for loading mtx files
import networkx as nx
def std_undir_graph_from_mm_file(path):
return nx.from_scipy_sparse_matrix(mmread(path))
def std_dir_graph_from_mm_file(path):
return nx.from_scipy_sparse_matrix(mmre... |
# script was primarily written by Miles McCain, it should be in a notebook but I'm lazy
import numpy as np
import pandas as pd
from datetime import datetime
import os
import csv
import pickle
# Category deduplication
REWRITE_CATEGORIES = {
"Business Day": "Business",
"nan": "Unknown",
"New York and Region... |
"""Strategy objects for creating ABINIT calculations."""
from __future__ import division, print_function
import abc
import collections
import copy
import numpy as np
from pprint import pprint, pformat
from pymatgen.util.string_utils import str_aligned, str_delimited, is_string, list_strings
from pymatgen.io.abinitio.... |
from models.ShoppingCart import *
from models.Store import *
from models.Item import *
from eshopee import *
from main import *
def test_getStoreItems():
store1 = Store()
assert len(store1.getStoreItems()) == len(Store.getStoreItems(Store()))
def test_getTotalPrice():
shop = ShoppingCart()
shop.items... |
"""
Fanciful names for integer indexes into lists - either a day of week,
a month, a planet, or a chemical element.
"""
import calendar
def to_index(name):
if isinstance(name, float):
raise KeyError('Indexes cannot be floating point')
try:
return int(name)
except:
pass
try:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-04-16 18:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import simplesite.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', ... |
from app import app
from neo4j import GraphDatabase, basic_auth
def setup_neo4j_driver(host, port, login, password):
try:
uri = f"bolt://{host}:{port}"
driver = GraphDatabase.driver(uri,
auth=basic_auth(login, password),
en... |
import csv
import copy
def is_valid(sequence, number):
""" Returns True if the number is a sum of two discrete numbers in
the preceding sequence.
"""
success = False
for i,num in enumerate(sequence):
if (number - num) in sequence[i:]:
success = True
break
return... |
#!/usr/bin/env python3
#FUNÇÂO DE CALIBRAÇÂO
#COLOCAR AS CORES DA PISTA
#SE A PISTA NAO TIVER YELLLOW TIRE O Yellow
#SE NECESSARIO CALIBRAR UM COR PARA ROBO NAO CAIR
#CRIE ESSA COR COM QUALQUER NOME E CALIBRE NORMALMENTE
#NO PROGRAMA PRINCIPAL CHAMAR ESSA COR PELO NOME DADO AQUI
import ev3dev2.fonts as fonts
from ev3d... |
"""
Zaimのアクセストークンを取得する
"""
from zaim_client import ZaimClient
if __name__ == '__main__':
client = ZaimClient()
client.print_access_token()
|
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class MutlInfo(nn.Module):
def __init__(self, num_classes=4):
super(MutlInfo, self).__init__()
self.convnet_1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
... |
from keras.models import Sequential, load_model
from keras.layers import LSTM, Dense, Dropout, GRU
from keras.optimizers import Adam, SGD, RMSprop
import numpy as np
import random
import cv2
import display as dp
from datetime import datetime
def arrange_data(x_train, y_train):
y_train = np.nan_to_num(y_train)
print(... |
import time
a = int(input())
b= {}
def m(a):
if a<=4:
return a
if a//2 in b:
return b[a//2]
if a//3 in b:
return b[a//3]
if a//4 in b:
return b[a//4]
c1 = max(a//2, m(a//2))
c3 = max(a//3, m(a//3))
c4 = max(a//4, m(a//4))
b[a]=c1+c3+c4
return ... |
import os
import re
import sys
from irc.client import NickMask
here = lambda x: os.path.join(os.path.dirname(__file__), x)
conf = lambda x: os.path.join(os.path.dirname(__file__), "conf/", x)
BT24_ENABLED = False
try:
from bitcoin24.bitcoin24 import Bitcoin24
BT24_ENABLED = True
except ImportError:
# happens, e.g.,... |
from collections import deque
import time
from threading import RLock
from functools import wraps
from warnings import warn
import logging
import threading
import numpy as np
logger = logging.getLogger(__name__)
class UseNewProperty(RuntimeError):
...
# This is used below by StatusBase.
def _locked(func):
... |
"""
Copyright 2022 Objectiv B.V.
"""
import pytest
from bach.series import SeriesList
from tests.functional.bach.test_data_and_utils import get_df_with_test_data, assert_equals_data
pytestmark = [pytest.mark.skip_postgres] # SeriesList is not (yet) supported on Postgres.
def test_basic_value_to_expression(engine)... |
import os
from nltk.corpus import stopwords
import unidecode
import re
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
#Config
agg_stopword = ['s', '2018','31','diciembre','financieros','000','2019','nota','grupo','valor','2017','resultados','compania','1',
'total... |
"""
Finds the number of triangles containing the origin in its interior
Author: Juan Rios
"""
import math
from itertools import combinations
def read_sets(filename):
"""
Reads sets file
"""
with open(filename) as sets_file:
sets = sets_file.read()
sets = sets.split('\n')
for idx in rang... |
#!/usr/bin/env mayapy
#
# Copyright 2021 Apple 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/LICENSE-2.0
#
# Unless required... |
def func1():
pass
def func2():
pass
d = {
"a": {
"b": func1
}
}
d["a"]["b"] = func2
d["a"]["b"]()
|
# Generated by Django 2.2.5 on 2019-10-18 19:11
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('defaults', '0008_auto_20191012_2339'),
]
operations = [
migrations.AddField(
model_name='blog',
name... |
import argparse
import requests
from bs4 import BeautifulSoup
import pandas as pd
from gamestonk_terminal.helper_funcs import (
check_positive,
get_user_agent,
parse_known_args_and_warn,
)
def earnings_release_dates(l_args):
parser = argparse.ArgumentParser(
prog="up_earnings",
descrip... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
*.py: Description of what * does.
Last Modified:
"""
__author__ = "Sathappan Muthiah"
__email__ = "sathap1@vt.edu"
__version__ = "0.0.1"
import unicodecsv
import os
from lxml import etree
import pdb
from parse import parse as textparse
def safe_gettext(tree_no... |
"""Common Docker components."""
import os
import ssl
import docker
BASE_URL = os.environ.get("DOCKER_HOST")
TLS_CONFIG = None
if len(os.environ.get("DOCKER_TLS_VERIFY", "")):
if BASE_URL is None:
raise RuntimeError("DOCKER_HOST not set.")
BASE_URL = "https://{}".format(BASE_URL.split("://", 1)[-1])
... |
from .file import FileFinder
def make_finder(url):
return FileFinder(url)
|
import pyqtgraph as pg
from PySide2 import QtCore, QtWidgets, QtGui
import pyqtgraph.functions as fn
import pandas as pd
from functools import partial
transparentCol = "#969696"
transparentStyle=f"background: transparent;color:{transparentCol};border-color: {transparentCol};border-width: 1px;border-style: solid;min-wi... |
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View, DetailView
from django.views.generic.edit import DeleteView
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from .models import Player
from .forms ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import argparse
import collections
import inspect
import json
import glob
import os
import sys
import shutil
import tempfile
from pathlib import PurePosixPath
from typing import Union, Optional, Any, List
from cryptog... |
# (c) 2021 Michał Górny
# 2-clause BSD license
"""Tests for database support"""
import io
import unittest.mock
import pytest
from kuroneko.database import Database, Bug, DatabaseError
JSON_DATA = '''
{{"kuroneko-version": {version},
"bugs": [
{{"bug": 123456,
"packages": [["dev-foo/bar"],
... |
#
# Copyright (c) 2016 MasterCard International Incorporated
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list of... |
# Imports
from os.path import join
# Input and output data
input_gz1 = join(config["data_dir"], "ont_DNA", "nanopolish_sample_1.tsv.gz")
input_gz2 = join(config["data_dir"], "ont_DNA", "nanopolish_sample_2.tsv.gz")
input_nc1 = join(config["data_dir"], "ont_DNA", "sniffles_1.vcf")
input_nc2 = join(config["data_dir"], "... |
"""Command-line interface functionality for the Drover interface"""
import argparse
import logging
import sys
from pathlib import Path
import yaml
from pydantic import ValidationError
from drover import Drover, SettingsError, UpdateError
from drover.__metadata__ import VERSION
from drover.models import Settings
_log... |
# This holds a large number of specific functions used in 'convert_script.py'.
import os
import sys
import json
import cv2
import dlib
# import `consts.py` from the parent directory
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(abspath(__file__)), '..')))
import consts
# indexes in... |
from discord.ext import commands
import perms
import discord, json, asyncio
with open("loan.json") as file:
bank = json.load(file)
class Loan(commands.Cog):
'''Loan Commands'''
def __init__(self, bot):
self.bot = bot
@commands.group(invoke_without_command=True)
async def loan(self,ctx):... |
import machine
#Setup 2 digital inputs for buttons
ButtonA = machine.Pin(0, machine.Pin.IN,
machine.Pin.PULL_DOWN)
ButtonB = machine.Pin(1,machine.Pin.IN,
machine.Pin.PULL_DOWN)
#setup a PWM Output
Buzzer = machine.PWM(machine.Pin(15))
Buzzer.duty_u16(32767) #... |
from decimal import Decimal
from django.contrib import messages
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.views.generic import FormView
from wtforms import SelectField, BooleanField, validators, StringField, DecimalField, widgets
from web_payments.forms impo... |
from lib import puzzle
def part1(data: str):
lower = int(data.split('-')[0])
upper = int(data.split('-')[1])
results = []
for i in range(lower, upper + 1):
if i == int(''.join(sorted(str(i)))):
prev = str(i)[0]
valid = False
for j in str(i)[1:]:
... |
import setuptools
from ublock import VERSION_STR
setuptools.setup(
name='ublock',
version=VERSION_STR,
description='a toolkit for the control of trial-based behavioral tasks',
url='https://github.com/gwappa/python-ublock',
author='Keisuke Sehara',
author_email='keisuke.sehara@gmail.com',
l... |
from flask import Flask, jsonify
from gevent.wsgi import WSGIServer
from collections import deque
import logging
import binascii
import decimal
class Logger(object):
""" A dummy file object to allow using a logger to log requests instead
of sending to stderr like the default WSGI logger """
logger = None... |
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
from setuptools import setup
deps = [ 'pyspotify', 'pyalsaaudio' ]
setup(name='Tylyfy',
version='0.0.2',
description='CLI-based Spotify player',
author='Kacper Żuk',
author_email='kacper.b.zuk+tylyfy@gmail.com',
url='https://github.com/kacpe... |
#FLM: RoboFab Intro, Kerning
#
#
# demo of RoboFab kerning.
#
#
# NOTE: this will mess up the kerning in your test font.
from robofab.world import CurrentFont
# (make sure you have a font with some kerning opened in FontLab)
f = CurrentFont()
# If you are familiar with the way RoboFog handled kerning,
# you will ... |
# Copyright (c) 2019, NVIDIA CORPORATION.
from libgdf_cffi import libgdf, ffi
import nvstrings
from cudf.dataframe.column import Column
from cudf.dataframe.dataframe import DataFrame
from cudf.dataframe.datetime import DatetimeColumn
from cudf.dataframe.numerical import NumericalColumn
from cudf.utils import ioutils
... |
import os
def list():
"""list all importable datasets"""
path = os.path.dirname(os.path.abspath(__file__))
for _, _, files in os.walk(path):
for file in files:
if file.endswith('.py') and file != '__init__.py':
print(file[:-3])
|
__author__ = 'jwely'
import os
import tarfile
import gzip
import zipfile
from dnppy import core
__all__ = ["extract_archive"]
def extract_archive(filepaths, delete_originals = False):
"""
Input list of filepaths OR a directory path with compressed
files in it. Attempts to decompress the following formats... |
"""a JupyterLite addon for serving"""
import sys
import doit
from traitlets import Bool, Int, default
from .base import BaseAddon
class ServeAddon(BaseAddon):
__all__ = ["status", "serve"]
has_tornado: bool = Bool()
port: int = Int(8000)
@default("has_tornado")
def _default_has_tornado(self):
... |
import os
import sys
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
file_path = os.path.abspath(__file__)
current_directory = os.path.dirname(file_path)
project_directory = os.path.dirname(current_directory)
sys.path.insert(0, project_directory)
from {{package_name}}.models import {{ pr... |
#!usr/bin/env python3
"""
Configuration file for the Sphinx documentation builder.
This file only contains a selection of the most common options. For a full
list see the documentation:
https://www.sphinx-doc.org/en/master/usage/configuration.html
"""
import binance
# -- Project information --------------------------... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os.path
from collections import OrderedDict, defaultdict
from .metadata import read_model_metadata, find_dimension
from .metadata import LocalizationContext
from .auth import NotAuthorized
from .common import read_json_file
from .config_parser im... |
def minimum():
l= [8, 6, 4, 8, 4, 50, 2, 7]
i=0
min=l[i]
while i<len(l):
if l[i]<min:
min=l[i]
i=i+1
print(min)
minimum() |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 09:21:23 2020
@author: SethHarden
"""
""" VERSION 1 ITERATIVE
# Data structure to store a Binary Tree node
class Node:
def __init__(self, key=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
# Recursive ... |
# -*- coding: utf-8 -*-
class Plateform(object):
""" Class who define a plateform.
yml files are read from heimdall/conf/hosts/plateform.yml and used for Plateform Object instantiation
Keyword Args:
:param: name: plateform's name.
:param: desc: plateform's description.
... |
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import BatchNormalization
from keras.layers import Dense
from keras.layers import Input, Reshape, CuDNNLSTM, Bidirectional
from keras.layers.advanced_activations import LeakyReLU
from keras.models impor... |
'''
Copyright 2020 The Microsoft DeepSpeed Team
'''
import math
import torch
import time
from pathlib import Path
from ..op_builder import CPUAdamBuilder
from deepspeed.utils.logging import should_log_le
class DeepSpeedCPUAdam(torch.optim.Optimizer):
optimizer_id = 0
def __init__(self,
... |
from django.shortcuts import render, redirect
from django.views import generic
from .forms import (
BookFormset,
BookModelFormset,
BookModelForm,
AuthorFormset
)
from .models import Book, Author
def create_book_normal(request):
template_name = 'store/create_normal.html'
heading_message = 'For... |
from trpgcreator.ui.widgets.other_stat_row import Ui_OtherStatRow
from PyQt5.QtWidgets import QWidget
class OtherStatRow(QWidget):
def __init__(self, stat_name, stat_id, current):
super().__init__()
self.wid = Ui_OtherStatRow()
self.wid.setupUi(self)
self.wid.doubleSpinBoxStart.set... |
# Generated by Django 3.0.6 on 2020-05-17 23:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('asana_app', '0002_auto_20200517_2349'),
]
operations = [
migrations.AddField(
model_name='taskmodel',
name='name',
... |
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import pandas as pd
import os
import numpy as np
from sklearn.metrics import precision_recall_curve, auc
from scipy.stats import mannwhitneyu
import math
XRAY_PATH = os.path.join("evaluation", "train_xray")
MI... |
import logging
logger = logging.getLogger(__name__)
TorchTrainer = None
TrainingOperator = None
BaseTorchTrainable = None
CreatorOperator = None
try:
import torch # noqa: F401
from ray.util.sgd.torch.torch_trainer import (TorchTrainer,
BaseTorchTrainable)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 22 10:43:29 2016
@author: rob
"""
import numpy as np
import tensorflow as tf
from numpy import genfromtxt
import matplotlib.pyplot as plt
sess = tf.InteractiveSession()
#Load the data
data_train = genfromtxt('ModelingTrain.csv',delimiter=',',skip_header=1)
data_test = g... |
import SloppyCell.Collections as Collections
expt = Collections.Experiment('ErkMekTraverse2EGF')
expt.longname = 'EGF Stimulation 100 ng/ml - Traverse 1994'
expt.comments = """REF: S. Traverse, et. al., Curr. Biol. (1994) 4, 694
CELLTYPE: PC12
MEAS: Erk1/Mek activation in the presence of EGF at 100 ng/ml
UNITS: units... |
class CustomTypeDescriptor(object, ICustomTypeDescriptor):
""" Provides a simple default implementation of the System.ComponentModel.ICustomTypeDescriptor interface. """
def GetAttributes(self):
"""
GetAttributes(self: CustomTypeDescriptor) -> AttributeCollection
Returns a collection... |
import subprocess
'''
该文件内容为手机截图操作
'''
class Screenshot():#截取手机屏幕并保存到电脑
def screen(self,cmd):#在手机上截图
screenExecute=subprocess.Popen(str(cmd),stderr=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
stdout, stderr = screenExecute.communicate()
# 输出执行命令结果结果
stdout = stdout... |
import time
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def timer(func):
"""
Returns a timer decorator.
See logger for info!
:type func: method
:rtype: method
"""
# Define wrapper
#
def wrapper(*args, **kwargs):
star... |
#
#
#
import unittest, sys
import IfxPy
import config
from testfunctions import IfxPyTestFunctions
class IfxPyTestCase(unittest.TestCase):
def test_020_RollbackDelete(self):
obj = IfxPyTestFunctions()
obj.assert_expect(self.run_test_020)
def run_test_020(self):
conn = IfxPy.connect(config.ConnStr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-03-19 15:18
# @Author : erwin
import pandas as pd
from common.util_function import *
df1 = pd.DataFrame(data={'name': ['a', 'b', 'c', 'd'], 'gender': ['male', 'male', 'female', 'female']})
df2 = pd.DataFrame(data={'name': ['a', 'b', 'c', 'e'], 'age': [21... |
from .context import pset
from nose.tools import raises
import numpy as np
class TestFreeParameter:
@classmethod
def setup_class(cls):
cls.p0 = pset.FreeParameter('var0__FREE', 'normal_var', 0, 1)
cls.p1 = pset.FreeParameter('var1__FREE', 'lognormal_var', 1, 2)
cls.p2 = pset.FreePara... |
import numpy as np
with open('input.txt', 'r') as f:
s = f.read().strip()
#s = '0222112222120000'
nr = 6
nc = 25
x = [int(c) for c in s]
d = np.array(x)
d = np.reshape(d, (-1, nr, nc))
nb = d.shape[0]
tups = []
for b in range(nb):
band = d[b,:,:]
unique, counts = np.unique(band, return_counts=True)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# "Fuzzing in the Large" - a chapter of "The Fuzzing Book"
# Web site: https://www.fuzzingbook.org/html/FuzzingInTheLarge.html
# Last change: 2021-11-03 13:27:49+01:00
#
# Copyright (c) 2021 CISPA Helmholtz Center for Information Security
# Copyright (c) 2018-2020 Saarlan... |
import cv2, numpy
img = cv2.imread('flower.png')
columns = img.shape[1]
rows = img.shape[0]
transformation_matrix = numpy.float32([[1, 0, 200], [0, 1, 100]])
transformed_image = cv2.warpAffine(img, transformation_matrix, (columns, rows))
cv2.imshow('Image', transformed_image)
cv2.waitKey(0)
cv2.destroyAllWindows() |
#! /usr/bin/env python3
import argparse
import subprocess
import sys
import unittest
from test_bech32 import TestSegwitAddress
from test_coldcard import coldcard_test_suite
from test_descriptor import TestDescriptor
from test_device import start_bitcoind
from test_psbt import TestPSBT
from test_trezor import trezor_t... |
from __future__ import unicode_literals
from .nuevo import NuevoBaseIE
class AnitubeIE(NuevoBaseIE):
IE_NAME = 'anitube.se'
_VALID_URL = r'https?://(?:www\.)?anitube\.se/video/(?P<id>\d+)'
_TEST = {
'url': 'http://www.anitube.se/video/36621',
'md5': '59d0eeae28ea0bc8c05e7af429... |
import hashlib
from django.core.cache import cache
from django.utils.translation import ugettext as _
from tools.context_processors import manual_url
class PrestaError(Exception):
KEY = "key"
DOMAIN = "domain"
API_PHP_INSTALL = _('Please install api.php file')
REGEN_HTACCESS = _('Please regenerate .... |
# coding: utf-8
import pprint
import re
import six
class CinderExportToImageOption:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and th... |
"""
Script to roll out a trained agent on the environment for several episodes.
"""
import json
import os
import re
import argparse
import numpy as np
import torch
from utils import helpers as utl
from utils.evaluation import evaluate
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Bu... |
import os
from os.path import join
from pathlib import Path
import json
from unittest.mock import patch
import src.superannotate as sa
from tests.integration.base import BaseTestCase
import tempfile
import pytest
class TestRecursiveFolderPixel(BaseTestCase):
PROJECT_NAME = "test_recursive_pixel"
PROJECT_DES... |
#!python
if __name__ == '__main__':
print("b defined")
print("c")
print("c")
|
# -*- coding: utf-8 -*-
from openprocurement.api.validation import validate_data, validate_json_data
from .utils import update_logging_context, raise_operation_error
from openprocurement.api.validation import ( # noqa: F401
validate_file_upload, # noqa forwarded import
validate_document_data, # noqa forwarded ... |
import unittest
import os
import numpy as np
import sys
# Add .. to the PYTHONPATH
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
from kaldi10feat.read_wave import *
# We'll also test computation of mel features on this .
from kaldi10feat.mel import *
class TestReadWave(unittest.TestCase):
... |
import unittest
from test import test_support
class Empty:
def __repr__(self):
return '<Empty>'
class Coerce:
def __init__(self, arg):
self.arg = arg
def __repr__(self):
return '<Coerce %s>' % self.arg
def __coerce__(self, other):
if isinstance(other, Coerce):
... |
token="2059760690:AAG9FiJ0Vvx59__Pj8w1SA_7s-Fzqz99RvA"
userId="293682875"
|
#!/usr/bin/env python3
'''
MIT No Attribution
Copyright Amazon Web Services
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, co... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from abc import ABCMeta, abstractmethod
from functools import wraps
WithABCMeta = ABCMeta(str('WithABCMeta'), (object,), {})
class Disposable(WithABCMeta):
'''
Exposes method to release resources held by the ... |
#!/usr/bin/python
from app import app
app.run(host="0.0.0.0", port=5000, debug=True)
|
from datetime import datetime
from liebraryrest.database import db, Model
from sqlalchemy import UniqueConstraint
class User(Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(50), nullable=False, index=True)
bookings = db.relationship('Booking', backref='user', lazy="dyna... |
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''
AQ = pd.read_csv('Beijing.csv')#read data
dic = {1: "Winter",
2: "Winter",
3: "Spring",
4: "Spring",
5: "Spring",
6: "Summer",
7: "Summe... |
"""
Command line utility to trigger indexing of bundles from DSS into Azul
"""
import argparse
from collections import (
defaultdict,
)
import fnmatch
import logging
import sys
from typing import (
List,
)
from args import (
AzulArgumentHelpFormatter,
)
from azul import (
config,
require,
)
from a... |
#***************************************************************************
# Copyright Jaime Machuca
#***************************************************************************
# Title : sc_SonyQX1.py
#
# Description : This file contains a class to use the Sony QX range of cams
# ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from djshop.apps.offers.models import BundleOffer
from django import forms
# Bundle offer form
class BundleOfferForm(forms.ModelForm):
class Meta:
model = BundleOffer
fields = ["name", "description", "product", "bundle_product_units... |
import gym
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
from Actor import Actor
from Critic import Critic
from Noise import OUActionNoise, OUNoise
from Buffer import Buffer
problem="MountainCarContinuous-v0"
env = gym.make(problem)
num_states = env.... |
#!/bin/python3
import argparse
import logging
parser = argparse.ArgumentParser(description="Generator plots of optical functions")
parser.add_argument("path to xml", metavar='path', type=str, help="Path to xml file")
parser.add_argument("-v", "--verbose", dest='logging-level', action='store_const', const=logging.DEBUG... |
from .actions import Action
from .status import Status
from .chambers import Chamber
|
import requests # Used to make HTTP requests
import json # Used to parse JSON
import os # Used to infer environment variables
from ..internal import fixFilter
API_TAGO = os.environ.get('TAGOIO_API') or 'https://api.tago.io'
class Network:
def __init__(self, acc_token):
self.token = acc_token
s... |
'''
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000
(“回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串)
'''
class Solution:
def longestPalindrome(self, s):
'''
方法1
DP
'''
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = ''
for l in range(n):
... |
from PySide import QtGui, QtCore
import settings
import utils
class NewDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(NewDialog, self).__init__(parent)
r = QtGui.QDesktopWidget().availableGeometry()
self.setGeometry(r.width()*0.25,
r.height() * 0.25,... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Autogenerated file. ANY CHANGES WILL BE OVERWRITTEN
from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
EventData, \
CompoundEventData
DUMP_PARTIAL = [
CompoundEventData(
serv... |
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views.generic import FormView, ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.auth.... |
"""A tool to scan a directory tree and generate snippets of an app.yaml file.
When configuring static paths in app.yaml file, there are a few things that may
need to be done manually. Specifically, if there's a desire to have an url like
'directory/' to serve the file 'directory/index.html', there has to be a static
m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.