content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, 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:
#
# * Redistributions of source code... |
import imageio
import numpy as np
import torch as th
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
clf = models.inception_v3(pretrained=True)
clf.eval()
pp = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
softmax = nn.Softmax(d... |
from behave import given
from django.contrib.auth.models import User
from django.utils import timezone
from rr.models.contact import Contact
from rr.models.email import Template
from rr.models.serviceprovider import ServiceProvider
from rr.models.spadmin import Keystore
from rr.models.organization import Organization... |
from components.base.ecu.types.impl_ecu_simple import SimpleECU
from components.base.ecu.software.ecu_software import ECUSoftware
from components.security.ecu.software.impl_app_layer_secure import SecureApplicationLayer
from layers.impl_comm_module_my_protocol import MyProtocolCommModule
class MyProtocolECU(SimpleECU)... |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from fvcore.common.file_io import PathManager
import os
import numpy as np
import xml.etree.ElementTree as ET
from detectron2.structures import BoxMode
from detectron2.data import DatasetCatalog, MetadataCatalog
__all__ =... |
from boto3_fixtures import utils
from boto3_fixtures.contrib import boto3, mindictive
def get_queue_url(queue_name):
return utils.call(boto3.client("sqs").get_queue_url, QueueName=queue_name)[
"QueueUrl"
]
def get_queue_arn(queue_url):
return mindictive.get_nested(
utils.call(
... |
import mock
from django import test
from django.conf import settings
from model_mommy import mommy
from devilry.devilry_group.cradmin_instances import crinstance_student
class TestCrinstanceStudent(test.TestCase):
def test_get_rolequeryset_publishing_time_in_future(self):
testuser = mommy.make(settings.... |
import random
import string
import steembase
import steem
# connect to testnet
steembase.chains.known_chains['STEEM'] = {
'chain_id': '79276aea5d4877d9a25892eaa01b0adf019d3e5cb12a97478df3298ccdd01673',
'prefix': 'STX', 'steem_symbol': 'STEEM', 'sbd_symbol': 'SBD', 'vests_symbol': 'VESTS'
}
#capture variables
... |
from ..client import Client
class AdGroups(Client):
def create_ad_group(self, data):
self.uri_path = "/v2/sp/adGroups"
self.method = "post"
self.data = data
return self.execute()
def update_ad_group(self, data):
self.uri_path = "/v2/sp/adGroups"
self.method = ... |
get_app_status_response_docs = """
Returns a JSON list with the current status of all **installed** apps
```
[
{
id: 'specter',
name: 'Specter Desktop',
status: 'online'
},
{
id: 'sphinx',
name: 'Sphinx Chat',
status: 'online'
},
...
]
```
"""
get_app_... |
import itertools
from centrality_metrics.utils import filter_pos, preprocess
TEXT = "Cosmology (from the Greek κόσμος, kosmos 'world' and -λογία, " \
"-logia 'study of') is a branch of astronomy concerned with the " \
"studies of the origin and evolution of the universe, from the " \
"Big Bang t... |
#! /usr/bin/env python
"""
Read and Write Sqlite3 database
"""
import sqlite3
import pandas as pd
TABLE_NAME = "people"
if __name__ == '__main__':
db = sqlite3.connect('../data/db.sqlite3')
df = pd.read_sql_query("SELECT * from " + TABLE_NAME, db)
print(df.head())
# This block of code will delete tab... |
from hackathon.container import *
from hackathon.game import *
|
import argparse
import cv2
from matplotlib.pyplot import gray
import numpy as np
import torch
from torchvision import models,transforms
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam import GuidedBackpropReLUModel
from pytorch_grad_cam.utils.image import show_cam_on_image, \
deprocess_image, \
prep... |
import os
# data_dir='D:/video_data/pets2009'
# data_dir='D:/video_data/videocaviar'
# sequence_list=os.listdir(data_dir)
# for file in sequence_list:
# label_dir = os.path.join(data_dir,file, 'groundtruth')
# examples_list = os.listdir(label_dir)
# for example in examples_list:
# newname=e... |
#!/usr/bin/env python
"""
SlipStream Client
=====
Copyright (C) 2014 SixSq Sarl (sixsq.com)
=====
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-... |
"""Top-level package for goaldsl-api."""
__author__ = """Konstantinos"""
__email__ = 'Panayiotou'
__version__ = '0.1.0'
|
from django.conf.urls import url
from .views import (
OrderListView,
OrderDetailView,
VerifyOwnership
)
urlpatterns = [
url(r'^$', OrderListView.as_view(), name='list'),
url(r'^endpoint/verify/ownership/$', VerifyOwnership.as_view(), name='verify-ownership'),
url(r'^(?P<ord... |
"""
Gau2grid base init
"""
from . import RSH
from . import c_generator as c_gen
from . import codegen
from . import order
from . import python_reference as ref
# Pull in code from the c wrapper
from .c_wrapper import (orbital, orbital_basis, collocation, collocation_basis, c_compiled, cgg_path, ncomponents, get_cgg_s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-09-02 10:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... |
import json
from .utils import castJson
from .utils import MLPModel
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def computeByMLP(request):
# método post
if request.method == "POST":
# decodificar los datos recibidos a un diccionario
b... |
""" B₁ mapping
"""
from .afi import AFI
|
# Copyright (c) 2019 Microsoft Corporation
# Distributed under the MIT software license
import logging
module_logger = logging.getLogger(__name__)
PROVIDER_EXTENSION_KEY = "interpret_ext_provider"
BLACKBOX_EXTENSION_KEY = "interpret_ext_blackbox"
GREYBOX_EXTENSION_KEY = "interpret_ext_greybox"
GLASSBOX_EXTENSION_KEY... |
from django.contrib import admin
from . import models
class ImageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('file', 'credit', 'caption', 'content_type',
'object_id')
}),
)
admin.site.register(models.Image, ImageAdmin)
class VideoAdmin(adm... |
class Transaction:
def __init__(self, l):
who, when, amount = l.split()
self.who = who
self.when = when
self.amount = float(amount)
def __str__(self):
return "%-10s %10s %8.2f" % (self.who, self.when, float(self.amount))
def __lt__(self, other):
return self... |
import FWCore.ParameterSet.Config as cms
# Parameters common for all boards
commonParam = cms.PSet(
# Master flag for Phase-2 studies
runPhase2 = cms.bool(False),
# Debug
verbosity = cms.int32(0),
## During Run-1, ME1a strips were triple-ganged
## Effectively, this means there were only 16 st... |
import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
z=int(sys.argv[3])
if x<y<z or x>y>z:
print("True")
else:
print("False") |
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
from collections import Counter
def array_plot(st, t, mdccm, vel, baz, ccmplot=False,
mcthresh=None, sigma_tau=None, stdict=None):
r"""
Creates plots for velocity--back-azimuth array processing.
Args:
st (... |
class Tri:
index = 0
def __init__(self, pi1, pi2, pi3, p1, p2, p3):
self.pointIndex = [pi1, pi2, pi3]
self.points = [p1 , p2, p3]
|
from __future__ import annotations
from unittest import TestCase
from tests.classes.cellphone_name import CellphoneName
class TestToCap(TestCase):
def test_tocap_capitalize_simple_str(self):
product = CellphoneName(cellphone_name='hello', cellphone_title='world')
self.assertEqual(product.cellphon... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-24 13:54
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('labhamster', '0005_auto_20180224_1538'),
]
operat... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
import datetime as dt
from tinymce.models import HTMLField
class Profile(models.Model):
bio=models.TextField(max_length=100,blank=True,default="bio please...")
profilepic=models.ImageField(upload_to='profile/'... |
import json
import boto3
# defaults
myfileconfig = {
'localdir': '/tmp', 'filename': 'CHANGE.ME',
'write': 'w', 'read': 'r'}
mys3config = {
'bucketname': 'CHANGE.ME', 'prefix': '/',
'regionname': 'CHANGE.ME', 'service': 's3'}
def get_local_config(**kwargs):
global myfileconfig, mys3config... |
from templeplus.pymod import PythonModifier
from toee import *
import tpdp
from utilities import *
import spell_utils
print "Registering sp-Resistance Superior"
def resistanceGreaterSpellBonus(attachee, args, evt_obj):
bonusValue = 6 #Resistance, Superior is a flat +6 resistance bouns to saves
bonusType = 15 #... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Module for monkeypatching our own copy of `envelopes`.'''
### Monkeypatching envelopes: #################################################
# #
from combi... |
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet, ViewSet
from rest_framework.views import APIView
from rest_framew... |
from rlkit.envs.read_hdf5 import get_dataset, qlearning_dataset
import matplotlib.pyplot as plt
import numpy as np
file_path = './data/sac-point-robot/2021_01_04_22_25_16_exp_0000_s_0/offline_buffer_itr_0.hdf5'
# Read the saved replay buffer
data_dict = get_dataset(file_path)
# Run a few quick sanity checks
for key in... |
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.getenv("XRAY_UTILS_DIR"))
import simpleroute
print()
print('ready')
def load_design(f):
'''
name node pin wire
clk CLK_HROW_TOP_R_X60Y130/CLK_HROW_CK_BUFHCLK_L0 W5 HCLK_VBRK_X34Y130/HCLK_VBRK_CK_BUFHCLK0
din[0] INT_R_X9Y100/NE2BEG3 V17 V... |
"""
Exercício 110
Problema: Adicione ao módulo moeda.py criado nos desafios anteriores, uma função
chamada resumo(). que mostre na tela algumas informações geradas pelas
funções que já temos no módulo criado até aqui.
Resolução do problema:
"""
from lib.ex110_modulo import moeda
preco = float(inpu... |
import torch
from torch import nn
from data import create_dataset
from models.networks import SimpleClassifier
from options.train_options import TrainOptions
opt = TrainOptions().parse() # get training options
dataset = create_dataset(opt)
net = SimpleClassifier()
optimizer_C = torch.optim.Adam(net.parameters(), lr=... |
# Copyright (c) 2017 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
import ast
class CannotEval(Exception):
def __repr__(self):
return self.__class__.__name__
__str__ = __repr__
def is_any(x, *args):
return any(
x is arg
for arg in args
)
def of_type(x, *types):
if is_any(type(x), *types):
return x
else:
raise Canno... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'app/ui/default.ui'
#
# Created by: PyQt5 UI code generator 5.10
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
Mai... |
from __future__ import division, absolute_import, print_function
import unittest
import numpy.testing as testing
import numpy as np
import healpy as hp
from numpy import random
import healsparse
class ValidAreaTestCase(unittest.TestCase):
def test_valid_area(self):
"""
Test getting the valid are... |
# -*- coding: utf-8 -*-
# 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... |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... |
computador = 0
usuario = 0
rodada = 0
def computador_escolhe_jogada(n, m):
global computador
n = n - m
if (n == 1):
print(" ")
print("O computador tirou %s peça." % n)
print("Agora restam %s peças no tabuleiro." % n)
print(" ")
if (n == 0):
print ("Fim do... |
VERSION = "0.8.0"
|
# Copyright (c) PagerDuty.
# See LICENSE for details.
import logging
import sys
import time
import warnings
from copy import deepcopy
import requests
from urllib3.connection import ConnectionError as Urllib3Error
from requests.exceptions import ConnectionError as RequestsError
if sys.version_info[0] == 3:
strin... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from typing import TYPE_CHECKING, Tuple, Union
import torch
from .utils import convert_pointclouds_to_tensor, get_point_covariances
if TYPE_CHECKING:
from ..structures import Pointclouds
def estimate_pointcloud_normals(
pointclouds: ... |
from unittest import TestCase
class TestSet_calculation(TestCase):
def tearDown(self):
from arkdbtools import config as c
c.CALCULATION_SETTINGS['BLACKLIST'] = None
c.CALCULATION_SETTINGS['EXCEPTIONS'] = None
c.CALCULATION_SETTINGS['MAX'] = None
c.CALCULATION_SETTINGS['SHA... |
__module_name__ = "_download_test_data.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
# package imports #
# --------------- #
import os
# local imports #
# ------------- #
from .._fetch._poolq_downloader import _poolq_downloader
def _download_test_data():
... |
"""Tests for Excel Ngrams."""
|
""" This file was generated when pymcuprog was built """
VERSION = '3.9.1.120'
COMMIT_ID = '9ef03c2c1682dc14d378fd36e1b35e8bfd9decf9'
BUILD_DATE = '2021-04-23 05:26:20 +0000'
|
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
from flair.data_fetcher import NLPTaskDataFetcher
from flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentLSTMEmbeddings
from flair.models import TextClassifier
from flair.trainers import ModelTrainer
from pathlib import Path
#shuffle the datafra... |
# -*- coding: utf-8 -*-
"""
dircrawler.crawl
This module contains the crux of dircrawler functionality i.e. traversing, determining states
against snapshot and file transformations
"""
import os
from pydoc import locate
import progressbar
from . import utils
from .structures import FileStatus
class DirCrawler(ob... |
# visualizing stop words:
from nltk.probability import FreqDist
import matplotlib.pyplot as plt
def fdist_words(words):
"""Make word frequency plot
Parameters
---------
words : list of str
list of words in text
Returns
-------
fig : matplotlib.pyplot.Figure
"""
fdist = Fr... |
# Generated by Django 2.2.6 on 2019-12-28 20:25
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
os.chdir('../')
import numpy as np
import pandas as pd
from src.d01_data.dengue_data_api import DengueDataApi
from src.d04_modeling.poisson_hmm import PoissonHMM
from src.d04_modeling.dynamic_factor_model import DynamicFactorModel
from src.d04_modeling.arx import ARX
dda = DengueDataApi()
x_train, x_validate... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
# Parse version from _version.py in package directory
# See https://packaging.python.org/guides/single-sourcing-package-version/#single-sourcing-the-version
version = {}
with open('alfred3_dbtools/_version.py') as f:
exec(f.read... |
# -*- coding: utf-8 -*-
import json
import logging
import os
import sys
import threading
import time
import uuid
from collections import namedtuple
import fake_connection
import requests
from flask import Flask, request
from flask_cors import CORS
# Hack to alter sys path, so we will run from microservices package
# T... |
"""empty message
Revision ID: 66ea073821ac
Revises: 02e7c8c58e35
Create Date: 2018-03-11 00:05:54.040903
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '66ea073821ac'
down_revision = '02e7c8c58e35'
branch_labels = None
depe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置信息
股票数据要能正常运行,需要准备工作如下
1. 安装通达信(日线数据来源),然后配置实际的__CONFIG_TDX_STK_DIR__
2. 安装大智慧(除权除息来源),确保路径__CONFIG_DZH_PWR_FILE__的目录已经创建。也可不安装大智慧直接建立对应的目录
3. 根据以下的配置文件,在D盘创建相应的目录
"""
import os
"""
股票
"""
# 通达信目录
__CONFIG_TDX_STK_DIR__ = r'D:\new_hbzq'
# 大智慧权息文件(已经废弃)
__CONFIG_DZH_... |
#!/usr/bin/env python3.6
# -*- coding:utf-8 -*-
import requests,json,base64
service_list = []
headers = {"X-Consul-Token": "xxxxxxxx"}
req = requests.get("http://192.168.200.60:8500/v1/kv/nginx?recurse=ture", headers=headers).json()
for i in req:
k=i['Key']
name = f"SV_{k.split('/')[2]}"
if name not in ['SV... |
# -*- coding: utf-8 -*-
'''
DEPRECATED: Decorators for old annotation-syntax
Created on 11.11.2014
@author: cschmitt
'''
from __future__ import absolute_import, print_function
from bkt.annotation import (require_ui,
ensure_callback_nfo,
ensure_invocation_context,
... |
'''
Conversion of basis sets to PQS
'''
from .. import lut, manip, sort, printing
from .gamess_us import write_gamess_us_ecp_basis
def write_pqs_electron_basis(basis, electron_elements):
s = ''
for z in electron_elements:
data = basis['elements'][z]
el_sym = lut.element_sym_from_Z(z, normal... |
from .token import *
from .user import *
from .plotting import *
from .misc import *
from .transferring import *
from .directories import * |
# Django Library
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
# Localfolder Library
from .father import PyFather
class PyPlugin(PyFather):
name = models.CharField(_("Name"), max_length=80)
author = models.CharField(_("Author"), max_lengt... |
from typing import Callable, Optional
from rx.core import Observable, typing
from rx.scheduler import TimeoutScheduler
def _take_last_with_time(duration: typing.RelativeTime, scheduler: Optional[typing.Scheduler] = None
) -> Callable[[Observable], Observable]:
def take_last_with_time(sour... |
from pyramid.compat import string_types
truthy = frozenset(('t', 'true', 'y', 'yes', 'on', '1'))
falsey = frozenset(('f', 'false', 'n', 'no', 'off', '0'))
def asbool(s):
""" Return the boolean value ``True`` if the case-lowered value of string
input ``s`` is a :term:`truthy string`. If ``s`` is already one of... |
import base64 as b64
def xor_encrypt(tips,key):
lkey = len(key)
secret = []
num = 0
for each in tips:
if num >= lkey:
num = num % lkey
secret.append(chr(ord(each) ^ ord(key[num])))
num += 1
#return b64.b64encode( "".join( secret ).encode() ).decode()
return... |
import os
from pathlib import Path
import subprocess
import paramiko
from paramiko.rsakey import RSAKey
from .box_config import BoxConfig
class SSH:
"""Manage SSH connections"""
ip: str
user: str
client: paramiko.SSHClient
def __init__(self, user: str, ip: str, cfg: BoxConfig) -> None:
se... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from collections import OrderedDict
import io
from PIL import Image
from . import common
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestVariantsSearch(Trans... |
"""
[STEPIK]
Python: основы и применение https://stepik.org/512
03_01_02 Стандартные методы и функции для строк
"""
"""
Вашей программе на вход подаются две строки s и t, состоящие из строчных латинских букв.
Выведите одно число – количество вхождений строки t в строку s.
Пример:
s = "abababa"
t = "aba"
Вхождения с... |
from euler import lcm
print lcm(*range(1, 21))
|
# Created by Ricardo Quintela
from pygame import Surface, Rect, draw
from guiElements.src.inputs.button import Button
class ColorPicker:
def __init__(self, color: tuple, pos: tuple = (0,0)):
"""
The constructor of the class ColorPicker\n
Args:
color: the color of the backgroun... |
# -*- coding:utf-8 -*-
from django.shortcuts import render
import urllib
import json
import logging
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from django.utils.encoding import smart_str
from sms.signals import ... |
__author__ = 'Antony Cherepanov'
def bubble_sort(t_input):
""" Bubble Sort Algorithm
Simple and slow algorithm
http://en.wikipedia.org/wiki/Bubble_sort
Best case performance: O(n^2)
Worst case performance: O(n^2)
Worst Case Auxiliary Space Complexity: O(1)
:param t_input: [li... |
#!/usr/bin/env python
from django import forms
from .models import Quote
class QuoteForm(forms.ModelForm):
class Meta:
model = Quote
exclude = []
text = forms.CharField(widget=forms.Textarea(
attrs={'rows': 5, 'cols': 68}
))
|
import os
MOCKAROO_URL = 'https://my.api.mockaroo.com/'
MOCKAROO_API_PATH = 'usermockdata.json'
MOCKAROO_API_KEY = 'cbb86130'
BROWSERSTACK_URL = 'https://felipehenao2:AEcZzcuK1nvH1QxSUnjR@hub-cloud.browserstack.com/wd/hub'
BROWSERSTACK_EXECUTION_BASE_URL = 'https://automate.browserstack.com/dashboard/v2/builds'
BROWS... |
# Generated by Django 2.2.4 on 2019-12-02 17:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('property', '0012_auto_20191202_1852'),
]
operations = [
migrations.AlterField(
model_name='owner',
name='owner'... |
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
from django.conf.urls import url
from django.urls import path
from tickets_handler.views.json_views import *
from tickets_handler.views.template_views import *
from tickets_handler.views.views import *
from django.contrib import admin
urlpatterns = [
url('admin/', admin.site.urls),
url('firebase/', firebase, ... |
# -*- coding: utf-8 -*-
'''
Export napalm-logs notifications as Prometheus metrics.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import logging
# Import third party libs
from prometheus_client import Counter, Gauge
# Import napalm-logs pkgs
import napalm_logs.uti... |
import spin
import numpy as np
from scipy.spatial.distance import squareform, cdist, pdist
n = 1000
rot = (spin.EulerAngles(), spin.ExponentialMap(), spin.AxisAngle(), spin.Quaternion())[-1]
dofs = rot.random(n).T
R = []
for x in dofs:
rot.dofs = np.ascontiguousarray(x)
R.append(rot.matrix.copy())
R =... |
from __future__ import unicode_literals, division, absolute_import
import os
from argparse import SUPPRESS
from flexget.options import ArgumentParser, CoreArgumentParser
class UIArgumentParser(ArgumentParser):
"""The UI options parser takes only ui options at the cli, but adds the default core options once cli is... |
from mido import Message, MidiFile, MidiTrack
import numpy.random as rd
import numpy as np
from pydub import AudioSegment
from pydub.playback import play
from lib import tempo_r, volume, velocity_r, mid2aud
def comp_lh1(track):
"""Generate the track for the left hand of comptine N°2"""
# A beat is a 100
t... |
class Dict:
def __init__(self):
self.me = {}
self.engania_pichanga = 0
def add_all(self, y):
self.engania_pichanga += y
def obtener(self, x):
return self.me[x] += self.engania_pichanga
def borrar(self, x):
if x in self.me:
del(self.me[x])
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mock
from django.test import TestCase
from django.conf import settings
from ralph.discovery.plugins.openstack import (openstack as openst... |
import requests
import tqdm
import gdown
import os
def http_get(url, filename, proxies=None):
req = requests.get(url, stream=True, proxies=proxies)
content_length = req.headers.get('Content-Length')
total = int(content_length) if content_length is not None else None
progress = tqdm.tqdm(unit="B", tot... |
from .autoshiftedlog import autoshiftedlog, _shiftedlog, _winsorize, _andersondarling, _skew
|
import sys
import tempfile
from collections import defaultdict
from distutils.ccompiler import CCompiler
from distutils.errors import CompileError
from glob import glob
from pathlib import Path
import pybind11
from setuptools import (Extension,
find_packages,
setup)
from... |
import re
import pickle
from keras.preprocessing import sequence
max_features = 20000
maxlen = 100
with open('/model/files/tokenizer.pickle', 'rb') as f:
tokenizer = pickle.load(f)
def tokenize(sentence):
if 'www.' in sentence or 'http:' in sentence or 'https:' in sentence or '.com' in sentence:
sent... |
import sys
import numpy as np
def is_sorted(
a: np.array,
) -> bool:
return np.all(
np.sort(a) == a,
)
def solve():
a = list(map(int, list(input())))
a.append(10)
a = a[::-1]
n = len(a)
dp = [
[1] * 4
for _ in range(n)
]
for i in range(n):
dp[i][0] = 0
for i in range(n - 1):
... |
import numpy as np
import copy
import pickle
from collections import defaultdict
def batch_generator(arr, n_seqs, n_steps):
arr = copy.copy(arr)
batch_size = n_seqs * n_steps
n_batches = int(len(arr) / batch_size)
arr = arr[:batch_size * n_batches]
arr = arr.reshape((n_seqs, -1))
while True:
... |
"""Netgear component constants."""
from datetime import timedelta
from homeassistant.const import Platform
DOMAIN = "netgear"
PLATFORMS = [Platform.DEVICE_TRACKER, Platform.SENSOR]
CONF_CONSIDER_HOME = "consider_home"
DEFAULT_CONSIDER_HOME = timedelta(seconds=180)
DEFAULT_NAME = "Netgear router"
# models using po... |
import gfapy
class References:
def _compute_required_links(self):
"""
Computes the list of links which are required to support
the path.
Returns
-------
list of (gfapy.OrientedLine, gfapy.OrientedLine, gfapy.CIGAR)
An array, which elements are 3-tuples
(from oriented segment, to... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 13:27:44 2020
@author: northner
"""
import time
import cv2
import sys
from time import sleep
import imutils
from imutils.video import VideoStream
import os
from colorama import Fore, Back, Style
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
d... |
# bot.py
# A custom Twitch bot for Hex + MtG card searches
# Based on tutorial here: http://www.instructables.com/id/Twitchtv-Moderator-Bot/
# (The tutorial has several non-functioning bits)
# Uses regex expressions to parse twitch messages and to match card names
# You will need an OAUTH token through Twitch
... |
from random import shuffle
import cv2
import numpy as np
from PIL import Image
import os
def get_file_name(path):
"""
return filename
such as :[100.png,101.png]->[100,101]
"""
filename = os.listdir(path)
filename = [file.split(".")[0] for file in filename]
return np.array(filename)
def rand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.