content stringlengths 5 1.05M |
|---|
"""Unit tests for cutty.projects."""
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
from Bio import SeqIO
import pygustus.util as util
def summarize_acgt_content(inputfile):
util.check_file(inputfile)
letters = ['a', 'c', 'g', 't', 'n']
file_sum = dict.fromkeys(letters, 0)
file_sum.update({'rest': 0})
seq_count = 0
for seq_record in SeqIO.parse(inputfile, 'fasta'):
... |
import PIL
import glob
from PIL import Image
number = 0
image_list = []
for File in glob.glob('positive_images/*.pgm'):
im = Image.open(File)
rgb_im = im.convert('RGB')
rgb_im.save('newImages/pos-' + str(number)+'.jpg')
number = number + 1
|
CLIQZDEX_URL = "https://raw.githubusercontent.com/InTEGr8or/cliqzdex/main/index.yaml"
quiz_url = "https://raw.githubusercontent.com/InTEGr8or/cliqzdex/main/quizzes/"
default_max_questions = 10
CONFIG = {
"cliqzdex_url": "https://raw.githubusercontent.com/InTEGr8or/cliqzdex/main/index.yaml",
"quiz_url": "https:... |
from django import template
register = template.Library()
@register.inclusion_tag('blog/tags/meta.html')
def meta(*objects):
"""Вывод description and title категории"""
try:
object = objects[0][0]
except IndexError:
object = []
return {"object": object}
|
"""Custom log messages."""
import re
RE_BIND_FAILED = re.compile(r".*Bind for.*:(\d*) failed: port is already allocated.*")
def format_message(message: str) -> str:
"""Return a formated message if it's known."""
match = RE_BIND_FAILED.match(message)
if match:
return (
f"Port '{match.g... |
from .mtgnn_layers import *
class MTGNN(nn.Module):
r"""An implementation of the Multivariate Time Series Forecasting Graph Neural Networks.
For details see this paper: `"Connecting the Dots: Multivariate Time Series Forecasting with Graph Neural Networks." <https://arxiv.org/pdf/2005.11650.pdf>`_
Args:
... |
import logging
import sys
from metanime import Anime, Renderer
def render(season):
animes = Anime.load(f'seasons/{season}.yml')
renderer = Renderer('views', 'docs')
for anime in animes:
renderer.render_anime(anime)
renderer.render_season(season, animes)
if __name__ == '__main__':
loggi... |
#!/usr/bin/env python
from yaml import load, dump
from collections import OrderedDict
import time, os
from visualize import visualize
DIV = '\n'+ '='*64 + '\n'
start_time = time.time()
def usage():
pass
# Iterate over all conversation threads
def summarize():
print 'Opening file... ',
file = open('messages_... |
import collections
from data.logic.dsl import *
from spec.mamba import *
with description('dsl'):
with before.each:
self.dimensions = DimensionFactory()
self.model = Model(self.dimensions)
with it('defines dimensions'):
(Andy, Bob, Cathy) = name = self.dimensions(name=['Andy', 'Bob', 'Cathy'])
(C... |
import cv2
import numpy as np
from DAL_utils.overlaps_cuda.rbbox_overlaps import rbbx_overlaps
from DAL_utils.overlaps.rbox_overlaps import rbox_overlaps
a = np.array([[10, 10, 20, 10, 0]], dtype=np.float32)
b = np.array([[10, 10, 20, 10, 0]], dtype=np.float32)
c = rbbx_overlaps(a, b)
d = rbox_overlaps(a, b)
print(c)
... |
"""
This is a script that can be used to retrain the YOLOv2 model for your own dataset.
"""
import argparse
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import l... |
from permissions import Permissions
from address_descriptor import AddressDescriptor
from bitstring import BitArray
from enum import Enum
TLBRecType = Enum(
"TLBRecType",
"TLBRecType_SmallPage TLBRecType_LargePage TLBRecType_Section TLBRecType_Supersection TLBRecType_MMUDisabled"
)
class TLBRecord(ob... |
# Copyright (c) 2020 Uber Technologies, 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... |
from datetime import datetime, timedelta
import pytz
from collections import defaultdict
from itertools import groupby
class MarketCapWeightedPortfolioConstructionModel(PortfolioConstructionModel):
def __init__(self):
self.marketCapDict = {}
self.removedSymbols = []
self.insightCollec... |
#!/usr/bin/env python
# -*- 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 Licen... |
from socketIO_client import SocketIO, BaseNamespace
class Handlers(BaseNamespace):
def on_message_from_server(self, msg):
print("Incoming msg: %s" % msg)
io = SocketIO('localhost', 9090, Handlers, resource="api/v1/socket")
io.emit('hello_from_client')
io.wait(seconds=10)
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import unittest
from fedora import utils
class TestUtils(unittest.TestCase):
def test_parse_to_date(self):
w3 = utils.as_w3c_datetime("2016-12-12")
self.assertEqual("2016-12-11T23:00Z", w3)
w3 = utils.as_w3c_datetime("Wed, 21 Dec... |
from .parser import Parser
from .parse_result import ParseResult
from .nodes import *
|
'''
Created on 29 nov. 2019
@author: usuario
'''
from odoo import api, fields, models
class mecanico(models.Model):
_name = "upocar.mecanico"
_rec_name = "nombre_apellidos"
nombre = fields.Char("Nombre", size=32, required=True)
apellidos = fields.Char("Apellidos", size=64, required=True)
esp... |
"""A game engine for running a game of Dominos."""
import sys, random, json, time
sys.path.insert(0, '..') # For importing app config, required for using db
from dominos.Config import Config
from dominos.classes.Board import Board
from dominos.classes.Pack import Pack
from dominos.classes.Player import Player
class E... |
from Vintageous import PluginLogger
import sublime
import os
_logger = PluginLogger(__name__)
class DotFile(object):
def __init__(self, path):
self.path = path
@staticmethod
def from_user():
path = os.path.join(sublime.packages_path(), 'User', '.vintageousrc')
return DotFile(p... |
# Generated by Django 2.0.4 on 2018-06-19 01:41
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(au... |
from abc import ABCMeta, abstractmethod
from ..helpers import shell_helper
class AbstractResource(object):
__metaclass__ = ABCMeta
AFTER_TASKS_KEY = 'after_tasks'
@abstractmethod
def __init__(self, properties, global_variables=None):
self.properties = properties
self.global_variable... |
import math
import numpy as np
import statsmodels.api as stat
from scipy import stats
from matplotlib import pyplot as plt
#Question 1
alpha = 0
theta = 0
beta = 0.015
sigma_u = 0.053
sigma_v = 0.044
rho = -0.2 #-0.2 #-0.5
sigma_uv = rho*sigma_u*sigma_v
mean = [0, 0]
cov = [[sigma_u**2, sigma_uv], [sigma_uv, sigma... |
"""
Hash table - example
"""
import ads_02_00_DB as DB
from B_Data_Structures.hashtable import HashTable
#ht.HashTable.SIZE = 20
def main():
agenda = HashTable()
print(agenda)
print()
for user in DB.user_to_add:
if agenda.insert(user[0], user):
print("User was a... |
###########################################################################
###########################################################################
##################TEST FUNCTION############################################
###########################################################################
################... |
from django.contrib import admin
from .models import DepartmentInfo, Designation, ExtraInfo, Faculty, Staff, HoldsDesignation
# Register your models here.
admin.site.register(ExtraInfo)
admin.site.register(Staff)
admin.site.register(Faculty)
admin.site.register(DepartmentInfo)
admin.site.register(Designation)
admin.... |
a = int(input('digite el primer nro '))
b = int(input('digite el segundo nro '))
if a == b:
print('SON IGUALES')
|
#!/usr/bin/python
#-*- coding:utf-8 -*-
# 百度翻译 API 文档:http://api.fanyi.baidu.com/api/trans/product/apidoc
import httplib
import md5
import urllib
import random
import re
import json
import os
import sys
kBaiduAppID = 'Please generate from you Baidu developer center' # 百度开发管理后台申请的 AppID
kBaiduSecretKey = 'Please... |
from core.framework.module import FridaModule
class Module(FridaModule):
meta = {
'name': 'Title',
'author': '@AUTHOR (@MWRLabs)',
'description': 'Description',
'options': (
),
}
# ========================================================================... |
from django.urls import path
from .views import teacher as teacher_view
from .views import student as student_view
from .views import notification as notification_view
from .views import common as common_view
from .views import statistics as statistics_view
urlpatterns = [
path('', common_view.index, name='index'... |
import torch
from torch.nn import functional as F
import torch.nn as nn
import math
from ..model_utils.weight_process import _fill_fc_weights, _HEAD_NORM_SPECS
from ..model_utils.center_based_utils import sigmoid_hm, select_point_of_interest, nms_hm, select_topk
def get_channel_spec(reg_channels, name):
if name =... |
from django.test import TestCase
from django.forms.models import model_to_dict
from nose.tools import eq_
from apps.assist.unittests.factories import NoticeFactory, BannerFactory, SplashFactory
from apps.assist.serializers import NoticeCreateSerializer, BannerCreateSerializer, SplashCreateSerializer
class TestNotice... |
"""Loading and plotting data from CSV logs.
Schematic example of usage
- load all `log.csv` files that can be found by recursing a root directory:
`dfs = load_logs($BABYAI_STORAGE)`
- concatenate them in the master dataframe
`df = pandas.concat(dfs, sort=True)`
- plot average performance for groups of runs using ... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
try:
from buildbot_pkg import setup_www_plugin
except ImportError:
import sys
print("Please install buildbot_pkg module in order to install that package, or use the pre-build .whl modules available on pypi", file=sys.st... |
#追加ライブラリ
import urllib
import xml.etree.ElementTree as elementtree
import MeCab
import random
WIKI_URL = u"http://wikipedia.simpleapi.net/api?keyword="
class CreateResult:
senryu = ''
furigana = ''
errormessage = ''
word = ''
url = ''
def createSenryu(serch_word):
utftext = serch_... |
from django_filters import rest_framework as filters
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from care.facility.api.mixins i... |
# Copyright 2020 DeepMind Technologies Limited. 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 ... |
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
x = r.get('foo')
print(x)
r.set(x,'baz')
x = r.get(x)
print(x)
|
from dynamic_graph.sot.torque_control.control_manager import ControlManager
from dynamic_graph.sot.torque_control.tests.robot_data_test import initRobotData
from numpy import array, ones, zeros
# Instanciate the free flyer
cm = ControlManager("cm_test")
q = zeros(initRobotData.nbJoints + 6)
dq = zeros(initRobotData.n... |
from .Node import Node
from Utils.config import *
from Utils.constants import *
class LoopNode(Node):
def __init__(self, depth, node_type, anchor):
super().__init__(depth, node_type, anchor.get_regex())
self.go_back = anchor.is_goback_anchor()
def __str__(self):
return f"Node {self.type} (simple) to {self.l... |
'''
Author: W.R. Jackson, Damp Lab 2020
'''
import datetime
import logging
import sys
import colorama
class SingletonBaseClass(type):
_instances = {}
def __call__(cls, *args, **kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
... |
'''
Created on 2013/04/25
@author: duongnt
'''
import numpy as np
from scipy.linalg import eig
from scipy import spatial # for kdtree
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
def loadData(file... |
import numpy as np
class ARMA:
"""Class that generates WN, AR, MA and ARMA processes."""
@staticmethod
def generate_wn(n, sigma=1):
"""Generates a white noise series.
The code follows:
y_{t} = \epsilon_{t}
Args:
n: length of the series.
sigma: sta... |
""" Implementação do algoritmo de busca binária com recursão """
def busca_binaria(valor, vetor, esquerda, direita):
"""
Implementação de um algoritmo de busca binária com recursão.
Argumentos:
valor: Any. Valor a ser buscado na lista
vetor: list. lista ordenada na qual o valor será buscado
e... |
"""
Utilities for working with datasets in
`CVAT format <https://github.com/opencv/cvat>`_.
| Copyright 2017-2020, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
from collections import defaultdict
from datetime import datetime
import logging
import os
import jinja2
import eta.core.data as etad
import e... |
#take user inputs for time period
timePeriod = input("Time Period : ")
timePeriod = float(timePeriod)
#take user inputs for number of times
noOfTimes = input("Number of times : ")
noOfTimes = float(noOfTimes)
#take user inputs for peak time feature
peakTime = input("Peak time (Y /N) : ")
while peakTime != "Y" and pe... |
import tensorflow as tf
def discriminator(x):
with tf.variable_scope("discriminator"):
fc1 = tf.layers.dense(inputs=x, units=256, activation=tf.nn.leaky_relu)
fc2 = tf.layers.dense(inputs=fc1, units=256, activation=tf.nn.leaky_relu)
logits = tf.layers.dense(inputs=fc2, units=1)
... |
import os
from unittest.mock import patch
from click.testing import CliRunner
from mindmeld import cli
from mindmeld.cli import clean, num_parser
def test_num_parse_already_running(mocker):
runner = CliRunner()
with patch("logging.Logger.info") as mocking:
mocker.patch.object(cli, "_get_duckling_pid... |
import sys
import pygame
import random
SCREEN = pygame.display.set_mode((640, 480))
class Missile(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('images/missile/missile.png').convert_alpha()
self.rect = self.image.get_rect()
... |
import pymongo
from bson.objectid import ObjectId
from pyzotero import zotero
from getpass import getpass
from sys import argv
if __name__ == '__main__':
#passwd = getpass ("Password: ")
mongo = pymongo.Connection ('localhost', 27017)['refs'] #test
#mongo = pymongo.Connection('localhost', 3002)['meteor']
... |
"""
PyTorch implementation of paper "A Neural Algorithm of Artistic Style".
Helper functions.
@author: Zhenye Na
@references:
[1] Leon A. Gatys, Alexander S. Ecker, Matthias Bethge
A Neural Algorithm of Artistic Style. arXiv:1508.06576
"""
import os
import torch
import torch.nn as nn
from PIL import Ima... |
##******** 1- QUICK PYTHON EXERCISES FOR DATA SCIENCE / PART 1 ##*********
#1 What is virtual environment ?
# In short [*] : Creating a virtual environment to isolate projects with different needs.
# Different versions of libraries, packages or modules can be kept.
# They can work without affecting each other.
... |
import os
import sipconfig
#CAS: this is a win32 version, specific to my machine, provided for example.
# The name of the SIP build file generated by SIP and used by the build
# system.
build_file = "blist.sbf"
# Get the SIP configuration information.
config = sipconfig.Configuration()
# Run SIP to gene... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Code heavily inspired by:
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
#
# Modified by:
# author: John Bass
# email: john.bo... |
# Generated by Django 3.0 on 2021-03-07 20:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lms_app', '0004_auto_20210228_2000'),
]
operations = [
migrations.AddField(
model_name='video',
name='vimeo_video',
... |
#!/usr/bin/python
import Queue
import subprocess
import os
import datetime
import argparse
import shutil
import multiprocessing
from celery import Celery
from gridmaster import submit
from gridmaster import getwork
from gridmaster import donework
def main():
parser = argparse.ArgumentParser()
parser.add_argument(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
from sklearn import base, cross_validation
from sklearn.externals import joblib
from .sofia_ml import svm_train, learner_type, loop_type, eta_type
class RankSVM(base... |
# Importing the Libraries
import tensorflow as tf
import nni
# loading the MNIST dataset & performing the Normalization
def load_dataset():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
return (x_train/255., y_train), (x_test/255., y_test)
# Creating the Sequential Mo... |
""" test get/set & misc """
import pandas as pd
from pandas import MultiIndex, Series
def test_access_none_value_in_multiindex():
# GH34318: test that you can access a None value using .loc through a Multiindex
s = Series([None], pd.MultiIndex.from_arrays([["Level1"], ["Level2"]]))
result = ... |
import base64
import gzip
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from yarl import URL
def _generate_download_link(base_url: URL, code: str) -> URL:
return base_url.with_query(gzip=base64.urlsafe_b64encode(gzip.compress(code.encode())).decode())
async def g... |
import copy
import random
import sys
# ------------------------------------------------------------------
def aux_print (elem):
if elem == 0:
return " . "
if elem == 1:
return " X "
if elem == -1:
return " O "
def mostra_tabuleiro(T):
for x in range (0,(9)):
if (x == 3 or x == 6):
print ("\n")
print ... |
#!/usr/bin/python
# -*- coding:UTF-8 -*-
if __name__ == '__main__':
l1 = [3, [66, 55, 44], (7, 8, 9)]
l2 = list(l1)
l1.append(100)
l1[1].remove(55)
print('l1:', l1)
print('l2:', l2)
l2[1] += [33, 22]
l2[2] += (10, 11) # +=对雨元组来说,相当于创建了一个新的元组。
print('l1:', l1)
print('l2:', l2)
|
import json
import unittest
from libsaas import port
from libsaas.executors import test_executor
from libsaas.services import googlecalendar
from libsaas.services.base import MethodNotSupported
class GoogleCalendarTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""The Controller class for Cities."""
import re
from flask import Blueprint, render_template, redirect, url_for, current_app, \
request, abort, flash
from modules.Countries.model import Country
from modules.Regions.model import Region
from modules.Cities.model import City... |
from __future__ import print_function, absolute_import
from .image import ImageSoftmaxEngine, ImageTripletEngine,ImageHardTripletEngine
from .video import VideoSoftmaxEngine, VideoTripletEngine
from .engine import Engine
|
#!/data/data/com.termux/files/usr/bin/python
# Update : (2020-09-03 23:04:09)
# Finish : Now!
# © Copyright 2020 | Ezz-Kun | kyun-kyunnn
from bs4 import BeautifulSoup as bs_
from os import system as _Auth
from string import ascii_letters as _ascii
from time import sleep
from random import randint
import requests as req... |
# This script has been designed to perform multi-objective learning of core sets
# by Alberto Tonda and Pietro Barbiero, 2018 <alberto.tonda@gmail.com> <pietro.barbiero@studenti.polito.it>
#basic libraries
import argparse
import copy
import datetime
import inspyred
import matplotlib.pyplot as plt
import numpy as np
i... |
# rndly.py
import numpy as np
import time
class RNDLy:
def __init__(self):
self.name = 'rndly'
def predict(self,queryList):
lo = 0.0
hi = 1.0
n = len(queryList)
preds = np.random.uniform(lo,hi,n)
preds = preds.tolist()
time.sleep(0.5)
return pr... |
from .YelpAPI import YelpAuth
from .YelpAPI import YelpAPI
from .HereAPI import HereAuth
from .HereAPI import HereAPI
|
#!/usr/bin/python
#############################################################################
# Range cleanup program
#############################################################################
import os
import sys
import subprocess
import logging
import parse_config
logging.basicConfig(level=logging.INFO, form... |
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root
DATA_DIR = os.path.join(ROOT_DIR, 'data')
|
import numpy
import plotly.figure_factory as figure_factory
import plotly.graph_objs as graph_objs
import plotly.offline as offline
# Configure plotly to run in offline mode
offline.init_notebook_mode(connected=False)
def make_bar_chart(columns, title='', x_axis=''):
"""Takes an array of dictionaries that have t... |
#!/usr/bin/env python3
"""Parse a directory contains Librispeech dataset.
Recursively search for "*.trans.txt" file in the given directory and print out
`<ID>\\t<AUDIO_PATH>\\t<TRANSCRIPTION>`
example: python parse_librispeech.py LibriSpeech/test-clean
1089-134691-0000\t/LibriSpeech/test-clean/1089/134691/1089-... |
#!/usr/bin/env python
# DiabloHorn - QIBA_server_poc
# Bypassing IP whitelisting using quantum inject
import sys
import time
import socket
import collections
from scapy.all import *
"""
iptables -A OUTPUT -p tcp --tcp-flags RST RST -s <ip> -j DROP
"""
STATE_TEMP = []
CMD_DATA = collections.OrderedDict()
def pkt_inspe... |
import time
from uuid import uuid4
from emmett import App, request, response
from emmett.tools import service
app = App(__name__)
app.config.handle_static = False
@app.route(methods=["get"], output="str")
async def html():
"""Return HTML content and a custom header."""
response.headers["x-time"] = f"{time.... |
import csv
from datetime import datetime
from lurge_types.group_report import GroupReport
from directory_config import REPORT_DIR
import logging
import logging.config
from lurge_types.user import UserReport
import typing as T
def createTsvReport(group_reports: T.Dict[str, T.List[GroupReport]], date: str, report_dir: ... |
import arrow
from optional import Optional
from eynnyd.exceptions import InvalidCookieBuildException
from eynnyd.internal.utils.cookies import rfc
from eynnyd.internal.utils.cookies.response_cookie import ResponseCookie
class ResponseCookieBuilder:
"""
Response cookies are generally just key-value pairs but ... |
# pylint: disable=missing-function-docstring,missing-module-docstring, protected-access
from unittest.mock import AsyncMock, patch
import pytest
from custom_components.hacs.base import HacsBase, HacsRepositories
from custom_components.hacs.enums import HacsDisabledReason
from custom_components.hacs.exceptions import ... |
#!/usr/bin/env python3
from unittest import TestCase, main
from graph2tensor.model.data import EgoTensorGenerator, build_output_signature
from graph2tensor.model.data import build_sampling_table
from graph2tensor.model.data import SkipGramGenerator4DeepWalk
from graph2tensor.model.data import SkipGramGenerator4Node2Ve... |
import speech_recognition as sr
import webbrowser
import wikipedia
import requests
import pyttsx3
import urllib
import random
import json
import lxml
import math
import time
import bs4
import os
from nltk.corpus import wordnet as wn
from bs4 import BeautifulSoup as soup
from time import gmtime, strftime
... |
from app import runWebsite
runWebsite()
|
# -*- coding: utf-8 -*-
# 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。
from PIL import Image, ImageFont, ImageDraw
def add_num(img):
im = Image.open(img)
w, h = im.size
font = ImageFont.truetype('/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf', 30)
fillcolor = "#ff0000"
draw = Ima... |
"""
MIT License
Copyright (c) 2021 mooncell07
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, di... |
from dependency_injector import containers
from fdap.config.config import Config
from fdap.utils.customlogger import CustomLogger
from fdap.utils.loggeradapter import LoggerAdapter
from typing import Callable
class Application:
_container: containers.DeclarativeContainer
_logger: LoggerAdapter
def __init... |
# Copyright 2020 Alibaba Group Holding Limited. 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 ... |
'''
(1) - Indique como um troco deve ser dado utilizando-se um número mínimo de notas. Seu
algoritmo deve ler o valor da conta a ser paga e o valor do pagamento efetuado desprezando
os centavos. Suponha que as notas para troco sejam as de 50, 20, 10, 5, 2 e 1 reais, e que
nenhuma delas esteja em falta no caixa
'''... |
# -*- coding: utf-8 -*-
"""
@object: weibo & twitter
@task: split train & test, evaluate performance
@author: majing
@variable: T,
@time: Tue Nov 10 16:29:42 2015
"""
import sys
import random
import os
import re
import math
import numpy as np
################## evaluation of model result ###########... |
from src.gui.Server import Server
server = Server()
|
import json
from alibaba_cloud_secretsmanager_client.model.client_key_credentials import ClientKeyCredential
from alibaba_cloud_secretsmanager_client.model.credentials_properties import CredentialsProperties
from alibaba_cloud_secretsmanager_client.model.region_info import RegionInfo
from aliyunsdkcore.auth import cre... |
# flake8: noqa
"""
__init__.py for import child .py files
isort:skip_file
"""
# Utility classes & functions
import pororo.tasks.utils
from pororo.tasks.utils.download_utils import download_or_load
from pororo.tasks.utils.base import (
PororoBiencoderBase,
PororoFactoryBase,
PororoGenerationBase,
P... |
from . import algorithms, buffers, noise, transition
__all__ = ["algorithms", "buffers", "noise", "transition"]
|
"""Copyright 2018 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
from keras.layers import Conv2D, Input,MaxPool2D, Reshape,Activation,Flatten, Dense,concatenate
from keras.models import Model, Sequential
from keras.layers.advanced_activations import PReLU
from keras.optimizers import adam
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
impor... |
import enum
from sqlalchemy import Column, VARCHAR, Integer, Boolean, TIMESTAMP, ForeignKey, CheckConstraint
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy.ext.hybrid import hybrid_property
# local imports
from .base import Base
class GameStatuses(enum.Enum):
"""Holds info... |
# Problem: https://www.hackerrank.com/challenges/np-mean-var-and-std/problem
# Score: 20.0
import numpy as np
n,m = map(int, input().split())
my_array = np.array([input().strip().split() for _ in range(n)], int)
print(np.mean(my_array, axis=1), np.var(my_array, axis=0), np.around(np.std(my_array), decimals=11), sep=... |
import re
from moban.plugins.jinja2.extensions import JinjaFilter
GITHUB_REF_PATTERN = "`([^`]*?#[0-9]+)`"
ISSUE = "^.*?" + GITHUB_REF_PATTERN + ".*?$"
SAME_PROJ_FULL_ISSUE = "`#{3} <https://github.com/{0}/{1}/{2}/{3}>`_"
DIFF_PROJ_FULL_ISSUE = "`{1}#{3} <https://github.com/{0}/{1}/{2}/{3}>`_"
PULL_REQUEST = "PR"
PUL... |
# -*- encoding: utf-8 -*-
from django import forms
from camara_zona.models import CamaraZona
#from cliente.models import Cliente
from instalacion.models import Instalacion
from monitor.models import Monitor
class MonitorForm(forms.ModelForm):
id = forms.CharField(widget=forms.HiddenInput, required=False, initial=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.