content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from flask import Flask, blueprints, jsonify, request, Blueprint, g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from werkzeug.utils import secure_filename
import os
import uuid
from resource.model import dicModel
from ..model.textLibModel import TextLibrary
fro... |
from sqlalchemy import BigInteger, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class User(Base):
__tablename__ = 'es_users'
id = Column(BigInteger, primary_key=True)
email = Column(String(150), nullable=False)
first_name ... |
from flask import Flask
from flask import render_template
from flask import request
from flask.helpers import url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import redirect
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICAT... |
import numpy as np
def mean_filter(mat, mask=None, h=1):
x = np.array(mat)
n = x.shape[0]
if mask is None:
mask = np.invert(np.isnan(mat))
# make sure to exclude main diagonal and lower traingle
mask = np.triu(mask, k=1)
# !!! treat zeros as missing
x[x == 0] = np.nan
x... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... |
gdf.plot(column="no2", figsize=(20, 10)) |
from binaryninja import *
def show_comments(bv):
comments = []
for func in bv.functions:
if func.comments:
for offset, value in func.comments.iteritems():
comments.append((offset, value))
comments = [str(hex(offset)).strip("L") + ": " + value for offset, value in sorted(... |
from Data.TradeItem import*
class TradeStartPacket:
def __init__(self):
self.type = "TRADESTART"
self.clientItems = []
self.partnerName = ""
self.partnerItems = []
def read(self, reader):
clientItems_len = reader.readShort()
for i in range(clientItems... |
# 5. Palindrome Integers
# A palindrome is a number which reads the same backward as forward, such as 323 or 1001.
# Write a function which receives a list of positive integers and checks if each integer is a palindrome or not.
# Print the results on the console
# The input will be a single string containing the number... |
import os
username='input your username'
password='input your password'
notification_email='input your notification email'
endpoint='https://control.akamai.com/webservices/services/PublishECCU'
wsdl_url='file://%s' % os.path.join(os.path.dirname(__file__), 'PublishECCU.wsdl')
print wsdl_url
try:
from sett... |
from rest_framework import routers
from django.urls import path
from . import views
from .apps import app_name # NOQA: F401
router = routers.SimpleRouter()
router.register(r"users", views.UserViewSet)
# TODO EmailChange, EmailVerification
urlpatterns = [
path("login/", views.LoginView.as_view(), name="login"),... |
# Copyright 2008-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
# http://aws.amazon.com/apache2.0/
# or in the "license" file accompanyin... |
# -*- coding: utf-8 -*-
import os
import shutil
import glob
import unittest
import zipfile
from simple_idml.extras import create_idml_package_from_dir
CURRENT_DIR = os.path.dirname(__file__)
IDMLFILES_DIR = os.path.join(CURRENT_DIR, "IDML")
OUTPUT_DIR = os.path.join(CURRENT_DIR, "outputs")
class ExtrasTestCase(unitt... |
#
# pact.py
#
# Author(s):
# Georg Rutishauser <georgr@iis.ee.ethz.ch>
#
# Copyright (c) 2020-2021 ETH Zurich.
#
# 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/l... |
###########
# IMPORTS #
###########
# Standard Library Imports
import os
import logging
# Third Party Library Imports
import discord
from discord.ext import commands
from dotenv import load_dotenv
# Local Library Imports
########
# MAIN #
########
def logger():
"""
Logs errors and debug information from d... |
from kervi.core.utility.schedule import Job
class ActionJob(Job):
"""
A periodic job as used by :class:`Scheduler`.
:param interval: A quantity of a certain time unit
:param scheduler: The :class:`Scheduler <Scheduler>` instance that
this job will register itself with once it has
... |
import abc
import json
import click
import six
import terminaltables
from click import style
from halo import halo
from gradient import api_sdk, exceptions, TensorboardClient
from gradient.api_sdk import constants, sdk_exceptions
from gradient.api_sdk.config import config
from gradient.api_sdk.utils import concatenat... |
import sys
import random
sys.path.append('../')
from protocols.ether import EtherRaw
from protocols.s01fd import *
from protocols.cotp import *
from protocols.s7 import *
szl_0000 = "\x32\x07\x00\x00\x06\x00\x00\x0c\x01\x82\x00\x01\x12\x08\x12\x84" \
"\x01\x01\x00\x00\x00\x00\xff\x09\x01\x7e\x00\x00\x00\x00\x00\x02" \... |
from bs4 import BeautifulSoup
from pathlib import Path
import os
# NOTE: tab0.html can be safely ignored
def extract_primer_page(html_string, dig_parent_dir, current_page_name, readfile):
# primer*.html, including subpages like 14a, 13b, 23a, etc.
soup = BeautifulSoup(html_string, 'html5lib')
pag... |
class Wizard:
def __init__(self, name):
self.hp = 100
self.name = name
def wand(self):
return True
class HarryPotter(Wizard):
def faculty(self):
print('Gryffindor')
def skills(self):
print('Умеет летать на метле')
def spells(self):... |
import requests as http
from lib.connect import SpotifyConnect
from lib.network import get_next_song
from multiprocessing import Process, Queue
from subprocess import Popen
from lib.play import play_loop
import time
import os
import sys
os.environ['TOKEN'] = ''
Popen(['python', 'server.py'])
url = 'http://127.0.0.1:50... |
from CoolProp.CoolProp import PropsSI
import numpy as np
from . import ureg, FluidState
class AbstractFluid:
def __init__(self, fluid_name):
self.fluid_name = fluid_name
T_crit = PropsSI('T_critical', fluid_name) * ureg.K
p_crit = PropsSI('p_critical', fluid_name) * ureg.Pa
proper... |
from flask import render_template
from app import app
from app.models import Guest
@app.route('/guests', methods=['GET'])
def view_guests():
return render_template('view_guests.html', guest_list=Guest.query.all())
|
import os
from collections import deque
from queue import Empty
import threading
import queue
from threading import Thread
from eggroll.core.constants import StoreTypes
from eggroll.core.meta_model import ErStore
from eggroll.utils.log_utils import get_logger
L = get_logger()
# from Python 3.7.5
class _PySimpleQu... |
#!/usr/bin/env python3
from ev3dev.ev3 import *
from time import *
dis = UltrasonicSensor('in1')
touch = TouchSensor('in2')
angle = GyroSensor('in3')
cs = ColorSensor('in4');
cs.mode = 'COL-COLOR';
#for motor
m1 = Motor('outA')
m2 = Motor('outB')
m3 = Motor('outC')
#for gyro
sp = 900
angle.mode='GYRO-ANG' # Put the gy... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class FulfillmentResult(object):
def __init__(self):
self._fulfillment_order_no = None
self._out_order_no = None
@property
def fulfillment_order_no(self):
return self._... |
n = int(input("Enter N: "))
arr = [int(x) for x in input("Enter ARR seprated by space: ").split()][:n]
res = 0
for i in range(n):
add = 0
for j in range(i, n):
add += arr[j]
if add == 0:
res += 1
print(res)
|
#
# PySNMP MIB module TOKENRING-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/TOKENRING-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:31:49 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ... |
begin_unit
comment|'# Copyright 2013 Nicira, Inc.'
nl|'\n'
comment|'# All Rights Reserved'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# ... |
"""
Utilities for querying Google's APIs.
The following documentation may be useful::
http://code.google.com/apis/ajaxsearch/documentation/#fonje
"""
try:
import simplejson as json
json # For Pyflakes.
except ImportError:
import json
from twisted.internet import defer
from nevow.url import URL
from... |
from collections import defaultdict as dd
G = dd(lambda :dd(lambda :0))
vis = dd(lambda :False)
def load_data():
N,M,C1,C2 = [int(x) for x in input().split()]
weight = [int(x) for x in input().split()]
for i in range(M):
c1, c2, L = [int(x) for x in input().split()]
G[c1][c2] = G[c2][c1] =... |
# using Eve library to create rest api
# this file runs the eve application and declares additional endpoints
# for FB authentication
from flask import make_response, request, jsonify, json
from eve import Eve
from priceprobi.utils import get_env
from priceprobi.config import get_config
from auth import get_pp_user, P... |
from pyonize import pyonize, Pyon
def test_pyonize():
pyon = pyonize({"id":1,"name":"bilal","job":{"id":1,"title":"CTO"}})
print(str(type(pyon)))
assert pyon.name == "bilal"
assert str(pyon.job) == str({"id":1,"title":"CTO"})
assert pyon.job.title == "CTO"
def test_pyon_class():
pyon = Pyo... |
import json
class DataObject(object):
data = ''
def __init__(self, dataFunc = None):
if dataFunc is not None:
self.data = dataFunc()
|
"""
Level order traversal is also called breadth first traversal
"""
from collections import deque
from binary_tree_node import Node # type: ignore
def level_order_using_extra_space(root: Node):
"""
Using a queue
time complexity: O(n)
space complexity: O(n)
"""
queue: deque = deque()
wh... |
from django_jenkins.management.commands import jenkins
try:
import cProfile as profile
except ImportError:
import profile
import pstats
class Command(jenkins.Command):
def handle(self, *test_labels, **options):
profile.runctx('super(Command, self).handle(*test_labels, **options)',
... |
# simple_wire.py
# Play microphone input to speaker using callback function
#
# Adapted from Wire(Callback) example
# https://people.csail.mit.edu/hubert/pyaudio/
import pyaudio
import time
CHANNELS = 1
RATE = 16000
# Define callback function
def my_callback_fun(input_string, block_size, time_info, status):
retu... |
# Copyright (c) 2021, Srijena_Nithish and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class BakeryCusInvoice(Document):
def validate(self):
if self.qty >0:
if frappe.db.exists("Bakery Cus Payment",{'customer': self.customer}):
exist... |
import tempfile
import json
import sys
import os
DEBUG = os.getenv("DEBUG", False)
DRYRUN = os.getenv("DRYRUN", False)
def run(dir, command):
if DEBUG:
print(command)
return os.system("cd "+dir+"; "+command)
def exists_resource(resource, resources):
for item in resources:
# "mode":"data",
# "type":... |
# Copyright 2015 Open Source Robotics Foundation, 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... |
import settings
import numpy as np
import mxnet as mx
import logging
from fileiter import FileIter
import cv2
import os
import sys
sys.path.append("..")
from symbols.symbol_common import *
def convolution_module(net, kernel_size=(3,3), pad_size=(1,1), stride=(1, 1), filter_count = 32, work_space=2048, batch_norm=True... |
from django import template
from utilities.util import parse_float
register = template.Library()
@register.filter
def round(value) -> float:
"""
>>> round(123412)
123.412
>>> round("123579")
123.579
>>> round(1234567)
1.234567
"""
try:
value_int = pa... |
# This script uses an external Python package called Requests to make its HTTP requests.
# Install this package on your system using pip with the command:
# pip install requests
import requests
from config import username, password, api_key, base_url
# This is an example User object to create a new administrator ac... |
import numpy as np
import pandas as pd
import scipy as sp
import math
import os
import sys
import time
def mainfn(bin_size, Pmin, Pmax, tmin):
start = time.time()
tmax= Pmax - tmin;
Pin_point= int((Pmax-Pmin)/bin_size +1);
obs_point=int((tmax-tmin)/bin_size + 1);
Zmax=tmax;
Zmin=tmin-Pmax;
... |
#MenuTitle: Assign fallback codepoints
# -*- coding: utf-8 -*-
__doc__="""
Assigns private-use codepoints to glyphs which are not mapped
to any Unicode codepoints.
This script will ignore glyphs:
- glyphs which are not exported
- glyphs which name starts with "."
- glyphs which name ends with ".case"
- empty glyphs
""... |
#desafio 63: Sequência de Fibonacci v1.0
print('>>>>>>>>>>> Sequência de Fibonacci v1.0 <<<<<<<<<<<<<<')
n = int(input('Quantos termos quer mostrar: '))
n1 = 0
n2 = 1
count = 3
print('~'*50)
print(f' {n1} → {n2}', end=' → ')
while count <= n:
n3 = n1 + n2
print(f'{n3}', end=' → ')
n1 = n2
n2 = n3
... |
from typing import Any, Dict
import streamlit as st
def input_metrics(readme: Dict[Any, Any], config: Dict[Any, Any]) -> Dict[Any, Any]:
"""Lets the user select evaluation metrics to be used for model evaluation.
Parameters
----------
readme : Dict
Dictionary containing tooltips to guide use... |
import os
import pybedtools
import numpy as np
"""
Tools for working with data across sessions.
"""
def load_features_and_arrays(prefix, mmap_mode='r'):
"""
Returns the features and NumPy arrays that were saved with
save_features_and_arrays.
Parameters
----------
prefix : str
Path t... |
#!/usr/bin/python3
import os
import sys
import time
import json
import subprocess
from pprint import pformat
from cluster_config_parse_utils import get_current_node_info
sys.path.insert(0, '../')
from bkdrft_common import *
"""
setup_node.py can fully setup the environment of a node.
The measured values should be g... |
# Create a program that takes in 3 integers that are 5 digits long. Find the product of multiplying the last digits of the 3 integers.
# input
num1 = int(input('Enter a number: '))
num2 = int(input('Enter a number: '))
num3 = int(input('Enter a number: '))
# processing
last_digit1 = num1 % 10 # if you ever need the l... |
TABLE, COLUMNS = "table", "columns"
DATE_FORMAT = "%Y-%m-%d"
TOKEN = 'ca7a0727b75dce94ad988adf953673340308f01bacf1a101d23f15fc'
STOCK_DAY = {TABLE: "stock_day", COLUMNS: (
"code", "date", "open", "high", "low", "close", "vol", "amt", "adj_factor")}
INDEX_DAY = {TABLE: "index_day",
COLUMNS: ("code", "date"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# 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/L... |
from import_addressbase.importing import import_csv, make_es_actions, make_es_mappings
|
import copy
from math import cos, pi, sin
from typing import Tuple, Union
import numpy as np
import torch
from PIL import Image
from src.data_loader.joints import Joints
from src.types import CAMERA_PARAM, JOINTS_3D, JOINTS_25D, SCALE
from src.constants import MANO_MAT
from torch.utils.data import ConcatDataset, DataL... |
# coding: utf-8
# In[1]:
get_ipython().magic('load_ext autoreload')
# In[2]:
get_ipython().magic('aimport Planner')
# In[3]:
get_ipython().magic('autoreload')
# In[4]:
import pyddl
# In[5]:
from Planner import Predicate, DualPredicate, Action, Problem
# In[6]:
from tracery import Grammar, modifiers
... |
class Node:
def __init__(self):
self.val = ""
self.children = []
class Problem:
"""
Print N-ary Tree
@FakeMesa ~/P/A/mola (master)> tree
.
├── README.md
├── charts
│ └── mola
│ ├── Chart.yaml
│ ├── README.md
│ ├── templates
│ │... |
import imp
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("home", views.homepage, name="home"),
path("", views.login, name="login"),
path("logout", views.logout, name="logout"),
path("register", views.r... |
import numpy as np
import numpy.random
import sys
import ScalarSchedule
class RBMTrainParams:
def __init__(self):
self.k = 1 # for Contrastive Divergence
self.mu = ScalarSchedule.LinearSchedule(0.5, 0.99, 100) # momentum update parameter
self.eta = Sca... |
import os.path
PSKS_client = {b'server1' : b'abcdef',
b'server2' : b'uvwxyz'}
PSKS_server = {b'client1' : b'abcdef',
b'client2' : b'123456'}
#b'value' : b'231.27#232.63#14.98#205.04#212.04'
PSKS_test = {
b'kudalumping' : b'uvwxyz',
b'kudalumping2' : b'abcdef',
b'value' : b'231.27#... |
import time
import threading
import dataclasses
from tests.case import Case
import rich
import rich.progress
class TestThread(threading.Thread):
def __init__(self, *args, **kwargs):
self.exc = None
threading.Thread.__init__(self, *args, **kwargs)
def run(self):
try:
i... |
from fastapi import FastAPI
from . import models
from .database import engine
from .routers import blog, user, authentication
app = FastAPI()
app.include_router(blog.router)
app.include_router(user.router)
app.include_router(authentication.router)
# models.Base.metadata.create_all(bind=engine)
|
# -*- coding: utf-8 -*-
import sys
from prompt_toolkit.completion import Completer, Completion
class PyTestCompleter(Completer):
def __init__(self, app_name, app_conf, client):
self.app_name = app_name
self.client = client
self.test_items = {}
self.update_test_items()
def ge... |
__author__ = 'paoolo'
import random
from nsh_app.function.trainer import neighborhood, outstar, instar
from nsh_app.tools.function import normalize
def train_competitive(network, signals, targets, iterations, kohonen_learning_rate, grossberg_learning_rate):
trainer_kohonen = instar(kohonen_learning_rate)
tr... |
from typing import List
import numpy as np
import time
class EpochSummary(object):
def __init__(self, is_train, epoch):
self.losses = []
self.current_loss = -1
self.loss_index = -1
self.is_train = is_train
self.wrong = None
self.wrong_batch = []
self.accur... |
#!/usr/bin/env python3
'''
Very simple NTLM hash monitor & brute forcer
Monitors Responder database (Responder.db) and runs
user supplied command to brute force it.
Configuration is stored in config.py
'''
import os.path
import sys
import time
import subprocess
import argparse
import io
import shlex
from enum import... |
import matplotlib.pyplot as plt
import MDSplus as mds
import numpy as np
from scipy import signal
#import peakutils
from lmfit.models import GaussianModel, ConstantModel
class Thomson:
def __init__(self, shot):
self.shot = shot
def get_raw_data(shot):
tree = '... |
# Generated by Django 3.0.7 on 2020-06-11 23:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('log', '0004_auto_20200612_0436'),
]
operations = [
migrations.RenameField(
model_name='logger',
old_name='is_encrypted',
... |
with open("D:/Development/External/RCSNN/rcsnn/generated/bd_mon.py") as f:
exec(f.read())
|
import json
import logging
import configparser
def read_config_file(json_file_path):
"""
Reads a json_file and returns it as a python dict
:param string json_file_path: path to a json file with configuration information
:returns: dict
"""
json_file=check_file(json_file_path)
with... |
"""
utils.py
Author: William Guss
Basic building blocks for tensorflow.
"""
import tensorflow as tf
import numpy as np
def uniform_random_tensor(shape, name="weights"):
"""
Makes a tensor of shape SHAPE with uniform random intiialization.
"""
with tf.variable_scope(name):
tensor = tf.Variable(tf.random_unif... |
import pandas as pd
import matplotlib.pyplot as plt
def show_count(df: pd.DataFrame, title: str):
fig, axes = plt.subplots(nrows=1, ncols=2)
title = f'{title}\nКоличество треков: {len(df)}'
df.emotion.value_counts().plot.barh(
ax=axes[0],
figsize=(10, 10),
title='Распределение по... |
# Generated by Django 3.1.2 on 2021-02-09 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("archive", "0009_auto_20210204_1946"),
]
operations = [
migrations.AlterField(
model_name="archivedocument",
name="ye... |
#! /usr/bin/env python
import sys
import SimpleITK as sitk
import getopt
# vertices of a tetrahedron
tverts = [ [0.732843, 0.45, 0.35],
[0.308579, 0.694949, 0.35],
[0.308579, 0.205051, 0.35],
[0.45, 0.45, 0.75]]
def make_tetra(dim=128, pixel_type=sitk.sitkUInt8):
sigma=[dim/6,di... |
import os, os.path
from bs4 import BeautifulSoup
import urllib2
from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED
from whoosh.analysis import StemmingAnalyzer
from whoosh import index
schema = Schema(title = TEXT(stored=True, phrase=True, field_boost=100.0, analyzer=StemmingAnalyzer()),
headi... |
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure
output_file("stacked_split.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
exports = {'fruit... |
#!/usr/bin/python
#
# ============================================================================
# Copyright (c) 2011 Marvell International, Ltd. All Rights Reserved
#
# Marvell Confidential
# ============================================================================
#
# Draw lines to se... |
from sandstone.datasets.loader.factory import RegisterInputLoader
from sandstone.datasets.loader.abstract_loader import abstract_loader
import cv2
import numpy as np
import pydicom
import os
LOADING_ERROR = 'LOADING ERROR! {}'
IRS_IMAGE_SIZE = (384, 288)
@RegisterInputLoader('default_image_loader')
class OpenCVLoader(... |
"""Функции для получения информации о свечках."""
from typing import Optional
import aiohttp
from aiomoex import client, request_helpers
from aiomoex.request_helpers import (
CANDLE_BORDERS,
CANDLES,
DEFAULT_BOARD,
DEFAULT_ENGINE,
DEFAULT_MARKET,
)
async def get_market_candle_borders(
sessio... |
# 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... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.request import Request
from rest_framework.test import APIClient, APIRequestFactory
from assessment import models, serializers
QUESTION_URL = reverse('a... |
# -*- coding: utf-8 -*-
""" This module provides template tags for handeling plugins
"""
from django.conf import settings as djangosettings
from django import template
from django.urls import reverse
from common.models import InvenTreeSetting
from plugin import plugin_reg
register = template.Library()
@register.s... |
__docformat__ = "reStructuredText"
import weakref
from weakref import WeakSet
import platform
import copy
from . import _chipmunk_cffi
cp = _chipmunk_cffi.lib
ffi = _chipmunk_cffi.ffi
from .vec2d import Vec2d
from .body import Body
from .collision_handler import CollisionHandler
from .query_info import Point... |
# Script to generate comparison plots between two models.
# Example command:
# SAC: python model/plot_result_comparisons.py
import argparse
import matplotlib
matplotlib.use("TkAgg")
import csv
import os
import pdb
import matplotlib.pyplot as plt
import numpy as np
def plot_mean_std(ax, x, y_mean, y_std, color="da... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ImggramConfig(AppConfig):
name = 'imggram'
|
import sys
from PIL import Image, ImageDraw, ImageFont
img_name = "" # Image name
scale = 1 # Image scale
sample = 64 # Skip pixels
font_size = 40 # Font size
shift = 2 # Move characters to right
colored = False # Colored or Mono
extended_range = False # Extended ASCII characters
reverce_basic_colors = False # Set b... |
"""
Some convenience macros for gdb. If you have pypy in your path, you can simply do:
(gdb) python import pypy.tool.gdb_pypy
Or, alternatively:
(gdb) python execfile('/path/to/gdb_pypy.py')
"""
from __future__ import with_statement
import re
import sys
import os.path
try:
# when running inside gdb
from ... |
# -*- coding: utf-8 -*-
import scrapy
from douban.items import DoubanItem
class DoubanSpiderSpider(scrapy.Spider):
name = 'douban_spider'
allowed_domains = ['movie.douban.com']
start_urls = ['http://movie.douban.com/top250']
base_domain = "https://movie.douban.com/top250"
def parse(self, response... |
""" Models module
"""
import datetime
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from site_app.models import ModelTimestampMixin
class Location(ModelTimestampMixin, models.Model):
"""Location"""
class Meta:
... |
from service.models import Service
def services(request):
return {
'categories': Service.objects.all()
}
|
# Standard libraries
import unittest
# Third party libraries
import xmlrunner
if __name__ == '__main__':
# Only run tests in packages contain an __init__.py file
unittest.main(module=None,
testRunner=xmlrunner.XMLTestRunner(output="test_results"),
failfast=False,
... |
# python3
"""Example: Max Cut Algorithm for bi-directional graph."""
import random
import timeit
from typing import List
from absl import app
from absl import flags
import numpy as np
from src.lib import helper
from src.lib import ops
flags.DEFINE_integer('nodes', 12, 'Number of graph nodes')
flags.DEFINE_boolean(... |
# This file is auto-generated from a Python script that parses a PhysiCell configuration (.xml) file.
#
# Edit at your own risk.
#
import os
from ipywidgets import Label,Text,Checkbox,Button,HBox,VBox,FloatText,IntText,BoundedIntText,BoundedFloatText,Layout,Box
class UserTab(object):
def __init__(self):
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T N A N O
#
# Copyright (c) 2020+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# ---... |
# Generated by Django 3.0.2 on 2020-03-07 21:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('browse', '0002_auto_20200201_0137'),
]
operations = [
migrations.CreateModel(
name='ExperimentC... |
import logging
import sys
from src.alerter.alerts.alert import Alert
from src.channels_manager.channels.channel import Channel
from src.utils.data import RequestStatus
class ConsoleChannel(Channel):
def __init__(self, channel_name: str, channel_id: str,
logger: logging.Logger) -> None:
... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import stochannpy
DISTNAME = "stochannpy"
DESCRIPTION = "StochANNPy"
LONG_DESCRIPTION = """StochANNPy (STOCHAstic Artificial Neural Network for PYthon) provides user-friendly routines compatible with Scikit-Learn for stochastic learning."""
AUTHOR =... |
import threading
from queue import Queue
from random import random
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
from tkinter.ttk import Progressbar
from shutil import copyfile
import os
import xlsxwriter
import json
from datetime import datetime
import requests
import time
fr... |
from django.urls import path
from . import views
urlpatterns = [
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register_view, name="register"),
path('', views.index, name='index'),
path('stories', views.FinishedStoryListView... |
# ========================= eCAL LICENSE =================================
#
# Copyright (C) 2016 - 2019 Continental Corporation
#
# 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... |
"""Tests for alpacka.trainers.td."""
import collections
import os
import numpy as np
from alpacka import data
from alpacka import testing
from alpacka.networks import core
from alpacka.trainers import td
# TODO(xxx): Refactor, add integration with Keras.
def test_target_n_return():
"""A rudimentary test of tar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.