content stringlengths 5 1.05M |
|---|
import firebase_admin
from firebase_admin import credentials, messaging
from firebase_admin.exceptions import FirebaseError
from secret import cred_cert
def test_firebase_call():
print('1')
if not firebase_admin._apps:
cred = credentials.Certificate(cred_cert)
default_app = firebase_admin.initi... |
import numpy as np
from scipy.constants import c as c_light, e as qe, m_p
from scipy.signal import hilbert
from scipy.stats import linregress
from PyHEADTAIL.feedback.transverse_damper import TransverseDamper
from PyHEADTAIL.machines.synchrotron import Synchrotron
def test_damping_time():
n_attempts = 5
n_... |
"""Top-level package for chess_clock."""
__author__ = """Musharraf Omer"""
__email__ = 'ibnomer2011@hotmail.com'
__version__ = '0.1.0'
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 2 11:43:37 2021
@author: Chai Wah Wu
Python functions to generate The On-Line Encyclopedia of Integer Sequences (OEIS) sequences
Requires python >= 3.8
Installation: pip install OEISsequences
After installation, `from oeis_sequences import OEISsequences` will import ... |
from matplotlib import pyplot
import numpy
import sys
import os
def plot_nx(length_frequencies, total_length, output_dir):
figure = pyplot.figure()
axes = pyplot.axes()
legend_names = list()
x1 = 0
y_prev = None
x_coords = list()
y_coords = list()
for length,frequency in length_fr... |
from ..parents import ConnRDBMS
from ..parents import DB as ParentDB
import sqlalchemy
import sys
import os
import logging as lg
import jaydebeapi
import pprint
lg.basicConfig()
logging = lg.getLogger(__name__)
class DB(ConnRDBMS, ParentDB):
# https://stackoverflow.com/questions/25596737/working-with-an-acces... |
import collections
from zope.interface import implementer
from sqlalchemy import (
Column,
String,
Unicode,
Integer,
Float,
ForeignKey,
)
from sqlalchemy.orm import relationship, backref
from uritemplate import expand, variables
from clld import interfaces
from clld.db.meta import CustomModelM... |
idade=int(input('Digite sua idade: '))
if idade<16:
print('Não pode votar')
elif idade>=18 and idade<=70:
print('Você é obrigado a votar')
else:
print('Seu voto é opcional') |
import os
_current_dir = os.path.abspath(os.path.dirname(__file__))
PT_HOME = os.path.normpath(os.path.join(_current_dir, "../../../.."))
PT_VERSION = '0.01'
|
"""
Usage: plotAtmFlux.py [-o OUTPUT_FILE] -p PARAMETER_FILE -f FLUX_FILE
Options:
-h --help Help.
-o --output_file OUTPUT_FILE Output file.
-p --parameter_file PARAMETER_FILE Input file.
-f --flux_file FLUX_FILE Flux file.
"""
from docopt import docopt
from pathl... |
#!/usr/bin/python
import os
import sys
import presquel
import argparse
VERSION = "%{prog}s " + presquel.VERSION_STR
def find_max_order_len(max_len, schema_list):
for sch in schema_list:
if not isinstance(sch, presquel.model.SchemaObject):
raise Exception("expected SchemaObject... |
import sys
sys.path.append('..')
from booru_db import BooruDatabase
from database import *
import datetime
import json
import traceback
import random
import time
import logging
import redis
import collections
r = redis.Redis(db=12)
bdb = BooruDatabase('danbooru')
def parse_date(val):
try:
v = datetime.da... |
'''Extracts the texts of a scraped LexDk corpus.
Usage:
python extract_lexdk_texts.py <lexdk_jsonl_dump>
'''
import sys
import json
from pathlib import Path
from tqdm.auto import tqdm
def main():
file_in = Path(sys.argv[1])
file_out = file_in.parent / f'{file_in.stem}.txt'
with file_out.open('w', e... |
'''
By Chris Paxton
Copyright (c) 2017, The Johns Hopkins University
All rights reserved. See license for details.
'''
from abstract import AbstractExtract
import operator
'''
Return the most visited nodes all the way down the tree.
'''
class MostVisitedExtract(AbstractExtract):
def __call__(self, node):
... |
from collections import OrderedDict
from qtpy.QtGui import QStandardItemModel, QStandardItem
from qtpy.QtCore import Qt
from qtpy.QtWidgets import (QTableView, QWidget, QLabel, QStyledItemDelegate,
QHBoxLayout, QVBoxLayout, QMessageBox,
QPushButton)
from .widgets ... |
import datetime
import re
from freenit.db import db
from peewee import BooleanField, DateTimeField, ForeignKeyField, TextField
from unidecode import unidecode
from ..date import datetime_format
from .user import User
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
Model = db.Model
class Blog(Mod... |
# -*- coding: utf-8 -*-
import json
import boto3
import time
from build_info import BuildInfo, CodeBuildInfo
from slack_helper import post_build_msg, find_message_for_build, send_codepipeline_result
from message_builder import MessageBuilder
codepipeline_client = boto3.client('codepipeline')
codebuild_client = boto... |
from django.shortcuts import render, redirect
# Login needed decorator
from django.contrib.auth.decorators import login_required
from reports.forms import Report_Form
from reports.models import Report
from patients.models import Patient
""" Reportlab modules """
import io
from django.http import FileResponse
from rep... |
#%% Imports
from operator import itemgetter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from graspy.cluster import GaussianCluster, KMeansCluster
from graspy.embed import AdjacencySpectralEmbed, LaplacianSpectralEmbed, OmnibusEmbed
from graspy.models import DCSBMEstimat... |
# Copyright (c) 2020-2021, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice... |
import snitch
from snitch import explicit_dispatch
from snitch.constants import DEFAULT_CONFIG
from tests.app.events import DUMMY_EVENT
@snitch.dispatch(DUMMY_EVENT, config=DEFAULT_CONFIG)
def dispatch_dummy_event(actor, trigger, target):
pass
def dispatch_explicit_dummy_event(actor, trigger, target):
expli... |
from django.test import TestCase
class LocaleTest(TestCase):
def test_set_locale_cookie(self):
response = self.client.get('/control/login')
assert response['Content-Language'] == 'en'
self.client.get('/locale/set?locale=de')
response = self.client.get('/control/login')
ass... |
from .tools import load_yaml, get, strict_str, KnittyError # noqa
|
from __future__ import print_function, division, absolute_import
import argparse
import os
import cv2
from tqdm import tqdm
from rt_gene.extract_landmarks_method_base import LandmarkMethodBase
script_path = os.path.dirname(os.path.realpath(__file__))
if __name__ == "__main__":
parser = argparse.ArgumentParser(... |
from django.contrib.auth.models import User
from django.template.response import TemplateResponse
from django.test import TestCase
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class TopLevelAdminTestCase(TestCase):
@classmethod
def setUpTestDat... |
#!/usr/bin/env 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.0OA
#
# Authors:
# - Wen Guan, <wen.guan@cern.ch>, 2020
"""
core operations ... |
# ---------------------------------------------------------------------------
# |
# | FileSystem.py
# |
# | David Brownell (db@DavidBrownell.com)
# |
# | 09/05/2015 08:47:49 PM
# |
# ---------------------------------------------------------------------------
# |
# | Copyright David Brownell 201... |
"""
Plot composite periods for LRP between experiments
Reference : Deser et al. [2020, JCLI]
Author : Zachary M. Labe
Date : 5 April 2021
Version : R1
"""
### Import packages
import math
import time
import matplotlib.pyplot as plt
import numpy as np
from netCDF4 import Dataset
import scipy.stats as sts
fro... |
from imdb import IMDB
from imagenet_vid import TwitchVID
|
import logging
import src.core.config as config
from functools import wraps
from src.main import logger, get_resource
from src.core.request import Request
from src.core.response import response
from src.core.request import DEBUG_HEADER
def api_endpoint():
"""Decorate a lambda function endpoint with user access ch... |
'''
Author: Junbong Jang
6/10/2020
Automatically get the edge from the images to aid human labelers
'''
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import cv2
import numpy as np
from skimage import io
import matplotlib.pyplot as plt
import glob
import... |
from .General_Core import SparCC_MicNet
__all__=['SparCC_MicNet'] |
# coding: utf-8
from __future__ import unicode_literals
import json
class WxBot(object):
"""
储存微信 bot 相关信息及 wechat_sender 各类 receiver 的类
"""
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(WxBot, cls)
cls._instance = orig.__new__(cls)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from six.moves import range
from functools import reduce
__author__ = 'Austin Taylor'
from ..base.config import vwConfig
import pandas as pd
from lxml import objectify
import sys
import os
import io
import time
import sqlite3
import json... |
from django.core.management.base import BaseCommand, CommandError
from bankruptcy.cases.models import Case, DocketEntry, Document
class Command(BaseCommand):
help = 'Consolidate entities'
def handle (sself, *args, **options):
cases = Case.objects.all()
case_count = cases.count()
for i... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
import os
from bob.pipelines import DelayedSample, SampleSet
from bob.db.base.utils import check_parameters_for_validity
import csv
import bob.io.base
import functools
import numpy as np
import itertools
import logging
import bob.db.base
from bob.bio.base.pipeline... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# MIT: https://opensource.org... |
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
return heapq.nsmallest(k, arr)
|
from django.db import models
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=256, default='')
text = models.TextField(default='')
creation_date = models.DateTimeField(blank=True, null=True)
def __str__(self):
... |
from typing import TypedDict
class IConstituentConfig(TypedDict):
entity_tag: str
display_name: float
|
#! /usr/bin/env python3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Author: Giangi Sacco
# Copyright 2012, by the California Institute of Technology. ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged.... |
from ..grammar.state import Label, State, STATE_LABEL, States
from ..grammar.symbols import Symbols
from tokenize import NAME, OP, NEWLINE, ENDMARKER, ERRORTOKEN
class _Symbols(Symbols):
attr = 257
attrs = 258
item = 259
stmt = 260
module = 261
asdl = 262
symbols = _Symbols()
attr = State(Fa... |
# -*- coding: utf-8 -*-
from multiprocessing import Pool
import math
import nltk
import sys
import os
def runn(data, index, size, path):
print("jjjjj"+str(index))
if __name__ == '__main__':
if len(sys.argv) == 2:
path = sys.argv[1]
f = open(path, "r", encoding='UTF-8')
print(path)
... |
import numpy as np
import torch
from torch import nn
class LinearModel(nn.Module):
def __init__(self, dim_input, num_of_classes):
"""
Parameters
----------
dim_input: int > 0
number of neurons for this layer
num_of_classes: int > 0
number of classes... |
import unittest
import tfexpt
import expt
class TestAccNative(unittest.TestCase):
def testIt(self):
acc,loss = expt.runMain(250)
self.assertTrue(acc >= 0.205)
class TestAccTF(unittest.TestCase):
def testIt(self):
acc = tfexpt.runMain(250)
self.assertTrue(acc >= 0.27)
if __name__ == "__main__":
... |
# This is an example VISAN script showing the extraction and plotting of ECMWF MARS data in GRIB format
# Make sure to set the 'products-file directory' option in the VISAN Preferences panel
# to a directory containing ECMWF MARS GRIB products.
# This example will then take the first product it finds in this director... |
import json
import os
from builder.network_builder import Network
class Generator:
def __init__(self):
self.best_accuracy = 0
self.best_accuracy_logdir = None
self.best_network_spec = None
def get_best_spec (self, logdir):
# get all netswork.json
for subdir, dirs, file... |
import json
import glob
import io
data = {
"AUDIO": {
"SAMPLE_RATE": 8000,
"SPEAKERS_TRAINING_SET": [
],
"SPEAKERS_TESTING_SET": [
]
}
}
conf_jsonpath = '/home/rice/PycharmProjects/deep-speaker-master/conf.json'
speakerjson = data
train_speakerids = glob.glob('/run/media/rice/DATA/tripletdata_... |
import unittest
import zserio
from testutils import getZserioApi
class UnionTemplatedFieldTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "templates.zs").union_templated_field
def testReadWrite(self):
uintUnion = self.api.TemplatedUnion_uint16_u... |
plus = 'script/adblock+adguard.txt'
no = list(set(plus))
with open(plus,w) as f
f.write(no)
|
# -*- coding: utf-8 -*-
from pyquery import PyQuery
import datetime
import sqlite3
def delete_brands_generator():
url = 'http://www.jpx.co.jp/listing/stocks/delisted/index.html'
q = PyQuery(url)
for d, i in zip(q.find('tbody > tr > td:eq(0)'),
q.find('tbody > tr > td:eq(2)')):
... |
# rps data for the rock-paper-scissors portion of the red-green game
# to be imported by rg.cgi
# this file represents the "host throw" for each numbered round
rps_data = {
0: "rock",
1: "rock",
2: "scissors",
3: "paper",
4: "paper",
5: "scissors",
6: "rock",
7: "scissors",
8: "pape... |
# Generated by Django 3.0.3 on 2020-04-17 21:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('usermanagement', '0008_profile_anonymous'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='NTNU... |
import data.model
from endpoints.keyserver.models_interface import (
KeyServerDataInterface,
ServiceKey,
ServiceKeyDoesNotExist,
)
class PreOCIModel(KeyServerDataInterface):
"""
PreOCIModel implements the data model for JWT key service using a database schema before it was
changed to support ... |
from distutils.core import setup
long_description = """
A pure-Python tiling window manager.
Features
========
* Simple, small and extensible. It's easy to write your own layouts,
widgets and commands.
* Configured in Python.
* Command shell that allows all aspects of
Qtile to be managed and ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 2 11:03:28 2020
@author: Tarun Jaiswal
"""
a=int(input("Enter the first no="))
b=int(input("Enter the second no= "))
c=int(input("Enter the third no="))
print("a={0}".format(a))
print("b={0}".format(b))
print("c={0}".format(c))
if a>=b and a>=c:
max=a
else:
... |
# -*- coding: utf-8 -*-
"""
Batch sampler
Defines how to sample the streamlines available in the MultiSubjectData.
- Defines the __iter__ method:
- Finds a list of streamlines ids and associated subj that you can later
load in your favorite way.
- It is possible to restric... |
import os
import unittest
from unittest.mock import patch
from requests.auth import HTTPBasicAuth
from shutterstock.utils.prettyprint import pretty_print
from shutterstock.utils.request import get, put, post, delete
from shutterstock.utils.request_helper import RequestHelper
class UtilTests(unittest.TestCase):
"... |
from django.forms import ModelForm ,Textarea
from reports.models import DailyReport ,ReportActivity
from django import forms
class ReportActivityForm(ModelForm):
class Meta:
model=ReportActivity
fields=['activity','cp','area','description','remarks']
# widgets={
# ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from chk import checkpoint_sequential_step, checkpoint
import math
import numpy as np
from torchvision.utils import save_image
import gin
def ginM(n): return gin.query_parameter(f'%{n}')
gin.external_configurable(nn.MaxPool2d, module='nn')
gin.extern... |
# encoding: utf-8
# Author: Bingxin Ke
# Created: 2021/10/28
from collections import defaultdict
from src.io import RasterReader, RasterWriter
from src.utils.libraster import dilate_mask
import numpy as np
import os
from typing import Dict
from rasterio.transform import Affine
from tabulate import tabulate
from dateti... |
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url('^manifest-revalidation$', views.manifest_revalidation,
name='zadmin.manifest_revalidation'),
)
|
#!/usr/bin/env python
# Copyright (c) 2014 Johns Hopkins University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# noti... |
#%% import
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
import os
#%% prepare chinese character dataset
dataset = keras.preprocessing.image_dataset_from_directory(
"white256", label_mode=None, color_mode='grays... |
#!/usr/bin/env python
# coding: utf-8
# # SMIB system as in Milano's book example 8.1
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from IPython.core.display import HTML
get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'")
plt.ion()
# In[2]:
get_ipython().run_line_magic('m... |
from cloudaux.aws.ec2 import describe_images
from cloudaux.aws.ec2 import describe_image_attribute
from cloudaux.decorators import modify_output
from flagpole import FlagRegistry, Flags
registry = FlagRegistry()
FLAGS = Flags('BASE', 'KERNEL', 'RAMDISK', 'LAUNCHPERMISSION', 'PRODUCTCODES')
@registry.register(flag=FL... |
# see https://github.com/WolfgangFahl/gremlin-python-tutorial/blob/master/test_001.py
from tutorial import remote
# initialize a remote traversal
g = remote.RemoteTraversal().g()
# test the number of vertices
def test_VCount():
vCount=g.V().count().next()
print ("g.V().count=%d" % (vCount))
assert vCount == 6
... |
class NoSuchEventException(Exception):
r""""""
def __init__(self, message=None):
if message is None:
message = "The specified event is not registered."
super(NoSuchEventException, self).__init__(message)
|
# Generates Random char sequence
# The Grabs a random word within a set char length to use as the base
# The char length is based on a difficulty setting
import random
# Shuffles the word in place
def WordScrambler(word):
listWord = list(word)
random.shuffle(listWord)
result = ''.join(listWord)
... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import init, get_clones
from .attention import Encoder
class MLPLayer(nn.Module):
def __init__(self, input_dim, hidden_size, layer_N, use_orthogonal, use_ReLU):
super(MLPLayer, self).__init__()
self._... |
from markdownTable import markdownTable
import json
with open('idl.json') as f:
idl = json.load(f)
for ins in idl['instructions']:
print('### ' + ins['name'])
print('#### Accounts')
print(markdownTable(ins['accounts']).setParams(row_sep = 'markdown', quote = False).getMarkdown())
... |
from django_filters.rest_framework import BaseInFilter, CharFilter, FilterSet
from titles.models import Title
class CharFilterInFilter(BaseInFilter, CharFilter):
pass
class TitleFilter(FilterSet):
category = CharFilterInFilter(
field_name='category__slug',
lookup_expr='in'
)
... |
import xml.etree.ElementTree
import os
files = os.listdir('feature_points')
categories = {}
types = {}
cn = 0
t = 0
m = []
classes = {}
cl = 0
y = []
indices = {}
ind = 0
for f in files:
name = f
if name[0] not in classes:
classes[name[0]] = cl
cl = cl + 1
y.append(classes[name[0]])
roo... |
#!/usr/bin/python3.5
# -*- coding utf-8
|
import json
import os
from django.core.management.base import BaseCommand
from home.models import ReplicaSet, DownloadLocation
from wcd_pth_migration.utils import generate_spectrals_for_dir
class Command(BaseCommand):
help = 'Clears the database of what torrents, trans torrents, also removes all torrents from t... |
# -*- coding: utf-8 -*-
from unittest import TestCase
from ..number_token import (
gen_float_token_with_digit,
gen_int_token_with_digit,
sub_token_with_value_sequentially,
NumberToken,
)
class NumberTokenTestCase(TestCase):
def run_test_denormalizable(self, test_cases, normalizer):
for te... |
from radixlib.api_types.identifiers import AccountIdentifier
from radixlib.api_types.token_amount import TokenAmount
from radixlib.serializable import Serializable
from typing import Optional, Dict, Any
import radixlib as radix
import json
class CreateTokenDefinition(Serializable):
""" Defines a CreateTokenDefinit... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainWin.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWin(object):
def setupUi(self, MainWin):
MainWin.setObj... |
from typing import Sequence, Iterable, List
from KafNafParserPy import KafNafParser, Cterm, Cwf
def sort_tokens(tokens: Iterable[Cwf]) -> List[Cwf]:
"""Sort tokens by natural order (sent, offset)"""
return sorted(tokens, key=lambda t: (t.get_sent(), int(t.get_offset())))
def sort_terms(naf: KafNafParser, ... |
transform_table = bytes.fromhex("c649139a6709de2b581e48534f9d35ae81d8c477ad96c1ee0c16321faa08e5ca8783fe45e01454ff5e107fd3202d2ea77b3e64a2846f91bfb441d6ef75aced5b3c50740f045d714b25ba9f3fe1608c33e7c7f41bc5bce2ecb3b143231a9c247ecdda826cd038707d0afd01114e7a97ce408826b7a086cb1799306e63988accd2025a56348ba4807c19429521b9c28e6... |
import os
import logging
import time
from azureml.core.authentication import ServicePrincipalAuthentication
_TENANT_ID_ENV_NAME = "TenantId"
_SERVICE_PRINCIPAL_ID_ENV_NAME = "ServicePrincipalId"
_SERVICE_PRINCIPAL_SECRET_ENV_NAME = "ServicePrincipalSecret"
def get_service_principal_auth():
tenant_id = os.enviro... |
"""
214. Shortest Palindrome
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it.
Find and return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dc... |
#!/usr/bin/env python
import argparse, yaml
from xidb import Guild
parser = argparse.ArgumentParser(description="Generate project xid")
parser.add_argument('-c', '--config', dest='config', required=True)
args = parser.parse_args()
with open(args.config) as f:
config = yaml.load(f.read())
guild = Guild(config)
p... |
import argparse
import logging
from role_analyzer import allows
import yaml
from z3 import Distinct, Solver, sat, unsat # type: ignore
def roles_are_equivalent(r1, r2) -> tuple[bool, str]:
r1 = allows(r1)
r2 = allows(r2)
s = Solver()
s.add(Distinct(r1, r2))
result = s.check()
if unsat == result:
return... |
#!/usr/bin/env python3
import unittest
class Fence:
def __init__(self, woods):
self.__woods = woods
self.size = len(woods)
self.__init_db()
def __init_db(self):
self.__left_db = self.__init_db_to_left()
self.__right_db = self.__init_db_to_right()
def height(self, ... |
from piece import Piece
from util import pattern, select, rep, join
from tones import tonify
from points import note, notes, chord, rest, tied_note
from markup import voices
class PreludeInCSimple(Piece):
def details(self):
self.title = "Prelude in C"
self.composer = "J. S. Bach"
self.opu... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-12 09:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fpraktikum', '0010_auto_20170910_1434'),
]
operations = [
migrations.CreateM... |
# compatibility with deprecated API
from nuclear.shell.shell_utils import shell, shell_error_code, shell_output
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
# Copyright 2013 Mirantis, 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 ... |
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""MXNet Framework Adapter plugin."""
from pickle import dumps
from pickle import loads
from typing import Dict
import mxnet as mx
import numpy as np
from mxnet import nd
from openfl.plugins.frameworks_adapters.framework_adapter_interf... |
import datetime as dt
from django.dispatch import receiver
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from django_scopes import scope
from pretalx.common.models.settings import hierarkey
from pretalx.common.signals import periodic_task
f... |
"""
This file contains functions to convert CML style puncturing configurations
for turbo codes to "interleaving sequences" good for the IT++ implementation
"""
import numpy as np
def getInterleaving(msg_len, num_g1, num_g2, constraint_length, punc1, punc2,
tail1, tail2):
"""
Returns, a l... |
__author__ = 'bartek'
from py2neo import Node, Relationship
class Groups:
LABEL = "GROUP"
@staticmethod
def create_group(db, name, owner):
node = Node(Groups.LABEL, name=name)
db.create(node)
rel = Relationship(owner, Relationships.OWNS, node)
db.create(rel)
@staticm... |
import re
import argparse
def fastq_to_fasta(fastq_in, fasta_out=None):
# idea copied from Humann2
with open(fastq_in, "r") as fp_fastq_in:
fp_fasta_out = None
if fasta_out:
fp_fasta_out = open(fasta_out, "w")
line = fp_fastq_in.readline()
while line:
... |
from sqlalchemy import Column, Integer, String
from .views import db
class MemberOfParliament(db.Model):
def __init__(self, url=None, profile_pic=None, name=None, detail=None, party=None, gender=None):
self.url = url
self.profile_pic = profile_pic
self.name = name
self.detail = de... |
# Dumping Format
# [
# {
# "contact": 0/1,
# "region": target_region,
# "anchor_id": anchor_list,
# "anchor_elasti": elasti_mat.tolist(),
# }
# ]
# and
# {
# "object_tsl": np.array(3,)
# "object_rot": np.array(3,3)
# "hand_tsl": np.array(3,)
# "hand_rot": np.array(3,3)
# "han... |
from presurvey.models import BostonZip
b = BostonZip(zipcode='01760', name='Framingham')
b.save()
b = BostonZip(zipcode='01730', name='Bedford')
b.save()
b = BostonZip(zipcode='01731', name='Hanscom Air Force Base')
b.save()
b = BostonZip(zipcode='01773', name='Lincoln')
b.save()
b = BostonZip(zipcode='01801', name='W... |
# greaseweazle/tools/reset.py
#
# Greaseweazle control script: Reset to power-on defaults.
#
# Written & released by Keir Fraser <keir.xen@gmail.com>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
description = "Rese... |
#!/usr/bin/env python3
""" 引数1=現在のAP,引数2までの時間,引数2がなければ40の倍数"""
import sys
import time
import datetime
APOverflow = "現在,APの最大値は139です。"
AP_LIMIT = 139
def error():
sys.exit(2)
""" ここまで回復"""
count = 0
if len(sys.argv) > 3:
error()
elif len(sys.argv) == 3:
if int(sys.argv[1]) >= int(sys.argv[2]):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.