repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/NewsOrchestrator/app.py | <gh_stars>10-100
import os
from flask import Flask
from views import news
# instantiate the app
app = Flask(__name__)
# set config
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
# register blueprints
app.register_blueprint(news)
if __name__ == '__main__':
app.run(host='0.0.0.0', ... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/NewsOrchestrator/views.py | import os
import json
import itertools
from flask import Blueprint, jsonify, request
from nameko.standalone.rpc import ClusterRpcProxy
from nameko.standalone.events import event_dispatcher
news = Blueprint('news', __name__)
BROKER_CONFIG = {'AMQP_URI': os.environ.get('QUEUE_HOST')}
@news.route('/<string:news_type>... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/RecommendationService/tests.py | <reponame>PacktPublishing/Microservice-Patterns-and-Best-Practices
import os
import pytest
from .service import Command
from nameko.testing.services import worker_factory
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture
def session():
db_engine = create_engine(os.envi... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter06/NewsOrchestrator/tests.py | import os
import pytest
from .service import Command
from nameko.testing.services import worker_factory
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture
def session():
db_engine = create_engine(os.environ.get('COMMANDDB_TEST_HOST'))
Session = sessionmaker(db_engine)... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/PoliticsNewsService/dbmigrate.py | import os
from models import Base
from sqlalchemy import create_engine
def create_db():
db = create_engine(os.environ.get("COMMANDDB_HOST"))
db.execute('CREATE SEQUENCE IF NOT EXISTS news_id_seq START 1;')
Base.metadata.create_all(db)
if __name__ == '__main__':
print('creating databases')
create... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter06/PoliticsNewsService/app.py | import os
from flask import Flask
from views import politics_news
from models import db
app = Flask(__name__)
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
db.init_app(app)
app.register_blueprint(politics_news)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
|
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter06/SportsNewsService/config.py | class BaseConfig:
"""Base configuration"""
DEBUG = False
TESTING = False
MONGODB_SETTINGS = {}
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
DEBUG = True
MONGODB_SETTINGS = {
'db': 'sports_dev',
'host': '{}{}'.format(
os.environ.get('DATAB... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/RecommendationService/user_client.py | <reponame>PacktPublishing/Microservice-Patterns-and-Best-Practices<filename>Chapter11/RecommendationService/user_client.py<gh_stars>10-100
import logging
import os
import grpc
import user_data_pb2
import user_data_pb2_grpc
class UserClient:
def __init__(self, user_id):
self.user_id = int(user_id)
... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter13/NewsOrchestrator/tests.py | # -*- coding: utf-8 -*-
import json
import unittest
from mock import patch
from app import app
from views import error_response
from flask_testing import TestCase
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('config.TestingConfig')
return app
class TestDevelopme... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/FamousNewsService/service.py | import mongoengine
from models import (
CommandNewsModel,
Base,
QueryNewsModel,
)
from sqlalchemy import Sequence
from nameko.events import EventDispatcher
from nameko.rpc import rpc
from nameko.events import event_handler
from nameko_sqlalchemy import DatabaseSession
class Command:
name = 'command... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/NewsOrchestrator/tests_integration.py | # -*- coding: utf-8 -*-
import json
import unittest
from app import app
from flask_testing import TestCase
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('config.TestingConfig')
return app
class TestIntegration(BaseTestCase):
def setUp(self):
dict_obj ... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter05/SportsNewsService/views.py | import datetime
import mongoengine
from flask import Blueprint, jsonify, request
from models import News
sports_news = Blueprint('sports_news', __name__)
@sports_news.route('/sports/news/<string:news_id>', methods=['GET'])
def get_single_news(news_id):
"""Get single user details"""
response_object = {
... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/PoliticsNewsService/models.py | <filename>Chapter11/PoliticsNewsService/models.py
import os
from datetime import datetime
from mongoengine import (
connect,
Document,
DateTimeField,
ListField,
IntField,
StringField,
)
from sqlalchemy import (
Column,
String,
BigInteger,
DateTime,
Index,
)
from sqlalchemy.d... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/RecommendationService/user_data_pb2_grpc.py | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import user_data_pb2 as user__data__pb2
class GetUserDataStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/RecommendationService/user_data_pb2.py | <filename>Chapter11/RecommendationService/user_data_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: user_data.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter10/RecommendationService/service.py | import json
import logging
import os
import requests
from nameko.web.handlers import http
from nameko.events import event_handler
from models import (
create_user_node,
create_label_node,
create_recommendation,
get_labels_by_user_id,
get_users_by_label,
)
class Recommendation:
name = 'recom... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter11/RecommendationService/models.py | <gh_stars>10-100
import os
from py2neo import (
Graph,
Node,
Relationship,
)
USERS_NODE = 'Users'
LABELS_NODE = 'Labels'
REL_TYPE = 'RECOMMENDATION'
graph = Graph(os.getenv('DATABASE_URL'))
def get_user_node(user_id):
return graph.find_one(
USERS_NODE,
property_key='id',
pro... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter05/FamousNewsService/tests.py | <reponame>PacktPublishing/Microservice-Patterns-and-Best-Practices<filename>Chapter05/FamousNewsService/tests.py<gh_stars>10-100
import json
import unittest
from app import app
from flask_testing import TestCase
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('config.TestingCon... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter05/SportsNewsService/models.py | import datetime
from flask_mongoengine import MongoEngine
db = MongoEngine()
class News(db.Document):
title = db.StringField(required=True, max_length=200)
content = db.StringField(required=True)
author = db.StringField(required=True, max_length=50)
created_at = db.DateTimeField(default=datetime.date... |
PacktPublishing/Microservice-Patterns-and-Best-Practices | Chapter05/FamousNewsService/config.py | import os
class BaseConfig:
"""Base configuration"""
DEBUG = False
TESTING = False
MONGODB_SETTINGS = {}
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
DEBUG = True
MONGODB_SETTINGS = {
'db': 'famous_dev',
'host': '{}{}'.format(
os.environ... |
mmmuuuuua/FCOS | tests/test_coco.py | from PIL import Image
import os
import os.path
from pycocotools.coco import COCO
import unittest
annFile = "C:\\zhulei\\data\\instance_segmentation\\rock\\shapes\\train\\instances_leaf_train2017.json"
root = "C:\\zhulei\\data\\instance_segmentation\\rock\\shapes\\train\\shapes_train2017"
class TestCocoApi(unittest.... |
peaceabuya/TesterSimulator | socket_prog.py | #!/usr/bin/python
# Import modules
import sys
import socket
import time
# Create socket object
s = socket.socket()
print s
def get_command(command):
print s
# Send ENQ and check ACK
s.send('\x05')
#time.sleep(.1)
rsp = s.recv(1)
while rsp != '\x06':
s.send('\x05')
#time.sleep(.1)
rsp ... |
99wanglin/d2w_mini_projects | mp_calc/app/serverlibrary.py | <reponame>99wanglin/d2w_mini_projects<gh_stars>0
def merge(array, p, q, r, byfunc):
# print('merging')
nleft = q - p + 1
nright = r - q
left_array = array[p:q+1]
right_array = array[(q+1):r+1]
left = 0
right = 0
dest = p
while left < nleft and right < nright:
if byfunc(left_a... |
99wanglin/d2w_mini_projects | mp_sort/app/static/library.py | <filename>mp_sort/app/static/library.py<gh_stars>0
from org.transcrypt.stubs.browser import *
import random
array = []
def gen_random_int(number, seed):
array = []
random.seed(seed)
for i in range(number):
array.append(i)
random.shuffle(array)
return array
def create_array_str():
array_str = ''
for i, v in ... |
99wanglin/d2w_mini_projects | test.py | def fibonacci(index):
result = 0
if index == 0:
return 0
elif index == 1:
return 1
else:
return fibonacci(index - 1) + fibonacci(index - 2)
fibonacci(3) |
99wanglin/d2w_mini_projects | mp_calc/virtenv/Scripts/transcrypt-script.py | <reponame>99wanglin/d2w_mini_projects<gh_stars>0
#!"C:\Users\sim_w\Desktop\School\Term 3 DDW\d2w_mini_projects\mp_calc\virtenv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'Transcrypt==3.7.16','console_scripts','transcrypt'
__requires__ = 'Transcrypt==3.7.16'
import re
import sys
from pkg_resources import load_entr... |
99wanglin/d2w_mini_projects | mergesort.py | <reponame>99wanglin/d2w_mini_projects
def merge(array, p, q, r):
nleft = q - p + 1
nright = r - q
left_array = array[p:q+1]
right_array = array[(q+1):r+1]
left = 0
right = 0
dest = p
while left < nleft and right < nright:
if left_array[left] <= right_array[right]:
arr... |
ddeangelis/unshorten | isurlshortener/unshortener.py | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Unshortener Documentation
This module unshortens URLs
"""
import re
import http
from urllib.parse import urlparse
from http import client
from isurlshortener.exceptions import PathMissing, UnhandledHTTPStatusCode, LocationHeaderMissing, ProtocolException
class Unshortene... |
ddeangelis/unshorten | isurlshortener/exceptions.py | <filename>isurlshortener/exceptions.py
class ProtocolException(Exception):
pass
class PathMissing(Exception):
pass
class UnhandledHTTPStatusCode(Exception):
pass
class LocationHeaderMissing(Exception):
pass
|
ddeangelis/unshorten | isurlshortener/tests/test_isurlshortener.py | import unittest
from isurlshortener.isurlshortener import IsUrlShortener
class TestIsUrlShortener(unittest.TestCase):
def test_empty_string(self):
self.assertFalse(IsUrlShortener.is_url_shortener(''), 'Empty string error')
def test_bitly_url(self):
HTTPS_BIT_LY = 'https://bitly.is/1g3AhR6'
... |
ddeangelis/unshorten | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='isurlshortener',
version='0.1.6',
description='Provides information if a given url is from an url shortener service',
author='<NAME>',
author_email='<EMAIL>',
packages=['isurlshortener'],
data_files=[('isurlshortene... |
ddeangelis/unshorten | isurlshortener/tests/test_unshorten.py | import unittest
from isurlshortener.unshortener import Unshortener
from isurlshortener.exceptions import ProtocolException, PathMissing
class TestUnshortener(unittest.TestCase):
def test_unshorten_without_protocol(self):
BIT_LY = 'bitly.is/1g3AhR6'
with self.assertRaises(ProtocolException):
... |
ddeangelis/unshorten | isurlshortener/isurlshortener.py | <reponame>ddeangelis/unshorten
# -*- coding: utf-8 -*-
"""IsUrlShortener Documentation
This module answer the question if a given URL is a URL from an URL shortener service
"""
import os
import re
class IsUrlShortener(object):
"""IsUrlShortener
This class contains all required program logic.
"""
... |
ddeangelis/unshorten | isurlshortener/__init__.py | <reponame>ddeangelis/unshorten
from .isurlshortener import IsUrlShortener
from .unshortener import Unshortener
|
deni-zen/CSVelte | docs/_contrib/apigenrole.py | from docutils import nodes, utils
from docutils.parsers.rst.roles import set_classes
# I cant figure out how the hell to import this so I'm just gonna forget it for now
def apigen_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to API Docs page.
Returns 2 part tuple containing lis... |
marsild/ProgettoReti-2021 | spahiuWebServer.py | <reponame>marsild/ProgettoReti-2021<filename>spahiuWebServer.py
# -*- coding: utf-8 -*-
"""
Progetto di Programmazione di Reti a.a. 2020-21
Cognome e Nome: <NAME>
Matricola: 916048
Traccia 2: Python Web Server
"""
import sys
import signal
import http.server
import socketserver
import threading
#Gestire l'attesa sen... |
coleygroup/pyscreener | pyscreener/docking/dock/runner.py | <reponame>coleygroup/pyscreener
import os
from pathlib import Path
import re
import subprocess as sp
import sys
from typing import Mapping, Optional, Tuple, Union
from openbabel import pybel
from rdkit.Chem import AllChem as Chem
import ray
from pyscreener.exceptions import MisconfiguredDirectoryError, MissingEnviron... |
coleygroup/pyscreener | pyscreener/docking/runner.py | <filename>pyscreener/docking/runner.py
from abc import ABC, abstractmethod
from typing import Optional, Sequence
from pyscreener.docking.data import CalculationData
from pyscreener.docking.metadata import CalculationMetadata
class DockingRunner(ABC):
@staticmethod
@abstractmethod
def prepare_receptor(data... |
coleygroup/pyscreener | pyscreener/utils/utils.py | <reponame>coleygroup/pyscreener<gh_stars>10-100
__all__ = [
"AutoName",
"ScoreMode",
"FileFormat",
"chunks",
"calc_score",
"reduce_scores",
"run_on_all_nodes",
]
from enum import Enum, auto
import functools
from itertools import islice
from typing import Callable, Iterable, Iterator, List, ... |
bsholy/learn_flask_email | app.py | import os
from threading import Thread
from flask import Flask, redirect, url_for
from flask_mail import Mail, Message
from mail_html import get_mail_msg
app = Flask(__name__)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.config.update(
SECRET_KEY=os.getenv('SECRET_KEY', 'secret string'... |
bsholy/learn_flask_email | mail_html/get_mail_message.py | <reponame>bsholy/learn_flask_email<filename>mail_html/get_mail_message.py
mail_msg = """
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<table width="100%">
<tbody>
<tr>
<td style="width: 100%;">
<center>
<table class="content-wrap" style="margin: 0px auto; width: 600px;">
... |
bsholy/learn_flask_email | mail_html/__init__.py | <reponame>bsholy/learn_flask_email
from mail_html.get_mail_message import get_mail_msg |
hortinstein/NOSETEST | PRETTYGOOD/test/encryption_test.py | """
Test the monocypher python binding.
"""
import unittest
import monocypher
import hashlib
import numpy as np
import binascii
import os
import json
import warnings
#!COMMENT Take a look how the monocypher library is tested
#!COMMENT This should help in understanding the crypto wrappers that I wrote
#... |
hortinstein/NOSETEST | STOPANDCHAT/4_understanding_testoutput.py | <reponame>hortinstein/NOSETEST
#!COMMENT Warmup Exercise #4
def sum(arg):
total = 0
for val in arg:
total += val
return total
# Understanding Test Output
# That was a very simple example where everything passes, so now you’re going to try a failing test and interpret the output.
# sum() should be ... |
hortinstein/NOSETEST | STOPANDCHAT/3_writing_first_test.py | <reponame>hortinstein/NOSETEST
#!COMMENT Warmup Exercise #3
# Writing Your First Test
# Let’s bring together what you’ve learned so far and, instead of testing the built-in sum() function,
# test a simple implementation of the same requirement.
# Create a new project folder and, inside that, create a new folder calle... |
hortinstein/NOSETEST | STOPANDCHAT/1_basic_testing.py | #!COMMENT Warmup Exercise #1
# Testing Your Code
# There are many ways to test your code. In this tutorial, you’ll learn the techniques from the most basic steps and work towards advanced methods.
# Automated vs. Manual Testing
# The good news is, you’ve probably already created a test without realizing it. Remember w... |
hortinstein/NOSETEST | SWANKILLER.py | <filename>SWANKILLER.py
import os
import sys
import fileinput
import shutil, errno
def copyanything(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
old_dir = sys.argv[1]
#cre... |
hortinstein/NOSETEST | PRETTYGOOD/PRETTYGOOD.py | """
Very simple HTTP server in python (Updated for Python 3.7)
Usage:
./PRETTYGOOD.py -h
./PRETTYGOOD.py -l localhost -p 8000
Send a GET request:
curl http://localhost:8000
Send a HEAD request:
curl -I http://localhost:8000
Send a POST request:
curl -d "foo=bar&bin=baz" http://localhost:80... |
hortinstein/NOSETEST | STOPANDCHAT/2_automated_testing.py | #!COMMENT Warmup Exercise #2
# Writing tests in this way is okay for a simple check, but what if more than one fails? This is where test runners come in.
# The test runner is a special application designed for running tests, checking the output,
# and giving you tools for debugging and diagnosing tests and applicatio... |
hortinstein/NOSETEST | PRETTYGOOD/data_utils.py | <gh_stars>1-10
import unittest
import monocypher
import random
import numpy as np
import unittest
import monocypher
import hashlib
import numpy as np
import binascii
import os
import json
import warnings
import struct
#encryption globals
KEY_LEN = 32
NONCE_LEN = 24
MAC_LEN = 16
###################... |
gclaassen/extension-scraper | pyScraper.py |
import os
import sys
import getopt
import shutil
import time
from datetime import datetime
EXT_TYPE = 0
MOVE_TYPE = 1
SCR_DIR = 2
DEST_DIR = 3
COPY = 0
MOVE = 1
REPORT_NAME = "_report.txt"
ignoreDirKeyWords = [
'Recycle',
'Windows',
'System Volume Information',
'AppData'
]
def argumentExtraction(... |
elhachimi-ch/dst | src/data_science_toolkit/rl.py | <filename>src/data_science_toolkit/rl.py
import gym
import numpy as np
class Environment:
def __init__(self, environment_name="FrozenLake-v0", is_slippery=True):
"""The environment constructor"""
if environment_name == "FrozenLake-v0":
self.__environment = gym.make(environment_name... |
elhachimi-ch/dst | src/data_science_toolkit/gis.py | <filename>src/data_science_toolkit/gis.py
import numpy as np
from numpy.linalg import matrix_power
from dataframe import DataFrame
from rl import *
import pandas as pd
from .lib import Lib
import contextily as cx
from matplotlib import pyplot as plt
import geopandas as gpd
from shapely.geometry import Point
import xarr... |
elhachimi-ch/dst | test/test.py | import data_science_toolkit.dataframe as dst
data = dst.DataFrame()
data.show() |
elhachimi-ch/dst | setup.py | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="data-science-toolkit",
version="0.0.980",
author="<NAME>",
author_email="<EMAIL>",
description="Data Science Toolkit (DST) is a Python library that helps impleme... |
elhachimi-ch/dst | src/data_science_toolkit/imagefactory.py | <gh_stars>1-10
import cv2
import imutils
import imutils.perspective
import numpy as np
from matplotlib import pyplot as plt
from skimage.filters import threshold_local
class ImageFactory:
def __init__(self, img_link=None, url=False):
self.__img = None
if url:
self.__img = imutils.url_to... |
elhachimi-ch/dst | src/data_science_toolkit/dataframe.py | from datetime import timedelta
from math import ceil
import pandas as pd
from pyparsing import col
import scipy.sparse
from sklearn.decomposition import PCA
from sklearn.feature_extraction import DictVectorizer
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler, MinMaxScal... |
elhachimi-ch/dst | test/kitchen.py | import time
import os
import sys
def main():
ti = time.time()
data = DataFrame()
data.load_dataset('iris')
y = data.get_column('target')
data.drop_column('target')
# decision tree model
model = Model(data_x=data.get_dataframe(), data_y=y, model_type='dt', training_percent=0.8)
... |
elhachimi-ch/dst | src/data_science_toolkit/lib.py | <reponame>elhachimi-ch/dst
import csv
import pickle
import re
from os import listdir
from os.path import isfile, join
from time import sleep
import math
import numpy as np
import unidecode
from emoji import UNICODE_EMOJI
from textblob import TextBlob
#from stringdist.pystringdist.levenshtein import levenshtein as ed
im... |
elhachimi-ch/dst | src/data_science_toolkit/vectorizer.py | <reponame>elhachimi-ch/dst<gh_stars>1-10
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
import joblib
from tensorflow.keras.utils import to_categorical
from .lib import Lib
from sklearn.preprocessing import MinMaxScal... |
elhachimi-ch/dst | src/data_science_toolkit/r3.py | <reponame>elhachimi-ch/dst
import gym
import numpy as np
from .dataframe import DataFrame
from gis import GIS
import re
from csm import CSM
class R3(gym.Env):
#
MAX_SOWING_DAY = 100
# action space definition
ADD_DAY = 0
SUB_DAY = 1
SAME_DAY = 2
action_space = gym.spaces.Discret... |
elhachimi-ch/dst | src/data_science_toolkit/rl_dqn.py | <reponame>elhachimi-ch/dst<filename>src/data_science_toolkit/rl_dqn.py
import time
import os
import re
from stable_baselines3 import PPO, DQN
import gym
from r3 import R3
from stable_baselines3.common.env_checker import check_env
def main():
ti = time.time()
#left, down, up, right
#environment = Env... |
elhachimi-ch/dst | src/data_science_toolkit/chart.py | <gh_stars>1-10
import seaborn as sns
from matplotlib import pyplot as plt
import plotly.graph_objects as go
import plotly.express as px
import matplotlib.ticker as plticker
import numpy as np
import pandas as pd
class Chart:
chart_type_list = ['line', 'bar', 'box', 'swarm', 'strip_swarm', 'count', 'scatter', 'di... |
elhachimi-ch/dst | src/data_science_toolkit/model.py | <gh_stars>1-10
"""
Under MIT License by <NAME>
"""
import tensorflow.keras.losses
import tensorflow.keras.optimizers
from tensorflow.keras import backend as K
import sklearn.tree as tree
from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D, Dropout, MaxPool1D, Conv1D, Reshape, LSTM
from tensorflow.k... |
elhachimi-ch/dst | src/data_science_toolkit/csm.py | from math import exp
from .dataframe import DataFrame
import numpy as np
import matplotlib.pyplot as plt
from pandas import Series
from .chart import Chart
import seaborn as sns
class CSM:
def __init__(self):
self.crop_type = 'Wheat'
self.season_length = 242
self.climate_dataframe = se... |
nickwanninger/helion | tools/scripts/generate_tokens.py | <filename>tools/scripts/generate_tokens.py<gh_stars>1-10
tokens = [
"eof",
"num",
"var",
"type",
"self_var",
"str",
"keyword",
"left_curly",
"right_curly",
"left_angle",
"right_angle",
"left_square",
"right_square",
"left_paren",
"right_paren",
"typedef... |
DalavanCloud/alluxio-py | alluxio/__init__.py | <reponame>DalavanCloud/alluxio-py<gh_stars>1-10
# -*- coding: utf-8 -*-
from .client import Client
import option
import wire
__version__ = '0.1.1'
|
radjivC/interaction-node-riak | ExampleZukaiRestApi/node_modules/riak-js/node_modules/riakpbc/node_modules/riakproto/riak_pb/msgcodegen.py | <reponame>radjivC/interaction-node-riak<gh_stars>1-10
# Copyright 2013 Basho Technologies, Inc.
#
# This file is provided to you 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.o... |
radjivC/interaction-node-riak | ExampleZukaiRestApi/node_modules/riak-js/node_modules/riakpbc/node_modules/riakproto/riak_pb/riak_pb/__init__.py | from riak_pb2 import *
from riak_kv_pb2 import *
from riak_search_pb2 import *
from riak_dt_pb2 import *
from riak_yokozuna_pb2 import *
|
senzil/cabot-alert-hipchat | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
VERSION = '2.0.3'
setup(name='cabot-alert-hipchat',
version=VERSION,
description='A Hipchat alert plugin for Cabot by Arachnys',
author='Arachnys',
author_email='<EMAIL>',
url='http://cabotapp.com',
packages=find_pa... |
kuduta/QueueSystem | QueueWebProject/QueueWebProject/app.py | """
This script runs the application using a development server.
It contains the definition of routes and views for the application.
command >>> from api import db
command >>> db.create_all()
"""
import os
import queue
import pygame
import sys
from datetime import datetime
<<<<<<< HEAD
from flask import Flask
=====... |
kuduta/QueueSystem | QueueWebProject/QueueWebProject/playsound.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 18:35:06 2019
@author: nexpose
"""
import pygame
import time
import sys
def playsound(num):
pygame.init()
#pygame.mixer.music.load("sounds/"+ str(num)+".mp3")
pygame.mixer.music.load("sound/"+ str(num)+".wav")
pygame.mixer.... |
kuduta/QueueSystem | QueueWebProject/QueueWebProject/api.py | <reponame>kuduta/QueueSystem
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 17:25:09 2019
@author: nexpose
"""
import sys
import time
import sqlalchemy as db
import pandas as pd
from datetime import datetime
from flask import Flask , request ,jsonify
app = Flask(__name__)
# Make the WSGI ... |
ANDRESROMEROH/aws-solutions-architect | rekognition-app/rekognitionlambda/index.py | <filename>rekognition-app/rekognitionlambda/index.py<gh_stars>0
#
# Lambda function to detect labels in image using Amazon Rekognition
#
import logging
import boto3
from botocore.exceptions import ClientError
import os
from urllib.parse import unquote_plus
from boto3.dynamodb.conditions import Key, Attr
# Set the min... |
jeffkess/excel2gtfs | excel2gtfs.py | <gh_stars>0
""""------------------------------------------------------------------
Excel2GTFS v0.0.8
(c) <NAME>, 2021-12-12-1620
0.0.1 Initial Commit
0.0.2 Schedule data processing
0.0.3 Support for calendar dates and overrides
0.0.4 GTFS specification conformity adjustments
0.0.5 Post-midnight trip support & con... |
jivii/connect-express-oauth | server/python/server.py | <gh_stars>0
#! /usr/bin/env python3.6
"""
server.py
Stripe Sample.
Python 3.6 or newer required.
"""
import json
import os
import secrets
import string
import stripe
from dotenv import load_dotenv, find_dotenv
from flask import Flask, jsonify, render_template, redirect, request, session, send_from_directory
import u... |
hexops/Azure-Kinect-Python | k4a/__init__.py | from .pyk4a import *
from .pyk4abt import * |
hexops/Azure-Kinect-Python | k4a/pyk4a.py | import ctypes
import enum
import sys
import os
try:
dirPath = os.path.dirname(os.path.abspath(__file__))+r'/../vendor/azure_kinect/windows/amd64/'
print(dirPath)
_k4a = ctypes.CDLL(dirPath+r'k4a.dll')
os.environ['PATH'] = dirPath+';'+os.environ['PATH']
except Exception as e1:
try:
dirPath =... |
hexops/Azure-Kinect-Python | k4a/pyk4abt.py | import ctypes
import enum
import sys
import os
from .pyk4a import k4a_float3_t, k4a_calibration_t, k4a_capture_t, k4a_image_t
try:
dirPath = os.path.dirname(os.path.abspath(__file__))+r'/../vendor/azure_kinect/windows/amd64/'
_k4abt = ctypes.CDLL(dirPath+r'k4abt.dll')
os.environ['PATH'] = dirPath+';'+os.e... |
medtray/MultiEm-RGCN | utils.py | <reponame>medtray/MultiEm-RGCN<gh_stars>0
"""
Utility functions for link prediction
Most code is adapted from authors' implementation of RGCN link prediction:
https://github.com/MichSchli/RelationPrediction
"""
import numpy as np
import torch
import dgl
import datetime
import re
import random
import networkx as nx
fr... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/retrieval/toy_indexer.py | """
Toy Indexer
===========
Toy indexing example for testing purposes.
:Authors: <NAME>, <NAME>
"""
from nordlys.core.retrieval.elastic import Elastic
from nordlys.core.retrieval.elastic_cache import ElasticCache
from nordlys.core.retrieval.scorer import *
import math
def main():
index_name = "toy_index"
ma... |
medtray/MultiEm-RGCN | nordlys/nordlys/logic/features/word2vec.py | <reponame>medtray/MultiEm-RGCN
"""
Word2vec
========
Implements functionalities over the 300-dim GoogleNews word2vec semantic representations of words.
:Author: <NAME>
"""
import argparse
import numpy as np
from nordlys.config import MONGO_HOST, MONGO_DB, MONGO_COLLECTION_WORD2VEC
from nordlys.core.storage.mongo im... |
medtray/MultiEm-RGCN | utils_.py | import numpy as np
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import string
#import tensorflow as tf
import os
import re
def isEnglish(s):
try:
s.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
return False
else:
return True
def c... |
medtray/MultiEm-RGCN | nordlys/nordlys/config.py | """
config
------
Global nordlys config.
:Author: <NAME>
:Author: <NAME>
"""
import logging
import os
from nordlys.core.utils.file_utils import FileUtils
from nordlys.core.utils.logging_utils import PrintHandler
def load_nordlys_config(file_name):
"""Loads nordlys config file. If local file is provided, global ... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/__init__.py | """
Core packages
=============
These low-level packages (basic IR, ML, NLP, storage, etc.) are basic building blocks that do not have any interdependencies among each other.
""" |
medtray/MultiEm-RGCN | nordlys/nordlys/core/data/dbpedia/indexer_dbpedia_types.py | <filename>nordlys/nordlys/core/data/dbpedia/indexer_dbpedia_types.py
"""
DBpedia Types Indexer
=====================
Build an index of DBpedia types from entity abstracts.
:Authors: <NAME>, <NAME>
"""
import os
import argparse
from random import sample
from math import floor
from rdflib.plugins.parsers.ntriples imp... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/storage/nt2mongo.py | """
NTriples to Mongo
=================
Loads NTriples RDF file into MongoDB.
Documents are identified by subject URIs.
Predicate-object values are stored as key-value pairs in a dictionary,
where object can be single-valued (string) or multi-valued (list of strings).
- Multiple ntriple files can be added to the sa... |
medtray/MultiEm-RGCN | LTR/data_reader_jm.py | <filename>LTR/data_reader_jm.py<gh_stars>0
from collections import Counter
import sys
import os
cwd = os.getcwd()
from pathlib import Path
path = Path(cwd)
sys.path.append(os.path.join(path.parent.absolute(),'nordlys'))
from nordlys.core.retrieval.elastic import Elastic
from nordlys.core.retrieval.elastic_cache import... |
medtray/MultiEm-RGCN | nordlys/nordlys/logic/features/ftr_entity_similarity.py | """
FTR Entity Similarity
=====================
Implements features capturing the similarity between entity and a query.
:Author: <NAME>
"""
from __future__ import division
import re
import math
from nordlys.core.retrieval.elastic import Elastic
from nordlys.core.retrieval.scorer import ScorerMLM
class FtrEntityS... |
medtray/MultiEm-RGCN | nordlys/nordlys/logic/features/ftr_mention.py | <reponame>medtray/MultiEm-RGCN
"""
FTR Mention
===========
Implements mention feature.
:Author: <NAME>
"""
from nordlys.logic.query.mention import Mention
class FtrMention(object):
def __init__(self, mention, entity=None, cand_ens=None):
self.__mention = mention.strip()
self.__entity = entity
... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/eval/trec_run.py | <filename>nordlys/nordlys/core/eval/trec_run.py
"""
Trec run
========
Utility module for working with TREC runfiles.
Usage
-----
Get statistics about a runfile
``trec_run <run_file> -o stat``
Filter runfile to contain only documents from a given set
``trec_run <run_file> -o filter -d <doc_ids_file> -f <output_... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/storage/parser/nt_parser.py | <filename>nordlys/nordlys/core/storage/parser/nt_parser.py
"""
NTriples Parser
===============
NTriples parser with URI prefixing
:Author: <NAME>
"""
import sys
import logging
from nordlys.core.storage.parser.uri_prefix import URIPrefix
from rdflib.plugins.parsers.ntriples import NTriplesParser
from rdflib.term impo... |
medtray/MultiEm-RGCN | nordlys/nordlys/services/er.py | """
Entity Retrieval
================
Command-line application for entity retrieval.
Usage
-----
::
python -m nordlys.services.er -c <config_file> -q <query>
If `-q <query>` is passed, it returns the results for the specified query and prints them in terminal.
Config parameters
------------------
- **index_na... |
medtray/MultiEm-RGCN | load_model_for_testing.py | <reponame>medtray/MultiEm-RGCN<gh_stars>0
import argparse
import numpy as np
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from dgl.contrib.data import load_data
from dgl.nn.pytorch import RelGraphConv
import subprocess
from model import BaseRGCN
import os
import utils
... |
medtray/MultiEm-RGCN | nordlys/nordlys/logic/features/__init__.py | """
Features
========
This is the features package.
"""
|
medtray/MultiEm-RGCN | LTR/conv_knrm.py | <gh_stars>0
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as f
from torch.autograd import Variable
import torch.nn.functional as F
class CONVKNRM(nn.Module):
"""Class that classifies question pair as duplicate or not."""
def __init__(self, args):
""""Constructor of... |
medtray/MultiEm-RGCN | nordlys/nordlys/services/el.py | """
Entity Linking
==============
The command-line application for entity linking
Usage
-----
::
python -m nordlys.services.el -c <config_file> -q <query>
If `-q <query>` is passed, it returns the results for the specified query and prints them in terminal.
Config parameters
-----------------
- **method**: nam... |
medtray/MultiEm-RGCN | nordlys/nordlys/core/storage/parser/uri_prefix.py | """
URI Prefixing
=============
URI prefixing.
:Author: <NAME>
"""
import json
from nordlys import config
PREFIX_JSON_FILE = config.DATA_DIR + "/uri_prefix/prefixes.json"
class URIPrefix(object):
def __init__(self, prefix_file=PREFIX_JSON_FILE):
self.prefixes = json.load(open(prefix_file))
def __... |
medtray/MultiEm-RGCN | nordlys/nordlys/logic/entity/__init__.py | """
Entity
======
This is the entity package.
"""
|
medtray/MultiEm-RGCN | nordlys/nordlys/logic/fusion/fusion_scorer.py | <gh_stars>10-100
"""
Fusion Scorer
=============
Abstract class for fusion-based scoring.
:Authors: <NAME>, <NAME>, <NAME>
"""
from nordlys.core.retrieval.retrieval import Retrieval
class FusionScorer(object):
ASSOC_MODE_BINARY = 1
ASSOC_MODE_UNIFORM = 2
"""Abstract class for any fusion-based method.""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.