content stringlengths 5 1.05M |
|---|
import sys
import os
import numpy as np
import pandas as pd
from algorithms import EMUr, MMD, RA, KPITU, CHIM, CD
def file_name(file_dir):
file_list = []
for root, dirs, files in os.walk(file_dir):
files.sort()
for file in files:
file_list.append([os.path.join(root, file), os.path.s... |
# ~ <script type="text/python">
from browser import document, alert # Brython in-browser support
# ~ from store import Store
from operator import *
about_str = """GuessPresso:
Using Brython to play the Expression Game.
Currently on Brython-3.8.0.
José L Balcázar (balqui at GitHub), spring and summer 2021."""
def ... |
#!/usr/bin/python
#
# Author: Jashua R. Cloutier (contact via sourceforge username:senexcanis)
#
# Copyright (C) 2010, Jashua R. Cloutier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Re... |
import os, sys, h5py
import numpy as np
from pyglib.model import semicir as bethlatt
import subprocess
from builtins import zip
import matplotlib
matplotlib.rcParams['backend'] = "Qt5Agg"
import matplotlib.pyplot as plt
def generate_data(u_list, mu_list):
'''run *CyGutz* calculations for a list of U and mu.
... |
import inspect
import itertools
import logging
import math
import queue
import random
import signal
import sys
import threading
from datetime import datetime
if sys.implementation.name == 'cpython':
_LOWEST_VERSION = (3, 6)
else:
_LOWEST_VERSION = (3, 7)
if sys.version_info >= _LOWEST_VERSION:
_dict = dic... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : naive dormin
# @time : 2021/04/19 02:18:51
# @version : 1.0.0
import os
from KB import KB
from BFS import BFS
import sys
def main():
if len(sys.argv) != 5:
print("Please use the following format: ./run dataFromKB entity1 entity2 number_... |
import tensorflow as tf
import tflib.read
import scipy.misc
import numpy as np
from scipy.misc import imsave
from srres import generator
import sys
import os
NAME = sys.argv[1]
OUTPUT_PATH = 'test_output/'+NAME
N_GPUS = 1
DEVICES = ['/gpu:{}'.format(i) for i in range(N_GPUS)]
OUTPUT_DIM = 112*96*3
H=int(112/4)
W=int(9... |
from unittest import TestCase
from gcd import gcd
class GcdTest(TestCase):
def test_gcd(self):
assert gcd(16, 4) == 4
assert gcd(17, 5) == 1
assert gcd(30, 20) == 10
assert gcd(10, 0) == 10
|
class Solution:
def XXX(self, a: str, b: str) -> str:
# 以二进制数相加
num = int(a,2) + int(b,2)
return str(bin(num))[2:]
|
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
#(@:Description): "email Management, and automation api code"
#(@:Author): "inteliJence development team"
#under the license of Apache License 2.0 and intelijence ProtectiveRights please edit and use it with all the care you can give
#(@:App-Type): "Api (Restfull & RestLess)"
#(@:Language): "Python"
#(@:... |
import os
import torch
import pickle
import numpy as np
from torch.utils.data import Dataset
class MultipleSampleMeshDataset(Dataset):
def __init__(self, subj_ids, rsfc_dir, contrast_dir, num_samples=8):
self.rsfc_dir = rsfc_dir
self.contrast_dir = contrast_dir
self.subj_ids = subj_ids
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 14:35:01 2018
@author: ldh
"""
# prepare_daily.py
import time
import os
import datetime as dt
import yaml
import numpy as np
import pandas as pd
from sqlalchemy.types import VARCHAR,DECIMAL,DATETIME
from podaci.guosen.data import get_stock_basic,get_stock_daily_data
... |
# Advent of Code
# Karl Mathias Moberg
# Day 1
import itertools
def compareNumbers(num1, num2, num3 = 0):
numSum = num1 + num2 + num3
if numSum == 2020:
if num3 == 0:
matchSum = num1 * num2
print("MATCH: {} + {} = 2020. Multiplier: {}".format(num1, num2, matchSum))
... |
###
#
# Electripy, HAL library for Python
#
# Library was originally created for WeIO, www.we-io.net and than forked as a
# separate project in order to promote concept of using interpreted languages
# in microcontrolers.
#
# This library is common effort of their original creators
# Uros PETREVSKI, Drasko DRASKOVIC ... |
from microbit import *
while True:
for j in range(-1,2,2):
for i in range(5):
display.set_pixel(2 + j * (i - 2),i,9)
sleep(250)
display.set_pixel(2 + j * (i - 2),i,0)
for i in range(3):
display.set_pixel(2 + 2*j,3-i,9)
sleep(250)
... |
import subprocess
import time
import httpx
import humanize
import re
import os
import shutil
import json
import hashlib
import winreg
import io
from pathlib import Path
from urllib.parse import urljoin, urlparse
from datetime import datetime, timedelta
from defusedxml import ElementTree
from dateutil.parser import... |
from coyote_framework.mixins.filesystem import create_directory
__author__ = 'justin'
import sys
import logging
import datetime
import os
from coyote_framework.util.apps.templating.template import build_string_from_method_args
loggers = []
FORMAT = '%(levelname)s: %(asctime)s: %(message)s'
DATE_FORMAT = '%m/%d/%Y ... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
""""
Preprocessing pipeline for all datasets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
def image_preprocessing(file,
label,
file_type = 'filename',
... |
from .base_node import BaseNode
class TriumphSubaccountUsNode(BaseNode):
"""Represents a TRIUMPH-SUBACCOUNT-US node."""
@classmethod
def payload_for_create(cls, nickname, **kwargs):
"""Build the API 'create node' payload specific to TRIUMPH-SUBACCOUNT-US.
"""
payload = super().pay... |
from distutils.core import setup, Extension
setup(name='ctest',
version='1.0.0',
description='This is a test package',
ext_modules=[Extension('hello', ['hello_world/hello.c']),
Extension('loop', ['loop/loop.c']),
Extension('csum', ['csum/csum.c'])])
|
# -*- coding: utf-8 -*-
import scrapy, json, re, threading
from scrapy.spiders import CrawlSpider
from datetime import datetime, timedelta
from ..items import UserInfoItem, FollowItem, FanItem, \
PostInfoItem, TextItem, ImageItem, CommentItem, ForwardItem, ThumbupItem
class WeiboSpider(CrawlSpider):
name = ... |
# Generated by Django 3.2.5 on 2021-07-12 16:37
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('providers', '0002_alter_provider_phone_number'),
]
o... |
"""
Adapted from
https://github.com/Jackson-Kang/Pytorch-VAE-tutorial/blob/master/01_Variational_AutoEncoder.ipynb
A simple implementation of Gaussian MLP Encoder and Decoder trained on MNIST
"""
import argparse
import logging
import os
import sys
import time
from pathlib import Path
import cv2
import joblib
import nu... |
from ows_refactored.ows_reslim_cfg import reslim_wms_min_zoom_15_cache_rules
from ows_refactored.wofs.bands_wo_cfg import bands_wofs_obs
style_s2_water_classifier = {
"name": "water_classifier",
"title": " Water Summary",
"abstract": "WOfS NRT",
"needed_bands": ["water"],
"value_map": {
"wa... |
import os
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pypro4sail import pypro4sail as fs
from pypro4sail import machine_learning_regression as inv
from pypro4sail import four_sail as sail
from pypro4sail import prospect as pro
import ipywidgets as w
from IPython.dis... |
"""
File: function_pitch_range.py
Purpose: Takes a univarate function as a means to map to pitch range.
"""
import math
from function.chromatic_range_interpreter import ChromaticRangeInterpreter
from tonalmodel.chromatic_scale import ChromaticScale
class FunctionPitchRange(object):
"""
FunctionPitchRange ... |
import unittest
import pandas as pd
import analysis_tools as analysis
import matplotlib.pyplot as plt
class TestStringMethods(unittest.TestCase):
def setUp(self):
xs = [10, 30, 110, -20, 50, 50, 30, 80, 99, 10]
ys = [20, 60, 110, -40, 100, 100, 60, 160, 200, 20]
ts = [0, 1000, 2000, 3000,... |
import numpy as np
input_file = 'wine.txt'
X = []
y = []
with open(input_file, 'r') as f:
for line in f.readlines():
data = [float(x) for x in line.split(',')]
X.append(data[1:])
y.append(data[0])
X = np.array(X)
y = np.array(y)
from sklearn import model_selection
X_train, X_test, y_tr... |
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from backend_wagtail_api.users.forms import UserChangeForm, UserCreationForm
from wagtail.contrib.modeladmin.options import (
ModelAdmin,
modeladmin_register
)
User = get_user_model... |
"""
Created on Aug 2, 2015
From: https://github.com/izderadicka/xmpp-tester/blob/master/commander.py
@author: ivan
"""
from collections import deque
import inspect
import re
import threading
import traceback
import urwid
from importlib import import_module
import attr
import elkm1_lib.message
@attr.s
class Command:
... |
import pytest
import cslib
# TODO: add negative cases..
@pytest.mark.parametrize("command,expected", [
("gcc", True),
("gcc-10.1", True),
("llvm-g++", True),
("g++", True),
("c++", True),
("cc", False),
("cc1", False)
])
def test_is_interest_call(command, expected):
assert cslib.csutil... |
"""
Test utilities
"""
class SkipMessages(object):
"""
A class that maintains the skipped messages
"""
def __init__(self):
self.messages = []
def add(self, msg):
self.messages.append( msg )
def __len__(self):
return len(self.messages)
def __iter__(self):
r... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from djanban.apps.base.auth import user_is_member
from djanban.apps.b... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def vae_loss(x_decoded_mean, x, z_mean, z_logvar):
xent_loss = F.binary_cross_entropy(x_decoded_mean, x, reduction='sum')
kl_loss = -0.5 * torch.sum(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
return xent_loss + kl_loss
class Molecula... |
import math
import discord
from discord.ext import commands, menus
from helpers.pagination import AsyncListPageSource
class Reputation(commands.Cog):
"""Reputation Tools"""
def __init__(self, bot):
self.bot = bot
@commands.guild_only()
@commands.command()
async def vouch(self, ctx, ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 KuraLabs S.R.L
#
# 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 applicabl... |
# *****************************************************************
# Copyright 2013 MIT Lincoln Laboratory
# Project: SPAR
# Authors: OMD
# Description: An exmaple muddler.
#
# Modifications:
# Date Name Modification
# ---- ---- ------------... |
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib... |
from pathlib import Path
import os
import logging
import sys
import importlib
import inspect
import argparse
from collections.abc import Mapping
import warnings
try:
import importlib.resources as importlib_resources
except ImportError: # pragma: no cover
# backported
import importlib_resources
from ploomb... |
import pygame as pg
import time as now
from model import Screen, Frame
import os
import ctypes
from function import setting
from operator import attrgetter
class Game:
'''
It defines the game characteristics'''
def __init__(self,name,fps,aps,colors,
position=(0,0),
scaleRang... |
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.curdir)
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
scripts=[path.join(here,f'src/parse_flp') ]
packages=find_packages('src')
print(f'Packages is "{packages}"')
setup(
... |
import os
import pytest
import datetime
import numpy as np
# import xarray as xr
# from pathlib import Path
from netCDF4 import Dataset
from postladim import ParticleFile
# Should not have to repeat this from test_particlefile.py
@pytest.fixture(scope="module")
def particle_file():
# set up
# Return a small... |
import os, sys, nrrd, json
from tiffile import TiffFile, imsave
import numpy as np
from cmtk import tempfolder, active, run_stage, host, templatedir, cur, comp_orien, ori, orien
def createTiff(RedCh=None, GreenCh=None, BlueCh=None, Output='merged.tif'):
if not RedCh == None:
print 'Loading red channel: ' + str(... |
import tests
class TestS3(tests.AgileTest):
async def test_skip_upload(self):
app = await self.executor(tasks=["upload"])
self.assertFalse(app.cfg.push)
await app.run()
|
#Imoprt the kronecker model
from context import k_model
from k_model import KroneckerModel
from k_model_fitting import KModelFitter
#Import the function bases that will be used to create the functions
from context import function_bases
from function_bases import FourierBasis, HermiteBasis
#Common imports
import numpy... |
from django.db import models
class EntryManager(models.Manager):
''' Entrada é todo orçamento com num_prop = 0 '''
def get_queryset(self):
return super(EntryManager, self).get_queryset().filter(num_prop=0)
class ProposalManager(models.Manager):
''' Orçamento é todo orçamento com num_prop > 0 ''... |
from tkinter import *
window = Tk()
window.title("Simple Calculator")
window.geometry("400x300+20+10")
class MyWindow:
def __init__(self,window):
self.lbl1 = Label(window,text= "Simple Calculator")
self.lbl1.grid(row=0, columnspan=6, pady = 10)
self.lbl2 = Label(window, text = ... |
# Generated by Django 3.2.12 on 2022-03-20 14:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import house_of_refuge.main.models
import markdownx.models
class Migration(migrations.Migration):
dependencies = [
migr... |
from PIL.PngImagePlugin import *
|
from datetime import timedelta
from collections import defaultdict
from collections import Iterator
from marthe import *
import tensorflow as tf
import far_ho.examples.datasets as dts
import intervaltree as it
import pandas as pd
from marthe import AllPlaceholders
TIMIT_DIR = '/home/common/DATASETS/timit4python'
... |
#!/usr/bin/env python3
import os
import sys
import argparse
import copy
import traceback
# Add the pulsar path
thispath = os.path.dirname(os.path.realpath(__file__))
psrpath = os.path.join(os.path.dirname(thispath), "modules")
sys.path.insert(0, psrpath)
import pulsar as psr
def Run():
try:
tester ... |
import cv2
def preprocess_image(img,swap_channels=False):
"""
:param img: numpy array of shape (H,W,3)
:param swap_channels: True, if channelorder is BGR
:return:
"""
if swap_channels:
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# this seems to be possible as flownet2 outputs only ... |
import os
import numpy as np
import pandas as pd
from pathlib import Path
import shutil
from sklearn.model_selection import StratifiedGroupKFold
input_dir = Path('../input')
img_dir = input_dir / 'photos'
img_dir_dino = input_dir / 'photos_ssl' / 'train_test'
#---------------------------------------#
# make inpu... |
from pygitinterface.git_interface import GitInterface
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Frederik Elwert <frederik.elwert@web.de>
#
# 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... |
#!/usr/bin/env python
# coding: utf-8
# ./sblu.py
# Description:
# Uses sblu (see: https://bitbucket.org/bu-structure/sb-lab-utils/src/master/)
# todo: make a submit function
from __future__ import division
from subprocess import Popen, PIPE
def rmsd(lig, crys_lig, ft, rot, output, options=None):
"""Usage: sbl... |
#!/usr/bin/python
# Copyright 2018 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 agre... |
import unittest
from cloudsplaining.scan.policy_detail import PolicyDetails
# class TestPolicyDetails(unittest.TestCase):
# def test_remove_wildcard_only_actions(self):
# print()
|
"""Base filters."""
import django_filters
from django.db.models import Case, IntegerField, Value, When
from rest_framework.filters import SearchFilter
class CommonFieldsFilterset(django_filters.FilterSet):
"""This is intended to be the base filter for most app filtersets."""
search = SearchFilter()
def ... |
"""Test utility functions."""
import numpy as np
from compoda.utils import truncate_range, scale_range
def test_truncate_range():
"""Test range truncation."""
# Given
data = np.random.random(100)
data.ravel()[np.random.choice(data.size, 10, replace=False)] = 0
data.ravel()[np.random.choice(data.s... |
# measure version 1.8.7
from measure import npfarray,sqrt,ln,exp,arctan,lst,tbl,sig,val,mv,dsto_mv,dsys_mv,dtot_mv,plt,pltext,expreg,pi,curve_fit
# Aufgabe 1
R_A1 = npfarray([1,10,1])*1e3
R_A1_dsys = 0.05 * R_A1
C_A1 = npfarray([470,4.7,47])*1e-9
C_A1_dsys = 0.10 * C_A1
g_thalb = npfarray([312,32.6,32.6])*1e-6
g_thalb... |
import contextlib
import os
import shutil
import pytest
from tests.utils import DATA, TESTS, CURR
from dfs_sdk import scaffold
@pytest.yield_fixture
def search_path():
old = scaffold.CONFIG_SEARCH_PATH
scaffold.CONFIG_SEARCH_PATH = [os.getcwd(), TESTS, DATA]
yield
scaffold.CONFIG_SEARCH_PATH = old
... |
from statistics import median
def FindSplittingNode(tau,mu1,mu2):
n=tau.rootNode
while not isinstance(n,Value) and ((mu1 is not None and mu1>=n.value) or (mu2 is not None and mu2<=n.value)):
if mu2<=n.value:
if n.leftChild is not None: n=n.leftChild
else: return None
els... |
'A class and variable for Tile objects'
#IMPORTS
from pygame import Vector2, Rect
#IMPORTS
#VARIABLES
tile_size = 0
#VARIABLES
#TILE
class Tile:
'''A tile used by the Entity object to check collision
size can be a single number and it will be the width and the height, or it can be a tuple/list
It also... |
from argparse import ArgumentParser
import os
report_name = "report.html"
survivor_graph = "log.png"
net_extension = ".svg"
def write_header(output_file):
html_code = f"""
<html>
<head>
<style>
table, th, td {{
border: 1px solid black;
border-collapse: collapse;
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from conf.settings import ConfigMap
# 创建数据库db
db = SQLAlchemy()
def create_app(config):
'''
工厂模式创建app
@config: 'develop': 开发环境, 'product': 生产环境, 'test': 测试环境
'''
app = Flask(__name__, static_folder='blog/static', template_folder='... |
"""data_process
Useful classes, method, definitions for image captioning data preprocessing.
Download and Unzip data
All this code is based on the paper:
Xu, Kelvin, et al. "Show, attend and tell: Neural image caption generation
with visual attention." International conference on machine learning. 2015.
And Github ... |
"""State.py
Definition for namedtuple representation of a State
"""
from __future__ import print_function, division, unicode_literals
from collections import namedtuple
# noinspection PyClassHasNoInit
class State(namedtuple('State', ['E', 'J', 'T'])):
"""Stores the four data corresponding to a specific state
... |
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
from random import randint
class Trainer:
"""
This class implements methods for training, evaluating and
saving a ML model.
"""
def __init__(self, model, optimizer, scheduler, scheduler_active, cr... |
# To run:
# export FLASK_APP=flask_video.py
# flask run
from camera import Camera
from flask import Flask, send_file
app = Flask(__name__)
cam = None
# State checks to prevent multiple initialization
def check_cam():
global cam
if cam == None:
print('starting camera')
cam = Camera()
... |
import numpy as np
from torch.utils.data import Dataset
import torch
# from rlkit.envs.half_cheetah import HalfCheetahEnv
from gym.envs.mujoco import HalfCheetahEnv as HalfCheetahEnv_
import gym
import d4rl
class ScatterDataset(Dataset):
def __init__(self, path):
self.datas = np.load(path)
self.X, ... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\server_commands\crafting_commands.py
# Compiled at: 2020-05-07 00:26:00
# Size of source mod 2**32: ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import uuid
def get_uuid() -> str:
"""
生成uuid
:return: str(uuid)
"""
return str(uuid.uuid4())
|
# Copyright 2022 iiPython
# Modules
import os
from importlib.util import (
spec_from_file_location, module_from_spec
)
# Initialization
rootf = os.path.abspath(os.path.dirname(__file__))
operator_files = [x[:-3] for x in os.listdir(rootf) if x[0] != "_" and x.endswith(".py")]
# Load operators
opmap = {}
for opf ... |
from argparse import ArgumentParser
from re import findall
def old_is_valid_password(lower: int, upper: int, char: str, pw: str) -> bool:
return int(lower) <= sum(1 for c in pw if c == char) <= int(upper)
def new_is_valid_password(lower: int, upper: int, char: str, pw: str) -> bool:
return sum(1 for idx in (... |
#!/usr/bin/env python
import sys
import os.path as osp
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = osp.dirname(__file__)
dqn_path = osp.join(this_dir, '..', 'bin', 'lib')
add_path(dqn_path)
pylib_path = osp.join(this_dir, '..', 'pylib')
add_path(pylib_path)
|
import logging
from aiohttp_jinja2 import template
from app.service.auth_svc import for_all_public_methods, check_authorization
from app.utility.base_world import BaseWorld
@for_all_public_methods(check_authorization)
class EmuGUI(BaseWorld):
def __init__(self, services, name, description):
self.auth_s... |
from fabric.api import *
from fabric.api import run
#comment
env.user = 'raony'
env.hosts = ['mendel']
def install():
# local('pip install cython')
# local('pip install pynnotator')
local('pip install -r requirements.txt')
# local('pynnotator install')
# local('python manage.py migrate auth')#bug ... |
from marshmallow import fields, validate, Schema, pre_dump, post_dump
from marshmallow_enum import EnumField
from api.models.couriers import *
class CourierGetResponse(Schema):
courier_id = fields.Integer(required=True)
# courier_type = EnumField(CourierType, by_value=True)
courier_type = fields.String(... |
"""This subpackage contains the definition of classes specialized in reading
FrameNet databases from .xml files in various schemas. The utility function
:func:`load` is provided as an interface to automatically detect the correct
loader and use it.
.. note::
All loader classes must inherit from :class:`FNLoader`.
..... |
import unittest
from pgxnclient import tar
from pgxnclient import zip
from pgxnclient import archive
from pgxnclient.errors import PgxnClientException
from .testutils import get_test_filename
class TestArchive(unittest.TestCase):
def test_from_file_zip(self):
fn = get_test_filename('foobar-0.42.1.zip')
... |
import numpy as np
import mavsim_python_parameters_aerosonde_parameters as P
class Thrust:
def __init__(self, state):
self.state = state
# self.atmosphere = ISA()?
self.delta_t = 0
self.force_moment = np.zeros(6)
def update(self, delta_t):
self.delta_t = delta_t
... |
"""
Copyright 2019 Dominik Werner
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... |
from split_helper import write_file, split_into_chunks, retrieve_all_chunks, join_chunks, read_chunk
import os
def split(filename,pwd,n):
chunks = split_into_chunks(filename,4)
# print("The chunks are : ", chunks)
write_file(filename,pwd,n,chunks)
os.remove(filename)
def recreate_file(filename,pwd):
... |
__all__ = ['ttypes', 'constants', 'ThriftSecureEventTransmissionService']
|
# Weighted SUM
def w_sum(a, b):
assert(len(a) == len(b))
output = 0
for i in range(len(a)):
output += (a[i] * b[i])
return output
def nn(input, weights):
return w_sum(input, weights)
weights = [0.10, 0.20, 0.00]
data = [8.50, 0.65, 1.20]
print(nn(data, weights)) |
# -*- coding: utf-8 -*-
import os
import datetime
import requests_cache
import unittest
from novaplaylist.core.tools import parse_duration, os_query, remove_and_create_directory, create_directory, clean_filename
from novaplaylist.core.Song import Song
from novaplaylist.scrapers import Scraper, FipScraper, NovaScraper,... |
import random
import copy
from count_sort import sys_sort
from calculate_time import cal_time
from quick_sort import quick_sort
@cal_time
def redix_sort(li):
max_num = max(li)
t = 0
while 10 ** t <= max_num:
buckets = [[] for _ in range(10)]
for val in li:
idx = (val//10**t) % 1... |
import datetime
import uuid
from sqlalchemy import Column, Integer, String, DateTime, DECIMAL, ForeignKey
from src.dal.base import Base
class OrderModel(Base):
"""订单信息"""
__tablename__ = "order"
order_id = Column(String, primary_key=True)
mobile = Column(String, ForeignKey("profile.mobile"))
add... |
from enum import Enum
class RolandAddressMap(Enum):
# 010000xx
serverSetupFileName = b"\x01\x00\x00\x00"
# 010001xx
songToneLanguage = b"\x01\x00\x01\x00"
keyTransposeRO = b"\x01\x00\x01\x01"
songTransposeRO = b"\x01\x00\x01\x02"
sequencerStatus = b"\x01\x00\x01\x03"
sequencerMeasure =... |
import numpy as np
try:
import scipy
import scipy.interpolate
import scipy.sparse as sp
import scipy.sparse.linalg
except ImportError:
pass
verbose = False
def Log(msg):
if verbose:
print(str(msg))
def report(re, n="residual"):
re = re.flatten()
nr = np.linalg.norm
l = ... |
import argparse
import subprocess
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from time import time
from hosts_common import discovery, get_hosts
parser = argparse.ArgumentParser(description="Threadpool example")
parser.add_argument("-poolsize", default=10, help="Size of the thread... |
from returns.io import IO, impure
def _fake_impure_function(some_param: int) -> int:
return some_param
def test_impure():
"""Ensures that impure returns IO container."""
impure_result = impure(_fake_impure_function)(1)
assert isinstance(impure_result, IO)
assert impure_result == IO(1)
|
# -*- coding: utf-8 -*-
"""
flaskbb.forum.forms
~~~~~~~~~~~~~~~~~~~~
It provides the forms that are needed for the forum views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from flask.ext.wtf import Form
from wtforms import (TextAreaField, StringField,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def num_questions_worst_case2(n):
if n==0:
return 0
else:
return 1 + num_questions_worst_case_support2((n-1)//2) + num_questions_worst_case_support2((n-1)//2 + ((n-1)%2) )
def num_questions_worst_case_support2(n):
if n==0:
... |
import re
import urllib
from headers import*
from vulnz import*
print (ga.green+''')
__ __ _ _____ ____
\ \ / / | | | __ \ |___ \
\ \ /\ / /__| |__ | |__) |_ ___ __ __) |_ __
\ \/ \/ / _ \ '_ \| ___/\ \ /\ / / '_... |
from typing import (
Any,
Callable,
Dict,
Iterable,
Sequence,
Tuple,
)
from eth_utils import (
to_dict,
)
from eth_utils.toolz import (
curry,
first,
)
from eth2.beacon import helpers
from eth2._utils.numeric import (
is_power_of_two,
)
from eth2._utils.tuple import (
updat... |
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener
from selenium.webd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.