content stringlengths 5 1.05M |
|---|
import numpy as np
import torch
DNA_SIZE = 16
POP_SIZE = 10
CROSSOVER_RATE = 0.8
MUTATION_RATE = 0.005
N_GENERATIONS = 10
class GA(object):
def setF(self,func):
self.F = func
def get_fitness(self,pop):
weight = self.translateDNA(pop)
pred = []
for i in range(len(weight)):
... |
import unittest
from jgi_mg_assembly.pipeline_steps.step import Step
import util
class StepTest(unittest.TestCase):
"""
Tests the pipeline step base class.
"""
def test_step_bad_fn(self):
name = "Foo"
version_name = "Bar"
base_command = "foo"
output_dir = "output_dir"
... |
import os
import subprocess
import argparse
# prefix = os.path.join(os.path.expanduser("~"), "Projects", "pandaPI")
prefix = os.path.join(os.path.expanduser("~"), "projects", "pandaPI")
# planFilePath = os.path.join(prefix, "ipc-2020-plans", "po-plans", "IPC-2020")
# planFilePath = os.path.join(prefix, "ipc-2020-plans... |
import unittest, math, sys, os
from datetime import date
from dateutil.relativedelta import relativedelta
sys.path.insert(0, os.path.join(os.path.dirname(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pdgatools import Rating, RoundRating
class TestRating(unittest.TestCase):
def ... |
# FIXME: Merge this with fixfmt.table!
from . import palide
from .lib import ansi, box
from .table import _get_header_position # FIXME
#-------------------------------------------------------------------------------
class _Table:
"""
Base class for tables.
"""
@staticmethod
def _normalize... |
import numpy as np
import pyrender
import trimesh
# render with gl camera
def render_glcam(model_in, # model name or trimesh
K = None,
Rt = None,
scale=1.0,
rend_size=(512, 512),
flat_shading=False):
# Mesh creation
if is... |
# Generated by Django 2.2 on 2022-01-08 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0002_category_course_image_instructor_review_video'),
]
operations = [
migrations.AlterField(
model_name='image',
... |
# encoding: utf8
import env
from senti_analysis.train import train
from senti_analysis.models.model_v1 import get_model
if __name__ == '__main__':
model = get_model()
train(model)
|
from datetime import datetime
from typing import cast
import discord
from redbot.core import commands, i18n, checks, Config
from redbot.core.utils.common_filters import (
filter_invites,
filter_various_mentions,
escape_spoilers_and_mass_mentions,
)
from redbot.core.utils.mod import get_audit_reason
from .a... |
__all__ = ['Coffee', 'Widget', 'widgets', 'kill', 'pid', 'start', 'restart']
import os
from ubersicht._coffee import Coffee
import listify
from ubersicht._widgets import Widget
WIDGETS = "%s/Library/Application Support/Übersicht/widgets" % os.environ[
"HOME"]
def widgets():
"""return a list with widgets p... |
"""
Copyright (c) 2022 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.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... |
#!/usr/bin/python
#Makefile is driving me crazy. For now i will use python
import glob
import re
import os
from subprocess import call
sources = []
RebuildAll = True
#compiler and args to use
CXX = "g++"
CXXFLAGS = "-std=c++11 -Wc++11-extensions"
#this function will scan the filesystem and add .cpp in the specifie... |
import json
import random
import string
from SoftLayer import SoftLayerAPIError, SshKeyManager
from jumpgate.common.error_handling import bad_request, duplicate, not_found
NULL_KEY = "AAAAB3NzaC1yc2EAAAABIwAAAIEArkwv9X8eTVK4F7pMlSt45pWoiakFk" \
"ZMwG9BjydOJPGH0RFNAy1QqIWBGWv7vS5K2tr+EEO+F8WL2Y/jK4ZkUoQgoi+n7" \... |
import hashlib
from django.db import migrations
def create_hashes_from_ip_addresses(apps, schema_editor):
Commenter = apps.get_model('blog', 'Commenter')
for commenter in Commenter.objects.all():
commenter.ip_hash = (
hashlib.sha256(commenter.ip_address.encode("utf-8"))
.diges... |
""" Uncertainty Sampling
This module contains a class that implements two of the most well-known uncertainty sampling
query strategies, which are least confidence and smallest margin (margin sampling).
"""
import numpy as np
from libact.base.interfaces import QueryStrategy, ContinuousModel
class UncertaintySamplin... |
from typing import Optional, List
import copy
import random
from math import sqrt, log
import numpy as np
from environments import DiscreteEnv, MazeEnv
from agents import AbstractAgent
BIG_NUMBER = 999999999999999999999
class Node:
def __init__(self, action: Optional[int] = None, parent: Optional[object] = None... |
# Copyright 2016 Google 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 by applicable law or ag... |
class Gear(object):
def __init__(self, chainring, cog, observer, wheel=None):
self.__chainring = chainring
self.__cog = cog
self.__wheel = wheel
self.__observer = observer
@property
def chainring(self):
return self.__chainring
@property
def cog(self):
... |
#!/usr/bin/env python
import os
import sys
import subprocess
import re
PATCHESDIR = "patches"
QUILT_PC = ".pc"
def execute_command_line(arguments, cwd = None):
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd = cwd)
stdoutstring, stderrstring = process.communicate()... |
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from src.data.dataset import GPReviewDataset
def create_dataloaders(df, tokenizer, batch_size):
df_train, df_test = train_test_split(df, test_size=0.1, random_state=42)
df_val, df_test = train_test_split(df, test... |
# ----------------------------------------------
# -*- coding: utf-8 -*-
# @Time : 2020-03-08 11:30
# @Author : 吴林江
# @Email : wulinjiang1@kingsoft.com
# @File : test19.py
# ----------------------------------------------
# 单例模式的 N 种实现方法,就是程序在不同位置都可以且仅可以取到同一个实例
# 函数装饰器实现
def singleton(cls):
_instance = {}... |
import logging
from retrying import retry
from sqlalchemy import (
Column,
Integer,
String,
create_engine,
MetaData,
Table
)
from sqlalchemy.orm import mapper, scoped_session, sessionmaker
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.util import class_mapper
from atomi... |
n1 = int(input('Digite um número: '))
print('Seu número é: {}, O antecessor dele é: {}, o sucessor dele é: {}'.format(n1, n1-1,n1+1))
|
#!/usr/bin/env python3
import sys
from os import path, linesep
from glob import iglob
from configparser import ConfigParser
from datetime import datetime
def fatal(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
sys.exit(1)
def to_stringlist(arg):
if len(arg) == 0:
return []
retur... |
#! /usr/bin/env python3
"""sort a given (text) file, line by line, alphabetically
depending on the value of the second parameter, the resulting file is either saved
in the same directory as the original (with the suffix "sorted") or in the system's
temporary directory
"""
import sys
import os
TMP = '/tmp'
if sys.platf... |
"""
A component with a large number of inputs is finite differenced.
"""
import numpy as np
from openmdao.lib.optproblems.scalable import Discipline
from openmdao.main.api import Assembly, Component, set_as_top
N = 200
np.random.seed(12345)
class Model(Assembly):
def configure(self):
self.add('comp', ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 random
import yaml
from enums import ChallengeType, TeamLevel
with open("src/challenges.yml", "r") as challenge_file:
challenges = yaml.load(challenge_file, Loader=yaml.Loader)
class SkillChallenge:
"""Represents a challenge of a team"""
def __init__(self, challenge: ChallengeType):
sel... |
from pkg_resources import require
|
import math
import random
import re
import time
import aiohttp
import discord
from discord.ext import commands
import pandas as pd
pd.set_option('display.max_rows', 1000)
import datetime
from fuzzywuzzy import process
class WaitTimes(commands.Cog):
def __init__(self, client):
self._CACHE_TIME = 60 * 3 ... |
from collections import OrderedDict
# list of supported video modes and, for each, resolution, default target bitrate for recording, supported profiles and bitrate limits
VIDEO_MODES = OrderedDict ([
("4K DCI", {
"width": 4096,
"height": 2048,
"previewDownsamplingFactor": 2,
"record... |
import os
import time
from abc import ABC, abstractmethod
from pathlib import PurePosixPath
from typing import Dict, Iterable, List, NamedTuple, Optional, Union
from atlassian import Bitbucket
from gitlab import DEVELOPER_ACCESS, Gitlab, GitlabError, GitlabHttpError, \
OWNER_ACCESS, REPORTER_ACCESS
from gitlab.v4.... |
import os
from functools import partial
import numpy
import pyproj
import shapely.geometry as shp
from shapely.ops import transform
from triangle import triangulate
from vistas.core.color import RGBColor
from vistas.core.gis.elevation import ElevationService, TILE_SIZE, meters_per_px
from vistas.core.graphics.factory... |
class Tomcat(object):
def __init__(self , home , ver):
self.home = home
self.version = ver
return None
def display(self):
print(self.home)
print(self.version)
class Apache(Tomcat):
def __init__(self , home , ver):
self.home = home
self.version =... |
import pytest
from clean_architecture.rest.app import create_app
from clean_architecture.rest.settings import TestConfig
@pytest.fixture
def app():
app = create_app(TestConfig)
return app
|
from __future__ import print_function
from __future__ import division
from . import _C
import numpy as np
import matplotlib.pyplot as plt
import fuzzytools.matplotlib.plots as cplots
import fuzzytools.matplotlib.colors as cc
from fuzzytools.datascience.statistics import dropout_extreme_percentiles
import pandas as pd
... |
#------------------------------------
# Logging
#------------------------------------
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("luna")
#------------------------------------
# Generate RAW data
#------------------------------------
from luna.datatypes.dimensional import DataTi... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittest for c_format.py.
"""
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__... |
# Copyright 2018 SAS Project 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 requ... |
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import PermissionDenied
from django.utils.decorators import method_decorator
from django_filters.views import FilterView
from django_tables2.views import SingleTableMixin
from guardian.mixins import LoginRequiredMixi... |
"""
Apply automatic fixes for known errors in cmorized data
All functions in this module will work even if no fixes are available
for the given dataset. Therefore is recommended to apply them to all
variables to be sure that all known errors are
fixed.
"""
from ._fixes.fix import Fix
from .check import _get_cmor_chec... |
from django.shortcuts import render_to_response
# Create your views here.
def home(request, template_name='home.html'):
data = {
'name': '<Your Name Here>'
}
return render_to_response(template_name,
data)
|
"""Main plotting module."""
import math
import locale
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
def init_params(german_labels=True, font_size=20, font_family='Carlito',
pdf_padding=0.1, pdf_bbox='tight', pdf_fonttype=42,
... |
from sanic_testing.manager import TestManager
url = "/api/skill/all_skills"
def test_all_skills(app: TestManager):
_, response = app.test_client.get(url)
assert response.status == 200
|
from flask import request, jsonify
from api.index import home_blu
from api.index.utils.handle_json import handle_json
@home_blu.route('/home')
def home():
path = request.args.get('path')
json_dict = handle_json(path)
return jsonify(json_dict)
|
"""
In the Core module you can find all basic classes and functions which form the backbone of the toolbox.
"""
import warnings
import numbers
import numpy as np
import numpy.ma as ma
import collections
from copy import copy, deepcopy
from numbers import Number
from scipy import integrate
from scipy.linalg import blo... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from kokemomo.plugins.engine.utils.km_model_utils import *
from kokemomo.plugins.engine.model.km_storage.impl.km_rdb_adapter import adapter
__author__ = 'hiroki'
"""
It is the accessor to group table to be used in the KOKEMOMO.
[Table Layouts]
id:Integer
name:Strin... |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
import unittest
try:
import ansible_collections.amazon.aws.plugins.modules.aws_s3 as s3
except ImportError:
pytestmark = pytest.mark.skip("This test requires the s3 Python libr... |
import argparse
import sys
import enum
from . import scanners
from .environment import GITHUB_PAT
# Program exit codes
class ExitCode(enum.Enum):
OK = 0
MISSING_ARGUMENTS = 1
LANGUAGE_NOT_SUPPORTED = 2
ERROR_OPENING_DEPENDENCIES = 3
languages = {
# language:ecosystem
"python": "pip",
}
if... |
"""tsipy includes tools for signal degradation correction and fusion.
Originally, it was built for processing measurements of Total Solar Irradiance (TSI).
However, the package implements tools for degradation correction and sensor fusion
not particular of any measurement quantity.
"""
from .__version__ import version... |
"""
Contains utilities regarding messages
"""
from math import ceil
class Paginate:
'Chop a string into even chunks of max_length around the given separator'
def __init__(self, string, enclose=('```\n', '```'),
page_size=2000, separator='\n'):
self._string = string
self._prefi... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import common
from common import TestDriver
from common import IntegrationTest
from decorators import ChromeVersionEqualOrAfterM
from decorators import SkipI... |
b='Hu Xi Shu He Xun Ku Juan Xiao Xi Yan Han Zhuang Jun Di Xie Ji Wu Yan Lu Han Yan Huan Men Ju Dao Bei Fen Lin Kun Hun Tun Xi Cui Wu Hong Chao Fu Wo Jiao Cong Feng Ping Qiong Ruo Xi Qiong Xin Chao Yan Yan Yi Jue Yu Gang Ran Pi Xiong Gang Sheng Chang Shao Xiong Nian Geng Wei Chen He Kui Zhong Duan Xia Hui Feng Lian Xuan... |
import subprocess
import argparse
import logging
import shutil
import os
import re
logging.basicConfig(format='%(asctime)s %(message)s')
logging.getLogger().setLevel(logging.INFO)
REPO_URL_TEMPLATE = "https://github.com/openshift/{}.git"
valid_commit_regex = '^([A-Z]+-[0-9]+|#[0-9]+|merge|no-issue)'
################... |
def cons_count(s):
"""
>>> cons_count('hello')
3
>>> cons_count('I\\'m fine')
3
"""
pass
|
x = int(input())
arr = []
for _ in range(x):
arr.append(list(map(int, input().split())))
for i in range(1, len(arr)):
arr[i][0] = min(arr[i-1][1], arr[i-1][2]) + arr[i][0]
arr[i][1] = min(arr[i-1][0], arr[i-1][2]) + arr[i][1]
arr[i][2] = min(arr[i-1][0], arr[i-1][1]) + arr[i][2]
print(min(arr[x-1][0]... |
#!/usr/bin/env python
#
# Copyright 2015 Airbus
# Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
#
# 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
#
# ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import abc
__appname__ = ""
__author__ = "Marco Sirabella"
__copyright__ = ""
__credits__ = ["Marco Sirabella"] # Authors and bug reporters
__license__ = "GPL"
__version__ = "1.0"
__maintainers__ = "Marco Sirabella"
__email__ =... |
from typing import List
from git import CheckoutError
from too_many_repos.models.wrapped_repo import WrappedRepo
def repos_checkout_master(repos: List[WrappedRepo], force_dirty: bool = False, force_unpushed: bool = False) -> None:
for repo in repos:
if repo.is_master:
print(repo.name + ' [Su... |
#!/usr/bin/python
import subprocess
import sys
import cgi
import datetime
import re
import requests
validMac = False
ERROR = False
form = cgi.FieldStorage()
user = "READONLY_USER_HERE"
pwd = "PASSWORD"
OUI = form.getvalue('OUI')
host = form.getvalue('HOST')
def formatOUI(OUI):
ot=OUI[0:2]
... |
"""Document processor Endpoint."""
from typing import Dict, Optional
from time import time
from fastapi import APIRouter, HTTPException, Query
from lib.db import integrate_phrase_data
from phrase_counter.ingest import ingest_doc
from pydantic import BaseModel
from phrase_api.logger import LoggerSetup
from lib.statu... |
import math
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from scratch_ml.deep_learning.optimizers import Adam
from scratch_ml.deep_learning import NeuralNetwork
from scratch_ml.deep_learning.layers import Dense, Dropout, Conv2D, Flatten, Activation, BatchNormalization
from scratch_ml.... |
import enum
import typing
from dataclasses import dataclass
class MessageType(enum.Enum):
Action = 1 # data: str representing command
Message = 2 # data: each line of message in a list
UpdateCharacter = 3 # data: updated character
SyncDataResponse = 4 # data: all syncable data
SyncDataR... |
# Generated by Django 2.0 on 2017-12-23 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lecturer', '0031_auto_20171223_1537'),
]
operations = [
migrations.AddField(
model_name='unit',
name='class_day',
... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.java.package import deploy_jar # TODO: Should move to the JVM package.
from pants.backend.java.target_types import DeployJarTarget # TODO: Should move to the JVM packag... |
#!/home/ssericksen/anaconda2/bin/python2.7
# evaluate F1 and MCC metrics on new targets. Assume 10% hit fractions,
# and predict top 10% of cpds by score as the actives
import numpy as np
import pandas as pd
import informer_functions as inf
import sklearn as sk
import sys
try:
matrix = sys.argv[1] # 1 or 2
t... |
import subprocess
workingDir = 'tale-linear-optimization-part1'
subprocess.call(['pandoc','-t','revealjs','-s',
'-o','content.html','content.md','--slide-level=2',
'-V','revealjs-url=../../reveal.js','--metadata', 'pagetitle="Uzdevumi"',
'--mathjax=https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX... |
import os
import unittest
import logging
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import NodeModify, toBool, VTKObservationMixin
from Resources import QReadsResources
#
# QReads
#
class QReads(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, availab... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
from sprinter.lib.dependencytree import DependencyTree, DependencyTreeException
LEGAL_TREE = {
'a': ['b', 'c', 'd'],
'd': [],
'c': [],
'b': ['d'],
'e': []
}
MISSING_ENTRY_TREE = {
'a': ['b', 'c', 'd'],
'b': []
}
CYCLIC_TREE = {
'a': ['b', 'c', 'd'],
'b': [],
'c': ['b'],
'd... |
"""Adapted from Optimus:
https://github.com/xuqifan897/Optimus/blob/main/summa/mpu/layers.py
"""
import math
from typing import Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
from cubework.distributed import ParallelManager as pm
from cubework.distributed import broadcast
from cubework.dis... |
#MenuTitle: Report Area in Square Units
# -*- coding: utf-8 -*-
__doc__="""
Calculates the area of each selected glyph, and outputs it in square units. Increase precision by changing the value for PRECISION in line 9 (script will slow down).
"""
import GlyphsApp
PRECISION = 2 # higher numbers = more precision, but sl... |
from shared import *
from helper_functions import *
from app import app
from flask_restful import Api, Resource, reqparse, fields, marshal_with, marshal
#Wraps the flask 'app' with the Api function from flask-RESTful. Assigns this to the 'api' variable.
api = Api(app)
#---------------MAIN API------------------
#Fie... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import ValidationError, DataRequired, Length, Email
from app.models import User
class EditProfileForm(FlaskForm):
username = StringField('Usuário', validators=[DataRequired()])
email = StringFie... |
import requests
import json
import datetime
import src.heat as oh
url_base = "http://localhost"
### Keystone API
def get_token(id,passwd):
data = \
{"auth":
{
"identity":
{"password":
{"user":
{"domain":... |
from greynoise import GreyNoise
from sw_greynoise import GreynoiseBaseClass
PLUGIN_VERSION = "v1.1.0"
class SwMain(GreynoiseBaseClass):
def __init__(self, context):
super(SwMain, self).__init__(context)
self.ip_address = context.inputs["ip_address"]
self.api_key = context.asset["api_key"]... |
from .events import TLNetworkEvent
TransferEventType = "Transfer"
ApprovalEventType = "Approval"
class TokenEvent(TLNetworkEvent):
def __init__(self, web3_event, current_blocknumber, timestamp, user=None):
super().__init__(
web3_event, current_blocknumber, timestamp, from_to_types, user
... |
from seahub.tags.models import Tags
from seahub.test_utils import BaseTestCase
class TagsManagerTest(BaseTestCase):
def setUp(self):
pass
def test_create_tag(self):
assert 'a' == Tags.objects.get_or_create_tag('a').name
|
import random
first = list()
first.append(" traditional ")
first.append(" poor ")
first.append(" southern ")
first.append(" areful ")
first.append(" united ")
first.append(" different ")
first.append(" tiny ")
first.append(" former ")
first.append(" exciting ")
first.append(" important ")
first.append("... |
from python.qrcode import *
qr = QRCode()
qr.setTypeNumber(4)
qr.setErrorCorrectLevel(ErrorCorrectLevel.M)
qr.addData('ssswhere comes qr!')
qr.make()
|
from construct import Struct, Byte
from constructutils import _global_struct_io_patch
def test_main():
s = Struct('a' / Byte)
# original behavior
_global_struct_io_patch.unpatch()
try:
value = s.parse(b'\x01')
assert '_io' in value
finally:
_global_struct_io_patch.patch()... |
#Write an import statement for the Python random module
import random
class Die:
sides = 6
die = random.randint(1,sides)
def __init__(self):
'''
Define a constructor method with one attribute sides with a values of 6.
'''
self.sides = 6
def roll(self):... |
import voluptuous as vol
from esphome.components import i2c, sensor
import esphome.config_validation as cv
from esphome.const import CONF_HUMIDITY, CONF_ID, CONF_NAME, CONF_TEMPERATURE, \
CONF_UPDATE_INTERVAL
from esphome.cpp_generator import Pvariable
from esphome.cpp_helpers import setup_component
from esphome.c... |
from django.shortcuts import render, redirect
#from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import UserRegistrationForm, ProfileUpdateForm, UserUpdateForm
from django.contrib.auth.decorators import login_required
# Create your views here.
##User creation form ... |
#!/usr/bin/env python3
"""Create custom invitations from a guest list with flowery decorations."""
import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def create_card(name):
"""Creates a personalised invitation card with the provided name on it."""
card = Image.new('RGBA', (36... |
import cachetools, cachetools.func, time, threading, traceback
hashkey = cachetools.keys.hashkey
tm = time.monotonic
Lock = threading.Lock
# buffer that refreshes in the bkgnd
class StaleBuffer:
# f returns what we want to serve
def __init__(self, f, ttr=5, ttl=10): # time to refresh / time to live
s... |
#! /usr/bin/python3
#
# Copyright (c) 2018 Warren J. Jasper <wjasper@ncsu.edu>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) a... |
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project
import sys
import os
# add your p... |
# coding=utf-8
# Copyright (c) DLUP Contributors
import json
from pathlib import Path
from typing import Tuple, Union
import h5py
import torch
import torch.nn.functional as F
from pytorch_lightning import LightningModule
from dlup_lightning_mil.utils.model import get_backbone
from torch import nn
import numpy as np
im... |
#
# @lc app=leetcode.cn id=80 lang=python3
#
# [80] 删除有序数组中的重复项 II
#
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/description/
#
# algorithms
# Medium (57.54%)
# Likes: 452
# Dislikes: 0
# Total Accepted: 105.9K
# Total Submissions: 176.2K
# Testcase Example: '[1,1,1,2,2,3]'
#
# 给你一个... |
avtobots = {"Оптімус Прайм": "Грузовик Peterbilt 379",
"Бамблбі": "Chevrolet Camaro", "Джаз": "Porsche 935 Turbo"}
avtobots.update({"Сентінел Прайм": "Пожежна машина"})
print(avtobots)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 02 19:15:18 2016
@author: Florian Wolf
__________________________________________________
### MacPyver.postgres ###
### The Swissknife like Python-Package for ###
### work in general and... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 20 13:03:34 2020
@author: admin
"""
from tkinter import filedialog
from tkinter import messagebox
import os
def get_location():
loc = filedialog.askdirectory(initialdir=os.getcwd(), title='Select a save folder.')
os.chdir(loc)
return loc
def alert(msg... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
writer = tf.summary.FileWriter('./graphs',tf.get_default_graph())
with tf.Session() as ses:
result ... |
import os
def filter_str(text, in_filter, out_filter):
'''
text在out_filter,返回False
in_filter不等于None,text在里边返回True,不在里边返回False
in_filter等于None,返回True
'''
if in_filter is not None:
assert (isinstance(in_filter, list) or isinstance(in_filter, tuple))
if out_filter is not None:
... |
from collections import deque
from utils.solution_base import SolutionBase
class Solution(SolutionBase):
def solve(self, part_num: int):
self.test_runner(part_num)
func = getattr(self, f"part{part_num}")
result = func(self.data)
return result
def test_runner(self, part_num):
... |
#!/bin/python3
import os
#
# Complete the 'contacts' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_STRING_ARRAY queries as parameter.
#
def contacts(queries):
# Write your code here
from collections import Counter
counter = Counter()
for operatio... |
from typing import List, Optional
from fastapi.encoders import jsonable_encoder
from .models import Policy, PolicyCreate, PolicyUpdate
from .dsl import build_parser
def get(*, db_session, policy_id: int) -> Optional[Policy]:
"""Gets a policy by id."""
return db_session.query(Policy).filter(Policy.id == polic... |
# coding: utf-8
import pytest
mysql = pytest.importorskip("mysql.connector")
from snlocest.areadb import AreaDataManager
def pytest_funcarg__areadb(request):
return AreaDataManager('geo', 'area_feature')
#return AreaDataManager('test20160513_geo', 'test20160513_area')
# エリアDBにデータがちゃんと入っているかのテスト
def tes... |
import uuid
from collections import Counter
from functools import partial
from typing import (Callable,
Dict,
List)
import numpy as np
import pandas as pd
from sqlalchemy import func
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.session import S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.