content stringlengths 5 1.05M |
|---|
from __future__ import print_function
import errno
import os
import re
import shutil
import subprocess
import sys
def clean_dir(path):
"""
Removes directory at path (and all its subdirectories) if it exists,
and creates an empty directory in its place.
"""
try:
rmtree(path)
except OSE... |
__version__ = '0.1.0'
from beancount.core.number import D
from beancount.ingest import importer
from beancount.core import data, flags
from beancount.core.amount import Amount
from beancount.core.number import Decimal
from datetime import datetime
import csv
class ChaseBankImporter(importer.ImporterProtocol):
"... |
import enum
import torch
import warnings
import inspect
from sys import maxsize as maxsize
from typing import Set
import torch.onnx
# This import monkey-patches graph manipulation methods on Graph, used for the
# ONNX symbolics
import torch.onnx.utils
from functools import wraps
from torch._C import OptionalType
# ... |
#!/user/bin/python
'''Covering Segments by Points
Given a set of n segments with integer coordinates on a line, find the min
number m points such that each segment contains at least one point.
'''
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segment... |
from typing import List
from test_framework import generic_test
def minimum_total_waiting_time(service_times: List[int]) -> int:
# TODO - you fill in here.
return 0
if __name__ == '__main__':
exit(
generic_test.generic_test_main('minimum_waiting_time.py',
... |
"""
Module contains class ErrorInfo. Structure for errors.
"""
import inspect
from typing import Dict, Union
from FaceEngine import FSDKErrorResult # pylint: disable=E0611,E0401
class ErrorInfo:
"""
Error info
Attributes:
errorCode (int): error code
desc (str): error description
... |
import os
import random
import pyperclip
import string
from datetime import datetime
import pandas as pd
def generator():
length = 16
password = []
punctuation = "-+?_!&"
password.append(random.choice(string.ascii_lowercase))
password.append(random.choice(string.ascii_uppercase))
password.ap... |
import pandas as pd
import spacy
from spacy.util import minibatch, compounding
import plac
import random
from pathlib import Path
import pandas as pd
import re
df = pd.read_csv("train_data_and_labels.csv")
df = df.dropna()
len(df)
training_data1 = []
for index, row in df.iterrows():
content =s... |
from tri.delaunay.helpers import ToPointsAndSegments
from tri.delaunay.insert_kd import triangulate
from tri.delaunay.iter import FiniteEdgeIterator, TriangleIterator
from tri.delaunay.inout import output_triangles
from grassfire.inout import output_offsets, output_skel
from grassfire.initialize import init_skeleton, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ActivationEvent:
def __init__(self, request, user):
self.request = request
self.user = user
class LoginEvent:
def __init__(self, request, user):
self.request = request
self.user = user
class LogoutEvent:
... |
# Date: 05/05/2018
# Author: Pure-L0G1C
# Description: Bruteforce Instagram
from time import sleep
from os.path import exists
from sys import exit, version
from lib.bruter import Bruter
from lib.session import Session
from argparse import ArgumentParser
def _input(msg):
return raw_input(msg).lower() ... |
# This Python file uses the following encoding: utf-8
"""
This module contains several functions to measure diversity and a few
related concepts. The diversity indicators all have different advantages and
disadvantages. An overview is given in [Wessing2015]_.
"""
import math
from decimal import Decimal
import numpy a... |
#ย INTIALISATION
importย pygame,ย math,ย sys
fromย pygame.localsย importย *
screenย =ย pygame.display.set_mode((1024,ย 768))
carย =ย pygame.image.load('car.png')
clockย =ย pygame.time.Clock()
k_upย =ย k_downย =ย k_leftย =ย k_rightย =ย 0
speedย =ย directionย =ย 0
positionย =ย (100,ย 100)
TURN_SPEEDย =ย 5
ACCELERATIONย =ย 2
MAX_FORWARD_SPEEDย =ย 10
MAX_RE... |
class Solution(object):
def generateParenthesis(self, n):
left = right = n
result = []
curr = ""
def dfs(left, right, curr, result):
if left == right == 0:
result.append(curr)
return
if left > 0:
... |
from time import sleep
def rgb2hex(r, g, b, ): # RGB to Hex
hex = "#{:02x}{:02x}{:02x}".format(r, g, b)
return hex
def hex2rgb(hex): # Hex to RGB
value = hex.lstrip('#')
return tuple(int(value[i:i + len(value) // 3], 16) for i in range(0, len(value), len(value) // 3))... |
# Copyright 2021 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 applicable law or agreed to... |
"""Evaluation script for the DeepLab-ResNet network on the validation subset
of PASCAL VOC dataset.
This script evaluates the model on 1449 validation images.
"""
from __future__ import print_function
import argparse
from datetime import datetime
import os
import sys
import time
import tensorflow as tf
import nu... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import subprocess
import traceback
import util
from inferlib import config, utils
MODULE_NAME = 'ndk-build/clang'
MODULE_... |
# -*- coding: utf-8 -*-
import string
import random
def test_create_appeal(app):
app.open_appeal_page()
app.appeal.fill_username(fullname=random_string("firstname", 5), name=random_string("firstname", 5),
secondname=random_string("firstname", 5))
app.appeal.fill_phone(phone=... |
# Copyright 2015-2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# Generated by Django 2.1.5 on 2019-02-02 03:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import os
import biothings, config
biothings.config_for_app(config)
from config import DATA_ARCHIVE_ROOT
from biothings.hub.dataload.dumper import FTPDumper
class UniprotSpeciesDumper(FTPDumper):
SRC_NAME = "uniprot_species"
SRC_ROOT_FOLDER = os.path.join(DATA_ARCHIVE_ROOT, SRC_NAME)
FTP_HOST = 'ftp.un... |
from typing import Dict, Tuple, List, Union, Optional
from hdlConvertorAst.to.hdlUtils import iter_with_last
from hwt.code import If, Switch, SwitchLogic, Or
from hwt.hdl.statement import HdlStatement
from hwt.hdl.typeShortcuts import hBit
from hwt.hdl.types.bits import Bits
from hwt.hdl.types.hdlType import HdlType
f... |
#!/usr/bin/env python3
"""Generates the TensorStore logo in SVG format."""
import argparse
import numpy as np
def write_logo(path: str) -> None:
letter_cells = np.array([
[1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 1],
... |
from __future__ import absolute_import
_last_figure = None
import ipywidgets
from IPython.display import display
import IPython
import ipyvolume as ipv
import ipyvolume.embed
import os
import numpy as np
from . import utils
import time
from . import examples
import warnings
import PIL.Image
import traitlets
import uuid... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
class User(AbstractUser):
""" Custom User Model """
GENDER_MALE = "male"
GENDER_FEMALE = "female"
GENDER_OTHER = "other"
GENDER... |
"""Implements the abstract `Corrector` base class to document the generic
methods the subclasses should aim to provide.
`Corrector` classes must adopt the following design:
- `__init__()` takes the required data (e.g. LightCurve, TargetPixelFile);
- `correct()` takes optional parameters and returns a LightCurve;
- `di... |
# pylint: disable=invalid-name
# mypy: ignore-errors
from __future__ import annotations
import typing
from functools import lru_cache
from flupy import flu
from nebulo.config import Config
from nebulo.gql.alias import CompositeType, ConnectionType, EnumType, ScalarType, TableType
from nebulo.gql.parse_info import AST... |
from botomatic import TBot
|
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12345
s.connect(('127.0.0.1', port))
message = s.recv(1024)
print(message.decode("utf-8"))
s.close()
|
# -*- coding: utf-8 -*-
'''
'''
from elasticsearch import Elasticsearch
from datetime import datetime
obj = Elasticsearch([{"host": "192.168.100.104", "port": 9200}]) #ๅจESไธญ้
็ฝฎIPๅฐๅ
# obj = Elasticsearch([{"host": "localhost", "port": 9200}])
res3 = obj.get(index="my-index3", doc_type="test-type", id=42)['_sourc... |
from .renderer import Renderer
class HTMLRenderer(Renderer):
@staticmethod
def render_heading(level, text):
return "<h%d>%s</h%d>\n" % (level, text, level)
@staticmethod
def render_paragraph(text):
return "<p>%s</p>\n\n" % (text, )
@staticmethod
def render_widget(name, para... |
from youtube_livechat_messages.utils import isostr_to_datetime
class EventType:
# Todo: Support more events
textMessageEvent = "textMessageEvent"
superChatEvent = "superChatEvent"
fanFundingEvent = "fanFundingEvent"
class Author:
def __init__(self, author_json):
self.raw_json = author_j... |
from sentry_sdk import start_span
from sentry_sdk.tracing import Span
def test_start_span_to_start_transaction(sentry_init, capture_events):
# XXX: this only exists for backwards compatibility with code before
# Transaction / start_transaction were introduced.
sentry_init(traces_sample_rate=1.0)
even... |
"""Application scope holds command line arguments."""
import meetup2xibo
APP_NAME = "summarize-m2x-logs"
class ApplicationScope:
"""Application scope provides configuration values."""
def __init__(self, args):
"""Initialize with parsed command line arguments."""
self._args = args
@pr... |
from flask import Flask, request, json
import requests
import urllib.parse
app = Flask(__name__)
API_TOKEN = "pk.eyJ1Ijoibm9hbW4iLCJhIjoiY2thYjY3ampjMHo0YzJ4czlqcTc2b3VnNSJ9.vvXvQ9paTOkTSlxH0kLoyQ"
MAPBOX_URL = "https://api.mapbox.com/geocoding/v5/mapbox.places/"
@app.route("/geoloc")
def get_geo_loc():
loc = r... |
import logging
from graphene import config
from discoursesimplification.runner.discourse_tree.extraction.rules.coordination_extractor import CoordinationExtractor
from discoursesimplification.runner.discourse_tree.extraction.rules.restrictive_apposition_extractor import RestrictiveAppositionExtractor
from discoursesi... |
import os
from django.contrib import admin
from django import forms
from django.conf import settings
from django.utils.translation import ugettext as _
from django.contrib.contenttypes import generic
from django.core.urlresolvers import reverse
from brookie.models import Client, Invoice, Tax, Quote, Item, QuotePart
fr... |
import sys
input = sys.stdin.readline
size, total = map(int, input().split())
coins = []
for _ in range(size):
coin = int(input())
coins.append(coin)
coins.sort(reverse=True)
num_of_coins = 0
for coin in coins:
if total == 0:
break
elif total < coin:
continue
else:
num ... |
import sys
import logging
sys.path.append('../api')
from django.contrib.auth.views import LoginView as BaseLoginView
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
fro... |
import pickle
import signal
import argparse
import numpy as np
import itertools as it
from timeit import default_timer as timer
from scipy.stats import unitary_group
import qfactor
from qfactor import CnotGate, Gate, optimize
from qfactor.tensors import CircuitTensor
import qsearch
import qfast
from qfast.decomposi... |
from django.utils.safestring import mark_safe
"""
ๅ้กตไฝฟ็จๆๆกฃ๏ผ
from utils.pagination import Pagination
่งๅพ๏ผ
page_obj = Pagination(request.GET.get('page'), all_departs.count())
return render(request, 'user_list.html', {
'all_user': all_user[page_obj.start:page_obj.end],
'page_html':page_obj.page_html
})
ๆจกๆฟ๏ผ
... |
'''
Tests for the DoneXBlock.
This is nice as a simple example of the edX XBlock test framework.
'''
from openedx.tests.xblock_integration.xblock_testcase import XBlockTestCase
# pylint: disable=abstract-method
class TestDone(XBlockTestCase):
"""
Simple tests for the completion XBlock. We set up a page wit... |
"""
Module with global fixtures
"""
import os
import pytest
from sentinelhub import SHConfig
@pytest.fixture(name='config')
def config_fixture():
config = SHConfig()
for param in config.get_params():
env_variable = param.upper()
if os.environ.get(env_variable):
setattr(config, pa... |
import libtcodpy as libtcod
import os
import pickle
from menu import Menu
from enum import Enum
from vec2d import Vec2d
from model.entity_manager import EntityManager
from menu_manager import MenuStatus
from model.attribute import Attribute, AttributeTag
from model.entity import Entity
from model.action import Action... |
import random
import string
import json
import colorama
import requests
import time
from colorama import Fore
colorama.init(convert=True)
import os
import sys, aiohttp, asyncio
banner = """โโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโ... |
from magicbus.base import Graph
# EXIT_ERROR
# |
# V
# START -----------> EXIT ------> EXITED
# / | ... |
#!antioch
if not(has_dobj_str()):
write(caller, "Where do you want to go?", is_error=True)
return
if not(caller.location.has_property('exits')):
write(caller, "You can't go that way.", is_error=True)
return
exits = caller.location['exits'].value
direction = get_dobj_str()
if(direction not in exits):... |
from datetime import date, datetime
import json
from flask import Blueprint, jsonify, request
from flask import Response
from app.device.device import DeviceObject
from app.device.meter import Meter
from app.user.user import UserObject
from app.util.ML.data_manipulator import setDataForTrain
app_device = Blueprint(... |
import asyncio
import discord
from redbot.core.bot import Red
from starboard.base import get_starboard, get_starboard_cache
from starboard.guild import StarboardGuild
from starboard.shared import log
import_lock = asyncio.Lock()
__all__ = ("import_data", "NoMotorError", "import_lock")
r"""
'alright wtf is this and... |
"""Detailed descriptions will be added soon.
At this time the code is enough.
"""
from datetime import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta
_MONTHS_IN_YEAR = 12
_TODAY = datetime.date
_FORMATS = [
'%Y-%m-%d',
'%y-%m-%d',
'%Y/%m/%d',
'%y/%m/%d',
... |
import discord
import os
import aiofiles
import asyncio
from discord.ext import commands, tasks
from discord_slash import SlashCommand, SlashContext
from itertools import cycle
import time
from datetime import datetime
intents = discord.Intents().default()
intents.members = True
client = commands.Bot(command_prefix = ... |
import uuid
import logging
from datetime import datetime
from django.db import models
from django.db.models import signals
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers impor... |
# !/usr/bin/env python3
""" Factorio mod deployement script
Just move you code in a separate Directory like .../Deploy/ModName
This will be your root/Workspace which is preset to "."
The script will create a tempDir in which it copies all files and folders
and then creates a zip file which is moved to ./_release... |
#!/usr/bin/env python
import sys
import argparse
import scipy.cluster.vq as vq
import numpy
from traj import trajimport
from traj import trajnorm
from traj import trajfeat
from traj import boof
from traj import spatialpyramid
NORM_ARGS = ["flip", "slope", "resample", "slant", "height", "origin"]
FEAT_ARGS = ["dir",... |
r"""Train a neural network to predict feedback for a program string."""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import random
import numpy as np
from tqdm import tqdm
import torch
import torch.optim as optim
import torch.utils.... |
from ..generic_ast import Ast
class BasicAstNode(Ast):
def __init__(self, sons=None):
super(BasicAstNode, self).__init__(sons)
def to_basic_string(self):
return ''.join(s.to_basic_string() for s in self.sons)
class BasicEscapedCharacterNode(Ast):
def __init__(self, escaped_char):
... |
#!/usr/bin/env python
# Copyright 2020 ARC Centre of Excellence for Climate Extremes
# author: Scott Wales <scott.wales@unimelb.edu.au>
#
# 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
#
# ... |
# ๅฐๅๅง็ voc ๆ ผๅผ็ๆฐๆฎ้่ฝฌๆyolov5่ฎญ็ป่ฆๆฑ็ๆฐๆฎ้ๆ ผๅผ
'''
dataset
-images
-train
-xxx.jpg
-test
-val
-labels
-train
-xxx.txt(label x,y,w,h)
-test
-val
'''
# coding:utf-8
from __future__ import print_function
import os
import random
import glob
import xml.et... |
import numpy as np
from scipy import stats
class baseOption():
def __init__(self, underlying_price, volatility, strike_price, time_to_expiration, risk_free_rate, continuous_yield, type="call"):
'''
:param underlying_price: S
:param volatility: sigma
:param strike_price: K
:p... |
__author__ = 'aymgal'
import numpy as np
_support_profiles = ['SLIT_STARLETS', 'SLIT_STARLETS_GEN2']
def create_solver_class(data_class, psf_class, image_numerics_class, source_numerics_class,
lens_model_class, source_model_class, lens_light_model_class, point_source_class,
... |
'''
Import modules to register class names in global registry
'''
from . import base_keras_classifier
from . import model
from . import seq2seq
from . import sequential
__author__ = 'Elisha Yadgaran'
|
"""Supervisr DNS Utils"""
from datetime import date
import dns.name
import dns.query
import dns.rdata
import dns.rdataclass
import dns.rdatatype
import dns.tokenizer
import dns.zone
from dns.rdtypes.ANY.MX import MX
from dns.rdtypes.ANY.SOA import SOA
from supervisr.dns.models import DataRecord, Zone
def date_to_s... |
# -----------------------------
# Options affecting formatting.
# -----------------------------
with section("format"):
# How wide to allow formatted cmake files
line_width = 130
# How many spaces to tab for indent
tab_size = 4
# If an argument group contains more than this many sub-groups (parg or kwarg
... |
import jmespath
import logging
logger = logging.getLogger(__name__)
class JSONRemapper(object):
""" To effect the remapping of data in one JSON format to another using a
config file storing JMESPath expressions."""
def __init__(self, config_file_path):
with open(config_file_path, 'r') as co... |
# -*- coding: utf-8 -*-
import os
import filecmp
from sst_unittest import *
from sst_unittest_support import *
################################################################################
class testcase_simpleRNGComponent(SSTTestCase):
def setUp(self):
super(type(self), self).setUp()
# Put ... |
"""Plot the result of a KNN classification on the sphere."""
import logging
import os
import matplotlib.pyplot as plt
import geomstats.backend as gs
import geomstats.visualization as visualization
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.learning.knn import KNearestNeighborsClassifier
... |
from iziapi.basket.operations import request_contains_basket, request_contains_line
from rest_framework.permissions import BasePermission, IsAuthenticated
class HasUser(BasePermission):
"Only anonymous and authenticated users can access this resource."
def has_permission(self, request, view):
return r... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .user import User
from .achievement import Achievement
from .obtained import Obtained
from .question import Question
from .answer import Answer
from .trivia import Trivia
from .submitted_answer import SubmittedAnswer
|
import _dk_core as core
Quaternion = core.Quaternion
|
def pairwise(iterable):
itnext = iter(iterable).next
while True:
yield itnext(), itnext()
def dictFromSequence(seq):
return dict(pairwise(seq))
|
# Title : TODO
# Objective : TODO
# Created by: Wenzurk
# Created on: 2018/2/8
numbers = list(range(1,10))
for number in numbers:
if number == 1:
print(str(number) + "st")
elif number == 2:
print(str(number) + "nd")
elif number == 3:
print(str(number) + "rd")
else:
... |
# a Line is an object where a wall lay. When different Lines meet, they form Surfaces.
from __future__ import division
import numpy as np
import math
class Line(object):
def __init__(self, point, angular_cluster, spatial_cluster):
self.point = point
self.angular_cluster = angular_cluster
self.spatial_cluster ... |
# Statements are printed one by one, but changing the character's name or age can be tedious.
print("There once was a man named John, ")
print("he was 70 years old, ")
print("He really liked the name John, ")
print("but didn't like being 70.")
# Character's name and age can be stored in variables, so that changes can ... |
import pytest
@pytest.mark.parametrize('installed_version', [
'+ tmp',
'* 0.51.0',
'* 0.50.0',
'* 0.49.0',
])
def test_installed(host, installed_version):
cmd = 'source ~/.sdkman/bin/sdkman-init.sh && sdk list jbang'
out = host.check_output("sudo --login --user=test_usr1 bash -c %s", cmd)
... |
#!/bin/env /usr/bin/python
"""
Test modules found in the local directory. Note that this test is designed
not to have side effects such as modifying any database or file system content.
"""
print """
__________________________________
testing module psdm.file_status...
"""
import psana.pscalib.calib.experiment_info... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/12/6 12:17
# @Author : weihuchao
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m, n = len(word1), len(word2)
if m == 0 or n ==... |
# Pi GPIO port which is connected to the lock servo signal line.
LOCK_SERVO_PIN = 12
LED_PIN = 13
# Pulse width value (in microseconds) for the servo at the unlocked and locked
# position. Center should be a value of 1500, max left a value of 1000, and
# max right a value of 2000.
LOCK_SERVO_UNLOCKED = 1500
LO... |
from flask import render_template, request, session, redirect, url_for
from ..models import Listings, Images, User
from ..models import db
from freshwater import UPLOAD_FOLDER
def makeListing(dics):
newListing = Listings(
fk_user_id = dics['fk_user_id'],
title = dic... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# by pxy 2017-03-10 15:38:39
import time
class Msg(object):
def __init__(self):
pass
def send(self):
return "success"
class TextMsg(Msg):
def __init__(self, toUserName, fromUserName, content):
super().__init__()
self.__dict =... |
import torch
import torch.nn as nn
from torch import Tensor
from functorch import make_fx
from torch.fx import immutable_collections
import torch.utils._pytree as pytree
import torch.utils.dlpack
from torch.nn.utils import _stateless
from functorch._C import CompileCache
from .decompositions import register_decompositi... |
import base64
import json
from pywebapp.route_webapp import RouteWebApp, route
from pywebapp.root_webapp import RootWebApp
from pywebapp import http_helper
from secure_webapp import SecureWebApp
def random_bytes(n):
with open('/dev/urandom', 'rb') as f:
return f.read(n)
class TestApp(SecureWebApp):
@route(''... |
"""
transforms
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import weakref
log = logging.getLogger(__name__)
class SceneNodeState(object):
def __init__(self):
self._parents = []
def addParent(self, parent):
self._parents.append(wea... |
from functools import partial
import numpy as np
from .activations import Softmax
from .config import epsilon
from .utils.generic_utils import get_from_module
class Loss:
"""
"""
@staticmethod
def f(y, y_pred):
raise NotImplementedError
@staticmethod
def df(y, y_pred):
... |
from pygears import gear
from pygears.sim import sim
from pygears.typing import Fixpnumber, Integer, Tuple, Ufixp, Uint, code
from pygears.util.utils import gather
from pygears.lib.verif import directed, drv
from pygears.sim.modules import SimVerilated
from pygears import datagear
from pygears.lib import add, mul
def... |
from datetime import timedelta
import pytest
from django.core.exceptions import ValidationError
from django.utils import timezone
from didadata import api
from didadata.exceptions import InvalidValueException, MetricNotFoundException
from .factories.metrics import MetricFactory
@pytest.mark.django_db
class TestRec... |
from typing import List
import pytest
from src.Img2VecResnet18 import Img2VecResnet18
recognizer = Img2VecResnet18(reload=True)
@pytest.mark.parametrize("filename, expected", [
("Cake.jpg", ["Cake copy.jpg"]),
("buildings0.jpg", ["buildings1.jpg", "buildings2.jpg", "buildings3.jpg", "buildings4.jpg", "buildin... |
import shutil
import superannotate as sa
# COCO to SA
# test panoptic-segmentation
def panoptic_segmentation_coco2sa(tmpdir):
out_path = tmpdir / "toSuperAnnotate/panoptic_test"
try:
sa.import_annotation_format(
"tests/converter_test/COCO/input/toSuperAnnotate/panoptic_segmentation",
... |
# 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, software
# distributed under t... |
# /*
# * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# * SPDX-License-Identifier: MIT-0
# *
# * 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 restrict... |
from DSPbox import MFCC
import scipy.io.wavfile as wav
import numpy as np
import librosa
rate, signal = wav.read('./Observation.wav')
obser = MFCC(signal, rate)
result = []
for i in range(5):
rate, signal = wav.read('./{:d}.wav'.format(i+1))
compare = MFCC(signal, rate)
d = np.zeros((len(obser)+1, len(comp... |
import os.path, sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import srllib
extra_kwds = {}
setup(name="srllib",
version=srllib.__version__,
author="Arve Knudsen",
author_email="arve.knudsen@gmail.com",
url="http://code.go... |
import requests
# from tenacity import retry, wait_exponential
# @retry(wait=wait_exponential(multiplier=1, min=4, max=20))
def requests_get_content(uri, timeout=10):
response = requests.get(uri, timeout=timeout)
return response.content.decode("utf-8")
# @retry(wait=wait_exponential(multiplier=1, min=4, ma... |
from typing import List, Any, Set, Optional
def starts_with_item_from_list(string: str, list_of_strings: List[str]) -> bool:
return any([string.startswith(restriction) for restriction in list_of_strings])
def item_if_string_starts_with_item_from_list(string: str, set_of_strings: Set[str]) -> Optional[str]:
... |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the Kramers-Kronig Calculator software package.
#
# Copyright (c) 2013 Benjamin Watts, Daniel J. Lauk
#
# The software is licensed under the terms of the zlib/libpng license.
# For details see LICENSE.txt
"""This module implements data formats and c... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
##########################################################################
# Copyright (c) 2017-2018 Bertrand Nรฉron. All rights reserved. #
# Use of this source code is governed by a BSD-style license that can be #
# found in the LICENSE file. ... |
# Copyright (c) 2018 PaddlePaddle 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... |
import copy
import functools
import math
import numpy as np
import scipy.signal as ssig
import kwiiyatta
def reshape(feature, new_shape):
shape = feature.shape[1]
shape_gcd = math.gcd(shape, new_shape)
pad_shape = shape//shape_gcd*20
trim_shape = new_shape//shape_gcd*20
feature = np.hstack((fe... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import json
import socket
import time
import random
import logging
import os
import threadpool
import threading
from hyper import HTTP20Connection, tls
def make_response(r):
info = r.read()
code = r.status
return code,info
def writeLog(info):
global... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.