content stringlengths 5 1.05M |
|---|
import logging
from flask import jsonify, request, Response
from werkzeug.exceptions import BadRequest, InternalServerError
from middleware import api_key_authentication
from predictors.contributors_predictor import ContributorsPredictor
from utils import LoggingUtils
from utils.NestableBlueprint import NestableBluepri... |
from operator import itemgetter
t = int(input())
for l in range(t):
d = int(input())
s = []
for i in range(d):
temp = list(map(int, input().split()))
s.append(temp)
s_sorted = list(sorted(s,key=itemgetter(0)))
# print(s_sorted)
q = int(input())
queries = []
for j in range... |
from typing import Optional, Dict, Any
from spark_pipeline_framework.proxy_generator.proxy_base import ProxyBase
from spark_pipeline_framework.progress_logger.progress_logger import ProgressLogger
from os import path
# This file was auto-generated by generate_proxies(). It enables auto-complete in PyCharm. Do not edi... |
# Q2: find median for entire sample
# Q1: find median for first half of the sample
# Q3: find median for second half of the sample
# Before doing any calculation of Quartiles we need to order the sequence from lowest to highest
"""
https://towardsdatascience.com/what-are-quartiles-c3e117114cf1
Quartiles are positio... |
from Symmetric import Symmetric
from KeyPair import KeyPair
from NoiseHandshakeType import NoiseHandshakeType
class NoiseConfig(object):
DISCO_DRAFT_VERSION : str = "3"
NOISE_DH : str = "25519"
NOISE_MESSAGE_LENGTH : int = 65535 - 2 # 2-byte length
NOISE_TAG_LENGTH : int = Symmetric.TAG_SIZE;
N... |
import string
import json
import ConfigParser
import argparse
import tweepy
class Twitter2Robot(tweepy.StreamListener):
valid = ['moveforward',
'movebackward',
'turnleft',
'turnright',
'kickleft',
'kickright',
'dance']
def __init_... |
from datetime import timedelta
from tlbx.date_utils import utcnow, to_tz
def test_tz_conversion():
utc = utcnow()
est = to_tz(utc, "US/Eastern", strip_tz=True)
utc = utc.replace(tzinfo=None)
assert (utc - est) in [timedelta(hours=5), timedelta(hours=4)]
|
"""Services for updating Mug information."""
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple
from bleak import BleakClient, discover
from homeassistant.core import ServiceCall
from . import _LOGGER
from .const import ATTR_MUG_NAME, ATTR_RGB_COLOR, ATTR_TARGET_TEMP
if TYPE_CHECKING:
fr... |
import matplotlib.pyplot as plt
import numpy as np
# 3D图标必须的模块,project='3d'的定义
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(42)
n_grids = 51 # x-y平面的格点数
c = n_grids // 2 # 中心位置
nf = 2 # 低频成分的个数
# 生成格点
x = np.linspace(0, 1, n_grids)
y = np.linspace(0, 1, n_grids)
# x和y是长度为n_grid... |
from JavaListener import JavaListener
from CollectTokenFeatures import CollectTokenFeatures
import groomlib
from antlr4 import ParseTreeListener
import sys
"""
Similar to CollectTokenFeatures but we do prediction of newline on the fly
for each token. Must adjust token line/column info on the fly as current token
posi... |
"""Module for the root command: scan."""
from ostorlab.cli.scan.scan import scan
from ostorlab.cli.scan.run import run
from ostorlab.cli.scan.stop import stop
from ostorlab.cli.scan.list import list as scan_list
|
import copy # 딥 카피 (깊은 복사)
Sbox = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0... |
#!/usr/bin/python
""" Usage
python2.5 appengine_console.py <app-id>
for more information please read: http://code.google.com/appengine/articles/remote_api.html
"""
import code
import getpass
import sys
import os
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(root_dir, 'lib'))
f... |
from SupportMethods.ContentSupport import isNotNone, CheckAnyListElementSameType
class Category(object):
def __init__(self, category:str, sentences:list = None):
"""
This constructor defines a category sample.
:param category:str: words category
:param sentences:list: list ... |
import json
import time
from crawl_lib import *
# Parses starting from the base_url and sends the data to the db
def parse():
deps_exclusions = {'91083', '5426', '4096', '4104'}
full_json = json.loads(urlopen('http://api.walmartlabs.com/v1/taxonomy?format=json&apiKey=' + api_key).read().decode('utf8'))
d... |
from galaxy import eggs
import pkg_resources
pkg_resources.require( "bx-python" )
import logging, os, sys, time, tempfile, shutil
import data
from galaxy import util
from galaxy.datatypes.sniff import *
from cgi import escape
import urllib
from bx.intervals.io import *
from galaxy.datatypes import metadata
from galax... |
import os
import weakref
from metakernel.tests.utils import (get_kernel, get_log_text,
clear_log_text)
from gnuplot_kernel import GnuplotKernel
from gnuplot_kernel.magics import GnuplotMagic
from .conftest import remove_files
# Note: Empty lines after indented triple quoted may
# ... |
from .build import ARCHs_REGISTRY
from .base_arch import BaseReIDModel
from .reduction_arch import ReductionReIDModel |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
import argparse
def count_layer(module, layer):
"""Count number of times a layer is in a network."""
i = 0
if isinstance(module, layer):
return 1
else:
for m in module.children():
i += count_layer(m, layer)
return i
def count_parameters(model):
"""Count the number... |
"""Class for the symbols stack"""
class SymbolsStack:
"""Class for the symbols stack"""
def __init__(self):
self.symbols = [[]]
def add_symbol(self, name):
"""Add a new symbol to the curent stack"""
self.symbols[-1].append(name)
def exists(self, name):
"""Check symbol... |
"""Provider of data related to date and time."""
from calendar import monthrange, timegm
from datetime import date, datetime, time
from mimesis.data import GMT_OFFSETS, ROMAN_NUMS, TIMEZONES
from mimesis.providers.base import BaseDataProvider
from mimesis.typing import DateTime, Timestamp
from mimesis.utils import pu... |
from model.contact2 import Contact2
testdata = [
Contact2(firstname="firstname1", lastname="lastname1"),
Contact2(firstname="firstname2", lastname="lastname2"),
]
|
import os
import sys
import time
import posixpath
import urllib
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from threading import Thread
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from crotal import settings
from crotal.core import C... |
# Generated by Django 2.0.6 on 2018-07-06 13:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('landing', '0009_auto_20180705_1953'),
]
operations = [
migrations.AddField(
model_name='profile... |
# -*- coding:utf-8 -*-
# author:Anson
from __future__ import unicode_literals
import json
from datetime import date, datetime
import requests
import settings
from request_api import RequestAPI
from db import AccessToken
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from C... |
from django.contrib.auth.backends import BaseBackend, UserModel, ModelBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.db.models import Exists, OuterRef, Q
import rest_framework_simplejwt.serializers
from pprint import pprint
class MyModelBackend(Mod... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
from dagster import pipeline
from .solids import download_zipfiles_from_urls, unzip_files
@pipeline
def download_csv_pipeline():
file_names = download_zipfiles_from_urls()
unzip_files(file_names)
|
from django.apps import AppConfig
class InternetCheckConfig(AppConfig):
name = 'internet_check'
|
import collections
import functools
import numpy as np
import math
import random
def _ent_impl(counts):
total = 0
inds = 0
if isinstance(counts, collections.Counter):
counts = (c for _, c in counts.most_common())
if isinstance(counts, dict):
counts = list(counts.values())
for c in ... |
from pathlib import Path
from typing import Iterator, List, Tuple, Union
import numpy as np
from xlib import onnxruntime as lib_ort
from xlib import path as lib_path
from xlib.image import ImageProcessor
from xlib.net import ThreadFileDownloader
from xlib.onnxruntime.device import ORTDeviceInfo
class DFMModelInfo:
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import requests
from .integration import Integration
class Rested:
"""
A basic HTTP Rest client for API Integrations
"""
def __init__(self, integrations=None):
self._integrations = integrations if... |
#!/usr/bin/env python
# -*- encoding: utf8 -*-
from __future__ import division
from math import exp, log
import sys
from video_complexity import read_csv, write_csv
def group_by(rows, field):
groups = {}
for row in rows:
groups.setdefault(row.get(field), list()).append(row)
for i in sorted(grou... |
"""Unit tests for the single threaded binary search tree module."""
import random
from forest.binary_trees import single_threaded_binary_trees
def test_right_threaded_tree(test_single_threaded_tree: list) -> None:
"""Test the basic opeartions of a binary search tree."""
tree = single_threaded_binary_trees.R... |
import requests
import bs4
from six.moves import urllib
class Browser:
def __init__(self, session=None):
self.session = session or requests.Session()
@staticmethod
def add_soup(response):
if 'text/html' in response.headers['Content-Type']:
try:
response.soup = b... |
import numpy as np
import math
from scipy.special import erfc, erfcinv
def phi(input):
"""Phi function.
:param input:
Float (scalar or array) value.
:returns:
phi(input).
"""
return 0.5 * erfc(-input/np.sqrt(2))
def invphi(input):
"""Inverse phi function.
:param... |
# -*- coding: utf-8 -*-
"""Header Package.
This package creates the header that will be written in the images created by
the AIS.
"""
from .header import Header
|
from rest_framework.generics import RetrieveUpdateDestroyAPIView, ListCreateAPIView
from rest_framework.permissions import IsAuthenticated
from django_filters import rest_framework as filters
from .models import Droid
from .permissions import IsOwnerOrReadOnly
from .serializers import DroidSerializer
from .pagination i... |
from script import Script
import subprocess
from pytest import raises
from pytest import skip
class TestUpdatekeys(Script):
script_name = 'teuthology-updatekeys'
def test_invalid(self):
skip("teuthology.lock needs to be partially refactored to allow" +
"teuthology-updatekeys to return no... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
import scipy.integrate
from scipy.stats import norm,uniform
class Convert_Random:
""" 任意の確率関数に従う乱数を生成 """
def __init__(self,f,Nsim = 100000):
np.random.seed()
self.f = f
self.f_normalized = lambda x: f(x) / scipy.integrate.quad(f, -float(... |
# 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,
# distribute, sublicense, and/or sell copi... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
from typing import Any, Mapping
import tensorflow as tf
from tensorflow.python.ipu.ipu_outfeed_queue import IPUOutfeedQueue
from tensorflow.keras.optimizers.schedules import LearningRateSchedule
class LearningRateEnqueuer(LearningRateSchedule):
def __ini... |
from shared.algebra import square_sum, arithmetic_progression_sum
def square_difference(number: int) -> int:
return arithmetic_progression_sum(1, number, number) ** 2 - square_sum(number)
if __name__ == "__main__":
diff = square_difference(100)
print(diff)
|
from os.path import join, dirname
def get_calib_data(fn):
return join(dirname(__file__), fn)
|
from . import attachment
__all__ = ["attachment"]
|
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
#Code starts here
new_record=np.array(new_record)
census=n... |
import os
import subprocess
class Adb(object):
""" Provides some adb methods """
@staticmethod
def adb_devices():
"""
Do adb devices
:return The first connected device ID
"""
cmd = "adb devices"
c_line = subprocess.Popen(cmd, shell=True, stdout=subprocess.P... |
# Copyright 2019 Curtin University. 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... |
# dummy __init__.py for doxygen
|
import pandas as pd
table = pd.read_table('confusion_matrix.csv',header=None, sep=',')
matrixs=table.values
a,b,c,d=matrixs[0][0],matrixs[0][1],matrixs[1][0],matrixs[1][1]
accuracy=(a+d)/(a+b+c+d)
recall = d/(d + c)
precision = d/(d + b)
F1=2*d/(a+b+c+d+d-a)
iou=d/(c+b+d)
print(matrixs)
print('accuracy:',accuracy)
pri... |
import numpy as np
import matplotlib.pyplot as plt
#@matplotlib inline
import math
import csv
from sets import Set
from scipy.stats import itemfreq
#from __future__ import print_function
from chunk2 import *
# Make sure that caffe is on the python path:
caffe_root = '../' # this file is expected to be in {caffe_root}/... |
# Copyright (c) 2019 Bita Hasheminezhad
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
# #942: `fold_left`, `fold_right` and `fmap` do not work with a lazy function
import numpy as np
from phylanx import Phyl... |
#-*- coding:utf-8 -*-
import tensorflow as tf
from common.layers import get_initializer
from encoder import EncoderBase
class DCNN(EncoderBase):
def __init__(self, **kwargs):
super(DCNN, self).__init__(**kwargs)
self.embed_dim = kwargs['embedding_size']
self.num_filters = [6,14]
sel... |
from http import client, cookies
from urllib import request, parse
class Api:
"""A class used to make http requests."""
base_url = 'test.unnax.com'
base_login = '/login'
customer_url = 'http://test.unnax.com/customer'
account_url = 'http://test.unnax.com/account'
statement_url = 'http://test... |
from __future__ import print_function, division
import numpy as np
from scipy.sparse import coo_matrix, csc_matrix, lil_matrix
def AssemblyBEM2D(C, global_coord, boundary_elements, element_connectivity, dN, Basis, w, z, Jacobian, nx, ny, XCO, YCO, geo_args):
# Allocate the two kernels
stiffness_K1 = np.zeros... |
from django import template
import re
register = template.Library()
@register.filter
def phone(string):
return re.sub(r'[^\+\w\d]', '', string) |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2018 sarah-murray
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 us... |
"""
Author: Igor
Date: 2020.06.17
"""
from children import db
from models.city import City
from exceptions.model_exceptions import ColumnValidationError
from sqlalchemy.orm import validates
class Phone(db.Model):
"""
Represents an useful phone number with its description
and additional phone numbers.
... |
from bin.IntervalEnum import *
from bin.TimeInterval import *
from bin.MovingAverageInterval import *
from bin.ohlcv import *
import numpy as np
import time, sys
class Token():
def __init__(self, client, token, time_ranges, ma_ranges, precision, progress_bar):
self.token = token
self.precision = pr... |
# Script to compile GimmeMotifs for packaging for several different distributions
# A VirtualBox image needs to be present for every "host"
# Borrows some code from whiteinge http://gist.github.com/234001
#
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
from fa... |
import argparse
import subprocess
import time
import sys
import os
import boto3
from create_jobs import create_turk_job
from get_results import get_hits_result
"""
Kicks off a pipeline that schedules Turk jobs for tool 1A,
collects results in batches and collates data.
1. Read in newline separated commands and const... |
# -*- coding: utf-8 -*-
from . import img
from . import io
try:
from . import plt
except NameError:
# matplotlib not imported
print('warning : matplotlib not imported')
pass
from .flags import *
|
import pandas as pd
class DataConnector(object):
server = None
username = None
password = None
driver = None
database = None
def __init__(self, database=None):
self.database = database
def read_sql(self, sql):
return pd.read_sql(sql, self.conn)
def execute_sql(self,... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RAer(RPackage):
"""Functions, data sets, examples, demos, and vignettes
for the book C... |
import solarsystem
import math
AU = 149597900 / 1000000 # Astronomical distance unit
G = 6.67430E-20 # Gravitational constant
u = 1.32712440042E11
# Mean orbital distance
planet_vals = {
"Mercury" : {"m": 1.989E30, "a": 57.91E6, "color": [219,206,202]},
"Venus" : {"m": 4.867E24,... |
# -*- coding: UTF-8 -*-
#Exercício Python 45: Crie um programa que faça o computador jogar Jokenpô com você.
print("-=-=--=-=- |GAME - JOKENPÔ| -=-=--=-=-\n")
from random import choice
from time import sleep
#configurando as respostas adversário
escolhas = ["PEDRA", "PAPEL", "TESOURA"]
jogada_adversario = choice(esco... |
import functools
from flask import request, current_app
from werkzeug.exceptions import NotAcceptable
class ExtendHeaders(object):
def __init__(self, app=None, header: str = ""):
self.app = app
self.header = header
if app is not None:
self.init_app(app)
def init_app(self,... |
# Generated by Django 3.1.2 on 2020-10-16 17:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('content', '0010_wikipost'),
]
operations = [
migrations.AlterModelOptions(
name='wikipost',
options={'ordering': ['-created_... |
from __future__ import unicode_literals
import textile
from textile.objects import Block
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
def test_block():
t = textile.Textile()
result = t.block('h1. foobar baby')
expect = '\t<h1>foobar baby</h1>'
... |
# Generated by Django 2.0.5 on 2018-05-25 09:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TestCase',
fields=[
('id', m... |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.MCXRayModel
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Model type used in MCXRay.
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""
__date__ = ""
__copyright... |
# --------------
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings('ignore')
# Load the data
df = pd.read_csv(path)
# replace the $ symbol
columns = ['INCOME','HOME_VAL','BLUEBOOK','... |
"""
Pong (Cooperative Two Player)
=============================
A pong game.
"""
from random import randint
from sys import exit
import pygame
class Paddle(pygame.Rect):
"""
Paddle(self, velocity, up_key, down_key, *args, **kwars)
A paddle object.
Parameters
----------
velocity : int
... |
import unittest
import utils
# O(n) time. O(n) space. Iteration.
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
if len(num1) < len(num2):
num1, num2 = num2, num1
result = []
carry = 0
for i in range(len(num1)):
a = ord(num1[len(num1) -... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from pathlib import Path
from wildfires.utils import handle_array_job_args
try:
# This will only work after the path modification carried out in the job script.
from specific import (
CACHE_DIR,
SimpleCache,
cross_val_cache,
... |
#!"C:\Users\maisu\PycharmProjects\Python_ Script_Image_To_text\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pytesseract==0.3.7','console_scripts','pytesseract'
__requires__ = 'pytesseract==0.3.7'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.s... |
import random
import time
from tkinter import Tk, Button, DISABLED
def show_symbol(x, y):
global first
global previousX, previousY
buttons[x, y]['text'] = button_symbols[x, y]
buttons[x, y].update_idletasks()
if first:
previousX = x
previousY = y
first = False
... |
import asyncio
from PoEQuery.query_generator import bisect_count_two_mod
from PoEQuery.official_api import (
fetch_query_with_query_dividers,
)
from PoEQuery.official_api_query import OfficialApiQuery, StatFilter, StatFilters
from PoEQuery.affix_finder import find_affixes
option_idx_dicts = [
{
"id": ... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
import socket
import json
import time
# Arquivo referente ao Servidor de e-mail que enviará o e-mail para outro Servidor de e-mail
while True:
print("Servidor enviando.")
time.sleep(60)
cli_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Lê o ... |
r"""
.. _ref_vm6_example:
Pinched Cylinder
----------------
Problem Description:
- A thin-walled cylinder is pinched by a force :math:`F` at the middle
of the cylinder length. Determine the radial displacement :math:`\delta`
at the point where the force :math:`F` is applied.
The ends of the cylinder are free... |
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.lib.coverage import get_coverage_by_build_id
from changes.models import Build
from changes.utils.diff_parser import DiffParser
class BuildTestCoverageStatsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_ar... |
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "08 Mar 2016"
import os, sys; sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore
import numpy as np
import copy
#import matplotlib as mpl
import matplotlib.pyplot as plt
import xrt.backends.raycing as raycing
import xrt.backends.r... |
import unittest
from .libsbol import *
import random
import string
import os, sys
import tempfile, shutil
#####################
# utility functions
#####################
URIS_USED = set()
RANDOM_CHARS = string.ascii_letters
MODULE_LOCATION = os.path.dirname(os.path.abspath(__file__))
TEST_LOCATION = os.path.join(MODU... |
#
# Testinfra testcases for systemd service announcing homie devices
#
# Author: cdeck3r
#
import pytest
@pytest.mark.usefixtures("centralnode_ssh_config")
class TestHomieServiceCamnode:
@pytest.mark.parametrize('userhome', ['/home/pi'])
@pytest.mark.parametrize('servicefile', ['homie_centralnode.service'])
... |
from imutils.perspective import four_point_transform
from imutils import contours
import imutils
import cv2
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help='path to the input image')
args = vars(ap.parse_args())
ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3:... |
# File name: MoonsModel
# Copyright 2017 Chidambaram Periakaruppan
# 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
import matplotlib.pyplot as plt
impo... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from yak.rest_user.serializers import LoginSerializer, AuthSerializerMixin
User = get_user_model()
class SocialSignUpSerializer(AuthSerializerMixin, LoginSerializer):
fullname = serializers.CharField(read_only=True)
usernam... |
# -*- encoding:utf-8 -*-
from app import app
# Run the app
app.run() |
'''
PyTorch has its own implementation of backward function for symmetric eigensolver https://github.com/pytorch/pytorch/blob/291746f11047361100102577ce7d1cfa1833be50/tools/autograd/templates/Functions.cpp#L1660
However, it assumes a triangular adjoint.
We reimplement it to return a symmetric adjoint
'''
import nump... |
"""An Accessory for the AM2302 temperature and humidity sensor.
Assumes the DHT22 module is in a package called sensors.
Also, make sure pigpiod is running.
"""
import asyncio
import pigpio
from pyhap.accessory import Accessory
from pyhap.const import CATEGORY_SENSOR
from .sensor import sensor
class AM2302(Access... |
class Solution():
def isIsomorphic(self, s, t):
d1, d2 = [0 for _ in range(256)], [0 for _ in range(256)]
for i in range(len(s)):
if d1[ord(s[i])] != d2[ord(t[i])]:
return False
d1[ord(s[i])] = i + 1
d2[ord(t[i])] = i + 1
return True
s = ... |
# puppycompanyblog/__init__.py
from flask import Flask
app = Flask(__name__)
from puppycompanyblog.core.views import core
app.register_blueprint(core)
|
#
# Unit Tests for json (in json_utils)
#
#
import os
from os.path import abspath, dirname
currdir = dirname(abspath(__file__)) + os.sep
import pyutilib.th as unittest
import pyutilib.misc
try:
import json
json_available = True
except ImportError:
json_available = False
class Test(unittest.TestCase):
... |
from math import sin, cos, tan, radians
ang = float(input('Digite o valor do ângulo: '))
s = sin(radians(ang))
c = cos(radians(ang))
t = tan(radians(ang))
print('O ângulo de {} \ntem O Seno valendo {:.2f},\nO Cosseno valendo {:.2f},\nE a Tangente valendo {:.2f}.'.format(ang, s, c, t))
|
"""
Contains settings for only development environment.
Note: DEBUG is already set to True in defaults.
"""
import tempfile
from .base import *
ALLOWED_HOSTS = ["*"]
INTERNAL_IPS = ["127.0.0.1"]
# Static Files
STATIC_ROOT = env.str(
"DJANGO_STATIC_ROOT", os.path.join(tempfile.gettempdir(), "django")
)
# Debug ... |
import py
from pypy.rpython.llinterp import LLInterpreter
from pypy.translator.translator import TranslationContext, graphof
from pypy.translator.oosupport.treebuilder import build_trees, SubOperation
from pypy.conftest import option
from pypy.rpython.test.test_rlist import BaseTestRlist
from pypy.rpython.test.tool imp... |
from marbles_service_pb2 import LucidaServiceStub, QueryInput, QuerySpec, Request, Response
from infox_service_pb2 import InfoxServiceStub, GConstituent, GLexeme, GSentence, GText, GWikidata
from google.protobuf import empty_pb2
import grpc
import os
import time
import subprocess
import logging
from marbles import PROJ... |
# SPDX-FileCopyrightText: 2020 Splunk Inc.
#
# SPDX-License-Identifier: Apache-2.0
import pytest
import os
from .base import SplunkEnv
from .external import SplunkEnvExternal
import splunklib.client as client
import logging
LOGGER = logging.getLogger(__name__)
class SplunkEnvDockerCompose(SplunkEnv):
def __init... |
from setuptools import setup, find_packages
setup(
name='rgtools',
version='0.1',
description='A useful module',
author='Fenno Vermeij',
author_email='fennovj@gmail.com',
packages=find_packages('rgtools'),
install_requires=[]
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.