text stringlengths 1 927k |
|---|
from typing import Iterable, Callable
import numpy as np
from examples.synthetic_sounds.util import (
seeds_to_wfs,
seed_to_wf_chk,
DFLT_SEEDS,
DFLT_CHUNKER,
chk_tag_gen,
frame_annots_to_chk_annots,
)
from sklearn.decomposition import PCA
from sklearn.svm import SVC
def make_frequency_groups(s... |
"""The definition of the base geometrical entity with attributes common to
all derived geometrical entities.
Contains
========
GeometryEntity
GeometricSet
Notes
=====
A GeometryEntity is any object that has special geometric properties.
A GeometrySet is a superclass of any GeometryEntity that can also
be viewed as ... |
import numpy as np
##Read in data matrix
data = np.load("data/matrix.npy")
print('Creating data...')
##Generate individual CSVs
S_init_data = data[:, :, 2]
I_init_data = data[:, :, 3]
R_init_data = data[:, :, 4]
isUS_data = data[:, :, 5]
#Use fixed beta and gamma for stable simulation
beta_data = 0.8 * np.ones(S_init... |
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.cloudformation.checks.resource.base_resource_check import BaseResourceCheck
class EKSSecretsEncryption(BaseResourceCheck):
def __init__(self):
name = "Ensure EKS Cluster has Secrets Encryption Enabled"
id = "CKV_AWS_... |
from __future__ import absolute_import
from datetime import timedelta
from mock import Mock, patch
from celery import current_app
from celery import states
from celery.result import AsyncResult
from celery.registry import tasks
from celery.task import subtask
from celery.utils import cached_property, uuid
from celer... |
from .expr import *
def_Topic(
Title("Bernoulli numbers and polynomials"),
Entries(
"ac8eca",
"1f88a4",
),
Section("Tables"),
Entries(
"aed6bd",
"588889",
),
Section("Generating functions"),
Entries(
"522b04",
"f79ff0",
),
Section(... |
import yaml
def load_config_data(path: str) -> dict:
with open(path) as f:
cfg: dict = yaml.load(f, Loader=yaml.FullLoader)
return cfg
def save_config_data(data: dict, path: str) -> None:
with open(path, "w") as f:
yaml.dump(data, f) |
import bblfsh_sonar_checks.utils as utils
import bblfsh
def check(uast):
findings = []
bad_methods = (
('hashcode', 'int', 'hashCode'),
('tostring', 'String', 'toString'),
('equal', 'boolean', 'equals'),
)
for method in utils.get_methods(uast):
if "public"... |
from __future__ import print_function, unicode_literals, division
import codecs
import logging
import os
import platform
import re
from functools import partial
from subprocess import check_output
from tempfile import mkdtemp
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser imp... |
import nuke
from avalon.vendor import qargparse
from avalon import api, io
from openpype.api import get_current_project_settings
from openpype.hosts.nuke.api.lib import (
get_imageio_input_colorspace
)
def add_review_presets_config():
returning = {
"families": list(),
"representations": list()... |
from django.test import TestCase
from fluent_contents.tests.factories import create_content_item
from fluent_contents.tests.utils import render_content_items
from .models import {{ model }}
class Test{{ plugin }}(TestCase):
"""
Testing the CMS plugin.
"""
def test_rendering(self):
"""
... |
from nmigen import *
from nmigen.lib.io import *
from nmigen_soc import wishbone
from nmigen_soc.memory import MemoryMap
__all__ = ["GpioCtrl"]
class DummyIO():
def __init__(self, width, name='io'):
self.o = Signal(width, name='%s_o'%name)
self.i = Signal(width, name='%s_i'%name)
self.oe =... |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.2321
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class TransactionRequest(object):
"""NOTE: This cla... |
# Copyright (c) 2020, NVIDIA CORPORATION.
import os
import shutil
import sysconfig
from distutils.sysconfig import get_python_lib
import numpy as np
from Cython.Build import cythonize
from setuptools import find_packages, setup
from setuptools.extension import Extension
import versioneer
install_requires = ["cudf", ... |
import re
import urllib
from django import template
register = template.Library()
@register.filter
def thumbnail_format(path):
match = re.search(r'\.\w+$', path)
if match:
ext = match.group(0)
if ext.lower() in ['.gif', '.png']:
return 'PNG'
return 'JPEG'
@register.filter
de... |
# Generated by Django 2.2 on 2020-10-12 22:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('paper', '0063_paper_paper_... |
import sys
import nltk
import string, re
import csv, pandas
import numpy
"""feature-extract.py: extract data with a features list"""
__author__ = "YuanSun"
# main
def main(feature_list_file, input_file, output_file):
df_feature = pandas.read_csv(feature_list_file)
feature_list = df_feature.values[:,0]
fea... |
"""
comp_parser.py transforms a packet dump into a dictionnary. Dictionnary
format is the following:
{
("field ID", position) : [value, field length in bits, fixed or variable ]
}
since field ID can be repeated, the index is the tuple field ID and position.
"""
from base_import import *
from schccomp import * # for c... |
from unittest import TestCase
from scrapy.http import Response, Request
from scrapy.spider import BaseSpider
from scrapy.contrib.spidermiddleware.offsite import OffsiteMiddleware
class TestOffsiteMiddleware(TestCase):
def setUp(self):
self.spider = self._get_spider()
self.mw = OffsiteMiddleware(... |
import os
class Config:
OPEN_SKY_START_POINT_LONGITUDE = float(os.environ.get('OPEN_SKY_MIDDLE_POINT_LONGITUDE', 13.41053))
OPEN_SKY_START_POINT_LATITUDE = float(os.environ.get('OPEN_SKY_MIDDLE_POINT_LATITUDE', 52.52437))
OPEN_SKY_FLY_DISTANCE_FROM_START_POINT = int(os.environ.get('OPEN_SKY_FLY_DISTANCE_F... |
# Study Drills 29
# In this Study Drill, try to guess what you think the if-statement is and what it does.
# Try to answer these questions in your own words before moving on to the next exercise:
# 1. What do you think the if does to the code under it?
# 2. Why does the code under the if need to be indented four spac... |
from django.contrib import admin
from .models import Day, Lecture_day_and_venue, Lecture,Recommended_text
# Register your models here.
admin.site.register(Day)
admin.site.register(Lecture_day_and_venue)
admin.site.register(Lecture)
admin.site.register(Recommended_text) |
print(f'\033[1:33m{"-"*40:^40}\033[m')
print(f'\033[1:33m{"DICIONÁRIO EM PYTHON":^40}\033[m')
print(f'\033[1:33m{"-"*40:^40}\033[m')
aluno = dict()
aluno['Nome'] = str(input('Nome: '))
aluno['Média'] = float(input(f'Média de {aluno["Nome"]}: '))
if aluno['Média'] >= 7:
aluno['Situação'] = '\033[1:32mAprovado\033[... |
#!/usr/bin/env python
"""
Import MPPT CSV data and plot it.
CSV format:
Volts,volts,amps,watts,state,mode_str,panelSN,resistance,timestamp
29.646,29.646,0.0,0.0,0,CR,B41J00052893,100000,20210913_120014.79
14.267,14.267,0.354,5.05,1,CR,B41J00052893,40.0,20210913_120016.16
"""
from __future__ import print_functi... |
# -*- coding=utf-8 -*-
"""
주요 기능:
- 매매 신호 수신
- 매매 결과 송신
- 사용자 인증
사용례:
-
"""
##@@@ 모듈 import
##============================================================
##@@ Built-In 모듈
##------------------------------------------------------------
import os, sys
import requests
import time
import json
import z... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
def is_nonterminal(s):
return s.isupper()
def is_terminal(s):
return not is_nonterminal(s) and not s == "l"
def __calc(F, prod_list):
while __iter(F, prod_list):
pass
def __iter(F, prod_list):
change = False
for p in prod_list:
if __i... |
import os
from flask import Flask, send_file, abort
# Imports and stuff.
webserver = Flask(__name__)
# Defines the web server.
@webserver.route("/")
def acc_denied():
return "You cannot browse this subdomain."
# Denies access if user tries to browse the subdomain.
@webserver.route("/<path:imageid>")
def i(imagei... |
"""
The :mod:`tslearn.early_classification` module gathers early classifiers for
time series.
Such classifiers aim at performing prediction as early as possible (i.e. they
do not necessarily wait for the end of the series before prediction is
triggered).
**User guide:** See the :ref:`Early Classification <early>` sec... |
# coding: utf-8
"""
InsightVM API
OpenAPI spec version: 3
Contact: support@rapid7.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class HostName(object):
"""NOTE: This class is auto generated by the swagger code genera... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 15:18:12 2020
@author: Abhishek Mukherjee
"""
#Lexicographic order
# N can be 10^5
#So, time complexity might matter!!
#Not in linear time.
#
# Complete the solve function below.
#
def solve(arr):
Words=list()
for i in range(len(arr)):
Words.appen... |
from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
from jmetal.operator import BinaryTournamentSelection
from jmetal.operator.crossover import PMXCrossover
from jmetal.operator.mutation import PermutationSwapMutation
from jmetal.problem.singleobjective.tsp import TSP
from jmetal.util.densit... |
from decimal import Decimal
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy import literal_column
from sqlalchemy import Numeric
from sqlalchemy i... |
"""PYXFOIL: XFOIL AUTOMATION USING PYTHON
Logan Halstrom
EAE 127
UCD
CREATED: 15 SEP 2015
MODIFIED: 17 OCT 2018
DESCRIPTION: Provides functions for automating XFOIL runs.
Each function will iteratively build a list of inputs. When you are ready,
use the RunXfoil command to run the input list
NOTE: Since input list i... |
from lazy_dataset import Dataset, FilterException
import numpy as np
import numbers
class MixUpDataset(Dataset):
"""
>>> ds = MixUpDataset(range(10), SampleMixupComponents((.0,1.)), (lambda x: x), buffer_size=2)
>>> list(ds)
"""
def __init__(self, input_dataset, sample_fn, mixup_fn, buffer_size=10... |
import os
from twisted.python import usage, runtime, filepath, log
from twisted.application import service
from twisted.internet import defer, reactor, protocol
from foolscap.api import Referenceable
class BadServiceArguments(Exception):
pass
class UnknownServiceType(Exception):
pass
class BaseOptions(usage.O... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangocms_personalisation', '0002_personalisationredirectpluginmodel'),
]
operations = [
migrations.AddField(
mo... |
import random
import numpy as np
import networkx as nx
import sys, os, json, argparse, itertools
import grinpy as gp
import time
from glob import glob
from multiprocessing import Pool
from ortools.sat.python import cp_model
"""
This code is based on https://github.com/machine-reasoning-ufrgs/GNN-GCP
"""
def solve_cs... |
from django.shortcuts import render
# Create your views here.
import logging
logger = logging.getLogger('django')
from django import http
import random
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
# from meiduo_mall.libs.yuntongxun.ccp... |
import time
import unittest
import upytester
# ------------ Bench Environment ------------
class Switch(object):
def __init__(self, device):
self.device = device
@property
def value(self):
return self.device.get_switch()()['value']
class BenchTest(unittest.TestCase):
@classmethod
... |
from io import StringIO
import arrow
import mdv
from .cards import *
from .utils import collect_cards, card_markdown
from .. import *
from ..utils import trim_doc
def run_card_simulator(raw=False):
card_groups = {
'Baselines': [
hp_no_invest,
dmg_no_invest,
],
'HP... |
import os
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, "../../../")))
import v2.utils.utils as utils
import traceback
SSL_CERT_PATH = '/etc/ssl/certs/'
PEM_FILE_NAME = 'server.pem'
PEM_FILE_PATH = os.path.join(SSL_CERT_PATH,
PEM_FILE_NAME)
import logging
log = loggi... |
from single_version import __version__
from single_version.ver import _REGEX_VERSION
def test_version():
assert __version__ == '1.2.2'
def test_version_regex():
assert _REGEX_VERSION.match('version="1.2"')
def test_version_regex_with_prefix():
assert _REGEX_VERSION.match('version="v1.2"')
def test_v... |
"""
Tests for Advent of Code Day 24.
https://adventofcode.com/2018/day/24
"""
from os import path
from .day24 import run_part1, run_part2
_CURRENT_FILE_DIR = path.dirname(__file__)
_TEST_DATA = [
'Immune System:',
'17 units each with 5390 hit points (weak to radiation, bludgeoning) with an attack that does '... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
#MenuTitle: Set Tool Shortcuts
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Set Shortcuts for tools in toolbar.
"""
import vanilla
shortcuts = {
"AnnotationTool": u"a",
"DrawTool": u"p",
"HandTool": u"h",
"MeasurementTool": u"l",
"OtherPathsTool": u"e",
"... |
import sys
sys.path.insert(0, "../")
import aiml
from aiml.constants import *
# The Kernel object is the public interface to
# the AIML interpreter.
k = aiml.Kernel()
# Use the 'learn' method to load the contents
# of an AIML file into the Kernel.
k.learn("cn-startup.xml")
# Use the 'respond' method to compute the ... |
import base64
output = base64.b64decode(input) |
from rest_framework.routers import DefaultRouter
# from rest_framework.authtoken import views
from django.urls import include, path
from cats.views import CatViewSet, OwnerViewSet, LightCatViewSet
router = DefaultRouter()
router.register('cats', CatViewSet)
router.register('owners', OwnerViewSet)
router.register(r'm... |
# use this file inside every minute cron in order to recalculate bloom filters. location: staging server
# folder structure
# /home/archiveteam/CAH/
# |_bloom archiveteam@IP::bloom contains bloom filters
# |_clipped contains clipped lists
# ... |
import pack.submod
pack.submod |
"""
======================================================================
Compressive sensing: tomography reconstruction with L1 prior (Lasso)
======================================================================
This example shows the reconstruction of an image from a set of parallel
projections, acquired along dif... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import os
import sys
from evaluate.arcs_inferred_antecedents import evaluate
import json
import tempfile
import subprocess
import operator
import collections
BEGIN_DOCUMENT_REGEX = re.compile(r"#begi... |
"""empty message
Revision ID: 8e5760ed365b
Revises:
Create Date: 2021-06-20 09:49:52.813237
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8e5760ed365b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade(engine_name):
globals()["up... |
#!/bin/env python3
# Copyright 2019 Red Hat
#
# 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... |
import threading
import requests
class APIClient:
def __init__(self):
super().__init__()
self._thread_local = threading.local()
def request(self, method, url, token, **kwargs):
session = self._session()
headers = kwargs.pop('headers', {})
if (not headers or 'Authorizat... |
# Generated by Django 3.2 on 2021-04-08 21:49
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... |
from django.urls import re_path
from django.conf import settings
from django.conf.urls.static import static
from account.views import CreateUserView
urlpatterns = [
re_path('^signup/$', CreateUserView.as_view(), name='signup'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL + 'account/', docu... |
"""
Memes Plugin for Userbot
usage = .meme someCharacter //default delay will be 3
By : - @Zero_cool7870
"""
import asyncio
from telebot import CMD_HELP
from telebot.utils import admin_cmd
@telebot.on(admin_cmd(pattern=r"meme", outgoing=True))
@telebot.on(sudo_cmd(pattern=r"meme", allow_sudo=True))
async def meme(e... |
#! /usr/bin/env python3
import os
import json
import folium
import argparse
import pandas as pd
import mysql.connector
from matplotlib import cm
from matplotlib.colors import to_hex
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--cfg', type=str, required=True)
args = ... |
# Copyright (C) 2015 OpenStack Foundation
# 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 ... |
"""
Download the device tree overlay package use Robert C Nelson's source install:
https://raw.github.com/RobertCNelson/tools/master/pkgs/dtc.sh
After installing the software, make the file executable, and then run the bash
file to install device-tree-overlay (dtc) from the source:
> sudo chmod +x dtc.sh
> sudo bash d... |
import hashlib
import os
import asyncio
import logging
import math
import binascii
import typing
import base58
from aioupnp import __version__ as aioupnp_version
from aioupnp.upnp import UPnP
from aioupnp.fault import UPnPError
from lbry import utils
from lbry.dht.node import Node
from lbry.dht.blob_announcer import ... |
import webbrowser
def open_term(home_url, term):
'''Open a search term in the home_url'''
if ' ' in term:
new_term=term.replace(' ', '%20')
webbrowser.open_new_tab('%s/search?q=%s' % (home_url, new_term))
else:
webbrowser.open_new_tab('%s/search?q=%s' % (home_url, term))
def wbsxcred... |
##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact block... |
import numpy
import argparse
import cv2
image = cv2.imread('pikachu.jpg')
cv2.imshow("Original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
eq = cv2.equalizeHist(gray)
##cv2.imshow("Gray EQ", eq)
#display two images in a figure
cv2.imshow("Histogram Equalization", numpy.hstack([gr... |
def print_graph(g):
print(f"People: {len(g.people)}")
for pid, p in g.people.items():
print(f" * {p.name} ({p.id})")
for s in p.skills:
print(f" - {s.name} ({s.id})")
print(f"Skills: {len(g.skills)}")
for sid, s in g.skills.items():
print(f" * {s.name} ({s.id})")
... |
from __future__ import unicode_literals
from collections import defaultdict
from itertools import chain
from django.contrib.contenttypes.models import ContentType
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError: # Django < 1.9 pragma: no cover
from django.contrib.conten... |
#!/usr/bin/env python3
import os, re
rshift = [1,3,5,7,1]
dshift = [1,1,1,1,2]
def splitter(word):
return [char for char in word]
for i in range(len(rshift)) :
cou = 0
right = 0
lineno = 0
with open("input.txt") as f:
for line in f:
if lineno % dshift[i] == 1:
... |
from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import json
from flask import render_template
from flask import request
from flask import session
from info import db
from info.models import News, User, Comment
from info.utils.common import user_login_data
from info.utils.r... |
import datetime
from pathlib import Path
from unittest import mock
import pytest
from django.test.utils import override_settings
from olympia import amo
from olympia.amo.tests import (
TestCase,
addon_factory,
create_switch,
version_factory,
)
from olympia.git.utils import AddonGitRepository, Broken... |
import requests
import time
import lxml
from selenium import webdriver
from bs4 import BeautifulSoup
from sys import argv
#open page
driver = webdriver.Chrome(executable_path="/Users/chocolee/git/Map-for-Lumpie/src/crawlers/chromedriver")
#load page with input model
driver.get("https://www.ubereats.com/au/location"... |
# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors)
#
# SPDX-License-Identifier: MIT
# This script renders a graph of the CircuitPython rom image.
# It takes the single elf file and uses objdump to get its contents.
import pygraphviz ... |
from alpha_vantage.cryptocurrencies import CryptoCurrencies
import time as timer
import socket, requests
from bs4 import BeautifulSoup
from random import randint
'''
#### CryptoCurrencies Methods: ####
#### get_digital_currency_intraday, ####
#### get_digital_currency_daily, ... |
from setuptools import setup, find_packages
setup(
name = 'CompoundScalingSeg',
version = '1.1',
description = 'Experiment on compound scaling effects U-Net segmentation',
author = 'Younghan Kim',
author_email = 'godppkyh@mosqtech.com',
install_requires= [],
... |
import pytest
from eth_enr.tools.factories import ENRFactory
from eth_utils import to_bytes
from eth.chains.ropsten import ROPSTEN_GENESIS_HEADER, ROPSTEN_VM_CONFIGURATION
from eth.db.atomic import AtomicDB
from eth.db.chain import ChainDB
from trinity.components.builtin.peer_discovery.component import generate_eth... |
from flask import current_app
from http import HTTPStatus
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound
from app.controllers.exc.user_erros import (
BodyNoContent,
TypeSellerInvalid,
)
from app.models.user_completed.users_completed import UsersCompletedModel
from app.models... |
"""
Always handy to have a random agent.
If an RL agent performs significantly better than random, then it must be at least learning something.
"""
import gym
from microtbs_rl import envs
from microtbs_rl.algorithms.common import run_policy_loop
from microtbs_rl.algorithms.common.agent import AgentRandom
from mic... |
"""CoinMarketCap model"""
__docformat__ = "numpy"
import logging
import pandas as pd
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError
import openbb_terminal.config_terminal as cfg
from openbb_terminal.decorators import log_start_end
from openbb_terminal.rich_config import console
logger = loggin... |
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertE... |
#
# Copyright (c) 2021 Citrix Systems, 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... |
# rtlib - Slash Command
from discord.ext import commands
import discord
from .types import (
ApplicationCommand as ApplicationCommandType, OptionType
)
from .application_command import ApplicationCommand
from typing import Type, List, Dict
from .executor import executor
from inspect import signature
from .option... |
"""asynchelper - Allows execution of unlimited number of asynchronous tasks while limiting the amount of active concurrent ones."""
__version__ = '0.1.4'
__author__ = 'Mario Nascimento <mario@whitehathacking.tech>'
__all__ = ["TaskExecutor"] |
from conan_tests.test_regression.utils.base_exe import BaseExeTest, run, conan_create_command
class Bzip2Test(BaseExeTest):
libref = "bzip2/1.0.6@conan/stable"
librepo = "https://github.com/lasote/conan-bzip2.git"
branch = "release/1.0.6"
def setUp(self):
super(Bzip2Test, self).setUp()
... |
# Copyright (c) OpenMMLab. All rights reserved.
from collections.abc import Mapping, Sequence
import torch
import torch.nn.functional as F
from torch.utils.data.dataloader import default_collate
from .data_container import DataContainer
def collate(batch, samples_per_gpu=1):
"""Puts each data field into a tenso... |
Numbers = []
count = 0
N = str(input(''))
for i in N:
if i != '+':
Numbers.append(i)
else:
count += 1
Numbers = sorted(Numbers)
for j in Numbers:
print(j, end = '')
if count != 0:
print('+', end = '')
count -= 1 |
from .molybdenum import MolybdenumModel |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2012, Jim Richardson <weaselkeeper@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_vers... |
from sqlite3 import connect
cxn = connect("./files/database.db", check_same_thread=False)
cur = cxn.cursor()
def with_commit(func):
def inner(*args, **kwargs):
func(*args, **kwargs)
commit()
return inner
@with_commit
def build():
scriptexec("./files/script.sql")
def commit():
cxn.commit()
def close():
... |
from functools import partial
from tests.integration.cli_stub import fxt as _fxt, ExceptionHandling
# Ignore exceptions so that we can test error codes instead
fxt = partial(_fxt, exception_handling=ExceptionHandling.IGNORE) |
import cv2
import numpy as np
img = cv2.imread('corner detection.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
corners = np.int0(corners)
for corner in corners:
x, y = corner.ravel()
cv2.circle(img, (x,y), 3, 255, -1)
cv2.imshow('... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.geometry import allclose
from compas.geometry import transform_points
from compas.geometry.predicates import is_point_on_line
from compas.geometry.primitives import Line
from compas.geometry.primit... |
# Copyright 2020 MONAI Consortium
# 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, s... |
from __future__ import annotations
__author__ = "Suyash Soni"
__email__ = "suyash.soni248@gmail.com"
from _collections import defaultdict
from uuid import uuid4
from typing import TypeVar, Generic, List, Set, Tuple, Dict
T = TypeVar('T')
class Vertex(Generic[T]):
def __init__(self, data: T):
self._id_: ... |
from sqlalchemy.orm import Session
from fastapi import APIRouter
from fastapi import Depends
from fastapi import status
from fastapi import Response
from fastapi import Security
from fastapi_okta import OktaUser
from literature import database
from literature.user import set_global_user_id
from literature.schemas ... |
from abc import ABC, abstractmethod
from typing import List, Literal
class StorageProvider(ABC):
@abstractmethod
def __init__(self, allow_db_create=False, if_table_exists: Literal['ignore', 'recreate'] = 'ignore'):
pass
### MAIN INTERFACE ###
# Function args are the split parts of a typical db... |
from __future__ import annotations
from typing import List, Dict, Optional
from Tile import Tile
from EmptyTile import EmptyTile
from BombTile import BombTile
from NumberTile import NumberTile
from random import randint
import random
# random.seed(0)
class Board:
"""A class representing the state of the Mineswe... |
import master_duel_auto_scan_version as mda
from threading import Thread
def start():
"""method to start searching
"""
scan_card = Thread(target=mda.main)
scan_card.start()
def kill():
"""method to exit searching
"""
mda.status_change(False, False, True,False)
def pause():
"""metho... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
# Generated by Django 3.2.9 on 2021-11-06 07:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('interestsProfile', '0003_alter_algoidtouserid_mapping'),
]
operations = [
migrations.AlterField(
model_name='algoidtouserid',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.