content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""Functionality to enhance parallelism.
This module can import things from threading_utils,
multiprocessing_utils, and queue_utils.
"""
from __future__ import annotations
import multiprocessing
import multiprocessing.queues
from queue import Queue
from time import perf_counter
from time impor... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\role\role_state.py
# Compiled at: 2020-10-01 01:34:40
# Size of source mod 2**32: 23843 bytes
from a... |
GnomeXzPackage ('cogl', '1.10', '2')
|
"""
Usage:
pgdatadiff --firstdb=<firstconnectionstring> --seconddb=<secondconnectionstring> [--only-data|--only-sequences] [--count-only] [--chunk-size=<size>] [--full-data]
pgdatadiff --version
Options:
-h --help Show this screen.
--version Show version.
--firstdb=postgres://postgres... |
# %%
import torch
import torch.nn as nn
import torch.nn.functional as F
def logits(input):
'''
(N, C, d1, d2, ..., dn)
'''
return torch.softmax(input, dim=1) if input.size(1) > 1 else torch.sigmoid(input)
def flatten_and_tranpose_C(input, target):
'''
(N, C, d1, d2, ..., dn) => (N*d1*d2*... |
import pytest
import subprocess
import tempfile
import os
from pathlib import Path
import sgap.system
import sgap.git
def test_system():
assert sgap.system.run("echo", "hi") == "hi"
assert sgap.system.run("cat", stdin="hi") == "hi"
with pytest.raises(subprocess.CalledProcessError):
sgap.system.ru... |
import re
class Lexer(object):
def __init__(self, source_code):
self.source_code = source_code
def tokenize(self):
source_text = self.source_code.split()
source_index = 0
tokens = []
for text in source_text:
if text == "tree":
tokens.append([... |
import itertools
def f(x):
return x * x
k, m = map(int, input().split())
K = []
for i in range(k):
K.append(list(map(int, input().split()))[1:])
paramList = list(itertools.product(*K))
Smax = -1
for param in paramList:
S = 0
for param_ in param:
S += f(param_)
S %= m
if S > Sma... |
try:
from google.cloud.container_v1 import ClusterManagerClient # type: ignore
from google.oauth2 import service_account # type: ignore
from kubernetes import client, utils # type: ignore
from kubernetes.utils.create_from_yaml import FailToCreateError # type: ignore
except ModuleNotFoundError:
r... |
# -*- coding: utf-8 -*-
# © 2015 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import http
from odoo.http import request
class Main(http.Controller):
@http.route('/my_module/book_details', type='http', auth='none')
def book_details(self, book_id):
... |
from typing import Optional, Sequence
from http_types import Request, Response
from openapi_typed_2.openapi import OAuth2SecurityScheme, OpenAPIObject
from .matcher import truncate_path
def generate_code():
return "xyz"
def gen_authflow_response(req: Request):
if "redirect_uri" not in req.query:
r... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 18 20:58:22 2021
@author: mhamz
"""
from datetime import datetime
import socket
import threading
import random
import string
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import DES
from Crypto.Cipher import DES3
from Crypto... |
from eth_utils import encode_hex
from raiden.settings import GAS_LIMIT_HEX
GENESIS_STUB = {
'config': {
'homesteadBlock': 0,
'eip150Block': 0,
'eip150Hash': '0x0000000000000000000000000000000000000000000000000000000000000000',
'eip155Block': 0,
'eip158Block': 0,
'By... |
"""
mnist_loader
Reads and loads the MNIST image data bank into a format easily readable by a neural network.
To retrieve formatted data call ``load_formatted`` and to retrieve a more raw version,
call ``load_raw_data``
"""
import pickle
import gzip
import numpy as mmath
IMAGE_VECTOR_SIZE = 784
def _load_raw(mni... |
# import os
import logging
from typing import Union
from telegram import KeyboardButton
from telegram import ReplyKeyboardMarkup
from telegram import Update
from telegram.ext import CallbackContext
from telegram.ext import CallbackQueryHandler
from telegram.ext import CommandHandler
from telegram.ext import ... |
'''
Created on April 15, 2018
@author: Alejandro Molina
'''
import numpy as np
from spn.algorithms.Inference import add_node_likelihood, add_node_mpe_likelihood
from spn.structure.leaves.parametric.Parametric import *
from spn.structure.leaves.parametric.utils import get_scipy_obj_params
POS_EPS = 1e-7
def parame... |
#! python
# -*- coding: utf-8 -*-
# $Id: pt-BR.py 146 2006-11-07 07:44:29Z sgrayban $
g_strtable = -1
language_code = __name__.split('.')[-1]
def add(label, txt):
global g_strtable
g_strtable.AddText(language_code, label, txt)
def AddStrings(strtable):
global g_strtable
g_strtable = strtable
###... |
from typing import List
from unittest.mock import MagicMock, call
from bluesky import RunEngine
from mocks import DefaultArgumentMock, ExampleTask, MultipleArgumentTask
from python_bluesky_taskgraph.core.decision_engine import decision_engine_plan
from python_bluesky_taskgraph.core.task_graph import TaskGraph
from py... |
#!/usr/bin/env python3
# Copyright (C) 2017-2020 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... |
#!/usr/bin/env python
#this doesn't work. finding a different way
import asn1
with open('ip-asn.txt') as f:
asn = f.read()
decoder = asn1.Decoder()
decoder.start(asn)
tag, value = decoder.read()
print(tag + ' ' + value)
|
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import skipIf
from django.urls import reverse
from django.test import Client
from myuw.views.display_dates import override
from myuw.test.api import missing_url, require_url, MyuwApiTest
@require_url('myuw_date_overr... |
from PyQt5.QtCore import Qt, QRectF, QPointF
from PyQt5.QtGui import QBrush, QPainterPath, QPainter, QColor, QPen, QFont
from PyQt5.QtWidgets import QGraphicsRectItem, QGraphicsItem, QWidget, QVBoxLayout, QGraphicsSceneMouseEvent, \
QGraphicsSceneHoverEvent, QStyleOptionGraphicsItem, QLabel, QTextEdit, QGraphicsPro... |
#Scan an image and read the contents of scanned image
from pyimagesearch.transform import four_point_transform
from pyimagesearch import imutils
from skimage.filters import threshold_adaptive
import cv2
#Open the image for reading
image = cv2.imread("murray.jpg")
ratio = image.shape[0] / 500.0
orig = image.copy()
#R... |
# Deploied On TencentCloud Serverless Cloud Function
# -*- coding: utf8 -*-
import requests
import json
import base64
cookies = {'SESSDATA':'Your Cookies'}
def ep2bvid(bzurl, urlcase):
global VideoName
ep2id_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
ep2id_data = {}
ep2id_cookies ... |
"""A module for testing Genomic Silent Mutation tokenization."""
import unittest
from variation.tokenizers import GenomicSilentMutation
from .tokenizer_base import TokenizerBase
class TestGenomicSilentMutationTokenizer(TokenizerBase, unittest.TestCase):
"""A class for testing Genomic Silent Mutation Tokenization.... |
import datetime
import os
import signal
import subprocess
import unittest
from fase_lib import fase
from fase_lib.fase_model import fase_model
from fase_lib.fase_server import fase_database
DYNAMODB_CMD = (
'java'
' -Djava.library.path=~/DynamoDBLocal/DynamoDBLocal_lib'
' -jar ~/DynamoDBLocal/DynamoDBLo... |
import os
import sys
if sys.version_info[0] < 3:
import Tkinter as tk
import tkFont as tkfont
import tkMessageBox
import Tkconstants, tkFileDialog
else:
import tkinter as tk
import tkinter.font as tkfont
import tkinter.messagebox as tkMessagebox
import tkinter.constants as Tkconstants
... |
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import AbstractUser
from enum import Enum
from django.utils.translation import ugettext_lazy as _
license_list = (
("CC_BY_IGO" , "CC BY-IGO"),
("CC_BY" , "CC BY"),
("CC_BY_SA", "CC BY-SA"),
... |
#!/usr/bin/env python
"""
I have a list of my external writing: https://alexwlchan.net/elsewhere/
I don't want the only copy of those articles to be on the external site,
so I save a copy to my local computer. This script prompts me to save
any articles I haven't already backed up, and records the local copies in
els... |
# Generated by Django 2.1.15 on 2020-09-15 19:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0005_reicpe'),
]
operations = [
migrations.RenameModel(
old_name='Reicpe',
new_name='Recipe',
),
]
|
"""
Defines the following contact cards:
- BCONP
- BLSEG
- BCRPARA
- BCTPARA
- BCTADD
- BCTSET
- BSURF
- BSURFS
"""
from pyNastran.bdf.cards.base_card import BaseCard, expand_thru_by
from pyNastran.bdf.bdf_interface.assign_type import (
integer, integer_or_blank, integer_string_or_blank, double_or_blank,
... |
import os
from posix import listdir
from shutil import copyfile
#from app import app
from flask import Flask, render_template, request, redirect
from flask.wrappers import Request
from create_annotation import create_annotation
from convert_data import main
from res_final import main_res
skills_app = Flask(__name__)
... |
"""Miscellaneous methods."""
import logging
from typing import Dict, Iterable
import petab_select.ui
from petab.C import ESTIMATE, NOMINAL_VALUE
from petab_select import Model, parameter_string_to_value
from petab_select.constants import PETAB_PROBLEM
from ..objective import Objective
from ..petab import PetabImporte... |
from util import django_utils
import django
django.setup()
|
"""
ALEXNET
Various versions of Alexnet, should that be needed for something
Stefan Wong 2019
"""
import torch
import torch.nn as nn
from lernomatic.models import common
class AlexNetCIFAR10(common.LernomaticModel):
def __init__(self) -> None:
self.net = AlexNetModule(10)
self.model_name = 'Alex... |
#!/usr/bin/python
import links
import quo
import requests
import os
banner = """
██████╗░██████╗░░█████╗░██████╗░███████╗
██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝
██████╔╝██████╔╝██║░░██║██████╦╝█████╗░░
██╔═══╝░██╔══██╗██║░░██║██╔══██╗██╔══╝░░
██║░░░░░██║░░██║╚█████╔╝██████╦╝███████╗
╚═╝░░░░░╚═╝░░╚═╝░╚════╝░╚═════╝░... |
from bleach_extras import clean_strip_content
from bleach_extras import TagTreeFilter
from bleach_extras import cleaner_factory__strip_content
from bleach_extras import TAG_TREE_TAGS
from bleach.sanitizer import Cleaner
# ==============================================================================
class FilterTag... |
"""
The ``write_scec`` module contains several functions useful for converting binary output from a
simulation to the text file format used by the SCEC Rupture Code Verification group. Functions are
written for on fault, off fault, and front data types, and there are versions for both 2D and 3D
problems. The functions ... |
#!/usr/bin/python
from topology import *
T = Topology()
net1 = Network(T, "pyt0")
#h1 = Host(T, net1)
h2 = Host(T, net1, args="tcpecho:8888", delay1="20", loss1="0.01")
#h3 = Host(T, net1, args="tcpbench:t:172.16.1.1:")
sleep(1)
start(T)
#wait(h3)
wait(h2)
cleanup()
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2019 Giuliano França
MIT License
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, cop... |
from test import *
class DeviceTest(TestCase):
def test_devices(self):
for device in NetworkManager.NetworkManager.Devices:
self.assertIsStrictSubclass(type(device), NetworkManager.Device)
if device.Dhcp4Config:
self.assertIsInstance(device.Dhcp4Config, NetworkManage... |
from .service import ServiceApiV2
from .healthcheck import HealthApiV2
from .working import WorkApiV2
from .info import InfoApiV2
services = [ServiceApiV2, HealthApiV2, WorkApiV2, InfoApiV2,]
|
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
KV = '''
GridLayout
display: entry
rows: 5
padding: 10
spacing: 10
BoxLayout:
TextInput:
id: entry
font_size: 32
BoxLayout:
spacing: 10
... |
from __future__ import annotations
from typing import Optional, List, Dict
from pydantic import BaseModel
class Request(BaseModel):
url: str
method: str
headers: Dict[str, str]
referrerPolicy: str
isSameSite: Optional[bool]
class CallFrame(BaseModel):
functionName: str
url: str
lin... |
import logging
from datetime import timedelta
from time import time
import discord
from discord.ext import commands
from messages.core import *
from config import CURRENT_VERSION
start_time = time()
class Core(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async de... |
class FormQuestion(object):
"""TypeForm form question object"""
__slots__ = ['_field_id', '_group', '_id', '_question']
def __init__(self, field_id=None, group=None, id=None, question=None):
"""Constructor for TypeForm form question"""
self._field_id = field_id
self._group = group
... |
import pandas as pd
def load_data() :
data = pd.read_csv('hn_stories.csv', header=None)
data.columns = ['submission_time', 'upvotes', 'url', 'headline']
return data
# for testing in read.py
if __name__ == '__main__' :
data = load_data()
print(data.head(2))
|
# Copyright (c) 2019, NVIDIA 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... |
import pytest
import pandas as pd
from dask.distributed import Client, wait, default_client, futures_of
from dask_cuda import LocalCUDACluster
import os
def test_pagerank():
cluster = LocalCUDACluster(threads_per_worker=1)
client = Client(cluster)
import dask.dataframe as dd
import dask_cudf
from ... |
import json
import os
from io import StringIO
import requests
from auth487 import common as acm
from app import data_handler
from app.secret_provider import SecretProvider
from cli_tasks import common
APP_PORT = int(os.getenv('APP_PORT', 8080))
PROJECT_DIR = os.path.dirname(__file__)
TEST_DATA_PATH = os.path.join(PRO... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
##########
## proielsearcher.py Version 1.0 (2015-02-17)
##
## Original author: Matthew Menzenski (menzenski@ku.edu)
##
## License: CC-BY-4.0 ( https://creativecommons.org/licenses/by/4.0/ )
##########
from bs4 import BeautifulSoup
import codecs
import urllib
import sgml... |
# Copyright (C) 2009-2018, Quentin "mefyl" Hocquet
#
# This software is provided "as is" without warranty of any kind,
# either expressed or implied, including but not limited to the
# implied warranties of fitness for a particular purpose.
#
# See the LICENSE file for more information.
import drake
import subprocess
... |
import tkinter as tk
import tkinter.ttk as ttk
import json
root = tk.Tk()
root.resizable(False, False)
combobox_and_calendar_frame = tk.Frame(root)
combobox_and_calendar_frame.pack(side='left', fill='both', expand=1)
perma_frame, redraw_frame = tk.Frame(combobox_and_calendar_frame), tk.Frame(combobox_and_calendar_fra... |
# Generated by Django 3.0.8 on 2020-07-22 23:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Actor',
fields=[
... |
import unittest
from linkedList.SinglyLinkedList import SinglyLinkedList
class SinglyLinkedListTest(unittest.TestCase):
def test_create(self):
true_lists = [
[1, 2, 3, 4, 5],
[1],
[1, 2],
[1, 2, 3, 4],
]
for item in true_lists:
te... |
# Generated by Django 4.0.2 on 2022-02-22 14:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('employees', '0014_alter_employee_options_department_created_on_and_more'),
]
operations = [
migrations.AddField(
model_name='emp... |
import requests
import json
import yaml
import request
def symbol(authtoken):
endpoint="/symbol"
response = requests.get(
request.client.url+endpoint,
headers={'content-type': 'application/json',"Authorization":authtoken})
output=yaml.load(json.dumps(response.json()))... |
from django.conf import settings
from django.contrib.sites.requests import RequestSite
from django.core import urlresolvers
from django.utils.encoding import smart_text
from django.utils import timezone
def import_class(path):
"""
Import a class from a dot-delimited module path. Accepts both dot and
colo... |
"""
This module provides two classes for managing LayerArtists with Qt.
The LayerArtistModel implements a QtModel to interface with a list of
LayerManagers.
The LayerArtistView is a list widget that displays
these layers, and provides GUI access to the model
"""
#pylint: disable=I0011, W0613, R0913, R0904, W0611
from... |
# coding=utf-8
#
# @lc app=leetcode id=686 lang=python
#
# [686] Repeated String Match
#
# https://leetcode.com/problems/repeated-string-match/description/
#
# algorithms
# Easy (31.32%)
# Likes: 525
# Dislikes: 518
# Total Accepted: 71.8K
# Total Submissions: 227.2K
# Testcase Example: '"abcd"\n"cdabcdab"'
#
# ... |
#! /opt/conda/bin/python3
""" Virtual Connector class for combining multiple connectors """
# Copyright 2019 FAU-iPAT (http://ipat.uni-erlangen.de/)
#
# 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 Lice... |
from requests import Session, Request
import asyncio
from hashlib import sha1
import hmac
class Bandcamp:
HOST = 'https://bandcamp.com'
CLIENT_ID = 134
CLIENT_SECRET = "1myK12VeCL3dWl9o/ncV2VyUUbOJuNPVJK6bZZJxHvk="
SECRET_DM_HMAC_KEY = b'dtmfa'
def __init__(self, client):
self.client = cl... |
from netCDF4 import Dataset
import glob,os.path
import numpy as np
from scipy.interpolate import interp1d
import matplotlib
import matplotlib.pyplot as plt
""" starting to collect commonly used functions"""
def calc_rino(BLHeight, MLTheta, SfcFlux, Theta_jump, gamma, delta_h):
"""Richardson number
Arguments... |
"""Utility functions."""
import settings
from selenium.common.exceptions import (NoSuchElementException,
TimeoutException)
from selenium.webdriver.support.ui import WebDriverWait
def is_page_ready(driver):
"""Checks whether document.readyState == 'complete'"""
state = d... |
#!/usr/bin/env/ python
# encoding: utf-8
"""
Configuration logic.
"""
import configparser
import logging
import RedditWallpaperChooser.utils
__author__ = 'aldur'
logger = logging.getLogger(__name__)
SECTION_REDDIT = "reddit"
REDDIT_SUBREDDITS = "subreddits"
REDDIT_RESULT_LIMIT = "result_limit"
REDDIT_SORTING = "... |
import ast
from typing import Optional, Dict
import numpy as np
import napari
from napari.qt import thread_worker
from napari_plugin_engine import napari_hook_implementation
from magicgui import widgets, magic_factory
from .predict import throttle_function, u, predict_output_chunks
from . import watershed as ws
def... |
from setuptools import setup, find_packages
setup(
name='fastotp',
version='0.2.0',
packages=find_packages(include=[
'fastotp',
])
)
|
# -*- coding: utf-8 -*-
"""A simple application to read joystick inputs and send them over UART
Modified from: http://www.pygame.org/docs/ref/joystick.html
Example:
$ python joystick_uart.py
Attributes:
Todo:
"""
import pygame
import serial
import argparse
import debug_messages as dm
# Define some colo... |
#
# Copyright 2021 The Modelbox 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 required by app... |
"""Registry for signal names."""
from delphi_utils import Smoother
CONFIRMED = "confirmed_admissions_covid_1d"
SUM_CONF_SUSP = "sum_confirmed_suspected_admissions_covid_1d"
CONFIRMED_PROP = "confirmed_admissions_covid_1d_prop"
SUM_CONF_SUSP_PROP = "sum_confirmed_suspected_admissions_covid_1d_prop"
CONFIRMED_FLU = "con... |
# Model architecture analyzer
import os
import logging
import logging.handlers as handlers
import json
import numpy as np
import tensorflow as tf
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], enable=True)
tf.keras.backend.set_floatx('float32')
fr... |
# 입력
a = input()
b = input()
c = input()
d = input()
# 판별
if (b == c) and (a == '8' or a == '9') and (d == '8' or d == '9'):
print("ignore")
else:
print("answer")
|
# -*- coding: utf-8 -*-
import pandas as pd
import re
class Msstats():
def __init__(self) -> None:
"""Convert sdrf to msstats annotation file (label free sample)."""
self.warnings = dict()
# Consider unlabeled analysis for now
def convert_msstats_annotation(self, sdrf_file, split_by_co... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may... |
import time
import grpc
from xain.grpc import coordinator_pb2, coordinator_pb2_grpc
RETRY_TIMEOUT = 5
def run():
with grpc.insecure_channel("localhost:50051") as channel:
stub = coordinator_pb2_grpc.CoordinatorStub(channel)
response = coordinator_pb2.RendezvousResponse.LATER
while res... |
from itertools import chain
import numpy as np
from unittest import TestCase
from word2morph.data.mappings import CharToIdMapping, WordSegmentTypeToIdMapping, BMESToIdMapping, LabelToIdMapping
from word2morph.data.processing import DataProcessor
from word2morph.entities.sample import Sample, Segment
class TestPrePr... |
"""
Markdown extensions to support Church Slavonic
"""
import re
import markdown
import logging
from markdown.extensions import Extension
from markdown.inlinepatterns import InlineProcessor
from markdown.treeprocessors import Treeprocessor
import xml.etree.ElementTree as et
from . import __version__
CU_ACCENTS_1 = [ ... |
import re
import rsa
import json
import time
import base64
import logging
import binascii
import requests
import urllib.parse
from uuid import uuid4
from PIL.Image import Image
from conf.weibo import WeiboAccount
class WeiboLogin(object):
"""
class of WeiBoLogin, to login weibo.com
"""
def __init_... |
#! /opt/conda/bin/python3
""" File containing keras interrupt handler class for stopping on ".stop" file """
# Copyright 2018 FAU-iPAT (http://ipat.uni-erlangen.de/)
#
# 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... |
import dempy
import time
def main():
start = time.time()
print("Testing - Users")
print(f"Users [{dempy.users.count()}]:", f"cached {len(dempy.users.get())}")
dempy.users.get("e695c872-edb4-4488-932b-2f49dd5c1b04")
print("---")
print("Testing - Organizations")
print(f"Organizations [{d... |
import json
from pathlib import Path
import boto3
from igata import settings
S3 = boto3.client("s3", endpoint_url=settings.S3_ENDPOINT)
SQS = boto3.client("sqs", endpoint_url=settings.SQS_ENDPOINT, region_name="ap-northeast-1")
DYANMODB = boto3.resource("dynamodb", endpoint_url=settings.DYNAMODB_ENDPOINT, region_nam... |
import argparse
from datetime import datetime, timedelta
import json
import traceback
from uuid import UUID, uuid4
from bson import ObjectId
from motor import motor_tornado
from tornado import escape, gen, ioloop, web
class _JSONEncoder(json.JSONEncoder):
"""Custom JSON encoder."""
def default(self, obj):
... |
import numpy as np
import cv2
# @ahthor Mosfiqun Nahid Hassan
#detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
detector = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while (True):
ret, img = cap.read()
gray... |
from .info import project_info
from .add import add_component
from .new import new_project
from .as_template import project_as_temp
__all__ = ["project_info", "add_component", "new_project", "project_as_temp"]
|
from sqlalchemy.exc import ProgrammingError
from clover.exts import db
from clover.common import get_mysql_error
from clover.common.tasks import interface_task
from clover.models import soft_delete
from clover.models import query_to_dict
from clover.suite.models import SuiteModel
from clover.interface.models import ... |
# This sample tests that generic type variables
# with constrained types properly generate errors. It tests
# both class-defined and function-defined type variables.
from typing import Generic, Literal, TypeVar
class Foo:
var1: int
def __call__(self, val: int):
pass
def do_stuff(self) -> int:
... |
class Panel(Gtk.Image):
def __init__(self,parent):
super(Panel, self).__init__()
self.Parent = parent
self.current_pixbuf = None
def display_page(self,image_file,nextimage_file=True):
if image_file:
self.set_image(image_file)
def set_image(self,bytes_image):... |
_base_ = [
'_base_/models/retinanet_r50_fpn.py',
'_base_/datasets/coco_detection.py',
'_base_/schedules/schedule_1x.py',
'_base_/default_runtime.py'
]
model = dict(
# pretrained='pretrained/pvt_large.pth',
pretrained='https://github.com/whai362/PVT/releases/download/v2/pvt_large.pth',
backbo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-09-04 06:38
from __future__ import unicode_literals
from django.db import migrations
def map_donation_status(status):
mapping = {
'failed': 'failed',
'cancelled': 'failed',
'success': 'succeeded',
'created': 'new',
... |
from setuptools import setup
setup(name='box-requests',
version='0.1',
description='Helper for using Box API with python-requests',
url='http://github.com/cg2v/box-requests',
author='Chaskiel Grundman',
author_email='cg2v@andrew.cmu.edu',
license='BSD',
packages=['box_requests... |
"""
Author: Peratham Wiriyathammabhum
"""
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import scipy.sparse.linalg as linalg
def naivebayes(X):
"""
Perform spectral clustering on an input row matrix X.
mode \in {'affinity','neighborhood','gaussian'}
See: http://www.... |
from SimPEG import Mesh, Regularization, Maps, Utils, EM
from SimPEG.EM.Static import DC
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import copy
import pandas as pd
from scipy.sparse import csr_matrix, spdiags, dia_matrix,diags
from scipy.sparse.linalg import spsolve
from scipy.stats import... |
from flask import Blueprint
from flask_restful import Api
from resources import RectResource
RECT_BLUEPRINT = Blueprint("rect", __name__)
#print("rout details",RECT_BLUEPRINT)
Api(RECT_BLUEPRINT).add_resource(
RectResource, "/rect/recipe"
)
|
import asyncio
from contextlib import suppress
from sanic import Blueprint, response
from sanic.log import logger
from sanic_openapi import doc
from .. import helpers, models, settings, utils
blueprint = Blueprint("images", url_prefix="/images")
@blueprint.get("/")
@doc.summary("List example memes")
@doc.operation... |
dias = int(input('Quantos dias alugados? '))
km = float(input('Qauntos Km rodados? '))
d = (dias * 60) + (km * 0.15)
print('O tatal a pagar é de R${:.2f}'.format(d))
|
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... |
"""
Entry points for all of the primary SRM commands.
"""
import click
from . import config
@click.command()
def init() -> None:
"""Initialize the current directory for SRM."""
conf = config.LocalConf()
if not conf.exists():
conf.load(create=True)
else:
click.secho("Directory is alrea... |
import argparse
from termcolor import colored
from edge_detect import canny
from utils import *
def generate_template(img):
tpl = canny(img, low_thr=160, high_thr=180, sigma=0.8)
return tpl
def match_template(img_edges, tpl_edges):
scales = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8]
tpl_ms = [cv2.res... |
import discord
import yaml
from src.utils.api_manager import APIManager
from src.utils.embeds_manager import EmbedsManager
api_manager = APIManager()
class LogManager:
@staticmethod
async def complete_log(client: discord.Client, sanction_type: str, author: discord.Member or discord.User,
... |
from typing import List, Union, Generator, Tuple, Dict, Optional
import twitch.helix as helix
from twitch.api import API
from .resource import Resource
import logging
logger = logging.getLogger(__name__)
class Users(Resource['helix.User']):
def __init__(self, api: API, *args, ignore_cache: bool = False):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.