text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
# Copyright (c) 2005-2010 ActiveState Software Inc.
# Copyright (c) 2013 Eddy Petrișor
"""Utilities for determining application-specific dirs.
See <https://github.com/ActiveState/appdirs> for details and usage.
"""
# Dev Notes:
# - MSDN on where to store app data files:
# http://support.micr... |
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView, LogoutView
class UserLoginView(LoginView):
redirect_authenticated_user = True
template_name = 'accounts/login.html'
def get_success_url(self):
return reverse_lazy('root')
class UserLogoutView(LogoutView):
t... |
import requests
import json
# import related models here
from requests.auth import HTTPBasicAuth
# Create a `get_request` to make HTTP GET requests
# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
# auth=HTTPBasicAuth('apikey', api_k... |
"""hug/redirect.py
Implements convenience redirect methods that raise a redirection exception when called
Copyright (C) 2016 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Softwa... |
"""Naive maze runner controller."""
from controller import Robot
# Get reference to the robot.
robot = Robot()
# Get simulation step length.
timeStep = int(robot.getBasicTimeStep())
# Constants of the Thymio II motors and distance sensors.
maxMotorVelocity = 6
# Get left and right wheel motors.
leftMotor = robot.g... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import decimal
import uuid
import base64
import requests
import json
from datetime import datetime
from flask import request, current_app, Response
from flask_restplus import Resource, reqparse
from werkzeug.datastructures import FileStorage
from werkzeug import exceptions
from sqlalchemy.exc import DBAPIError
from .... |
# Copyright (c) 2020 ING Bank N.V.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distr... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module is to contain an improved bounding box
"""
import abc
import copy
import warnings
from collections import namedtuple
from typing import Any, Callable, Dict, List, Tuple
import numpy as np
from astropy.units import Quantity
from astropy... |
# Copyright 2016 Google 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 agreed to in writing, ... |
import sys
import pytest
from saltfactories.exceptions import FactoryTimeout
from saltfactories.factories.base import ProcessFactory
@pytest.mark.parametrize("exitcode", [0, 1, 3, 9, 40, 120])
def test_exitcode(exitcode, tempfiles):
shell = ProcessFactory(cli_script_name=sys.executable)
script = tempfiles.m... |
import torch
from torch import jit
class ComputeReturns(jit.ScriptModule):
__constants__ = ['gamma', 'T', 'B']
def __init__(self, target_actor_net, target_critic_net,
num_processes, reward_steps, batch_size, device,
gamma=0.99):
super(ComputeReturns, self).__init__(... |
import re
from bs4 import BeautifulSoup
import string
def clean_filing(text, remove_xbrl=True, to_lower=True, remove_punctuation=True):
if remove_xbrl:
xml_start = max(text.find('<XBRL>'), text.find('<xbrl>'))
text = text[:xml_start]
text = BeautifulSoup(text, "lxml").text.encode('ascii', ... |
# =================================================================
#
# Authors: Seth Girvin
#
# Copyright (c) 2021 Seth Girvin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# res... |
def Get_Items(filename):
"""Convert plain text to class string"""
L = []
with open(filename, 'r') as file:
items = file.readlines()
for line in items:
L.append(line[:-1])
return L
#--- vestigial code
def repeat(txt):
""""""
data = []
for i in txt:
... |
# Copyright 2019 Google LLC
#
# 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 writing, ... |
"""Test fire front interpolation"""
# Copyright (c) 2019, CNRS-LAAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... |
# Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis sobre ele
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
s = n1+n2
print (' A soma de {} e {}, vale: {}'.format(n1,n2,s)) |
# Copyright 2015 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 a... |
"""
MCView
------
Compute metacell analysis in preparation for exporting the data to MCView.
"""
from typing import Any
from typing import Dict
from typing import Optional
from typing import Union
import numpy as np
from anndata import AnnData # type: ignore
import metacells.parameters as pr
import metacells.tools... |
from .Circle import Circle
from .GraphicShape import GraphicShape
from .Rectangle import Rectangle
from .View import View
from .Line import Line
|
import ChromaPy32 as Chroma # Import the Chroma Module
from time import sleep # Import the sleep-function
Mousepad = Chroma.Mousepad()
Mousepad.setWave(1) # sets the Keypad to Wave from left to right
sleep(10)
Mousepad.setWave(2) # sets the Keypad to Wave from right to left
sleep(10)
|
import math
from typing import Tuple, List, Dict, Any
import bnn
import numpy as np
import torch
from bnn import BDropout, CDropout
from torch import Tensor
from torch.nn import Module, functional as F
from .ssm_cem import CemSSM
from ..ssm_pytorch import utilities
from ..utils import get_device, assert_shape
class... |
from __future__ import division
from libtbx.math_utils import ifloor, iceil
from libtbx import adopt_init_args
import os
MAP_TYPE_F_OBS = 1
MAP_TYPE_DIFF = 2
MAP_TYPE_ANOMALOUS = 4
MAP_TYPE_ISO_DIFF = 8
MAP_TYPE_NEUTRON = 16
MAP_TYPE_F_CALC = 32
MAP_TYPE_FILLED = 64
standard_map_names = {
'2FOFCWT' : '2mFo-DFc',
... |
# This file is part of the pyMOR project (https://www.pymor.org).
# Copyright 2013-2021 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
import scipy.linalg as spla
import numpy as np
from pymor.algorithms.genericsolvers import _par... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from load_data import train_iter, val_iter, id2vocab, PAD_IDX
from model import Encoder, Decoder, Seq2Seq
device = "cuda" if torch.cuda.is_available() else 'cp... |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""
Forcefield tests for the mmic_parmed package.
"""
# Import package, test suite, and other packages as needed
import mmic_parmed
import pytest
import sys
import os
import parmed
import mmelemental as mm
import mm_data
from pathlib import Path
top_files = lambda ext: [
mm_data.ffs[f"1dzl_gro.{e... |
#!/usr/bin/env python3
import simplejson as json
import spacy
from copy import deepcopy
# Init
nlp = spacy.load("en_core_web_md")
in_file = 'dict.json'
print("READ : Reading json file : " + in_file)
with open(in_file, 'r', encoding='utf-8') as f:
data_text = f.read()
print("READ : Parsing json file")
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-04-29 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finncon2018', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='signupextra',
... |
# encoding: utf-8
"""
在已有的md文件上生成目录,方便阅读跳转
"""
import os, sys, re
# 标题模式
title_pattern = re.compile(r'^(#+)\s+(.*)')
def generateList(filePath):
if not os.path.exists(filePath):
print 'file not exists: {}'.format(filePath)
sys.exit(1)
if os.path.isfile(filePath) and filePath.endswith('.md'... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/lair/structure/exterior/shared_lair_cave_giant_exterior_graul.iff"
... |
import gdspy
import numpy
import colorsys
from PIL import Image, ImageDraw, ImageFont
class ColorDict(dict):
def __missing__(self, key):
layer, datatype = key
rgb = tuple(int(255 * c + 0.5) for c in colorsys.hsv_to_rgb((layer % 3) / 3.0 + (layer % 6 // 3) / 6.0 + (layer // 6) / 11.0, 1 - ( (layer ... |
from tkinter import *
import AST
from reporteAST import *
from temporal import *
ventana = Tk()
ventana.title("COMPI2")
#ventana.geometry("600x500") #ancho y alto de ventana
def enviarTexto():
input=cuadroTxt.get(1.0,"end-1c")
#print(input)
output=AST.Analisar(input)
cuadroTxtSalida.delete(1.0,"end-... |
# coding=utf-8
# Marcelo Ambrosio de Goes
# marcelogoes@gmail.com
# 2022-04-24
# 100 Days of Code: The Complete Python Pro Bootcamp for 2022
# Day 73 - Aggregate Merge LEGO Dataset
import pandas
import matplotlib.pyplot as plt
# Import data
colors_df = pandas.read_csv("data/colors.csv")
sets_df = pandas.read_csv("da... |
# -*- coding: iso-8859-1 -*-
### EVLA DATA REDUCTION
### Project: 13A-341
### Dataset date: 10mar13 (first observation)
### Original dataset name: 13A-341.sb19189214.eb19331287.56361.737114351854
### Renamed as: cig96_03.ms
###
### Configuration: D (3/3)
# ==============================================================... |
# vim: set ff=unix expandtab ts=4 sw=4:
from .TimeBin import TimeBin
class TsTpBin(TimeBin):
def plot(self, ax):
super().plot(ax)
ax.set_xlabel("system age")
ax.set_ylabel("pool age")
|
from typing import Optional, Iterable, List, Union, Tuple
import numpy as np
from overrides import overrides
from checklist.test_suite import TestSuite
from checklist.test_types import MFT, INV, DIR, Expect
from checklist.editor import Editor
from checklist.perturb import Perturb
from allennlp.sanity_checks.task_checkl... |
#-----------------------------------------------------------------------------
# Title : PyRogue Common Application Core Level
#-----------------------------------------------------------------------------
# File : AppCore.py
# Created : 2019-10-08
#--------------------------------------------------------... |
# Generated by Django 3.1.2 on 2021-03-03 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipients', '0054_groceryrequest_senior'),
]
operations = [
migrations.AddField(
model_name='mealrequest',
name='se... |
import numpy as np
import time
from sklearn.utils import check_random_state
from scipy.special import expit
def sigmoid_prime(z):
p = expit(z)
return p*(1 - p)
sigmoid = expit
random_state = check_random_state(None)
class RecurrentNetwork:
def __init__(self, n_hidden_neurons, learning_rate=1.0, n_epoch... |
import camelot
def extract_df(filename,page_number):
tables = camelot.read_pdf(filename,pages=page_number)
df = tables[0].df
print('Table successfully extracted')
return df
|
import torch
import torch.nn as nn
import torchvision.models as models
from typing import *
import copy
import PIL
from PIL import Image
import numpy as np
from pathlib import Path
from .datamodule import transform_fn
from . import utils
import onnx
import onnxruntime as ort
import numpy as np
class MobileNetClassify... |
import numpy as np
import random
import cv2
from typing import List
from ....datasets import BaseTransform
from ....builder import TRANSFORMS
@TRANSFORMS.register_module()
class GroupRectRotate(BaseTransform):
def get_transform_param(self, data, *args, **kwargs) -> dict:
flag = random.randint(0, 3)
... |
#!/usr/bin/env python3
import os
import subprocess
import sys
def y_n(q):
while True:
ri = input('{} (y/n): '.format(q))
if ri.lower() in ['yes', 'y']: return True
elif ri.lower() in ['no', 'n']: return False
def update_deps():
print("Attempting to update dependencies..."... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.regularizers import l2
import time
from absl import app, flags, logging
def create_model(size, yolo_anchors, yolo_anchor_masks, classes, training=False):
inputs = tf.keras.Input(shape=(siz... |
import torch
import numpy as np
def get_ntk_n(xloader, networks, recalbn=0, train_mode=False, num_batch=-1):
device = torch.cuda.current_device()
# if recalbn > 0:
# network = recal_bn(network, xloader, recalbn, device)
# if network_2 is not None:
# network_2 = recal_bn(network_2, ... |
# Generated by Django 2.2.2 on 2019-06-21 08:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('openbook_common', '0012_auto_20190202_1320'),
migrations.swappable_dependency(setti... |
#!/usr/bin/python3.9
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import sys
from collections import OrderedDict
from wwr_ui.randomizer_window import WWRandomizerWindow
def signal_handler(sig, frame):
print("Interrupt")
sys.exit(0)
# Allow keyboard interrupts on the ... |
import os
from shutil import copyfile
LIBRARY_PATH = '/usr/local/lib/'
PREFIX = '/usr/local/include/jupyter'
INCLUDE_OPENCV_FILE_NAME = 'jupyter_opencv_include.h'
INCLUDE_PATH = """
#pragma cling add_library_path("/usr/local/lib")
#pragma cling add_include_path("/usr/local/include/opencv4/")
#pragma cling add_inclu... |
"""
Support for Tornado Authentication.
"""
import hashlib
from sqlalchemy.sql import select, insert, update, and_
from .connection import ConnectionMgr
from .user import user
def login(email: str, password: str):
""" hash the password and see if you can find the user """
hex_key = hashlib.md5(password.en... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-27 14:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_remove_current_snapshot'),
]
operations = [
migrations.AddFie... |
"""file_repo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
# Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
import os
import time
import telebot
from flask import Flask, request
from constants import *
bot = telebot.TeleBot(token)
server = Flask(__name__)
Main_mark_up = telebot.types.ReplyKeyboardMarkup(True, False)
Main_mark_up.row('Список задач', 'Поиск')
Main_mark_up.row('Получить задачу по сложности', 'Книги')
Main_ma... |
'''This module defines hint objects that can be added to a field to assist with displaying a
human-readable field value for a id-type field.'''
# Copyright 2019, James Humphry
# This work is released under the ISC license - see LICENSE for details
# SPDX-License-Identifier: ISC
from . import dialects
class HV():
... |
from django.shortcuts import render
from django.views.generic import TemplateView, ListView
from django.contrib.auth.mixins import UserPassesTestMixin
from forum.models import Question
from website.mixin import FrontMixin
from django.core.urlresolvers import reverse_lazy
class HomepageView(FrontMixin, ListView):
... |
# -*- coding: utf-8 -*-
import logging
import pandas as pd
from pathlib import Path
from sklearn.preprocessing import MinMaxScaler
logger = logging.getLogger(__name__)
def main(data, output_filepath, output_filepath2):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data rea... |
# -*- coding: utf-8 -*-
from plugin.settings import ICON_PATH
RESULT_TEMPLATE = {
'Title': '',
'SubTitle': '',
'IcoPath': ICON_PATH,
}
ACTION_TEMPLATE = {
'JsonRPCAction': {
'method': '',
'parameters': '',
}
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import io
import os
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.images import ImageFile
from sampledata.helper import SampleData
from sampledata.exceptions import NotChoicesFound, ParameterError
fr... |
import csv
import logging
import math
import time
import torch
import torch.nn.functional as F
import xlsxwriter
from colour import Color
from torch.nn.modules.loss import _Loss
from torch.optim import Adam
from torchtext.data import Iterator, BucketIterator
from tqdm import tqdm
from task_A.datasets.RumourEvalDatase... |
from django.conf.urls import url
from core.loading import APIViewLoader
from .views_api_json import CommentListJSON, CommentDetailJSON
from .views_api_xml import CommentListXML, CommentDetailXML
data_format = '(?P<format>\.\w{1,4})'
urlpatterns = [
# List of Comments
url(
r'^' + data_format + '$',
... |
#
# @lc app=leetcode id=300 lang=python3
#
# [300] Longest Increasing Subsequence
#
from typing import List
# @lc code=start
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = dict()
res = min(1, len(nums))
for i in range(len(nums)):
dp[i] = 1
for j... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
import os
import pickle
import argparse
import numpy as np
import pandas as pd
from torchvision import transforms
from PIL import ImageFilter, Image
def load_bbox(data_dir):
bbox_path = os.path.join(data_dir, 'CUB_200_2011/bounding_boxes.txt')
df_bounding_boxes = pd.read_csv(bbox_path,... |
import time
from hypernets.dispatchers.predict.grpc.proto import predict_pb2_grpc
from hypernets.dispatchers.predict.grpc.proto.predict_pb2 import PredictResponse
from hypernets.dispatchers.process import LocalProcess
from hypernets.utils import logging
logger = logging.get_logger(__name__)
class PredictService(pre... |
import collections.abc
import logging
import os
import re
import sys
from collections import OrderedDict
from functools import reduce
from pathlib import Path
from time import sleep
import requests
import yaml
from botocore.exceptions import ClientError
from dulwich.config import ConfigFile, parse_submodules
from tas... |
import os
import random
import fakeredis
import pytest
from sqlalchemy import create_engine, inspect
from sqlalchemy.dialects.postgresql.base import PGInspector
from sqlalchemy.orm import sessionmaker
from testing import postgresql
from backend.database.objects import Player
from tests.utils.database_utils import cre... |
#!/home/yogesh/Desktop/scout_n_sellar/saleor/myvenv/bin/python3
# $Id: rst2xetex.py 7847 2015-03-17 17:30:47Z milde $
# Author: Guenter Milde
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing Lua/XeLaTeX code.
"""
try:
import locale
lo... |
import json
import matplotlib as mpl
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
with open('./data.json') as f:
data = json.load(f)
mpl.style.use("seaborn")
lines = [
[[],[]],
[[],[]],
[[],[]],
[[],[]],
... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['ThunderThings.py']
DATA_FILES = []
OPTIONS = {
'iconfile':'tt.icns',
'plist': {
'LSEnvironment' : {'APPLAUNCHED':'Y'}
}
}
setup(
app=APP,
data_files=DATA_FI... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
"""Access to realtime market information."""
from dataclasses import dataclass, field
from datetime import datetime
from typing import ClassVar, List, Optional, Union
from eventkit import Event, Op
from ib_insync.contract import Contract
from ib_insync.objects import (
BarList, DOMLevel, Dividends, FundamentalRa... |
############################
# written by Trang H. Tran and Lam M. Nguyen
############################
"""
Average data and plot
"""
import pandas as pd
from csv import reader
import numpy as np
import matplotlib.pyplot as plt
#-------------------------------------------------------------------------------
# Functio... |
import os
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from spacy.tokens import Doc, Span
def _filter_doc_by_page(doc: Doc, page_number: str) -> Span:
"""Filter the doc by page number.
Args:
doc: The doc to filter.
... |
# -*- coding: utf-8 -*-
# @Author: xiaodong
# @Date : 2021/5/27
from elasticsearch import Elasticsearch
from .question import ElasticSearchQuestion
from ...setting import ELASTICSEARCH_HOST
ElasticSearchQuestion.es = Elasticsearch(ELASTICSEARCH_HOST)
esq = ElasticSearchQuestion("mm_question")
|
import fnmatch
import sys
import traceback
from typing import Iterable, Tuple, List
from packaging.version import Version, parse, LegacyVersion
class PyVer(Version):
def nix(self):
res = 'python'
res += str(self.release[0])
if len(self.release) >= 2:
res += str(self.release[1]... |
from django.conf.urls import url, include
from django.urls import reverse
from .base import ViewConfig
from pinax.waitinglist.forms import WaitingListEntryForm
context = dict(
form=WaitingListEntryForm()
)
patch = "http://pinaxproject.com/pinax-design/patches/pinax-waitinglist.svg"
label = "waitinglist"
title ... |
import os
import matplotlib.pyplot as plt
def save_generations(
args,
edges: list,
reals: list,
fakes: list,
paths: list,
epoch: str
) -> None:
if args.results_dir not in os.listdir(args.root_dir, ):
os.mkdir(os.path.join(args.root_dir, args.results_dir))
for edge, real, fa... |
import os
from ..modules import ImageCapture
from .observable import observable
class CaptureImagePipe:
def __init__(self, *args, **kwargs):
self.image_capture = ImageCapture(*args, **kwargs)
self.stop = False
observable.register("stop", self, self.on_stop)
def __iter__(self):
... |
"""Generic Z-Wave Entity Class."""
from __future__ import annotations
from zwave_js_server.const import NodeStatus
from zwave_js_server.model.driver import Driver
from zwave_js_server.model.value import Value as ZwaveValue, get_value_id
from homeassistant.config_entries import ConfigEntry
from homeassistant.core impo... |
from typing import Dict, List, Optional
from blspy import AugSchemeMPL, G2Element, PrivateKey
from chia.consensus.constants import ConsensusConstants
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.blockchain_format.sized_bytes import bytes32... |
"""Models for use in `bscan` operations."""
from collections import namedtuple
from typing import List
from bscan.io_files import file_exists
from bscan.runtime import get_db_value
from bscan.dir_structure import get_scan_file
ParsedService = namedtuple(
'ParsedService',
['name', 'port'])
"""A class represen... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
im... |
from __future__ import division
from six.moves import range
import math
from scitbx import matrix
from cctbx import miller
from dials.array_family import flex
from scitbx.math.tests.tst_weighted_correlation import simple_weighted_correlation
from libtbx import adopt_init_args, group_args
class legacy_cxi_merge_postref... |
# USAGE
# python objectness_saliency.py --model objectness_trained_model --image images/barcelona.jpg
# import the necessary packages
import numpy as np
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True,
he... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class AddPublicipsIntoSharedBandwidthResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Generated by Django 3.2.6 on 2021-08-17 09:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio_app', '0002_auto_20210816_2217'),
]
operations = [
migrations.RemoveField(
model_name='projects',
name='sk... |
# This will be in torchvision's next version, but it's not conveniently accessible yet, hence just dropping it here.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils import model_zoo
__all__ = ['GoogLeNet', 'googlenet']
model_urls = {
# GoogLeNet ported from TensorFlow
'goo... |
# parameters.py
"""
Exp 455 - {'Initial_genes': '500', 'Host_mutation_rate': '0.03', 'TE_progeny': '0.00, 0, 0.55, 1, 0.30, 2, 0.15, 3', 'TE_Insertion_Distribution': 'Triangle( pmax=0, pzero=3.0/3.0 )', 'Carrying_capacity': '300', 'TE_excision_rate': '0.5', 'Junk_BP': '1.4', 'Gene_Insertion_Distribution': 'Triangle( p... |
__VERSION__ = "2.1.9"
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("sites", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Redirect",
fields=[
(
"id",
models.Au... |
# -*- coding:utf-8 -*-
from __future__ import print_function
import scipy
import numpy as np
import os
import sys
import time
import random
import math
import cv2
from tqdm import tqdm
from deeploader.dataset.dataset_base import ArrayDataset
def allowed_file(filename, exts=None):
ALLOWED_EXTENSI... |
from __future__ import unicode_literals
from django.conf.urls import url
from django.contrib import admin
import tagulous.views
from example import models, views
urlpatterns = [
url(r"^admin/", admin.site.urls),
url(
r"^api/skills/$",
tagulous.views.autocomplete,
{"tag_model": models... |
"""Functional tests for WSGI app for Protocol RPC service API."""
import unittest
from webtest import TestApp
import app_engine_test_utils
from gae.room import cru_api
from test import test_models
app = TestApp(cru_api.application)
# Configuration for basic CRUD tests.
# List of pairs: (model name, fields dict)
# ... |
import os
import smtplib
smtpserver = smtplib.SMTP("smtp.gmail.com:587")
smtpserver.ehlo()
smtpserver.starttls()
red='\033[31m'
green='\033[32m'
orange='\033[33m'
pink='\033[95m'
print(f"{green}=============================")
print(f"{green} made by bad_boy ")
print(f"{green} my telegram id:@Bad_boy_468 ")
... |
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import asyncio
import random
from greenletio import async_, await_
@async_
def sleep(delay):
await_(asyncio.sleep(delay))
async def main():
for i in range(10):
await sleep(random.random())
print(i)
asyncio.run(main())
|
try:
from urlparse import urlparse, urlunparse
except ImportError:
from urllib.parse import urlparse, urlunparse
from tornado.httputil import _normalized_headers
class MockRequest(object):
def __init__(self, request):
self._request = request
def get_full_url(self):
if not self._requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.