content stringlengths 5 1.05M |
|---|
import numpy as np
def get_random_int():
return np.random.randn(10) |
# Dr. Kaputa
# pyqt pong example
import sys
from PyQt4 import QtGui, QtCore
class Pong(QtGui.QMainWindow):
Key_K = QtCore.pyqtSignal()
Key_M = QtCore.pyqtSignal()
Key_A = QtCore.pyqtSignal()
Key_Z = QtCore.pyqtSignal()
def __init__(self):
super(Pong, self).__init__()
self.statusBar().show... |
from .face_analysis import *
|
# encoding: utf-8
import argparse
import qtciutil
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Build Arg Parser')
parser.add_argument('--pro_file', '-p', type=str, required=True,
help='pro path', metavar='$CI_PROJECT_DIR/test/something.pro')
parser.add_argument(... |
import fenics as fe
import numpy as np
import matplotlib.pyplot as plt
import sys
plt.rcParams.update({'font.size': 12})
def matMult(A,x):
''' Multiply a 2by2 matrix with a 2by1 vector '''
return [ A[0][0]*x[0]+A[0][1]*x[1] , A[1][0]*x[0] + A[1][1]*x[1] ]
def prettyPrint(A):
''' Print arrays in a pretty ... |
salario = 750
aumento = 15
print(salario + (salario*aumento/100)) |
import requests
import pandas as pd
# Runtime notes: ~8000 objects takes ~30 secs, ~65000 takes several minutes, 150k+ takes 10+ minutes
shop = 'YOUR SHOP NAME HERE' # Shop is what your shop is called in your homepage URL. EG. Shop called MyShop would be myshop.myshopify.com. Shop name = myshop
token = 'YOUR API ... |
from typing import List
import pytest
from di import Container, Dependant, SyncExecutor
from di.typing import Annotated
class Request:
def __init__(self, value: int = 0) -> None:
self.value = value
def endpoint(r: Request) -> int:
return r.value
def test_bind():
container = Container()
... |
arq = open("maneiro.txt", "r")
conteudo = arq.read()
for i in conteudo:
print(i, sep="", end="")
arq.close()
arq2 = open("maneirasso.txt", "w+")
arq2.write("Gororoba azul")
arq2.seek(0)
conteudo2 = arq2.read()
print("")
for i in conteudo2:
print(i, sep="", end="")
arq2.close()
|
from libctw import ctw
def create_model(deterministic=False, max_depth=None, num_factors=8):
cts = []
for i in xrange(num_factors):
cts.append(ctw.create_model(deterministic, max_depth))
return _Factored(cts)
def create_factored_model(bit_models):
"""Creates a factored model.
Bits on di... |
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.analytics_azure_output import AnalyticsAzureOutput
from bitmovin_api_sdk.models.response_envelope import R... |
order = balanced.Order.fetch(order_href) |
from build.management.commands.build_complex_models import Command as BuildComplexModels
class Command(BuildComplexModels):
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Convert a Zettelkasten into a Setevi HTML page """
import os
import sys
from libzk2setevi.convert import Zk2Setevi
def is_valid_file(parser, arg):
arg = os.path.abspath(arg)
if not os.path.exists(arg):
parser.error("The path %s does not exist!" % arg... |
import pickle
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.simplefilter("ignore")
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from ..data.utils import get_public_df_ohe, get_train_df_ohe, get_class_names, are_all_imgs_present
i... |
import dxr.plugins
def pre_process(tree, environ):
pass
def post_process(tree, conn):
pass
__all__ = dxr.plugins.indexer_exports()
|
import json
from aio_pubsub.interfaces import PubSub, Subscriber
from aio_pubsub.typings import Message
aioredis_installed = False
try:
import aioredis
aioredis_installed = True
except ImportError:
pass # pragma: no cover
class RedisSubscriber(Subscriber):
def __init__(self, sub, channel):
... |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from pathlib import Path
from typing import Optional
import numpy as np
from src.biota_models.coral.model.coral_model import Coral
from src.core.base_model import BaseModel
class Reef0D(BaseModel):
"""Implements the `HydrodynamicProtocol`."""
working_dir: Optional[Path] = None
definition_file: Optional... |
# We test the base and dummy together. |
import pytest
from pytest_mock import MockerFixture
from pystratis.api.collateralvoting import CollateralVoting
from pystratis.core.types import Address
from pystratis.core.networks import StraxMain
def test_all_strax_endpoints_implemented(strax_swagger_json):
paths = [key.lower() for key in strax_swagger_json['p... |
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, SearchField, DateTimeDyField, EnumDyField, SizeField
from spaceone.inventory.libs.schema.cloud_service_type import CloudServiceTypeResource, CloudServiceTypeResponse, \
CloudServiceTypeMeta
cst_sql_workspace = CloudServiceTypeResource()... |
import numpy as np
from pybind_isce3 import focus
def test_chirp():
T = 1.0
K = 0.0
fs = 1.0
chirp = focus.form_linear_chirp(K, T, fs)
assert np.allclose(chirp, [1+0j])
|
import re
import io
import os
import json
import uuid
import shutil
import random
import requests
from PIL import Image
from urllib import parse
from joblib import Parallel, delayed
ALL = None
CREATIVE_COMMONS = "Any"
PUBLIC_DOMAIN = "Public"
SHARE_AND_USE = "Share"
SHARE_AND_USE_COMMECIALLY = "ShareCommercially"
MODI... |
import numpy as np
import util.np
import util.rand
import util.mod
import util.dec
@util.dec.print_test
def test_flatten():
a = util.rand.rand(3, 5, 2)
b = util.np.flatten(a, 2)
b = np.reshape(b, a.shape)
assert util.np.sum_all(b == a) == np.prod(a.shape)
@util.dec.print_test
def test_arcsin():
... |
#!/usr/bin/env python
import os
from setuptools import setup
# Since masakari-controller does not own its own repo
# it can not derives the version of a package from the git tags.
# Therfore, we use PBR_VERSION=1.2.3
# to sikp all version calculation logics in pbr.
os.environ["PBR_VERSION"] = "1.2.3"
setup(
setu... |
from app.main import bp
from flask import render_template, url_for
from flask_login import login_required, current_user
from app.models import User, Task, Schedule
from datetime import datetime
@bp.route('/')
@bp.route('/index')
@login_required
def index():
schedules = Schedule.get_schedule(current_user, start_dat... |
#coding=utf-8
print '# map'
def _pow(num):
return num * num;
print 'map[1-10],获取每个元素自身平方运算的结果', map(_pow, range(1, 11))
print 'map[1-10],将每个元素转换为字符串', map(str, range(1, 11))
def _capitalize(s):
return s.capitalize()
ls0 = ['anit', 'tac', 'cisum']
print 'map%s,将每个元素首字母转换为大写 %s' % (ls0, map(_capitalize, ls0))
... |
"""
Operations Mixins.
"""
from eventstore_grpc import operations
from eventstore_grpc.proto import operations_pb2, operations_pb2_grpc, shared_pb2
class Operations:
"""Handles Operations."""
def merge_indexes(self, **kwargs) -> shared_pb2.Empty:
"""Merges indexes."""
stub = operations_pb2_g... |
class Flight:
def __init__(self, origin_short_name, destination_short_name, departure_time, fare_with_taxes, currency, status):
"""
Initialize Flight
:param origin_short_name: string - departure city
:param destination_short_name: string - destination city
:param departure_ti... |
from django.db import models
class Cowsay(models.Model):
cowsay_string = models.TextField()
def __str__(self):
return self.cowsay_string
|
import cv2
import numpy as np
# Dynamic constants
CAM_PATH = 6 # "http://192.168.43.156:4747/video"
TESTER = "sanket"
WHICH_SYSTEM = "sanket"
# Independent constants
BAUD_RATE = 115200 # sampeling speed
CAR_BELOW_Y = 25 # y coordinate of car below max y coordinate
LIMIT_CONE = 100 # threshold after which detecti... |
class DieException(BaseException):
pass
# def __init__(self, *args, **kwargs):
# super().__init__(args, kwargs)
# self.message = args[0] |
class CodonUsage():
def __init__(self):
self.counts = None
self.codon_usage = None
|
from wegene.Controllers.WeGeneUser import *
from wegene.Controllers.Allele import *
from wegene.Controllers.Health import *
from wegene.Controllers.Athletigen import *
from wegene.Controllers.Skin import *
from wegene.Controllers.Psychology import *
from wegene.Controllers.Risk import *
from wegene.Controllers.Haplogro... |
import pytest
def test_import_order():
# monkeypatching tf.keras caused import issue
WandbCallback = pytest.importorskip(
"wandb.keras.WandbCallback", reason="imports tensorflow"
)
tf = pytest.importorskip(
"tensorflow", minversion="2.6.2", reason="only relevant for tf>=2.6"
)
... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright Irshad Ahmad Bhat 2016.
# Copyright Arjuna Rao Chavala 2018
# IT3 mapping Checked for Telugu and works for other languages
from __future__ import unicode_literals
import io
import os
import re
from six import unichr
class IT3():
"""it3-converter for UTF... |
"""Django rest framework serializers for the brewery app.
"""
from rest_framework import serializers
from brewery import models
class JouliaControllerReleaseSerializers(serializers.ModelSerializer):
"""Standard serializer for JouliaControllerRelease model."""
class Meta:
model = models.JouliaControll... |
""" Simple FTP client module. """
import subprocess
from collections import namedtuple
from datetime import datetime
from enum import IntEnum
from ftplib import all_errors
from pathlib import Path
from shutil import rmtree
from urllib.parse import urlparse, unquote
from gi.repository import GLib
from app.commons impo... |
"""Tests for bllb logging module."""
# pylint: disable=unused-wildcard-import, undefined-variable
import re
from hypothesis import given
from hypothesis.strategies import text
from hypothesis_auto import auto_pytest, auto_pytest_magic
import pytest
from bripy.bllb.str import *
DEFAULT_RUNS = 50
FUNCTIONS = {
h... |
# coding: utf-8# File content is auto-generated. Do not modify.
# pylint: skip-file
from ._internal import SymbolBase
from ..base import _Null
def Activation(data=None, act_type=_Null, name=None, attr=None, out=None, **kwargs):
r"""Applies an activation function element-wise to the input.
The following activa... |
/home/runner/.cache/pip/pool/5f/95/f1/cc1311c7e8ad01e274ec0d2b6d14d64b05dced62d76fa640d7ee406860 |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Neural Network assisted Euler Integrator #
# Contact yhuang@caltech.edu for details. 06/08/2021 #
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
... |
__author__ = 'joefrancia'
|
import sys
from pyspark import SparkContext
import time
import json
import collections
import copy
import math
import time
from functools import reduce
from itertools import combinations
from operator import add
tickTime = time.time()
sc = SparkContext()
# #FilePaths
# input_file, output_file = sys.argv[1:]
#LocalR... |
#!/usr/bin/env python
"""Command-line utility for db setup."""
import os
import logging
import sys
from time import time, sleep
from psycopg2 import connect, sql, OperationalError
db_type = os.getenv("DJANGO_DB_TYPE", "postgres")
db_user = os.getenv("DJANGO_DB_USER","tau_db")
db_name = os.getenv("DJANGO_DB","tau_db")
d... |
from unittest import TestCase
from unittest.mock import patch
from opwen_email_server.api import client_read
from tests.opwen_email_server.api.api_test_base import AuthTestMixin
class DownloadTests(TestCase, AuthTestMixin):
def test_denies_unknown_client(self):
with self.given_clients(client_read, {'clie... |
import datetime
import os.path
import pkg_resources
import re
import flask
import jinja2.loaders
import six
import edera.helpers
URL_PATTERN = "https?://[^\\s]*"
class MonitoringUI(flask.Flask):
"""
A monitoring UI (web-application).
This class aims to render monitoring snapshots and task payloads ob... |
# -*- coding: utf-8 -*-
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Luc LEGER / Coopérative ARTEFACTS <artefacts.lle@gmail.com>
"""
Mission tests
"""
import factory
import pytest
import sys
from django... |
import os
import platform
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
import secret
def add_chrome_webdriver():
print(platform.system())
working_path = os.getcwd()
library = 'library'
... |
#!/usr/bin/env python
#--------------------------------------------------------
# Name: bearings.py
# Purpose: Calculate the great circle distance and bearing
# between 2 points
#
# Author: Al Neal
#
# Created: 2015
# Copyright: (c) Al Neal
# Licence: MIT
#-------------------------------------... |
class Money:
dollars: int
cents: int
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
@staticmethod
def factory_func_money_from_cents(total_cents): # hacky way to support Polymorphic constructor
# wrapper function to return a Money class object... |
import re
thisDict = {
"2": "2",
"3": "3",
"5": "5",
"7": "7",
"2 x 2": "{2} x {2}",
"3 x 2": "{3} x {2}",
"4": "{2 x 2}",
"6": "{3 x 2}",
"8": "{2 x 2} x {2}",
"16": "{2 x 2} x {2 x 2}",
"96": "{16} x {6}",
"Model.Root": "{96} bottles of {Favored Beverage} on the {House... |
import torch
import torch.nn as nn
from torch_sparse import SparseTensor
from torch_geometric.nn import global_mean_pool
from torch_geometric.nn.inits import reset
import torch.nn.functional as F
def to_normalized_sparsetensor(edge_index, N, mode='DA'):
row, col = edge_index
adj = SparseTensor(row=row, col=co... |
from pyapp.checks.registry import register
from .factory import session_factory
register(session_factory)
|
# Copyright (c) 2021 Stephan Gerhold
# 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 conditions and ... |
#!/usr/bin/env python
#
# Copyright (c) 2011 Kyle Gorman
# Modified 2018 Erika Burdon
#
# 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 r... |
import sys
import os
from unittest import mock
import pytest
from click.testing import CliRunner
test_path = os.path.dirname(os.path.abspath(__file__))
modules_path = os.path.dirname(test_path)
sys.path.insert(0, modules_path)
sys.modules['sonic_platform'] = mock.MagicMock()
import psuutil.main as psuutil
class Te... |
import torch
import numpy as np
import albumentations as albu
import albumentations.pytorch as albu_pytorch
from torch.utils.data import Dataset
from .registry import DATASETS
from .base import BaseDataset
@DATASETS.register_module
class DummyDataset(BaseDataset):
""" DummyDataset
"""
def __init__(self, ... |
from django.contrib import admin
from petstagram2.pets.models import Pet
@admin.register(Pet)
class PetAdmin(admin.ModelAdmin):
list_display = ['name', 'type', 'age']
# admin.site.register(Pet, PetAdmin)
|
class FParser:
"""
The file-parser class is made in such way that can support all bookshelf format benchmarks.
FParser class can be used either in combination with the other classes in order to have a complete
object-oriented version of a benchmark, or can be used separately as a class or not (you'l... |
# coding: utf-8
#
# Refs: https://github.com/openatx/uiautomator2/blob/d08e2e8468/uiautomator2/adbutils.py
from __future__ import print_function
import datetime
import os
import re
import socket
import stat
import struct
import subprocess
import time
from collections import namedtuple
from contextlib import contextma... |
'''
Set of tools for processing the
data of mechanical testings.
'''
__name__ = 'mechanical_testing'
__version__ = '0.0.0'
from .TensileTest import TensileTest |
from .bot import Bot
from .errors import *
from .converter import *
from .context import Context
from .core import *
from .cog import Cog
from .help import HelpCommand, DefaultHelpCommand
|
"""Parallel beam search module for online simulation."""
import logging
from pathlib import Path
from typing import List
import yaml
import torch
from espnet_pytorch_library.batch_beam_search import BatchBeamSearch
from espnet_pytorch_library.beam_search import Hypothesis
from espnet_pytorch_library.e2e_asr_common ... |
import plyfile
import numpy as np
from skimage.measure import marching_cubes_lewiner
from mayavi import mlab
def extract_mesh_marching_cubes(volume, color=None, level=0.5,
step_size=1.0, gradient_direction="ascent"):
if level > volume.max() or level < volume.min():
return
... |
"""
conftest.py
"""
def pytest_addoption(parser):
parser.addoption(
"--no-catalog", action="store_true", default=False, help="skip tests that need catalogs"
)
_SKIP_IF_NO_CATALOG = {
'test_protoDC2.py',
'test_catalogs.py',
}
def pytest_ignore_collect(path, config):
if config.getoption('--... |
class OnlyOne(object):
"""
Signleton class , only one obejct of this type can be created
any class derived from it will be Singleton
"""
__instance = None
def __new__(typ, *args, **kwargs):
if OnlyOne.__instance == None:
obj = object.__new__(typ, *args, **kwargs)
... |
import os
############
#Definitions
############
Import('mode')
use_gcc = GetOption('use_gcc')
std_cc_flags = ['-std=gnu11',
'-Wall',
'-Wextra',
'-pedantic',
'-fPIC',
'-pthread']
std_cxx_flags = ['-std=c++11',
'-Wall',
'-Wextra',
... |
# coding=utf-8
import socket
import ipaddress
import re
import geoip2.database
# 通过VT查询pdns,然后排除国内外常见的cdn段,如果出现极有可能是真实ip
cdns = ['173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '19... |
import torch
from torch.autograd import Variable
import torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.optim as optim
import math
import numpy as np
import os
import torch.nn.functional as F
import torch.nn.init as init
import matplotlib.pyplot as plt
... |
from scipy.stats import zscore
class Statseg:
def __init__(self, coordinates, stat_mat, res, eval_func):
# initialization
self.coordinates = coordinates
self.stat_mat = stat_mat
self.norm_stat_mat = zscore(stat_mat, axis=0)
self.res = res
# make var_mat
self... |
# -*- test-case-name: xquotient.test.test_filter -*-
"""
Defines simple, customizable rule-based Message filtering.
"""
import re
from zope.interface import implements
from twisted.python import reflect, components
from nevow import inevow, athena
from axiom import item, attributes
from axiom.iaxiom import IRelia... |
# PYTHON - MIT - UNICAMP
# =============================================================================
# Created By : Matheus Percário Bruder
# Created Date : February 3rd, 2021
# =============================================================================
dividend = 7
divisor = 2
quocient = 0
if dividend > 0 an... |
# Conway's game of life (no frills version)
import random
ROWS = 50
COLS = 70
CELL_SIZE = 10
HEIGHT = (ROWS * CELL_SIZE)
WIDTH = (COLS * CELL_SIZE)
BACK_COLOR = (0, 0, 127)
CELL_COLOR = (0, 200, 0)
def Rule(rule): return [(b != '_') for b in rule]
WAKEUP = Rule('___X_____')
KEEPUP = Rule('__XX_____')
def grid_build... |
#!/usr/bin/python
#
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
emojis = {
"happy": [
"😀",
"😁",
"😂",
"🤣",
"😃",
"😄",
"😅",
"😆",
"😉",
"😊",
"😋",
"😎",
"🙂",
"🙃",
"🤓",
"😝",
"😜",
]
}
print(type(emojis))
print("")
question = input... |
import os
import sys
import json
import subprocess
import numpy as np
import torch
from torch import nn
from opts import parse_opts
from model import generate_model
from mean import get_mean
from classify import classify_video
import glob
from tqdm import tqdm
import pdb
import pickle as pkl
def convert_to_np(resul... |
class Solution:
def findMinMoves(self, machines: List[int]) -> int:
dresses = sum(machines)
if dresses % len(machines) != 0:
return -1
ans = 0
average = dresses // len(machines)
inout = 0
for dress in machines:
inout += dress - average
ans = max(ans, abs(inout), dress - av... |
# Update zones table, zone_data - [zone, latitude, longitude, id]
UPDATE_ZONES_TABLE = '''
UPDATE zones
SET zone = ? ,
latitude = ? ,
longitude = ?
WHERE id = ?
'''
# Update locations table, location_data [last_used, usage_cnt, id]
UPDATE_LOCATION_USED = '''
UPDATE ... |
"""
Even though orthogonal polynomials created using three terms recurrence is
the recommended approach as it is the most numerical stable method, it can not
be used directly on stochastically dependent random variables. On method that
bypasses this problem is Cholesky decomposition method.
Cholesky exploits the fact ... |
from random import randint
# Linked List Implementation in python
# Node definition
class LinkedListNode:
def __init__(self, data):
self.data= data
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
... |
from __future__ import print_function
import numpy as np
import time
# noinspection PyUnresolvedReferences
from std_msgs.msg import Float64MultiArray
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
# noinspection PyUnresolvedReferences
from mpl_toolkits.mplot3d import Axes3D # for: fig.gca(pr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
"""
from __future__ import uni... |
"""Top-level package for navigate."""
from navigate.model import QNetwork
__author__ = """Juan Carlos Calvo Jackson"""
__email__ = "juancarlos.calvojackson@gmail.com"
__version__ = "0.1.0"
|
from datetime import date
from dateutil.relativedelta import relativedelta, SU
def get_mothers_day_date(year):
"""Given the passed in year int, return the date Mother's Day
is celebrated assuming it's the 2nd Sunday of May."""
return date(year, 1, 1) + relativedelta(months=+4, weekday=SU(2))
# Pybite... |
import param
from nick_derobertis_site.common.page_model import PageModel
class LoadingPageModel(PageModel):
pass |
class BinaryTree:
def __init__(self, size):
self.customList = size * [None]
self.lastUsedIndex = 0
self.maxSize = size
def insertNode(self, value):
if self.lastUsedIndex + 1 == self.maxSize:
return "The Binary tree is full"
self.customList[self.lastUsedIndex ... |
#!/usr/bin/env python
import hashlib
import sys
if len(sys.argv) < 2:
print('<passwd>')
sys.exit(1)
h = hashlib.sha1()
h.update(sys.argv[1])
print(h.hexdigest())
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: quantizer
# Author: Alexandros-Apostolos A. Boulogeorgos
# Generated: Fri Mar 6 07:02:02 2020
##################################################
if __name__ == '__main__':
impor... |
#!/usr/bin/pxi2thon
# -*- coding: utf-8 -*-
from sympy import *
from sympy.abc import *
# compute stencil for FE rhs (int phi_i phi_j)
#
xi,xi1,xi2,xi3 = symbols('xi xi1 xi2 xi3')
### 1D element contributions for linear Lagrange ansatz function (phi)
def phi0(xi):
return (1-xi)
def phi1(xi):
return xi
pri... |
from collections import Counter
from importlib.resources import open_text
from typing import Dict, Iterable, NamedTuple, Tuple
from more_itertools import windowed
class Pair(NamedTuple):
left: str
right: str
class Rule(NamedTuple):
left: str
right: str
inner: str
@classmethod
def parse... |
try:
string = '1'
number = 1
print(string + number)
except TypeError:
print('error')
list1 = [1,2,3,4]
try:
for i in range(10):
print(list1[i])
except IndexError:
print('Vyvyshli za gran spiska!') |
from Line import *
from Date import Date
class Flux(Line):
def __init__(self, name="",iD ="",value =0.0 ,shortInfo="" ,
longInfo="" ,supplier="" , iN=0.0 , out=0.0 ,date="none"):
super(Flux,self).__init__(name,iD,date)
self.value=value
self.shortInfo=shortInfo
self.longInfo=longInfo
... |
import numpy as np
import argparse
import os.path
import tools # in https://github.com/abigailStev/whizzy_scripts
__author__ = "Abigail Stevens <A.L.Stevens at uva.nl>"
__version__ = "0.2 2015-06-16"
"""
Converts an RXTE energy channel list to a list of real energy *boundaries* per
detector mode energy channel.
Us... |
import re
import sys
from napalm import get_network_driver
from getpass import getpass
def pretty_print(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty_print(value, indent+1)
elif isinstance(value, list):
... |
from . import gatingmechanism
from .gatingmechanism import *
__all__ = list(gatingmechanism.__all__)
|
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.models import User
from core.schemes.user import UserInDb
from api.deps import get_current_user, get_db
router = APIRouter()
@router.get('/me', response_model=UserInDb)
def get_me(user: User = Depends(get_curre... |
import json
from datetime import datetime
from flask import url_for
from werkzeug.security import generate_password_hash, check_password_hash
from apidoc.extensions import db
class Role(db.Model):
""" 角色表 """
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.St... |
'''Breadth-First Search module. '''
from collections import deque
GRAPH = {}
GRAPH["you"] = ["alice", "bob", "claire"]
GRAPH["bob"] = ["anuj", "peggy"]
GRAPH["alice"] = ["peggy"]
GRAPH["claire"] = ["thom", "jonny"]
GRAPH["anuj"] = []
GRAPH["peggy"] = []
GRAPH["thom"] = []
GRAPH["jonny"] = []
def _sells_mango(person... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.