repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
fortyninemaps/picoraster | src/pipeline.py | class Pipeline(object):
def __init__(self, steps=None):
self._instructions = steps if steps else []
@property
def instructions(self):
return [instr for instr in self._instructions]
def and_then(self, instruction):
return Pipeline(self.instructions + [instruction])
def app... |
fortyninemaps/picoraster | src/__init__.py | <filename>src/__init__.py
name = "picoraster"
from .band import Band
from .instruction import *
from .geotransform import GeoTransform
from .part import Part
from .pipeline import Pipeline
from .source import * |
fortyninemaps/picoraster | src/source.py | from os import path
import numpy
from osgeo import gdal
from .geotransform import GeoTransform
from .part import Part
from .types import GDT_TO_NUMPY
class Source(object):
def part(self, j, i, nx, ny):
""" Read (nx, ny) pixels, starting from x0, y0 in the top left """
raise NotImplementedError
... |
fortyninemaps/picoraster | src/tests/__init__.py | <filename>src/tests/__init__.py
from .geotransform_tests import * |
fortyninemaps/picoraster | src/part.py | <reponame>fortyninemaps/picoraster
from osgeo import gdal
class Part(object):
def __init__(self, geotransform, projection, data):
self.geotransform = geotransform
self.projection = projection
self._data = data
@property
def data(self):
return self._data
@property
... |
fortyninemaps/picoraster | src/instruction.py | import os
import numpy
from osgeo import gdal
from .part import Part
from .geotransform import GeoTransform
class Instruction(object):
""" An instruction represents a pure function from a Part to a list of
new Parts. """
def __init__(self):
pass
def apply(self, part):
""" Apply inst... |
BaichuanTang/Container | ui_and_pys/Ui_select_item.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'e:\Object Detection\YOLOX\ui_and_pys\select_item.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you ar... |
BaichuanTang/Container | code_entry.py | # -*- coding: utf-8 -*-
import datetime
import json
import cv2
import os
import sys
sys.path.append("../..")
sys.path.append("..")
import pymysql
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
#导入前台页面
from ui_and_pys.Ui_Main import Ui_MainWindow
from ui_and_pys.Ui_open_succ import ... |
BaichuanTang/Container | yolox/utils/visualize.py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import cv2
import numpy as np
import random
import os
import time
import tensorflow as tf
from tensorflow import keras
from loguru import logger
import matplotlib.pyplot as plt
__all__ = ["vis"]
dct_name = {
0:... |
BaichuanTang/Container | ui_and_pys/Ui_select_item_results.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'e:\Object Detection\YOLOX\ui_and_pys\select_item_results.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know wha... |
asleep-cult/asygpy | asygpy/notifier.py | <gh_stars>0
from __future__ import annotations
import asyncio
import errno
import os
import signal
import socket
import sys
import types
import typing
from .channel import SignalChannel
__all__ = ('SignalNotifier', 'create_notifier')
WIN32 = sys.platform == 'win32'
if WIN32:
WSAENOTSOCK: int = getattr(errno, 'W... |
asleep-cult/asygpy | test.py | import asyncio
import signal
import asygpy
async def main() -> None:
print("hello")
notifier = asygpy.create_notifier()
channel = (
notifier.open_channel()
.add_signal(signal.SIGINT)
.add_signal(signal.SIGTERM)
)
notifier.start_notifying()
signum = await channel.rece... |
asleep-cult/asygpy | asygpy/__init__.py | <gh_stars>0
from .channel import *
from .notifier import *
|
asleep-cult/asygpy | asygpy/channel.py | <reponame>asleep-cult/asygpy<gh_stars>0
from __future__ import annotations
import asyncio
import signal
import typing
if typing.TYPE_CHECKING:
from typing_extensions import Self
__all__ = ('SignalChannel',)
class SignalChannel:
__slots__ = ('_signals', '_queue')
def __init__(self) -> None:
sel... |
steventhan/raspberry-pi | src/test_lock.py | <filename>src/test_lock.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import json
from lock import RPiLock
from user import User
from requests import Response
try:
from unittest.mock import patch, MagicMock, mock_open
except ImportError:
from mock import patch, MagicMock, mock_... |
steventhan/raspberry-pi | src/lock.py | # coding: utf-8
import requests
from rfid import get_RFID
try:
input = raw_input
except:
pass
class RPiLock(object):
"""RPiLock class, a representation of the physical lock."""
def __init__(self, user, server, port=80, model='motorized'):
"""RPiLock instance with socketio connection."""
... |
steventhan/raspberry-pi | src/socketio_client.py | # coding: utf-8
from socketIO_client import SocketIO
import pigpio
io_client = SocketIO('192.168.1.109', 5000)
AVAIL_ACTIONS = {
'unlock': 600,
'lock': 2400,
}
def lock_control(action, pin_num=18):
"""Output approriate control signal and pulswidth to the locl."""
pi = pigpio.pi()
pulsewidth = AV... |
steventhan/raspberry-pi | src/test_user_authentication.py | <reponame>steventhan/raspberry-pi
"""Test module for webcam_face_detector."""
from user_authentication import SERVER, PORT, send_img_to_server
def test_send_img_to_server():
"""Assert that an image can be sent to the server for verification."""
t_rfid = 'testing-rfid'
response = send_img_to_server('testi... |
steventhan/raspberry-pi | src/rfid.py | """Module for the RFID scanner.
To learn more about MFRC522, visit: github.com/mxgxw/MFRC522-python
"""
import RPi.GPIO as GPIO
import MFRC522
import signal
import sys
def get_RFID():
"""Return the uid of rfid card."""
def end_read(signal, frame):
global continue_reading
continue_reading = F... |
steventhan/raspberry-pi | src/user_authentication.py | """
This module contains code related to verification on the Raspberry-Pi.
The begin_watch function initializes the RFID scanner and webcam, then begins
looking for a face after an RFID is scanned. Once a face is found, the
image is sent to the server to be validated. Some parts adapted from:
https://pythonprogrammin... |
steventhan/raspberry-pi | src/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from lock import RPiLock
from user import User
import sys
import logging
import getpass
logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
SERVER, PORT = '192.168.1.109', 8000 # Django server, port
FLASK_PORT = 5000
try:... |
steventhan/raspberry-pi | src/user.py | <reponame>steventhan/raspberry-pi<filename>src/user.py
# coding: utf-8
import requests
class User(object):
"""User class, a representation of the Django user."""
def __init__(self, username, password, server, port=80):
self.server = server
self.port = port
self.username = username
... |
steventhan/raspberry-pi | setup.py | # -*- coding: utf-8 -*-
"""Package for implementing a RPi lock client"""
from setuptools import setup
setup(
name="RPi lock client",
description="Package for Secured Pi locks",
version="0.1.0",
author="<NAME>, <NAME>, <NAME>, <NAME>",
author_email="",
license="MIT",
py_modules=["RPi-client"... |
scottfwilliams/unclutter | src/unclutter/remove-directories.py | import os
import sys
def remove_dirpaths(input_file):
fileset = set()
with open(input_file, "r") as img_file:
for line in img_file:
pathparts = line.split("/")
filename = pathparts[-1]
fileset.add(filename)
print("Found {} unique files".format(len(fileset)))
... |
scottfwilliams/unclutter | src/unclutter/comparer.py | import sys
def ingest_image_file(filename):
img_set = set()
with open(filename, "r") as img_file:
for line in img_file:
pathparts = line.split("/")
filename = pathparts[-1]
img_set.add(filename)
return img_set
def output_file_delta_list(input_filename, output_... |
scottfwilliams/unclutter | src/unclutter/find-extensions.py | <filename>src/unclutter/find-extensions.py
import os
import sys
def walk_fs(start_dir):
print("Finding list of unique file extensions under " + start_dir)
extension_set = set()
for root, dirs, files in os.walk(start_dir):
for filename in files:
if "." in filename:
filen... |
scottfwilliams/unclutter | src/unclutter/initialize-db.py | <reponame>scottfwilliams/unclutter
import sqlite3
def main():
initialize_database("file.db")
def initialize_database(db_file_name):
# Set up the sqlite DB instance
conn = sqlite3.connect(db_file_name)
c = conn.cursor()
# Create table for file output results
c.execute("""CREATE TABLE files (s... |
scottfwilliams/unclutter | src/unclutter/find-images.py | import os
import sys
def walk_fs(starting_dir):
# print("Picture finder")
# print("Starting directory is " + starting_dir)
extensions = {"jpg", "mp4", "gif", "mov", "JPEG", "jpeg", "MP4", "MOV", "JPG", "PNG"}
"""
extensions = {
"BMP",
"GIF",
"JPEG",
"JPG",
... |
scottfwilliams/unclutter | setup.py | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Setup file for unclutter.
Use setup.cfg to configure your project.
"""
from setuptools import setup, find_packages
setup(
entry_points={
'console_scripts': [
'init_unclutter_db = unclutter.initialize-db:initialize_database',
# 'init_... |
scottfwilliams/unclutter | src/unclutter/build-file-db.py | import os
import sys
import hashlib
import pathlib
import sqlite3
from pathlib import Path
BUF_SIZE = 65536 # read files in 64kb chunks to avoid consuming excess memory on large files
DB_FILENAME = "file.db"
def clean_filepath_str(relative_path_str):
return str(clean_filepath(relative_path_str))
def clean_fi... |
favorspin/onx | sql/queries.py | <filename>sql/queries.py<gh_stars>0
# owner data queries
owner_create_temp_table = """
DROP TABLE IF EXISTS onx_raw.temp_owners;
CREATE TABLE onx_raw.temp_owners (
created_date timestamp,
strap varchar,
folio varchar,
status_cd varc... |
favorspin/onx | loader.py | <gh_stars>0
import argparse, os, shapefile, pygeoif
from datetime import date
from config.config import connect_db
from sql import queries as q
parser = argparse.ArgumentParser(description='Load Boulder, CO daily parcel data and shapefiles.')
parser.add_argument('-l', '--latest',
dest='load_latest'... |
favorspin/onx | config/config.py | <reponame>favorspin/onx<filename>config/config.py
from configparser import ConfigParser
import psycopg2 as pg
def config(filename='config/database.ini', section='postgresql'):
parser = ConfigParser()
parser.read(filename)
db = {}
if parser.has_section(section):
params = parser.items(section)
... |
ortem/intellij-rust | prettyPrinters/lookup.py | import lldb
import re
from providers import *
class RustType:
OTHER = 0
STD_VEC = 1
STD_STRING = 2
STD_STR = 3
STD_VEC_REGEX = re.compile(r"^(alloc::([a-zA-Z]+::)+)Vec<.+>$")
STD_STRING_REGEX = re.compile(r"^(alloc::([a-zA-Z]+::)+)String$")
STD_STR_REGEX = re.compile(r"^&str$")
def classify_rust_... |
ortem/intellij-rust | prettyPrinters/providers.py | from lldb import SBValue, SBType, SBError
from lldb.formatters import Logger
#################################################################################################################
# This file contains two kinds of pretty-printers: summary and synthetic.
#
# Important classes from LLDB module:
# SBValue: ... |
siuryan/black | tests/data/remove_except_parens.py | # These brackets are redundant, therefore remove.
try:
a.something
except (AttributeError) as err:
raise err
# This is tuple of exceptions.
# Although this could be replaced with just the exception,
# we do not remove brackets to preserve AST.
try:
a.something
except (AttributeError,) as err:
raise err... |
siuryan/black | tests/data/one_element_subscript.py | # We should not treat the trailing comma
# in a single-element subscript.
a: tuple[int,]
b = tuple[int,]
# The magic comma still applies to multi-element subscripts.
c: tuple[int, int,]
d = tuple[int, int,]
# Magic commas still work as expected for non-subscripts.
small_list = [1,]
list_of_types = [tuple[int,],]
# o... |
siuryan/black | tests/data/remove_with_brackets.py | with (open("bla.txt")):
pass
with (open("bla.txt")), (open("bla.txt")):
pass
with (open("bla.txt") as f):
pass
# Remove brackets within alias expression
with (open("bla.txt")) as f:
pass
# Remove brackets around one-line context managers
with (open("bla.txt") as f, (open("x"))):
pass
with ((ope... |
siuryan/black | tests/data/fmtskip7.py | a = "this is some code"
b = 5 #fmt:skip
c = 9 #fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip
# output
a = "this is some code"
b = 5 # fmt:skip
c = 9 # fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstring... |
siuryan/black | scripts/diff_shades_gha_helper.py | <gh_stars>1-10
"""Helper script for psf/black's diff-shades Github Actions integration.
diff-shades is a tool for analyzing what happens when you run Black on
OSS code capturing it for comparisons or other usage. It's used here to
help measure the impact of a change *before* landing it (in particular
posting a comment... |
checongcong/dst-exploratory-analysis | src/main.py | <reponame>checongcong/dst-exploratory-analysis
# Usage:
# python main.py --data="../data/IAGA-2000.txt"
from __future__ import absolute_import, division, print_function
import argparse
from dst import Dst
from parser_iaga import IAGAParser
def argparser():
"""Parses command line options and returns an args ob... |
checongcong/dst-exploratory-analysis | src/dst.py | # Data structure wrapping Dst.
class Dst:
def __init__(self):
self._data = dict() # maps timestamp to value
def add_item(self, timestamp, val):
self._data[timestamp] = val
def head(self, n):
cnt = 0
for ts, val in self._data.items():
print('Timestamp = {},... |
checongcong/dst-exploratory-analysis | src/parser_iaga.py | <gh_stars>0
# IAGAParser parses the IAGA2002 format into DST data.
# IAGA2002 format: http://wdc.kugi.kyoto-u.ac.jp/mdplt/format/iaga2002.html
import sys
import time
from datetime import datetime
from dst import Dst
class IAGAParser:
def __init__(self):
pass
def parse_file(self, filename):
d... |
almeida-matheus/mawts | resources/__init__.py | from resources.aws import Aws
from resources.database import Database
from resources.osystem import OSystem
from resources.utils import Color
from resources.utils import Help |
almeida-matheus/mawts | resources/aws.py | <gh_stars>0
import boto3
from botocore.exceptions import ClientError
class Aws:
def __init__(self,access_key,secret_key):
if access_key: self.access_key = access_key
if secret_key: self.secret_key = secret_key
def get_caller_identity(self) -> str:
try:
session = boto3.... |
almeida-matheus/mawts | resources/database.py | <gh_stars>0
import sqlite3
import bcrypt
class Database:
def __init__(self,db_credentials) -> str:
'''constructor to create cursor to connect to db and create a table with credentials if not exist'''
try:
self.con = sqlite3.connect(db_credentials)
self.cursor = self.con.cur... |
almeida-matheus/mawts | resources/utils.py | class Color:
white = '\033[1;97m'
red = '\033[0;91m'
green = '\033[38;5;77m'
yellow = '\033[38;5;227'
purple = '\033[38;5;147m'
blue = '\033[38;5;81m'
end = '\033[0m'
class Help:
def show(self):
print('')
print(' '+'—' * 68 + ' ')
print('│ CLI to easily manag... |
almeida-matheus/mawts | main.py | # -*- coding: utf-8 -*-
#!/usr/bin/env python3
import os
import argparse
import sys
import stdiomask
import getpass
import resources
__version__ = '0.0.1'
__description__ = """\
Command line tool to manage aws credentials and automate tasks
"""
DB_CREDENTIALS = os.path.join(os.path.dirname(os.path.realpath(__file__))... |
almeida-matheus/mawts | resources/osystem.py | <filename>resources/osystem.py
import os
from random import choice
class OSystem:
def handle_dir(self,path='.aws'):
''' create a dir if not exit'''
try:
if not os.path.exists(path):
os.makedirs(path)
except:
raise OSError("Error: Can't create directo... |
benaryorg/worldofpython | src/Object.py | from Color import RGBA
class Object(object):
def __init__(self,mass=0,color=RGBA()):
self.setMass(mass)
self.setColor(color)
def __str__(self):
return ';'.join([str(self.mass)+'kg',str(self.color)])
def __repr__(self):
return str(self)
def setMass(self,mass):
... |
benaryorg/worldofpython | src/Furniture.py | <filename>src/Furniture.py
from Object import Object
class Furniture(Object):
def __init__(self,mass,material,color):
Object.__init__(self,mass=mass,color=color)
self.setMaterial(material)
def __str__(self):
return ';'.join([self.material,Object.__str__(self)])
def setMaterial(sel... |
benaryorg/worldofpython | src/Food.py | import Color
from Object import Object
class Food(Object):
def __init__(self,mass,hunger,color):
Object.__init__(self,mass=mass,color=color)
self.setHunger(hunger)
def __str__(self):
return ';'.join([str(self.hunger),Object.__str__(self)])
def setHunger(self,hunger):
if hu... |
benaryorg/worldofpython | src/Fruits.py | <filename>src/Fruits.py
from Food import Fruit
class Apple(Fruit):
pass
class Pear(Fruit):
pass
class Cherry(Fruit):
pass
class Grape(Fruit):
pass
class Banana(Fruit):
pass
class Orange(Fruit):
pass
|
benaryorg/worldofpython | src/Color.py | <filename>src/Color.py
def chartohex(c):
c=int(c)
s=hex(c)[2:]
if len(s)<2:
s='0'+s
return s
class RGB(object):
def __init__(self,red=0,green=0,blue=0):
self.setRed(red)
self.setGreen(green)
self.setBlue(blue)
def __str__(self):
return ''.join(['#',chart... |
noshluk2/Self_driving_car_engineer | src/turtlesim_robotics/setup.py | from setuptools import setup
package_name = 'turtlesim_robotics'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
... |
noshluk2/Self_driving_car_engineer | src/turtlesim_robotics/turtlesim_robotics/w3_b_propertional_controller_goToGoal.py | """
--> Go to Goal Node
This is is a publisher(Command Velocity) and a subscriber(Pose) both
- Takes in a goal specified in 2D
- Makes the robot calculate goal Heading
- Then Calculates Distance between the robot (through Pose) to Goal
- Send Command Velocities to reach the goal
- A tolerance is also set to make it e... |
noshluk2/Self_driving_car_engineer | src/turtlesim_robotics/turtlesim_robotics/w3_a_go_to_goal.py | """
--> Go to Goal Node
This is is a publisher(Command Velocity) and a subscriber(Pose) both
- Takes in a goal specified in 2D
- Makes the robot calculate goal Heading
- Then Calculates Distance between the robot (through Pose) to Goal
- Send Command Velocities to reach the goal
- A tolerance is also set to make it e... |
noshluk2/Self_driving_car_engineer | src/turtlesim_robotics/turtlesim_robotics/w4_kinematics_circular_rotation.py | """
--> Kinematic Modeling Implementation for differential Drive Robot
- This node contains kinematics Implementation
- Which is going to be driven through a velocity or acceleration controller
- Circular Trajectory is going to be followed
- Errors are going to be calculated using Derivates
10/11/21
Author :
M.Luqman... |
noshluk2/Self_driving_car_engineer | src/turtlesim_robotics/turtlesim_robotics/w2_driving_node.py | <gh_stars>1-10
"""
--> Drive the robot through a Node
This node is to drive the Turtlesim with
- linear velocity
- angular velocity
using 'Twist' Message type on topic '/turtle1/cmd_vel'
It is a publisher Only
10/11/21
Author
M.Luqman
"""
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist... |
isabellaleehs/Discover-Dish | DiscoverDish/form/views.py | <gh_stars>0
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponseNotFound
from django.urls import reverse
from django.shortcuts import get_object_or_404, render
from io import BytesIO
import base64
from form.forms import InputForm
from form.forms import RandInputForm
# files
fr... |
isabellaleehs/Discover-Dish | DiscoverDish/form/forms.py | <gh_stars>0
# sudo pip3 install --upgrade django-crispy-forms
import os
import csv
from django import forms
from django.core.validators import EMPTY_VALUES
from . import main
RES_DIR = os.path.join(os.path.dirname(__file__), 'csv')
RANGE_WIDGET = forms.widgets.MultiWidget(widgets=(forms.widgets.NumberInput,
... |
isabellaleehs/Discover-Dish | DiscoverDish/form/apis.py | # Functions using the googlemaps api to search for locations, and opentable.
import sys
import urllib
import json
from difflib import SequenceMatcher
import re
import geopy
from geopy.distance import vincenty
API_KEYS = json.load(open('form/api_keys.json'))
CUISINE_COORDINATES = json.load(open('form/cuisine_coordina... |
isabellaleehs/Discover-Dish | DiscoverDish/form/main.py | # Contains main computations to get top 3 recommendations, and randomizer computations.
#sudo pip3 install geoplotlib
#sudo pip3 install pyglet==1.2.4
#sudo pip3 install beautifulsoup4
import csv
import json
import geoplotlib
import bs4
import re
import random
import requests
import time
from . import yelp
from . im... |
isabellaleehs/Discover-Dish | DiscoverDish/form/yelp.py | # Contains all Yelp queries.
import argparse
import json
import requests
import sys
import urllib
import re
import bs4
import random
import time
from . import apis
'''
try:
# For Python 3.0 and later
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode... |
isabellaleehs/Discover-Dish | DiscoverDish/form/apps.py | <reponame>isabellaleehs/Discover-Dish
from django.apps import AppConfig
class FirstformConfig(AppConfig):
name = 'firstform'
|
isabellaleehs/Discover-Dish | DiscoverDish/form/cuisines.py | # Creates cuisine coordinates JSON file based on dictionary of all possible Yelp
# cuisines, by mapping each cuisine to a country.
from geopy.geocoders import Nominatim
from geopy.distance import vincenty
from . import apis
import json
def create_cuisine_coordinates_dict(cuisine_country_dict):
cuisine_coordina... |
isabellaleehs/Discover-Dish | DiscoverDish/form/urls.py | <reponame>isabellaleehs/Discover-Dish<gh_stars>0
from django.urls import path
from . import views
urlpatterns = [
path('', views.get_list, name='get_list'),
path('form/results.html', views.get_list, name='get_list_1'),
path('form/rand.html', views.rand, name='rand'),
path('form/rand_form.html', views.... |
RutvikJ77/Mouse-controller | src/head_pose_estimation.py | <reponame>RutvikJ77/Mouse-controller
import cv2
import numpy as np
import logging as log
from openvino.inference_engine import IECore
class Head_Pose_estimation:
'''
Class for the Head Pose Detection Model.
'''
def __init__(self, model_name, device='CPU', extensions=None):
self.exec_... |
RutvikJ77/Mouse-controller | src/main.py | <gh_stars>0
from face_detection import FaceDetection
from head_pose_estimation import Head_Pose_estimation
from facial_landmarks_detection import FacialLandmarkDetection
from gaze_estimation import GazeEstimation
from argparse import ArgumentParser
from input_feeder import InputFeeder
from mouse_controller import Mous... |
RutvikJ77/Mouse-controller | src/gaze_estimation.py | <filename>src/gaze_estimation.py
import cv2
import numpy as np
import logging as log
import math
from openvino.inference_engine import IECore
class GazeEstimation:
'''
Class for the Face Detection Model.
'''
def __init__(self, model_name, device='CPU', extensions=None):
self.exec_net... |
RutvikJ77/Mouse-controller | src/facial_landmarks_detection.py | <gh_stars>0
import cv2
import numpy as np
import logging as log
from openvino.inference_engine import IECore
class FacialLandmarkDetection:
'''
Class for the Facial Landmark Detection Model.
'''
def __init__(self, model_name, device='CPU', extensions=None):
self.exec_net = None
... |
k-lyda/doge-detector | src/data_preparer.py | import os
from xml.dom import minidom
import imageio
from tqdm import tqdm_notebook
from skimage.transform import resize
class DataPreparer():
def crop_images(self, images_path, image_size, output_folder='dataset/Cropped'):
total_folders = sum(1 for e in os.scandir(images_path) if e.is_dir())
for e... |
k-lyda/doge-detector | src/feature_extractor.py | <reponame>k-lyda/doge-detector
import os
from tqdm import tqdm_notebook
from keras.preprocessing import image
from pickle import dump, load
class FeatureExtractor():
def extract_feature(self, filename, model, app, image_size):
# load an image from file
img = image.load_img(filename, target_size... |
k-lyda/doge-detector | src/predictor.py | <reponame>k-lyda/doge-detector<filename>src/predictor.py
import numpy as np
import keras
import imageio
import matplotlib.pyplot as plt
from skimage.transform import resize
from src.utils import get_key_by_value
class Predictor():
def __init__(self, name, model, base_model, app, image_size, labels_coding):
... |
k-lyda/doge-detector | src/utils.py | <reponame>k-lyda/doge-detector<gh_stars>1-10
import pandas as pd
import matplotlib.pyplot as plt
def prob_plot(preds):
df = pd.DataFrame({
'breed': [breed[0] for pred in preds for breed in pred],
'prob': [breed[1] for pred in preds for breed in pred]
}).set_index('breed')
df.sort_values(['... |
k-lyda/doge-detector | src/yolo_detector.py | import cv2
import numpy as np
from src.YOLOv3.model.yolo_model import YOLO
import matplotlib.pyplot as plt
class YoloDetector():
def __init__(self, obj_threshold=0.6, nms_threshold=0.5, classes_file='src/YOLOv3/model/coco_classes.txt'):
self.yolo = YOLO(obj_threshold, nms_threshold, 'src/YOLOv3/data/yolo... |
ruromgar/git-merge-strategies | main.py | from typing import Any
from typing import Dict
from django.http.request import HttpRequest
from ninja import Query
from ninja import Router
from result import Ok
from .types import APISomething
from .types import APINegativeResponse
router = Router(tags=["somethings"])
@router.get(
"/{id}/",
response={200:... |
lsetiawan/py-github-actions-starter | main.py | import os
import time
import subprocess
import datetime
def main():
wait_time = os.environ.get("INPUT_SECONDS", 10)
print(f"Waiting {wait_time} seconds ...")
time.sleep(int(wait_time))
print("Done.")
now = datetime.datetime.now()
args = ["echo", "::set-output", f"name=time::{now.isoformat()}"... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/tests/testcases.py | from django.test import testcases
from graphql_jwt.testcases import JSONWebTokenClient
from gw_viterbi.schema import schema
from graphql_jwt.shortcuts import get_token
from graphql_jwt.settings import jwt_settings
class ViterbiJSONWebTokenClient(JSONWebTokenClient):
"""Viterbi test client with a custom authentica... |
gravitationalwavedc/gwlab-viterbi-cw | src/gw_viterbi/development-settings.py | <filename>src/gw_viterbi/development-settings.py
from .base import *
INSTALLED_APPS += ('corsheaders', )
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE.append('corsheaders.middleware.CorsMiddleware')
SITE_URL = "http://localhost:3000"
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
try:
from .local i... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/utils/db_search/db_search.py | <filename>src/viterbi/utils/db_search/db_search.py<gh_stars>0
import datetime
import json
import jwt
import requests
from django.conf import settings
def perform_db_search(user, kwargs):
"""
Perform a db job search based on parameters provided in kwargs
:param kwargs: The search parameters as passed fro... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/status.py | <reponame>gravitationalwavedc/gwlab-viterbi-cw
class JobStatus:
# A job that is currently in draft state - it is not yet submitted
DRAFT = 0
# A job is pending if it is currently waiting for a cluster to submit the job to
# (ie, all available clusters are offline)
PENDING = 10
# A job is submitt... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/utils/auth/filter_users.py | <reponame>gravitationalwavedc/gwlab-viterbi-cw<filename>src/viterbi/utils/auth/filter_users.py
import datetime
import json
import jwt
import requests
from django.conf import settings
def request_filter_users(search, user_id):
"""
Requests a filter of users based on search from the auth service
:param se... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/forms.py | from django import forms
from .validators import validate_float_string, validate_boolean_string
class ViterbiJobForm(forms.Form):
# Start
job_name = forms.CharField()
job_description = forms.CharField()
# Data
data_type = forms.CharField()
hanford = forms.BooleanField(required=False)
livin... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/tests/test_authenticated_queries.py | from django.contrib.auth import get_user_model
from graphql_relay.node.node import to_global_id
from viterbi.models import ViterbiJob
from viterbi.tests.testcases import ViterbiTestCase
from unittest import mock
User = get_user_model()
class TestQueriesWithAuthenticatedUser(ViterbiTestCase):
def setUp(self):
... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/validators.py | <filename>src/viterbi/validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_boolean_string(value):
if value not in ['false', 'False', 'true', 'True']:
raise ValidationError(_('%(value)s is not a boolean string'))
def validate_f... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/apps.py | from django.apps import AppConfig
class ViterbiConfig(AppConfig):
name = 'viterbi'
|
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/utils/jobs/request_job_filter.py | <filename>src/viterbi/utils/jobs/request_job_filter.py
import datetime
import json
import jwt
import requests
from django.conf import settings
def request_job_filter(user_id, ids=None, end_time_gt=None):
"""
Requests a filtered list of jobs from the job controller
:param ids: A list of job ids to fetch
... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/variables.py | from types import SimpleNamespace
viterbi_parameters = SimpleNamespace()
viterbi_parameters.FAKE_DATA = ["simulated", "Simulated"]
viterbi_parameters.REAL_DATA = ["real", "Real"]
viterbi_parameters.DATA_SOURCES = [
viterbi_parameters.FAKE_DATA,
viterbi_parameters.REAL_DATA
]
viterbi_parameters.O1 = ["o1", "... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/migrations/0004_auto_20210608_0414.py | # Generated by Django 2.2.16 on 2021-06-08 04:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('viterbi', '0003_auto_20210322_2003'),
]
operations = [
migrations.RenameField(
model_name='viterbijob',
old_name='job_id',
... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/migrations/0003_auto_20210322_2003.py | # Generated by Django 2.2.16 on 2021-03-22 20:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('viterbi', '0002_auto_20210322_2003'),
]
operations = [
migrations.AlterField(
model_name='viterbijob',
name='is_lig... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/tests/test_models.py | <gh_stars>0
from django.test import TestCase
from gw_viterbi.jwt_tools import GWCloudUser
from viterbi.models import ViterbiJob, Data, Label
from viterbi.variables import viterbi_parameters
from viterbi.views import update_viterbi_job
class TestViterbiJobModel(TestCase):
@classmethod
def setUpTestData(cls):
... |
gravitationalwavedc/gwlab-viterbi-cw | src/gw_viterbi/environment.py | <gh_stars>0
import os
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE')
MYSQL_HOST = os.getenv('MYSQL_HOST')
MYSQL_USER = os.getenv('MYSQL_USER')
MYSQL_ROOT_PASSWORD = os.getenv('MYSQL_ROOT_PASSWORD')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD')
SECRET_KEY = os.getenv('SECRET_KEY')
JOB_CONTROLLER_JWT_SECRET = os.getenv('J... |
gravitationalwavedc/gwlab-viterbi-cw | src/gw_viterbi/schema.py | import graphene
import viterbi.schema
class Query(viterbi.schema.Query, graphene.ObjectType):
pass
class Mutation(viterbi.schema.Mutation, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
|
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/migrations/0002_auto_20210322_2003.py | # Generated by Django 2.2.16 on 2021-03-22 20:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('viterbi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='viterbijob',
... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/types.py | from graphene import AbstractType, ObjectType, Int, String, Boolean
class OutputStartType(ObjectType):
name = String()
description = String()
private = Boolean()
class AbstractDataType(AbstractType):
start_frequency_band = String()
min_start_time = String()
max_start_time = String()
asin... |
gravitationalwavedc/gwlab-viterbi-cw | src/viterbi/models.py | from django.db import models
from viterbi.utils.jobs.request_file_download_id import request_file_download_id
from viterbi.utils.jobs.request_file_list import request_file_list
from viterbi.utils.jobs.request_job_status import request_job_status
from .variables import viterbi_parameters
class Label(models.Model):
... |
TianyuWu1990/ChatterBot | Keras_test.py | import json
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import... |
TianyuWu1990/ChatterBot | sarcasm_classifier.py | import json
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
vocab_size = 1000
embedding_dim = 16
max_length = 32
trunc_type = 'post'
padding_type = 'post'
oov_tok = "<OOV>"
training_size = 350
with ... |
TianyuWu1990/ChatterBot | AI_Text_Classification.py | <gh_stars>0
import tensorflow as tf
from tensorflow import keras
import numpy as np
# SSL issue fix
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
data = keras.datasets... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.