content stringlengths 5 1.05M |
|---|
from django.conf.urls import url
from . import views
urlpatterns = (
url('^$', views.landing,
name='landing'),
url('^about$', views.about,
name='about'),
url('^faq$', views.faq,
name='faq'),
url('^contact$', views.contact,
name='contact'),
url('^terms-and-conditio... |
#!/usr/bin/env python
import sys
import logging
import time
import simpleaudio
import csv
from beepy import beep
from tqdm import tqdm
from colorama import Fore
from typing import List
from time import sleep
from sylo.models import (
Durations,
Database,
Config,
ConfigFile,
)
from sylo.definitions impor... |
#!/usr/bin/env python
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
import pytest
import random
import connections
import environment
from adapters import print_message as log_message
from edgehub_control import (... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-09-09 03:41
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('convention', '0001_initial'),
]
... |
InfuraProjectId = '1761beb5aae7459b83afd64e8f1003fc'
import os
os.environ['WEB3_INFURA_PROJECT_ID'] = InfuraProjectId
from web3.auto.infura import w3
print(w3.isConnected())
address = '0xDE9d2de48969B86826da4336F389c21e2d1c9812'
privateKey = '0x48bd694bbfd4f2816b4355776d3c403449d95298a0cc4835e0372447013e84de'
w3.et... |
# Exercício Python 066: Crie um programa que leia números inteiros pelo teclado. O programa só vai parar
# quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram
# digitados e qual foi a soma entre elas (desconsiderando o flag).
count = sum = number = 0
while True:
... |
#!/usr/bin/env python2
# coding: UTF-8
import rospy, unittest, rostest
import rosnode
import time
class TestRefereeReceiver(unittest.TestCase):
def test_node_exist(self):
nodes = rosnode.get_node_names()
self.assertIn('/referee_receiver', nodes, 'node does not exist')
if __name__ == '__main__':
... |
import logging
import logging.handlers
import time
from PyTango.server import run, device_property
from PyTango.server import Device, DeviceMeta
from PyTango.server import attribute, command
import PyTango
import datetime
logger_dict = {}
class FileLogger(Device):
__metaclass__ = DeviceMeta
log_path = dev... |
import re
from typing import List, Optional, Tuple, Union
import attr
import pendulum # type: ignore
from bs4 import BeautifulSoup # type: ignore
from bs4.element import Tag # type: ignore
from furl import furl # type: ignore
from requests import Response
from pyffdl.sites.story import Story
from pyffdl.utilities... |
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
flip = lambda x:'1' if x=='0' else '0'
data = ''.join([flip(x) for x in bin(num)[2:]])
return int(data, 2) |
#! /usr/bin/env python3
#
# Florian Streibelt <florian.streibelt@streibelt.net>
import sys
import argparse
import time
import irc.client
import jaraco.logging
import logging
from ircbgp import __version__ as libversion
__version__ = libversion
class BGP:
def __init__(self, channels, asn, prefixname):
... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: proto
class AuthMode(object):
FIRST = 0
MULTIFACTOR = 1
|
import BLE_CF
import time
from PyObjCTools import AppHelper # BLE
import objc # BLE
import struct #send
from multiprocessing import Pool
objc.loadBundle("CoreBluetooth", globals(),
bundle_path=objc.pathForFramework(
u'/System/Library/Frameworks/CoreBluetooth.framework/Versions/A/Co... |
#!/usr/bin/env python
__author__ = "XXX"
__email__ = "XXX"
import os
from pathlib import Path
import numpy as np
import shutil
from tensorflow import keras
class EarlyStoppingHandlerTensorFlow:
"""
TensorFlow Early Stopping Handler
Early stopping handler stop training when the watched metric is not imp... |
import pyttsx3
#init the TTS
TTS = pyttsx3.init()
TTS.setProperty('rate', 150)
#string to speak
text = "pythonexplainedto.me"
TTS.save_to_file(text,text+".mp3")
#run the TTS
TTS.runAndWait()
|
import matplotlib
import pandas as pd
import numpy as np
import pickle
import urllib.request
import dateutil.parser
import dateutil.rrule
import dateutil.tz
import datetime
import warnings
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.patheffects as pe
import matplotli... |
# Copyright 2018 The TensorFlow Authors. 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 applica... |
装饰器
import functools
外层方法():
before 方法
方法()
after 方法
1. 函数装饰器无参数
def login_required(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
# 执行函数前
if not kwargs.get('current_user_id'):
return "无权限"
print("before:current_user:%s" % kwargs.get('... |
r"""Example of using the replace_placeholder method of the SQLContainer class.
It demonstrates how to replace multiple placeholders.
This example is present in the section "Replace placeholders" in the
SQLite part of the documentation.
"""
# ===============================================================
# Imports
#... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------... |
import os
import subprocess
fileexisted = os.path.isfile(f"../../results/cache/cache.csv")
f = open(f"../../results/cache/cache.csv", "a")
def write_csv_results(ds, n, op, num_ops, cache, misses):
f.write(f"{ds},{n},{op},{num_ops},{cache},{misses}\n")
f.flush()
if not fileexisted:
write_csv_results(... |
"""
repl.py - top level read/eval/print loop.
INTRO 1 : This is where ActorForth all begins for execution purposes.
"""
import sys
from continuation import Continuation, Stack
from interpret import interpret
from af_types.af_any import print_words
def print_stack_stats(stack):
print("")
print(stack.contents... |
from . import goodsAdminBP
from flask import render_template
@goodsAdminBP.route('/')
def index():
from .main import getAllGoods
return render_template("admin/goods.html", goods=getAllGoods())
|
import adv.adv_test
from core.advbase import *
from slot.d import *
from slot.a import *
def module():
return Xainfried
class Xainfried(Adv):
a1 = ('dc', 4)
a3 = ('dt', 0.25)
conf = {}
conf['slot.a'] = RR()+JotS()
conf['slot.d'] = Siren()
conf['acl'] = """
`s1
`s2
`... |
""" Implement shared pieces of Erlang node negotiation and distribution
protocol
"""
DIST_VSN = 5
DIST_VSN_PAIR = (DIST_VSN, DIST_VSN)
" Supported distribution protocol version (MAX,MIN). "
def dist_version_check(max_min: tuple) -> bool:
""" Check pair of versions against version which is supported by us
... |
import os
from pyrogram import Client
TRIGGERS = os.environ.get("TRIGGERS", "/ !").split(" ")
API_HASH = os.environ.get("API_HASH")
BOT_TOKEN = os.environ.get("BOT_TOKEN")
BOT_NAME = os.environ.get("BOT_NAME")
SAUCE_API = os.environ.get("SAUCENAO_API")
DB_URL = os.environ.get("DATABASE_URL")
ANILIST_CLIENT = ... |
from functools import partial
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.test import TestCase
from opendebates.tests.factories import SiteFactory, DebateFactory
# Force the reverse() used here in the tests to always use the full
# urlconf, despite whatever ... |
"""
File: draw_line.py
Name: Zach Hsu
-------------------------
TODO: This program allows users to create straight lines by clicking the mouse.
The first click creates a circle to indicate the origin of the line, whereas the second click indicates the end.
As soon as a line is formed, the circle will ... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_task_utils"""
import base64
import os
import io
try:
from resilient import ImportDefinition
except ImportError:
# Support Apps running on resilient-circuits < v35.0.195
from resilient_circuits.util import ImportDefinition
RE... |
import pytest
from app.api.analytics.service import get_prediction_for_pipeline
from ..dataclasses.analytics_service_dataclasses import \
PipelinePredictionTestCase
from ..fixtures.analytics_service_fixtures import (input_output_data_fixture,
make_chart_dicts_fixt... |
import warnings
from datetime import datetime
from typing import Callable, Dict, NamedTuple, Optional, Tuple
import jax
from jax import numpy as jnp
from tqdm import tqdm
from mcx.inference.adaptation import (
StanWarmupState,
stan_hmc_warmup,
stan_warmup_schedule,
)
from mcx.inference.integrators import ... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from djangocms_baseplugins.baseplugin.models import AbstractBasePlugin
from djangocms_baseplugins.baseplugin.utils import truncate_richtext_content
from djangocms_baseplugins.baseplugin.utils import check_migration_modules_needed
ch... |
import functions
from imports import *
#------------------------------------------------------------------#
# Classe de rede neural para predição de dados espectrais de imagens. Utiliza
# bibliotecas Keras, Numpy e Pillow
class Model():
#
# Initialize the model and set the dataset for trainning and valid... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2018 Bruno Tibério
#
# 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 l... |
#!/usr/bin/python3
import sys,os
logs = open(sys.argv[1], "rt").readlines()
logs = [l for l in logs if l.startswith('EVENT_HOST_')]
record_num = len(logs)
first = logs[0]
last = logs[-1]
#EVENT_HOST_START 1330 4 HELLO_sta -1 4411277.674832291
first_t = float(first.split()[-1])
last_t = float(last.split()[-1])
dur_t... |
import os
import sys
import uuid
import tempfile
from .face import Face
from .solid import Solid
from .assembly import Assembly
from .tools import generate_solid_from_faces
import FreeCAD
import Part as FCPart
from FreeCAD import Base
App = FreeCAD
class ReferenceFace(object):
def __init__(se... |
# Generated by Django 3.1.1 on 2020-09-30 02:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('comments', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='profile',
),
]
|
import sys
import os
src_path = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
if src_path not in sys.path:
sys.path.insert(0, src_path)
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application
from tests.tests_new import MyVariantTest
from biothings.tests.test_helper impor... |
# Copyright 2018 eBay Inc.
# Copyright 2012 OpenStack LLC.
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0... |
# -*- coding: utf-8 -*-
import datetime
try:
# python 3.x
from urllib.parse import urlparse, parse_qs
except Exception:
# python 2.x
from urlparse import urlparse, parse_qs
import logging
from scrapy.spiders import CrawlSpider
from scrapy.http import Request
from reserve_america.items import Reservat... |
# -*- coding: utf-8 -*-
"""
Tests for tipfyext.appenginetaskqueue
"""
import time
import unittest
from google.appengine.ext import deferred
from google.appengine.api import taskqueue
from google.appengine.ext import db
from tipfy import Rule, Tipfy
from tipfy.app import local
import test_utils
def get_rules()... |
# Copyright (C) 2013 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import re
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.types import UserDefinedType
from sqlalchemy.sql.expression import ClauseElement, TextClause
try:
from sqlalchemy.dialects.postgresql imp... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import LambdaLR, MultiStepLR
from torch.utils.data import DataLoader
from torchvision.datasets.cifar import CIFAR10
import torchvision.transforms as transforms
from torchvision.models.resnet import resnet18
from t... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import subprocess
import tempfile
import unittest
from contextlib import contextmanager
from fs_image.btrfs... |
import pickle
import time
from string import punctuation
import nltk
import numpy as np
import sent2vec
from absl import app
from absl import flags
from absl import logging
from nltk import sent_tokenize
from nltk import word_tokenize
from nltk.corpus import stopwords
FLAGS = flags.FLAGS
flags.DEFINE_string('model_fi... |
"""
Copyright (C) 2012 STFC.
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 writ... |
def get_bins(n, bs = ''):
result = []
def genbin(n, bs = ''):
if n-1:
genbin(n-1, bs + '0')
genbin(n-1, bs + '1')
else:
result.append('1' + bs)
genbin(n)
return result
def compute(input_list):
result = 0
all_bin = get_bins(len(input_list))
... |
from __future__ import absolute_import
from bluepandas.bluepandas import * |
import djclick as click
from isic.ingest.models import Accession
from isic.ingest.validators import MetadataRow
@click.command(help='Revalidate all accession metadata')
def revalidate_metadata():
accessions = Accession.objects.values_list('pk', 'metadata')
num_accessions = accessions.count()
num_errors =... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_norm_layer
from mmcv.cnn.utils.weight_init import (constant_init, trunc_normal_,
trunc_normal_init)
from mmcv.runner import ModuleList
fr... |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... |
#!/usr/bin/env python
from setuptools import setup, find_packages
PROJECT = "origamid"
with open('README.md') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.7',
'flask==1.0.2 ',
'requests==2.18.4',
'tornado==5.0.2',
'six==1.11.0',
'peewee==3.5.0',
'celery==4.2.0',
'do... |
#!/usr/bin/env python
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
#
# filename: inject_into_junit.py
# author: v-greach@microsoft.com
# created: 03/11/2019
# Rev: 03/11/2019 D
import sys
import os
import argpa... |
import tkinter as tk
from tkinter.ttk import Combobox
from PIL import Image, ImageTk
import numpy as np
from tkinter.font import Font
from time import sleep
import RPi.GPIO as GPIO
import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
from fpdf import FPDF
im... |
import sounddevice as sd
duration = 5.5 # seconds
from queue import Queue
from threading import Thread
import numpy as np
from numpy import sin, pi
import sounddevice as sd
import time
import matplotlib.pyplot as plt
# Parameters for sine wave
fs = 44100 # sampling rate, Hz
duration = .5 # in seconds
f = 1... |
import requests as r
from urllib import parse
from pprint import pprint
from requests.cookies import create_cookie
import traceback
import os
import base64
from typing import Optional, Dict, Tuple, Union, List
import urllib3
import json
import yaml
import re
from enum import Enum
from src.utils import logger
urllib3.d... |
# coding: utf-8
import pprint
import re
import six
class BlackEnhance:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is js... |
"""
Python compatibility functions.
"""
import sys
import os
import warnings
from typing import Any, Callable
# ------------------------------------------------------------------------------
# Python 2/3 compatibility
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
def relpath(path: str, start:... |
"""Define battery utilities."""
from typing import Union
BATTERY_STATE_OFF = "off"
BATTERY_STATE_ON = "on"
def calculate_battery(value: Union[float, int]) -> Union[float, str]:
"""Calculate a battery value.
1. If the value is a float, we assume it represents voltage and return it as-is.
2. If the value ... |
from scipy.linalg import solve
import numpy as np
import pickle
import math
import eos
import glob
import os
import json
from lsfm.eos_utils import Blendshape, MorphableModel, PcaModel
def recoverModelFromPca(id, path, pca_model, alpha):
alpha_np = np.array(list(map(float,alpha)))
eigenvector_linear_sum = np.d... |
from os.path import join, dirname
DATA_DIR = dirname(__file__)
def path_to_file(name):
return join(DATA_DIR, name)
|
import abc
import typing
import time
import asyncio
import multiprocessing
class OnePlusOneBase(abc.ABC):
"""
OnePlusOne Abstract Class
'This Class Have Super Cat Power'
"""
__repl__ = """OnePlusOne Abstract Class"""
__str__ = __repl__
@abc.abstractmethod
def onePlusOne(self, one: Non... |
from typing import List, Dict, Any
import albumentations as A
import cv2
import numpy as np
import streamlit as st
import torch
from PIL import Image
from retinaface.pre_trained_models import get_model as get_detector
from facemask_detection.pre_trained_models import get_model as get_classifier
st.set_option("deprec... |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
import sys
sell1 = sell2 = 0
buy1 = buy2 = -sys.maxint
for p in prices:
sell2 = max(sell2, p+buy2... |
import itertools
from numpy import linspace
from pylinal import VectorFunc
from math import cos, sin, pi
# u in [0, 2pi); v in [-1, 1]
x = lambda u, v: (1 + v/2 * cos(u/2)) * cos(u)
y = lambda u, v: (1 + v/2 * cos(u/2)) * sin(u)
z = lambda u, v: v/2 * sin(u/2)
mobius_strip = VectorFunc([x, y, z])
us = linspace(0, 2*... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
spec = load_test_spec("vpp", "hue")
NOOP = 50 # i.e. 0.0 in msdkvpp range should result in no-op result
@slash.requires(have_gst)
@slash.requires(*have_gst_element("msdk"))
... |
"""Loaders."""
import datetime
from pathlib import Path
import re
from typing import Dict, List, Optional
import fsspec
import pandas as pd
from prefect import Task
from ...data.endpoints import BoxScoreTraditional
from ...data.endpoints.parameters import SEASONS
from ...data.factory import NBADataFactory
class Ge... |
#this imports numpy
import numpy as np
#this step creates a function called main
def main():
i = 0 #sets a variable i equal to 0
x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?)
for i in range(120): #starting at i, add one everytime the program gets to t... |
from django.db import models
from django.contrib.auth.hashers import (
check_password,
make_password,
)
from .managers import UserManager
class User(models.Model):
username = models.CharField(verbose_name='username', db_column='username', max_length=40, unique=True)
email = models.EmailField(verbose_... |
"""Solution.
HackerRank > Algorithms > Implementation > Beautiful Days at the Movies.
"""
def beautifulDays(i, j, k):
"""Problem solution."""
def reverse(n):
return int(str(n)[::-1])
c = 0
for day in range(i, j + 1):
if (day - reverse(day)) % k == 0:
c += 1
return c
|
import os
import socket
import json
import requests
import pygeohash as pgh
from influxdb import InfluxDBClient
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 7007 # Port to listen on (non-privileged ports are > 1023)
apikey = os.getenv("API_KEY")
influxHost = os.getenv("INFLUX... |
#!/usr/bin/python3
#
# MIT License
#
# Copyright (c) 2017 Arkadiusz Netczuk <dev.arnet@gmail.com>
#
# 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 limi... |
from pyomo.environ import *
infinity = float('inf')
model = AbstractModel()
# Foods
model.F = Set()
# Nutrients
model.N = Set()
# Cost of each food
model.c = Param(model.F, within=PositiveReals)
# Amount of nutrient in each food
model.a = Param(model.F, model.N, within=NonNegativeReals)
# Lower and upper bound... |
from . import BaseGenerator
from random import choice, randint
class Seed(BaseGenerator):
def __init__(self, company):
self.nouns = self._load_txt('nouns.txt')
self.adjectives = self._load_txt('adjectives.txt')
def generate(self):
return '-'.join([
choice(self.adje... |
import json
import time
from collections import namedtuple
import pytest
from click.testing import CliRunner
from firebolt_cli.main import main
def test_engine_start_running(engine_name: str, cli_runner: CliRunner) -> None:
"""
Test start engine, which is running should fail
"""
result = cli_runner.... |
from ctgan.synthesizers.ctgan import CTGANSynthesizer
from reader import get_datasets, read_csv, write_csv
import time
import warnings
#warnings.filterwarnings('ignore')
datasets = get_datasets()
discriminator_steps = 5
verbose = True
for dataset in datasets:
data = read_csv(dataset)
print('Dataset name: ' +... |
import json
import pytest
def test_dotdict():
from flask_dropin.nameddrops import DotDict
d = DotDict({'val': 100}, True)
assert d.val == 100
assert hasattr(d, 'val')
assert 'val' in d
with pytest.raises(ValueError):
d.val = 200
with pytest.raises(AttributeError):
d.bad_ke... |
import torch.nn as nn
import torch.nn.functional as F
class ShapesClassifier(nn.Module):
def __init__(self):
super(ShapesClassifier, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=1,
out_channels=16,
kernel_size=(3, 3),
... |
import gc
import os
import atexit
import signal
import asyncio
import inspect
import logging
import weakref
import contextlib
import collections
if __debug__:
import traceback
import synapse.exc as s_exc
import synapse.glob as s_glob
import synapse.lib.coro as s_coro
logger = logging.getLogger(__name__)
OMIT_F... |
from nltk import word_tokenize
from nltk import Text
tokens = word_tokenize("Here is my first aprroach with nltk")
text = Text(tokens)
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os.path
import subprocess
from textwrap import dedent
from colors import crossed, red
from pex.common import safe_open
from pex.testing import run_pex_command
from pex.typing impo... |
from starlette.requests import Request
from typing import List, Optional
from viewmodels.shared.viewmodel import ViewModelBase
from services import transcripts_service
class TranscriptsViewModel(ViewModelBase):
def __init__(self, episode_number, request: Request):
super().__init__(request)
self.... |
# Copyright (c) Ingmar Nitze and Konrad Heidler
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import glob
import os
import shutil
import numpy as np
import rasterio as rio
from .udm import burn_mask
from ..utils import get_logger, log_run
... |
# -*- coding: utf-8 -*-
"""
@Time : 2018/3/23 21:53
@Author : Elvis
"""
import os
import numpy as np
from utils.data_loader import TestDataset
import torch
from torch.utils.data import DataLoader
from torch.backends import cudnn
from torch.autograd import Variable
from tqdm import tqdm
superclass = "vehicles"
NUM_... |
FORECAST_MAPPING = {
'Krajowe zapotrzebowanie na moc': 'load_forecast',
'Suma zdolności wytwórczych JWCD': 'capacity_jwcd_forecast',
'Suma zdolności wytwórczych nJWCD': 'capacity_njwcd_forecast',
'Generacja JWCD': 'generation_jwcd_forecast',
'Generacja nJWCD': 'generation_njwcd_forecast',
'Gener... |
import os, json, logging, shutil, time, zipfile
from io import BytesIO
from collections import OrderedDict
from .util.descriptor import AddChecksum
from .helpers import alias, load_jsons
from .rpc import get_default_datadir, RpcError
from .specter_error import SpecterError
from .wallet import Wallet
logger = logging.... |
import os
def get_current():
print("Current Working Directory: ",os.getcwd())
get_current()
os.chdir('/home/pablo/Courses')
get_current()
|
"""
Wrap 2
A library for wrapping social network wrappers.
"""
from wrap2.facebook import Facebook
from wrap2.twitter import Twitter
__all__ = [Facebook.__name__, Twitter.__name__]
|
import requests
import logging
class BranchClient(object):
base_url = "https://api.branch.io/v1"
def __init__(self,
branch_key,
branch_secret,
upside_url='https://upsideappbeta.app.link', # default to alpha
session_factory=requests.session... |
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
# __str__ => showing info about object (user friendly)
def __str__(self):
return f'{self.title} by {self.author} costs {self.price}'
# __repr__ => deb... |
# ============================== WEBHOOKS TABLE ==============================
CREATE_WEBHOOK_TABLE = """
CREATE TABLE IF NOT EXISTS webhooks (
id BIGINT PRIMARY KEY,
token VARCHAR(100),
guild_id BIGINT,
ch_id BIGINT UNIQUE,
timesta... |
from setuptools import setup, find_packages
REQUIRED_PACKAGES = ['keras==2.1.2', 'h5py==2.7.1', 'tqdm==4.19.5']
# Setup parameters for GC ML Engine.
setup(name='trainer',
version='0.1',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='... |
from django.contrib import admin
from django.db import models
from .models.class_ import Class
from .models.clase import Clase
from .models.domain import Domain
from .models.dominio import Dominio
from .models.diagnostic_tag import DiagnosticTag
from .models.defining_characteristics import DefiningCharacteristic
fro... |
from django.utils.module_loading import autodiscover_modules
from django.db import models
class FSMField(models.CharField):
pass
class TransitionsMixin:
pass
def autodiscover():
autodiscover_modules('states')
autodiscover_modules('triggers')
default_app_config = 'bluebottle.fsm.apps.FSMConfig'
|
import pytest
from packaging import version
from flask import Flask, json
from device_manager import app
from unittest import mock
def test_get(mocked_get_mini_provider, test_devices):
client = app.app.test_client()
response = client.get("/")
assert response.status_code == 200
devices = json.loads(r... |
# -*- coding: utf-8 -*-
"""Test simple questions thread author
Notes:
1. We're a bit more strict with this test case.
Consistency is important for the weekly thread, and
formatting and patterns should not change easily.
2. There's lot's of implementation details here.
we can't depend on p... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
class Layer_Dense:
"""
Dokumentasi
input :
output :
"""
# Layer initialization
def __init__(self, n_inputs, n_neurons):
# Initialize weights and biases
self.w... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import pyfits as pf
import numpy as np
import matplotlib.pyplot as plt
from MuSCADeT import MCA
from MuSCADeT import pca_ring_spectrum as pcas
import scipy.stats as sc
from MuSCADeT import colour_subtraction as cs
## Openning data cube
cube = pf.open('./Simu_real/Cube.fits')[0].data
num,n,n = np.shape(cube)
## A for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.