content stringlengths 5 1.05M |
|---|
from _context import kgmodels
from kgmodels import util
from util import d
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
import rdflib as rdf
import pandas as pd
import numpy as np
import random, sys, tqdm
from tqdm import trange
import rgat
from argparse i... |
import sys
import logging
from config_parser import cfg
from logging.handlers import TimedRotatingFileHandler
logging.getLogger("qrcode_machinecontrol").setLevel(logging.ERROR)
log_formatter = logging.Formatter("%(asctime)s.%(msecs)03d %(levelname)7s %(processName)10s - %(message)s", "%H:%M:%S")
mylogger = log... |
#!/usr/bin/env python
"""Create lxc-conf.yml"""
# Copyright 2018 IBM Corp.
#
# 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/LIC... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for source in orm.Source.objects.all():
if source.visibility == 'i':
source.visibility = 'v'
... |
from flask import current_app as app
from flask import Blueprint, render_template
from flask import session, request
from flask import redirect, url_for, abort
from werkzeug.routing import RequestRedirect
from .discord import make_session, get_twitch_name, add_role, DISCORD_AUTH_BASE_URL, DISCORD_TOKEN_URL
from .twitc... |
# Copyright 2021 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from a10.rules import baserule
import a10.utils.constants
class TestQuote(baserule.BaseRule):
def __init__(self, cid, ps):
super().__init__(cid, ps)
self.description = "TestQuote Test Rule Ru... |
import numpy as np
import openmc
from collections.abc import Iterable
def legendre_from_expcoef(coef, domain=(-1, 1)):
"""Return a Legendre series object based on expansion coefficients.
Given a list of coefficients from FET tally and a array of down, return
the numpy Legendre object.
Parameters
... |
# Configuration for quiz maker
quiz_configurations = {
"amount_songs":50,
"guessing_time":15,
"result_time":5,
}
# File related configurations
file_configurations = {
"output_folder":"Output",
"output_file_name":"Automated guess album",
"output_file_extension":"mp4",
"input_folder":"songs",... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 10:42:30 2019
@author: ghosh128
"""
import sys
sys.path.append("../../")
import os
import config
import numpy as np
import tensorflow as tf
from collections import defaultdict
from sklearn.metrics import f1_score
import matplotlib.pyplot as plt
... |
import click
import random
import time
from gameoflife.Game import Game
def random_pop(width, height, initialpop):
"""Populate the board randomly, with specified population percentage."""
initial_state = [
[ True if random.random() > (1 - initialpop/100) else False
for y in range(0, height) ]
for x... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Pattern.search(string[, pos[, endpos]])
"""
import re
def test1():
pattern = re.compile("d")
match = pattern.search("dog") # Match at index 0
print(match) # <_sre.SRE_Match object; span=(0, 1), match='d'>
# No match; search doesn't include the "d"... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
"""
tf2onnx.rewrite - rewrite tensorflow subgraph to onnx random_uniform op
"""
from tf2onnx.graph_matcher import OpTypePattern, GraphMatcher
from tf2onnx import utils
# pylint: disable=missing-docstring
def ... |
# Lemoneval Project
# Author: Abhabongse Janthong <6845502+abhabongse@users.noreply.github.com>
"""Parameter classes for each attribute in exercise frameworks."""
from typing import Sequence
from ..utils.argdefault import EMPTY_DEFAULT
class BaseParameter(object):
"""Parameter descriptor for framework classes.
... |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... |
#!/usr/bin/env python3
import glob, os, shutil, time
print('File watcher started')
while True:
i = 0
while True:
i = i + 1
shareEnable = os.getenv('PROXY{}_ENABLE'.format(i))
if shareEnable == None:
break
elif not shareEnable == "1":
continue
shareDirectory = '/share{}'.format(i)... |
import numpy as np
import pytest
from numpy.testing import assert_equal, assert_almost_equal
from skimage import data
from skimage._shared._warnings import expected_warnings
from skimage.metrics import (peak_signal_noise_ratio, normalized_root_mse,
mean_squared_error, normalized_mutual_inf... |
"""
# Details:
# Migration Tool
# Usage:
# python databaseMigrate.py db init
# Authors:
# Andrej Berg
# Michael King
# History:
# -
# Last modified: 12.07.2018
# ToDo:
# -
# Bugs:
# -
"""
__author__ = ["Andrej Berg", "Michael King"]
__date__ = "17.04.2018"
from flask import Flask
from flask_sqlalc... |
#! /usr/bin/env python3
#encoding: UTF-8
from os import *
import traceback
import sys, random
try:
(rd, wd) = pipe()
if fork():
# père
N = random.randint(0,0xFFFFFFFF)
print ("envoi de : ", N)
close(rd)
write(wd,N.to_bytes(4, sys.byteorder))
close(wd)
ex... |
#
# PySNMP MIB module WL400-GLOBAL-REG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WL400-GLOBAL-REG
# Produced by pysmi-0.3.4 at Wed May 1 15:36:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
import argparse
import torch
from torchvision import datasets
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
class Generator(nn.Module):
''' Definition of the generator class
''... |
from pydantic import AnyUrl, ValidationError, BaseModel
from typing import List, Dict, Optional, Any
from enum import Enum
class DataciteIdentifier(BaseModel):
class DataciteIdentifierType(Enum):
DOI="DOI"
identifier: str = ""
identifierType: DataciteIdentifierType
class DataciteCreator... |
### only inferencing
### with 100 images of COCO test2017 dataset
# reference : https://tutorials.pytorch.kr/beginner/transfer_learning_tutorial.html
# ResNet, GoogLeNet
import torch
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions
import torch.optim as optim # For ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import io
import time
import random
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import winsound
CONFIG_FILE = './config_toefl.json'
BROWSER_WAIT_TIME = 5
HOST = 'toefl.neea.cn'
FRONT_PAGE_URL = 'https://' + HOST
BASE_LOGIN... |
"""
API operations on remote files.
"""
import os
import time
import hashlib
from galaxy import exceptions
from galaxy.web import _future_expose_api as expose_api
from galaxy.util import jstree
from galaxy.web.base.controller import BaseAPIController
from operator import itemgetter
import logging
log = logging.getLogg... |
# Standard library imports
from typing import TYPE_CHECKING
# Related third party imports
import pytest
# Local application/library specific imports
if TYPE_CHECKING:
from pyaww import AlwaysOnTask, User
@pytest.mark.asyncio
async def test_restart(always_on_task: "AlwaysOnTask") -> None:
assert await alw... |
'''Creates latex table row to log experiment results'''
def create_latex_table_row(results_dict, model_name, train_name = "multinli"):
f = open("./results/"+model_name+"_"+train_name+"_results.txt", "w")
latex_string = model_name+" & "
if "Numerical Stress Test" in results_dict:
latex_string +=st... |
"""Token bucket throttle backed by Redis."""
import time
import pkg_resources
KEY_FORMAT = 'throttle:{}'
# throttle knob defaults
THROTTLE_BURST_DEFAULT = 1
THROTTLE_WINDOW_DEFAULT = 5
THROTTLE_REQUESTED_TOKENS_DEFAULT = 1
# The default is to extend a throttle's knob settings TTL out
# 7 days each time the throttl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 14:13:05 2019
@author: matusmacbookpro
"""
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torchvision
#adapted from: https://github.com/NVlabs/Deep_Object_Pose/blob/master/scripts/train... |
import pytest
from vlde import Validator, ValidateError, RulesError
def test_str():
'''test str type'''
v = Validator()
v.set_rules('hello', 'str|string')
v.set_rules('', 'str|string')
v.set_rules(str(123), 'str|string')
with pytest.raises(ValidateError):
v.set_rules(123, 'str')
... |
import pixels
pixels.Pixels().brightness_decrease(step = 10)
|
"Yang/Wu's OEP implementation, in PyQuante."
from math import sqrt
import settings
from PyQuante.NumWrap import zeros,matrixmultiply,transpose,dot,identity,\
array,solve
from PyQuante.Ints import getbasis, getints, getJ,get2JmK,getK
from PyQuante.LA2 import geigh,mkdens,trace2,simx
from PyQuante.hartree_fock impo... |
from balebot.models.messages.json_message import JsonMessage
from balebot.filters.filter import Filter
class JsonFilter(Filter):
def match(self, message):
return isinstance(message, JsonMessage)
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
def get_package_data():
formats = "fits root xml json conf txt csv".split()
files = ["data/*.{}".format(_) for _ in formats]
return {"gammapy.irf.tests": files}
|
from os.path import join, dirname
from ovos_plugin_common_play.ocp import MediaType, PlaybackType
from ovos_utils.parse import fuzzy_match, MatchStrategy
from ovos_workshop.skills.common_play import OVOSCommonPlaybackSkill, \
ocp_search
from tutubo import YoutubeSearch
from tutubo.models import *
class YoutubeFu... |
class Base(object):
def configure(self):
pass
def get_include_paths(self):
return []
def get_lib_paths(self):
return []
def get_static_lib_paths(self):
return []
def get_libs(self):
return []
def get_static_libs(self):
return []
def get_linkflags(self):
return []
def get_static_linkflags(se... |
from . import __version__, client
print('\u001b[38;5;208m\033[1mGroupManagerBot is running.. version %s\033[0m' % __version__)
client.run() |
# 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 u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Loic Jaquemet loic.jaquemet+python@gmail.com
#
import logging
log = logging.getLogger('view')
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.Qt import Qt
from .. import model
LINE_SIZE = 512
PAGE_SIZE = 4096
# LINE_SIZE=512*4
# PAGE_SIZE=4... |
#
# Post social media broadcast about news.
#
# This doesn't actually make a post -- it just places them in the
# outbound queue for the global social media script to handle.
#
# Copyright (C) 2019, PostgreSQL Europe
from django.core.management.base import BaseCommand
from django.db import transaction
from django.uti... |
#!C:/Users/Kushang Darbar/AppData/Local/Programs/Python/Python38-32/python
#print("Content-Type:text/html; charset=utf-8\n\n")
print()
import cgi
#!/usr/bin/env python
# coding: utf-8
import cv2
import os
import numpy as np
import FaceRecognition as fr
import retrieve as rt
import cgitb
cgitb.enable()
form = cgi.Fiel... |
import random
import string
from unittest import mock
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase
from django.urls import reverse
from django.utils.crypto import get_random_string
from mtp_common.auth.api_client import MoJOAuth2Session
from mtp_common.auth.test_... |
import os
import sys
import time
import subprocess
from tornado import gen
from traitlets import Dict
from jupyterhub.utils import random_port
from jupyterhub.spawner import Spawner
__all__ = ['SGESpawner']
class SGESpawner(Spawner):
sge_env = Dict({}, config=True,
help="Extra SGE environ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-28 11:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("challenges", "0006_changed_path_to_upload")]
operations = [
migrations.RenameModel(
... |
import random
import re
import subprocess
import time
from threading import Thread
import httpx # type: ignore
import pytest
import mosec
TEST_PORT = "8090"
URI = f"http://localhost:{TEST_PORT}"
@pytest.fixture(scope="module")
def http_client():
client = httpx.Client()
yield client
client.close()
@p... |
#!/usr/bin/env python
import os
import click
import pandas as pd
import numpy as np
@click.command()
@click.argument('orig_csv', type=click.Path())
@click.argument('out_csv', type=click.Path())
def clean_afm_db(orig_csv, out_csv):
df_mg = pd.read_csv(orig_csv) # open csv to dataframe
df_mg = df_mg.loc[0... |
t = int(input())
for _ in range(t):
r, s = input().split()
r = int(r)
print(''.join(c for c in s for _ in range(r)))
|
class Pattern_Twenty_Nine:
'''Pattern twenty_nine
***
* *
* *
* *
* *
* *
***
'''
def __init__(self, strings='*'):
if not isinstance(strings, str):
strings = str(strings)
for i in range(7)... |
"""
The project is developed as part of Computer Architecture class.
Project Name: Functional Simulator for subset of RISC-V Processor
-------------------------------------------------
| Developer's Name | Developer's Email ID |
|-----------------------------------------------|
| Akhil Arya | 2019csb1066... |
# coding=utf-8
import cv2
import numpy as np
import os
import glob
from img_tool import *
# args
MPIIGAZE_path='D:\\winpython\\py36\\work\\eye-gaze\\MPIIGaze'
# TO DO
todo=1
# 0 test a image
TXT= "p01"
INDEX=11
# 1 output darknet dataset format
RE_size=0
OUTPUT_folder = "C:\\dataset\\gaze_o"
# 2 test output darknet tx... |
import linear_algebra.linear_algebra_core as core
import modeling.helpers.regression_metrics as reg_met
import modeling.helpers.regression_evaluation as reg_eval
import modeling.helpers.nn_distances as nn_dist
from tabulate import tabulate
from scipy.stats import f, t
# TODO: add preprocessing for categorical variabl... |
import os
import subprocess
config = get_config()
# Use GitHub OAuth to authenticate users
config.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
config.GitHubOAuthenticator.oauth_callback_url = 'https://206.12.96.12/hub/oauth_callback'
config.GitHubOAuthenticator.client_id = 'a4b7e7154c6f9d8497... |
"""File containing the shared constants of the tests
.. moduleauthor:: Armand BENETEAU <armand.beneteau@iot.bzh>
*Date: 26/07/2019*
*License:*
*Copyright (C) 2019 "IoT.bzh"*
*Licensed under the Apache License, Version 2.0 (the "License");\
you may not use this file except in compliance with the License.... |
from more.webassets import WebassetsApp
class MapboxApp(WebassetsApp):
""" Provides mapbox integration
:class:`onegov.core.framework.Framework` based applications.
Doesn't do much except serve the mapbox public token, so we can store it
in configuration and not with the source. Not that this token is... |
import io
import os
import unittest
from stango import Stango
from stango.files import Files
from . import StangoTestCase, make_suite, view_value, view_template
dummy_view = view_value('')
class GenerateTestCase(StangoTestCase):
def setup(self):
self.tmp = self.tempdir()
self.manager = Stango()
... |
# -*- coding: utf-8 -*-
from os import environ
import pytest
import rethinkdb
def pytest_addoption(parser):
group = parser.getgroup('rethinkdb')
group.addoption(
'--rethinkdb-host',
action='store',
dest='rethinkdb_host',
default='localhost',
help='Host of the Rethink... |
from .curl_connector import CurlConnector
|
from typing import List
from operations import Operation, tabs
from operations.variable import *
class Split(Operation):
"""The split operation parallelize a number of operations, the execution time is the time of the longest path"""
ops: [Operation] = []
def __init__(self, *args):
self.ops = li... |
# 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 the Li... |
from mock import patch
from data import word_frequencies
from spec.mamba import *
patcher = patch.object(word_frequencies.data, 'open_project_path')
_SMALL_FILE = textwrap.dedent("""
the 23135851162
of 13151942776
and 12997637966
to 12136980858
a 9081174698
in 8469404971
for 5933321709
... |
from sentiment_analysis import SentimentAnalysis
import pandas as pd
from tqdm import tqdm
import os
import random
import numpy as np
seed = 42
random.seed(seed)
np.random.seed(seed)
def check_bias(results, alpha):
'''decide whether it's bias given prediction results of mutants'''
is_bias = False
length ... |
from distutils.core import setup
from Cython.Build import cythonize
import numpy
setup(
name = 'Shift utility',
ext_modules = cythonize("shift.pyx"),
include_dirs=[numpy.get_include()]
)
|
from histogram import frequency
def histogram():
with open('twelve_years.txt', 'r') as f:
myList = f.read().split(" ")
total_word_count = len(myList)
final_dictionary = frequency(myList)
return final_dictionary
my_dictionary = histogram()
def intermediate_histogram(my_dictionary):
... |
#2-3
# name = "kristen"
# print(f"Hello, {name.title()} would you like to learn some Python today?")
#2-4
# name = "aleX"
# print(name.title())
# print(name.upper())
# print(name.lower())
#2-5 and 2-6
quote = '"And now that you don\'t have to be perfect, you can be good."'
author = "John Steinbeck"
print(f"{author} o... |
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos
e vai retornar um dicionário com as seguintes informações:
– Quantidade de notas
- A maior nota
– A menor nota
– A média da turma
– A situação (opcional)"""
def notas(* num, s=False):
"""
-> Função para coletar notas dos ... |
##############################################
# The MIT License (MIT)
# Copyright (c) 2014 Kevin Walchko
# see LICENSE for full details
##############################################
# -*- coding: utf-8 -*
from opencv_camera.color_space import bgr2gray, gray2bgr
import numpy as np
import cv2
class ApriltagMarker:
... |
matriz1 = []
for i in range(4):
matriz1.append(list(map(int, input(
f"Digite os 5 elementos da linha {i + 1} divididos por espaço: ").split())))
matriz2 = []
for i in range(5):
matriz2.append(list(map(int, input(
f"Digite os 2 elementos da linha {i + 1} divididos por espaço: ").split())... |
import stripe
from django.conf import settings
from django.shortcuts import render, redirect, Http404
from django.http import JsonResponse
from .models import Cart
from accounts.models import GuestEmail
from addresses.forms import AddressForm
from addresses.models import Address
from accounts.forms import LoginForm, Gu... |
from app import app
from flask import jsonify, render_template, request
from rq.job import Job, NoSuchJobError
from worker import conn, queue
from .jobs import compute_path
from .requests import get_address_by_name, get_address_by_location
import json
# ENTRY ROUTE
@app.route("/")
def entry():
return render_templa... |
import ntpath
import cudf
from optimus.engines.base.io.load import BaseLoad
from optimus.engines.base.meta import Meta
from optimus.engines.cudf.dataframe import CUDFDataFrame
from optimus.helpers.functions import prepare_path, unquote_path
from optimus.helpers.logger import logger
class Load(BaseLoad):
def __... |
class Translator:
def __init__(self, template):
"""
Initializes the translator.
:param template: Dictionary with the translations.
key = translation key, value = translation.
"""
self.vocabulary = dict()
for k in template:
self.vocabulary[k] = temp... |
'''oData service CLI tests.'''
# !/usr/bin/env python3
# pylint: disable=protected-access,missing-function-docstring
from unittest.mock import Mock, patch
from mock import (
ConsoleOutputTestCase,
PatcherTestCase
)
import sap.cli.rap
from infra import generate_parse_args
from mock import Connection, Resp... |
#!/usr/local/bin/python
#coding=utf-8
import os
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import math
import csv
import urllib
import urllib2
import pywt
from numpy import log
import cwavelet
import copy
import cleastsq
import BP
date_begin = [1, 1, 2014]
date_end = [5, 27, 2015... |
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name='searchbot',
version='0.1.0',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='a simp... |
s = input()
i = 0
while i < len(s):
c1 = s[i]
if i == len(s) - 1:
print(c1, end='')
i += 1
continue
c2 = s[i + 1]
if c1.isalpha() and c2.isalpha():
print(c1 + ' ', end='')
else:
print(c1, end='')
i += 1
|
description = 'setup for the NICOS watchdog'
group = 'special'
# The entries in this list are dictionaries. Possible keys:
#
# 'setup' -- setup that must be loaded (default '' to mean all setups)
# 'condition' -- condition for warning (a Python expression where cache keys
# can be used: t_value stands for t/value e... |
# -*- coding: utf-8 -*-
import numpy as np
import warnings
import pandas as pd
import json
import time
import math
import secrets
from args import *
def load_json(filename):
"""Load json files in a given directory"""
data = []
with open(filename) as f:
for line in f:
data.append(json.... |
import abc
import sqlalchemy
from typing import List
from src.controller import action
import src.model.movie
import src.model.fields
import src.model.person
class AddMovie(action.ControllerAction):
""" Adds movie record if it doesn't exist, otherwise updates it """
def execute(
self, movie_title... |
# coding=utf-8
import os
import pickle
import re
from itertools import permutations
from itertools import product
import click
from backend.evaluation.summary import ResultsSummary
from generate_tests import COVERAGE_MAP
from generate_tests import HISTORY_MAP
@click.group()
def cli():
pass
@cli.command("per_s... |
"""
方策強化学習用ベースライン棋譜生成
yaneuraouのsearch(=駒得評価で数手読む)で自己対戦
yaneuraouの40バイトの形式の棋譜を出力する。評価値は意味なし。
ランダム性のため、最初に20手ランダムムーブしてから開始する。この部分は棋譜に含まない。
"""
import os
import sys
import argparse
import random
import struct
from tqdm import tqdm
from .move import Piece, Color, Move
from .position import Position, PositionHelper
pack_... |
import unittest
class Empty:
def __repr__(self):
return '<Empty>'
class Cmp:
def __init__(self,arg):
self.arg = arg
def __repr__(self):
return '<Cmp %s>' % self.arg
def __eq__(self, other):
return self.arg == other
class Anything:
def __eq__(self, other):
... |
import sys
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Union
from pydantic import UUID4, BaseModel, EmailStr, Extra, Field, HttpUrl, constr
from .services import KEY_RE, PROPERTY_KEY_RE, VERSION_RE
current_file = Path(sys.argv[0] if __name__ == "__main__" else __f... |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from ibemc.models import Subject
def landing(request):
return render(request, 'landing.html')
def ibemc_stats(request):
contact_list = Subject.objects.all()
assert len(concact_list) != 2014, "Wro... |
#!/usr/bin/env python3
# https://github.com/dietervanhoof/polybar-spotify-controls
import sys
import dbus
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'-t',
'--trunclen',
type=int,
metavar='trunclen'
)
parser.add_argument(
'-f',
'--format',
type=str,
metavar=... |
# -*- coding: utf-8 -*-
import logging
from django.db.transaction import commit_on_success
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from networkapi.api_rest import exceptions as api_exceptions
from networkapi.api_vip_request.faca... |
import contextlib
import typing
from pybuses.foundation import get_subscribed
from pybuses.types import (
Subscribable,
Listener,
)
class CommandBus:
def __init__(self, middlewares: typing.Optional[typing.List[typing.Callable]] = None) -> None:
if not middlewares:
middlewares = []
... |
# Copyright 2016 Canonical 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 in writing, s... |
from jaraco.windows.filesystem import trace_symlink_target
from optparse import OptionParser
def get_args():
parser = OptionParser()
options, args = parser.parse_args()
try:
options.filename = args.pop(0)
except IndexError:
parser.error('filename required')
return opti... |
# Copyright 2015 Google Inc. All Rights Reserved.
import datetime
import json
import logging
import os
import time
import httplib2
import webapp2
from apiclient import discovery
from google.appengine.api import app_identity
from oauth2client.appengine import AppAssertionCredentials
from oauth2client.client import Sig... |
from enum import Enum
from frozendict import frozendict
class Datasets(str, Enum):
MNIST = "MNIST"
CIFAR10 = "CIFAR10"
CIFAR100 = "CIFAR100"
COCO = "COCO"
PASCAL_VOC2012 = 'PASCAL_VOC2012'
STL10 = "STL10"
SVHN = "SVHN"
PHOTOTOUR = "PHOTOTOUR"
SBD = "SBD"
USPS = "USPS"
HMDB5... |
import os
import sys
here = sys.path[0]
sys.path.insert(0, os.path.join(here,'..'))
import time
import binascii
from coap import coap
from coap import coapOption as o
from coap import coapObjectSecurity as oscoap
import logging_setup
SERVER_IP = '::1'
# open
c = coap.coap(udpPort=500... |
from setuptools import setup, find_packages
setup(
name='fsm_strip_length_analysis',
version='1.0.1',
url='https://github.com/petarmaric/fsm_strip_length_analysis',
license='BSD',
author='Petar Maric',
author_email='petarmaric@uns.ac.rs',
description='Console app and Python API for strip l... |
# -*- coding: utf-8 -*-
"""
obspy.io.cnv - CNV file format support for ObsPy
================================================
This module provides write support for CNV event summary file
format as used by VELEST program.
:copyright:
The ObsPy Development Team (devs@obspy.org)
:license:
GNU Lesser General Pub... |
# -*- coding: utf-8 -*-
"""The Task Scheduler event formatter."""
from __future__ import unicode_literals
from plaso.formatters import interface
from plaso.formatters import manager
class TaskCacheEventFormatter(interface.ConditionalEventFormatter):
"""Formatter for a Task Scheduler Cache event."""
DATA_TYPE =... |
"""Notifier package responsible for user notification
"""
# std
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List
from enum import Enum
import logging
class EventPriority(Enum):
"""Event priority dictates how urgently
the user needs to be notified about it
"""... |
#!/bin/env python
# generate logarithmic waveform
import numpy as np
import matplotlib.pyplot as plt
import sys, getopt
from math import log
def normalise(w, minval, maxval):
ymin = min(w)
ymax = max(w)
for i in range(len(w)):
w[i] = minval + (w[i] - ymin) / (ymax - ymin) * (maxval - minval)
... |
from django.urls import path
from backend.consumers import SpeechConsumer
websocket_urlpatterns = [
path('ws/speech/', SpeechConsumer)
] |
import unittest
from werkzeug.datastructures import MultiDict
from .context import forms
class TestSmsInviteForm(unittest.TestCase):
def test_e164(self):
test_formats = ['(555) 555 5555', '555.555.5555', '(555)555.5555',
'5555555555']
for test_format in test_formats:
... |
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
def dedup_and_title_case_names(names):
"""Should return a li... |
""" Approximate e**0.5 Numerically and add error analysis"""
import math as m
n = 0.5
accuracy = 10000000
error = 0.0001
Analytical_value = m.exp(n)
print(f'The Analytical solution is {Analytical_value}')
def numerical_e(n):
sm = 0
i = 0
accuracy = 6
while i <= accuracy:
diff = (... |
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
def load_image(file_path):
return cv2.imread(file_path)
def extract_label(file_name):
return 1 if "dog" in file_name else 0
train_path = "C:/Users/Daniel/.keras/datasets/cats_and_dogs/"
image_files = os.listdir(tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.