repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
bradshjg/nameko-cron | nameko_cron/__init__.py | import datetime
from enum import Enum
import time
from logging import getLogger
from croniter import croniter
from eventlet import Timeout
from eventlet.event import Event
import pytz
from nameko.extensions import Entrypoint
_log = getLogger(__name__)
class ConcurrencyPolicy(Enum):
ALLOW = 'allow'
SKIP = ... |
joramwessels/torcs-client | torcs_tournament.py | #! /usr/bin/env python3.5
import logging
import os
import re
import pwd
import csv
import time
import shutil
import psutil
import pathlib
import datetime
import subprocess
from collections import OrderedDict, abc
import elo
import yaml
from bs4 import BeautifulSoup
DROPBOX_DEBUG = logging.DEBUG - 1
logger = logging... |
joramwessels/torcs-client | driver_utils.py | <reponame>joramwessels/torcs-client
# file: driver_utils.py
# author: <NAME>
# date: 11-12-2017
# dependencies: numpy
# description
# usage
#
from sys import stderr
from numpy import sign
# as stated by Torcs documentation
MAX_WHEEL_ROTATION = 21
# confusing polarities
STR_R, STR_L = -1, 1
ANG_... |
joramwessels/torcs-client | mlp_driver.py | from pytocl.driver import Driver
from pytocl.car import State, Command
import mlp
class MyDriver(Driver):
def __init__(self, model_file="mlp_100x100.pt"):
mlp.use_cuda = False
self.model = mlp.load_model(model_file)
self.it = 0
def drive(self, carstate):
self.it += 1
... |
joramwessels/torcs-client | basic_control.py | <gh_stars>1-10
# file: basic_control.py
# author: <NAME>
# date:
# dependencies:
# description:
# usage:
#
from math import radians
import numpy as np
import torch
import ffnn_speed
import ffnn_steer
ANGLES = [90, 75, 60, 45, 30, 20, 15, 10, 5, 0, -5, -10, -15, -20, -30, -45, -60, -75, -90]
... |
joramwessels/torcs-client | combined_driver.py | # file: crisis_driver.py
# authors: Haukur, <NAME>
# date: 07-12-2017
# dependencies: pytocl, basic_control, swarm, crisis_driver
# description
# usage
#
from pytocl.driver import Driver
from pytocl.car import State, Command
from sys import stderr
from math import radians
from operator import sub... |
joramwessels/torcs-client | ffnn_steer.py | <reponame>joramwessels/torcs-client<filename>ffnn_steer.py
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import sys
import numpy as np
import argparse
import driver_support
import math
from os import listdir
from os.path im... |
joramwessels/torcs-client | ffnn_gears.py | <filename>ffnn_gears.py
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import sys
import numpy as np
import argparse
import driver_support
from os import listdir
from os.path import isfile, join
from collections import defau... |
joramwessels/torcs-client | data_generator.py | import argparse
import xml.etree.ElementTree as ET
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--drivers', nargs='+', type=str)
parser.add_argument('--tracks', nargs='+', type=str)
parser.add_argument('--length', type=int)
parser.add_argument('--laps', type=int)
parser.add_argument('--fil... |
joramwessels/torcs-client | combined_driver_old.py | <reponame>joramwessels/torcs-client<gh_stars>1-10
from pytocl.driver import Driver
from pytocl.car import State, Command
import torch
import time
import sys
import math
import numpy as np
from os import listdir
from os.path import isfile, join
import driver_support
from torch.autograd import Variable
from operator impo... |
joramwessels/torcs-client | gru.py | <reponame>joramwessels/torcs-client<gh_stars>1-10
# file: gru.py
# author: <NAME>
# date: 23-11-2017
# source: https://github.com/spro/practical-pytorch
# description:
#
# Trains a GRU RNN on your training data and saves the weights.
# Run by calling "python gru.py <train_data_file> <save_file>"... |
joramwessels/torcs-client | run.py | <filename>run.py<gh_stars>1-10
#! /usr/bin/env python3
from pytocl.main import main
from my_driver import MyDriver
from nn_driver import FFNNDriver
if __name__ == '__main__':
main(FFNNDriver())
|
joramwessels/torcs-client | driver_support.py | import typing as t
import numpy as np
def get_gear(current_rpm, current_gear):
if current_rpm >= 8500:
current_gear += 1
if current_rpm <= 2000:
current_gear -= 1
if current_gear <= 0:
current_gear = 1
if current_gear >= 6:
current_gear = 6
return current_gear
def g... |
joramwessels/torcs-client | train.py | <filename>train.py
#! /usr/bin/env python3
from pytocl.main import main
from combined_driver import Final_Driver
steering = [REPLACE_STEERING]
max_speed = REPLACE_MAX_SPEED
if __name__ == '__main__':
main(Final_Driver(steering, max_speed))
|
joramwessels/torcs-client | ffnn_driver.py | from pytocl.driver import Driver
from pytocl.car import State, Command
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import time
import sys
from os import listdir
from os.path import isfile, join
import driver_support
class FFNN_Driver(Driver):
def __init__(self, ... |
joramwessels/torcs-client | swarm.py | <reponame>joramwessels/torcs-client
# file: swarm.py
# author: <NAME>
# date: 05-12-2017
# depedencies: numpy
# description:
# Handles the swarm technology behind the autonomous TORCS driver.
# usage:
# Assuming the variables
# *distTraveled*, *pos*, *spd*, *crashed*, and *c... |
joramwessels/torcs-client | rnn.py | import torch.nn as nn
from torch.autograd import Variable
import torch
import torch.optim as optim
import argparse
import driver_support
import time
import sys
from os import listdir
from os.path import isfile, join
class RNNMove(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder.""... |
joramwessels/torcs-client | crisis_driver.py | # file: crisis_driver.py
# author: <NAME>
# date: 07-12-2017
# dependencies: numpy, pytocl
# description
# usage
#
from pytocl.driver import Driver
from pytocl.car import State, Command
from sys import stderr
from numpy import sign
from driver_utils import *
# margins of error when trying the ... |
joramwessels/torcs-client | empty_driver.py | from pytocl.driver import Driver
from pytocl.car import State, Command
class EmptyDriver(Driver):
...
|
joramwessels/torcs-client | genetic_approach.py | <filename>genetic_approach.py<gh_stars>1-10
import numpy as np
import random
import run_torcs
import matplotlib.pyplot as plt
from multiprocessing import TimeoutError
DATA_FILE = "gen.data"
PLOT_NAME = "evolutionary.png"
ranges = [(-5,5,float),(-5,5,float),(-5,5,float),(-5,5,float),(-5,5,float),(10,360,int)]
def muta... |
joramwessels/torcs-client | mlp.py | <reponame>joramwessels/torcs-client
# file: mlp.py
# author: <NAME>
# source: http://pytorch.org/tutorials/beginner/
# date: 15-11-2017
# description:
# Trains a fully connected feed forward neural network with
# a variable amount of units and layers. The model can be
# trained using CUDA,... |
joramwessels/torcs-client | run_torcs.py | <filename>run_torcs.py<gh_stars>1-10
import argparse
import xml.etree.ElementTree as ET
import multiprocessing
import subprocess
from pytocl.main import main
from combined_driver import Final_Driver
import os
import signal
import time
parser = argparse.ArgumentParser()
parser.add_argument('--drivers', nargs='+', type=... |
joramwessels/torcs-client | my_driver.py | from pytocl.driver import Driver
from pytocl.car import State, Command
class MyDriver(Driver):
def drive(self, carstate):
command = Command()
command.steering = carstate.angle / 180
if carstate.angle > 30 or carstate.angle < -30:
command.brake = 0.5
command.accelerator = 0
else:
command.brake = 0
... |
lankunyao/txt_to_json | main.py | <reponame>lankunyao/txt_to_json<filename>main.py
# -*- coding: utf-8 -*-
import argparse
import os
import json
from pathlib import Path
parser = argparse.ArgumentParser(description="命令行传入参数")
parser.add_argument('-t', '--txt', default="SciKG_min_1.0")
args = parser.parse_args()
txt = args.txt
root_dir = os... |
bactopia/bactopia-parser | bactopia/__init__.py | """Top-level package for Bactopia."""
__author__ = """<NAME> III"""
__email__ = '<EMAIL>'
__version__ = '0.1.1'
from .parse import parse, get_bactopia_files, parse_bactopia_files
|
bactopia/bactopia-parser | bactopia/parse.py | """
Bactopia's parser entry-point.
Example: bactopia.parse(result_type, filename)
"""
import errno
import os
from collections import OrderedDict
from typing import Union
from . import parsers
from .const import RESULT_TYPES, IGNORE_LIST
def parse(result_type: str, *files: str) -> Union[list, dict]:
"""
Use t... |
bactopia/bactopia-parser | bactopia/parsers/__init__.py | <reponame>bactopia/bactopia-parser<gh_stars>1-10
import os
import glob
modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [os.path.basename(f)[:-3] for f in modules if os.path.isfile(f) and not f.endswith('__init__.py')]
del modules
del glob
del os
from . import *
|
bactopia/bactopia-parser | tests/__init__.py | <reponame>bactopia/bactopia-parser<gh_stars>1-10
"""Unit test package for bactopia."""
|
bactopia/bactopia-parser | bactopia/parsers/qc.py | <reponame>bactopia/bactopia-parser
"""
Parsers for QC (FASTQ) related results.
"""
import os
from .generic import get_file_type, parse_json
RESULT_TYPE = 'quality-control'
ACCEPTED_FILES = ["final.json", "original.json"]
def parse(r1: str, r2: str = None) -> dict:
"""
Check input file is an accepted file, the... |
bactopia/bactopia-parser | tests/test_bactopia.py | #!/usr/bin/env python
"""Tests for `bactopia` package."""
import unittest
from bactopia import bactopia
class TestBactopia_parser(unittest.TestCase):
"""Tests for `bactopia` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixture... |
bactopia/bactopia-parser | bactopia/const.py | <reponame>bactopia/bactopia-parser
"""
Constant values used throughout the Bactopia package.
"""
RESULT_TYPES = [
"amr",
"annotation",
"ariba",
"assembly",
"blast",
"error",
"generic",
"kmers",
"mapping",
"minmers",
"mlst",
"qc",
"variants"
]
IGNORE_LIST = ['.nextfl... |
vivatoviva/shell | first.py | import math
def quadratic(a, b, c):
# 首先计算代尔塔
temp = b**2 - 4*a*c
if temp < 0:
return 0,0
# 两个解为
x1 = (-b + math.sqrt(temp)) / 2*a
x2 = (-b - math.sqrt(temp)) / 2*a
return x1,x2
pass
# 测试:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadra... |
Lornatang/TensorFlow-AE | main.py | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
#
# Licensed under the MIT License.
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://opensource.org/licenses/MIT
# ===========================================================... |
Lornatang/TensorFlow-AE | util/loss_and_optim.py | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
#
# Licensed under the MIT License.
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://opensource.org/licenses/MIT
# ==========================================================... |
Lornatang/TensorFlow-AE | util/save_checkpoints.py | # Copyright 2019 ChangyuLiu Authors. All Rights Reserved.
#
# Licensed under the MIT License.
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://opensource.org/licenses/MIT
# ==========================================================... |
danya02/booru-mirror-unified | danbooru_dump/danbooru_dump_bulkdata_download_missing.py | <filename>danbooru_dump/danbooru_dump_bulkdata_download_missing.py
import subprocess
import os
import sys
sys.path.append('..')
from database import *
import time
import random
import danbooru_dump_transfer_queue_into_redis_from_find
os.chdir('/hugedata/booru/danbooru_temp')
def download_content(id):
print ... |
danya02/booru-mirror-unified | danbooru_dump/danbooru_dump_redis_load_json.py | <filename>danbooru_dump/danbooru_dump_redis_load_json.py
import os
import json
import redis
import time
info = redis.Redis(db=12)
time_start = time.time()
count = 0
os.chdir('/hugedata/booru_old/danbooru2020/danbooru2020/metadata/split')
for i in sorted(os.listdir('.')):
while info.dbsize() > 100000:
pri... |
danya02/booru-mirror-unified | queue_work.py | <reponame>danya02/booru-mirror-unified
from database import *
import functools
import traceback
ENTITY_IMPORT_METHODS = dict()
def to_import_entity(imageboard, ent_type):
def wrapper(func):
@functools.wraps(func)
def wrapped(queued_ent):
queued_ent.row_locked = True
queued_... |
danya02/booru-mirror-unified | danbooru_dump/danbooru_dump_import.py | import sys
sys.path.append('..')
from booru_db import BooruDatabase
from database import *
import datetime
import json
import traceback
import random
import time
import logging
import redis
import collections
r = redis.Redis(db=12)
bdb = BooruDatabase('danbooru')
def parse_date(val):
try:
v = datetime.da... |
danya02/booru-mirror-unified | danbooru_dump/danbooru_dump_bulkdata_transfer.py | <filename>danbooru_dump/danbooru_dump_bulkdata_transfer.py
import sys
sys.path.append('..')
from database import *
import traceback
import os
import shutil
#import threading
import queue
import time
import magic
import redis
import functools
import concurrent.futures
r = redis.Redis()
rc = redis.Redis(db=2)
#rhashes_m... |
danya02/booru-mirror-unified | danbooru_dump/danbooru_dump_transfer_queue_into_redis_from_find.py | <filename>danbooru_dump/danbooru_dump_transfer_queue_into_redis_from_find.py<gh_stars>0
import sys
sys.path.append('..')
from database import *
import sys
import os
import redis
import time
r = redis.Redis()
def find_transfer():
os.system('find /hugedata/booru/danbooru_temp -type f -empty -print -delete')
f = ... |
danya02/booru-mirror-unified | mv_hash_tree_files.py | from database import *
import os
import shutil
import time
import humanize
import datetime
import redis
import tqdm
import traceback
queue = redis.Redis(db=5)
os.chdir('/hugedata/booru_old/unified/files') # copy from
cwd = os.getcwd()
TARGET = '/hugedata/booru/' # copy to
if input('input Q to enqueue paths, anythi... |
danya02/booru-mirror-unified | booru_db.py | <reponame>danya02/booru-mirror-unified
from database import *
import functools
class BooruDatabase:
def __init__(self, booru):
if not isinstance(booru, Imageboard):
if isinstance(booru, str):
booru = Imageboard.get(Imageboard.name == booru)
else:
boor... |
danya02/booru-mirror-unified | create_thumbnails.py | <reponame>danya02/booru-mirror-unified<filename>create_thumbnails.py
from database import *
import subprocess
import os
import datetime
import random
mimetype_jpg = MimeType.get(MimeType.ext == 'jpg')
mimetype_png = MimeType.get(MimeType.ext == 'png')
mts = [mimetype_jpg, mimetype_png]
mtids = [mt.id for mt in mts]
d... |
danya02/booru-mirror-unified | database.py | <reponame>danya02/booru-mirror-unified<filename>database.py
from peewee import *
import peewee
import datetime
from PIL import Image
import hashlib
import io
import os
import random
import hashlib
IMAGE_DIR = '/hugedata/booru/'
DIR_TREE_DEPTH = 2
DIR_TREE_SEGMENT_LEN = 2
#db = SqliteDatabase('test.db', timeout=600)
db... |
danya02/booru-mirror-unified | transfer_rule34.py | import database
from peewee import *
import datetime
import functools
import magic
import hashlib
import os
import shutil
BOARD, _ = database.Imageboard.get_or_create(name='rule34', base_url='https://rule34.xxx')
olddb = MySQLDatabase('rule34_bk', user='booru', password='<PASSWORD>')
class OldModel(Model):
delet... |
danya02/booru-mirror-unified | count_post_tags.py | from database import *
#boards = list(Imageboard.select())
#last_tag_id = TagPostCount.select(fn.MAX(TagPostCount.tag_id)).scalar() or 1
for tag in Tag.select().join(TagPostCount, JOIN.LEFT_OUTER).where(TagPostCount.tag.is_null(True)).orwhere(TagPostCount.changed_at < (datetime.datetime.now() - datetime.timedelta(da... |
shreyashsrivastava/wagtail | wagtail/admin/tests/test_reports_views.py | import datetime
from io import BytesIO
from django.conf import settings
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from openpyxl import load_workbook
from wagtail.core.models import Page, PageLogEntry
from wagtail.tests.utils import WagtailTestUtils
class Tes... |
shreyashsrivastava/wagtail | wagtail/admin/tests/pages/test_copy_page.py | from django.contrib.auth.models import Group, Permission
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from django.urls import reverse
from wagtail.core.models import GroupPagePermission, Page
from wagtail.tests.testapp.models import SimplePage
from wagtail.tests.utils import Wagta... |
shreyashsrivastava/wagtail | wagtail/admin/urls/reports.py | <reponame>shreyashsrivastava/wagtail<filename>wagtail/admin/urls/reports.py<gh_stars>1000+
from django.urls import path
from wagtail.admin.views.reports.audit_logging import LogEntriesView
from wagtail.admin.views.reports.locked_pages import LockedPagesView
from wagtail.admin.views.reports.workflows import WorkflowTas... |
shreyashsrivastava/wagtail | wagtail/admin/views/reports/base.py | from django.utils.translation import gettext_lazy as _
from django.views.generic.base import TemplateResponseMixin
from django.views.generic.list import BaseListView
from wagtail.admin.views.mixins import SpreadsheetExportMixin
class ReportView(SpreadsheetExportMixin, TemplateResponseMixin, BaseListView):
header... |
shreyashsrivastava/wagtail | wagtail/admin/tests/pages/test_workflow_history.py | from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from wagtail.core.models import Page, PageLogEntry
from wagtail.tests.utils import WagtailTestUtils
class TestWorkflowHistoryDetail(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def set... |
shreyashsrivastava/wagtail | wagtail/admin/views/reports/__init__.py | from .base import PageReportView, ReportView # noqa
|
shreyashsrivastava/wagtail | wagtail/admin/tests/test_buttons_hooks.py | <filename>wagtail/admin/tests/test_buttons_hooks.py
from django.test import TestCase
from django.urls import reverse
from django.utils.http import urlencode
from wagtail.admin import widgets as wagtailadmin_widgets
from wagtail.admin.wagtail_hooks import page_listing_more_buttons
from wagtail.core import hooks
from wa... |
shreyashsrivastava/wagtail | wagtail/admin/tests/test_templatetags.py | from datetime import timedelta
from unittest import mock
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from freezegun import freeze_time
from wagtail.admin.staticfiles import versioned_static
from wagtail.admin.templ... |
shreyashsrivastava/wagtail | wagtail/admin/filters.py | import django_filters
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_filters.widgets import SuffixedMultiWidget
from wagtail.admin.widgets import AdminDateInput, BooleanButtonSelect, ButtonSelect, FilteredSelect
class DateRangePickerWidget(SuffixedMultiWidget):
"... |
DapperDino/Learning-TensorFlow | BreastCancerDataSVM/breast_cancer_data_svm.py | <filename>BreastCancerDataSVM/breast_cancer_data_svm.py
import sklearn as sk
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Load cancer data from dataset.
cancer = load_breast_cancer()
# Define which data will be on the x and y axis.
x = cancer... |
DapperDino/Learning-TensorFlow | CarDataKNN/car_data_knn.py | <filename>CarDataKNN/car_data_knn.py
import pandas as pd
import sklearn as sk
from sklearn import preprocessing
from sklearn.neighbors import KNeighborsClassifier
# Load car data from file.
data = pd.read_csv("CarDataKNN/Car.data")
# Convert attribute names to int.
le = preprocessing.LabelEncoder()
buying = le.fit_tr... |
DapperDino/Learning-TensorFlow | StudentDataRegression/student_data_regression.py | import pickle
import pandas as pd
import numpy as np
import sklearn as sk
from sklearn import linear_model
import matplotlib.pyplot as pyplot
from matplotlib import style
# Load student data from file.
data = pd.read_csv("StudentDataRegression/StudentData.csv", sep=";")
# Filter only the data we wish to model.
data =... |
OrlandoCano/JavaDevDay2019 | data/sessionize_data/transform_data.py | import requests
import json
import re
API_URL = "https://sessionize.com/api/v2/ezuter2b/view/all"
res = requests.get(API_URL)
json_data = json.loads(res.text)
speakers = {}
def clean_name(name):
regex = re.compile('[^a-zA-Z]')
res = regex.sub('', name)
return res.lower()
# Speakers
for i, s in enumerate(j... |
TeamMacLean/cgr_view | cgr/__init__.py | """
cgr
A module for creating, saving and drawing k-mer matrices and Chaos Game Representations (CGRs) of nucleotide sequences
Prerequisites
-------------
- Jellyfish
An external program for counting k-mers. Must be accessible on the path. You can install from conda as follows:
.. highlight:: bash
.. code-... |
TeamMacLean/cgr_view | test_cgr.py | <reponame>TeamMacLean/cgr_view
import unittest
import cgr
import os
from scipy.sparse import dok_matrix
import numpy
class CGRTest(unittest.TestCase):
def test_guess_genome_size(self):
self.assertEqual(cgr.estimate_genome_size("test_data/10kfile"),10240)
def test_run_jellyfish(self):
... |
TeamMacLean/cgr_view | setup.py | <gh_stars>0
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='cgr_view',
version='0.0.1dev2',
url='https://github.com/TeamMacLean/cgr_view',
packages=setuptools.find_packages(),
long_description_content_type="text/markdown",
license=... |
cazalaa/connectedhomeip | src/controller/python/chip-repl.py | <reponame>cazalaa/connectedhomeip
#!/usr/bin/env python
#
# Copyright (c) 2021 Project CHIP Authors
# 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
#
# ... |
cazalaa/connectedhomeip | src/controller/python/chip/ble/__init__.py | <filename>src/controller/python/chip/ble/__init__.py
# 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 app... |
xyb/python-xxhash | tests/test_xxh3_64.py | <filename>tests/test_xxh3_64.py
from __future__ import print_function
import os
import sys
import unittest
import random
import xxhash
class TestXXH(unittest.TestCase):
def test_xxh3_64(self):
self.assertEqual(xxhash.xxh3_64('a').intdigest(), 16629034431890738719)
self.assertEqual(xxhash.xxh3_64('... |
xyb/python-xxhash | tests/test_xxh3_128.py | import os
import unittest
import random
import xxhash
class TestXXH(unittest.TestCase):
def test_xxh3_128(self):
self.assertEqual(xxhash.xxh3_128('a').intdigest(), 225219434562328483135862406050043285023)
self.assertEqual(xxhash.xxh3_128('a', 0).intdigest(), 225219434562328483135862406050043285023... |
taipahuchu/language-Identification- | code/batcher.py | """This file holds the Dataset class, which helps with the loading
and organizing of the training data."""
import argparse
import collections
import gzip
import itertools
import numpy as np
import re
import sys
np.random.seed(666)
def LoadData(filename, mode='train', model='tweet'):
"""Load data stored in tweetli... |
taipahuchu/language-Identification- | code/models.py | <reponame>taipahuchu/language-Identification-
import tensorflow as tf
import numpy as np
class BaseModel(object):
"""Holds code shared between all the different model variants."""
def __init__(self, batch_size, max_sequence_len, out_vocab_size, c2v,
dropout_keep_prob=0.0):
self._batch_size = b... |
taipahuchu/language-Identification- | code/char2vec.py | """Models to create word embeddings from character sequences.
Use BasicEmbedding for traditional word embeddings or use the CharLSTM or
CharCNN implementations of char2vec.
"""
import numpy as np
import tensorflow as tf
import util
initializer = tf.random_uniform_initializer(-0.1, 0.1)
class BasicEmbedding(object):... |
taipahuchu/language-Identification- | code/util.py | # Misc. helper functions go in this file.
import collections
import numpy as np
import os
import random
import sys
# Need to use these three lines to import pyplot with a good font
import matplotlib
matplotlib.rc('font', family='DejaVu Sans')
from matplotlib import pyplot
def Metrics(preds, labs, show=True):
"""Pr... |
taipahuchu/language-Identification- | code/vocab.py | <reponame>taipahuchu/language-Identification-
import argparse
import collections
import numpy as np
import pickle
import re
class Vocab(object):
def _normalize(self, word):
if re.match(ur'^<.*>$', word):
return word
if self.specialcase:
newword = []
prev_is_lower = True
for letter ... |
taipahuchu/language-Identification- | code/getembeddings.py | """
Utility for printing nearest neighbors to a given word in embedding space.
Uses the char2vec portion of a trained model and the tweetlid vocabulary.
Nearest neighbors are given based on cosine similarity.
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import argparse
import json
import numpy as np
impo... |
taipahuchu/language-Identification- | code/langid.py | import sys
reload(sys) # need to reload to set default encoding
sys.setdefaultencoding('utf8')
import argparse
import collections
import json
import logging
import numpy as np
import os
import shutil
import tensorflow as tf
import util
from char2vec import CharCNN as Char2Vec
from batcher import Dataset
from vocab i... |
nickromano/django-daily-digest | leather/ticks/score.py | <gh_stars>1-10
#!/usr/bin/env python
from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR
import math
import sys
from leather.ticks.base import Ticker
from leather.utils import isclose
# Shorthand
ZERO = Decimal("0")
TEN = Decimal("10")
#: Normalized intervals to be tested for ticks
INTERVALS = [
Decimal("0.... |
nickromano/django-daily-digest | daily_digest/tests.py | import random
from datetime import date, datetime, timedelta
import mock
import pytz
from django.contrib.auth.models import User
from django.core.management import call_command
from django.test import TestCase
from django.test.client import Client
from project.photos.models import PhotoUpload
from .config import Dail... |
nickromano/django-daily-digest | leather/svg.py | <reponame>nickromano/django-daily-digest
#!/usr/bin/env python
"""
Helpers for working with SVG.
"""
import xml.etree.ElementTree as ET
import six
HEADER = (
'<?xml version="1.0" standalone="no"?>\n'
+ '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"\n'
+ '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dt... |
nickromano/django-daily-digest | daily_digest/apps.py | <reponame>nickromano/django-daily-digest
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class DailyDigestConfig(AppConfig):
name = "daily_digest"
|
nickromano/django-daily-digest | leather/ticks/score_time.py | <reponame>nickromano/django-daily-digest<filename>leather/ticks/score_time.py<gh_stars>1-10
#!/usr/bin/env python
from datetime import date, datetime, timedelta
from decimal import Decimal
from functools import partial
import math
import sys
from leather.ticks.score import ScoreTicker
from leather import utils
#: T... |
nickromano/django-daily-digest | daily_digest/urls.py | <reponame>nickromano/django-daily-digest
from django.conf.urls import url
from .views import preview_daily_digest
urlpatterns = [
url(
r"admin/daily-digest-preview/$",
preview_daily_digest,
name="preview-daily-digest",
),
]
|
nickromano/django-daily-digest | project/photos/models.py | from django.contrib.auth.models import User
from django.db import models
class PhotoUpload(models.Model):
user = models.ForeignKey(
User, related_name="photo_uploads", on_delete=models.CASCADE
)
created = models.DateTimeField(auto_now_add=True)
|
nickromano/django-daily-digest | leather/scales/ordinal.py | <reponame>nickromano/django-daily-digest<filename>leather/scales/ordinal.py<gh_stars>1-10
#!/usr/bin/env python
from decimal import Decimal
from leather.scales.base import Scale
class Ordinal(Scale):
"""
A scale that maps individual values (e.g. strings) to a range.
"""
def __init__(self, domain):
... |
nickromano/django-daily-digest | daily_digest/config.py | from collections import namedtuple
import importlib
import pytz
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.text import slugify
class DailyDigestConfigurationException(Exception):
pass
class DailyDigestRequiredFieldException(DailyDigestConfigura... |
nickromano/django-daily-digest | daily_digest/utils.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import leather
import pytz
from cairosvg import svg2png
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from email.mime.image import MIMEImage
from premailer import transform
from .config import daily_... |
nickromano/django-daily-digest | testrunner.py | <reponame>nickromano/django-daily-digest<filename>testrunner.py
import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
def runtests():
... |
nickromano/django-daily-digest | project/settings.py | import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
UNIT_TESTING = "test" in sys.argv
DEBUG = True
ALLOWED_HOSTS = []
SECRET_KEY = "test"
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ... |
nickromano/django-daily-digest | daily_digest/__init__.py | <reponame>nickromano/django-daily-digest<filename>daily_digest/__init__.py
__version__ = "0.0.3"
default_app_config = "daily_digest.apps.DailyDigestConfig" # noqa
|
nickromano/django-daily-digest | leather/scales/linear.py | #!/usr/bin/env python
from decimal import Decimal
from leather.scales.base import Scale
from leather.ticks.score import ScoreTicker
class Linear(Scale):
"""
A scale that linearly maps values from a domain to a range.
:param domain_min:
The minimum value of the input domain.
:param domain_ma... |
nickromano/django-daily-digest | leather/chart.py | #!/usr/bin/env python
from copy import copy
import os
import xml.etree.ElementTree as ET
import six
from leather.axis import Axis
from leather.data_types import Date, DateTime
from leather.scales import Scale, Linear, Temporal
from leather.series import Series, CategorySeries
from leather.shapes import Bars, Columns... |
nickromano/django-daily-digest | leather/axis.py | #!/usr/bin/env python
import xml.etree.ElementTree as ET
import six
from leather import svg
from leather import theme
class Axis(object):
"""
A horizontal or vertical chart axis.
:param ticks:
Instead of inferring tick values from the data, use exactly this
sequence of ticks values. Th... |
nickromano/django-daily-digest | daily_digest/management/commands/send_daily_digest.py | from django.core.management.base import BaseCommand
from daily_digest.utils import send_daily_digest
class Command(BaseCommand):
help = "Send daily digest email."
def success_message(self, message):
if hasattr(self.style, "SUCCESS"):
self.stdout.write(self.style.SUCCESS(message))
... |
nickromano/django-daily-digest | leather/data_types.py | #!/usr/bin/env python
from datetime import date, datetime
from decimal import Decimal
import six
class DataType(object):
"""
Base class for :class:`.Series` data types.
"""
@classmethod
def infer(cls, v):
for t in [DateTime, Date, Number, Text]:
if isinstance(v, t.types):
... |
nickromano/django-daily-digest | daily_digest/views.py | # -*- coding: utf-8 -*-
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render
from .config import daily_digest_config
from .utils import charts_data_for_config
@staff_member_required
def preview_daily_digest(request):
context = {"title": daily_digest_config.t... |
nickromano/django-daily-digest | leather/ticks/base.py | <reponame>nickromano/django-daily-digest<gh_stars>1-10
#!/usr/bin/env python
class Ticker(object):
"""
Base class for ticker implementations.
"""
@property
def ticks(self):
raise NotImplementedError
@property
def min(self):
raise NotImplementedError
@property
def... |
nickromano/django-daily-digest | leather/lattice.py | <gh_stars>1-10
#!/usr/bin/env python
from leather.axis import Axis
from leather.chart import Chart
from leather.data_types import Date, DateTime
from leather.grid import Grid
from leather.scales import Scale, Linear
from leather.series import Series
from leather.shapes import Line
from leather import theme
from leathe... |
Nixon-Aguado/Feature-Extraction-and-Image-Processing-Book-Examples | ExamplesPython_3.6/Chapter9/CamShift.py | <filename>ExamplesPython_3.6/Chapter9/CamShift.py
'''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
Chapter 9
CamShift: Tracks a region by implementing the CamShift technique. Similar to the MEanShift, but
it uses backprojection to update the region position... |
Nixon-Aguado/Feature-Extraction-and-Image-Processing-Book-Examples | ExamplesPython_3.6/Chapter10/Reprojection.py | '''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
Chapter 10
Reprojection: Compute a projection from seven corresponding image and 3D points and re-project
the image to create a new view of the scene
'''
# Set module functions
from ImageUtilitie... |
Nixon-Aguado/Feature-Extraction-and-Image-Processing-Book-Examples | ExamplesPython_3.6/Chapter5/InvariantGeneralizedHoughTransform.py | '''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
Chapter 5
InvariantGeneralizedHoughTransform: Shape detection by the invariant generalized Hough transform
'''
# Set module functions
from ImageUtilities import imageReadL, showImageF, showImageL, createImageF
from Im... |
Nixon-Aguado/Feature-Extraction-and-Image-Processing-Book-Examples | ExamplesPython_3.6/Chapter4/HarrisOperator.py | '''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
Chapter 4
HarrisOperator: Compute corners by using the Harris operator or minimal direction
'''
# Set module functions
from ImageUtilities import imageReadL, createImageF, showImageF, showImageL
from ImageOperatorsUtil... |
Nixon-Aguado/Feature-Extraction-and-Image-Processing-Book-Examples | ExamplesPython_3.6/Chapter3/Dilation.py | <gh_stars>10-100
'''
Feature Extraction and Image Processing
<NAME> & <NAME>
http://www.southampton.ac.uk/~msn/book/
Chapter 3
Dilation: Dilation morphological filter
'''
# Set module functions
from ImageUtilities import imageReadL, showImageL, createImageL
# Iteration
from timeit import itertools
'''
Parameters:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.