repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
Joshinn-io/augur | workers/message_insights_worker/message_novelty.py | import logging
import multiprocessing
import os
from datetime import date
import numpy as np
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from keras.layers import Dense, Input
from keras.models import Model, load_model
from scipy.spatial.distance import cosine
from skimage.filters impo... |
Joshinn-io/augur | augur/cli/_multicommand.py | <reponame>Joshinn-io/augur<filename>augur/cli/_multicommand.py
#SPDX-License-Identifier: MIT
"""
Runs Augur with Gunicorn when called
"""
import os
import sys
import click
import importlib
import augur.application
CONTEXT_SETTINGS = dict(auto_envvar_prefix='AUGUR')
class AugurMultiCommand(click.MultiCommand):
de... |
Joshinn-io/augur | tests/test_metrics/test_commit_metrics.py | #SPDX-License-Identifier: MIT
import pytest
def test_annual_commit_count_ranked_by_repo_in_repo_group(metrics):
assert metrics.annual_commit_count_ranked_by_repo_in_repo_group(10).iloc[0].net > 0
assert metrics.annual_commit_count_ranked_by_repo_in_repo_group(10, 25430).iloc[0].net > 0
def test_annual_commit... |
Joshinn-io/augur | workers/worker_base.py | <filename>workers/worker_base.py<gh_stars>100-1000
from workers.worker_persistance import *
#I figure I can seperate this class into at least three parts.
#I should also look into the subclass and see what uses what.
#
# Parts (Hierarchal relation)
#1. Persistance
#2. Base
#3. Github/lab
# Might be good to seperate... |
Joshinn-io/augur | augur/routes/batch.py | <filename>augur/routes/batch.py
#SPDX-License-Identifier: MIT
"""
Creates routes for the manager
"""
import logging
import time
import requests
import sqlalchemy as s
from sqlalchemy import exc
from flask import request, Response
from augur.util import metric_metadata
import json
logger = logging.getLogger(__name__)
... |
Joshinn-io/augur | workers/deps_worker/vb_deps.py | import sys
import re
from pathlib import Path
def get_files(path):
#copied from example on https://docs.python.org/3/library/pathlib.html
dir = path
p = Path(dir)
files = list(p.glob('**/*.vb'))
return files
def get_deps_for_file(path):
f = open(path, 'r')
matches = re.findall("Imports\s*(.*)", f.read())
f.c... |
Joshinn-io/augur | tests/test_application.py | #SPDX-License-Identifier: MIT
import pytest
import augur.application
import sqlalchemy as s
import json
from augur.application import Application
def test_init_augur_regular():
augur_app = Application(disable_logs=True)
assert augur_app is not None
def test_connect_to_database(monkeypatch):
def mock_fail... |
Joshinn-io/augur | augur/gunicorn.py | <filename>augur/gunicorn.py
import logging
import gunicorn.app.base
from gunicorn.arbiter import Arbiter
from augur.server import Server
logger = logging.getLogger(__name__)
class AugurGunicornApp(gunicorn.app.base.BaseApplication):
"""
Loads configurations, initializes Gunicorn, loads server
"""
d... |
Joshinn-io/augur | augur/metrics/deps.py | <filename>augur/metrics/deps.py<gh_stars>1-10
#SPDX-License-Identifier: MIT
"""
Metrics that provide data about with insight detection and reporting
"""
import sqlalchemy as s
import pandas as pd
from augur.util import register_metric
@register_metric()
def deps(self, repo_group_id, repo_id=None):
depsSQL = s.sql.te... |
Joshinn-io/augur | workers/deps_worker/deps_worker.py | #SPDX-License-Identifier: MIT
import os, subprocess
from datetime import datetime
import logging
from workers.worker_git_integration import WorkerGitInterfaceable
import requests
import json
from urllib.parse import quote
from multiprocessing import Process, Queue
import traceback
import pandas as pd
import sqlalchemy ... |
Joshinn-io/augur | workers/release_worker/__init__.py | #SPDX-License-Identifier: MIT
"""gh_release_worker - Augur Worker that collects GitHub Repo Info data"""
__version__ = '0.0.0'
__author__ = '<NAME> <<EMAIL>>'
__all__ = []
|
Joshinn-io/augur | workers/facade_worker/contributor_interfaceable/contributor_interface.py | from requests.api import head
from workers.worker_base import *
import logging
from logging import FileHandler, Formatter, StreamHandler, log
from workers.worker_git_integration import WorkerGitInterfaceable
from workers.util import read_config
from psycopg2.errors import UniqueViolation
from random import randint
impo... |
fsmosca/chess-tuning-tools | tune/summary.py | <gh_stars>10-100
import numpy as np
__all__ = ["confidence_intervals"]
def _round_interval(interval, threshold=0.01, max_precision=32):
diff = interval[1] - interval[0]
if diff == 0:
return tuple(interval)
for i in range(max_precision):
rounded = np.around(interval, decimals=i)
di... |
fsmosca/chess-tuning-tools | tests/__init__.py | <filename>tests/__init__.py<gh_stars>10-100
"""Unit test package for chess_tuning_tools."""
|
fsmosca/chess-tuning-tools | tests/test_priors.py | <filename>tests/test_priors.py
import numpy as np
from pytest import approx, raises
from tune.priors import create_priors, make_invgamma_prior, roundflat
def test_roundflat():
assert roundflat(0.3) == approx(0.0, abs=1e-6)
assert roundflat(0.0) == -np.inf
assert roundflat(-1.0) == -np.inf
def test_make... |
fsmosca/chess-tuning-tools | tests/test_io.py | <gh_stars>0
from tune.io import load_tuning_config
def test_load_tuning_config():
testdict = {
"engines": [
{"command": "lc0", "fixed_parameters": {"CPuctBase": 13232, "Threads": 2}},
{"command": "sf", "fixed_parameters": {"Threads": 8}},
],
"parameter_ranges": {"CP... |
fsmosca/chess-tuning-tools | tune/priors.py | import warnings
from typing import Callable, List
import numpy as np
from scipy.optimize import curve_fit
from scipy.stats import halfnorm, invgamma
from scipy.stats._distn_infrastructure import rv_frozen # noqa
__all__ = ["make_invgamma_prior", "roundflat", "create_priors"]
def roundflat(x, a_low=2.0, a_high=8.0,... |
fsmosca/chess-tuning-tools | tune/db_workers/__init__.py | from .tuning_client import TuningClient
from .tuning_server import TuningServer
__all__ = ["TuningClient", "TuningServer"]
|
fsmosca/chess-tuning-tools | tune/io.py | <reponame>fsmosca/chess-tuning-tools<filename>tune/io.py
import json
import re
import sys
from ast import literal_eval
from collections.abc import MutableMapping
from pathlib import Path
import skopt.space as skspace
from skopt.space.space import check_dimension
__all__ = [
"InitStrings",
"uci_tuple",
"pa... |
fsmosca/chess-tuning-tools | tune/db_workers/dbmodels/base_model.py | <reponame>fsmosca/chess-tuning-tools
__all__ = ["Base"]
try:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
except ImportError:
Base = None
declarative_base = None
|
fsmosca/chess-tuning-tools | tune/local.py | <filename>tune/local.py
import logging
import pathlib
import re
import subprocess
import sys
import time
from datetime import datetime
from logging import Logger
from typing import Callable, List, Optional, Sequence, Tuple, Union
import dill
import matplotlib.pyplot as plt
import numpy as np
from bask import Optimizer... |
fsmosca/chess-tuning-tools | tune/plots.py | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import LogLocator
from skopt.plots import _format_scatter_plot_axes
from tune.utils import expected_ucb
__all__ = ["partial_dependence", "plot_objective"]
def _evenly_sample(dim, n_points):
"""Return `n_points` evenly spaced points from a... |
fsmosca/chess-tuning-tools | tune/db_workers/dbmodels/__init__.py | from tune.db_workers.dbmodels.base_model import Base
from tune.db_workers.dbmodels.models import *
__all__ = ["Base", "SqlTune", "SqlJob", "SqlUCIParam", "SqlTimeControl", "SqlResult"]
|
fsmosca/chess-tuning-tools | tests/test_dbutils.py | #!/usr/bin/env python
from decimal import Decimal
import numpy as np
from numpy.testing import assert_almost_equal
from tune.db_workers.utils import (
TimeControl,
compute_probabilities,
compute_probabilities_for_bias,
draw_rate_to_elo,
elo_to_bayeselo,
ldw_probabilities,
penta,
penta... |
defunSM/SpecialRel | SpaceTimeGraph.py | import sys, os, math
import optparse
import SpecialRel as sprl
import matplotlib.pyplot as plt
import numpy as np
def time_of_the_object(v, b, x):
return (1 / v) * x + b
def given_velocity_and_initial_position(v, b=0, limit=11, lower_limit=-11):
data = []
for i in np.arange(lower_limit,limit):
... |
defunSM/SpecialRel | SpecialRel.py | <gh_stars>1-10
#!/usr/bin/env python
import sys, os, math
c = 299792458
def main():
print("SpecialRel.py has been loaded.")
def ctometer(a): # Converts the speed that is in terms of c to meters per second.
return a * c
def metertoc(a): # Converts the speeed that is in terms of meters per second into t... |
adeel/timed | scripts/011_to_012.py | #!/usr/bin/env python
"Converts a timed-0.11-style log file to a timed-0.12-style log file."
import timed
import yaml
def read():
data = open(timed.log_file).read()
if not data:
return []
return yaml.safe_load(data)
logs = read()
timed.save(logs) |
adeel/timed | timed/client.py | "Timed: a command-line time tracker."
__name__ = 'client'
import sys
import os.path
import datetime
from termcolor import colored
from timed import server
from timed import cmdapp
now = datetime.datetime.now
def main():
cmdapp.main(name='timed', desc=__doc__, config={
'logfile': os.path.expanduser('~/.timed'... |
adeel/timed | timed/cmdapp.py | <filename>timed/cmdapp.py<gh_stars>10-100
import sys
program = {}
handlers = {}
def main(name, desc, config={}):
program['name'] = name
program['desc'] = desc
if len(sys.argv) < 2:
command, args = '', []
else:
command, args = sys.argv[1], sys.argv[2:]
options = config
for i, arg in enumerate... |
adeel/timed | timed/server.py | import datetime
import itertools
from operator import itemgetter
def summarize(records):
return [(r[0], sum(s[1] for s in r[1])) for r in
itertools.groupby(sorted(records, key=itemgetter(0)), itemgetter(0))]
def start(project, records):
if records and not records[-1][1][1]:
return records
return records... |
adeel/timed | setup.py | from distutils.core import setup
setup(
name='timed',
version='0.4.1',
description="command-line time tracker",
url='http://adeel.github.com/timed',
author='<NAME>',
author_email='<EMAIL>',
packages=['timed'],
scripts=['bin/timed'],
install_requires=['termcolor'],
license='MIT',
classifiers=[
... |
minervaproject/dd-trace-py | tests/profiling/test_profiler.py | <gh_stars>1-10
import pytest
import ddtrace
from ddtrace.profiling import profiler
from ddtrace.profiling.collector import stack
from ddtrace.profiling.exporter import http
def test_status():
p = profiler.Profiler()
assert repr(p.status) == "STOPPED"
p.start()
assert repr(p.status) == "RUNNING"
p... |
minervaproject/dd-trace-py | ddtrace/profiling/profiler.py | # -*- encoding: utf-8 -*-
import atexit
import logging
import os
from ddtrace.profiling import recorder
from ddtrace.profiling import scheduler
from ddtrace.utils import deprecation
from ddtrace.vendor import attr
from ddtrace.profiling.collector import exceptions
from ddtrace.profiling.collector import memory
from dd... |
minervaproject/dd-trace-py | ddtrace/contrib/redis/__init__.py | <reponame>minervaproject/dd-trace-py<filename>ddtrace/contrib/redis/__init__.py
"""
Traces redis client queries.
If you are not autoinstrumenting with ``ddtrace-run`` then install the redis
instrumentation with::
from ddtrace import patch
patch(redis=True)
Global Configuration
~~~~~~~~~~~~~~~~~~~~
.. py:da... |
dblevin1/TheHaloMod | halomod_app/form_utils.py | """
Defines custom meta-forms and other utilities to make forms easier.
"""
import logging
import re
from collections import OrderedDict
from crispy_forms.bootstrap import Tab
from crispy_forms.layout import Div, Field
from django import forms
from django.utils.safestring import mark_safe
from halomod import TracerH... |
dblevin1/TheHaloMod | TheHaloMod/urls.py | from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include, path
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
path("", include("halomod_app.urls")),
]
if sett... |
dblevin1/TheHaloMod | halomod_app/views.py | import datetime
# import logging
import io
import logging
import zipfile
from collections import OrderedDict
import numpy as np
from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.base import TemplateView
from dja... |
dblevin1/TheHaloMod | TheHaloMod/settings/local.py | <filename>TheHaloMod/settings/local.py
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
DEBUG = True
SECRET_KEY = env("DJANGO_SECRET_KEY", default="!!!SET DJANGO_SECRET_KEY!!!",)
# https://docs.djangoproject.com/en/dev/ref/set... |
dblevin1/TheHaloMod | TheHaloMod/settings/production.py | import logging
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.logging import LoggingIntegration
from .base import * # noqa
from .base import env, LOGGING, ROOT_DIR
# GENERAL
# ------------------------------------------------------------------------------
# ... |
dblevin1/TheHaloMod | TheHaloMod/settings/base.py | <gh_stars>1-10
"""Base settings to build other settings off."""
# ===============================================================================
# THIRD_PARTY IMPORTS
# ===============================================================================
import dill
from django.contrib.sessions import serializers
from djan... |
dblevin1/TheHaloMod | halomod_app/templatetags/hmf_version.py | """
Created on Apr 10, 2013
@author: Steven
"""
import hmf
from django import template
register = template.Library()
def current_hmf_version():
return hmf.__version__
register.simple_tag(current_hmf_version)
|
dblevin1/TheHaloMod | halomod_app/urls.py | from django.urls import path
from django.views.generic.base import RedirectView
from django.contrib.staticfiles.storage import staticfiles_storage
from . import views
urlpatterns = [
path(
"favicon.ico",
RedirectView.as_view(
url=staticfiles_storage.url("halomod_app/img/favicon.ico"), ... |
dblevin1/TheHaloMod | halomod_app/templatetags/halomod_version.py | <filename>halomod_app/templatetags/halomod_version.py
"""
Created on Apr 10, 2013
@author: Steven
"""
import halomod
from django import template
register = template.Library()
def current_halomod_version():
return halomod.__version__
register.simple_tag(current_halomod_version)
|
dblevin1/TheHaloMod | halomod_app/utils.py | <filename>halomod_app/utils.py
"""Plotting and driving utilities for halomod."""
import io
import logging
import matplotlib.ticker as tick
from halomod import TracerHaloModel
from halomod.wdm import HaloModelWDM
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.backends.backend_pdf import Fig... |
Jitesh17/printj | test/test_print_colors.py | <gh_stars>1-10
import printj
printj.red('YOUR TEXT')
printj.bold('YOUR TEXT')
printj.blue.italic_on_yellow('YOUR TEXT')
|
Jitesh17/printj | printj/printj_colors.py | <gh_stars>1-10
#!/usr/bin/python3
from printj.lib import Template
import os
from functools import partial
class say:
def __init__(self, text):
os.system(f'spd-say " {text} "')
class clear:
def __init__(self):
os.system('clear')
class bold:
# color = 'red'
def __init__(self, text... |
Jitesh17/printj | printj/__init__.py | <reponame>Jitesh17/printj
from .printj_colors import *
from .lib import *
# from .printj_colors import *
|
Jitesh17/printj | printj/lib.py | <gh_stars>1-10
#!/usr/bin/python3
CRED = '\033[31m'
CEND = '\033[0m'
CSI = '\x1B['
code = {
'black': '0',
'red': '1',
'green': '2',
'yellow': '3',
'blue': '4',
'purple': '5',
'cyan': '6',
'white': '7',
}
stl = dict()
stl['normal'] = '0'
stl['bold'] = '1'
stl['italic'] = '3'
stl['unde... |
MeteoSwiss-APN/mch-python-blueprint-cython-example-chain_calc | {{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/cli.py | # -*- coding: utf-8 -*-
"""Console script for {{ cookiecutter.project_slug }}."""
import sys
import click
from . import __version__
from .mutable_number import MutableNumber
def print_version(ctx, param, value):
"""Print the version number and exit."""
if value:
click.echo(__version__)
ctx.e... |
MeteoSwiss-APN/mch-python-blueprint-cython-example-chain_calc | {{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/__init__.py | # -*- coding: utf-8 -*-
"""Top-level package for Chain Calculator."""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "0.1.0"
|
MeteoSwiss-APN/mch-python-blueprint-cython-example-chain_calc | {{cookiecutter.project_slug}}/setup.py | <reponame>MeteoSwiss-APN/mch-python-blueprint-cython-example-chain_calc<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The setup script.
"""
from setuptools import setup
from setuptools import find_packages
# Import Cython after setuptools
from Cython.Build import cythonize # isort:skip
def read_file(... |
prince21298/SCRAPING | task1.py | import requests
from bs4 import BeautifulSoup
import pprint
def scrap_top_list():
url=" https://www.imdb.com/india/top-rated-indian-movies/"
page=requests.get(url)
soup=BeautifulSoup(page.text,'html.parser')
main_div=soup.find('div',class_="lister")
div=main_div.find('tbody',class_="lister-list")
trs=div.findAll(... |
prince21298/SCRAPING | task12ex.py | import requests
from bs4 import BeautifulSoup
import json
import os.path
from os import path
from pprint import pprint
def scrap_top_list():
if os.path.exists("movie.json"):
with open ("movie.json",'r') as file:
read=file.read()
main_data=json.loads(read)
return(main_data)
else:
url=" https://www.imdb.co... |
prince21298/SCRAPING | task9/task9.py | <filename>task9/task9.py<gh_stars>1-10
import requests,random,time
from bs4 import BeautifulSoup
import json
import os.path
from os import path
from pprint import pprint
def scrap_top_list():
if os.path.exists("movie.json"):
with open ("movie.json",'r') as file:
read=file.read()
main_data=json.loads(read)
r... |
prince21298/SCRAPING | task3.py | import requests
from bs4 import BeautifulSoup
import json
import os.path
from os import path
import pprint
def scrap_top_list():
if os.path.exists("movie.json"):
with open ("movie.json",'r') as file:
read=file.read()
main_data=json.loads(read)
return(main_data)
else:
url=" https://www.imdb.com/india/top-... |
yapdianang/fast_transformer | onmt/modules/copy_generator.py | import math
import torch
import torch.nn as nn
from onmt.utils.misc import aeq
from onmt.utils.loss import LossComputeBase
def collapse_copy_scores(scores, batch, tgt_vocab, src_vocabs,
batch_dim=1, batch_offset=None):
"""
Given scores from an expanded dictionary
corresponeding t... |
yapdianang/fast_transformer | onmt/encoders/transformer.py | <reponame>yapdianang/fast_transformer<gh_stars>0
"""
Implementation of "Attention is All You Need"
"""
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.modules import MultiHeadedAttention
from onmt.modules import MultiHeadedStridedAttention
from onmt.modules.position_ffn import Positionwi... |
yapdianang/fast_transformer | onmt/modules/multi_headed_strided_attn.py | import math
import torch
import torch.nn as nn
from onmt.utils.misc import generate_relative_positions_matrix,\
relative_matmul
class MultiHeadedStridedAttention(nn.Module):
def __init__(self, head_count, model_dim, dropout=0.1,
max_relative_positions=0):
asse... |
Artemiche/polypy | poly.py | import colorsys
import ctypes
from itertools import product
from multiprocessing import Process, Array
from PIL import Image, ImageDraw, ImageFilter
import random
from scipy.spatial import Delaunay
import sys
# Global parameters that are not (yet) automatically computed
POINT_COUNT = 150
EDGE_THRESHOLD = 172
EDGE_RATI... |
brianjimenez/ant_thony | ant_thony.py | #!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Process, cpu_count
import argparse
import logging
import os
logging.basicConfig(format='[Ant-Thony] %(levelname)s: %(message)s', level=logging.DEBUG)
class Task(object):
"""A task class"""
def __init__(self, command, p... |
mofojed/deephaven-plugin-matplotlib | src/deephaven/plugin/matplotlib/__init__.py | from deephaven.plugin import Registration
__version__ = "0.0.1.dev5"
class MatplotlibRegistration(Registration):
@classmethod
def register_into(cls, callback: Registration.Callback) -> None:
from . import figure_type
callback.register(figure_type.FigureType)
|
mofojed/deephaven-plugin-matplotlib | src/deephaven/plugin/matplotlib/figure_type.py | <reponame>mofojed/deephaven-plugin-matplotlib<filename>src/deephaven/plugin/matplotlib/figure_type.py
from io import BytesIO
from matplotlib.figure import Figure
from deephaven.plugin.object import Exporter, ObjectType
NAME = "matplotlib.figure.Figure"
class FigureType(ObjectType):
@property
def name(self) ->... |
LSU-4444-AI/five-in-a-row-alpha-zero | plot.py | import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
from keras.callbacks import History
from policy_value_net_keras import his_path
from keras.utils import plot_model
# Model accuracy and loss plots
def plot_model_history(model_details):
# Create sub-plots
# fig, axs = plt.subplots(1, 2... |
mathieupoirier/rust-vmm-ci | integration_tests/conftest.py | <gh_stars>10-100
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import pytest
PROFILE_CI = "ci"
PROFILE_DEVEL = "devel"
WORKSPACE = "workspace"
CRATE = "crate"
def pytest_addoption(parser):
parser.addoption(
"--profile",
default=P... |
mathieupoirier/rust-vmm-ci | test_run.py | <reponame>mathieupoirier/rust-vmm-ci<filename>test_run.py
#!/usr/bin/env python3
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import json
import subprocess
import platform
import pathlib
import unittest
from argparse import ArgumentPar... |
mathieupoirier/rust-vmm-ci | integration_tests/test_commit_format.py | <gh_stars>10-100
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Test the commit message format.
This test works properly on the local machine only when the environment
variables REMOTE and BASE_BRANCH are set. Otherwise the default values
are "origin... |
mathieupoirier/rust-vmm-ci | integration_tests/test_benchmark.py | <gh_stars>10-100
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Compare benchmark results before and after a pull request.
This test works properly on the local machine only when the environment
variables REMOTE and BASE_BRANCH are set. Otherwise the... |
Mansouroopi/TDD | account/tests/test_models.py | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_new_user_with_email_successful(self):
email = '<EMAIL>'
password = '<PASSWORD>'
user = get_user_model().objects.create_user(
email=email,
pas... |
zkerhcy/dotfiles | i3/conky/volumelevel.py | <reponame>zkerhcy/dotfiles
#!/usr/bin/python
import alsaaudio
m = alsaaudio.Mixer() # defined alsaaudio.Mixer to change volume
vol = m.getvolume()
print vol
##!/bin/bash
#vol=`amixer get Master | awk -F'[]%[]' '/%/ {if ($7 == "off") { print "Mute" } else { print $2"%" }}' | uniq | head -1`
#echo "$vol"
|
hbergh/jlrpy | setup.py | <filename>setup.py<gh_stars>0
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="jlrpy",
version="1.1.2",
author="Edvard",
author_email="<EMAIL>",
description="Control your Jaguar I-Pace",
long_description=long_description,
long_d... |
plista/news_knowledge_tree | data_processing/googlenews.py | <gh_stars>0
from dotenv import load_dotenv
from pprint import pprint
from newsapi import NewsApiClient
import urllib
import os
from bs4 import BeautifulSoup
from readability import Document
from find_entity import find_entity
import pickle
import pandas as pd
from mysql_caching import set_cache_entities, get_cached_ent... |
plista/news_knowledge_tree | data_processing/mysql_caching.py | import pymysql
from typing import Set
import hashlib
from pymysql.cursors import Cursor
import json
db = pymysql.connect(host="db", user="root", password="password")
cursor = db.cursor()
try:
cursor.execute("CREATE DATABASE opendigitalworld")
except pymysql.err.ProgrammingError:
print("Database already exists... |
plista/news_knowledge_tree | backend/utility.py | <reponame>plista/news_knowledge_tree
import os
import pickle
from copy import deepcopy
import random
import json
from pandas import DataFrame
import pandas as pd
from typing import Tuple, Dict
import urllib
random.seed(30)
class NoValidArticle(Exception):
"""no article can be found with the given constraints"""
... |
plista/news_knowledge_tree | data_processing/find_entity.py | import functools
import sys
from typing import Set
import nltk
from flair.data import Sentence
from flair.models import SequenceTagger
from langdetect import detect
@functools.lru_cache(maxsize=1)
def get_tagger(language: str) -> SequenceTagger:
"""Return the tagger needed """
if language == "de":
re... |
plista/news_knowledge_tree | data_processing/main.py | <gh_stars>0
from flask_restplus import Resource, Api, fields
from flask import Flask, request, jsonify
from flask_restplus import reqparse
from googlenews import process_headlines
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
CORS(app)
interaction_model = api.model(
"interaction",
{
... |
moff4/gladius | db/tag_tag_map.py | <reponame>moff4/gladius
from pony import orm
from conf import conf
from .tag import Tag
class TagTagMap(conf.sql.Entity):
_table_ = ('hashtag', 'tag_tag_map')
tag1 = orm.Required(Tag, reverse='nears')
tag2 = orm.Required(Tag, reverse='nears_')
posts_num = orm.Required(float)
orm.PrimaryKey(tag1... |
moff4/gladius | tasks/server.py |
from conf import conf
from k2.aeon import Aeon
from sm import (
VecRelSM,
)
task_description = 'run web api'
def start():
server = Aeon(
namespace={
r'^/relevance': {
r'^/vecrel$': VecRelSM(),
},
},
**conf.aeon
)
server.run()
|
moff4/gladius | main.py | <gh_stars>0
#!/usr/bin/env python3.8
import sys
import asyncio
from k2.logger import BaseLogger as logger
from conf import conf
from tasks import TASKS
HELP_MSG = '''
Gladius - recomendation system
$ ./main.py [commands] [flags]
Flags:
-h, --help, -? - see this msg again
-s, --server - start web-server
--crea... |
moff4/gladius | logic/rank/ext.py | #!/usr/bin/env python3
import ctypes
import numpy.linalg
import random
mod = ctypes.CDLL(r'ext/utils.so')
"""
double interpolice(double, double* , double*,int);
"""
__interpolice = ctypes.CFUNCTYPE(
ctypes.c_double,
ctypes.c_double,
ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double),... |
moff4/gladius | db/path.py | <filename>db/path.py
from pony import orm
from conf import conf
from .tag import Tag
class Path(conf.sql.Entity):
_table_ = ('hashtag', 'path')
src = orm.Required(Tag, reverse='path_src')
dst = orm.Required(Tag, reverse='path_dst')
tag = orm.Required(Tag, reverse='path_in')
pos = orm.Required(i... |
moff4/gladius | logic/rank/__init__.py | <reponame>moff4/gladius
from .rank import ranks
__all__ = [
'ranks',
]
|
moff4/gladius | tasks/__init__.py | from tasks import shell
from tasks import server
from tasks import ranks
from tasks import clustering
from tasks import pather
from tasks import graph
from tasks import node2vec
TASKS = {
'shell': shell,
'server': server,
'ranks': ranks,
'clustering': clustering,
'pather': pather,
'graph': grap... |
moff4/gladius | tasks/pather.py | <reponame>moff4/gladius
import asyncio
import random
from pony import orm
import networkx as nx
from k2.logger import new_channel
from conf import conf
from logic import GRAPH
from db import Tag, Path
from utils import parse_args
from utils.parallel import parallel_run
ARGS = {
'limit': None,
}
logger = new_ch... |
moff4/gladius | logic/__init__.py |
from .rank import ranks
from .clustering import Clustering
from .graph import Graph, GRAPH
from .cursach import Cursach
__all__ = [
'ranks',
'Clustering',
'Graph',
'GRAPH',
'Cursach',
]
|
moff4/gladius | db/tag.py | from datetime import datetime
from pony import orm
from conf import conf
class Tag(conf.sql.Entity):
_table_ = ('hashtag', 'tag')
tag = orm.PrimaryKey(str)
created = orm.Optional(datetime)
checked = orm.Optional(int)
rank_pop = orm.Optional(float, nullable=True)
rank_qual = orm.Optional(floa... |
moff4/gladius | tasks/clustering.py | import asyncio
from pony import orm
from k2.logger import new_channel
from conf import conf
from db import Tag
from logic import Clustering
from utils import parse_args
from utils.parallel import parallel_run
ARGS = {
'dry': False,
'limit': None,
'tag': None,
'reverse': None,
}
logger = new_channel... |
moff4/gladius | logic/narrowness.py |
from typing import List
from logic.graph import GRAPH
def narrowness(tags: List[str]) -> float:
if not tags:
return 1.0
GRAPH.multi_weight(
(src, dst)
for src in tags
for dst in tags
)
res = (
sum(
weights := [
GRAPH.weight(src, ds... |
moff4/gladius | logic/graph.py | import json
from typing import Iterable, Tuple, List
import networkx as nx
from k2.logger import new_channel
from conf import conf
from utils.parallel import parallel_run
def worker(q_in, q_out):
graph = GRAPH.graph
while (args := q_in.get()) is not None:
src, dst = args
try:
q_o... |
moff4/gladius | db/rought.py |
from pony import orm
from conf import conf
class Rought(conf.sql.Entity):
_table_ = ('hashtag', 'rought')
tag1 = orm.Required(str)
tag2 = orm.Required(str)
weight = orm.Required(float)
orm.PrimaryKey(tag1, tag2)
@staticmethod
def create_multi(roughts):
if roughts:
s... |
moff4/gladius | tasks/graph.py | import asyncio
from pony import orm
from k2.logger import new_channel
from conf import conf
from db import TagTagMap
logger = new_channel('graph-dump')
task_description = 'dump graph to file (for clustering & pather)'
async def dump():
done = 0
try:
with orm.db_session:
await logger.inf... |
moff4/gladius | utils/__init__.py | <gh_stars>0
import sys
def parse_args(default_args):
args = dict(default_args)
for arg in sys.argv[1:]:
for key in args:
if arg.startswith('--{}'.format(key)):
arg = arg[len(key) + 2:]
args[key] = arg[1:] if arg.startswith('=') else True
return args
|
moff4/gladius | db/__init__.py |
from .tag import Tag
from .post import Post
from .rought import Rought
from .post_tag import PostTag
from .tag_tag_map import TagTagMap
from .path import Path
__all__ = [
'Tag',
'Post',
'Rought',
'PostTag',
'TagTagMap',
'Path',
]
|
moff4/gladius | db/post_tag.py | from pony import orm
from datetime import datetime
from conf import conf
from .post import Post
from .tag import Tag
class PostTag(conf.sql.Entity):
_table_ = ('hashtag', 'post_tag')
post = orm.Required(Post, reverse='tags')
tag = orm.Required(Tag, reverse='posts')
created = orm.Optional(datetime)
... |
moff4/gladius | logic/clustering.py |
from collections import defaultdict
from conf import conf
SQL_LOAD_NEAREST = '''
SELECT distinct pt1.tag, pt2.tag
FROM (
select *
from hashtag.post_tag
where tag in (%s)
) pt1 inner join hashtag.post_tag pt2 on pt1.post = pt2.post
and pt1.tag != pt2.tag
'''
LOAD_LIMIT = 50
class Clustering:
def _... |
moff4/gladius | tasks/ranks.py | import math
import asyncio
from pony import orm
from multiprocessing.pool import Pool
from k2.logger import new_channel
from conf import conf
from db import (
Tag,
PostTag,
)
from logic import ranks
from utils import parse_args
logger = new_channel('ranks')
ARGS = {
'dry': False,
'tags': None,
'... |
moff4/gladius | sm/vecrel.py | <reponame>moff4/gladius
from k2.aeon.sitemodules import (
AuthSM,
RestSM,
)
from conf import conf
from logic import Cursach
ALG_MAP = {
'mindminer': {
'func': (cursach := Cursach()).relevanse,
'params': {},
},
'rankedminer': {
'func': cursach.ranked_relevanse,
'pa... |
moff4/gladius | utils/parallel.py | import time
from multiprocessing import Process, Queue
from typing import List, Callable
async def parallel_run(itr: List, handler: Callable, worker: Callable, proc_num: int):
async def read(q):
x = 0
while not q.empty():
res = q.get()
x += 1
await handler(res)
... |
moff4/gladius | logic/rank/rank.py | #!/user/bin/env python3
import math
import time
from conf import conf
from .wr import (
interpolice,
WeightRandom,
WR_params,
)
LOOPS_MAP = {}
for i in range(10):
LOOPS_MAP[i] = 50
for i in range(10, 50):
LOOPS_MAP[i] = 10
for i in range(50, 100):
LOOPS_MAP[i] = 5
def f(_time) -> float:
... |
moff4/gladius | sm/__init__.py | <gh_stars>0
from .vecrel import VecRelSM
__all__ = [
'VecRelSM',
]
|
moff4/gladius | logic/cursach.py | <filename>logic/cursach.py
from typing import Any, List, Dict
from pony import orm
from k2.logger import new_channel
from db import Tag
from .graph import GRAPH
class Cursach:
def __init__(self):
self.logger = new_channel('cursach')
async def prepare(self, cases: Dict[str, Any]):
await GRA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.