text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
import click
import langml
@click.group()
@click.version_option(version=langml.__version__)
def cli():
"""LangML client"""
pass
def main():
from langml.baselines.cli import baseline
cli.add_command(baseline)
cli(prog_name='langml', obj={})
|
from functools import reduce
def score(motifs):
return map(reduce(lambda score, cur: score + cur, motifColumn), rotate(motifs))
def score(motifs):
return map(reduce(
lambda columnScore, nucleotide: columnScore.addToScore(nucleotide),
rotate(motifs), MotifColumnScore()), rotate(motifs))
# Rot... |
class Solution:
def maxVowels(self, s: str, k: int) -> int:
window_start = 0
vowels = ['a','e','i','o','u']
max_vow = 0
count = 0
for window_end in range(len(s)):
if s[window_end] in vowels:
count+=1
if window_end >=k-1:
... |
import numpy as np
import os
from matplotlib import pyplot as plt
error_list=np.genfromtxt("error_result", dtype=np.float64).reshape((-1,))
e_gap=np.genfromtxt("label_of_qe", dtype=np.float64).reshape((-1,))
e_pre=error_list+e_gap[:28600]
plt.scatter(e_gap[:25725],e_pre[:25725], s=3,marker="o",
al... |
# Generated by Django 3.2.8 on 2021-11-01 18:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dastugo_school', '0003_alter_contact_options'),
]
operations = [
migrations.RenameField(
model_name='contact',
old_name='mes... |
from icalendar import Calendar, Event
from django.conf import settings
from datetime import datetime, timedelta
def create_google_cal_link(event):
time_fmt = '%Y%m%dT%H%M%SZ'
event_url = ('https://www.google.com/calendar/render?action=TEMPLATE&text={text}'
'&dates={start_time}/{end_time}'
... |
# Generated by Django 2.1.7 on 2019-04-02 01:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('translate', '0004_auto_20190327_0915'),
]
operations = [
migrations.AddField(
model_name='file',
name=... |
grocery_item = {} # defines empty dictionary
grocery_history = [] # defines empty list
stop = 'go'
while stop != 'q' : # creates the while loop
item_name = input('Item name: ') # accepts the item name
quantity = input('Quantity purchased: ') # accepts quantity of items purchased
cost = input('Price p... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9a1 on 2015-11-01 04:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
m... |
#coding=utf8
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import time
import uuid
from items import TitleItem, TitleGroup
import libs.hound
import config
from bs4 import BeautifulSoup
from pymongo... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or m... |
import folium
import pandas as pd
from jobs.routes import *
from jobs import db
NY_COORDINATES = (40.7128, -74.0060)
job_locations = lat_long_trace()
# create empty map zoomed in on New York
ny_map = folium.Map(location=NY_COORDINATES,tiles = 'Stamen Toner', zoom_start=12)
def map_job_locations():
for item in ... |
import numpy as np
np.set_printoptions(threshold=np.inf)
from scipy import ndimage
from skimage.morphology import thin
import matplotlib.pyplot as plt
from skimage.morphology import skeletonize,binary_closing
import mahotas as mh
import math
from utilities import bcolors
class EnergyCalibrator:
def __init__(se... |
from django.conf import settings
from rest_framework import serializers
from openbook_auth.models import User, UserProfile
from openbook_auth.validators import username_characters_validator, user_username_exists
from openbook_common.models import Badge
from openbook_common.serializers_fields.user import IsFollowingFie... |
import sys
import time
def text2word(filename):
with open(filename) as f:
word_list = [i for i in f.read().split()]
return word_list
#########################
# levenschtein distance #
#########################
def levenschtein(source, target):
source = ' '+source
target = ' '+target
n = l... |
import argparse
import skrf as rf
from pathlib import Path
from scipy.interpolate import interp1d
from numpy import log10
parser = argparse.ArgumentParser(description = 'script to return the amplitude of a circuit at a given freqeuncy based on its measured S-paramter file')
parser.add_argument("file", help="The S-par... |
from django.test import TestCase
from requests.exceptions import HTTPError
from requests.models import Response
from generic_api.errors_handler import HttpErrorsHandler
class GenericErrorsHandlerTestCase(TestCase):
def setUp(self):
self.errors_handler = HttpErrorsHandler()
def test_response_valid(se... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time : 18-7-26 下午4:59
# @Author : viaeou
# @Site :
# @File : tensorboard_start.py
# @Software: PyCharm
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
with tf.name_scope('inputs'):
# define placeholder for inputs to networ... |
#!/usr/bin/python
def main():
n = input()
l = map(int, raw_input().split())
print sorted(l)[len(l)/2]
if __name__ == '__main__':
main()
|
from unittest import TestCase, main
from Utilities import StringOperations
class TestStringOperations(TestCase):
def test_getLastChar(self):
last_char = StringOperations.getLastChar("PBD-7541")
self.assertEqual("1", last_char)
def test_getLastChar_arg_not_string(self):
self.assertRai... |
storage = {}
def add(channel, message):
if channel in storage:
storage[channel].append(message)
return message
else:
storage[channel] = [message]
return message
def get(channel, fromDate=None, toDate=None):
if channel in storage:
return storage[channel]
else:
return None |
"""
Abstraction layer over an agent's neural network.
"""
from typing import Tuple
import torch
import torch.nn.functional as F
from model import ActorCritic
class ActorCriticAgent(object):
"""
Abstraction layer over an agent's neural network
"""
def __init__(self, model: ActorCritic, shared_model: ... |
#!/bin/python3
import sys
x1,v1,x2,v2 = input().strip().split(' ')
x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]
'''
def checker():
if x1 == x2:
return True
elif x1 < x2 and v1 < v2:
return False
elif x1 > x2 and v1 > v2:
return False
else:
return None
while T... |
#!/usr/bin/env python3
# UPS patcher based on UPS module for Rom Patcher JS v20180930 - Marc Robledo 2017-2018
# Author: MinN
import sys
import zlib
CHECKSUM_TARGET = True # check the target's checksum
CHECKSUM_PATCH = False # don't check the patch's checksum because NUPS BUG
class ChecksumError(Exception):
p... |
import dataset
import torch
import pickle
import pytorch_lightning as pt
from pytorch_lightning.trainer.supporters import CombinedLoader
import model
class MyDataModule(pt.LightningDataModule):
def __init__(self, vocab, vocab_size, csv_path, batch_size, batch_size_val, **kwargs):
super().__init__()
... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from std_msgs.msg import Float64
class JointPub(object):
def __init__(self):
self.publishers_array = []
self._pub_upperlegM1_joint_position = rospy.Publisher(
'/spotmini/head_upperlegM1_joint_position_controller/comman... |
from setuptools import setup
setup(
name = 'front',
version = '0.1',
install_requires = ['Click',],
py_modules = ['endpoints'],
entry_points= '''
[console_scripts]
hello=endpoints:hello
signup=endpoints:SignUp
login=endpoints:Login
refreshtoken=endpoints:RefreshToken... |
import discord
from discord.ext import commands
from weather import Weather, Unit #weather-api
from weatheralerts import WeatherAlerts #weatheralerts
class StormCog:
'''For Important Weather Alert Parsing'''
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['weather'], pass_conte... |
#!/usr/bin/env python
from time import sleep
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.mei_message import *
from pymodbus.exceptions import *
from ModbusSocketFramerHMAC import ModbusSocketFramerHMAC as ModbusFramer
#depuracion
import logging
logging.basicConfig()
log = logging.getLogger()
#log.se... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# github: https://github.com/houm01
# blog: https://houm01.com
from django.shortcuts import render
from datetime import datetime
from data import courses_db
from houm01_demo.models import Courses
import json
def readme(request):
mytime = int(datetime.now().strftim... |
# side = 7
# i = 4
# j = 7
# while side <= 7:
# for i in range(0, 4):
# for j in range(0, 7):
# if((j == 0 or j == 6) and i <= 2) or ((j == 1 or j == 5) and i <= 1) or ((j == 2 or j == 4) and i <= 0):
# print(" " ,end= " ")
# else:
# print("*", end= ... |
import json
import requests
from os import path
from logger import Logger
class Puller:
""" Class for pulling data from GitHub via API """
api_url = 'https://api.github.com/'
def __init__(self, config):
self.auth_params = config[u'auth']
self.rate_limit = 5000 # rate limit remaining
... |
from django.contrib import admin
from business.models import Business, Category, Neighborhood
class BusinessAdmin(admin.ModelAdmin):
pass
class CategoryAdmin(admin.ModelAdmin):
pass
class NeighborhoodAdmin(admin.ModelAdmin):
pass
admin.site.register(Business, BusinessAdmin)
admin.site.register(Categ... |
# -*- coding: utf-8 -*-
# @Author: Dang Kai
# @Email : 1370465454@qq.com
# @Date: 2019-04-28 18:12:53
# @Last Modified time: 2019-04-28 18:12:53
from flask import render_template,request,flash,session,url_for
from Api_Manager import server
from Api_Manager.controller.login_form import LoginForm
from Api_Manager.model... |
import numpy as np
import pandas as pd
import os
from scipy import optimize
from scipy.special import expit
class main:
class NN:
def __init__(self, hidden_layer_count, hidden_layer_size, lambda_val):
"""
Neural Network class.
What it basically is doing:-
1. ... |
import pandas as pd
def get_monthly_pred(city, BASE_DIR):
data = []
if city == "Agra":
data_df = pd.read_csv(
BASE_DIR+"/app_aerify/monthly_predicted_data/pred_Agra.csv")
elif city == "Ahmedabad":
data_df = pd.read_csv(
BASE_DIR+"/app_aerify/monthly_predicted_data/p... |
from unittest import TestCase
import unittest
from src.Year2016.Day14 import Day14
class Day14Test(TestCase):
def setUp(self):
self.day = Day14()
def test_abc(self):
starting_key = 'abc'
result = self.day.one_time_pads(starting_key, 64, self.day.simple_md5)
self.assertEqual(r... |
import os, json, time, csv
from datetime import datetime, timedelta
from betfair_python_rest.managers import (
BetFairAPIManagerBetting,
BetFairAPIManagerAccounts,
)
from betfair_python_rest.forms import (
MarketFilterAndTimeGranularityForm,
MarketFilterAndLocaleForm,
ListMarketCatalogueForm,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from skymap import *
def main():
# Based on the 5th Revised edition of the Yale Bright
# Star Catalog, 1991, from
# ftp://adc.gsfc.nasa.gov/pub/adc/archives/catalogs/5/5050.
cat = Catalog("YBS.edb")
obs = ephem.Observer()
obs.lat = ephem.de... |
import numpy as np
from pyflann import *
import math
import clusterAssign
import fileStructure
import tfidf
import ml_metrics as metrics
import hamEmbed
he_threshold = 52
invFileTable = np.load('matrices/data72/invFileTable20000k3.npy')
centers = np.load('matrices/data72/codebook.npy')
numcenters = invFileTable.shap... |
import abc
import os
import re
import threading
import time
import socket
import subprocess
import typing
import devcluster as dc
class AtomicOperation(metaclass=abc.ABCMeta):
"""
Only have one atomic operation in flight at a time. You must wait for it to finish but you may
request it ends early if you ... |
class Solution(object):
def __init__(self):
self.ans = ""
def DFS(self, node, visited, k):
for num in map(str, range(k)):
nodeCur = node + num
if nodeCur not in visited:
visited.add(nodeCur)
self.DFS(nodeCur[1:], visited, k)
... |
import ast
import json
import logging
import math
import tempfile
import random
import string
from abc import ABC, abstractmethod
from math import inf
import graphviz
import requests
from dulwich import porcelain
ccsGitCache = {}
""" Caches all cloned git repositories """
importedClasses = {
"VMAsAService": {
... |
import os
from Bio import SeqIO
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
## script to find mean charge of protein region by sliding window
fasta_file_path = "/Users/jon/Google Drive (WIBR)/projects/active_repressive/181217_charge_analysis_of_ChIP_factors/HDGF_enriched.fasta"
km... |
# https://blog.csdn.net/caimouse/article/details/79692118
'''
从CAN的通道0向通道1来发送一帧CAN数据
'''
#python3.6 32位
#https://blog.csdn.net/caimouse/article/details/51749579
#开发人员:蔡军生(QQ:9073204) 深圳 2018-3-25
#
import os
from ctypes import *
VCI_USBCAN2A = 4
STATUS_OK = 1
class VCI_INIT_CONFIG(Structure):
_fi... |
# Generated by Django 2.2 on 2019-04-25 10:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('input', '0014_auto_20190425_1530'),
]
operations = [
migrations.AlterField(
model_name='userinfo',
name=... |
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from .views import *
from django.urls import path, include
from . import views
urlpatterns = [
#path('movies/', create_movie_view, name="create"),
#path('<slug>/', detail_movie_view, name="detail"),
#path('<slug>/edit/', edit... |
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
import csv
import numpy as np
import pandas as pd
import random
from matplotlib import pyplot as plt
from scipy import stats
from bhtsne import tsn... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 18:21:15 2019
@author: exame
"""
def dvu(u,v):
return u*(u/2 + 1)*v**3 + (u + 5/2)*v**2
def rk4(u,uf,v,h):
while (u < uf):
d1 = h*dvu(u,v)
d2 = h*dvu(u + (h/2), v+ (d1/2))
d3 = h*dvu(u + (h/2), v + (d2/2))
... |
# -*- coding: utf-8 -*-
"""Top-level package for Bulker.gr Python API Client."""
__author__ = """Yiannis Inglessis """
__email__ = 'negtheone@gmail.com'
__version__ = '0.1.4'
from .bulkergr_api import Bulkergr
from .exceptions import AuthKeyMissingError
|
# coding=utf8
class Record:
def __init__(self, stkcd, dealseq, inscode, biddercode, price_normal, shares, policy_flag):
self.stkcd = str(stkcd)
self.dealseq = int(dealseq)
self.inscode = str(inscode)
self.biddercode = str(biddercode)
self.price_normal = float(price_normal)... |
from selenium.webdriver.common.keys import Keys
from seleniumbase.fixtures.base_case import BaseCase
from common.login_page import MyTest
from common.Element_API import WeiGeLi, ComoonPagee, WangZhanHoumenpage, SuoYouZhuJi, RuoMimaPage
from selenium.common.exceptions import NoSuchElementException
import time
import re
... |
#HAND GESTURE RECOGNIZATION USING OPENCV
import numpy as np
import cv2
import math
capture=cv2.VideoCapture(0)
while capture.isOpened():
check,frame=capture.read()
cv2.rectangle(frame,(100,100),(400,400), (0,255,0),0)
crop_image=frame[100:350,100:350]
blur=cv2.GaussianBlur(crop_image,(3,3),0)... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tina.base.db.models.fields import JSONField
class Webhook(models.Model):
project = models.ForeignKey("projects.Project", null=False, blank=False,
related_name="webhoo... |
##import itertools
##T = input()
##for _ in range(int(T)):
## entries = list(map(int,input().split()))
## n1,n2,n = entries[0],entries[1],entries[2]
## arr = []
##
## for i in range(1,n+1):
## num,x=[],0
## if i == 1:
## arr.append(i)
## continue
## l =... |
import boto3
import StringIO
import zipfile
import mimetypes
def lambda_handler(event, context):
sns = boto3.resource('sns')
topic = sns.Topic('arn:aws:sns:us-east-1:418230580652:SLReactS3Website')
try:
s3 = boto3.resource('s3')
website_build_bucket = s3.Bucket('sl-react-website-build')
... |
"""
These are used for data-aware declare deviance mining.
Each template gives back: locations activations, which were fulfilled and activations, which were violated.
No short-circuiting of conditions, which could previously be done in other templates
"""
def template_not_responded_existence(trace, event_set):
""... |
""" display menu
get choice
while choice != quit option
if choice == first option
do first task
else if choice == <second option>
do second task
...
else if choice == <n-th option>
do n-th task
else
display invalid input error m... |
import pandas as pd
import numpy as np
from numpy import array
import psycopg2
import math
import csv
import traceback
import matplotlib.pyplot as plt
from collections import defaultdict
import time
from sklearn.linear_model import SGDClassifier
from sklearn.ensemble import GradientBoostingClassifier
from... |
import requests, csv
from bs4 import BeautifulSoup
url = 'http://www.mtime.com/top/tv/top100/index-2.html'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
h2_list = soup.find_all("h2", class_ = "px14 pb6")
cvs_file = open("Top10.csv", 'w', newline='', encoding='utf-8')
writer = csv.writer(cvs_fil... |
import cv2
import os
import numpy as np
import moments_calc
import clf_finder
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from sklearn import svm
INPUT_DIR = "input_images"
OUTPUT_DIR = "output"
CATEGORIES = np.array(["walking", "jogging", "running", "boxing", "handwavin... |
from setuptools import setup
setup (
name='img2pdf',
version='0.1.3',
author = "Johannes 'josch' Schauer",
author_email = 'j.schauer@email.de',
description = "Convert images to PDF via direct JPEG inclusion.",
long_description = open('README.md').read(),
license = "LGPL",
keywords = "jp... |
#!/usr/bin/env python
import sys,HTSeq,time,re,math,gc
#
# Test HTSeq's GTF parsing speed against doing it manually
gc.disable()
try:
fin = open(sys.argv[1])
except IOError,e:
print e
else:
fin.close()
_CHROM = 0
_START = 1
_END = 2
_STRAND = 3
_TYPE = 4
_ATTR = 5
#=============================================... |
#!/usr/bin/python3
import gi
gi.require_version('Gtk', '3.0')
import sys, os, threading, re, gettext
from gi.repository import Gio, Gtk, GLib, GObject, Pango, GdkPixbuf
gettext.install("placesCenter@scollins", os.environ['HOME'] + "/.local/share/locale")
def launch(path):
fileObj = Gio.File.new_for_path(path)
... |
"""
single root plots - soil potentials of 1-3 soils, with fancy background
from xls result files (in results/)
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fancy = False
ls = ['-']
# add_str = "_dry"
# fnames = ["results/sink_" + "small_sra" + add_str + ".xls",
# "results/si... |
# Copyright 2016 - Nokia
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
#!/usr/bin/env python
# coding=utf-8
'''
> File Name: database.py
> Author: vassago
> Mail: f811194414@gmail.com
> Created Time: 五 8/10 18:57:22 2018
'''
from contextlib import contextmanager
import logging
from alembic import command
from alembic.config import Config
from sqlalchemy.orm import sessionmaker
from sql... |
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from django.core.validators import MaxValueValidator, MinValueValidator
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db.mod... |
from django.contrib import admin
from ChatBot.models import UserMessage #importing the UserMessage module to register here.
# Register your models here.
admin.site.register(UserMessage) #Registering the model.
|
# -*- coding: utf-8 -*-
{
'name': 'Leave Management',
'version': '10.0.2.0.0',
'summary': 'Manage Leave',
'description': """
Helps you to manage Leave.\n
HR Leave extension functionality\n
""",
'category': 'Human Resources',
'author': 'Al Kidhma Group',
'webs... |
import os
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity
from resources.user import UserRegister
from resources.user import UserList
from resources.item import Item, ItemList
from resources.store import Store, StoreList
from resources.dbinit... |
def q_04():
# 세 개의 정수를 입력 받아서 합계와 평균을 출력하시오.
# (단 평균은 소수 이하를 버리고 정수부분만 출력한다.)
while True:
try:
num1, num2, num3 = map(int, input("정수 세 개 입력: ").split(' '))
print("합계: %d" % (num1 + num2 + num3))
print("평균: %d" % ((num1 + num2 + num3) / 3))
return
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2019.6
# Email : muyanru345@163.com
###################################################################
# Import future modules
from __future__ import absolute_import
from __fu... |
"""
LeetCode 189. Rotate Array (Easy)
blog : https://daimhada.tistory.com/113
problem : https://leetcode.com/problems/rotate-array
"""
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.reverse()
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root, sum):
def pathSumFrom (n, sum):
if n is None:
return 0
total = 0... |
from decimal import Decimal
from BaseController import BaseController
import tornado.ioloop
import tornado.web
import re
class InfoController(BaseController):
def get(self):
"""Serves a GET request.
"""
server = self.get_argument("server")
redis_info = self.stats_provider.get_info(... |
'''
@package: dc
@author igor
@link: http://hierarchical-cluster-engine.com/
@copyright: Copyright © 2013-2014 IOIX Ukraine
@license: http://hierarchical-cluster-engine.com/license/
@since: 0.1
'''
import glob
import os
import base64
from datetime import datetime
import dc.EventObjects
import dc.Constants as DC_... |
from django.test import TestCase
from tarefas.models import Tarefa
from django.db.utils import IntegrityError
from django.contrib.auth.models import User
class CriaTarefaTestCase(TestCase):
def test_cria_tarefa_vazia(self):
self.assertIsNotNone(Tarefa.objects.create())
def test_cria_tarefa_sem_nome(s... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from .source import SourceStrava
__all__ = ["SourceStrava"]
|
# create strong scaling plot data
import sys
from math import sqrt
# refinement level used for speedup study
r = 9
# list of number of processes
plist = list([1,2,4,8,16,20])
# list of timed sections
sectionlist = list(["assemble","initialize","output","setup","solve"])
# get lines from input file
inputfile = open("... |
from .inference import (convert_SyncBN, inference_detector,
inference_multi_modality_detector, init_detector,
show_result_meshlab)
from .test import single_gpu_test
__all__ = [
'inference_detector', 'init_detector', 'single_gpu_test',
'show_result_meshlab', 'conv... |
import datetime
import date_fun
import numpy as np
import mygis
from bunch import Bunch
def stats(data):
"""Calculate the rate of melt from peak to 0
Assumes that data starts at peak and decreases from there
Takes the first point data dips below peak as the onset of melt
Takes the first day data get t... |
import sys
import tensorflow as tf
from pyspark.sql import SparkSession
from recsys_tf_237.recsystf_model import TfrsModelMaker
NUM_TRAIN_EPOCHS = 3
items_path = "./input-data/items"
users_path = "./input-data/users"
events_path = "./input-data/events"
num_items = 494433
num_users = 3827078
num_events = 6757870
d... |
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly
import pandas as pd
import pymysql as mysql
import urllib.parse as urllib
from datetime import datetime as dt
externa... |
from ..forms import UniversityForm
from ..models import University
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
# Просмотр списка университетов
class UniversityListView(generic.ListView):
model = University
templ... |
from django.conf.urls import patterns, include, url
from django.views import generic
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('stories.urls')),
url(r'^success$', generic.TemplateView.as_view(template_name="about.html"),
name='ab... |
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from orders.products.views import ListProductsView
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^test/', 'Prometheus.views.test', name='test'),
# Uncomment the admin/doc line below to enable... |
# coding: utf-8
from math import sin, cos, sqrt
from six.moves import xrange
import h5py
import numpy as np
import scipy.io as sio
import tensorflow as tf
class Id:
def __init__(self, Ia, Ib):
self.Ia=Ia
self.Ib=Ib
def show(self):
print('A: %s\nB: %s'%(self.Ia, self.Ib))
def convlay... |
import math
def solve(k, c, s):
tries = int(math.ceil(k / float(c)))
if s < tries:
return "IMPOSSIBLE"
indexes = []
curK = 0
for i in range(0, tries):
ind = 0
mult = k**(c-1)
for j in range(0, c):
ind += curK * mult
mult /= k
curK += 1
if curK >= k:
break
oldInd =... |
import pandas as pd, numpy as np
import re, sys, os
from matplotlib import pyplot as plt
def parse(file_path, pattern="Accuracy Score"):
scores = []
count = 0
print (file_path)
with open(file_path, 'r') as f:
line = f.readline()
while line:
count = count + 1
# pr... |
'''
Get python modules
'''
import cPickle
import os
import csv
'''
Get third-party modules
'''
from fisher import pvalue as fisher
'''
Get MOCA modules
'''
from MOCA.DataHandler import get_path, get_supervised_dataset
from MOCA.Statistics import Performance, contingency_table, EffectSize
from MOCA.Setworks import ass... |
import asyncio
import json
from asyncio import CancelledError
from copy import copy
from decimal import Decimal
from unittest import TestCase
from unittest.mock import patch
from aioresponses import aioresponses
import hummingbot.connector.parrot as parrot
class ParrotConnectorUnitTest(TestCase):
# logging.Leve... |
from assistance.smart_assistant import SmartAssistant
def main():
assistant = SmartAssistant()
assistant.hello()
while assistant.ready:
assistant.execute_cycle()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2016 Taylor C. Richberger <taywee@gmx.com>
# This code is released under the license described in the LICENSE file
from __future__ import division, absolute_import, print_function, unicode_literals
from datetime import datetime, timedelta
from ssllabs.chai... |
# This file is part of spot_motion_monitor.
#
# Developed for LSST System Integration, Test and Commissioning.
#
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause BSD-style
# license that can be found in the LICE... |
"""
Programa para realizar un filtro de datos
"""
DATA = [
{
'name': 'Facundo',
'age': 72,
'organization': 'Platzi',
'position': 'Technical Coach',
'language': 'python',
},
{
'name': 'Luisana',
'age': 33,
'organization': 'Globant',
'... |
"""Project settings. Configure connection to database."""
db_name = 'company'
password = ''
user = 'root'
host = 'localhost'
auto_commit = True
|
#!/usr/bin/env Python3
"""
Usage: ./promoter_finder.py <ctab>
"""
import sys
import pandas as pd
df = pd.read_csv(sys.argv[1], sep='\t', index_col='chr')
relevant_data = df.loc[:,['t_name','start', 'end','strand']]
relevant_data['promoter_start'] = relevant_data.loc[:,'start']
relevant_data['promoter_end'] = relev... |
from models.db_models.models import ActionLogTypes
from db.db import session
from flask import Flask, jsonify, request
from flask_restful import Resource, fields, marshal_with, abort,reqparse
action_log_type_fields = {
'id': fields.Integer,
'message': fields.String,
'code':fields.Integer
}
parser = reqpar... |
from talkback_accessible import talkback_focus
from node_checker import Node_Checker
class Node:
# raw_properties are the dictionary of properties associated with the node 9(e.g. "focusable" "cont_desc")
# characteristics are determined with heuristic tests (e.g. "is speakble" "is visible")
# parent, pointer to par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.