content stringlengths 5 1.05M |
|---|
import cv2
import numpy
import os
import threading
class MotionDetection:
def __init__(self,**opts):
self.opts={"cam_id":0,"image_scale_factor":1,"max_color_diff":[10,10,10]}
self.opts.update(opts)
self.cap=cv2.VideoCapture(self.opts["cam_id"])
self.last_img=None
self.d_img=[]
self.motion=False
def ... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
"""
Script for plotting data from abundance output summary file from MOOG.
"""
# Use LaTeX and CMU Serif font.
rc('text', usetex=True)
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
# initialize default... |
# coding: utf-8
# Copyright (C) 2019 Nguyen Ngoc Sang, <https://github.com/SangVn>
from numpy import array, zeros, loadtxt, sin, cos, deg2rad
from re import findall
from .constants import gamma, gamma_m1, R_gas
def P2U(P):
U = zeros(4)
U[0] = P[0]
U[1] = P[0] * P[1]
U[2] = P[0] * P[2]
U[3] = P[3]... |
"""
Implemention of the Maze ADT using a 2-D array.
git repo - https://github.com/OlehPalka/maze
"""
import copy
from arrays import Array2D
from lliststack import Stack
class Maze:
"""Define constants to represent contents of the maze cells."""
MAZE_WALL = "*"
PATH_TOKEN = "x"
TRIED_TOKEN = "o"
d... |
# 2020-09-11
# This code was made for use in the Fu lab
# by Vasilis Niaouris
# Call me as: from units.angle import *
from scipy.constants import pi
# angle
radians = rad = 1. # default units
# smaller
milliradians = mrad = 1.e-3
# other units
degrees = deg = 180./pi
keys = dir()
angle_units_dict = {}
for key in ... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import compas
from compas_rhino.helpers import volmesh_from_polysurfaces
from compas_3gs.diagrams import ForceVolMesh
from compas_3gs.rhino import rhino_vertex_move
from compas_3gs.rhino import rhino_vertex_... |
# Lint as: python3
"""Test errors.py."""
import io
import math
import tempfile
import time
from pytype import metrics
import unittest
class MetricsTest(unittest.TestCase):
"""Tests for metrics infrastructure and the Counter class."""
def setUp(self):
super().setUp()
metrics._prepare_for_test()
def ... |
# Natural Language Toolkit: Parsers
#
# Author: Ewan Klein <ewan@inf.ed.ac.uk>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_statement
"""
Demo of how to combine the output of parsing with evaluation in a model.
Use 'python syn2sem.py -h' to find out the various... |
from django import forms
# class BookForm(forms.Form):
# title = forms.CharField(label="书名", required=True, max_length=50)
# pub_date = forms.DateField(label='出版日期', required=True)
from booktest.models import BookInfo
class BookForm(forms.ModelForm):
class Meta:
model = BookInfo
fields = ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Rounds",
"category" : "Modules",
"color": "grey",
"icon": "octicon octicon-file-directory",
"type": "module",
"label": _("Rounds"),
"type":"module",
"description":"... |
import pytest
from src.roads_and_libraries import roads_and_libraries, roads_and_libraries_ds
cases = [
(3, 2, 1, [[1, 2], [3, 1], [2, 3]], 4),
(6, 2, 5, [[1, 3], [3, 4], [2, 4], [1, 2], [2, 3], [5, 6]], 12),
]
@pytest.mark.parametrize("n, c_lib, c_road, cities, expected", cases)
def test_roads_and_librarie... |
class Node(object):
def __init__(self):
self.children = {} # contains a map with child characters as keys and their Node as values
class Trie(object):
def __init__(self):
self.root = Node()
self.root.data = "/"
def addWord(self, word):
currentNode = self.root
i =... |
#!/usr/bin/env python3
# used against output of
# glab api --paginate groups/cmbu-tvg/projects > cmbu-tvg_projects.json
# use xargs with '-P' to run 'git clone --recursive' on each repo
import json
with open('cmbu-tvg_projects.json', 'r') as f:
projects_json = json.loads(f.read().replace('}][{','},{'))
# prin... |
#
# Copyright (C) 2020 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
# pylint: disable=missing-docstring,invalid-name
from __future__ import absolute_import
import fortios_xutils.netutils as TT
import tests.common as C
class TestCase_10_functions(C.unittest.TestCase):
def test_20_subnet... |
import numpy as np
import pytest
from dft_dummy import bravis
NINETY = np.pi / 2
FOURTY_FIVE = np.pi / 4
COS45 = np.cos(FOURTY_FIVE)
ACOS0_5 = np.arccos(0.5)
VEC_FCC = np.array(
[
[0.5, 0.0, 0.5],
[0.5, 0.5, 0.0],
[0.0, 0.5, 0.5],
]
)
@pytest.fixture(
params=[
(
... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/env python
"""
@author: Jordan Graesser
Date Created: 8/8/2012
"""
from __future__ import division
from future.utils import viewitems
from builtins import dict
import os
import sys
import time
import argparse
from copy import copy
try:
from .errors import logger
from . import raster_tools, v... |
import numpy as np
import csv
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import DBSCAN
from sklearn.metrics import silhouette_score
from sklearn.metrics import calinski_harabaz_score
from sklearn.neighbor... |
import asyncio
import base64
import json
import os
from datetime import datetime, timedelta
import aiohttp
import requests
from colorama import Fore, Style
class Auth:
def __init__(self, email, password):
self.token = base64.b64encode((email + ":" + password).encode("utf-8")).decode("utf-8")
self.appId = '39bae... |
# ----------------------------------------------------------------------------
# Copyright (c) 2018-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
#!/usr/bin/python
from app import app
app.run(debug = True)
|
"""routing - gas tank strategy manager"""
from .graph import Graph
from .node import Node
from ..dao.db import StationDAO
def generate_tank_infos(capacity, timestamps_stations_prices):
"""generate routing informations,
capacity: int, the tank capacity
timestamps_stations_prices: lst<str, int, int>, the p... |
from dolfin import *
import PETScIO as IO
import numpy as np
def DirectErrors(x,mesh,FSpaces,ExactSolution,k,dim):
Vdim = dim[0]
Pdim = dim[1]
Mdim = dim[2]
Rdim = dim[3]
VelocityE = VectorFunctionSpace(mesh,"CG",k+2)
u = interpolate(ExactSolution[0],VelocityE)
PressureE = FunctionSpace... |
import pathlib
import warnings
class ROIManagerWarning(UserWarning):
"""Used for unexpected keyword arguments."""
pass
class ROI(object):
def __init__(self, identifier, image_index, roi_index, roi_slice):
"""Handle one region of interest (ROI)"""
if not isinstance(identifier, str):
... |
# -*- coding: utf-8 -*-
"""
pint
~~~~
Pint is Python module/package to define, operate and manipulate
**physical quantities**: the product of a numerical value and a
unit of measurement. It allows arithmetic operations between them
and conversions from and to different units.
:copyright: 2... |
'''
Created on Feb 10, 2013
@author: mdickson
'''
import os.path
from ConfigParser import SafeConfigParser
from inworldz.util.network import GetPrivateIPs
from inworldz.util.filesystem import getCurrentUsersDesktopPath, getCurrentUsersAppDataPath
from inworldz.maestro.version import product_name
from inworldz.maestr... |
"""
Taken from axc2 pretty much as is
"""
import collections
import json
import toml
# colors from the os theme for python:
import os
import re
import shutil
import string
import subprocess
import sys
import time
import types
from copy import deepcopy
from fnmatch import fnmatch
# from jsondiff import diff as js_dif... |
# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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 ... |
"""
Отсортируйте данный массив, используя встроенную сортировку.
Формат ввода
Первая строка входных данных содержит количество элементов в
массиве N, N ≤ 10⁵. Далее идет N целых чисел, не превосходящих
по абсолютной величине 10⁹.
Формат вывода
Выведите эти числа в порядке неубывания.
"""
cnt = int(input())
N = map(... |
"""Mecab parser."""
import subprocess
import sys
from typing import Iterable, List, Optional, Union
import MeCab
import pandas as pd
from mecab2pandas.exception import NotSupportOSError
def listup_dictionaries() -> List[str]:
"""List up available dictionaries name.
Returns:
The list of dictionaries... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('openstack', '0027_delete_floating_ip_status'),
]
opera... |
# Copyright (c) 2015-2019, Activision Publishing, 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:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of ... |
from django import forms
from .models import Product, Stock
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'price', 'category', 'picture']
class StockForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['product', 'stock']
|
from cryptography.fernet import Fernet
from .helper_method import *
## Encrypting the files
def encryptFile(file, key):
f = Fernet(key)
with open(file, "rb") as fl:
fl_data = fl.read()
encrypt_data = f.encrypt(fl_data)
with open(file, "wb") as fl:
fl.write(encrypt_data)
## Do the ... |
from os import chdir as cd
from .command_structure import command
from .specific import system_call
from .this import read_version, REPO_DIR
@command('Pulls latest codebase from github.', False)
def update(args = None):
# move into the root directory of this repository
cd(REPO_DIR)
old_version = read_version()
sys... |
#!/usr/bin/env python3
# Copyright (c) 2016-2020, henry232323
#
# 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, mo... |
"""
CLI command 'vaskitsa version update'
"""
from .base import VersionSubCommand
class Update(VersionSubCommand):
"""
CLI command 'vaskitsa version update'
"""
name = 'update'
def run(self, args):
print(args)
|
import click
from ape.logging import logger
class Abort(click.ClickException):
"""
A wrapper around a CLI exception. When you raise this error,
the error is nicely printed to the terminal. This is
useful for all user-facing errors.
"""
def __init__(self, message):
if not message.ends... |
# encoding: utf-8
"""
@author: xingyu liao
@contact: sherlockliao01@gmail.com
"""
from fastreid.modeling.meta_arch import Baseline
from fastreid.modeling.meta_arch import META_ARCH_REGISTRY
@META_ARCH_REGISTRY.register()
class FaceBaseline(Baseline):
def __init__(self, cfg):
super().__init__(cfg)
... |
def is_prime_happy(n):
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import math
import json
from django.db import models
from moneywagon import crypto_data
class FraudAlert(models.Model):
fraud_services = models.TextField()
network_results = models.TextField()
offending_type = models.CharField... |
from ...typecheck import *
from ...import dap
from ...import core
from ...import ui
from ..debugger_session import Sources
from . import css
class SourcesView(ui.div):
def __init__(self, sources: Sources, on_click: Callable[[dap.Source], None]):
super().__init__()
self.sources = sources
self.on_click = on_clic... |
#bullyblocker.py
from flask import Flask, render_template
import requests
import json
app = Flask(__name__, template_folder = '.')
@app.route('/')
def render():
return render_template('index.html')
@app.route('/bullyblocker')
def homepage():
params = {
'api_key' : 'trSXSGm9BOHM',
}
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Miguel Domingo"
__license__ = "MIT License"
__email__ = "midobal@prhlt.upv.es"
import sys, os, subprocess
def commonWords(hyp, pe):
"""
This function computes the longest common subsequence between a translation hypothesis and
its post-edited ve... |
import time
import torch
from lib.Utility.metrics import AverageMeter
from lib.Utility.metrics import accuracy
def train(dataset, model, criterion, epoch, optimizer, lr_scheduler, device, args):
"""
Trains/updates the model for one epoch on the training dataset.
Parameters:
train_loader (torch.uti... |
import pytest
from pypgsync.utils import attrs_to_uri, intervals
def test_attrs_to_uri_with_valid_input():
"""Test behavior of attrs_to_uri method when receiving valid input."""
assert attrs_to_uri('user', 'passwd', 'host', 'port',
'db') == 'postgresql://user:passwd@host:port/db'
de... |
# -*- coding: utf-8 -*-
class UPKIError(Exception):
def __init__(self, code=0, reason=None):
try:
self.code = int(code)
except ValueError:
raise Exception('Invalid error code')
try:
self.reason = str(reason)
except ValueError:
... |
"""
Takes all study logs and generates a single report page.
"""
from collections import namedtuple
import os
study_dir = ".study_logs/"
if not os.path.exists(study_dir):
print("No study logs!")
exit()
log_result = namedtuple("log_result", ['problem_name', 'passes',
'fai... |
from .resnext import *
from .resnet import *
from .wider_resnet import *
from .densenet import *
|
# https://www.hackerrank.com/challenges/maximize-it/problem
from itertools import product
K, M = map(int, input().split())
n = [map(int, input().split()[1:]) for _ in range(K)]
prods = list(map(lambda x: sum(i * i for i in x) % M, product(*n)))
print(max(prods))
|
# -*- coding: utf-8 -*-
import os
import warnings
if os.environ.get('PYCGIR_DEBUG', '0') == '1':
DEBUG = True
from typeguard import typechecked
warnings.warn("running in debug mode with activated run-time type checks", RuntimeWarning)
else:
DEBUG = False
typechecked = lambda x: x
|
from PyQt5.QtWidgets import (QApplication, QWidget, QGroupBox, QInputDialog, QDialog, QPushButton,
QLabel, QVBoxLayout, QHBoxLayout, QDesktopWidget, QLineEdit)
def moveToCenter(widget: QWidget):
qtRectangle = widget.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry(... |
import graphene
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import SetPasswordForm, PasswordChangeForm
from django.contrib.auth.tokens import default_token_generator as token_generator
from django.core.exceptions import ValidationError, ImproperlyConfig... |
import tkinter as tk
from typing import List
def make_root() -> tk.Tk:
root = tk.Tk()
root.title('Calculator')
root.config(padx=10, pady=10, background='#fff')
root.resizable(False, False)
return root
def make_label(root) -> tk.Label:
label = tk.Label(
root, text='No accounts',
... |
'''import tensorflow'''
import flask
from flask import request, render_template,send_file
import base64
import cv2
import maskservice as ms
#import numpy as np
#import pandas as pd
'''from copy import deepcopy'''
#from werkzeug import secure_filename
app = flask.Flask(__name__)
@app.route("/")
def viz_page():
re... |
#!/usr/bin/env python
import sys
MAX_NUM_PROCESSING_ROUNDS = 4
VERBOSE = -1
CRASHING = False
def debug_var(level, var_name, var):
if VERBOSE < level:
return
if type(var) in [set, frozenset, list, tuple]:
svar = type(var)([str(i) for i in var])
var = svar
m = 'tag.py DEBUG: {} = {}'... |
"""
author rochanaph
August 20 2017
"""
## list
list = [ 'abcd', 786 , 2.23, 'john', 70.2, 123 ]
tinylist = [123, 'john']
#
# # append
# resapp = []
# for item in list*2:
# resapp.append(item)
# print (resapp)
#
# # extend
# restend = []
# for item in [list,tinylist]:
# restend.extend(item)
# print (restend)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-09-10 14:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("chroma_core", "0024_mountsnapshotjob_unmountsnapshotjob"),... |
import unittest
import numpy as np
import afterglowpy.flux as flux
class TestFlux(unittest.TestCase):
def compareArrayEqualSingle(a1, a2):
return (a1 == a2).all()
def compareArrayTuple(self, func, argin, out):
res = func(*argin)
self.assertEqual(len(res), len(out))
for i, a ... |
import cv2 as cv
import sys
import requests
import time
import numpy as np
import psutil
import threading
from threading import Thread
from queue import Queue
from datetime import datetime
from pathlib import Path
from fe.settings import common as config
from fe.thread_request import Request_api as request_api
from od... |
from ..error import PyAsn1Error
class ValueConstraintError(PyAsn1Error):
pass
|
# -- coding: utf-8 --
import sys
import threading
import msvcrt
from ctypes import *
sys.path.append("../MvImport")
from MvCameraControl_class import *
g_bExit = False
# 为线程定义一个函数
def work_thread(cam=0, pData=0, nDataSize=0):
stFrameInfo = MV_FRAME_OUT_INFO_EX()
memset(byref(stFrameInfo), 0, sizeof(stFrame... |
def fence(string):
res=""
if "HH" in string:
return "NO"
else:
res = string.replace(".","B")
return "YES"+"\n"+res
n = int(input())
string = input()
print(fence(string))
|
import numpy as np
import random
import copy
from collections import namedtuple, deque
from ddpg_model import Actor, Critic
from experience_buffers import ReplayBuffer
from ou_noise import OUNoise
import torch
import torch.nn.functional as F
import torch.optim as optim
# default parameter values
DEFAULT_NAME = 'defa... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
import random
def keygeneration(num, ip): # num - number of parties ; ip - ith party
publicKey... |
from typing import Tuple, Union, Iterable, List, Callable, Optional
import os
import numpy as np
import tensorflow as tf
from nnuncert.models._model_base import BaseModel
from nnuncert.models._pred_base import MCPredictions, PredConditionalGaussian
from nnuncert.utils.traintest import generate_random_split
from nnunc... |
import FWCore.ParameterSet.Config as cms
class ValidFFTJetLUT:
"""
A class which contains the info about a valid combination
of ES record types and ES producer type for FFTJet lookup tables
"""
def __init__(self, basename):
self.basename = basename
self.dbTag = "FFT" + basename + "T... |
from django.contrib import admin
from authentication import models
admin.site.register(models.User)
|
from fastapi import APIRouter, HTTPException
class Router:
def __init__(self, prefix, config, database):
self.config = config
self.database = database
self.router = APIRouter(prefix=prefix)
self.methods()
def check_api_key(self, key: str, permission: str = None):
wit... |
import datetime
import random
from django.contrib.auth.models import Group
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from core.tests.utils import make_test_users
from credit.models import Credit
from disbursement.models import Disbursement
from ... |
import torch
from .Criterion import Criterion
class L1HingeEmbeddingCriterion(Criterion):
def __init__(self, margin=1):
super(L1HingeEmbeddingCriterion, self).__init__()
self.margin = margin
self.gradInput = [torch.Tensor(), torch.Tensor()]
def updateOutput(self, input, y):
s... |
__copyright__ = """This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
from conans import ConanFile, CMake, tools
import shutil
class IrcConanfile(ConanFile):
name = "irc"
version = "6d5c7c37"
descrip... |
import os
from abc import abstractmethod
from dataclasses import dataclass
from functools import wraps
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar
import wandb
from git_t5.utils import rank_zero_only
from wandb.sdk.wandb_run import Run
if TYPE_CHECKING:
from .trainer import T5Trainer
... |
"""
Helper function for reading in the Sanger dataset, splitting into data X,
mask M, drug names, cancer cell line names.
Also have a helper for storing it back into a file.
"""
import numpy
import os
folder_gdsc = os.path.dirname(__file__)+"/"
gdsc_file = folder_gdsc+"ic50_excl_empty_filtered_cell_lines_drugs.txt"
... |
# -*- coding:utf-8 -*-
class MyMiddleware(object):
def process_response(self, request, response):
print('--------------response2222222222222Copy')
response.set_cookie("aaaaaaaaaaaaaaaa","bbbbbbbbbbbbbbbbbbb")
return response
# def process_exception(request, exception):
# pass |
"""
Project name: Data Collection Bot
Written by: Phillip Tat
Date written: 8/23/21
For: UCF Senior Design Project
Purpose: Collect data into our database whenever there is a push, issue, or pull request event.
"""
import os, aiohttp, base64
from aiohttp import web
from gidgethub import routing, sansio
from gidgethub i... |
from twisted.internet import defer
from twisted.python import failure
from twisted.trial import unittest
from webmagic.fakes import ListLog
from minerva.qan import (
OkayAnswer, KnownErrorAnswer, UnknownErrorAnswer, Question, Notification,
Cancellation, QANHelper, qanFrameToString, InvalidQANFrame,
stringToQANFram... |
from collections import namedtuple
from typing import List, Tuple
import torch
from wiki_search.dataset import Dataset, Document
from wiki_search.core.bert_ranking import BertRanking
SearchResult = namedtuple('SearchResult', ['score', 'document'])
class Engine(object):
def __init__(self, dataset: Dataset, ran... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""Multi-class Focal loss implementation.
Args:
gamma (float): The larger the gamma, the smaller
the loss weight of easier samples.
weight... |
import time
list = [i for i in range(2,400)]
start = time.time()
for i in list:
for a in list:
if a!=i and a%i == 0:
list.remove(a)
print(list)
for i in (i for i,x in enumerate(list) if x==1):
print(i)
end = time.time()
print(end-start)
|
"""
@author: Elif Koksal Ersoz
This file is for running simulations in simu_E_g.py file for a given combination.
"""
import numpy as np
import simu_E_g
import time
import os
from parameterLists import parameters
def runSimulation(p, eta, tau, u, mu, G):
for n in range(0, int(p.simulationspercombination... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
from ComssServiceDevelopment.connectors.tcp.msg_stream_connector import InputMessageConnector, OutputMessageConnector #import modułów konektora msg_stream_connector
from ComssServiceDevelopment.connectors.tcp.object_connector import InputObjectConnector, Ou... |
sheepCounted=0
while sheepCounted<30:
print("I have counted"+str(sheepCounted)+"sheep.")
sheepCounted=sheepCounted+1
print("I fall asleep.") |
import pygame
def mouse_within_md_area(self, mouse_x, mouse_y) -> bool:
""" Returns True if the given coordinates are within the console area of the pygame window, otherwise False.
:param self: MarkdownRenderer
:param mouse_x: x-coordinate of mouse position
:param mouse_y: y-coordinate of mouse posit... |
print ("Belum Luu Creat Goblokk")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 Benjamin Milde (Universitaet Hamburg)
# Copyright 2017 Guenter Bartsch
#
# 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
#
# ... |
import pickle
import measurements as msr
if __name__ == '__main__':
"""Get syllable counts of bird names"""
# Load list of NamedBirds
birds = pickle.load(open('built_birds.pickle', 'rb'))
# Divide birds
bop_names = [b.mod_name for b in birds if b.is_bop()]
nbop_names = [b.mod_name for b in bir... |
from string import Template
import base64
import logging
USER_DATA_TEMPLATE="""#!/bin/bash -xev
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
# Do some chef pre-work
/bin/mkdir -p /etc/chef
/bin/mkdir -p /var/lib/chef
/bin/mkdir -p /var/log/chef
cd /etc/chef/
# Install chef
curl -... |
"""
The MIT License (MIT)
Copyright (c) 2020 James
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, publis... |
import re
import configparser
from pyspark.sql import SparkSession
def process_file_with_anomaly():
config = configparser.ConfigParser()
config.read('settings.ini')
spark = SparkSession.builder.master(config["Spark"]["remote"]).getOrCreate()
rdd = spark.read.format('orc').load("E:\\Projects\\sigma\\... |
from __future__ import unicode_literals
from datetime import datetime
from erpnext.controllers.accounts_controller import get_taxes_and_charges
from frappe.model.mapper import get_mapped_doc
from frappe.utils import add_days, today, date_diff, getdate, add_months
from property.lease_invoice import getDueDate
import cal... |
# Copyright 2019 RedLotus <ssfdust@gmail.com>
# Author: RedLotus <ssfdust@gmail.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-2.0
#
# Unles... |
import plugins;
from bs4 import BeautifulSoup as bs4;
from bs4 import NavigableString;
from bs4.dammit import EntitySubstitution
escapeHTML = (EntitySubstitution()).substitute_xml;
class FFNetParser(plugins.BaseWebsiteParser):
# Called in the initializer:
def __init__(self):
self.name = "FanFictio... |
import os
print("""
=========== Directory Manager ===========
[1] View
[2] Create
[3] Delete
[4] Rename
[5] Exit
=========================================
""")
while True:
user_inp = int(input("Option: "))
if user_inp == 1:
x = os.getcwd()
print(x)
elif user_inp == 2:
dir_nam... |
#
# Copyright (c) 2019-2020 Google LLC. All Rights Reserved.
# Copyright (c) 2016-2018 Nest Labs Inc. 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
#
# ... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch_mlu
import torch_mlu.core.mlu_model as ct
from torch.nn import Parameter
import torch.nn.functional as F
import numpy as np
import sys
import os
import copy
import time
import unittest
sys.path.append("../")
from common_utils import ... |
import numpy as np
import librosa
import torch
import os
from librosa import amplitude_to_db
from math import floor
from models import modifyresnet18, UNet, Synthesizer
from util.validation import spec2wave
from image2instru import Instru_from_image
import soundfile as sf
import cv2
os.environ["CUDA_VISIBL... |
from ...exceptions.executorexceptions import CommandExecutionFailure
from ...exceptions.tardisexceptions import TardisError
from ...exceptions.tardisexceptions import TardisTimeout
from ...exceptions.tardisexceptions import TardisResourceStatusUpdateFailed
from ...interfaces.siteadapter import ResourceStatus
from ...in... |
#
# Copyright (c) 2016 Stefan Seefeld
# All rights reserved.
#
# This file is part of Faber. It is made available under the
# Boost Software License, Version 1.0.
# (Consult LICENSE or http://www.boost.org/LICENSE_1_0.txt)
from ..feature import set
from ..artefacts.library import library
from ..tools.compiler import l... |
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.