content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import re
import json
VIEW_KEY_RE = r"a.+?href=\".+?viewkey=(.+?)\""
INFO_RE = r"var flashvars_.+? = ({.+})"
class Extractor(object):
def __init__(self):
self._viewkey_re = re.compile(VIEW_KEY_RE, re.MULTILINE)
self._videoinfo_re = re.compile(INFO_RE, re.MULTILINE)
def get_viewkeys(self, dat... | python |
import logging
import random
import re
from datetime import datetime
from plugins import Processor, handler, match
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("neikea.plugins")
class Strip(Processor):
"""
Turn the 'message' string into a dict that will contain different
versions o... | python |
import os
import numpy as np
import sys
import json
def read_text_lines(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
lines = [l.rstrip() for l in lines]
return lines
def check_path(path):
if not os.path.exists(path):
os.makedirs(path, exist_ok=True) ... | python |
from twilio.rest import Client
from twilio.twiml.voice_response import Gather, VoiceResponse
import os
class TwilioNotification:
def __init__(self, sid, auth_token):
self.client = Client(sid, auth_token)
def send_call(self, action_url, contacts):
response = VoiceResponse()
gather = ... | python |
# -*- coding: utf-8 -*-
# @Time : 2021/5/10 11:13
# @Author : Jiangzhesheng
# @File : test0.py
# @Software: PyCharm
import sys
import os
from flye.repeat_graph.repeat_graph import RepeatGraph
import flye.utils.fasta_parser as fp
from my_change.ond_algo import *
from bioclass import Sequence
def get_e... | python |
# @Author: Yang Li
# @Date: 2020-05-20 21:17:13
# @Last Modified by: Yang Li
# @Last Modified time: 2021-04-19 22:14:04
from __future__ import division
from __future__ import print_function
import argparse
import time
import numpy as np
import scipy.sparse as sp
import networkx as nx
import torch
fr... | python |
'''This is sandbox code
'''
| python |
i=0
while False:
i+=1
print("Hello:",i)
| python |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from settings import EMAIL_SMTP_SETTINGS
def send_mail(subject, message, message_type='html'):
message = MIMEText(message, message_type, 'utf-8')
message['From'] = Header(EMAIL_SMTP_... | python |
from zeus import factories
from zeus.constants import Result, Status
from zeus.models import Job
def test_new_job(client, default_source, default_repo, default_hook):
build = factories.BuildFactory(
source=default_source, provider=default_hook.provider, external_id="3"
)
job_xid = "2"
path =... | python |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_descriptio... | python |
from flask import Flask, make_response, render_template, request
app = Flask(__name__, template_folder='template')
@app.route('/')
def index():
return render_template('index02.html')
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request... | python |
'''unit test class for churn library'''
import time
import logging
import unittest
from pandas.api.types import is_string_dtype
from functools import wraps
from churn_library import ChurnLibrarySolution
keep_cols = [
'Customer_Age',
'Dependent_count',
'Months_on_book',
'Total_Relationship_Count',
... | python |
from django.db import models
from s3upload.fields import S3UploadField
class Cat(models.Model):
custom_filename = S3UploadField(dest="custom_filename", blank=True)
class Kitten(models.Model):
mother = models.ForeignKey("Cat", on_delete=models.CASCADE)
video = S3UploadField(dest="vids", blank=True)
... | python |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from .util import number_color
from functools import partial
import glob
import math
from ui.util import number_object
from ui.mouse_event import ReferenceDialog, SnapshotDialog
import copy
Lb_width = 100
Lb_height = 40
Lb... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Warning: Auto-generated file, don't edit.
pinyin_dict = {
0x3416: 'xié',
0x3469: 'luo',
0x36BB: 'jī',
0x378E: 'bǎ,ba',
0x393D: 'chóu',
0x39D1: 'huī',
0x3D89: 'xī',
0x3E62: 'jiā',
0x3E74: 'gěng',
0x3EA2: 'huò',
... | python |
class DefaultableEntityEndpointsMixin(object):
"""
Defaultable entity endpoints.
"""
def set_default(self, id_):
"""
Sets a entity with given ID as default.
Args:
id_ (str): entity ID.
Returns:
dict: new entity.
"""
self.request... | python |
sexo = str(input('Informe seu sexo [M / F]: ')).strip().upper()[0] # pega somente a primeira letra
while sexo != 'M' and sexo != 'F':
sexo = str(input('DADOS INVALIDOS. Informe seu sexo [M / F]: ')).strip().upper()
| python |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, DateField
from wtforms.validators import DataRequired
class EntryForm(FlaskForm):
entry = StringField('Entry',validators=[DataRequired()])
project = StringField('Project')
notes = StringField('Notes')... | python |
'''
# DC Racer Testing and Reporting System (DC RTRS)
This script runs a standard test across all the different
student code bases. The tests will be based on 100 frame
scenarios.
'''
import cv2
import numpy as np
import platform
#import matplotlib.pyplot as plt
import time
import sys
from os import listdir
from ... | python |
from io import * | python |
with open('/usr/local/airflow//dags/1','a+') as f:
f.write("1")
| python |
x = input("x : ")
print(type(x))
y = int(x) + 1
print(y)
print(f"x : {x}, y : {y}")
#there are some falsy values in python3 whenever we use them in boolean sense it will output false
# "" --> this a empty string which is falsy according to python3
# 0 --> no. zero is also falsy
# None --> which represent absense... | python |
#
# PySNMP MIB module XEDIA-L2DIAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-L2DIAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:36:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | python |
'''
Stacking the cubes with sizes in descending order from bottom to top.
**NOTE**
Every time only the left-most or the right-most cube can be stacked from the array/list.
'''
#Input Format:
'''
The first line contains a single integer T, the number of test cases.
For each test case, there are 2 lines.
The f... | python |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from taysistunto.feeds import SpeakerFeed, DocumentFeed, ActionFeed, ActionsByWordFeed
urlpatterns = patterns('',
# Examples:
url(r'^$', 'taysistunto.vi... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 02/03/2020
"""
from enum import Enum
__all__ = ["UpscaleMode", "MergeMode"]
class MergeMode(Enum):
Concat = 0
Add = 1
class UpscaleMode(Enum):
FractionalTranspose = ... | python |
"""Refiner is the refinement module public interface. RefinerFactory is
what should usually be used to construct a Refiner."""
import copy
import logging
import math
import psutil
import libtbx
from dxtbx.model.experiment_list import ExperimentList
from libtbx.phil import parse
import dials.util
from dials.algorit... | python |
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat.mock import pa... | python |
import torch
from enum import Enum
from experiments import constants
class OptimizerType(Enum):
SGD = 0
Adam = 1
class SchedulerType(Enum):
MultiStep = 0
class SingleNetworkOptimization(object):
def __init__(self, network: torch.nn.Module, n_epochs: int,
lr=1e-4, weight_decay=1e-3... | python |
import sys
import random
import time
from cnn import utils
import logging
import warnings
warnings.filterwarnings("ignore")
import argparse
import torch.utils
import torch.backends.cudnn as cudnn
from utils.scheduler import Scheduler
from torchvision.transforms import transforms
import torchvision.datasets as datasets
... | python |
#!/usr/bin/env python3
import base64
import os
import subprocess
import sys
import yaml
EDITOR = os.environ.get('EDITOR', 'vi')
class NoDatesSafeLoader(yaml.SafeLoader):
@classmethod
def remove_implicit_resolver(cls, tag_to_remove):
"""
Remove implicit resolvers for a particular tag
... | python |
#!/usr/bin/python
"""
Basic class for communication to Parrot Bebop
usage:
./bebop.py <task> [<metalog> [<F>]]
"""
import sys
import socket
import datetime
import struct
import time
import numpy as np
import math
from navdata import *
from commands import *
from video import VideoFrames
# this will be in ... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | python |
import numpy as np
import csv
import json
import argparse
import pickle
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--method", help="vote Method to learn from")
ap.add_argument("-r", "--row", help="data row joined by comma")
ap.add_argument("-f", "--filename", help="filename of dataset")
args = vars(ap.parse_... | python |
# Copyright (C) Izumi Kawashima
#
# json2oscimv4 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# json2oscimv4 is distributed in the... | python |
load(
"@bazel_tools//tools/jdk:toolchain_utils.bzl",
"find_java_toolchain",
)
load(
"@rules_scala_annex//rules:providers.bzl",
_ScalaConfiguration = "ScalaConfiguration",
_ZincConfiguration = "ZincConfiguration",
_ZincInfo = "ZincInfo",
)
load(
"@rules_scala_annex//rules/common:private/utils... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import numpy as np
import timeit
import json
from operator_benchmark import benchmark_utils
"""Performance microbenchmarks.
This module contains core ... | python |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | python |
import abc
import numpy as np
class ErrFunc(abc.ABC):
"""Base class for classification model error functions."""
@abc.abstractmethod
def apply(self, prediction, y):
"""Apply the nonconformity function.
Parameters
----------
prediction : numpy array of shape [n_samples, n_... | python |
import bpy
from math import pi
# ----------------------------------------------------------------------------------------
# Start - copied functions
# ----------------------------------------------------------------------------------------
def sun_light(
location, rotation, power=2.5, angle=135, name="Light_sun"... | python |
#!/bin/python
#python
import sys
import os
import shutil
import numpy
import time
import math
import threading
from scipy import ndimage
#appion
from appionlib import appionScript
from appionlib import apStack
from appionlib import apDisplay
from appionlib import appiondata
from appionlib import apEMAN
from appionlib ... | python |
# terrascript/provider/josenk/esxi.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:15:57 UTC)
import terrascript
class esxi(terrascript.Provider):
"""Terraform-provider-esxi plugin"""
__description__ = "Terraform-provider-esxi plugin"
__namespace__ = "josenk"
__name__ = "esxi"
... | python |
from .db import session_scope, Server
from datetime import datetime, timedelta
class Gateway:
def get_all_servers(self):
with session_scope() as session:
raw_servers = session.query(Server)
raw_servers_dict = []
if raw_servers:
for raw_server in raw_se... | python |
"""Utility functions."""
from typing import typevar, List, Any
T = typevar('T')
def short_type(obj: object) -> str:
"""Return the last component of the type name of an object.
If obj is None, return 'nil'. For example, if obj is 1, return 'int'.
"""
if obj is None:
return 'nil'
t = str... | python |
from abc import ABC
from abc import abstractmethod
class DatabaseQuery(ABC):
@staticmethod
def query_invoke(func):
def wrapper_method(self_instance, *args, **kwargs):
try:
self_instance.create_connection()
result = func(self_instance, *args, **kwargs)
... | python |
# coding: utf-8
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
import os
sys.path.append('.\src')
sys.path.append('..\src')
from src.main_functions import *
updateInput='u'
fullupdateInput='fu'
downloadInput='d'
statusInput='s'
compressInput='c'
def check_env():
try:
os.... | python |
import json
from collections import defaultdict
from typing import List, Tuple, Dict
from commands.snapshot import snapshot
from drive.api import DriveFile, Snapshot, resolve_paths, ResourcePath, Resource
from drive.http import ErrorHandlingRunner, GAPIBatchRunner
from drive.misc import eprint
from drive.serializers i... | python |
#!/usr/bin/env python3
# -*- coding: UTF-8
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import bs4
import requests
import re
from urllib.request import urlretrieve
import os.path
import csv
if __name__ == "__main__":
base__url = "http://pesquisa.memoriasreveladas.gov.br/mrex/consulta/"
first_url = "... | python |
# 20412 - [Job Adv] (Lv.100) Mihile 4rd job adv
sm.setSpeakerID(1101002)
if sm.sendAskYesNo("Are you ready, are you okay to leave?"):
sm.warp(913070100, 0)
sm.setInstanceTime(300, 130000000) | python |
##############################################################################
# Written by: Cachen Chen <cachen@novell.com>
# Date: 09/25/2009
# Application wrapper for Moonlight combobox
# Used by the combobox-*.py tests
##############################################################... | python |
# Copyright 2020 Google LLC. 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 applicable law or a... | python |
"""
Copyright (c) Open Carbon, 2020
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
backend/tools.py
Provides range of backend tools that can be run from command line:
importlocations: Imports location data from file that is used to geolocate s... | python |
"""This module contains definitions and data structures for 2-, 4-, and 8-valued logic operations.
8 logic values are defined as integer constants.
* For 2-valued logic: ``ZERO`` and ``ONE``
* 4-valued logic adds: ``UNASSIGNED`` and ``UNKNOWN``
* 8-valued logic adds: ``RISE``, ``FALL``, ``PPULSE``, and ``NPULSE``.
T... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 14:46:51 2020
@author: gabriel
"""
#%% MATLAB Code to reproduce
# function thresh_calc(nbeg,nend,n_noise,sig_fact,necdf_flag,nlbound)
# % Calculate the threshold using one of two methods
# % P=mean|W| + c sigma
# % P is computed from the e... | python |
from torch.utils import data
import yaml
from argparse import ArgumentParser
from typing import Any, List, Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.distributions as dist
from torch.utils.data import DataLoader, Ran... | python |
"""
Code for defining the architecture of the Encoder and the Decoder blocks.
"""
import tensorflow as tf
class Encoder():
def __init__(self, vocab_size, embedding_dim, encoder_units):
# print(vocab_size, embedding_dim, encoder_units, "##########################################ENCODER#####################... | python |
'''
Created on Mar 13, 2018
@author: abelit
'''
import os
import json
from utils import filepath
project_settings = {
# 项目信息配置
'package': 'dev',
'version':'3.14',
'name':'__dbreport__.py',
'author':'abelit',
'email':'ychenid@live.com',
'description':'',
}
path_settings = {
'image'... | python |
# -*- coding: utf-8 -*-
# jvparidon@gmail.com
from .timer import timer
| python |
import base64
import json
import cv2
import numpy as np
from decouple import config
from flask import Flask, request
from api.face import FaceVerification
from db.mongo import FaceEncodings
app = Flask(__name__)
face_verification = FaceVerification(
FaceEncodings(
config("DATABASE_URI")
)
)
@app.r... | python |
import pocketcasts as pc
import requests
import re
import configparser
from pathlib import Path
def get_valid_filename(s):
s = str(s).strip()
return re.sub(r"(?u)[^-\w. ]", "", s)
def get_extension(url):
if "?" in url:
url, _ = url.split("?", 1)
return url.split(".")[-1]
print("Reading con... | python |
import numpy as np
from config import handTrackConfig as htconf
from math import sin, cos, sqrt, atan2, radians
import cv2
# 8 12 16 20
# | | | |
# 7 11 15 19
# 4 | | | |
# | 6 10 14 18
# 3 | | | |
# | 5---9---13--17
# 2 \ /
# \ ... | python |
"""
This module provides various utility functions.
"""
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
from typing import Tuple
import numpy as np
# -------------------------------------------... | python |
"""
Based on https://github.com/ikostrikov/pytorch-a2c-ppo-acktr
"""
import gym
import torch
import random
from environments.env_utils.vec_env import VecEnvWrapper
from environments.env_utils.vec_env.dummy_vec_env import DummyVecEnv
from environments.env_utils.vec_env.subproc_vec_env import SubprocVecEnv
from environm... | python |
"""
Sets permission for the API (ONLY)
"""
from rest_framework import permissions
# TODO: Add restriction to users (get token, refresh token, verify token, post request)
class IsReadOnly(permissions.DjangoModelPermissions):
"""
Custom permission to only allow reading.
"""
def has_object_permission(se... | python |
###############################################################################
##
## Copyright 2011 Tavendo GmbH
##
## 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
##
## ht... | python |
from typing import Set, List, Tuple, Dict
def fibonacci(n: int) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raise a ValueError.
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(10)
55
>>> fibonacci(-2)
Tracebac... | python |
from functools import wraps
from . import environment as env
import wx, os
class VirtualEnvMustExistDecorator:
"""装饰器:虚拟环境必须存在!!!"""
def __init__(self, *args, **kwargs): ...
def __call__(self, func, e=None):
@wraps(func)
def decorator(obj, *args, **kwargs):
env_path = env.getPyt... | python |
import os, json, sys, shutil, distutils
from distutils import dir_util
if_block_template = '\tif(!strcmp(cmd, "{}")){{\n\
\t\treturn {}(argv, argc);\n\
\t}}else '
ending = '{\n\
\t\tstde("Not a command:");\n\
\t\tstde(argv[0]);\n\
\t}'
set_driver_template = "\tdrivers[{}] = &{};\n"
include_template = '#include... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from typing import Dict
import torch
from torch import optim
from datasets import Dataset
from models i... | python |
# Author : BIZZOZZERO Nicolas
# Completed on Sun, 24 Jan 2016, 23:11
#
# This program find the solution of the problem 5 of the Project Euler.
# The problem is the following :
#
# 2520 is the smallest number that can be divided by each of the
# numbers from 1 to 10 without any remainder.
# What is the smallest ... | python |
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
from communication import Communication
import math
from dataBase import data_base
from PyQt5.QtWidgets import QPushButton
pg.setConfigOption('background', (33, 33, 33))
pg.setConfigOption('foreground', (197, 198, 199))
# Interface variab... | python |
import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, SharedMemoryFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import Mo... | python |
"""
This module performs all basic DFA operations.
It is an interface for pyfst.
"""
# /usr/bin/python
from operator import attrgetter
import fst
from alphabet import createalphabet
EPSILON = fst.EPSILON
def TropicalWeight(param):
"""
Returns fst TropicalWeight
Args:
param (str): The input
Re... | python |
from singlecellmultiomics.universalBamTagger.digest import DigestFlagger
from singlecellmultiomics.tagtools import tagtools
class NlaIIIFlagger(DigestFlagger):
def __init__(self, **kwargs):
DigestFlagger.__init__(self, **kwargs)
def addSite(self, reads, strand, restrictionChrom, restriction... | python |
#!/usr/bin/env python2
import sys
import time
import logging
import argparse
def main():
"""
Tumor Map Calc Agent
"""
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument("-i", "--interval", type=int, default=0,
help="Minutes between calc, default ... | python |
# -*- coding: utf-8 -*-
"""SOG run processor.
Do various operations related to running the the SOG bio-physical
model of deep estuaries. Most notably, run the model.
This module provides services to the SOG command processor.
:Author: Doug Latornell <djl@douglatornell.ca>
:License: Apache License, Version 2.0
Copy... | python |
import datetime
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from enum import Enum
from typing import List
from typing import Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pglet import BarChart
from pglet ... | python |
from .home import bp as home
from .dashboard import bp as dashboard
from .api import bp as api
# the .home syntax direct the program to find the module name home then import BP routes.
| python |
"""A class to hold data parsed from PDFs."""
import dataclasses
@dataclasses.dataclass
class Datum:
"""A class to hold data parsed from PDFs."""
text: str = ""
traits: list[dict] = dataclasses.field(default_factory=list)
reject: bool = False
| python |
import sounddevice as sd
from scipy.io import wavfile
from scipy import signal
import sys
import matplotlib.pyplot as plt
import os
import subprocess as sp
from collections import defaultdict, Counter
import pyprind
import numpy as np
import random
from .utils import readwav
output_seconds = 5
n_gram = 2
fname = 'Nigh... | python |
#!/usr/bin/python3.7
import subprocess
import sys
v = sys.argv[1]
subprocess.call(["amixer", "sset", "Speaker", v + "%"]) | python |
from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox, \
QLabel, QVBoxLayout, QSizePolicy, \
QCheckBox, QLineEdit, QPushButton, QHBoxLayout, \
QSpinBox, QTabWidget, QMessageBox
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtG... | python |
import twoLSTMcuda as t
model = t.torch.load(open("twoLSTMentireModel.npy", 'rb'))
print(t.checkAcc(model, t.data, t.labels))
print(t.checkAcc(model, t.valData, t.valLabels))
| python |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
import os
@slash.requires(have_ffmpeg)
@slash.requires(have_ffmpeg_vaapi_accel)
class TranscoderTest(slash.Test):
def before(self):
self.refctx = []
def transcode_1to... | python |
from django.shortcuts import *
from django.http import *
from django.shortcuts import *
from django.urls import *
import traceback
import json
from .models import *
from django.db.utils import IntegrityError
from django.db.models import F
from .crypto import *
import math
from account_info.models import User
from walle... | python |
#!/usr/bin/python
import unittest
from utils.logger import Logger
class UtLogger(unittest.TestCase):
def setUp(self):
self.logger = Logger().getLogger("test.utils.UtLogger")
def testLogger(self):
self.logger.debug("1")
self.logger.info("2")
self.logger.warn("3")
... | python |
from base_n_treble import db, auth
from base_n_treble.models.user import User
def setup_admin():
from tests.fixtures import TEST_ADMIN
db._adapter.reconnect()
admins = auth.id_group("admin") if auth.id_group("admin") else auth.add_group("admin")
print("Admin group id: '{}'".format(admins))
db._ada... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
# configuration
DATABASE = "/tmp/flaskr.db"
DEBUG = True
SECRET_KEY = "development key"
USERNAME= "admin"
PASSWORD = "default... | python |
#! /usr/bin/env python
import sys
import os
import disttools
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from strparser import *
from filehdl import *
from pyparser import *
def make_string_slash_ok(s):
sarr = re.split('\n', s)
rets = ''
for l in sarr:
l = l.rstrip('\r\n')
... | python |
import pytest
import abjad
import abjadext.nauert
class Job:
### INITIALIZER ###
def __init__(self, number):
self.number = number
### SPECIAL METHODS ###
def __call__(self):
self.result = [
x for x in abjad.math.yield_all_compositions_of_integer(self.number)
]
... | python |
"""
===========
04. Run ICA
===========
This fits ICA on epoched data filtered with 1 Hz highpass,
for this purpose only using fastICA. Separate ICAs are fitted and stored for
MEG and EEG data.
To actually remove designated ICA components from your data, you will have to
run 05a-apply_ica.py.
"""
import itertools
imp... | python |
import logging
import typing
import copy
from typing import Any, Dict, List, Text
from rasa.nlu.components import Component
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer
from rasa.nlu.training_data import Message, TrainingData
logger = logging.getLogger(__na... | python |
import datetime
import enum
from sqlalchemy import (
Column,
Integer,
String,
Enum,
TIMESTAMP,
ForeignKey,
Index,
Float,
)
from sqlalchemy.orm import relationship
from .base import Base
class SystemUpdate(Base):
__tablename__ = "system_update"
pk = Column(Integer, primary_ke... | python |
from italian_csv_type_prediction.simple_types import IntegerType
import numpy as np
def test_integer_type():
predictor = IntegerType()
valids = [
3,
6,
0,
"1.000.000.00"
]
invalids = [
"ciao",
"12.12.94",
"12.12.1994",
False,
Tru... | python |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
... | python |
"""Parameters for the model of marine particle microbial degradation
and coupling of degradation with sinking speed, part of the paper
"Sinking enhances the degradation of organic particle by marine bacteria"
Uria Alcolombri, François J. Peaudecerf, Vicente Fernandez, Lars Behrendt, Kang Soo Lee, Roman Stocker
Na... | python |
import os
import json
import shutil
import grp
from pathlib import Path
def change_key(my_json, old_key, new_key):
if old_key in my_json:
# store the value
val = my_json[old_key]
# delete the old key/value pair
del my_json[old_key]
# error checking
if new_key in my_j... | python |
from pytari2600.pytari2600 import new_atari
emulator = new_atari("../../roms/dragster.a26", headless=False)
while True:
emulator.core.step()
# print("---AFTER EXECUTION---" + str(emulator.stella.clocks.system_clock))
# print(emulator.stella.display_cache) | python |
# # -*- coding: utf-8 -*-
# """
# Created on Fri May 8 17:08:43 2020
#%%
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import pi, c
from numpy.fft import fft, ifft, fftshift
#%%
def calculate_spectrum(z, E, H, f=3.7e9):
k0 = 2*pi*f/c
lambda0 = c/f
# fourier domain points
B = ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.