content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""bis URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | python |
Desc = cellDescClass("CLKBUFX16")
Desc.properties["cell_leakage_power"] = "5029.443900"
Desc.properties["cell_footprint"] = "clkbuf"
Desc.properties["area"] = "63.201600"
Desc.pinOrder = ['A', 'Y']
Desc.add_arc("A","Y","combi")
Desc.set_job("buf") # A
Desc.add_param("area",63.201600);
Desc.add_pin("A","input")
Desc.add... | python |
{
"targets": [{
"target_name": "jimp-native",
"cflags": ["-fexceptions"],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc": [ "-std=c++17", "-fexceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
'defines': ['_HAS_EXCEPTIONS=1'],
"sources": [
"<!@(node... | python |
#!/usr/bin/python3
import matplotlib.pyplot as plt
import logging
import math
from tgblib import util
from tgblib.data import get_data, get_data_ul
logging.getLogger().setLevel(logging.INFO)
if __name__ == '__main__':
util.set_my_fonts(mode='talk')
show = False
label = 'std'
NU_TITLE = {
... | python |
def mandel(x, y, max_iters, value):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
... | python |
# -*- coding: utf-8 -*-
import os
def get_list(path):
j=0
f = open('cemianTrain.txt','w')
for i in os.listdir(path):
print(i)
f.write(os.path.join('/',i))
j+=1
if j%2 == 0:
f.write('\n')
else:
f.write(' ')
... | python |
from core import RunBossSpider
from data.tool.handler import HandlerData
from flask import Flask
def run_proxy():
pass
def run_web():
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
app.run()
def main():
# 开启爬虫
boss_spi = RunBossSpider()
boss_spi.r... | python |
import csv
from django.db.models import Q
from django.http import HttpResponse
from django.template import Context, loader
from django.template.loader import get_template
from pymedtermino.umls import *
from weasyprint import HTML
from modules.cnmb.models import Physic
from modules.cnmb.utils.dto import CnmbDto
from ... | python |
from setuptools import setup, find_packages
version = '1.0.0'
setup(
name="alerta-query",
version=version,
description='Alerta Generic Webhook by query parameters',
url='https://github.com/alerta/alerta-contrib',
license='MIT',
author='Pablo Villaverde',
author_email='pvillaverdecastro@gma... | python |
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
from base_bank import BankBase
import unicodedata
class Bank(BankBase):
def __init__(self):
BankBase.__init__(self)
self._bank_session = requests.Session()
self._base_url = 'https://online.bbt.com'
... | python |
from btchippython.btchip.bitcoinTransaction import bitcoinTransaction
from btchippython.btchip.btchip import btchip
from electrum_clone.electrumravencoin.electrum.transaction import Transaction
from electrum_clone.electrumravencoin.electrum.util import bfh
from electrum_clone.electrumravencoin.electrum.ravencoin import... | python |
#!/usr/bin/env python3
# python 3.5 without f strings
import argparse
import os, shutil, sys
import uuid
import itertools
from glob import glob
from snakemake.shell import shell
from snakemake.io import glob_wildcards
from multiprocessing import Pool
def predict_genes(genome,fasta,out_dir,log):
fna = "{}/{}.fn... | python |
"""The genome to be evolved."""
import random
import logging
import hashlib
import copy
from train import train_and_score
from train import trainsimulation
class Genome():
"""
Represents one genome and all relevant utility functions (add, mutate, etc.).
"""
def __init__( self, all_possible_genes = N... | python |
#!/usr/bin/python
import pickle
import numpy
numpy.random.seed(42)
### The words (features) and authors (labels), already largely processed.
### These files should have been created from the previous (Lesson 10)
### mini-project.
words_file = "../text_learning/your_word_data.pkl"
authors_file = "../text_learning/yo... | python |
#!/usr/bin/env python3
from PIL import Image
import requests
from io import BytesIO
import base64
import os
import sys
from Crypto.Cipher import AES
from colorama import *
import random
import json
import mysql.connector
from cmd import Cmd
import hashlib
import time
# these dicts are how we manage options settings f... | python |
"""
Assignment
1 create 5 variable for each data type
2 create 5 list variable with 3 elements like name,address,contact number
"""
# Int Data
a = 5
print(a)
b = 3
print(b)
c = 8
print(c)
d = 7
print(d)
e = 6
print(e)
# Float Data
a = 0.5
print(a)
b = 3.9
print(b)
c = 8.4
print(c)
d = 7.2
print(d)
e = 6.9
print(e)... | python |
dia=int(input("quantos dia alugados"))
km=float(input("quantos km rodado"))
pago=(dia*60)+(km*0.15)
print("o total a pagar e de R${:.2f}".format(pago)) | python |
""" Base class for records. """
from abc import ABCMeta, abstractmethod
from .utils import set_encoded
class InserterRegistry(object):
""" Registry of inserters. """
def __init__(self):
self._inserters = []
self._register_inserters()
def _register_inserters(self):
""" Register ... | python |
import torch
import numpy as np
from torch.nn import functional as F
def create_uv(width, height):
uv = np.flip(np.mgrid[height[0]:height[1], width[0]:width[1]].astype(np.int32), axis=0).copy()
return uv.reshape((2, -1)).T
def create_perpendicular_vectors_vectorized(normals): # Nx3 tensor
def handle_z... | python |
import numpy as np
import matplotlib.pyplot as plt
import IPython
from mm2d.model import ThreeInputModel
# model parameters
# link lengths
L1 = 1
L2 = 1
# input bounds
LB = -1
UB = 1
def pseudoinverse(J):
JJT = J.dot(J.T)
return J.T.dot(np.linalg.inv(JJT))
def weighted_ps(D, J):
A = np.diag(D)
r... | python |
import unittest
from bitmovin import Bitmovin
from tests.utils import get_settings
class BitmovinTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
def setUp(self):
super().setUp()... | python |
import numpy as np
from typing import Dict
from mlagents.torch_utils import torch
from mlagents.trainers.buffer import AgentBuffer
from mlagents.trainers.torch.components.reward_providers.base_reward_provider import (
BaseRewardProvider,
)
from mlagents.trainers.settings import RNDSettings
from mlagents_envs.base... | python |
from django.contrib import admin
from .models import Author, Category, Article, Comment
# Register your models here.
class AuthorModel(admin.ModelAdmin):
list_display = ["__str__"]
search_fields = ["__str__", "details"]
class Meta:
Model = Author
admin.site.register(Author, AuthorModel)
clas... | python |
# Copyright 2019 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
"""tipo_hilo_cuerda
Revision ID: 014
Revises: 013
Create Date: 2014-05-28 07:36:03.329028
"""
# revision identifiers, used by Alembic.
revision = '014'
down_revision = '013'
import inspect
import imp
import os
from alembic import op
def upgrade():
utils_path = os.path.join(os.path.dirname(os.path.abspath(inspe... | python |
'''
This file contains functions that help calculate the score and check word
validity in the game.
'''
####################################
# Global Variables
####################################
WORDLENGTH = 4
####################################
# Cows and Bulls Counter
####################################
def r... | python |
import sys
sys.path.append("/Users/zhouxuerong/projects/autotest/autotest/autotest")
from django.test import TestCase
from apitest.views import Login
from django.http import HttpRequest
class titlePageTest(TestCase):
def test_loginPage(self):
request = HttpRequest()
Response = Login(request)
... | python |
# -*- coding: utf-8 -*-
def main():
s = input()
if s == 'Sunny':
print('Cloudy')
elif s == 'Cloudy':
print('Rainy')
else:
print('Sunny')
if __name__ == '__main__':
main()
| python |
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
metadata = MetaData()
Base = declarative_base(metadata=metadata)
from . import Assignment, Driver, DriverAssignment, Location, LocationPair, MergeAddress, RevenueRate, Trip | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | python |
import utils
from symbolic.symbolic_types.symbolic_int import SymbolicInteger
from symbolic.symbolic_types.symbolic_type import SymbolicType
from z3 import *
class Z3Expression(object):
def __init__(self):
self.z3_vars = {}
def toZ3(self,solver,asserts,query):
self.z3_vars = {}
solver.assert_exprs([self.pred... | python |
import xgboost as xgb
# read in data
dtrain = xgb.DMatrix('../../data/data_20170722_01/train_data.txt')
dtest = xgb.DMatrix('../../data/data_20170722_01/test_data.txt')
# specify parameters via map, definition are same as c++ version
param = {'max_depth':22, 'eta':0.1, 'silent':0, 'objective':'binary:logistic','min_c... | python |
N = int(input())
N = str(N)
if len(N)==1:
print(1)
elif len(N)==2:
print(2)
elif len(N)==3:
print(3)
elif len(N)>3:
print("More than 3 digits") | python |
from passlib.context import CryptContext
PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return PWD_CONTEXT.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return PWD_CONTEXT.hash(... | python |
from .simple_ga import SimpleGA
from .simple_es import SimpleES
from .cma_es import CMA_ES
from .de import DE
from .pso import PSO
from .open_es import OpenES
from .pgpe import PGPE
from .pbt import PBT
from .persistent_es import PersistentES
from .xnes import xNES
from .ars import ARS
from .sep_cma_es import Sep_CMA_E... | python |
import random
from model import Actor, Critic
from ounoise import OUNoise
import torch
import torch.optim as optim
GAMMA = 0.99 # discount factor
TAU = 0.01 # for soft update of target parameters
LR_ACTOR = 0.001 # learning rate of the actor
LR_CRITIC = 0.001 # learning rate of the critic
class Agent():
def ... | python |
from __future__ import print_function
from sublime import Region, load_settings
from sublime_plugin import TextCommand
from collections import Iterable
DEBUG = False
def dbg(*msg):
if DEBUG:
print(' '.join(map(str, msg)))
class MyCommand(TextCommand):
def set_cursor_to(self, pos):
""" Set... | python |
import sys
sys.path.append('C:\Python27\Lib\site-packages')
import cv2
import numpy as np
import os
import pytesseract
from PIL import Image
from ConnectedAnalysis import ConnectedAnalysis
import post_process as pp
input_folder = r"C:\Users\SRIDHAR\Documents\python\final\seg_new";
output_folder= "temp";
d... | python |
from pymongo import MongoClient
import os
class Mongo:
def __init__(self):
self.__client = MongoClient(os.environ['MONGODB_CONNECTIONSTRING'])
self.__db = self.__client.WebScrapingStocks
def insert_quotes(self, quotes):
dict_quotes = []
for quote in quotes:
dict_q... | python |
class DubboError(RuntimeError):
def __init__(self, status, msg):
self.status = status
self.message = msg
| python |
test_issue_data = """
#### Advanced Settings Modified? (Yes or No)
## What is your overall Commons Configuration strategy?
{overall_strategy}
### [FORK MY PROPOSAL]() (link)
# Module 1: Token Freeze and Token Thaw
- **Token Freeze** is set to **{token_freeze_period} weeks**, meaning that 100% of TEC tokens minted ... | python |
import unittest
from rooms.room import Room
from rooms.position import Position
from rooms.vector import build_vector
from rooms.actor import Actor
from rooms.vision import Vision
from rooms.geography.basic_geography import BasicGeography
class SimpleVisionTest(unittest.TestCase):
def setUp(self):
self.... | python |
# coding: utf-8
import sys, os
sys.path.append(os.pardir)
import numpy as np
from common.layers import *
from common.gradient import numerical_gradient
from collections import OrderedDict
from dataset.mnist import load_mnist
class SGD:
def __init__(self, lr=0.01):
self.lr = lr
def update(self, param... | python |
# Generated by Django 3.0.7 on 2020-08-04 09:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contr_clienti', '0010_contractscan_actaditional'),
]
operations = [
migrations.AlterField(
mode... | python |
#!/usr/bin/python
import requests, json, fire, os
slack_webhook_url = os.environ['XKCD_SLACK_WEBHOOK_URL']
slack_headers={'Content-Type': 'application/json'}
def slack_post(content):
_slack_post = requests.post(slack_webhook_url, data=json.dumps(content), headers=slack_headers)
return(_slack_post.text)
def ... | python |
import pytest
import torch
from nnrl.nn.actor import (
Alpha,
DeterministicPolicy,
MLPContinuousPolicy,
MLPDeterministicPolicy,
)
from nnrl.nn.critic import ActionValueCritic, MLPVValue
from nnrl.nn.model import EnsembleSpec, build_ensemble, build_single
from ray.rllib import SampleBatch
from raylab.ut... | python |
_base_ = './fcn_r50-d8_512x512_20k_voc12aug.py'
model = dict(pretrained='open-mmlab://resnet101_v1c',
backbone=dict(depth=101),
decode_head=dict(num_classes=2),
auxiliary_head=dict(num_classes=2)
)
dataset_type = 'PLDUDataset' # Dataset type, this will be used to de... | python |
import sys
import os
import argparse
def make_streams_binary():
sys.stdin = sys.stdin.detach()
sys.stdout = sys.stdout.detach()
parser = argparse.ArgumentParser(description='generate random data.')
parser.add_argument('--octets', metavar='N', dest='octets',
type=int, nargs='?', default=2048... | python |
# pvtrace is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# pvtrace is distributed in the hope that it will be useful,
# but WITHOUT... | python |
import numpy as np
import math
import Graphics
from typing import List
import json
from scipy.optimize import fmin_powell
Vector = List[float]
import time
class Node (object):
"""A object that defines a position"""
def __init__(self, name: str, pos, constraint_x=0, constraint_y=0):
"""Node: has a name,... | python |
"""
This commander shell will be a implementation of the PX4 'commander' CLI (https://docs.px4.io/v1.9.0/en/flight_modes/).
Here you can switch modes on the go. Will require root access for safety reasons.
"""
from cmd import Cmd
import logger
import rospy
from mavros_msgs.srv import CommandBool
banner = """
... | python |
from data.scraper import DataScraper
from PIL import Image,ImageFont,ImageDraw
import time
class GenerateTiles:
def __init__(self,FONT,FONT_SIZE,FONT_COLOR,TILE_SIZE,TILE_BG_COLOR):
self.FONT = FONT
self.FONT_COLOR = FONT_COLOR
self.FONT_SIZE = FONT_SIZE
self.TILE_SIZE = TILE_SIZE
self.TILE_BG_COLOR = TILE_... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 14:56:30 2020
@author: sanja
"""
import numpy as np
from matplotlib import pyplot as plt
import cv2
import binascii
img = cv2.imread('4119.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY ) # Converting RGB to gray
#height, width = fi ... | python |
from ConexionSQL import ConexionSQL
def clean_api_count():
conSql = ConexionSQL()
conn = conSql.getConexion()
cur = conSql.getCursor()
query = """DELETE FROM tokens_count WHERE tiempo < (current_timestamp - interval \'15 minutes\');"""
cur.execute(query)
conn.commit()
query = 'VACUUM FUL... | python |
def get_knockout_options(model_class, form):
knockout_options = {
'knockout_exclude': [],
'knockout_fields': [],
'knockout_field_names': [],
'click_checked': True,
}
for item in (model_class, form):
if not item:
continue
has_fields_and_exclude =... | python |
# from coursesical.course import *
from course import *
def test0():
t = TimeTable([("08:00", "10:10")])
s = Semester("2021-03-01", t)
r = RawCourse(
name="通用魔法理论基础(2)",
group="(下课派:DD23333;疼逊会议)",
teacher="伊蕾娜",
zc="1-16(周)",
classroom="王立瑟雷斯特利亚",
weekday=0... | python |
from django.conf.urls import url
from bluebottle.funding_flutterwave.views import FlutterwavePaymentList, FlutterwaveWebhookView, \
FlutterwaveBankAccountAccountList, FlutterwaveBankAccountAccountDetail
urlpatterns = [
url(r'^/payments/$',
FlutterwavePaymentList.as_view(),
name='flutterwave-pa... | python |
"""
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related docu... | python |
from django.urls import path
from .views import encuesta
urlpatterns = [
path('', encuesta, name='encuesta'),
]
| python |
#
# PySNMP MIB module REDSTONE-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:46:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | python |
import asyncio
import aiohttp
import time
import sys
from aiohttp.client_exceptions import ClientConnectorError
try:
from aiohttp import ClientError
except:
from aiohttp import ClientProxyConnectionError as ProxyConnectionError
from proxypool.db import RedisClient
from proxypool.setting import *
class Tester... | python |
import sys
sys.path.append("..")
import cv2
from CORE.streamServerDependency.camera import Camera
c = Camera()
cv2.namedWindow("test")
while True:
cv2.imshow("test", c.image)
cv2.waitKey(1) | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('artwork', '0006_auto_20151010_2243'),
]
operations = [
migrations.AlterField(
model... | python |
import image2ascii.boot
import image2ascii.lib
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--filename', required=True, type=str)
parser.add_argument('-W', '--width', type=int)
parser.add_argument('-H', '--height', type=int)
parser.add_argument('-greysav... | python |
import itertools
from intcode import Computer
def run(data):
code = [int(c) for c in data.split(',')]
return find_max_thrust(code)[-1], find_max_thrust_feedback(code)[-1]
def find_max_thrust(code):
max_thrust = 0
for phases in itertools.permutations(range(5), 5):
val = 0
for phase i... | python |
'''
Development Test Module
'''
# import os
import argparse
from dotenv import load_dotenv
#from pyspreader.client import SpreadClient, MSSQLSpreadClient
from pyspreader.worker import SpreadWorker
load_dotenv(verbose=True)
if __name__ == '__main__':
# cli = MSSQLSpreadClient(connection_string=os.environ.get('SPREA... | python |
"""
Django settings for ac_mediator project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
impor... | python |
import time
import aiohttp
import asyncio
import statistics
runs = []
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main(loop):
for i in range(3):
latencies = []
expected_response = ','.join(['OK']*100)
async ... | python |
import logging
import torch.nn
from torch_scatter import scatter
from nequip.data import AtomicDataDict
from nequip.utils import instantiate_from_cls_name
class SimpleLoss:
"""wrapper to compute weighted loss function
if atomic_weight_on is True, the loss function will search for
AtomicDataDict.WEIGHTS_... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2017 ROBOTIS CO., LTD.
#
# 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 cop... | python |
import pandas as pd
import S3Api
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, ENGLISH_STOP_WORDS
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.decomposition import PCA
import numpy as np
import plotly.express as px
from sklea... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 17:35:51 2018
@author: Dr Kaustav Das (kaustav.das@monash.edu)
"""
# import numpy as np
import copy as cp
from math import sqrt, exp, log
from collections import deque
from scipy.stats import norm
# Computes the usual Black Scholes Put/Call formula (not PutBS) for... | python |
import xml.etree.ElementTree as ET
import traceback
def build_crafting_lookup():
# TODO: Keep working on this, I think only one ingredient is in the list currently.
"""
Returns a crafting lookup table
:return:
"""
crafting_dict = {}
itemtree = ET.parse('libs/game_data/items.xml')
item... | python |
def main():
for a in range(1,int(1000/3)+1):
for b in range(a+1, int(500-a/2)+1): # b < c <=> b < 1000-(a+b) <=> b < 500 - a/2
if chkVal(a, b):
print(a * b * (1000-(a+b)))
def chkVal(a, b):
left_term = a**2 + b**2
right_term = (1000 - (a + b))**2
return left_term ==... | python |
import time
from hyades.inventory.inventory import InventoryManager
inventory = InventoryManager('inventory.yml')
connectors_result = {}
for device in inventory.filter(mode='sync'):
connector = device.connection_manager.registry_name
print(f'\nStart collecting {device.name} with {connector}')
connectors_... | python |
from yourproduct.config import Config
CONFIG: Config = Config()
| python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from ._version import get_versions
__author__ = 'Juan Ortiz'
__email__ = 'ortizub41@gmail.com'
__version__ = get_versions()['version']
del get_versions
def hello_world():
print('Hello, world!')
return True
| python |
#!/usr/bin/env python
import json
import time
try:
import requests
except ImportError:
print "Install requests python module. pip install requests"
exit(1)
GREEN = '\033[92m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def check_file(value):
try:
f = open(value)
return f.read()... | python |
"""Tests for provide_url_scheme function."""
from url_normalize.url_normalize import provide_url_scheme
EXPECTED_DATA = {
"": "",
"-": "-",
"/file/path": "/file/path",
"//site/path": "https://site/path",
"ftp://site/": "ftp://site/",
"site/page": "https://site/page",
}
def test_provide_url_sc... | python |
import sys
import os
from datetime import datetime
import unittest
import xlwings as xw
from xlwings.constants import RgbColor
from .common import TestBase, this_dir
# Mac imports
if sys.platform.startswith('darwin'):
from appscript import k as kw
class TestRangeInstantiation(TestBase):
def test_range1(self... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pylab
import numpy
import Image # PIL
from supreme.lib import pywt
im = Image.open("data/aero.png").convert('L')
arr = numpy.fromstring(im.tostring(), numpy.uint8)
arr.shape = (im.size[1], im.size[0])
pylab.imshow(arr, interpolation="nearest", cmap=pylab.cm.gray)
... | python |
import sys
import math
def count_digit(p1, p2):
l1 = len(str(p1))
l2 = len(str(p2))
count = 0
for i in range(l1, l2+1):
if i == l1:
st = p1
else:
st = 10**(i-1)
if i == l2:
ed = p2
else:
ed = 10**i - 1
count += (ed... | python |
from utils import pandaman, handyman
from feature_extraction import data_loader
from feature_extraction import feature_preprocessor
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
plt.style.use('ggplot')
if __name__ == '__main__':
train_data, test_data = data_loader.create_flat_int... | python |
import numpy as np
import pandas as pd
import pytest
from dku_timeseries import IntervalRestrictor
from recipe_config_loading import get_interval_restriction_params
@pytest.fixture
def datetime_column():
return "Date"
@pytest.fixture
def df(datetime_column):
co2 = [315.58, 316.39, 316.79, 316.2]
countr... | python |
# Dan Thayer
# PID control servo motor and distance sensor.. just messing around
from range_sensor import measure_distance
# gains
k_p = 1.0
k_d = 1.0
k_i = 0.001
def run(target_dist, debug=False):
"""
Sense distance and drive motor towards a given target
:param target_dist: distance in cm
:return:
... | python |
# Copyright 2011 Justin Santa Barbara
#
# 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 l... | python |
from urlparse import urlparse, urlunparse
import re
from bs4 import BeautifulSoup
from .base import BaseCrawler
from ...models import Author, AuthorType
class CitizenCrawler(BaseCrawler):
TL_RE = re.compile('(www\.)?citizen.co.za')
def offer(self, url):
""" Can this crawler process this URL? """
... | python |
import sys
sys.path.insert(1, "../")
import pickle
from story_environment_neuro import *
from decode_redo_pipeline_top_p_multi import Decoder
import numpy as np
from data_utils import *
import argparse
from memoryGraph_scifi2 import MemoryGraph
import datetime
from semantic_fillIn_class_offloaded_vn34 import FillIn
fro... | python |
usrLvl = int(input("What level are you right now (1-50)?"))
usrXP = int(input("What is your XP count right now?"))
usrPrs = int(input("What prestige are you right now (0-10)?"))
usr20 = str(input("Are you a Kamado (write \"y\" or \"n\")?"))
usr10 = str(input("Are you a Tokito or Ubuyashiki (write \"y\" or \"n\")?"))
xp... | python |
import math
import os
import pytest
import torch
from tests import _PATH_DATA
@pytest.mark.skipif(not os.path.exists(_PATH_DATA), reason="Data files not found")
def test_load_traindata():
dataset = torch.load(f"{_PATH_DATA}/processed/train.pt")
assert len(dataset) == math.ceil(25000 / 64)
@pytest.mark.ski... | python |
"""
====================
Fetching Evaluations
====================
Evalutions contain a concise summary of the results of all runs made. Each evaluation
provides information on the dataset used, the flow applied, the setup used, the metric
evaluated, and the result obtained on the metric, for each such run made. These... | python |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import argparse
def plot_err_cdf(data1, data2):
"""draw cdf to see the error between without/with freeze"""
err_data = []
for x, y in zip(data1, data2):
err_data.append(abs(x-y))
sorted_err_data = np.sort(er... | python |
from datetime import timedelta
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.utils import timezone
from url_shortener.links.models import Link
class LinkTest(TestCase):
def create_link(self, expires_at=None, short_url="asdf", full_url="https://google.com"):
... | python |
import configparser
from datetime import datetime
import os
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import count
from pyspark.sql.types import DateType
def create_spark_session():
spark = SparkSession \
.builder \
.config("spark.jars.packages", "org.apache.hadoop... | python |
from src.loader.interface import ILoader
from src.loader.impl import DataLoader | python |
#!/usr/bin/python
import sys, re
import fabric.docs
import fabric, simplejson, inspect, pprint
from lib import fabfile
action_dir = "./"
def generate_meta(fabfile):
for i in dir(fabfile):
action_meta = {}
fabtask = getattr(fabfile,i)
if isinstance(fabtask,fabric.tasks.WrappedCallableTask):
print "%s is a ... | python |
from spike import PrimeHub
hub = PrimeHub()
while True:
if hub.left_button.was_pressed():
print("Left button was Pressed")
elif hub.right_button.was_pressed():
print("Right button was Pressed")
| python |
from distutils.core import setup
import glob, os
from osg_configure.version import __version__
def get_data_files():
"""
Generates a list of data files for packaging and locations where
they should be placed
"""
# create a list of test files
fileList = []
for root, subFolders, files in os... | python |
import socket
from tkinter import*
#Python socket client by Jeferson Oliveira
#ESSE É O CLIENTE ESSE CÓDIGO DEVER SER ADAPTADO NO PROJETO
HOST = 'ip' #DEFINE O IP DO SERVIDOR
PORT = 11000
tela = Tk()
def LerComando(comando):
if comando == "b1":
botao['text'] = "1"
def de(): #ESSA FUN... | python |
import asyncio
import copy
import logging
import time
from collections import defaultdict
from decimal import Decimal
from typing import Any, Dict, List, Mapping, Optional
from bidict import bidict, ValueDuplicationError
import hummingbot.connector.derivative.binance_perpetual.binance_perpetual_utils as utils
import ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.