repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
StanfordAHA/garnet | global_buffer/design/global_buffer_parameter.py | import dataclasses
import math
import os
@dataclasses.dataclass(eq=True, frozen=False)
class GlobalBufferParams:
# cgra parameters
num_prr: int = 16
num_prr_width: int = math.ceil(math.log(num_prr, 2))
cgra_axi_addr_width: int = 13
cgra_axi_data_width: int = 32
# tile parameters
num_glb_t... |
StanfordAHA/garnet | global_buffer/design/glb_tile.py | from kratos import Generator, RawStringStmt
from global_buffer.design.glb_core import GlbCore
from global_buffer.design.glb_tile_cfg import GlbTileCfg
from global_buffer.design.glb_tile_pcfg_switch import GlbTilePcfgSwitch
from global_buffer.design.glb_cfg_ifc import GlbConfigInterface
from global_buffer.design.global_... |
StanfordAHA/garnet | global_buffer/design/glb_core_strm_router.py | from kratos import Generator, always_ff, always_comb, posedge
from global_buffer.design.global_buffer_parameter import GlobalBufferParams
from global_buffer.design.glb_header import GlbHeader
class GlbCoreStrmRouter(Generator):
def __init__(self, _params: GlobalBufferParams):
super().__init__("glb_core_st... |
StanfordAHA/garnet | global_buffer/design/glb_tile_cfg.py | from kratos import Generator
from global_buffer.design.glb_header import GlbHeader
from global_buffer.design.glb_cfg_ifc import GlbConfigInterface
from global_buffer.design.glb_tile_cfg_ctrl import GlbTileCfgCtrl
from global_buffer.gen_global_buffer_rdl import gen_global_buffer_rdl, gen_glb_pio_wrapper
from global_buff... |
StanfordAHA/garnet | global_buffer/design/global_buffer_magma_helper.py | import magma as m
from global_buffer.design.global_buffer_parameter import GlobalBufferParams
def _get_raw_interface(params: GlobalBufferParams):
return dict(
clk=m.In(m.clock),
stall=m.In(m.Bits[params.num_glb_tiles]),
cgra_stall_in=m.In(m.Bits[params.num_glb_tiles]),
reset=m.In(m... |
StanfordAHA/garnet | systemRDL/util.py | import json
import argparse
import sys
import os
from systemrdl import RDLCompiler, node, RDLCompileError
from peakrdl.html import HTMLExporter
from dataclasses import dataclass
def convert_field(rdlc: RDLCompiler, obj: node.FieldNode) -> dict:
json_obj = dict()
json_obj['type'] = 'field'
json_obj['inst_n... |
clayman-micro/passport | src/passport/use_cases/users.py | <filename>src/passport/use_cases/users.py
from passport.domain import User
from passport.services.users import UserService
from passport.storage import DBStorage
from passport.use_cases import UseCase
class LoginUseCase(UseCase):
async def execute(self, email: str, password: str) -> User:
storage = DBStor... |
clayman-micro/passport | src/passport/storage/migrations/versions/615677fb3a4f_add_users_table.py | """
Add users table
Revision ID: 615677fb3a4f
Revises:
Create Date: 2020-09-09 21:36:41.102344
"""
import sqlalchemy # type: ignore
from alembic import op # type: ignore
# revision identifiers, used by Alembic.
revision = "<PASSWORD>"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
... |
clayman-micro/passport | src/passport/use_cases/__init__.py | <filename>src/passport/use_cases/__init__.py
from aiohttp import web
class UseCase:
def __init__(self, app: web.Application) -> None:
self.app = app
|
clayman-micro/passport | tests/handlers/test_api.py | <filename>tests/handlers/test_api.py
from datetime import datetime, timedelta
from typing import Dict
import jwt
import orjson # type: ignore
import pytest # type: ignore
from passlib.handlers.pbkdf2 import pbkdf2_sha512 # type: ignore
from passport.domain import TokenType, User
from passport.services.tokens impor... |
clayman-micro/passport | src/passport/services/users.py | <filename>src/passport/services/users.py
from aiohttp_micro.core.exceptions import EntityAlreadyExist # type: ignore
from passport.domain import User
from passport.domain.storage import Storage
from passport.exceptions import Forbidden
class UserService:
def __init__(self, storage: Storage) -> None:
sel... |
clayman-micro/passport | src/passport/domain/__init__.py | from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
from aiohttp_micro.core.entities import Entity # type: ignore
from passlib.handlers.pbkdf2 import pbkdf2_sha512 # type: ignore
class TokenType(Enum):
access = "access"
refresh = "refresh"
@dataclass
class Per... |
clayman-micro/passport | src/passport/handlers/api/tokens.py | from aiohttp import web
from aiohttp_micro.core.exceptions import EntityNotFound # type: ignore
from aiohttp_micro.web.handlers import json_response # type: ignore
from passport.domain import TokenType
from passport.exceptions import BadToken
from passport.handlers import (
session_required,
UserResponseSche... |
clayman-micro/passport | src/passport/handlers/__init__.py | <gh_stars>0
import functools
from aiohttp import web
from aiohttp_micro.core.exceptions import EntityNotFound # type: ignore
from aiohttp_micro.core.schemas import EntitySchema # type: ignore
from marshmallow import fields, Schema
from passport.domain import User
from passport.exceptions import BadToken, TokenExpir... |
clayman-micro/passport | src/passport/app.py | import os
from aiohttp import web
from aiohttp_micro import setup as setup_micro
from aiohttp_micro import setup_logging, setup_metrics
from aiohttp_storage import setup as setup_storage # type: ignore
from passport.config import AppConfig
from passport.handlers import auth as auth_endpoints
from passport.handlers.a... |
clayman-micro/passport | src/passport/handlers/auth.py | <gh_stars>0
import secrets
from datetime import datetime, timedelta
from typing import Dict
from aiohttp import web
from aiohttp_micro.core.exceptions import EntityNotFound # type: ignore
from aiohttp_micro.web.handlers import ( # type: ignore
json_response,
validate_payload,
)
from passport.exceptions impo... |
clayman-micro/passport | src/passport/__main__.py | from pathlib import Path
import click
import uvloop # type: ignore
from aiohttp_micro.cli.server import server # type: ignore
from aiohttp_storage.management.storage import storage # type: ignore
from config import EnvValueProvider, FileValueProvider, load # type: ignore
from passport.app import init
from passpor... |
clayman-micro/passport | src/passport/storage/migrations/versions/a01d1258d7a7_add_sessions.py | <gh_stars>0
"""Add sessions
Revision ID: a01d1258d7a7
Revises: 9ca629ddd362
Create Date: 2020-09-10 13:16:28.154448
"""
import sqlalchemy as sa # type: ignore
from alembic import op # type: ignore
# revision identifiers, used by Alembic.
revision = "a01d1258d7a7"
down_revision = "9ca629ddd362"
branch_labels = None... |
clayman-micro/passport | src/passport/storage/__init__.py | from aiohttp_storage.storage import ( # type: ignore
DBStorage as AbstractDBStorage,
)
from databases import Database
from passport.domain.storage import Storage
from passport.storage.sessions import SessionDBStorage
from passport.storage.users import UsersDBRepo
class DBStorage(Storage, AbstractDBStorage):
... |
clayman-micro/passport | src/passport/domain/storage/__init__.py | <filename>src/passport/domain/storage/__init__.py
from abc import ABC
from passport.domain.storage.sessions import SessionRepo
from passport.domain.storage.users import UsersRepo
class Storage(ABC):
sessions: SessionRepo
users: UsersRepo
|
clayman-micro/passport | src/passport/services/tokens.py | <gh_stars>0
from datetime import datetime, timedelta
import jwt
from passport.domain import TokenType, User
from passport.exceptions import BadToken, TokenExpired
class TokenGenerator:
__slots__ = ("_private_key",)
def __init__(self, private_key: str) -> None:
self._private_key = private_key
d... |
clayman-micro/passport | src/passport/handlers/api/users.py | from typing import Dict
from aiohttp import web
from aiohttp_micro.core.exceptions import ( # type: ignore
EntityAlreadyExist,
EntityNotFound,
)
from aiohttp_micro.web.handlers import ( # type: ignore
json_response,
validate_payload,
)
from passport.domain import TokenType
from passport.exceptions i... |
clayman-micro/passport | src/passport/storage/migrations/versions/9ca629ddd362_add_permissions.py | <reponame>clayman-micro/passport
"""Add permissions
Revision ID: 9ca629ddd362
Revises: 615677fb3a4f
Create Date: 2020-09-09 23:37:57.555057
"""
import sqlalchemy as sa # type: ignore
from alembic import op # type: ignore
# revision identifiers, used by Alembic.
revision = "9ca629ddd362"
down_revision = "615677fb3a... |
clayman-micro/passport | src/passport/storage/users.py | <filename>src/passport/storage/users.py
from datetime import datetime
import sqlalchemy # type: ignore
from aiohttp_micro.core.exceptions import EntityNotFound # type: ignore
from aiohttp_storage.storage import metadata # type: ignore
from databases import Database
from sqlalchemy import func
from sqlalchemy.orm.qu... |
clayman-micro/passport | src/passport/exceptions.py | class BadToken(Exception):
pass
class TokenExpired(Exception):
pass
class Forbidden(Exception):
pass
|
clayman-micro/passport | src/passport/client.py | <gh_stars>0
import functools
from typing import AsyncGenerator
from aiohttp import ClientSession, web
from config import Config, StrField # type: ignore
from passport.domain import User
from passport.exceptions import BadToken, TokenExpired
from passport.services.tokens import TokenDecoder
class PassportConfig(Con... |
clayman-micro/passport | src/passport/handlers/api/__init__.py | <filename>src/passport/handlers/api/__init__.py<gh_stars>0
from aiohttp import web
from aiohttp_micro.web.handlers import json_response # type: ignore
from marshmallow import fields, Schema # type: ignore
class KeysResponseSchema(Schema):
public = fields.Str()
async def keys(request: web.Request) -> web.Respo... |
clayman-micro/passport | src/passport/storage/sessions.py | from datetime import datetime
import sqlalchemy # type: ignore
from aiohttp_storage.storage import metadata # type: ignore
from databases import Database
from passport.domain import User
from passport.domain.storage.sessions import SessionRepo
sessions = sqlalchemy.Table(
"sessions",
metadata,
sqlalch... |
clayman-micro/passport | src/passport/domain/storage/sessions.py | <reponame>clayman-micro/passport
from datetime import datetime
from typing import Protocol
from passport.domain import User
class SessionRepo(Protocol):
async def fetch(self, key: str) -> int:
...
async def add(self, user: User, key: str, expires: datetime) -> None:
...
async def remove... |
clayman-micro/passport | src/passport/domain/storage/users.py | from typing import Protocol
from passport.domain import Permission, User
class UsersRepo(Protocol):
async def fetch_by_key(self, key: int) -> User:
...
async def fetch_by_email(self, email: str) -> User:
...
async def exists(self, email: str) -> bool:
...
async def add(self... |
clayman-micro/passport | tests/conftest.py | import faker # type: ignore
import pytest # type: ignore
from aiohttp import web
from aiohttp_storage.tests import storage # type: ignore
from passport.app import AppConfig, init
@pytest.fixture(scope="session")
def config():
conf = AppConfig(
defaults={
"consul": {"host": "localhost", "po... |
swaranjalii/modern-django | config/settings/local.py | <reponame>swaranjalii/modern-django<filename>config/settings/local.py
from .base import *
SECRET_KEY = env('DJANGO_SECRET_KEY', default=')<KEY>')
DEBUG = env.bool('DJANGO_DEBUG', default=True) |
ccolorado/branch_drawer | branch_drawer.py | #!/usr/bin/env python2.7
import argparse
import ConfigParser
import io
import os
import os.path
import subprocess
DEFAULTS = """
[branch_drawer]
# Location of drawer repo
drawer_dir=~/.branch_drawer.d
# Drawer Name
drawer_link_name=Branch_Drawer
"""
# git config hook.yourhook.yourconfigval value
def create_conf():
... |
DiegoGom/Photo-whit-NodeJS-Python-FsWebCam | tomarfoto.py | #!/usr/bin/env python
# -*- coding: utf-8
import os
import time
os.system("mkdir hola")
|
siyuan0/pytorch_model_prune | prune.py | <reponame>siyuan0/pytorch_model_prune
import torch
import torch.nn as nn
import numpy as np
import FLOP
PRUNE_ID = 0
DEBUG_MODE = False
## This code prunes all the Conv2d layers in a given pytorch model. The Conv2d are pruned by removing
## channels based on an evaluation of their weights. The pruning is done with th... |
Zachary-Jackson/Tacocat | forms.py | <gh_stars>1-10
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import (DataRequired, Email, Length, EqualTo,
ValidationError)
from models import User
def email_exists(form, field):
"""This checks the database to see if a user's em... |
Zachary-Jackson/Tacocat | models.py | <gh_stars>1-10
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('taco.db')
class User(UserMixin, Model):
"""This is the model for a user."""
email = CharField(unique=True)
password = CharField(max_len... |
Zachary-Jackson/Tacocat | tacocat.py | from flask import (Flask, render_template, flash, redirect, url_for, g)
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import (LoginManager, login_user, logout_user,
login_required, current_user)
import forms
import models
DEBUG = True
PORT = 8000
HOST = '0.0.0.0'
... |
rajeshnokia/monolithe | monolithe/generators/lang/python/converter.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# no... |
rajeshnokia/monolithe | tests/base/sdk/python/tdldk/cli/cli.py | #!/usr/bin/env python
#
# __code_header example
# put your license header here
# it will be added to all the generated files
#
import argparse
import sys
sys.path.append("../")
class _HelpAction(argparse._HelpAction):
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()... |
rajeshnokia/monolithe | tests/base/sdk/python/tdldk/cli/__init__.py | # -*- coding: utf-8 -*-
#
# __code_header example
# put your license header here
# it will be added to all the generated files
#
import requests
import requests.packages.urllib3.exceptions as exceptions
requests.packages.urllib3.disable_warnings(exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warn... |
KonecnyDavid/IdosNextDeparture | Scraper/scrape.py | <reponame>KonecnyDavid/IdosNextDeparture
import requests
import re
import json
from bs4 import BeautifulSoup
from_stop = "Jungmannova"
lines = {
"1": ("reckovice", "ecerova"),
"6": ("kralovo pole, nadrazi", "<NAME>")
}
week_start = 17
def create_url(line_n, end_stop, day):
return "https://idos.idnes.cz... |
rgbkrk/jupytext | jupytext/version.py | <filename>jupytext/version.py<gh_stars>0
"""Jupytext's version number"""
__version__ = '1.3.3-dev'
|
jbaker10/sal-saml | urls.py | from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from sal.origurls import *
urlpatterns += [
url(r'^saml2/', include('djangosaml2.urls')),
]
|
jbaker10/sal-saml | process_build.py | <filename>process_build.py
import argparse
import subprocess
import os
# parser = argparse.ArgumentParser()
# parser.add_argument('tag', nargs='?', default='')
# args = parser.parse_args()
tag = os.getenv('TAG', '')
if tag == '':
if os.getenv('CIRCLE_BRANCH') == 'master':
tag = 'latest'
else:
... |
Sudhishna/jetez | jet/main.py | <reponame>Sudhishna/jetez<gh_stars>0
#!/usr/bin/env python
# Copyright 2018 Juniper Networks, Inc. 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. You may obtain
# a copy of the License at
#
# h... |
Sudhishna/jetez | jet/crypto.py | # Copyright 2018 Juniper Networks, Inc. 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. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
bmng-dev/bitmessage-pow | test_pow.py | import os
import sys
platform = os.environ.get('PLATFORM', '').lower()
interpreter_bits = (sys.maxsize.bit_length() + 7) / 8 * 8
if platform == 'x64' and interpreter_bits != 64:
raise SystemExit
if platform in ['win32', 'x86'] and interpreter_bits != 32:
raise SystemExit
import ctypes
import hashlib
import l... |
bmng-dev/bitmessage-pow | test_old.py | <filename>test_old.py
import argparse
import ctypes
import hashlib
import logging
import struct
logging.basicConfig(format='%(levelname)8s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
Q = struct.Struct('!Q')
payload = '\x00' * 4
time_to_live = 300
trials = 1000
padding = 1000
payload = p... |
tbsexton/pythonbible | pythonbible/counters/book_counter.py | from functools import singledispatch
from typing import List
from pythonbible.normalized_reference import NormalizedReference
from pythonbible.parser import get_references
@singledispatch
def count_books(references: List[NormalizedReference]) -> int:
"""Return the count of books of the Bible included in the give... |
tbsexton/pythonbible | pythonbible/counters/chapter_counter.py | <reponame>tbsexton/pythonbible
from functools import singledispatch
from typing import List
from pythonbible.books import Book
from pythonbible.normalized_reference import NormalizedReference
from pythonbible.parser import get_references
from pythonbible.verses import get_number_of_chapters
@singledispatch
def count... |
tbsexton/pythonbible | pythonbible/counters/verse_counter.py | <reponame>tbsexton/pythonbible
from functools import singledispatch
from typing import List, Optional
from pythonbible.books import Book
from pythonbible.normalized_reference import NormalizedReference
from pythonbible.parser import get_references
from pythonbible.verses import get_max_number_of_verses, get_number_of_... |
tbsexton/pythonbible | tests/test_counters.py | from typing import List
import pythonbible as bible
def test_count_books_single_book() -> None:
# Given a list of references
references: List[bible.NormalizedReference] = bible.get_references("James 1:4-6")
# When we get the count of books in the references
number_of_books: int = bible.count_books(r... |
alanmitchell/bmon-structure-queries | make_reading_info.py | #!/usr/bin/env python3
import sqlite3
import time
from datetime import datetime
import sys
from pathlib import Path
import pytz
try:
conn_readings = sqlite3.connect('bms_data.sqlite')
cur_readings = conn_readings.cursor()
# Delete the old sensor_stats database
Path('sensor_stats.sqlite').unlink(missi... |
nansencenter/DAPPER | dapper/mods/Lorenz05/settings01.py | import numpy as np
import dapper.mods as modelling
from dapper.mods.Lorenz05 import Model
from dapper.tools.localization import nd_Id_localization
# Sakov uses K=300000, BurnIn=1000*0.05
tseq = modelling.Chronology(0.002, dto=0.05, Ko=400, Tplot=2, BurnIn=5)
model = Model(b=8)
Dyn = {
'M': model.M,
'model':... |
nansencenter/DAPPER | dapper/mods/__init__.py | <reponame>nansencenter/DAPPER
"""Models included with DAPPER.
.. include:: ./README.md
"""
import copy as cp
import inspect
from pathlib import Path
import numpy as np
import struct_tools
# Imports used to set up HMMs
import dapper.tools.progressbar as pb
from dapper.dpr_config import rc
from dapper.mods.utils impo... |
nansencenter/DAPPER | tests/test_example_2.py | <reponame>nansencenter/DAPPER<filename>tests/test_example_2.py
"""Stupidly compare the full results table.
Use `pytest -vv tests/test_example_2.py` for a better diff when tests fail.
Possible reasons for failing:
- Random number generation might change on different versions/platforms.
- pytest imports some other Lore... |
nansencenter/DAPPER | dapper/tools/localization.py | <filename>dapper/tools/localization.py
"""Localization tools, including distance and tapering comps.
A good introduction to localization:
Sakov (2011), Computational Geosciences:
'Relation between two common localisation methods for the EnKF'.
"""
import itertools
import numpy as np
def pairwise_distances(A, B=Non... |
nansencenter/DAPPER | dapper/xp_launch.py | <filename>dapper/xp_launch.py
"""Tools (notably `xpList`) for setup and running of experiments (known as `xp`s).
See `dapper.da_methods.da_method` for the strict definition of `xp`s.
"""
import copy
import dataclasses as dcs
import os
import re
import shutil
import sys
from functools import wraps
from pathlib import ... |
CherryYin/ml_algorithm | naive_bayes/bayes_longxinchen.py | #! /usr/bin/env python
# coding=utf-8
# Authors: Hanxiaoyang <<EMAIL>>
# simple naive bayes classifier to classify sohu news topic
# data can be downloaded in http://www.sogou.com/labs/dl/cs.html
# 代码功能:简易朴素贝叶斯分类器,用于对搜狐新闻主题分类,数据可在http://www.sogou.com/labs/dl/cs.html下载(精简版)
# 详细说明参见博客http://blog.csdn.net/han_xiaoyang/... |
CherryYin/ml_algorithm | knn/kd_tree.py | <gh_stars>0
#coding:utf-8
import numpy as np
import gzip
import itertools
from datetime import datetime
def _read32(bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(input_file, is_value_binary, is_matrix):
with gzip.open(inpu... |
CherryYin/ml_algorithm | policy_tree/policy_tree.py | <reponame>CherryYin/ml_algorithm
#coding:utf-8
import sys
#from tree import *
reload(sys)
sys.setdefaultencoding('utf-8')
from pylab import *
def createDataSet():
"""
创建数据集
:return:总数据集、特征标签列表、特征值map、类别值列表
"""
dataSet = [[u'青年', u'否', u'否', u'一般', u'拒绝'],
[u'青年', u'否', u'否', u'好', u'... |
CherryYin/ml_algorithm | naive_bayes/sogouC_prepare_bayes.py | <reponame>CherryYin/ml_algorithm<gh_stars>0
#coding:utf-8
import os, sys
import jieba
from datetime import datetime
reload(sys)
sys.setdefaultencoding("utf-8")
stopWordList= [','.decode('utf-8'), '的'.decode('utf-8'), '\n', ' ', '。'.decode('utf-8'), '、'.decode('utf-8'), '在'.decode('utf-8'),
'了'.decode(... |
CherryYin/ml_algorithm | naive_bayes/bayes_2.py | <filename>naive_bayes/bayes_2.py<gh_stars>0
#coding:utf-8
import numpy as np
#coding:utf-8
import numpy as np
import gzip
import itertools
from datetime import datetime
def _read32(bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_imag... |
CherryYin/ml_algorithm | SVM/drama_fans_predict.py | <reponame>CherryYin/ml_algorithm<gh_stars>0
#coding:utf-8
import numpy as np
import random
import os
from libsvm.python.svmutil import *
def split_data(input_data_path, input_label_path, input_size, K):
train_x = []
test_x = []
train_y = []
test_y = []
with open(input_data_path, 'r') as f1:
... |
CherryYin/ml_algorithm | naive_bayes/byes.py | #coding:utf-8
import numpy as np
def loadDataSet():
postingList = [[ 'my', 'dog', 'has', 'flea', 'problem', 'help', 'please'],
['maybe', 'not', 'take', 'hime', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'hime'],
['s... |
CherryYin/ml_algorithm | knn/kd_tree_hankcs.py | <gh_stars>0
# -*- coding:utf-8 -*-
# Filename: kdtree.py
# Author:hankcs
# Date: 2015/2/4 15:01
import copy
import itertools
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib import animation
T = [[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]]
def draw_point(data):
X,... |
CherryYin/ml_algorithm | knn/knn_mnist.py | <reponame>CherryYin/ml_algorithm<filename>knn/knn_mnist.py
#coding:utf-8
import numpy as np
import os
import gzip
from six.moves import urllib
import operator
from datetime import datetime
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
TRAIN_LABELS = 'train-labels-idx1-ub... |
pugmajere/fc-effects | layouts/create_strands.py | <reponame>pugmajere/fc-effects
#!/usr/bin/python
points = []
adj = 50 / 2 * 0.01
def f(x):
return [0.01 * x - adj, 0.2 * x - adj, 0.05 * x - adj]
def g(x):
return [0.01 * x - adj, 0.25 * x - adj * 2, 0.05 * x - adj]
def h(x):
return [0.01 * x - adj, 0.175 * x - adj * 3, 0.05 * x - adj]
for i in range(... |
Pheonnexx/alexa_pokemon | app/grab_pokemon_info.py | <reponame>Pheonnexx/alexa_pokemon<filename>app/grab_pokemon_info.py
import logging
import requests
import json
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.launch
def start_pokemon_ask():
welcome_to_... |
Pheonnexx/alexa_pokemon | app/__init__.py | from flask import Flask
from flask_ask import Ask
app = Flask(__name__)
ask = Ask(app, "/")
|
mrasskazov/tf-dev-env | scripts/gather-unittest-targets.py | <reponame>mrasskazov/tf-dev-env<gh_stars>10-100
#!/usr/bin/env python
import json
import sys
import os
from xml.etree import ElementTree
patchsets = json.load(sys.stdin)
home_dir = os.getenv("HOME", '/root')
with open("%s/contrail/controller/ci_unittests.json" % home_dir, 'r') as fh:
unittests = json.load(fh)
... |
mrasskazov/tf-dev-env | scripts/controller_ut/run-tests.py | #!/usr/bin/env python3
import os
import random
import sys
import json
import jinja2
import argparse
import subprocess
import string
import logging
import shutil
from lxml import etree
logging.basicConfig(level=logging.DEBUG)
class TestResult:
SUCCESS = 0
FAILURE = 1
MISSING_XML = 2
MISSING_LOG = 3
... |
mrasskazov/tf-dev-env | scripts/patch-repo-manifest.py | #!/usr/bin/env python
import argparse
import json
import logging
import os
import sys
import traceback
from xml.etree import ElementTree
def dbg(msg):
logging.debug(msg)
def err(msg):
logging.error(msg)
class Manifest(object):
def __init__(self, file, remote):
self.remote = remote
if ... |
MShokry/AIND-Planning | example_have_cake.py | from aimacode.logic import PropKB
from aimacode.planning import Action
from aimacode.search import (
Node, breadth_first_search, astar_search, depth_first_graph_search,
uniform_cost_search, greedy_best_first_graph_search, Problem,
)
from aimacode.utils import expr
from lp_utils import (
FluentState, encode_... |
MShokry/AIND-Planning | lp_utils.py | from aimacode.logic import associate
from aimacode.utils import expr
class FluentState():
""" state object for planning problems as positive and negative fluents
"""
def __init__(self, pos_list, neg_list):
self.pos = pos_list
self.neg = neg_list
def sentence(self):
return ex... |
MShokry/AIND-Planning | rep.py | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
|
MShokry/AIND-Planning | mytest.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 16 11:06:40 2018
@author: mshokry
"""
import argparse
from timeit import default_timer as timer
from aimacode.search import InstrumentedProblem
from aimacode.search import (breadth_first_search, astar_search,
breadth_first_tree_search, depth_f... |
MShokry/AIND-Planning | run_search_timer.py | import time
import signal
from run_search import *
timeout = time.time() + 60*5 # 5 Minutes sleep
def handle(signum,frame):
raise TimeoutError()
#raise Exception("Time Up exeeded 7 Minutes")
#signal.alarm(7*60)
for i in range(1,11):
start = timer()
signal.signal(signal.SIGALRM,handle)
signal.alarm(10*60)
try ... |
MShokry/AIND-Planning | oth.py |
import numpy as np
import math
class Clashes:
## constructor does not do anything
def __init__(self):
# self.chromosome=[2,4,7,4,8,5,5,2];
# self.chromosome=[3,2,7,5,2,4,1,1];
# self.chromosome=[2,4,4,1,5,1,2,4];
# self.chromosome=[3,2,5,4,3,2,1,3];
## GA Crossover ... |
binp-automation/ksfc-devsup | script/test.py | <filename>script/test.py
#!/usr/bin/python3
import os
import sys
import time
from subprocess import run
from lib.setup import setup
from lib.epics import CaRepeater, Ioc, caget, caput
def test_binding():
assert run(["cargo", "test"], cwd="./binding").returncode == 0
def test_ioc():
with CaRepeater(), Ioc("i... |
cburmeister/pwgen-xkcd | pwgen_xkcd.py | <reponame>cburmeister/pwgen-xkcd
#!/usr/bin/python
import click
import random
@click.command()
@click.argument('filename', type=click.File('r'))
@click.option('--n', default=10, help='Number of passphrases to generate.')
@click.option('--max_words', default=4, help='Number of words.')
@click.option('--min_word_lengt... |
cburmeister/pwgen-xkcd | setup.py | from setuptools import setup
setup(
name='pwgen_xkcd',
version='1.0',
url='http://github.com/cburmeister/pwgen_xkcd/',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
oescription='',
py_modules=['pwgen_xkcd'],
platforms='any',
install_requires=[
'click==3.3',
... |
ElliottYan/self-att | fairseq/criterions/cross_entropy_with_extra_loss.py | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import torch.nn.functi... |
sarthmit/mixture_density_VAEs | train_reg_gaussVAE.py | import os
from os.path import join as pjoin
import h5py
import cPickle as cp
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from models.gaussVAE import GaussVAE
from utils.sampling_utils import *
try:
import PIL.Image as Image
except ImportError:
import ... |
sarthmit/mixture_density_VAEs | models/gaussVAE.py | <reponame>sarthmit/mixture_density_VAEs<filename>models/gaussVAE.py
import numpy as np
import tensorflow as tf
### Base neural network
def init_mlp(layer_sizes, std=.01):
params = {'w':[], 'b':[]}
... |
informix/compose-ha-demo | informix-server3/add.py | import requests
import json
query='''{"$sql": "execute function admin ('create dbspace', 'dbs1', '/opt/ibm/data/spaces/dbs1', '20M', '0')" }'''
query='''{"$sql": "execute function admin ('cdr add trustedhost', 'server3 informix, server3.composehademo_default informix')" }'''
req = "http://server1:27018/sysadmin/s... |
bashirmohd/Hyplate | webapp/app.py | from flask import Flask, render_template
from json import loads
from engine import *
app = Flask(__name__)
@app.route('/')
def home():
return render_template('hyplate/index.html')
@app.route('/register')
def register():
return render_template('hyhub/oauth/register.html')
@app.route('/forgotpassword')
def ... |
bashirmohd/Hyplate | webapp/engine.py | from requests import get
from bs4 import BeautifulSoup
from datetime import datetime as dt
from random import shuffle
from pyquery import PyQuery
from pymongo import MongoClient
###Connect db
def connect_db(collection: str, db='Hyplate'):
conn = MongoClient(host = '127.0.0.1', port = 27017)
return conn[db][co... |
lanse011/tss-merge | merge.py | # Helper function to check if the two intervals overlap
def is_overlapping(a, b):
if b[0] > a[0] and b[0] < a[1]:
return True
else:
return False
class Merge:
def merge(intervals):
""" Merging a list of intervals into overlapping intervals"""
# return empty list if interval... |
lanse011/tss-merge | test_merge.py | <reponame>lanse011/tss-merge
import unittest
from merge import Merge
class TestMerge(unittest.TestCase):
""" Test merge with valid data"""
def test_merge(self):
test_intervals = [[25,30], [2,19], [14, 23], [4,8]]
merge_result = Merge.merge(intervals=test_intervals)
self.asse... |
bdowning/aiotools | examples/ticktock.py | <filename>examples/ticktock.py
import aiotools
import asyncio
async def mytick(interval):
print('tick')
async def run():
t = aiotools.create_timer(mytick, 1.0)
await asyncio.sleep(4)
t.cancel()
await t
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(lo... |
bdowning/aiotools | examples/contextgroup.py | <reponame>bdowning/aiotools
from pprint import pprint
import asyncio
import aiotools
@aiotools.actxmgr
async def mygen(id):
yield f'mygen id is {id}'
async def run():
ctxgrp = aiotools.actxgroup(mygen(i) for i in range(10))
async with ctxgrp as values:
pprint(values)
if __name__ == '__main__':... |
bdowning/aiotools | src/aiotools/ptaskgroup.py | <filename>src/aiotools/ptaskgroup.py
import asyncio
import enum
import itertools
import logging
import sys
import traceback
from types import TracebackType
from typing import (
Any,
Coroutine,
Optional,
Type,
TypeVar,
Union,
)
try:
from typing import Protocol
except ImportError:
from typ... |
bdowning/aiotools | tests/test_defer.py | <gh_stars>100-1000
import pytest
import asyncio
from aiotools.defer import defer, adefer
from aiotools.func import apartial
def test_defer():
x = []
@defer
def myfunc(defer):
x.append(1)
defer(lambda: x.append(1))
x.append(2)
defer(lambda: x.append(2))
x.append(3... |
bdowning/aiotools | src/aiotools/defer.py | """
Provides a Golang-like ``defer()`` API using decorators, which allows grouping
resource initialization and cleanup in one place without extra indentations.
Example:
.. code-block:: python3
async def init(x):
...
async def cleanup(x):
...
@aiotools.adefer
async def do(defer): # <-- be... |
bdowning/aiotools | src/aiotools/iter.py | <filename>src/aiotools/iter.py
__all__ = (
'aiter',
)
_sentinel = object()
async def aiter(obj, sentinel=_sentinel):
"""
Analogous to the builtin :func:`iter()`.
"""
if sentinel is _sentinel:
# Since we cannot directly return the return value of obj.__aiter__()
# as being an asy... |
bdowning/aiotools | src/aiotools/context.py | <gh_stars>100-1000
"""
Provides an implementation of asynchronous context manager and its applications.
.. note::
The async context managers in this module are transparent aliases to
``contextlib.asynccontextmanager`` of the standard library in Python 3.7
and later.
"""
import abc
import contextlib
import a... |
bdowning/aiotools | src/aiotools/timer.py | <filename>src/aiotools/timer.py
"""
Provides a simple implementation of timers run inside asyncio event loops.
"""
import asyncio
import contextlib
import enum
import functools
from typing import Callable, Optional
from unittest import mock
from .compat import get_running_loop
from .taskgroup import TaskGroup
__all_... |
bdowning/aiotools | tests/test_iter.py | import asyncio
import pytest
from aiotools.iter import aiter
def test_iter():
# extra test for cross-check with builtin iter()
def stream():
for i in range(10):
yield i
last_x = -1
for x in iter(stream()):
last_x = x
assert last_x == 9
def test_iter_sentinel():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.