repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
everydaytimmy/data-structures-and-algorithms
python/code_challenges/depth_first_graph/depth_first_graph.py
from code_challenges.graph.graph import Graph, Vertex def depth_traversal(node, graph): visited = set() stack = Stack() nodes = [] stack.push(node) while stack.top: current = stack.pop() nodes.append(current) neighbors = graph.get_neighbors(current) if neighbors: ...
everydaytimmy/data-structures-and-algorithms
python/tests/test_breadth_first.py
from code_challenges.breadth_first.breadth_first import Node, BinaryTree def test_node_has_value(): node = Node("apple") assert node.value == "apple" def test_node_has_left_of_none(): node = Node("apple") assert node.left is None def test_node_has_right_of_none(): node = Node("apple") asser...
everydaytimmy/data-structures-and-algorithms
python/tests/test_hashmap_tree_intersection.py
from code_challenges.hashmap_tree_intersection.hashmap_tree_intersection import tree_intersection from code_challenges.tree.tree import Node, BinaryTree, BinarySearchTree def test__tree_compare(): tree1 = BinarySearchTree() tree1.add(5) tree1.add(2) tree1.add(3) tree2 = BinarySearchTree() tree...
everydaytimmy/data-structures-and-algorithms
python/tests/test_animal_shelter.py
from code_challenges.fifo_animal_shelter.fifo_animal_shelter import Cat, Dog, Queue, AnimalShelter def test_single_animal(): shelter = AnimalShelter() cat = Cat() shelter.enqueue(cat) actual = shelter.dequeue("cat") expected = cat assert actual == expected def test_animal_dequeue(): shel...
everydaytimmy/data-structures-and-algorithms
python/code_challenges/quick_sort/quick_sort.py
def partition(start, end, array): pivot_index = start pivot = array[pivot_index] while start < end: while start < len(array) and array[start] <= pivot: start += 1 while array[end] > pivot: end -= 1 if(start < end): array[start], array[end] = arr...
everydaytimmy/data-structures-and-algorithms
python/tests/test_merge_sort.py
<filename>python/tests/test_merge_sort.py from code_challenges.merge_sort.merge_sort import merge_sort, merge def test_merge(): assert merge_sort def test_merge1(): actual = merge_sort([8,4,23,42,16,15]) expected = [4,8,15,16,23,42] assert actual == expected def test_merge2(): actual = merge_sort...
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/utility.py
<gh_stars>0 import matplotlib.pyplot as plt import matplotlib.animation as animation import datetime as dt def graph_it(x, y, x_text, y_text, title): plt.plot(x, y) plt.xlabel(x_text) plt.ylabel(y_text) plt.title
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/RnDGui.py
<reponame>mVolpe94/Pellet-Stove-Automation<filename>TestingEnvironment/RnDGui.py # import RPi.GPIO as gpio import time, os, sys, re import matplotlib.pyplot as plt import utility import mainprocess from tkinter import * from tkinter import ttk augers = 5 starter = 6 convection_blower = 13 combustion_blower = 21 room_a...
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/testtimer.py
<reponame>mVolpe94/Pellet-Stove-Automation import time x = 0 start = time.time() print(start) while x < 10000000: x += 1 end = time.time() print(end) print(end-start)
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/testfileread.py
import os, re temp_file = open("TestingEnvironment/temptest.txt") lines = temp_file.readlines() temp_line = lines[1] p = re.compile(r"[t][=](\d*)") result = p.search(lines[1]) temp = result.group(1) temp = int(temp) / 1000 temp = 9/5 * temp + 32 print(temp)
mVolpe94/Pellet-Stove-Automation
setup-noGUI.py
<reponame>mVolpe94/Pellet-Stove-Automation #import RPi.GPIO as gpio import time, os, sys from threading import Thread from tkinter import * from tkinter import ttk #tasks # When room temp is lower than set temperature, activate heat exchange blower, add pellets # If heat exchange intake delta t is low, increase feul ...
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/tempprocess.py
def temp(): x = 0 while x < 10: x += 1
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/threadtest.py
import mainprocess import os from multiprocessing import Process, Pipe # to use multiple pipes with one function, must define new connection names # and call the recieve for each # must have a pipeline for each sensor used if __name__ == '__main__': os.system('modprobe w1-gpio') os.system('modprobe w1-therm...
mVolpe94/Pellet-Stove-Automation
setup.py
<reponame>mVolpe94/Pellet-Stove-Automation<filename>setup.py #import RPi.GPIO as gpio import time, os, sys from tkinter import * from tkinter import ttk #tasks # When room temp is lower than set temperature, activate heat exchange blower, add pellets # If heat exchange intake delta t is low, increase feul into burn p...
mVolpe94/Pellet-Stove-Automation
TestingEnvironment/mainprocess.py
<reponame>mVolpe94/Pellet-Stove-Automation from multiprocessing import Process, Pipe import time, os, sys, re def read_temp(): temp_file = open("TestingEnvironment/temptest.txt") lines = temp_file.readlines() p = re.compile(r"[t][=](\d*)") result = p.search(lines[1]) room_air_temp = result.group(1)...
maknotavailable/uplabel
code/log.py
""" Log labeling iterations and metrics Local or from blob storage. """ import json from pathlib import Path class Log(): def __init__(self, fn): self.fn = fn self.logs = [] def read_log(self): """load or create logs""" if Path(self.fn).is_file(): with open(self.fn...
louisopen/Ethernet2uart
app_device.py
#!/usr/bin/env python #coding= utf-8 from ConsoleThreading import * from flask import Flask, render_template, Response, request, redirect, jsonify import json app = Flask(__name__) Model='Web2uart Control' nameing = [{"id": 1, "name": "CHIPS", "done": False}, {"id": 2, "name": "garden", "done": False}] #json def Ch...
louisopen/Ethernet2uart
ConsoleThreading.py
<gh_stars>1-10 #!/usr/bin/env python #coding= utf-8 import serial import serial.tools.list_ports from threading import Thread import time, os, sys, datetime #=========================================================================== class SerialTask: def __init__(self, p_ch, baud): self._running = False #True is f...
louisopen/Ethernet2uart
app.py
#!/usr/bin/env python #coding= utf-8 from app_device import * from flask import Flask, render_template, Response, request, redirect import os # home page @app.route('/') @app.route('/index') @app.route('/index.html') def index(): return render_template('index.html') if __name__ == '__main__': app.run(host=...
dchemishanov/GDrive-Access-Monitor
gdam.py
<reponame>dchemishanov/GDrive-Access-Monitor<filename>gdam.py # -*- coding: utf-8 -*- #from __future__ import print_function """ Google Drive Access Monitor This script is based on the Google's quick start guide to Google Drive API: https://developers.google.com/drive/v3/web/quickstart/python It uses the Oauth2 authent...
FelixMohr/terratrader
src/trading_core.py
<filename>src/trading_core.py from typing import Dict from terra_sdk.client.lcd import LCDClient, Wallet from terra_sdk.core import Coins from terra_sdk.core.auth import StdFee, StdTx from terra_sdk.core.broadcast import BlockTxBroadcastResult from terra_sdk.core.wasm import MsgExecuteContract from src import const f...
FelixMohr/terratrader
cli.py
import terra_sdk import sys from src.trading_core import get_bluna_for_luna_price, get_luna_for_bluna_price, buy, sell from src.helpers import create_params, info, create_terra, create_wallet, warn, from_u_unit, get_arg_safe from src import bot, const def main(): with open("files/greeting.txt") as f: con...
FelixMohr/terratrader
src/helpers.py
from typing import List, Union import datetime import terra_sdk.client.lcd from halo import Halo from terra_sdk.core import Coins from src import const from src.params import Params from terra_sdk.client.lcd import LCDClient, Wallet from terra_sdk.key.raw import RawKey import os import time import requests def crea...
FelixMohr/terratrader
src/const.py
<reponame>FelixMohr/terratrader # ----------- trading ----------- # luna bLuna pair in terra swap luna_bluna = "terra1jxazgm67et0ce260kvrpfv50acuushpjsz2y0p" bluna_contract = "<KEY>" luna_info = { "native_token": { "denom": "uluna" } } # has contract address of bLuna token bluna_info = { "to...
FelixMohr/terratrader
src/loans_core.py
from terra_sdk.client.lcd import Wallet from terra_sdk.core import Coins, Coin from terra_sdk.core.wasm import MsgExecuteContract from src import const from src.helpers import info, to_u_unit, get_infos_from_url, from_u_unit, warn from src.messages import get_borrower_info_msg, get_borrow_limit_uust_from_msg, get_loan...
FelixMohr/terratrader
src/bot.py
from time import sleep from terra_sdk.client.lcd import LCDClient, Wallet from src.trading_core import get_bluna_for_luna_price, buy, get_luna_for_bluna_price, sell from src.loans_core import get_loan_uust, get_borrow_limit_uust, execute_repay from src.params import Params from src.helpers import info, get_system_tim...
FelixMohr/terratrader
src/params.py
from src import const class Params(object): def __init__(self): self.amount_luna = 1.0 self.amount_bluna = 1.0 self.inv_sell_price = 0.985 self.buy_price = 0.975 self.mode = const.buy self.spread = 0.007 self.sleep_time_seconds = 3 self.sleep_time_l...
FelixMohr/terratrader
src/messages.py
<reponame>FelixMohr/terratrader import base64 from typing import Dict from src import const from src.helpers import to_u_unit from src.params import Params def get_borrower_info_msg(borrower_address: str) -> Dict: return { "borrower_info": {"borrower": borrower_address} } def get_loan_uust_from_msg...
nappernick/envelope
app/api/user_routes.py
from datetime import datetime from werkzeug.security import generate_password_hash from flask import Blueprint, jsonify, request from sqlalchemy.orm import joinedload from flask_login import login_required from app.models import db, User, Type from app.forms import UpdateUserForm from .auth_routes import authenticate, ...
nappernick/envelope
app/api/alt_envelope_api.py
<reponame>nappernick/envelope import pandas as pd import csv import tempfile import pysurveycto # # SAM ORIGINAL # # Get data from SurveyCTO API scto = pysurveycto.SurveyCTOObject('envelope', '<EMAIL>', 'Envelope-VisX') raw = scto.get_form_data('NORC-IGA-Endline-Menage') # # Change Directory # import os # os.chdir(r"...
nappernick/envelope
app/api/__init__.py
<reponame>nappernick/envelope from .auth_routes import validation_errors_to_error_messages
nappernick/envelope
app/api/data_set_routes.py
<gh_stars>1-10 import os import csv import zipfile import pickle import threading import pandas as pd import numpy as np import sys # For API import pysurveycto # Redis queue from rq import Queue from rq.job import Job from app.redis import conn # File reading utility from io import BytesIO from datetime import dateti...
nappernick/envelope
app/seeds/types.py
from app.models import db, Type def seed_types(): admin = Type(type="Admin") client = Type(type="Client") lb = Type(type="Low Bandwidth") db.session.add(admin) db.session.add(client) db.session.add(lb) db.session.commit() def undo_types(): db.session.execute('TRUNCATE TABLE types RES...
nappernick/envelope
app/api/playing_with_redis.py
<filename>app/api/playing_with_redis.py<gh_stars>1-10 # Redis job queue q = Queue(connection=conn) @data_set_routes.route('/data-sets') @login_required def data(): curr_user = current_user.to_dict() if curr_user["type_id"] == 1: data = db.session.query(DataSet).all() return jsonify([data_set.t...
nappernick/envelope
app/seeds/__init__.py
<filename>app/seeds/__init__.py<gh_stars>1-10 from flask.cli import AppGroup from .users import seed_users, undo_users from .types import seed_types, undo_types from .data_sets import seed_data_sets, undo_data_sets from .projects import seed_projects, undo_projects from .health_areas import seed_health_areas, undo_heal...
nappernick/envelope
app/seeds/data_sets.py
<reponame>nappernick/envelope from app.models import db, DataSet import csv import pickle def seed_data_sets(): # with open('/Users/nicholasmatthews/Library/Mobile Documents/com~apple~CloudDocs/app_academy/capstone/envelope/app/seeds/seed_survey.csv') as csvfile: with open('/var/www/app/seeds/seed_survey.csv')...
nappernick/envelope
app/forms/project_form.py
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField from wtforms.validators import DataRequired, ValidationError from app.models import db, Project def project_name_unique(form, field): name = field.data project = db.session.query(Project).filter(Project.project_name == name).first()...
nappernick/envelope
app/seeds/surveys.py
<reponame>nappernick/envelope<gh_stars>1-10 from app.models import db, Survey from app.api.data_processing import data_processing_for_survey_records from faker import Faker fake = Faker() def seed_surveys(): # surveys = data_processing_for_survey_records("/Users/nicholasmatthews/Library/Mobile Documents/com~apple...
nappernick/envelope
app/__init__.py
<reponame>nappernick/envelope import os from flask import Flask, render_template, request, session from flask_cors import CORS from flask_migrate import Migrate from flask_wtf.csrf import CSRFProtect, generate_csrf from flask_login import LoginManager from .models import db, User from .api.user_routes import user_rout...
nappernick/envelope
app/forms/__init__.py
<filename>app/forms/__init__.py from .login_form import LoginForm from .signup_form import SignUpForm from .project_form import ProjectForm from .update_user_form import UpdateUserForm
nappernick/envelope
app/seeds/projects.py
<reponame>nappernick/envelope from app.models import db, Project def seed_projects(): project1 = Project( project_name="NORC Clean Water", project_notes="", data_set_id=1, user_id=2, target_health_area_count=172, target_surv_count=24, survey_count=1884, ...
nappernick/envelope
app/models/data_set.py
from .db import db class DataSet(db.Model): __tablename__ = "data_sets" id = db.Column(db.Integer, primary_key = True, index=True) data_set_name = db.Column(db.String(100), nullable = False, unique = True, index=True) data_set = db.Column(db.LargeBinary, nullable = False) created_at = db.Column(db...
nappernick/envelope
app/models/health_area.py
from .db import db class HealthArea(db.Model): __tablename__ = "health_areas" id = db.Column(db.Integer, primary_key = True) health_area = db.Column(db.String(100), nullable = False, unique = True) ha_surveys = db.relationship("Survey", backref="health_area") def to_dict(self): return { ...
nappernick/envelope
app/seeds/users.py
from app.models import db, User # Adds a demo user, you can add other users here if you want def seed_users(): demo = User(username='demo', email='<EMAIL>', password='password', first_name='Demo', last_name='User', type_id=1) db.session.add(demo) demo1 = User(username='billyblanks', email=...
nappernick/envelope
app/seeds/health_areas.py
from app.models import db, HealthArea from app.api.data_processing import data_processing_for_health_areas def seed_health_areas(): health_areas = data_processing_for_health_areas("/var/www/app/seeds/seed_survey.csv") # health_areas = data_processing_for_health_areas("/Users/nicholasmatthews/Library/Mobile Doc...
nappernick/envelope
app/forms/update_user_form.py
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, PasswordField from wtforms.validators import DataRequired, Email, ValidationError from app.models import User class UpdateUserForm(FlaskForm): username = StringField('username', validators=[DataRequired()]) email = StringField('ema...
nappernick/envelope
app/api/scratch.py
import csv import os import pandas as pd def dta_to_pickle(dta): data = pd.io.stata.read_stata(dta) csv_file = data.to_csv() file_final = pickle.dumps(csv_file) return file_final def zip_to_pickle(zip): zipfile_ob = zipfile.ZipFile(file_like_object) file_names = zipfile_ob.namelist() file_...
nappernick/envelope
app/redis/__init__.py
<filename>app/redis/__init__.py from .redis_worker import conn
nappernick/envelope
app/models/type.py
<gh_stars>1-10 from .db import db class Type(db.Model): __tablename__ = "types" id = db.Column(db.Integer, primary_key = True) type = db.Column(db.String(40), nullable = False, unique = True) db.relationship("User", backref="type") def to_dict(self): return { "id": self.id, ...
nappernick/envelope
app/api/project_routes.py
import pickle import threading from faker import Faker from datetime import datetime from flask import Blueprint, jsonify, session, request from flask_login import current_user, login_required from datetime import datetime from app.forms import ProjectForm from app.models import Project, User, DataSet, Survey, db from ...
nappernick/envelope
app/models/user.py
from .db import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) first_name = db.Column(db.String(40), nullable = False) last_name = db.Column(d...
nappernick/envelope
app/models/project.py
<reponame>nappernick/envelope from .db import db class Project(db.Model): __tablename__ = "projects" id = db.Column(db.Integer, primary_key = True) project_name = db.Column(db.String(100), nullable = False, unique = True) project_notes = db.Column(db.Text, nullable = True) data_set_id = db.Column(...
nappernick/envelope
app/api/survey_routes.py
from flask import Blueprint, jsonify, session, request from flask_login import current_user, login_required from app.models import Survey, db survey_routes = Blueprint("surveys", __name__) @survey_routes.route("/") @login_required def all_surveys(): curr_user = current_user.to_dict() if curr_user["type_id"] ...
nappernick/envelope
app/models/__init__.py
from .db import db from .user import User from .type import Type from .data_set import DataSet from .project import Project from .survey import Survey from .health_area import HealthArea from .survey_question import SurveyQuestion
nappernick/envelope
app/models/survey.py
from .db import db from sqlalchemy.orm import load_only class Survey(db.Model): __tablename__ = "surveys" id = db.Column(db.Integer, primary_key = True, index=True) health_area_id = db.Column(db.Integer, db.ForeignKey("health_areas.id"), nullable = False, index=True) project_id = db.Column(db.Integer,...
nappernick/envelope
app/api/data_processing.py
<reponame>nappernick/envelope<gh_stars>1-10 import csv import os import tempfile import pandas as pd def dta_to_pickle(dta): data = pd.io.stata.read_stata(dta) csv_file = data.to_csv() file_final = pickle.dumps(csv_file) return file_final def zip_to_pickle(zip): zipfile_ob = zipfile.ZipFile(file_l...
nappernick/envelope
app/api/envelope_api.py
import pysurveycto import requests import json import pandas as pd # Get data from SurveyCTO API scto = pysurveycto.SurveyCTOObject('envelope', '<EMAIL>', 'Envelope-VisX') raw = scto.get_form_data('NORC-IGA-Endline-Menage') # Change Directory import os os.chdir(r"/Users/nicholasmatthews/Library/Mobile Documents/com~a...
nappernick/envelope
migrations/versions/20210124_012014_.py
<gh_stars>1-10 """empty message Revision ID: 26cae0588639 Revises: Create Date: 2021-01-24 01:20:14.782725 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands a...
nappernick/envelope
app/models/survey_question.py
from .db import db class SurveyQuestion(db.Model): __tablename__ = "survey_questions" id = db.Column(db.Integer, primary_key = True) survey_id = db.Column(db.Integer, db.ForeignKey("surveys.id"), nullable = False) question = db.Column(db.String(), nullable = False) value = db.Column(db.String(), n...
iflb/neji-finder-tutti-client-python
example.py
<reponame>iflb/neji-finder-tutti-client-python import sys import asyncio from neji_finder_tutti_client import NejiFinderTuttiClient async def on_response(data): print('Data received! (watch_id: {})'.format(data['last_watch_id'])) print(data) async def on_error(msg): print('on_error', msg) async def main...
iflb/neji-finder-tutti-client-python
neji_finder_tutti_client/main.py
<reponame>iflb/neji-finder-tutti-client-python import asyncio from typing import Optional, Tuple, Callable from tutti_client import TuttiClient from ducts_client import Duct from .market_controller import TuttiMarketController class NejiFinderTuttiClientConnectionError(Exception): def __init__(self, resource, err...
iflb/neji-finder-tutti-client-python
neji_finder_tutti_client/market_controller.py
<gh_stars>0 from typing import Optional import hashlib class TuttiMarketController: '''Tutti.marketに関連する操作を行うオブジェクトです。 現状、必要最低限のメソッド群のみを定義しています。JavaScriptにおいて既に `こちら`_ に定義された 操作のうち、このクラスに実装が必要なものは別途問い合わせてください。 .. _こちら: https://github.com/iflb/tutti-market/blob/a4b6b9054183f761a1692ff9633a84e8...
thomasxmeng/Simple-neural-network-and-linear-regression-analysis-on-avocado-data-in-US
linearReg.py
<reponame>thomasxmeng/Simple-neural-network-and-linear-regression-analysis-on-avocado-data-in-US<gh_stars>0 import numpy as np class LinearRegression(object): def __init__(self, X, y, theta, lambdaa): # Set number of nodes in input, hidden and output layers. self.X = X self.y = y s...
hermagrini/pochoclo-system
api/models/movimiento_model.py
from google.appengine.ext import ndb from google.appengine.ext.ndb.key import Key from api.lib.custom_handler import improve from api.lib.date_handler import date_handler from api.lib.bottle import json_dumps class Movimiento(ndb.Model): tipo = ndb.StringProperty() monto = ndb.IntegerProperty() ...
hermagrini/pochoclo-system
api/lib/custom_handler.py
from google.appengine.ext import ndb def improve(result, identificador = ""): #explota con las sesiones result["id"] = identificador for key, value in result.iteritems(): if type(value) is list: i = 0 for item in value: if isinstance(item,ndb.Key): ...
hermagrini/pochoclo-system
api/tipo.py
# coding: utf-8 -- from api.lib import bottle from api.lib.bottle import * from api.models.tipo_model import Tipo from json import dumps def initRoutes(app=None): if not app: app = bottle.default_app() @app.route('/tipo/traerListaTipos', method='POST') #testeado y andando! def getPost...
hermagrini/pochoclo-system
api/rubro.py
# coding: utf-8 -- from api.lib import bottle from api.lib.bottle import * from api.models.rubro_model import Rubro from json import dumps def initRoutes(app=None): if not app: app = bottle.default_app() @app.route('/rubro/traerListaRubros', method='POST') #testeado y andando! def get...
hermagrini/pochoclo-system
api/asientos.py
# coding: utf-8 -- from api.lib import bottle from api.lib.bottle import * from api.models.movimiento_model import Cuenta, Movimiento, Asiento def initRoutes(app=None): if not app: app = bottle.default_app() @app.route('/cuenta/traerListaCuentas', method='POST') def getCuentaList(): ...
hermagrini/pochoclo-system
api/models/tipo_model.py
from google.appengine.ext import ndb from google.appengine.ext.ndb.key import Key from api.lib.custom_handler import improve from api.lib.bottle import json_dumps class Tipo(ndb.Model): nombre = ndb.StringProperty(required=True) @classmethod def get_all_json(self): return json_dumps([imp...
hermagrini/pochoclo-system
api/lib/date_handler.py
<filename>api/lib/date_handler.py def date_handler(obj): return obj.isoformat() if hasattr(obj, 'isoformat') else obj
hermagrini/pochoclo-system
api/models/__init__.py
<reponame>hermagrini/pochoclo-system __author__ = 'Hernan'
hermagrini/pochoclo-system
api/lib/__init__.py
<reponame>hermagrini/pochoclo-system<gh_stars>0 __author__ = 'heborlz'
hermagrini/pochoclo-system
main.py
<gh_stars>0 # coding: utf-8 -- from api.lib import bottle from api.lib.bottle import * from api import tipo,asientos,rubro # Si vamos a tener por separado los handlers, aca no deberiamos importar modelos :P # from api.models import * app = bottle.Bottle({'mode': 'development'}) response.content_type = 'application/js...
Huanyu2019/Seedsortnet
model/seedsortnet.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 12 15:44:11 2021 @author: lihuanyu """ import torch.nn as nn import torch import math import torchsummary as summary from torchstat import stat import torch.nn.functional as F from blurpool import BlurPool __all__ = ["seedsortnet","seedsortnet75"]...
lopuhin/WSI-LDA
w2v.py
<reponame>lopuhin/WSI-LDA #!/usr/bin/env python import argparse from collections import defaultdict, Counter import numpy as np from gensim.models import Word2Vec import kmeans import utils def word_clusters_neighbours(w2v, word, n_senses, *, window): assert window similar = w2v.most_similar(positive=[word]...
lopuhin/WSI-LDA
run_adagram.py
#!/usr/bin/env python import json import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('filename') args = parser.parse_args() with open(args.filename) as f: data = json.load(f) for word, senses in sorted(data.items()): print() print(word) ...
lopuhin/WSI-LDA
kmeans.py
# kmeans.py using any of the 20-odd metrics in scipy.spatial.distance # kmeanssample 2 pass, first sample sqrt(N) import random import logging import numpy as np from scipy.spatial.distance import cdist # $scipy/spatial/distance.py # http://docs.scipy.org/doc/scipy/reference/spatial.html from scipy.sparse import...
lopuhin/WSI-LDA
tf_embeddings.py
import argparse from pathlib import Path from typing import List import adagram import numpy as np import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector def main(): parser = argparse.ArgumentParser() arg = parser.add_argument arg('model') arg('output') arg('--anchor...
lopuhin/WSI-LDA
lda.py
<reponame>lopuhin/WSI-LDA<filename>lda.py #!/usr/bin/env python import logging import argparse import os.path import numpy as np from gensim.models import LdaModel import rl_wsd_labeled from sklearn.metrics import v_measure_score, adjusted_rand_score import utils def word_lda(word, num_topics, window, limit=None): ...
lopuhin/WSI-LDA
lsi.py
<reponame>lopuhin/WSI-LDA #!/usr/bin/env python import logging import argparse from gensim.models.lsimodel import LsiModel import utils def word_lsi(word, num_topics, window, limit=None): dictionary, corpus, _ = \ utils.prepare_corpus(word, window=window, limit=limit) lsi = LsiModel(corpus, id2word=...
lopuhin/WSI-LDA
utils.py
<filename>utils.py import os.path import random import re from functools import partial from concurrent.futures import ProcessPoolExecutor from collections import defaultdict from gensim import corpora import pymystem3 from sklearn.metrics.pairwise import cosine_similarity all_words = [ # multiple dictionary sen...
lopuhin/WSI-LDA
hdp.py
#!/usr/bin/env python import logging import argparse from gensim.models import HdpModel import utils def word_hdp(word, *, window, limit=None): dictionary, corpus, _ = \ utils.prepare_corpus(word, window=window, limit=limit) hdp = HdpModel(corpus, id2word=dictionary) return hdp def run_all(*, ...
Egolas/gpu-statistics
mysql_utils.py
import sqlite3 import time from datetime import date, datetime, time from typing import Union import mysql.connector def insert_database(path: str, table: str, data: dict): database = sqlite3.connect(path) keys = ', '.join(data.keys()) holder = ', '.join(['?'] * len(data.keys())) command = f'insert in...
Egolas/gpu-statistics
gpu-statistics.py
<reponame>Egolas/gpu-statistics import os import json import time from mysql_utils import auto_insert_database host_name = 'hostname' # input your hostname # input database config database_config = { 'user': 'user', 'password': 'password', 'host': '0.0.0.0', 'database': 'gpustat', 'raise_on_warnin...
Benjamin-Lee/branchpro
branchpro/tests/__init__.py
<gh_stars>1-10 # # Test module for branchpro. # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for copyright # notice and full license details. # # To run all tests, use ``python -m unittest disco...
Benjamin-Lee/branchpro
branchpro/__init__.py
<reponame>Benjamin-Lee/branchpro # # Root of the branchpro module. # Provides access to all shared functionality (models, simulation, etc.). # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for co...
Benjamin-Lee/branchpro
run-tests.py
# This file contains code for running all tests. # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for copyright # notice and full license details. # import unittest import os import sys import ar...
Benjamin-Lee/branchpro
branchpro/tests/test_models.py
<reponame>Benjamin-Lee/branchpro # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for copyright # notice and full license details. # import unittest import branchpro as bp class TestForwardMode...
Benjamin-Lee/branchpro
branchpro/models.py
<filename>branchpro/models.py # # ForwardModel Class # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for copyright # notice and full license details. # class ForwardModel(object): """Forwar...
Benjamin-Lee/branchpro
branchpro/version_info.py
<filename>branchpro/version_info.py # # Version information for pkmodel. # # This file is part of BRANCHPRO # (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released # under the BSD 3-clause license. See accompanying LICENSE.md for copyright # notice and full license details. # # See: https://packagin...
angelosalton/pySGS
sgs/common.py
<reponame>angelosalton/pySGS<filename>sgs/common.py """ Shared functions. """ from datetime import datetime import locale import re from typing import Union import os LRU_CACHE_SIZE = 32 MAX_ATTEMPT_NUMBER = 5 def to_datetime(date_string: str, language: str) -> Union[datetime, str]: """ Converts a date string t...
Yu-Chuan/Survival-and-death-model
survial_death_model_conc.py
# -*- coding: utf-8 -*- """ Created on Fri Nov 27 15:32:42 2020 @author: b308 <NAME> """ import numpy as np import matplotlib.pyplot as plt import os #variable name si = ['TNF', 'TNFR1', 'TNFR1a' , 'TRADD', 'TNFR1a_TRADD', 'TRAF2', 'early_complex', 'RIPK1','early_complex_RIPK1', 'IKK...
Yu-Chuan/Survival-and-death-model
survival_death_model_CLE_multiple.py
<filename>survival_death_model_CLE_multiple.py # -*- coding: utf-8 -*- """ Created on Fri Nov 27 15:32:42 2020 @author: b308 """ import numpy as np import multiprocessing as mp from functools import partial import time si = ['TNF', 'TNFR1', 'TNFR1a' , 'TRADD', 'TNFR1a_TRADD', 'TRAF2', 'early_complex', ...
Yu-Chuan/Survival-and-death-model
read_survial_death _model_multiple.py
<filename>read_survial_death _model_multiple.py # -*- coding: utf-8 -*- """ Created on Mon Dec 7 09:21:46 2020 @author: b308 """ import numpy as np import matplotlib.pyplot as plt import os # create the folder for npy and results path = "/Yu-Chuan/ForYuChuan/python program/survial_death_model/CLE/multip...
WilliamOnVoyage/MontyHallSimulation
goat.py
<reponame>WilliamOnVoyage/MontyHallSimulation import random from argparse import ArgumentParser import sys DEFAULT_TRIES = 100000 DEFAULT_SEED = 1234 def setup_args(): parser = ArgumentParser(description="Simulates the probability of getting car in Monty Hall problem") parser.add_argument("-n", "--number-of-...
iafisher/precommit
precommit.py
<gh_stars>1-10 from precommitlib import checks def init(precommit): # Generic checks precommit.check(checks.NoStagedAndUnstagedChanges()) precommit.check(checks.NoWhitespaceInFilePath()) precommit.check(checks.DoNotSubmit()) # Language-specific checks precommit.check(checks.PythonFormat(exclu...
iafisher/precommit
test_repo/bad_python_format.py
print( "hello" )
iafisher/precommit
precommitlib/lib.py
""" The main library for the precommit tool. Holds the machinery for running pre-commit checks and fixes and reporting the results. The checks themselves are defined in checks.py. Author: <NAME> (<EMAIL>) Version: May 2020 """ import ast import fnmatch import subprocess import sys import time from collections import...
iafisher/precommit
precommitlib/checks.py
""" A suite of useful pre-commit checks. If you want to write your own check, you'll need to create a new class that inherits from `BaseCheck` and defines a `check` method that returns a `Problem` object if it finds any issues, or `None` otherwise. Read through the existing checks in this module for inspiration. If y...
iafisher/precommit
precommitlib/__init__.py
<reponame>iafisher/precommit<filename>precommitlib/__init__.py from .lib import BaseCheck, Precommit, Problem, Repository # noqa: F401