content stringlengths 5 1.05M |
|---|
"""
A demo of GMM (eventually versus DPMM) clustering of hand drawn digits data
"""
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import metrics
from sklearn.mixture import GMM
from sklearn.datasets import load_digits
from sklearn.decompo... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
from hypothesis import strategies as st
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.s... |
class Solution:
"""
Clarifications:
1. The division (/) corresponds to the floor division (//)
2. The integers could have multiple digits
3. The operators precedence is: (/,*), (+,-), from left to right
Intuition:
1. Extract expressions terms one by one
2. Compute 1st.... |
from pydantic import BaseModel
class ExampleOut(BaseModel):
name: str
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-ZTF/ampel/template/ZTFLegacyChannelTemplate.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 16.10.2019
# Last Modified Date: 30.05.2021
# Last Modified By: va... |
n = int(input())
for i in range(n):
b, p = input().split()
b, p = int(b), float(p)
max_time = p / (b - 1)
min_time = p / (b + 1)
min_abpm = 60 / max_time
max_abpm = 60 / min_time
bpm = (60 * b) / p
print(min_abpm, bpm, max_abpm) |
import builtins
from infra.userportal.functions.topology import RivUserPortalFunctionSet
from infra.userportal.states.interfaces import RivStateMachineConstruct
from infra.interfaces import IVpcRivStack
from constructs import Construct
from aws_cdk import (
aws_stepfunctions as sf,
aws_stepfunctions_tasks as... |
from aiohttp import web
from aiohttp_jsonrpc import handler
class JSONRPCExample(handler.JSONRPCView):
def rpc_test(self):
return None
def rpc_args(self, *args):
return len(args)
def rpc_kwargs(self, **kwargs):
return len(kwargs)
def rpc_args_kwargs(self, *args, **kwargs):
... |
"""
Author: Daniele Linguagossa
Heap CTF binary fuzzing made easy
"""
from pwn import *
import random
import struct
import re
import os
class Vulnerability():
vulns = {
'1': 'HEAP WRITE OOB',
'2': 'HEAP READ OOB',
'3': 'FREE NON ALLOC',
'4': 'DOUBLE FREE',
'5': 'USE_AFTER_... |
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import os
import sys
import numpy as np
from matplotlib import pyplot as plt
import cv2
currentfile = '/'.join(__file__.split('/')[:-1])
img_path = os.path.join(currentfile,'images')
def put_chess(l_img,s_img,cord):
l_img.flags.writeable = True... |
#!/usr/bin/env python
import curses
import time
import rospy
import sys
import signal
import numpy as np
import math
import datetime
from tr2py.tr2 import TR2
tr2 = TR2()
tr2.setMode(tr2.mode_rotate)
tr2.release()
jointSelected = 0;
joints = ["b0", "a0", "a1", "a2", "a3", "a4", "g0", "h0", "h1"]
modeSelected = 0
mo... |
"""
PEP 287: reStructuredText Docstring Format
https://www.python.org/dev/peps/pep-0287/
"""
from __future__ import absolute_import, unicode_literals
import os
import re
import astroid
from pylint import checkers
from pylint import interfaces
from pylint.checkers import utils
class PEP287Checker(checkers.BaseChecke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
This file contains code for utilities
_____________________________________________________________________________
"""
from pathlib import Path
import logging
from collections import Order... |
from setuptools import setup, find_packages
setup(
name='zeit.magazin',
version='1.5.3.dev0',
author='gocept, Zeit Online',
author_email='zon-backend@zeit.de',
url='http://www.zeit.de/',
description="vivi ZMO Content-Type extensions",
packages=find_packages('src'),
package_dir={'': 'sr... |
import app
import logging
import os
from spacy.language import Language
from spacy.tokens import Doc
# import gpt_2_simple as gpt2
log = logging.getLogger(__name__)
from app.models import PIPELINE_STAGES as STAGE
class StoryGenerator(object):
"""
generates some human-readable "story" from our NLP analysis... |
import gym
import pybullet_envs
import numpy as np
from ppo.agent import Agent
if __name__ == '__main__':
env = gym.make('AntBulletEnv-v0')
learn_interval = 100
batch_size = 5000
n_epochs = 1000
learning_rate = 0.0003
observation_space = env.observation_space.shape[0]
action_space = env.... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Property Management"),
"items": [
{
"type": "doctype",
"description": "Property",
"name": "Property",
},
{
"type": "doctype",
"description": "Property Unit"... |
import os
import re
from app import db, config, socketio, app
from app.library.formatters import formatted_file_data
from app.models.file import File
from app.models.package import Package
from app.modules.mod_process.file_repository import FileRepository
from app.modules.mod_process.status_map import StatusMap
clas... |
# coding: utf-8
# Fabo #902 Kerberos基盤を用いたLidarLiteV3の自動アドレス変更
import FaBoGPIO_PCAL6408
import time
import LidarLiteV3
class Kerberos():
def __init__(self):
pcal6408 = FaBoGPIO_PCAL6408.PCAL6408()
########################################
# Lidar1のアドレスを変更する 0x62 -> 0x52
###########... |
"""p2 users view"""
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import \
PermissionRequiredMixin as DjangoPermissionListMixin
from django.contrib.auth.models import User
from django.contrib.messages.views import SuccessMessageMixin
fr... |
from dbt.tests.util import AnyString, AnyFloat
def snowflake_stats():
return {
'has_stats': {
'id': 'has_stats',
'label': 'Has Stats?',
'value': True,
'description': 'Indicates whether there are statistics for this table',
'include': False,
... |
from recipe_compiler.recipe import Recipe
from recipe_compiler.recipe_category import RecipeCategory
def test_recipe_slug():
# Given
name = "Thomas Eckert"
residence = "Seattle, WA"
category = RecipeCategory("dessert")
recipe_name = '"Pie" Shell Script'
quote = "Hello, World"
ingredients =... |
# SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
from explorations_py import __version__
def test_ve... |
answer = ""
while answer != "n":
answer = input("Would you like to continue? [Y/n] ")
print("do this stuff")
if answer == "african swallow":
print("You found the secret password!")
break
if answer == european":
print("good point")
continue
print("Prompting in the wh... |
from werkzeug.exceptions import HTTPException
from flask import Response, redirect
from flask_admin import BaseView, expose
from flask_admin.contrib.sqla import ModelView as DefaultModelView
from flask_login import login_required
from project.home.decorators import roles_required
class BasicAuthException(HTTPExceptio... |
Import('env')
env.Prepend(CPPPATH=['/home/karl/.platformio/packages/framework-mbed/features/unsupported/rpc']) |
from collections import deque
import os
import cv2
from .wrapper_base import Wrapper, ObservationWrapper
import gym
import gym.spaces as spaces
import numpy as np
os.environ.setdefault("PATH", "")
cv2.ocl.setUseOpenCL(False)
class FrameStack(Wrapper):
def __init__(self, env, k):
"""Stack k last frames."... |
# -*- coding: utf-8 -*-
import unittest
from pyramid import testing
class TestRedisSessionFactory(unittest.TestCase):
def _makeOne(self, request, secret='secret', **kw):
from .. import RedisSessionFactory
return RedisSessionFactory(secret, **kw)(request)
def _assert_is_a_header_to_set_cooki... |
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info.major < 3 or (
sys.version_info.major == 3 and sys.version_info.minor < 6
):
sys.exit("Python 3.6 or newer is required")
VERSION = None
with open("elsie/version.py") as f:
exec(f.read())
if VERSION is None:
... |
"""This re-indexes resources in SOLR to fix problems during SOLR builds.
* By default, prints errors on stdout.
* Optional argument --log: logs output to system log.
"""
from django.core.management.base import BaseCommand
from hs_core.models import BaseResource
from hs_core.hydroshare.utils import get_resource_by_shor... |
import sys, os
import datetime
# a utility
from fasp.runner import FASPRunner
from fasp.search import DiscoverySearchClient
from fasp.workflow import DNAStackWESClient
from fasp.workflow import GCPLSsamtools
import pyega3.pyega3 as ega
class EGAhtsget():
def __init__(self, credentialsPath):
*cred... |
from typing import Dict, Literal, Optional
from pydantic import BaseModel, Field
from common.runtimes import ParameterDefinition, RuntimeConfig, SSHConfig
_DEFAULT: Dict[str, ParameterDefinition] = {
"worker_count": ParameterDefinition(name="worker_count", type="int", readable_name="Max. amount of workers",
... |
from pywr.nodes import InputNode, LinkNode, OutputNode
from pywr.model import Model
from pathlib import Path
import pytest
@pytest.fixture()
def test_dir() -> Path:
return Path(__file__).parent
@pytest.fixture()
def model_dir(test_dir: Path):
return test_dir / "models"
class TestSimple1:
def test_simp... |
# coding: utf-8
from __future__ import unicode_literals
from spacy.kb import KnowledgeBase
from spacy.util import ensure_path
from spacy.lang.en import English
from spacy.tests.util import make_tempdir
def test_issue4674():
"""Test that setting entities with overlapping identifiers does not mess up IO"""
nl... |
import os
import subprocess
import requests
import shutil
import tempfile
from datetime import timedelta
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from core.models import Image, AnimatedGif
class Command(BaseCommand):
help = """
Generates animat... |
"""
Setup file for automat
"""
from setuptools import setup, find_packages
try:
from m2r import parse_from_file
long_description = parse_from_file('README.md')
except(IOError, ImportError):
print("\n\n!!! m2r not found, long_description is bad, don't upload this to PyPI !!!\n\n")
import io
long_de... |
########
# Copyright (c) 2015 GigaSpaces Technologies 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
#
# Unless... |
import os
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
# Load the image from the source file
image_file = "C:/Repositories/Image_Analysis/data/voc/plane/002279.jpg"
image = Image.open(image_file)
""" #Common Filters
blurred_image = image.filter(ImageFilter.BLUR)
sharpened_image = image.filter(I... |
import numpy as np
import matplotlib.pylab as plt
import cv2
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import peak_signal_noise_ratio as psnr
import os
from os.path import join as opj
from os.path import dirname as opd
from tqdm import tqdm
def plot(img,title="",savename=""... |
#!/usr/bin/env python
import argparse
import shelve
import sys
import time
import fresh_tomatoes
from media import Movie
from omdb import get_movie_info
from youtube_trailer import get_trailer_url
# default movies to search for and add to the movie trailer page
default_titles = [
'inception', 'braveheart', 'jason... |
from flask import Flask, render_template, request, redirect, url_for, flash, session
from database import Mysql
from datetime import timedelta
app = Flask(__name__)
app.secret_key = b"secret_key"
app.permanent_session_lifetime = timedelta(days=30)
@app.route("/login", methods=["POST", "GET"])
def login():
"""
... |
import scipy.io
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
import csv
from features import *
dataDirectory = "data/clips"
... |
@bot.command(pass_context=True, name="태그")
async def 태그(ctx, *names):
name = ''
i = 0
for word in names:
i += 1
if word == names[-1] and len(names) == i:
name += str(word)
else:
name += str(word) + ' '
if name == '':
await bot.send_message(ctx.mess... |
from flask import Blueprint, request
from app.models import db, Photo
photo_routes = Blueprint('photos', __name__)
@photo_routes.route('/<int:id>', methods=["DELETE"])
def delete_photo(id):
photo = Photo.query.get(id)
db.session.delete(photo)
db.session.commit()
return {"message": "Delete Successful"} |
# -*- coding: UTF-8 -*-
from collections import defaultdict
from parsers.Parsers import StringParser, IntParser, DatetimeParser, LineParser
from utils import Exchange, Protocol
from parsers.Quotes import QuoteSnapshot
def test_head_rule_file():
rule_file = '../datas/head_rule.conf'
ex = Exchange.SH
proto... |
from socket import * # Contains everything you need to set up sockets
from Prime import is_prime
# Create server port address and socket
server_port = 400
server_socket = socket(AF_INET, SOCK_DGRAM) # Uses IPV4. SOCK_DGRAM indicates UDP
# Assign the port number server_port to the server's socket
server_sock... |
from itertools import count
from typing import Optional
import numpy as np
from matplotlib import patches
from ..lattice import Lattice
from .base import BaseElement
from .utils import straight_element
class Drift(BaseElement):
"""Drift element.
Args:
l: Drift length in meters.
name (option... |
import comments
from django.shortcuts import redirect, render ,HttpResponse ,get_object_or_404
from comments.models import Page , UserComment
from django.contrib.auth.models import User
from django.shortcuts import redirect
from comments.templatetags import extras
from .serializers import commentSerializer
from django.... |
import tensorflow as tf
import numpy as np
import os
from .settings import settings
#Architectural Notes:
#1. Generator: GRU Units
# - Many to Many
# - L1: Number units: 128, Activation = ELU
# - L2: Number units: 32, Activation = ELU
# - Dense: on each head and use tf.gather to get each output, and calcula... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from wouso.core.game import get_games
from wouso.core.game.models import Game
from wouso.interface import logger
def games(request):
""" List of games """
wgs = []
for model in get_games():
wgs.append({'link'... |
from __future__ import unicode_literals
from frappe import _
import frappe
COMMENT_ADDED_FROM_TEMPLATE = '''<span class="text-muted">comment from %s</span>'''
def before_save(doc, method=None):
if doc.reference_doctype in ("Back Order", "Sales Invoice", "Delivery Note", "Packing Slip"):
doc_reference = ... |
from subprocess import Popen
import os
import time
from marmot.representations.representation_generator import RepresentationGenerator
from marmot.experiment.import_utils import mk_tmp_dir
class POSRepresentationGenerator(RepresentationGenerator):
def _get_random_name(self, suffix=''):
return 'tmp_'+suf... |
import cherrypy
from wsmeext.tg1 import wsexpose, wsvalidate
import wsmeext.tg1
__all__ = ['adapt', 'wsexpose', 'wsvalidate']
def scan_api(root=None):
for baseurl, instance in cherrypy.tree.apps.items():
path = [token for token in baseurl.split('/') if token]
for i in wsmeext.tg1._scan_api(inst... |
# 21/11/02 = Tue
# 191. Number of 1 Bits [Easy]
# Write a function that takes an unsigned integer and returns the number of '1'
# bits it has (also known as the Hamming weight).
# Note:
# Note that in some languages, such as Java, there is no unsigned integer type.
# In this case, the input will be given as a signed... |
from .task import NotebookTask, record_outputs
|
from flask import Flask, request, jsonify, g
from datetime import datetime, timedelta, timezone
from collections import Counter
import os, sqlite3
app = Flask(__name__, static_url_path="", static_folder="static/dist")
# timeStart
# timeEnd
# returns => [{ x, y, magnitude }]
@app.get("/api/v1/locations")
def locations... |
import os, sys, email, re, base64, traceback
from datetime import datetime
def safe_b64decode(str):
length = len(str) % 4
if length == 0:
return base64.b64decode(str)
else:
for i in range(4 - int(length)):
str = str + '='
return base64.b64decode(str)
class MailExtactor:... |
import cv2
from tensorflow.python.keras.models import load_model
from pre_process import scale_and_center
def display_img(img):
cv2.imshow('sudoku', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def extract_number(img):
temp = [[0 for i in range(9)] for j in range(9)]
for i in range(9):
... |
"""
Universidad del Valle de Guatemala
Redes
CAtedrático: Vinicio Paz
Estuardo Ureta - Oliver Mazariegos - Pablo Viana
-> Logica del juego Old Maid
"""
import itertools, random
class OldMaid(object):
def __init__(self,players,copy):
# Lista de jugadores. Cada jugador es un diccionario
... |
# -*- coding: utf-8 -*-
from liao_xue_feng._6_oop.human import Human
class Student(Human):
def __init__(self, name, age, job):
super().__init__(name, age)
self.__job = job
def speak(self):
super().speak()
print('My job is %s.' % self.__job)
|
import asyncio
import aiohttp
import aiosqlite
from async_timeout import timeout
import os
import sqlite3
import json
from datetime import datetime
from urllib.parse import urlencode
from .settings import MAX_CACHE_AGE, SQLITE_PATH
async def check_existing_query(db, url):
""" Checks local SQLite3 DB to see if r... |
# The lists/dictionaries in this file let vendors build/link custom libraries
# paths are relative to platform/crosvm dir
DLLS = [
]
VS_PROJECTS_FROM_CMAKE = {
# Format of this dictionary is:
# "dll_path": { "src": "source_code_path", "cmake_flags": "flags", "cmake_flags_for_features": {"feature": "flags"}}
}... |
import os
import sys
# sys.path.append('./')
from transformers import BertTokenizer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import numpy as np
from utils.arguments_parse import args
import json
import torch
from torch import nn
from torch.utils.data import Da... |
# 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\objects\lighting\lighting_object_interactions.py
# Compiled at: 2020-04-17 02:47:04
# Size of source... |
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import ListProperty, StringProperty
class AdventureMap(RelativeLayout):
player_icon = StringProperty()
player_pos = ListProperty()
def __init__(self, **kw):
super(AdventureMap, self).__init__(**kw)
self.map_size = kw['map_size'] i... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
class BidirectionalRNN:
def __init__(self, name, rnn_size, data_type=tf.float32):
self.data_type = data_type
self.name = name
... |
"""Module for testing Coding DNA Insertion Validator."""
import unittest
from variation.validators import CodingDNAInsertion
from variation.classifiers import CodingDNAInsertionClassifier
from .validator_base import ValidatorBase
from variation.tokenizers import GeneSymbol
from variation.data_sources import TranscriptM... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 12:57:44 2018
@author: wolfpack
"""
import pandas as pd
from scipy.cluster import hierarchy as hc
import matplotlib.pyplot as plt
mean_all = pd.read_csv('marks_mean.csv')
mean_all = mean_all.drop("Unnamed: 0",axis=1)
#correlation matrices
corr_... |
import whois
from random import choice
from requests import get, exceptions
def components():
pre = [
'Hi', 'Oxyge', 'Tita', 'Nitro', 'Xeno', 'Ura', 'Vanda', 'Hype',
'Nexu', 'Alpha', 'Ze', 'Zen', 'Force', 'Neo', 'Ne', 'Xe',
'Veno', 'Ze', 'Argo', 'Xe', 'Auro', 'Nebula', 'Cryp', 'Lumi', 'Ve'... |
import labrad
import numpy as np
import time
import datetime as datetime
from EGGS_labrad.servers.script_scanner.experiment import experiment
class vibration_measurement_ss(experiment):
'''
Records scope trace and its FFT, then converts them to csv
'''
name = 'Vibration Measurement SS'
exp_para... |
# Copyright (c) 2019 Graphcore Ltd. All rights reserved.
import numpy as np
import numpy.random as npr
import popart
import onnx
import os
import pytest
import test_util as tu
batch_size = 12
# the number of classes, and the number of features at every depty of the net
hidden_size = 16
num_ipus = 2
# all input and ... |
import sys
import time
import warnings
import cupy
from cupy import cuda
from cupy.cuda import nccl
from cupy import testing
from cupyx.distributed import init_process_group
from cupyx.distributed._nccl_comm import NCCLBackend
from cupyx.distributed._store import ExceptionAwareProcess
from cupyx.scipy import sparse
... |
import sys
r="";i=1
while True:
l,p,v=map(int,sys.stdin.readline().split())
if l==0==p==v: break
t=(v//p)*l
if v%p>l: t+=l
else: t+=v%p
r+="Case "+str(i)+": "+str(t)+'\n'
i+=1
print(r,end="")
|
# Automatically generated by pb2py
# fmt: off
import protobuf as p
class StellarAccountMergeOp(p.MessageType):
MESSAGE_WIRE_TYPE = 218
def __init__(
self,
source_account: str = None,
destination_account: str = None,
) -> None:
self.source_account = source_account
s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import talib
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 30)
pd.set_option('precision', 7)
pd.options.display.float_format = '{:,... |
from fantasydjhousekeeper import leagues, util
from fantasydjhousekeeper.entities import SongStat
import pytest
TMPL_KEY = '-K{}'
TMPL_DT = '2017-01-0{}'
TMPL_SONG_ID = '-Ksong{}'
def __create_stats(*popularities, **kwargs):
day = 1
sg_idx = kwargs['sg_idx'] if 'sg_idx' in kwargs else 0
koffset = kwarg... |
import casbin
from casbin import persist
from mongoengine import Document
from mongoengine import connect
from mongoengine.fields import IntField, StringField
class CasbinRule(Document):
'''
CasbinRule model
'''
__tablename__ = "casbin_rule"
ptype = StringField(required=True, max_length=255)
... |
import six
from sevenbridges.meta.fields import IntegerField, DateTimeField
from sevenbridges.meta.resource import Resource
class Rate(Resource):
"""
Rate resource.
"""
limit = IntegerField(read_only=True)
remaining = IntegerField(read_only=True)
reset = DateTimeField()
def __str__(self)... |
# Copyright (C) 2009 Valmantas Paliksa <walmis at balticum-tv dot lt>
#
# Licensed under the GNU General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version... |
import logging
import urlparse
from bitfield.models import BitField
from django.contrib.auth.models import User
from django.core.exceptions import SuspiciousOperation
from django.db import models
from django.db.models import Count
from django_gravatar.helpers import has_gravatar, get_gravatar_url
from sorl.th... |
import os
from conans import ConanFile, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.33.0"
class VequeConan(ConanFile):
name = "veque"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/Shmoopty/veque"
description = "Fast C+... |
import logging
from threading import Event, Lock, RLock, Thread
logger = logging.getLogger(__name__)
class CriticalTask(object):
"""Represents a critical task in a background process that we either need to cancel or get the result of.
Fields of this object may be accessed only when holding a lock on it. To ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Milan Ondrasovic <milan.ondrasovic@gmail.com>
from typing import Iterable, Optional, Union, Callable, cast
import cv2 as cv
import numpy as np
import torch
from got10k.trackers import Tracker
from sot.bbox import BBox
from sot.cfg import TrackerConfig
from sot... |
from __future__ import annotations
from typing import Literal
from prettyqt import core
from prettyqt.qt import QtNetwork
from prettyqt.utils import InvalidParamError, bidict
mod = QtNetwork.QLocalSocket
LOCAL_SOCKET_ERROR = bidict(
connection_refused=mod.LocalSocketError.ConnectionRefusedError,
peer_close... |
import decimal
import uuid
from datetime import datetime
from flask import request
from flask_restplus import Resource, reqparse
from ..models.mine_expected_document import MineExpectedDocument
from app.extensions import api
from ....utils.access_decorators import requires_role_mine_view, requires_role_mine_create, ... |
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
#
# 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... |
# -*- coding: utf-8 -*-
import factory
from django.contrib.gis.geos import Point
from wallet.factory import WalletFactory
from .models import User
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User # Equivalent to ``model = myapp.models.User``
#django_get_or_create = ('... |
#!/usr/bin/env python
"""
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language ... |
import inspect
import logging
import numbers
import re
from datetime import date, datetime, timedelta
from functools import partial, wraps
from typing import (
Any,
Callable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
import sentry_sdk
from dateutil.par... |
from flask import Flask, render_template, request, flash, redirect, url_for,\
jsonify, send_from_directory, Blueprint, abort, current_app as app
from flask_mail import Mail, Message
from flask_login import logout_user, login_user, current_user, login_required
from app.models.user import User, VerifyEmailRequest, Re... |
import json
import random
import logging
from django.views import View
from django.http import HttpResponse, JsonResponse
from users import models
from verifications import contains
from utils.res_code.res_code import Code
from utils.captcha.captcha import captcha
from verifications.forms import SmsCodeForm
from cele... |
class Solution:
# @param A : integer
# @return a list of list of integers
def prettyPrint(self, A):
arr = []
for i in range(0, A):
new_arr = []
c = A
flag = 0
for j in range(0, 2*A - 1):
new_arr.append(c)
if i ==... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
# -*- coding: utf-8 -*-
# Settings for running the test application testcases
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import... |
from typing import Any
import tornado.websocket
import tornado.web
import tornado.ioloop
import time
import random
import threading
import asyncio
from tornado import httputil
class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
connect_users = set()
def __init__(self, application: tornado.web.Ap... |
# terrascript/chef/r.py
import terrascript
class chef_acl(terrascript.Resource):
pass
class chef_client(terrascript.Resource):
pass
class chef_cookbook(terrascript.Resource):
pass
class chef_data_bag(terrascript.Resource):
pass
class chef_data_bag_item(terrascript.Resource):
pass
class chef... |
testes = int(input())
for i in range(0, testes):
num = input()
E = int(num.split()[0])
D = int(num.split()[1])
if E == D and E == 1:
print('coma')
else:
print('pense')
|
import Agent
import Location
import random
import re
import time
import streamlit as st
class ReadConfiguration():
def __init__(self):
self.worlds=None
self.time_steps=None
self.starting_exposed_percentage=None
self.agent_info_keys=None
self.interaction_info_keys=None
self.f = open('config.txt','r')
se... |
from __future__ import annotations
from typing import List, Union, TextIO, Any
from io import StringIO
from ml.utils.ansi import ANSI
from ml.utils.printer import Printer
from .ast import (
Pattern,
BaseAST,
Axiom,
Axiom,
Sort,
SortInstance,
SortDefinition,
SymbolDefinition,
Vari... |
#!/usr/bin/python3
"""rabinkarp.py: A simple implementation of the Rabin-Karp string searching algorithm."""
__author__ = 'andrei.muntean.dev@gmail.com (Andrei Muntean)'
from sys import maxsize
# Raises x to the specified power. Must specify a mod as well.
def pow(x, exponent, mod):
if exponent == 0:
return 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.