content stringlengths 5 1.05M |
|---|
import peewee as pw
from core.model.base import BaseModel
from playhouse.shortcuts import model_to_dict
class Activity(BaseModel):
name = pw.CharField(null=False)
url_image = pw.CharField(null=False)
def to_dict(self, recurse=False, backrefs=False):
return model_to_dict(self, recurse=recurse, ba... |
# [M / F] while not strip upper
sexo = str(input('Digite seu sexo: [M/F] ')) .strip().upper()[0]
while sexo not in 'MmFf':
sexo = str(input('Dados inválidos. Por favor, informe corretamente: ')).strip().upper()[0]
print(sexo) |
import json
import jsonschema
import os
import re
from urllib.request import urlopen, Request
show_descriptions = True # If False, don't include 'name' as the description of 'licenseId'
repo = 'https://github.com/spdx/license-list-data/tree/master/json'
files = ['licenses.json', 'exceptions.json']
outfile = 'sp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains implementation for type editor
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
import logging
from functools i... |
import random
def n_list(n):
nl = [] #int list to be returned
#creating a list of integers from 1 to n
for i in xrange(1,n+1):
nl.extend([i])
#shuffle the list of integers into random order
#to the best ability of python prng
while n > 1:
choice = int(random.random()*n)
pick = nl.pop(choice)
nl.exten... |
"""
--- Day 18: Operation Order ---
As you look out the window and notice a heavily-forested continent slowly appear over the horizon, you are interrupted by the child sitting next to you. They're curious if you could help them with their math homework.
Unfortunately, it seems like this "math" follows different rules... |
"""Exceptions raised by the s3control service."""
from moto.core.exceptions import RESTError
ERROR_WITH_ACCESS_POINT_NAME = """{% extends 'wrapped_single_error' %}
{% block extra %}<AccessPointName>{{ name }}</AccessPointName>{% endblock %}
"""
ERROR_WITH_ACCESS_POINT_POLICY = """{% extends 'wrapped_single_error' %... |
# encoding: utf-8
from __future__ import unicode_literals
import os
from django.test import TestCase
from data_importer.core.descriptor import ReadDescriptor
from data_importer.core.descriptor import InvalidDescriptor
from data_importer.core.descriptor import InvalidModel
from data_importer.importers.base import BaseIm... |
#---------------------------------------------
# Set up Trick executive parameters.
#---------------------------------------------
#instruments.echo_jobs.echo_jobs_on()
trick.exec_set_trap_sigfpe(True)
#trick.checkpoint_pre_init(1)
trick.checkpoint_post_init(1)
#trick.add_read(0.0 , '''trick.checkpoint('chkpnt_point')... |
import hglib
import os
__all__ = ['HGState']
class HGState(object):
def __init__(self, path):
self.client, self.hg_root_path = self.find_hg_root(path)
def find_hg_root(self, path):
input_path = path
found_root = False
while not found_root:
try:
clie... |
def isPalindrome(word):
for i in range(len(word)//2):
if word[i]!=word[-(i+1)]:
return False
return True
for t in range(10):
N=int(input())
L=[]
for i in range(8):
L.append(input())
ans=0
for i in range(8):
for j in range(9-N):
if isPalindro... |
"""
pyStatic_problem
"""
# =============================================================================
# Imports
# =============================================================================
import warnings
import os
import numpy as np
from collections import OrderedDict
import time
from .base import TACSProblem
i... |
# A collection of functions for loading the esm2m perturbation experiments
import xarray as xr
from gfdl_utils.core import get_pathspp
def get_path(variable=None,
ppname=None,
override=False,
experiments=None,
timespan=None):
"""Returns a dictionary of paths rele... |
import imports.dataHandler as jdata
import imports.passwordToKey as keys
import imports.randomText as rand_text
import pyperclip as clipboard
import imports.CONSTS as CONSTS
import os
from cryptography.fernet import Fernet
from getpass import getpass
import json
protected = ["key", "state"]
MAIN_MENU = 0
RECORDS = ... |
# -*- coding: utf-8 -*-
from doodle.config import CONFIG
from doodle.core.models.article import Article, ArticleHitCount
from doodle.core.models.comment import ArticleComments
from ..base_handler import BaseHandler
class HomeHandler(BaseHandler):
def get(self):
articles, next_cursor = Article.get_articl... |
# NOTICE
# This software was produced for the U.S. Government under contract FA8702-21-C-0001,
# and is subject to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007)
# ©2021 The MITRE Corporation. All Rights Reserved.
'''
A PropertyConstraints object describes type and cardinality constraints
for a single... |
from mock import Mock
from flows.simulacra.youtube_dl.factory import youtube_dl_flow_factory
from flows.simulacra.youtube_dl.post import download_videos
from tests.testcase import TestCase
class TestDownloadVideos(TestCase):
def setUp(self):
self.open = self.set_up_patch(
'flows.simulacra.you... |
# Copyright 2015 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# Copyright 2021 Prayas Energy Group(https://www.prayaspune.org/peg/)
#
# 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... |
import gym
import numpy as np
from gym.spaces import Discrete
from gym_holdem.holdem import Table, Player, BetRound
from pokereval_cactus import Card
class HoldemEnv(gym.Env):
def __init__(self, player_amount=4, small_blind=25, big_blind=50, stakes=1000):
super().__init__()
self.player_amount =... |
# Generated by Django 4.0.1 on 2022-01-27 07:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='bookinstance',
options={'ordering': ... |
"""
return 0 = Success
return 1 = Login = 'Invalid username or password!', Register = 'User is already'
return 2 = 'Something went wrong'
"""
from connect_db import megatronDBC
# login sys / ระบบล็อคอิน
def loginSYS(userInput, passInput):
try:
cursor = megatronDBC.cursor()
select... |
from datetime import timedelta
from app import hackathon_variables
from django.db import models
from django.utils import timezone
from user.models import User
class ItemType(models.Model):
"""Represents a kind of hardware"""
# Human readable name
name = models.CharField(max_length=50, unique=True)
#... |
from __future__ import print_function
from builtins import object
import copy
import numpy as np
class Observer(object):
def __init__(self):
pass
def update(self, state):
pass
def reset(self):
pass
class Printer(object):
def __init__(self, elems=1, msg=None, skip=1):
... |
# proxy module
from __future__ import absolute_import
from chaco.abstract_plot_data import *
|
__author__ = "Doug Napoleone"
__version__ = "0.0.1"
__email__ = 'Doug.Napoleone+niche_scraper@gmail.com' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import logging
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'
@app.route("/... |
from loggers import Actions
from stopping_decision_makers.base_decision_maker import BaseDecisionMaker
class SequentialNonrelDecisionMaker(BaseDecisionMaker):
"""
A concrete implementation of a decision maker.
Returns True iif the depth at which a user is in a SERP is less than a predetermined value.
"... |
from django.db import models
from django.contrib.auth.models import User
from course.models import Course
# Create your models here.
class Answer(models.Model):
user = models.ForeignKey(User, name="user", on_delete=models.CASCADE)
answer = models.TextField()
def __str__(self) -> str:
return se... |
# Time: O(k * log(min(n, m, k))), with n x m matrix
# Space: O(min(n, m, k))
from heapq import heappush, heappop
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
kth_smallest = 0
min_he... |
# -*- coding: utf-8 -*-
from . import main_menu, signals, slides, widgets # noqa
|
# -*- coding: utf-8 -*-
'''
@author: wj3235@126.com
说明:(1)程序仅供技术学习,严禁用于任何商业用途
(2)对于抓取内容及其分析,请勿乱发布,后果自负
(3)软件可能有bug,如果发现望及时告知
(4)成交数据,需要提供修改账户密码,请查找 admin 或者password 修改
'''
import sqlite3
import os
from ErShouFangDbHelper import GetXiaoquNianDai
from ErShouFangDbHelper imp... |
from flask import Blueprint, request
from libs.tools import json_response, JsonParser, Argument
from .models import NotifyWay
blueprint = Blueprint(__name__, __name__)
@blueprint.route('/', methods=['GET'])
def get():
form, error = JsonParser(Argument('page', type=int, default=1, required=False),
... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Licen... |
import pytest
from django.contrib.auth.models import User
from shrubberies.factories import UserFactory
from shrubberies.models import Profile
from .rules import Is, current_user
@pytest.mark.django_db
def test_is_user_function():
u1 = UserFactory()
u2 = UserFactory()
is_own_profile = Is(lambda u: u.prof... |
if __name__ == '__main__':
from scummer.validator import Validator
t = {
'a': 'x',
'b': {
'b1': 123
},
'c': [1,2],
'd': {
'x': 1,
'y': 'aaaa'
}
}
v = Validator(schema={
'a': ('enum',{
'items': ['x',... |
import pandas as pd
import matplotlib.pyplot as plt
import pdb
def main():
results_df = pd.read_csv("results_nm.csv", delimiter=",")
fig_0, ax_0 = plt.subplots()
fig_1, ax_1 = plt.subplots()
for m in results_df.m.unique():
m_subset = results_df[results_df.m == m]
m_means = []
m_... |
import json
import sys
import os
def get_offset(call):
s = call.split("+")
try:
return int(s[1], 16)
except:
pass
def get_hashsum(call):
s = call.split("{")
try:
ss = s[1].split("}")
return ss[0]
except:
s = call.split("!")
try:
retur... |
import os
import shutil
# optional: if you get a SSL CERTIFICATE_VERIFY_FAILED exception
import ssl
import sys
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import urlopen, urlretrieve
from zipfile import ZipFile, is_zipfile
import pandas as pd
from tqdm import ... |
def test_latest():
print('\n >>> start Latest Features... \n')
import talos
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
x, y = talos.templates.datasets.iris()
p = {'activation': ['relu', 'elu'],
'optimizer': ['Nadam', 'Adam'],
'l... |
# Time Complexity: O(n^2)
# Space Complexity: O(n)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for cur in range(len(nums)):
if nums[cur] > 0: break
if cur>0 and nums[cur]==nums[cur-1]: continue # 重点理解
... |
import pandas as pd
import os
# df = pd.read_csv('./train_annotation_list.csv')
# for i in range (len(df['Image_Path'])):
# dirname = os.path.dirname(df['Image_Path'][i])
# patient_name = os.path.basename(df['Image_Path'][i])
# patient_no = int(patient_name.split('.')[0].split('_')[1])
# folder = 'center_'+str(in... |
import pandas as pd
import matplotlib.pyplot as plt
import errno
import os
import numpy as np
from pathlib import Path
import data_helper as dh
# Counts the number of learning agents in one log path
def count_learning_agents_in_logs_path(logs_path):
count = 0
# loop through win rates directories in logs
... |
# TODO: change name to queue
from db_works import db_connect, db_tables
import datetime
def get_settings(interval_param_):
db_schema_name, db_table_name, db_settings_table_name = db_tables()
cursor, cnxn = db_connect()
# interval parameter: current - API data; daily_hist - data from daily files; monthly... |
from tests.utils import TEST_DATA_DIR
from dexy.doc import Doc
from tests.utils import wrap
import os
markdown_file = os.path.join(TEST_DATA_DIR, "markdown-test.md")
def run_kramdown(ext):
with open(markdown_file, 'r') as f:
example_markdown = f.read()
with wrap() as wrapper:
node = Doc("mark... |
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import abort, jsonify, request
from flask_login import current_user
from flask_login import login_required
from app.models import User, load_user
from app.extensions import db
import os
import stripe
stripe.api_key =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404
from django.db import models, migrations
def encrypt_secrets(apps, schema_editor):
Secret = apps.get_model("server", "Secret")
for secret in Secret.objects.all():
secret.save()
class Migrat... |
import pytest
from tartiflette_middleware.examples.standalone import\
StandaloneMiddleware
from tartiflette_middleware.exceptions import\
RequestDataNotStoredException
class TestStandaloneMiddleware:
def test_standalone_example_init(self):
service = StandaloneMiddleware()
@pytest.mark.asyncio... |
import pyrebase
config={
"apiKey": "AIzaSyDYt-fmafI1kkMZSIphL829C6QgdlE1Tro",
"authDomain": "cp19-12.firebaseapp.com",
"databaseURL": "https://cp19-12.firebaseio.com",
" projectId": "cp19-12",
"storageBucket": "cp19-12.appspot.com",
"messagingSenderId": "681358965828",
"appId": "1:681358965828:we... |
# 代码仅供学习交流,不得用于商业/非法使用
# 作者:Charles
# 公众号:Charles的皮卡丘
# 视频下载器-Demo版
# 目前支持的平台:
# 网易云课堂: wangyiyun.wangyiyun()
# 音悦台: yinyuetai.yinyuetai()
# B站: bilibili.bilibili()
import os
import threading
from platforms import *
from utils.utils import *
from tkinter import *
from tkinter import messagebox
from tkinter import fi... |
from __future__ import print_function
import urllib2
import json
import re,datetime
import sys
import csv
class L():
"Anonymous container"
def __init__(i,**fields) :
i.override(fields)
def override(i,d): i.__dict__.update(d); return i
def __repr__(i):
d = i.__dict__
name = i.__class__.__name__
... |
#!/usr/bin/env python3
print(2+4)
print(5**2) # is like 5 power 2 (5^2)
print(5*7 - 9*1)
print(4/2)
print(5/2)
print(5//2) # removes the values after the point
print(7 % 3) # This is the remainder or modulus operator
print(1+1 +(2*5))
print(len("Linux"))
|
# SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import time
import os
# First, just write the file 'hello.txt' to the card
with open("/sd/hello.txt", "w") as f:
print("hello world", file=f)
print()
print("SD card I/O benchmarks")
# Test read and write speed in... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
key_mapping = {'w': [0, 1], 'x': [0, -1],
'a': [-1, 0], 'd': [1, 0],
's': [0, 0]}
g_last_twist = None
def keys_cb(msg, twist_pub):
global g_last_twist
if len(msg.data) == 0 ... |
import abc
import json
import logging
import os
import numpy as np
import tensorflow as tf
def zip_weights(model, ckpt, variables_mapping, self_weight_names, **kwargs):
weights, values = [], []
used_weights = [w for w in model.trainable_weights if w.name in self_weight_names]
for w in used_weights:
... |
import tensorflow as tf
import value_fns
class ValueFnTests(tf.test.TestCase):
def test_label_attention_fn(self):
with self.test_session():
mode = tf.estimator.ModeKeys.TRAIN
# num_labels x label_embedding_dim
label_embeddings = tf.constant([[0.1, 0.1, 0.1, 0.1],
... |
"""
fabfile module containing application-specific tasks.
"""
from fabric.api import task
from fabric.colors import cyan
from fabfile.utils import do
from fabfile.virtualenv import venv_path
@task
def build():
"""
Run application build tasks.
"""
# Generate static assets. Note that we always build ass... |
"""
OpenOpt SOCP example
for the problem http://openopt.org/images/2/28/SOCP.png
"""
from numpy import *
from openopt import SOCP
f = array([-2, 1, 5])
C0 = mat('-13 3 5; -12 12 -6')
d0 = [-3, -2]
q0 = array([-12, -6, 5])
s0 = -12
C1 = mat('-3 6 2; 1 9 2; -1 -19 3')
d1 = [0, 3, -42]
q1 = array([-3, 6, -10])
s1 = 27... |
from splinter import Browser
b = Browser()
b.visit('http://selenium.dunossauro.live/aula_09_a.html')
if b.is_text_not_present('Carregamento concluído'):
b.find_by_text('Barrinha top').click()
print(b.is_text_present('Barrinha top', wait_time=10))
|
""" Shows how to combine surface terrain with surface properties
"""
from __future__ import print_function
from __future__ import division
import matplotlib as mpl
mpl.interactive(False)
import sys
import numpy as np
import matplotlib.pyplot as plt
from plotting import make_test_data
from plotting import draw
from ... |
# Now make a simple example using the custom projection.
import pdb
import sys
import os
import pkg_resources
pkg_resources.require('matplotlib==1.4.0')
import datetime
from dateutil.relativedelta import relativedelta
import re
import math
from matplotlib.ticker import ScalarFormatter, MultipleLocator
from matplotlib... |
"""
Stores all the view logic for deckr.
"""
# pylint can't detect the constructor for a Django
# form. So we disable the no-value-for-parameter here.
# pylint: disable=no-value-for-parameter
from os.path import join as pjoin
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404... |
from org.transcrypt.stubs.browser import *
import random
array = []
array_str = ""
def gen_random_int(number, seed):
# console.log("random")
random.seed(seed)
array = list(range(0, number))
random.shuffle(array)
return array
def generate():
global array
global array_str
number = 10
seed = 200
array = ... |
"""Mathematical utility functions (intended for internal purposes).
A lot of this is experimental and has a high probability of changing in the future.
"""
import functools
import itertools
import math
import operator
import numpy as np
__all__ = [
"argmax",
"chain_dot",
"clamp",
"dot",
"dotvecm... |
from pymocap.color_terminal import ColorTerminal
from pymocap.event import Event
import struct, os
from datetime import datetime
class NatnetFile:
def __init__(self, path=None, loop=True):
self.path = path
self.loop = loop
# file handles
self.read_file = None
self.write_fi... |
import io
import re
from math import ceil
from . import *
from config import Config
from userbot import CMD_LIST, CMD_HELP
from telethon import custom, events
Andencento_pic = Config.PMPERMIT_PIC or "https://telegra.ph/file/ac32724650ef92663fbd1.png"
cstm_pmp = Config.CUSTOM_PMPERMIT
ALV_PIC = Config.ALIVE_PIC
mssge = ... |
import numpy as np
import sys
def get_randn(n=10):
randints = np.random.randint(100, size=n)
return ":".join(["%02d" % i for i in randints])
|
'''
hms_client
'''
from hubsync.http_client import client
class Repo(object):
''' Repo
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
LogoUrl string `json:"logoUrl"`
Summary string `json:"summary,omitempty"`
Description string `json:"descri... |
#!/usr/bin/env python
from peyotl.nexson_validation.helper import _NEXEL, errorReturn
from peyotl.nexson_validation.err_generator import (gen_InvalidKeyWarning,
gen_MissingCrucialContentWarning,
gen_MissingMandatoryK... |
pytest_plugins = "beancount.ingest.regression_pytest"
|
import sys
sys.path.append('../../')
import open3d
import numpy as np
import time
import os
from ThreeDMatch.Test.tools import get_pcd, get_ETH_keypts, get_desc, loadlog
from sklearn.neighbors import KDTree
import glob
def calculate_M(source_desc, target_desc):
"""
Find the mutually closest point pairs in fe... |
class Space(object):
def __init__(self, col, row, terrain='.'):
self.col = col
self.row = row
self.terrain = terrain
self.occupied = False
|
from django.contrib import admin
from .models import AcademicNotice
# Register your models here.
class MyModelAdmin(admin.ModelAdmin):
fields = ['title','body']
def save_model(self,request,obj,form,change):
obj.author = request.user
super().save_model(request, obj, form, change)
admin.site.register(AcademicNotice... |
import tensorflow as tf
from tensorflow import keras
# from tensorflow.
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10)
])
#1
# model.compile(loss='mean_squared_error', optimizer='sgd')
#2
from keras i... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode... |
"""pysat URL Configuration for User.Info
"""
from django.urls import path
from utils.views import view_maker
from utils.params import ParamType
from utils.permission import ActionType
from user.views import info
urlpatterns = [
path('get', view_maker(info.get_info, 'GET', [
ParamType.UsernameWithDefault
... |
"""Helpers for Roku Client."""
from ipaddress import ip_address
from socket import gaierror as SocketGIAError
from .exceptions import RokuConnectionError
from .resolver import ThreadedResolver
def is_ip_address(host: str) -> bool:
"""Determine if host is an IP Address."""
try:
ip_address(host)
ex... |
import asyncio_redis
from vibora import Vibora
from vibora.hooks import Events
from vibora.sessions import AsyncRedis
from vibora.responses import Response
app = Vibora(
sessions=AsyncRedis()
)
@app.route('/', cache=False)
async def home(request):
print(request.session.dump())
await request.load_session... |
# -*- coding: utf-8 -*-
from django.urls import reverse_lazy
from django.views.generic import View
from django.http import HttpResponse
from django.core import serializers
from djangoSIGE.apps.base.custom_views import CustomCreateView, CustomListView, CustomUpdateView
from djangoSIGE.apps.vendas.forms import Condica... |
import numpy as np
import pandas as pd
from scipy.stats import poisson
from cooltools.api.dotfinder import (
histogram_scored_pixels,
determine_thresholds,
annotate_pixels_with_qvalues,
extract_scored_pixels,
)
# helper functions for BH-FDR copied from www.statsmodels.org
def _fdrcorrection(pvals, al... |
import unittest
from flatten import flattener
class FlattenTests(unittest.TestCase):
def test_single_small_nested_list(self):
calculated = flattener([1, [2, 3]])
expected = [1, 2, 3]
self.assertEqual(calculated, expected)
if __name__ == "__main__":
unittest.main()
|
# Generated by Django 3.2.6 on 2021-08-30 14:52
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('todo', '0002_alter_profile_unique_together'),... |
categories = [
{"name": "Action"},
{"name": "Drama"},
{"name": "Comedy"},
{"name": "Fantasy"},
{"name": "Sci-fi"},
] |
# Copyright (c) 2021 China Unicom Cloud Data Co.,Ltd.
# 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
#
... |
import os
from operator import itemgetter
import fpdf
def gen_report(target, rep):
print("[=] Creating PDF...")
class PPDF(fpdf.FPDF):
def footer(self):
self.set_y(-15)
self.set_font("Arial", style="I", size=8)
self.cell(0, 10, "soc_recon report", align="C")
... |
# -*- coding: utf-8 -*-
"""Physics Guided Neural Network python library."""
import os
from .model_interfaces import PhygnnModel, RandomForestModel, TfModel
from .phygnn import PhysicsGuidedNeuralNetwork, p_fun_dummy
from .utilities import Layers, HiddenLayers, PreProcess, tf_isin, tf_log10
from phygnn.version import __... |
import numpy as np
class BodyModel:
def __init__(self, mapping, pairs) -> None:
self.mapping = mapping
self.pairs = pairs
BODY18 = BodyModel(
mapping=[
"nose",
"left_eye",
"right_eye",
"left_ear",
"right_ear",
"left_shoulder",
"right_sh... |
from datetime import datetime as dt
from . import __version__
import typing as t
def client_imports_f() -> str:
"""
Creates the string to import the client dependencies and
a default module doc string. Usually the first part
of the client module.
Returns:
str: import statements string rea... |
from django.utils import timezone
from rest_framework import serializers
from .models import Client
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
fields = (
'id',
'business_owner',
'first_name',
'last_name',
... |
from django.apps import AppConfig
class PhoneCodeConfig(AppConfig):
name = 'phonecode'
|
from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
QParams = namedtuple('QParams', ['range', 'zero_point', 'num_bits'])
_DEFAULT_FLATTEN = (1, -1)
_DEFAULT_FLATTEN_GRAD = (0, -1)
def _deflatt... |
from invoke import Collection
from tasks import build
ns = Collection()
ns.add_collection(build)
|
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from app.config import Config
# Init
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager... |
search_customizations = {
## The name of the variable to contain the list of results (default 'search_results')
# 'context_object_name': '',
## The list of models to exclude from search results (default empty list)
# 'exclude': (),
## The page to redirect to if the user enters an empty search term (... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Created on : 2019-03-06 17:36
# @Author : zpy
# @Software: PyCharm
import logging
from logging.handlers import RotatingFileHandler
import functools
import inspect
from datetime import datetime
from collections import defaultdict
import os
from config import LOGPATH as ... |
from copy import deepcopy
import dendropy
from iterpop import iterpop as ip
import itertools as it
import numpy as np
from sortedcontainers import SortedSet
def dendropy_tree_to_scipy_linkage_matrix(tree: dendropy.Tree) -> np.array:
# scipy linkage format
# http://docs.scipy.org/doc/scipy/reference/generated/... |
from __future__ import absolute_import
from .ABuGridSearch import ParameterGrid, GridSearch
from .ABuCrossVal import AbuCrossVal
from .ABuMetricsBase import AbuMetricsBase, MetricsDemo
from .ABuMetricsFutures import AbuMetricsFutures
from .ABuMetricsTC import AbuMetricsTC
from .ABuMetricsScore import AbuBaseScorer, Wr... |
#!/usr/bin/env python3
'''
Helper script to clean up some Redis keys
This should probably become part of the regular scheduler code!
'''
import click
import random
import redis
import collections
@click.command()
@click.argument('redis-host')
@click.argument('redis-port')
def main(redis_host, redis_port):
r = ... |
import math
print(math.pi) |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.