content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# 代码仅供学习交流,不得用于商业/非法使用
# 作者: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... | python |
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__
... | python |
#!/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"))
| python |
# 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... | python |
#!/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 ... | python |
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:
... | python |
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],
... | python |
"""
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... | python |
"""
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... | python |
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))
| python |
""" 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 ... | python |
# 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... | python |
"""
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... | python |
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 = ... | python |
"""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... | python |
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... | python |
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 = ... | python |
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])
| python |
'''
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... | python |
#!/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... | python |
pytest_plugins = "beancount.ingest.regression_pytest"
| python |
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... | python |
class Space(object):
def __init__(self, col, row, terrain='.'):
self.col = col
self.row = row
self.terrain = terrain
self.occupied = False
| python |
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... | python |
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... | python |
# 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... | python |
"""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
... | python |
"""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... | python |
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... | python |
# -*- 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... | python |
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... | python |
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()
| python |
# 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'),... | python |
categories = [
{"name": "Action"},
{"name": "Drama"},
{"name": "Comedy"},
{"name": "Fantasy"},
{"name": "Sci-fi"},
] | python |
# 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
#
... | python |
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")
... | python |
# -*- 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 __... | python |
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... | python |
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... | python |
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',
... | python |
from django.apps import AppConfig
class PhoneCodeConfig(AppConfig):
name = 'phonecode'
| python |
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... | python |
from invoke import Collection
from tasks import build
ns = Collection()
ns.add_collection(build)
| python |
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... | python |
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 (... | python |
#!/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 ... | python |
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/... | python |
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... | python |
#!/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 = ... | python |
import math
print(math.pi) | python |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | python |
"""
arguments.py
Handles the arguments of training and scoring Hasse diagrams.
"""
from tempfile import TemporaryDirectory
from tap import Tap
from typing import List
from typing_extensions import Literal
import json
class CommonArgs(Tap):
"""
CommonArgs contains arguments that are used in both TrainArgs and... | python |
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2020
"""
Host Collector: Manages the periodic collection of metrics & snapshot data
"""
from time import time
from ..log import logger
from .base import BaseCollector
from ..util import DictionaryOfStan
from .helpers.runtime import RuntimeHelper
class HostC... | python |
# Tests invocation of the interpreter with various command line arguments
# All tests are executed with environment variables ignored
# See test_cmd_line_script.py for testing of script execution
import test.test_support
import sys
import unittest
from test.script_helper import (
assert_python_ok, assert_python_fa... | python |
from AutoMxL.__main__ import AML
import unittest
import pandas as pd
from AutoMxL.Preprocessing.Categorical import CategoricalEncoder
from AutoMxL.Preprocessing.Date import DateEncoder
from AutoMxL.Preprocessing.Missing_Values import NAEncoder
from AutoMxL.Select_Features.Select_Features import FeatSelector
import nump... | python |
from django import forms
from .models import GonderiModel
class GonderiForm(forms.ModelForm):
class Meta:
model = GonderiModel
fields = ("tur","baslik","yazi","olusturzaman") | python |
import unittest
from utils import VCRTestBase
import utils
from pyVim import connect
import sys
sys.path.insert(0, '../')
import inventory
class InventoryTests(VCRTestBase):
@VCRTestBase.my_vcr.use_cassette('test_inventory_run.yaml',
cassette_library_dir=utils.fixtures_path... | python |
import numpy as np
import matplotlib.pyplot as plt
import random
# Pulling data from Data sets
datafile_1 = np.genfromtxt('data_1.csv', delimiter=',')
# print(datafile_1)
datafile_2 = np.genfromtxt('data_2.csv', delimiter=',')
# print(datafile_2)
datafile_1 = datafile_1[1:]
datafile_2 = datafile_2[1:]
# Least square... | python |
#!/usr/bin/env python3
import inspect
import sys
from xml.etree import ElementTree
def match(text, *queries):
doc = ElementTree.parse(text)
return [doc.findtext(query) for query in queries]
def _main(argv=None):
"""
Usage: python3 -m pup.xpath QUERY [QUERY...]
Where
- Each QUERY is a val... | python |
import pytest
from pybuildkite.agents import Agents
def test_get_agent(fake_client):
"""
Test the get_agent method
"""
agents = Agents(fake_client, "base")
agents.get_agent("org_slug", "agent_id")
fake_client.get.assert_called_with(agents.path.format("org_slug") + "agent_id")
def test_stop_... | python |
# Copyright (c) 2015 Microsoft Corporation
"""
>>> from z3 import *
>>> v = BitVecVal(0xbadc0de, 32)
>>> v.sexpr()
'#x0badc0de'
>>> v
195936478
>>> v.as_long() == 195936478
True
"""
if __name__ == "__main__":
import doctest
if doctest.testmod().failed:
exit(1)
| python |
def main():
print("Not implemented yet.")
| python |
import tensorflow_datasets as tfds
import config
def load_dataset():
imdb, info = tfds.load('imdb_reviews',
data_dir=config.DATA_PATH,
with_info=True,
as_supervised=True)
return imdb, info
if __name__ == '__main__':
load_da... | python |
'''
作者:邱少一
日期:2018/03/06
1、准备:
python版本:python3 --version
选择Web异步的框架aiohttp:pip3 install aiohttp(比较底层,需要再次封装)
前端模板引擎jinja2:pip3 install jinja2
MySQL的Python异步驱动程序aiomysql:pip3 install aiomysql
监控目录文件变化:pip3 install watchdog
2、流程:
1、编写web 骨架
2、编写ORM 和 Model
3、编写 web框架(基于aiohttp)
4、编写配置文件
5、编写MVC
6、构建前端
... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import codecs
import unittest
from StringIO import StringIO
# We include <pkg_root>/src, <pkg_root>/lib/python
extend_path = lambda root_path, folder: sys.path.insert(
0, os.path.join(root_path, folder))
ROOT = os.path.dirname(os.pat... | python |
# """
# Modul containing import methods from different packages / repositories.
# """
#
# import copy
# import json
# import os.path
# import tempfile
# from multiprocessing import Process
#
# import arff
# import networkx as nx
# import numpy as np
# import openml as oml
# import pandas as pd
# import pypadre.pod.back... | python |
# This code is part of the epytope distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""
.. module:: EpitopePrediction.ANN
:synopsis: This module contains all classes for ANN-based epitope prediction methods.
.. moduleauthor:: schubert,... | python |
from django.conf import settings
def init_permission(request, obj):
# 保存登录状态
request.session['is_login'] = True
# 查询出当前用户的权限
# 去除权限为空的权限
ret = obj.roles.filter(permissions__url__isnull=False).values(
'permissions__id',
'permissions__url',
'permissions__title',
'perm... | python |
import sys
import yaml
import logging
import typing
from typing import Dict
import clingo
from PyQt5.QtSvg import QSvgRenderer
from . import actions
from .visualizeritem import *
from .visualizerabstract import VisualizerDemand, VisualizerGoods
from .spritecontainer import SpriteContainer
from .model import *
def p... | python |
def check_close(input_string):
OPENS = ('(', '<', '[', '{')
CLOSES = (')', '>', ']', '}')
PAREN = ('(', ')')
ANGLE = ('<', '>')
SQUARE = ('[', ']')
CURLY = ('{', '}')
mem = []
for character in input_string:
try:
if character in OPENS:
mem.append(c... | python |
"""Password Policy tests"""
from django.test import TestCase
from guardian.shortcuts import get_anonymous_user
from authentik.lib.generators import generate_key
from authentik.policies.password.models import PasswordPolicy
from authentik.policies.types import PolicyRequest, PolicyResult
class TestPasswordPolicy(Test... | python |
from .unet import *
from .metric import * | python |
# Simple and compound interest
P = float(input("Enter principal: "))
R = float(input("Enter annual RoI (%): ")) / 100
T = float(input("Enter time (years): "))
C = int(input("Compounds per annum: "))
# Calculate simple interest
SI = P*R*T
# Calculate compound interest
R = R/C
T = int(T*C)
CI = (P*(1+R)**T) - P
# ... | python |
import torch
import torch.distributions
import numpy as np
import matplotlib.pyplot as plt
from pkg_resources import resource_filename
import activelo
def generated_example():
N = 20
truth = torch.randn(N)
n = torch.randint(1, 50, (N, N))
d = truth[:, None] - truth[None, :]
w = torch.distributions... | python |
def binary_search(l, value, low = 0, high = -1):
if not l: return -1
if(high == -1): high = len(l)-1
if low == high:
if l[low] == value: return low
else: return -1
mid = (low+high)//2
if l[mid] > value: return binary_search(l, value, low, mid-1)
elif l[mid] < value: return binary... | python |
# from file_path import ClassName
# class Car:
# wheels = 4
#
# def __init__(self, make, model, year, color):
# self.make = make
# self.model = model
# self.year = year
# self.color = color
#
# def drive(self):
# return f"The {self.model} is driving"
#
# def stop... | python |
from graphql_relay.node.node import from_global_id
from django_filters import FilterSet, CharFilter
from django_filters.filters import ModelMultipleChoiceFilter, ModelMultipleChoiceField
class BaseFilterSet(FilterSet):
"""
Base filter set for Movie and Person
"""
search = CharFilter(method='filter_by_... | python |
#!/usr/bin/env python
# author: d.koch
# coding: utf-8
# naming: pep-0008
# typing: pep-0484
# docstring: pep-0257
# indentation: tabulation
""" canp_view_enaml.py
Enaml view
"""
# --- IMPORT ---
# Standard libraries (installed with python)
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__f... | python |
# -*- coding: utf-8 -*-
# File: base.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
from abc import ABCMeta, abstractmethod
import signal
import re
from six.moves import range
import tqdm
import tensorflow as tf
from tensorpack.utils.utils import get_tqdm_kwargs
from .config import TrainConfig
from ..utils import *
fro... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Description: Implementation of the Louvain algorithm using igraph framework with input/
output formats adapted to the NMIs evaluation.
:Authors: Artem Lutov <luart@ya.ru>
:Organizations: eXascale lab <http://exascale.info/>, ScienceWise <http://sciencewise.info/>,
Lu... | python |
#!/usr/bin/env python3
# Custom imports
from .help import showHelp
from .cfg import (
MIN_WIDTH, MIN_HEIGHT,
MIN_BIG_WIDTH, MIN_BIG_HEIGHT,
CONF_FILEPATH,
MAX_COLORS,
startTime, stopSeconds,
arrNumBig, arrNumSmall,
helpMenu
)
from .utils import get_terminal_size
# External imports
import sys
import os
import c... | python |
'''
@author: Aeolus
@url: x-fei.me
@time: 2019-04-08 21:26
'''
from os.path import join, dirname, abspath
from src import tool
# Basic project info
AUTHOR = "Felix"
PROGRAM = "Robust"
DESCRIPTION = "Defense against adversarial attacks. " \
"If you find any bug, please new issue. "
# Main CMDs. This deci... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Helio de Jesus and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, msgprint, throw
from frappe.model.document import Document
from frappe.model.naming import make_autoname
from datet... | python |
from Source import ModelsIO as MIO
import numpy as np
from h5py import File
def E_fit(_cube: np.ndarray((10, 13, 21, 128, 128), '>f4'),
data: np.ndarray((128, 128), '>f4'),
seg: np.ndarray((128, 128), '>f4'),
noise: np.ndarray((128, 128), '>f4')) -> np.ndarray((10, 13, 21), '>f4'):
... | python |
from kivymd.uix.carousel import MDCarousel
class StaticCarousel(MDCarousel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_touch_down(self, touch):
return False
| python |
"""
Create a single inheritance class and use one method from a parent class.
"""
class Animal:
def __init__(self, breed):
self.breed = breed
self.living = True
def is_alive(self):
if self.living:
return f'{self.breed} is alive.'
return f'{self.breed} ... | python |
import torch
from torch import nn
from src.config import data
from src.utils import init_weights
class ClassifierModel(nn.Module):
def __init__(self):
super().__init__()
self.process = nn.Sequential(
nn.Linear(data.x_size, 64, bias=False),
nn.BatchNorm1d(64),
... | python |
import numbers
from bisect import bisect_right
from .. utils.cache import Cache
class NodeRefGroup:
"""
NodeRefGroup class
Members
-------
_ref_lists: dict
dictionary with keys as optimisation key and value as references to nodes sorted by that optimisation key
_temp_list: list
... | python |
# Building a List
# Generate all possible combinations of a string
#
# https://www.hackerrank.com/challenges/building-a-list/problem
#
import itertools
def combo(s):
n = len(s)
def lex():
for i in range(1, 2 ** n):
j = i
w = ''
k = 0
while j != 0:
... | python |
from utils import timer_decorator
@timer_decorator
def fact_1(n: int) -> int:
product = 1
for i in range(n):
product = product * (i+1)
return product
@timer_decorator
def fact_2(n: int) -> int:
if n == 0:
return 1
return n * fact_2(n-1)
| python |
from phreedf import *
name = 'phreedf'
| python |
import os
from fnmatch import fnmatch
import pandas as pd
class ReadFile:
def __init__(self, corpus_path, iters_bulk_size=1000000):
self.corpus_path = corpus_path
list_of_files_to_read = self.find_data_paths_in_corpus()
self.data_paths = [file_path for file_path in list_of_files... | python |
import os.path
import json
from prjxray import grid
from prjxray import tile
from prjxray import tile_segbits
from prjxray import site_type
from prjxray import connections
def get_available_databases(prjxray_root):
""" Return set of available directory to databases given the root directory
of prjxray-db
"... | python |
"""Wordlists loaded from package data.
We can treat them as part of the code for the imperative mood check, and
therefore we load them at import time, rather than on-demand.
"""
import re
import pkgutil
import snowballstemmer
from typing import Iterator, Dict, Set
#: Regular expression for stripping com... | python |
# Copyright 2013-2018 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 RBase64(RPackage):
"""Compatibility wrapper to replace the orphaned package by Romain
... | python |
from emanager.hr.worker import *
import emanager.utils.file_ops as fop
# fop.init_attendance_sheet(HR_DATA_DIR, ["WO2106242355"])
# test worker.py
worker_name = "Worker 1"
id_ = check_stakeholder_existance(WORKER_DATA_FILE, worker_name)
if id_ is None:
address = "address2"
age = 46
mobile_no = "79087953... | python |
# 使用__slots__限制类可定义的属性
class Student(object):
__slots__ = ("name","age")
#测试绑定其它属性
s = Student()
s.score = 90
| python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Bruce_H_Cottman"
__license__ = "MIT License"
import pandas as pd
from pydataset import data
from flask import Flask, request, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.debug = True
Bootstrap(app)
@app.route('/show', ... | python |
class MegaCoolNumbersEasy:
def count(self, N):
def is_mega(s):
return len(set(ord(s[i]) - ord(s[i - 1]) for i in range(1, len(s)))) < 2
return sum([is_mega(str(e)) for e in xrange(1, N + 1)])
| python |
#joel Lee
#3/21/2021
#creates a due date for a task
from driver import driver, Keys
import time
#connects to website
driver.get("http://localhost:8080")
#finds the create task button
findtask_button = driver.find_element_by_xpath('//*[@id="tasklist"]/div[1]/h2/span[1]/button').click()
time.sleep(2)
#finds the tas... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.