content stringlengths 5 1.05M |
|---|
from django.urls import path
from tee import views
app_name = "tee"
urlpatterns = [
path("create/<str:shape>/<str:color>/<str:text_color>/<str:font>/<path:sentence>/<str:filename>.png", views.GeneratorView.as_view(), name="generator"),
] |
from collections.abc import MutableMapping
import os
from os import path
from macresources import make_rez_code, parse_rez_code, make_file, parse_file
from warnings import warn
TEXT_TYPES = [b'TEXT', b'ttro'] # Teach Text read-only
def _unsyncability(name): # files named '_' reserved for directory Finder info
i... |
import pandas as pd
import numpy as np
import altair as alt
def plot_correlation(corr_data, title, strongest_only=True):
if strongest_only:
strongest = corr_data.sort_values("Correlation", ascending=False)
strongest = strongest[strongest["Variable 1"] != strongest["Variable 2"]]
corr_data ... |
# ===============================================================================
# Copyright 2021 Intel Corporation
#
# 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.... |
from sophysics_engine import EnvironmentComponent, Camera, EnvironmentUpdateEvent, PygameEvent
from time import process_time
from typing import Optional
import pygame
class CameraController(EnvironmentComponent):
"""
Allows the user to control the camera using the mousewheel
"""
def __init__(self, cam... |
# -*- coding: utf-8 -*-
import datetime
import furl
import httplib as http
import markupsafe
from flask import request
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from modularodm.exceptions import ValidationValueError
from framework import forms, status
from framework import auth as fra... |
import pytest
from django.test import RequestFactory
from cdsso.users.api.views import UserViewSet
from cdsso.users.models import User
pytestmark = pytest.mark.django_db
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
view = UserV... |
import os
from os import path as osp
import hydra
import pickle
from tqdm import tqdm
import torch
from data.dataset import MegaDepthDataset
from data.augmentations import get_img_augmentations
@hydra.main(config_path="configs", config_name="gen_val_dataset")
def main(cfg):
data_params = cfg.data_params
set_s... |
# ###########################################################################
import os
import numpy as np
from sts.data.loader import load_california_electricity_demand
from sts.models.prophet import default_prophet_model
# Load the training data (through 2018)
df = load_california_electricity_demand(train_only=... |
#@+leo-ver=5-thin
#@+node:tom.20210613135525.1: * @file ../plugins/freewin.py
r"""
#@+<< docstring >>
#@+node:tom.20210603022210.1: ** << docstring >>
Freewin - a plugin with a basic editor pane that tracks an
outline node.
Provides a free-floating window tied to one node in an outline.
The window functions as a plain... |
from distutils.core import setup
setup(
name='AutoTransformPy',
version='0.1',
author='Alycia Butterworth, Brenden Everitt, Rayce Rossum',
author_email='NA',
packages=['AutoTransformPy'],
description='A robust image transformation generator',
license='LICENSE.txt',
long_description=open... |
import os
import smtplib
from tkinter import *
import tkinter.messagebox as mb
os.chdir(r'C:\\ProgramData')
if os.path.isdir("PRIVATE"):
pass
else:
os.mkdir('PRIVATE')
os.chdir('PRIVATE')
class mypassword():
def __init__(self):
self.root = Tk()
self.root.title("Passwordsaver by king")
... |
import deuce.tests.db_mocking.swift_mocking.client
|
"""
This destination just print payload to stdout
"""
from pprint import pprint
from aeroport.abc import AbstractDestination, AbstractPayload
class ConsoleDestination(AbstractDestination):
async def process_payload(self, payload: AbstractPayload):
pprint(payload.as_dict)
async def prepare(self):
... |
import os, torch
class States(object):
def __init__(self, **attr):
self.attr = attr
def get_state(self, item):
try: return item.state_dict()
except AttributeError: return item
def set_state(self, name, item):
try: self.name.load_state_dict(item)
exc... |
from .generate import * |
#!/usr/bin/env python
import optparse
import sys
import numpy
from collections import defaultdict
#Shameless copy
optparser = optparse.OptionParser()
optparser.add_option("-d", "--data", dest="train", default="data/hansards", help="Data filename prefix (default=data)")
optparser.add_option("-e", "--english", dest="en... |
# -*- coding: utf-8 -*-
"""计算股票夏普比率
https://zhuanlan.zhihu.com/p/94058575
@Time : 2020/3/1 上午10:22
@File : test_sharp.py
@author : pchaos
@license : Copyright(C), pchaos
@Contact : p19992003#gmail.com
"""
import unittest
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
imp... |
from datetime import datetime
import pickle
def storeData(obj_model):
"""
Store object as (pk) dump file
:param obj_model: object model
:return: pickled file
"""
print("Saving file into (pk) dump file...\n")
time_stamp = datetime.today().strftime('%d_%m_%Y')
file_name = tim... |
import logging
from functools import partial
from dbnd import output, parameter, task
from dbnd._core.decorator.decorated_task import DecoratedPythonTask
class ExperiementTask(DecoratedPythonTask):
custom_name = parameter.value("aa")
previous_exp = parameter.value(1)
score_card = output.csv.data
my... |
import csv
import re
from os.path import abspath, basename, dirname, join
def read_csv(path, parser=None):
path = abspath(path)
name = basename(path)
name = re.sub('^test_', '', name)
name = re.sub('py$', 'csv', name)
cases = join(dirname(path), 'cases')
csv_path = join(cases, name)
with ... |
def visitsOnCircularRoad(n, v):
c = 1
t = 0
for i in v :
t += min(abs(i - c), abs(n - abs(i - c)))
c = i
return t
# v = visitsOrder
# n = number of houses
# c = Current position
# t = Time |
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'accounts/accounts.html') |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... |
'''
Created on Dec 16, 2012
@author: sar
'''
import numpy as np
#from sklearn import mixture
import gmm_diag2_forJason as proj
if __name__ == '__main__':
np.random.seed(1)
g = proj.GMM(n_components=2, covariance_type='full')
# Generate random observations with two modes centered on 0
# and 10 to use ... |
from base64 import b64encode
from typing import TYPE_CHECKING, List
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from typer import Argument, Typer, prompt
from kolombo.console import error, finished, info, print_list, started, step, warning
from kolombo.util import async_command, needs_database
if TY... |
import torch
import numpy as np
import torch.nn.functional as F
from box import Box
from force import ForceField
class Thermostat(torch.nn.Module):
def __init__(self, SimObj, type, timestep, temperature, device="cpu", **thrmst_params):
if type is "vel":
self.type = type
self.apply ... |
import argparse
import datetime
import multiprocessing
import time
import matplotlib.pyplot as plt
import numpy as np
import bss
from bss.head import HEADUpdate
config = {
"seed": 873009,
"n_repeat": 1000,
"n_chan": [4, 6, 8],
"tol": -1.0, # i.e. ignore tolerance
"maxiter": 100,
"dtype": np.... |
# Generated by Django 3.2.4 on 2021-06-24 04:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Results',
fields=[
('id', m... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 6 12:03:20 2017
@author: rachael
Create a dummy gsd file with 4 molecules of 17 beads each in 6 snapshots
Used to check cluster analysis
"""
from __future__ import absolute_import, division, print_function
import gsd.hoomd
import numpy as np
def quatMultiply(q1,q2):
... |
# -*- coding: utf-8 -*-
from mamba import description, context, it
from expects import expect, be, have_len, be_above, equal
import os
from infcommon.mysql import mysql
TEST_TABLE = 'integration_test_table'
with description('MySQLClientTest'):
with before.each:
self.mysql_client = mysql.MySQLClient(os... |
import re
from setuptools import setup, find_packages
install_requires = ["boto3==1.9.196", "click==7.0", "requests-aws4auth==0.9"]
tests_requires = [
"flake8==3.7.8",
"isort==4.3.21",
"pytest==5.0.1",
"pytest-cov==2.7.1",
]
with open("README.md") as fh:
long_description = re.sub(
"<!--... |
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
import tempfile
def _get_source_files(compilation_database):
for compile_command in compilation_database:
yield os.path.join(compile_command['directory'], compile_command['file'])
def _get_compilation_database(build_args):
su... |
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. =
# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ful... |
# -*- coding: utf-8 -*-
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def add(self, group):
wd = self.app.wd
self.open_groups_page()
wd.find_element_by_name("new").click()
self.fill_group_form(group)
wd.find_element_by... |
# Generated by Django 2.1.3 on 2018-12-05 22:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_tag_tag_type'),
]
operations = [
migrations.AddField(
model_name='ingestlog',
name='new',
... |
from flask import Flask, jsonify, request, make_response
import flask_restful
from flask_restful import Resource, Api
from flasgger.utils import swag_from
from werkzeug.security import generate_password_hash, check_password_hash
from . import users
from app.models import database, User
import jwt
import datetime
from f... |
import os
import argparse
from dotenv import load_dotenv
from mev.azure.run import get_auth_ws, run_prepare
load_dotenv()
ENVIRONMENT_VARIABLES = dict(
TENANT_ID=os.getenv("TENANT_ID"),
MONGO_CONNECTION_STRING=os.getenv("MONGO_CONNECTION_STRING"),
MONGO_DATABASE_NAME=os.getenv("MONGO_DATABASE_NAME"),
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url('api/users', views.UserCreate.as_view(), name='account-create'),
url('tasks', views.TaskCreate.as_view(), name='tasks-create'),
url('tasks2', views.Task2Create.as_view(), name='tasks-create'),
url('project', views.ProjectCreate.a... |
import cv2
import numpy as np
USE_TRACKING_AFTER_INITIAL_FACE_DETECTION = True
STABILIZED_WINDOW_HEIGHT_HALF = int(720 / 2)
STABILIZED_WINDOW_WIDTH_HALF = int(1800 / 2)
HEIGHT_OFFSET_FOR_STABILIZED_WINDOW = 2000
WIDTH_OFFSET_FOR_STABILIZED_WINDOW = 0
SAVE_OUTPUT_VIDEO = True
OUTPUT_VIDEO_FPS = 30
VIDEO_SRC_IS_CAM = Tr... |
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import override_settings
from eno_a3_django.users.tests.factories import EnProfileFactory, RoleFactory, UserFactory
from organizations.tests.factories import OrganizationFactory
from rest_framework import status... |
# -*- coding: utf-8 -*-
from flask import current_app
from flask.ext.login import UserMixin
from datetime import datetime, timedelta
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from stacksites.database import db, CRUDMixin
from stacksites.extensions import bcrypt
from stacksites.sites.models... |
__author__ = 'alexander'
import logging
log = logging.getLogger(__name__)
class MockRedisClient:
"""
Mocks Redis client class. Used if Celery is disabled. Does nothing.
"""
def set(self, *args):
log.debug("Setting a value in MockRedisClient")
def generate_task_id(self, client_id):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 客户端使用UDP时,首先创建基于UDP的Socket,然后不需要调用connect(),直接通过sendto()给服务器发数据
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in ['Michael', 'Tracy', 'Sarah']:
s.sendto(data, ('127.0.0.1', 9999)) # 发送数据
print s.recv(1024) # 接收数据
s.close()
|
import math
# Constants
event_type = 'EVENTMSGTYPE'
event_subtype = 'EVENTMSGACTIONTYPE'
home_description = 'HOMEDESCRIPTION'
neutral_description = 'NEUTRALDESCRIPTION'
away_description = 'VISITORDESCRIPTION'
period_column = 'PERIOD'
game_clock = 'PCTIMESTRING'
time_elapsed = 'TIME_ELAPSED'
time_elapsed_period = 'TIME_... |
import sqlite3 as lite
import sys
con = lite.connect('sensorsData.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS DHT_data")
cur.execute("CREATE TABLE DHT_data(timestamp DATETIME, temp NUMERIC, hum NUMERIC)") |
_author_ = 'fmoscato'
import random
import string
import hashlib
from datetime import datetime
import pymongo
import constants as c
import pubUtilities
# The User Data Access Object handles all interactions with the User collection.
class UserDAO:
def __init__(self, db):
self.db = db
self.us... |
from __future__ import unicode_literals
import os
from django.utils import six
from djblets.webapi.errors import INVALID_FORM_DATA
from reviewboard import scmtools
from reviewboard.attachments.models import FileAttachment
from reviewboard.diffviewer.models import DiffSet, FileDiff
from reviewboard.webapi.resources i... |
import numpy as np
class Schedule():
def __init__(self, name, dict_repr):
self.name = name
self.type_dict = {
'interchange':0,
'tiling':1,
'unrolling':2
}
self.binary_repr = None
... |
from __future__ import annotations
import collections
from typing import Dict, List, Optional, Tuple, Union
# TODO Implement more classmethods for each filter type.
class Equalizer:
def __init__(self, *, bands: List[Tuple[int, float]], name='Equalizer') -> None:
self._bands = self._bands(bands=bands)... |
# Copyright 2019-2021 Wingify Software Pvt. Ltd.
#
# 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 agr... |
# Contando Progressivamente
for c in range(0, 11):
print(c)
print('FIM!')
# Contando Regressivamente
for i in range(11, 0, -1):
print(i)
print('FIM!!')
|
from __future__ import absolute_import
from __future__ import print_function
from app.workflows.sample_tasks import add_one_and_print
from app.workflows.work import find_odd_numbers_with_string
def test_add_one_and_print():
outs = add_one_and_print.unit_test(value_to_print=15)
assert outs['out'] == 16
def ... |
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = '_'
STATIC_ROOT = os.path.join(BASE_DIR, '__STATIC_ROOT__')
STATIC_URL = '/static/'
INSTALLED_APPS = (
'django.contrib.staticfiles',
'tests.django_test_app',
'webpack',
)
STATICFILES_FINDERS = (
# Defaults
'django.cont... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBit64(RPackage):
"""A S3 Class for Vectors of 64bit Integers
Package 'bit64' provide... |
import numpy as np
from scipy import constants
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import cm
# from qtutils.analysis import ox_data_utils
from qtutils.analysis import data_utils
from .plot_utils import *
from .import_data_utils impor... |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
# square figure and square axes looks better for polar plots
numpy_test_figure = obj.mpl_new_figure(figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8], polar... |
# -*- coding: utf-8 -*-
from collections import defaultdict
from array import array as pyarray
from brainpy import (
calculate_mass, neutral_mass, PROTON,
isotopic_variants, mass_charge_ratio)
from brainpy.composition import (
parse_formula,
PyComposition)
from .utils import dict_proxy
from .constan... |
import os
import imageio
import numpy as np
import scipy
def load_images_from_folder(folder_name):
return list(
map(lambda image_name: (
image_name, imageio.imread(os.path.join(folder_name, image_name)) / 255),
os.listdir(folder_name)))
def prepare_input_data(database_folder='./i... |
# -*- coding: utf-8 -*-
# Created by restran on 2017/8/14
from __future__ import unicode_literals, absolute_import
from mountains.utils import PrintCollector
"""
手机9宫格键盘编码
"""
dict_map = {
'21': 'a', '22': 'b', '23': 'c',
'31': 'd', '32': 'e', '33': 'f',
'41': 'g', '42': 'h', '43': 'i',
'51': 'j', '52... |
"""Common audit metadata for our data models."""
import datetime
from sqlalchemy import schema, sql, func
from sqlalchemy.sql import sqltypes
class AuditColumnsMixin:
"""A mixin to add audit columns to a data model.
Attributes:
created_datetime: Metadata describing when a row was created.
up... |
# -*- coding: utf-8 -*-
"""
A parser for the Syslog Protocol (RFC5424 - http://tools.ietf.org/search/rfc542)
Copyright © 2011 Evax Software <contact@evax.fr>
"""
import calendar
import sys
from datetime import datetime
from ..pyparsing import Word, Regex, Group, White, Combine, CharsNotIn, \
ZeroOrMore, OneOrMor... |
import tensorflow as tf
import time
import datetime
import sys
import logging
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping
from train_data_preparation import tokenizer, dataset_train, train_max_length
from valid_data_preparation import dataset_val
from model import Captioner
from train_util... |
# Import a whole load of stuff
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from Analysis.EDM import *
from DAQ.Environment import *
from EDMConfig... |
from rest_framework.routers import DefaultRouter
from website.views import PartnerViewSet, FaqViewSet, MenuItemViewSet, ArticleViewSet, NewsletterViewSet, \
WantToHelpViewSet, ContactViewSet
router = DefaultRouter()
router.register('partners', PartnerViewSet)
router.register('faqs', FaqViewSet)
router.regist... |
# 정수 입력받아 유니코드 문자로 변환하기
print(chr(int(input()))) |
# Python Module example
import logging
logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
logger.setLevel(logging.INFO)
def sub(a, b):
"""This program subtracts two
numbers and return the result"""
result = a - b
return result
|
from .mulfft import PolyMul,PolyMullvl2Long
from .utils import gaussian32, dtot32, gaussian64, dtot64
from secrets import randbits
import os
import numpy as np
def trlweSymEncrypt(p, alpha, key, twist):
# a = np.array([randbits(32) for i in range(len(key))], dtype=np.uint32)
a = np.frombuffer(os.urandom(len(k... |
import torch
from torch import nn
from torch.utils.data import Dataset
class DataSet(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return self.data.shape[0]
def __getitem__(self, index):
return self.data[index, :]
class Loss(nn.Module):
def __ini... |
from django.contrib.auth.models import User
import factory
import factory.django
from rgd import models
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda n: f'user_{n}')
email = factory.Faker('safe_email')
first_name = factory.Fa... |
#!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='cwa',
version='1.0',
description='Python Implementation of the CoronaWarnApp (CWA) Event Registration',
author='Greg Ward',
author_email='github@mazdermind.de',
url='https://github.com/MaZderMind/cwa-qr',
package... |
import logging
import re
from django.apps import apps
from django.utils import timezone
import habanero
class Crossref:
def __init__(self, id=None, query=None):
# TODO: Handle query case
self.cr = habanero.Crossref(mailto='dev@quantfive.org')
self.data = None
self.data_message = ... |
from unittest import TestCase
from parameterized import parameterized
from design_patterns.proxy.protection import Driver, Car, CarProxy
class TestProtectionProxy(TestCase):
@parameterized.expand(
[
(Driver("James", 20), "Car is being driven by James"),
(Driver("Alex", 26), "Car ... |
import os
import sys
import shutil
import pkgutil
from os import path
from yadocgen.rendering import *
from anytree import Node, Resolver, RenderTree, PreOrderIter, ContRoundStyle
def walk_packages_error(name):
"""Error callback for pkgutil.walk_packages."""
extype, value, traceback = sys.exc_info()
print... |
import LevelBuilder
from sprites import *
def render(name,bg):
lb = LevelBuilder.LevelBuilder(name+".plist",background=bg)
lb.addObject(Bullet.BulletSprite(x=0, y=0,width=10,height=10,angle='0',restitution=0.5,static='false',friction=0.5,density=3,spawnEvent='onShoot'))
lb.addObject(Hero.HeroSprite(x=42, y=52,width=... |
#!/usr/bin/env python3
import boto3
def main():
dynamo = boto3.client('dynamodb')
result = dynamo.scan(TableName='jtate-dynamo-1')
items = result['Items']
for item in items:
if 'key' in item and 'value' in item:
print(item['key']['S'] + ':', item['value']['S'])
if __name__ == '__... |
import unittest
from binary_search import BinarySearch
class ListComprehensionTest(unittest.TestCase):
"""Binary Search to traverse an ordered list, effectively
Populate the arrays with valid content
"""
def setUp(self):
self.one_to_twenty = BinarySearch(20, 1)
self.two_to_forty =... |
from os import path
from unittest.mock import patch
from biocommons.seqrepo.dataproxy import SeqRepoRESTDataProxy
from biocommons.seqrepo.seqrepo import SeqRepo
from bioutils import seqfetcher
from hgvs.dataproviders.seqfetcher import SeqFetcher
@patch.object(path, "exists")
def test_seqfetcher_initialized_with_seq... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 12:15:43 2020
@author: mhayt
"""
#-------------------------------- API-FOOTBALL --------------------------------
import numpy as np
import pandas as pd
import pickle
from sklearn import preprocessing
import matplotlib.pyplot as plt
#-----------------------------... |
import xml.etree.ElementTree as ET
class Remediation(object):
def __init__(self, remediationId, text):
self.remediationId = remediationId
self.text = text
def getId(self):
return self.remediationId
def getText(self):
return self.text
... |
import pytest ; pytest
from cuXfilter.charts.core.core_chart import BaseChart
class TestBaseChart():
def test_variables(self):
bc = BaseChart()
assert bc.chart_type == None
assert bc.x == None
assert bc.y == None
assert bc.aggregate_fn == 'count'
assert bc.colo... |
# Generated by Django 2.2.2 on 2019-06-30 02:48
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
# migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('ontask', '0002_auto_20... |
'''
AUTHORS:
NORSTRÖM, ARVID 19940206-3193,
HISELIUS, LEO 19940221-4192
'''
from collections import namedtuple
import numpy as np
import gym
import torch
import matplotlib.pyplot as plt
from tqdm import trange
from DQN_agent import RandomAgent, Agent
from DQN_agent import ExperienceReplayBuffer
import torch.opt... |
import os
import re
import traceback
from datetime import datetime
from api import app, utils
from common.config import globals
from common.utils import converters
class FarmSummary:
def __init__(self, cli_stdout, blockchain):
self.plot_count = 0
self.plots_size = 0
for line ... |
import requests
endpoint = 'https://swapi.py4e.com/api'
response = requests.get(f"{endpoint}/people/", {'search': 'Finn'}).json()
finn = response['results'][0]
print(f"\nFinn = {finn}") |
import discord
import sqlite3
from discord.ext import commands
conn= sqlite3.connect("dbs/main.db")
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 30, commands.BucketType.guild)
@commands.has_permissions(manage_channels=True)
async def setchann... |
from typing import List
def linear_search(arr: List[int], target: int) -> int:
for idx, val in enumerate(arr):
if val == target:
return idx
return -1
|
# c0ded by zer0_p1k4chu
'''
This script is the Client module of the NSRL_Server_API project.
'''
try:
import traceback
import json
import sqlite3
import sqlalchemy as sa
import pandas as pd
import sys
from os import path
import requests
import argparse
from termcolor import color... |
from bottle import abort, get, post, redirect, request, route
from .. import dbengine
from ..app import authenticate, db_object_to_dict
from ..models import Chapter, Character, Passage
from ..view import render
class Passages:
def __init__(self):
pass
def all(self):
"""list all passages for e... |
print("Format masukkan = JAM:MENIT:DETIK")
waktu_awal = input("Masukkan waktu awal : ").split(":")
waktu_akhir = input("Masukkan waktu akhir : ").split(":")
try:
waktu_awal, waktu_akhir = [int(satuan) for satuan in waktu_awal], [int(satuan) for satuan in waktu_akhir]
if waktu_awal[1] > 60 or waktu_awal[2] > 60... |
import tvm
from hw_generator.generator import generator, accelerator, parse_params
from hw_generator.intrinsic_lib import conv_intrinsic, gemm_intrinsic
# from flextensor.intrinsic import INTRIN_TABLE
# from inspect import signature
from codesign.config import verbose, bits_map
def conv_interface(f_n, f_c, f_y, f_... |
#!/usr/bin/python3.4
''' A change to `local_bad_scope.py` avoiding any error by passing a parameter '''
def main():
x = 3
f(x)
def f(whatever):
print(whatever) # error: f doesn't know about the x defined in main
main()
|
from utils.utils import *
from utils.plotters import *
import os
import librosa
class AudioGenerator(object):
def __init__(self, params, generators_list=None, noise_amp_list=None, reconstruction_noise_list=None):
super(AudioGenerator, self).__init__()
if type(params) is str:
... |
class SimulatorError(Exception):
pass
class ConvergenceError(Exception):
pass
class CircuitParameterError(Exception):
pass
|
from config import db
from models import Application
def read_one(activatorId):
"""
Responds to a request for /api/application_meta/{activatorId}
:param application: activatorId
:return: count of applications that match the acivatorId
"""
acount = (
db.sessi... |
from django.urls import path
from Location.views import CityList
app_name='Location'
urlpatterns=[
path('city/',CityList.as_view()),
# path('city/area/',AreaList.as_view())
]
|
## Graphite local_settings.py
# Edit this file to customize the default Graphite webapp settings
DATABASES = {
'default': {
'NAME': 'graphite.db',
'ENGINE': 'django.db.backends.sqlite3',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': ''
}
}
|
# -*- coding: UTF-8 -*-
import os
from datetime import timedelta
# QQbot参数信息
HOST = "0.0.0.0"
PORT = 8080 # 事件端口
ACCESS_TOKEN = "" # access_token
SECRET = "" # secret
DEBUG = True ... |
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from hifireg import settings
database = settings.DATABASES['default']
def get_db_conn(db_name):
conn = psycopg2.connect(
host=database['HOST'],
port=database['PORT'],
database=db_name,
user=database['USER']... |
# Importing the libraries
import pandas as pd
import streamlit as st
import folium
import geopandas
import plotly.express as px
from streamlit_folium import folium_static
from folium.plugins import MarkerCluster
from datetime import datetime
# Setting page layout for figures
st.set_page_config(layout='wide')
@st.cach... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.