content stringlengths 5 1.05M |
|---|
"""this file router for delete user."""
from app import app
from db.db_queries.get_user_for_delete_query import get_user_for_delete, \
redirect_recipe
from db.db_queries.get_user_query import get_user
from flask import flash, redirect, url_for
from models.db impor... |
#coding:utf-8
'''
filename:points_distance.py
chap:5
subject:11
conditions:pionts a,b
solution:distance(a,b)
'''
import math
def distance(a:tuple,b:tuple)->float:
c = sum([(a[i]-b[i])**2 for i in range(2)])
return math.sqrt(c)
print(distance((0,2),(0,4)))
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
class CdmError(Exception):
"""Base CDM exception"""
|
#!/usr/bin/env python3
import os
import sqlite3
from pygments.formatters import HtmlFormatter
self_dir = os.path.dirname(os.path.realpath(__file__))
print("Setting up database...", end="")
db = sqlite3.connect(self_dir + "/data/db.sqlite")
db.execute("""
CREATE TABLE IF NOT EXISTS pastes (
id CHAR(8) PRIMARY KEY,
... |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def paginator(request, queryset, per_page=25):
per_page = request.GET.get('per_page', per_page)
paginator = Paginator(queryset, per_page)
page = request.GET.get('page')
try:
return paginator.page(page)
except PageNot... |
import os
import pandas as pd
import csv
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from datetime import datetime
import compress_json
def export_key(out):
"""Export Generated Key Template"""
data_name = "Master_Key/master_key.csv"
exists = os.path.exists(data_name)... |
"""
Collection of Numpy math functions, wrapped to fit Ivy syntax and signature.
"""
# global
import numpy as _np
try:
from scipy.special import erf as _erf
except (ImportError, ModuleNotFoundError):
_erf = None
tan = _np.tan
asin = _np.arcsin
acos = _np.arccos
atan = _np.arctan
atan2 = _np.arctan2
sinh = _np... |
try: # Python 3.5+
from http import HTTPStatus as HTTPStatus
except ImportError:
from http import client as HTTPStatus
from flask import Blueprint, jsonify, request
import json
import logging
from v1.db.db import Db
from v1.auth.auth import auth
from mongoengine import *
unsubscribe = Blueprint('unsubscribe',... |
"""
IMAP sensor support.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.imap/
"""
import logging
import voluptuous as vol
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassist... |
from typing import Optional
from ..interfaces.data_manager import DataManager
from ..mixins.pandas_storage_manager import PandasStorageManager
from ..mixins.configured_resource_manager import ConfiguredResourceManager
from ..mixins.logger import Logger
from ..mixins.string_path_resolver import StringPathResolver
cl... |
import wx
class StartPanel(wx.Panel):
def __init__(self,parent,id):
wx.Panel.__init__(self,parent,id)
self.parent = parent
self.txt = wx.StaticText(self, label="Drag A Pak File To Here")
self.txt.SetFont(wx.Font(15, wx.DEFAULT, wx.SLANT, wx.BOLD))
Vsizer = wx.BoxSize... |
import pickle
from os.path import join as pjoin
import click
import pandas
from vocabirt.embed_nn.loader.common import CVSplitEhara
from vocabirt.embed_nn.utils import get_sv12k_word_list
from .vocabirt2pl_svl12k import estimate_irt
def split_modewise(split_mode, df, words):
total_resp_splits = 3 if split_mode... |
import requests
import os
import config
from templates.text import TextTemplate
OPENWEATHER_API = os.environ.get('OPENWEATHER_API', config.OPENWEATHER_API)
def process(input, entities, sender):
output = {}
try:
location = entities['location'][0]['value']
r = requests.get('http://api.openweather... |
"""Simple test for monochromatic character LCD"""
import time
import board
import digitalio
import adafruit_character_lcd.character_lcd as characterlcd
# Modify this if you have a different sized character LCD
lcd_columns = 16
lcd_rows = 2
# Metro M0/M4 Pin Config:
lcd_rs = digitalio.DigitalInOut(board.D7)
lcd_en = d... |
from http.server import HTTPServer
from .handlers.http_request_handler import HttpRequestHandler
from .router.router import Router
class Application(Router):
def __init__(self):
super().__init__()
self.instance = None
self.asset_directory = {}
pass
def define... |
from aws_cdk import core
from aws_cdk import (aws_dynamodb,
aws_apigateway,
aws_lambda,
aws_s3,
aws_lambda,
aws_sns,
aws_sns_subscriptions,
aws_ecs,
... |
# -*- encoding: latin-1 -*-
import sys
MKL_THREADS_VAR = str(sys.argv[1])
import os
os.environ["MKL_NUM_THREADS"] = MKL_THREADS_VAR
os.environ["NUMEXPR_NUM_THREADS"] = MKL_THREADS_VAR
os.environ["OMP_NUM_THREADS"] = "1"
from numpy import *
from ir_load import ir_load
from parameters import parameters
from hamiltoni... |
matrix=[[1,4,7,3],[12,63,43,65],[12,55,22,77]]
for i in range(4):
lst=[]
for row in matrix:
print(row[i])
transposed=[[row[i] for row in matrix] for i in range(4)]
print(transposed)
|
import root_pandas
import pandas as pd
import numpy as np
from nose.tools import raises
def test_simple():
filename = 'tests/samples/simple.root'
reference_df = pd.DataFrame()
reference_df['one'] = np.array([1, 2, 3, 4], dtype=np.int32)
reference_df['two'] = np.array([1.1, 2.2, 3.3, 4.4], dtype=np.fl... |
#!/usr/bin/env python
import argparse
from scapy.all import load_layer
from scapy.sendrecv import AsyncSniffer
from meter.flow_session import generate_session_class
def create_sniffer(input_file, input_interface, output_mode, output_file):
assert (input_file is None) ^ (input_interface is None)
NewFlowSes... |
import jsonpatch
import re
import subprocess
import sys
import typer
import yaml
from pathlib import Path
from loguru import logger
app = typer.Typer(add_completion=False)
def _setup_logging(debug):
"""
Setup the log formatter for this script
"""
log_level = "INFO"
if debug:
log_level =... |
"""
Copyright: Wenyi Tang 2017-2018
Author: Wenyi Tang
Email: wenyi.tang@intel.com
Created Date: Oct 15th 2018
Extend the pre-Environment module, provide different and extensible
training methodology for SISR, VSR or other image tasks.
"""
# Copyright (c): Wenyi Tang 2017-2019.
# Author: Wenyi Tang
# Email: wenyi.... |
from flask import render_template, request, redirect, url_for,abort
from app.main import main
from flask_login import login_required, current_user
from app.main.forms import UpdateProfile, PitchForm, CommentForm
from .. import db,photos
from app.models import User, Pitch, Comment, ProfilePhoto
@main.route('/')
def ind... |
# -*- coding: utf-8 -*-
"""
test_utils.py
Copyright 2017 CodeRatchet
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
"""
from sc... |
from ._celery import app as celery_app
__all__ = ["celery_app"]
|
import sys, socket, os, re, time
from index import Index
THREADS = 32 # num of threads processing the queue
def process_file_name_and_text(path):
with open(path) as f:
return path.replace("/","\\"), f.read()
def load_directories(path):
docs = [path]
while docs:
top = docs.pop()
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 3/28/2018 2:27 PM
# @Author : sunyonghai
# @File : simple_argparse.py.py
# @Software: ZJ_AI
# =========================================================
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True, help="name ... |
from collections import deque
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# build graph
graph, indeg = {i:[] for i in range(numCourses)}, {i:0 for i in range(numCourses)}
for end, start in prerequisites:
graph[start].append(end)
... |
import datetime
import unittest
from pikax import params, ClientException, APIUserError
from pikax import settings
from pikax.api.androidclient import AndroidAPIClient
class AndroidClientTest(unittest.TestCase):
def setUp(self) -> None:
self.client = AndroidAPIClient(settings.username, settings.password... |
import numpy as np
from common.constant import *
from utils.data_load import normalize
class ClusteringAlgorithm():
""" 聚类算法 """
def __init__(self, X : np.ndarray, cluster_num : int):
self.X = X
self.c = cluster_num
self.n = X.shape[MatrixShapeIndex.column]
... |
# 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... |
import re
import unicodedata
from django.contrib.auth.models import PermissionsMixin
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.core import exceptions
from django.utils.translation import gettext_lazy as _
from taggit.managers import TaggableManager
from taggit... |
import unittest
from datetime import timedelta
import simplekv.memory
from flask import Flask
from flask_jwt_extended.config import get_access_expires, get_refresh_expires, \
get_algorithm, get_blacklist_enabled, get_blacklist_store, \
get_blacklist_checks, get_auth_header
from flask_jwt_extended import JWTMa... |
#!/usr/bin/env python
# coding=utf-8
"""Unit tests for pyiosxr, a module to interact with Cisco devices running IOS-XR."""
import os
import sys
import time
import unittest
from lxml import etree as ET
from six import binary_type
# ~~~ import pyIOSXR modules ~~~
from napalm.pyIOSXR import IOSXR
# exceptions
from napa... |
#!/usr/bin/env python
# Copyright 2014 Red Hat, 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... |
from typing import Dict, List
import json
def assert_properties_unset(metadata: Dict, must_not_be_set: Dict):
for (key, must_not_value) in must_not_be_set.items():
if key in metadata:
value = metadata[key]
if isinstance(must_not_value, dict):
assert_properties_unset... |
from stack_and_queue import __version__
import pytest
from stack_and_queue.stack_and_queue import Stack , Queue
def test_version():
assert __version__ == '0.1.0'
def test_push_onto_a_stack():
node = Stack()
node.push(1)
excepted =1
actual = node.top.data
assert excepted == actual
def test_p... |
"""SCons.Sig.MD5
The MD5 signature package for the SCons software construction
utility.
"""
#
# __COPYRIGHT__
#
# 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, includi... |
# Generated by Django 2.0.5 on 2018-09-29 13:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('repository', '0006_auto_20180927_2213'),
]
operations = [
migrations.AlterField(
model_name='ar... |
from google_trans_new import google_translator
from progressbar import progressbar
from random import shuffle, randint
LANGUAGES = ['af', 'sq', 'am', 'ar', 'hy', 'az', 'eu', 'be', 'bn', 'bs', 'bg', 'ca', 'ceb', 'ny', 'zh-cn', 'zh-tw', 'co', 'hr', 'cs', 'da', 'nl', 'en', 'eo', 'et', 'tl', 'fi', 'fr', 'fy', 'gl', 'ka'... |
from setuptools import setup
setup(
name="Flask-WTF",
install_requires=["Flask", "WTForms", "itsdangerous"],
extras_require={"email": ["email-validator"]},
)
|
#!/usr/bin/python3
from asyncore import write
from fileinput import close
import math
import subprocess
import pandas as pd
import os
import sys
from optparse import OptionParser
from bio_processing import bio_processing
#option_parser
optParser = OptionParser()
print("check file path: ")
print(os.path.dirname(os.pa... |
data['2012'].mean().plot(kind='bar') |
# -*- coding: utf-8 -*-
'''
ขอขอบคุณ คุณ Korakot Chaovavanich สำหรับโค้ด word_frequency จาก https://www.facebook.com/photo.php?fbid=363640477387469&set=gm.434330506948445&type=3&permPage=1
'''
from __future__ import absolute_import,division,unicode_literals,print_function
import re
import requests
import os
import cod... |
# ---------------------------------------------------------------------
# Vendor: GWD (GW Delight Technology Co., Ltd) http://www.gwdelight.com
# OS: GFA
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------... |
# Generated by Django 2.1.5 on 2019-03-27 18:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('gsndb', '0003_auto_20190326_2144'),
]
operations = [
migrations.RenameField(
model_name='student',
old_name='birth_date',
... |
from setuptools import setup, find_packages
from glob import glob
from distutils.extension import Extension
# from Cython.Distutils import build_ext
from os.path import pathsep
import numpy as np
try:
from Cython.Build import cythonize
except ImportError:
cythonize = False
# Cython extensions
ext... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.anovaglm import H2OANOVAGLMEstimator
# Simple test to check correct NA handling skip.
def testFrameTransform():
train = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip"))
y... |
from django.urls import path
from .views import ProjectListView, ProjectDetailView
app_name = 'upload'
urlpatterns = [
path('', ProjectListView.as_view(), name='project-list'),
path('projects/<slug:slug>/', ProjectDetailView.as_view(), name='project-detail'),
] |
import maya.cmds as cmds
from functools import partial
# Creates a connection between the 2 selected objects with a reverse node to drive to values in opposite directions of each other based on one attr.
# This is mostly used for having a single attr drive the 2 weights on a constraint with 2 sources in opposi... |
import unittest
import pytest
import numpy as np
from pathlib import Path
from rearrangement.datasets_cfg import SYNTHETIC_DATASETS, REAL_DATASETS, DS_DIR
from rearrangement.dataset.lmdb import LMDBDataset
from rearrangement.dataset.statedataset import StateDataset
from rearrangement.dataset.real_scene_dataset import ... |
import json
def tojsonsingle(result, file_path="./data.json"):
data = {}
for i in range(len(result['text'])):
data[i] = result['text'][i]['predicted_labels']
with open(file_path, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, ensure_ascii=False)
def tojsondual(result1, resu... |
import twitter_mention_frequency, twitter_get_user_timeline
import NLP_stats_repackaged, Doc_to_Vec_Refactored
import network_analysis, network_crawler
import Cluster_Analysis_NLP_with_Word_Clouds
import twitter_make_geojson, twitter_make_map
from nltk import FreqDist
import sys
from subprocess import call
from os im... |
import sys
if len(sys.argv) != 4:
print("must enter 3 values")
exit(1)
cost = float(sys.argv[1])
tip = float(sys.argv[2])
tax = float(sys.argv[3])
tipPercent = (cost * tip) / 100
taxPercent = (cost * tax) / 100
totalCost = cost + tipPercent + taxPercent
l = totalCost
m = (totalCost * 100) - (1 * 100)
if m >... |
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.postgres.search import SearchVector
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.utils import timezone
from django.utils.translation import ugettext as _
from djang... |
from pytest import fixture
@fixture(scope="module")
def add_end_user_advisory(context, api_test_client):
api_test_client.parties.add_eua_query()
context.end_user_advisory_id = api_test_client.context["end_user_advisory_id"]
context.end_user_advisory_name = api_test_client.context["end_user_advisory_name"]... |
import numpy as np
import os
from random import Random
import glob
import sys
import imageio
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
"""
This code is inspired from
HW2 of https://cs330.stanford.edu/
"""
def get_images(paths, labels, random, nb_samples=None, shuffle=True):
"""
... |
import pytest
from weaverbird.backends.sql_translator.metadata import ColumnMetadata, SqlQueryMetadataManager
from weaverbird.backends.sql_translator.steps import translate_dateextract
from weaverbird.backends.sql_translator.steps.utils.query_transformation import (
get_query_for_date_extract,
)
from weaverbird.ba... |
# encoding:utf-8
from app import app, db
from flask import g, abort
from app.submission.models import Submission
from app.common.models import JudgementStatus
from app.common.user import User
from utils import success, get_day_zero_time
from datetime import datetime, timedelta
from sqlalchemy import and_
@app.route('... |
from ... import config
if config.get('qapp', False):
from .consolepanel import MainThreadConsole, SubThreadConsole, ChildProcessConsole, ChildThreadConsole
from .consoleproxy import ConsoleGuiProxy |
"""
pip-review lets you smoothly manage all available PyPI updates.
"""
from setuptools import setup
setup(
name='pip-review',
version='1.1.0',
url='https://github.com/jgonggrijp/pip-review',
license='BSD',
author='Julian Gonggrijp, Vincent Driessen',
author_email='j.gonggrijp@gmail.com',
... |
# Generated by Django 3.1.3 on 2020-12-16 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('solver', '0003_parent_solve_attempt'),
]
operations = [
migrations.AddField(
model_name='parent',
name='initialized'... |
#!/usr/bin/env python3
"""
Load necessary values from the coursera sql extract into a sqlite3 database.
"""
import json
import os
import sys
from csv import reader, field_size_limit
from datetime import datetime
from sqlite3 import connect, Error
from bs4 import BeautifulSoup
from gensim.parsing.preprocessing import pr... |
"""Tests cac.models.dimensionality_reduction.DimensionalityReductionModel"""
import os
from os.path import dirname, join, exists
from copy import deepcopy
import torch
import wandb
import unittest
from tqdm import tqdm
from torch.nn import Conv2d, BatchNorm2d, LeakyReLU
from cac.config import Config
from cac.utils.logg... |
import os
from . import config
class MiscConfigError(Exception):
pass
class Misc(object):
"""Misc config object."""
__KEYS = ['testlib', 'desc', 'out']
def __init__(self, data):
self.testliblib = None
self.desc = None
self.out = None
self.update(data)
def updat... |
import Quandl
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
api_key = open('quandlapikey.txt', 'r').read()
def mortgage_30y():
df = Quandl.get('FMAC/MORTG', trim_start="1975-01-01", authtoken=api_key)
df['Value'] = (df['Value'] - d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from djanban.apps.recurrent_cards.models import WeeklyRecurrentCard
# Create cards based on recurrent cards
class ... |
#!/usr/bin/python
#
# Copyright 2018-2022 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 ... |
from .pointer_network import PointerNetwork |
import pytest
from django.urls import reverse
from {{ cookiecutter.project_slug }}.users.models import User
pytestmark = pytest.mark.django_db
class TestUserAdmin:
def test_changelist(self, admin_client):
url = reverse("admin:users_user_changelist")
response = admin_client.get(url)
asser... |
import sys
import tempfile
import re
import subprocess
def compile_krass_conditional(krass_conditional):
"""
Compile Krass conditional statements to Python conditional statements.
"""
# change true to True, && to and etc.
changes = [
("true", "True"),
("false", "False"),
("&&", " and "),
("||", " or "), ... |
from .trial_registry import Registry
from .trial_bot import TrialBot, Events, State
from .updater import Updater
from .updaters.training_updater import TrainingUpdater
from .updaters.testing_updater import TestingUpdater
from . import extensions as bot_extensions
|
import math
import numpy as np
from .detail.timeindex import to_timestamp
from .calibration import ForceCalibration
class Slice:
"""A lazily evaluated slice of a timeline/HDF5 channel
Users will only ever get these as a result of slicing a timeline/HDF5
channel or slicing another slice (via this class' ... |
from typing import Optional
from starlite import get
from starlite.utils import create_function_signature_model
def test_create_function_signature_model_parameter_parsing():
@get()
def my_fn(a: int, b: str, c: Optional[bytes], d: bytes = b"123", e: Optional[dict] = None) -> None:
pass
model = cr... |
import unittest
from io import BytesIO
from id3vx.frame import FrameHeader, Frame, TextFrame, Frames, PCNT
from id3vx.frame import CHAP, MCDI, NCON, COMM, TALB, APIC, PRIV
from id3vx.tag import TagHeader
class FramesTests(unittest.TestCase):
def test_reads_frames_from_file(self):
# Arrange
header... |
import os
import sys
from .neural_net import *
from .io import *
# # train_autoencoder(8,3,8)
test_predictions(pickle = False)
# cross_validation()
# vary_hidden_layer_size()
# vary_iterations()
|
from data import AudioPipeline, NoisedAudPipeline, dataset, get_data_loader
from torch.nn.parallel import DistributedDataParallel
from torch.multiprocessing import spawn
from torch.utils.tensorboard import SummaryWriter
from data import get_distributed_loader
from torch.utils.data import DataLoader
from abc import ABC,... |
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import praw
# email = "samuellawrenceJSE@gmail.com"
# password = "JSEStocksGoUp"
#Praw API login
username = "SamTheIceCreamMan"
password = "Samernator1"
id = "U9EagV0j3qUSbw"
secret = "Su_o5xTzvs4RKygGOBakQFutxw49-A"
u... |
#!/usr/bin/python -u
# ./gen_mlp_init.py
# script generateing NN initialization
#
# author: Karel Vesely
#
import math, random
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--dim', dest='dim', help='d1:d2:d3 layer dimensions in the network')
parser.add_option('--gauss', de... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="populate_secrets_gitlab",
version="0.2.0",
author="Joe Niland",
author_email="joe@deploymode.com",
description="Populate Gitlab CI/CD Variables from .env file",
long_... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
from collections import OrderedDict
from ceci.sites.cori import parse_int_set
from ceci.pipeline import override_config
from ceci.utils import embolden
from ceci.config import cast_value, cast_to_streamable
def test_parse_ints():
assert parse_int_set("1,2,3") == set([1, 2, 3])
assert parse_int_set("10-12") ... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Generic algorithms such as registration, statistics, simulation, etc.
"""
from __future__ import absolute_import
__docformat__ = 'restructuredtext'
from . import statistics
from . import fwhm, interpol... |
"""
@Author: NguyenKhacThanh
"""
__all__ = ["init_app"]
def _after_request(response):
"""Add headers to after request
"""
# allowed_origins = [
# re.compile("http?://(.*\.)?i2g\.vn"),
# ]
# origin = flask.request.headers.get("Origin")
# if origin:
# for allowed_origin in allo... |
# Generated by Django 3.1.2 on 2020-12-18 20:17
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apis', '0019_auto_20201218_2012'),
]
operations = [
migrations.AlterField(
model_name='commentapimodel',
... |
from app import cache
from base26 import Base26Converter
from database import urltable
class ShortURL:
def __init__(self):
self.__cacheUrlExpireTimeout: int = 300
self.__base26 = Base26Converter()
cache.setUrlTableObject(urltable=urltable)
def getShortURL(self, longURL: str):
... |
from django.apps import AppConfig
class ContractsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'contracts'
|
import argparse,os
parser = argparse.ArgumentParser(description='sequencing saturation')
parser.add_argument('--action', metavar='SELECT', default='mkref', choices=['mkref', 'mkgtf', 'stat'], help='Select the action for your program, include mkref,mkgtf,stat, default is mkref')
parser.add_argument('--ingtf', metavar='... |
print("\n")
texto = input(" Digite um texto: ")
print("\n")
print("Texto digitado: " + texto)
print("\n") |
# cssyacc/parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = b'\xd5t\xfa\x19\xdba\xab\x8dqF\x98h\xbfOA\x9c'
_lr_action_items = {'BRACES_L':([0,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,37,38,39,40,... |
# -*- coding: utf-8 -*-
# ------------- Cantidad de segundos que has vivido -------------
# Definición de variables
anios = 30
dias_por_anio = 365
horas_por_dia = 24
segundos_por_hora = 60
# Operación
print (anios * dias_por_anio * horas_por_dia * segundos_por_hora)
|
from .draw import plot |
# System modules.
from datetime import datetime
# 3rd party modules.
from flask import make_response, abort
import requests
# Personal modules.
from config import db
from models import Master, MasterSchema, Detail, DetailSchema
# Get current time as a timestamp string.
def _get_timestamp():
return datetime.now... |
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
DEFAULT_UPLOAD_TO = 'product_images'
class ImageProduct(models.ForeignKey):
def __init__(
self,
to='products.Product',
verbose_name=_("Product"... |
#
# This file is part of GreatFET
#
from .base import GlitchKitModule
from ..protocol import vendor_requests
from ..peripherals.gpio import GPIOPin
class GlitchKitSimple(GlitchKitModule):
"""
Simple trigger module for GlitchKit. Provides simple trigger conditions
(e.g. "the SPI clock ticks 25 times while ... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import labgraph as lg
from typing import Dict, Tuple
# Make the imports work when running from LabGraph root directory
import sys
sys.path.append("./")
# LabGraph WebSockets Components
from labgraph.websockets.ws_server.ws_api_node_server... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from gnpy.core.utils import (load_json,
itufs,
freq2wavelength,
lin2db,
db2lin)
from gnpy.core import ne... |
from __future__ import print_function
import h5py
import sys
import numpy as np
class NanoporeModel(object):
def __init__(self, fast5File):
self.fastFive = h5py.File(fast5File, "r")
self.stay_prob = 0
self.skip_prob_bins = []
self.model_name = ''
self.model = None
def ... |
# -*- coding: iso-8859-1 -*-
#
# http://en.wikipedia.org/wiki/Fourier_series
#
"""
http://rosettacode.org/wiki/Fast_Fourier_transform
http://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm
http://en.wikipedia.org/wiki/Discrete_Fourier_transform
http://es.wikipedia.org/wiki/Transformada_de_Fourier_discreta
"""
from... |
# coding=utf-8
from terminaltables import AsciiTable
import numpy as np
from random import randint
from mygrid.rnp import Arvore, Aresta
from mygrid.util import Fasor, Base
class Setor(Arvore):
def __init__(self, nome, vizinhos, nos_de_carga, prioridade=0):
assert isinstance(nome, str), 'O parâmetro nome ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.