content stringlengths 5 1.05M |
|---|
import pytest
from deep_lyric_visualizer.generator.generator_object import (GeneratorObject)
from deep_lyric_visualizer.generator.generation_environment import (GenerationEnvironment,
WikipediaBigGANGenerationEnviornment)
from deep_lyric_visualizer.g... |
# -*- coding: utf-8 -*-
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
fig_path = "/Users/gabriel/Documents/Research/USGS_Work/gmprocess/figs/spectra/"
#%%
def get_fft(series, fs, nfft):
ft = np.fft.fft(series,fs)
freq = np.fft.fftfreq(nfft)
return freq, ft
def get_ifft(se... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
ORIGINAL_MODEL = 'purePursuitUSCity'
THRESHOLD_KEYS = {
'TTD': ['Time to destination (Source)', 'Time to destination (FollowUp)'],
'TTO': ['Balancing (Source)', 'Balancing (FollowUp)'],
}
def evaluate_results(results, test_distances, thresholds):
... |
from django.contrib import admin
from .models import Coins
# Register your models here.
@admin.register(Coins)
class CoinAdmin(admin.ModelAdmin):
list_display = ['id', 'username', 'coins']
|
class User():
def __init__(self, username, password, nickname):
self._username = username
self._password = password
self._nickname = nickname
self._winRate = None
self._wins = 0
self._loses = 0
self._gamesPlayed = 0
self._doraemonPlayed = 0
... |
from scripts.register_fragments import *
class RefinePair(RegisterFragment):
def __init__(self, setting_path, ply_files, s, t, transform):
super().__init__(setting_path, ply_files, s, t)
self._transform = transform
def refine(self, source, target, init_transform):
""" multiscale icp r... |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... |
"Base definitions for transports based on IP networking."
import os
import socket
import logging
from thespian.actors import ActorAddress
_localAddresses = set(['', '127.0.0.1', 'localhost', None])
def _probeAddrInfo(usage, useAddr, af, socktype, proto):
try:
return socket.getaddrinfo(useAddr, 0, af, s... |
#!/usr/bin/env python3
# Copyright 2020 Salesforce Research (Aadyot Bhatnagar)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
from distutils.util import strtobool
import logging
import kaldiio
import tqdm
from speech_datasets.transform import Transformation
from speech_datasets.utils.io... |
#!/usr/bin/python3
import os
def main():
os.system('rm dist/* -rf')
os.system('python3 setup.py sdist')
os.system('python3 setup.py bdist_wheel --universal')
os.system('twine upload dist/*')
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
#
# tcpv4tracer Trace TCP connections.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: tcpv4tracer [-h] [-v] [-p PID] [-N NETNS]
#
# You should generally try to avoid writing long scripts that measure multiple
# functions and walk multiple kernel structures, as they will be a ... |
from flask import *
import requests
import sqlite3
import random
import json
##配置文件
api_url1 = 'http://127.0.0.1:5700/send_msg'
api_url2 = "http://127.0.0.1:5700/delete_msg"
qq_group=["723174283"]
##初始化
for a in qq_group:
db = sqlite3.connect("qq.db")
cur=db.cursor()
cur.execute("CREATE TABLE IF NOT EXIST... |
# -*- coding: utf-8 -*-
from django.contrib import admin, messages
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from civil.apps.search.models import SavedSearch
#==============================================================================
def s... |
# -*- coding: utf-8 -*-
from bot.dfs.bridge.data import Data
from gevent import monkey
monkey.patch_all()
import logging.config
from datetime import datetime
from gevent import spawn, sleep
from bot.dfs.bridge.workers.base_worker import BaseWorker
from bot.dfs.bridge.utils import business_date_checker, generate_doc_... |
import datetime
import logging
from osf.models import AbstractNode
from api.caching.tasks import update_storage_usage_cache
from django.core.management.base import BaseCommand
from datetime import timezone
from framework.celery_tasks import app as celery_app
from django.db import transaction
logger = logging.getLogg... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as fcnal
from sklearn.pipeline import Pipeline
from .metrics import eval_target_model
# Determine device to run network on (runs on gpu if available)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def label_t... |
import torch
from pytorch3d.structures import Meshes
from pytorch3d.renderer import look_at_view_transform, FoVPerspectiveCameras, RasterizationSettings, PointLights, \
MeshRenderer, MeshRasterizer, SoftPhongShader, TexturesVertex
from vedo.mesh import Mesh
from vedo.io import screenshot
from vedo.plotter import sh... |
import numpy as np
from ultramodule import divstd_prime, crossco, cc_multiorde
import h5py
from tqdm import tqdm
from tqdm import tnrange
###################################################################################################
len_vared=10
vmr_min=5
vmr_max=12
segment=10.
mol="vo"
specdir="./rainbow/"
exote... |
from os import listdir
from os.path import isfile, join, isdir
import numpy as np
import scipy.io as io
import torch
from torch.utils.data import Dataset, DataLoader, random_split
from torchvision import transforms
from PIL import Image
from pytorch_lightning.core.datamodule import LightningDataModule
import os
"""
... |
from dogapi import dog_http_api as api
api.api_key = '9775a026f1ca7d1c6c5af9d94d9595a4'
api.application_key = '87ce4a24b5553d2e482ea8a8500e71b8ad4554ff'
# Get an alert's details
api.get_alert(525)
|
# vim: fdm=indent
'''
author: Fabio Zanini
date: 02/03/18
content: IO functions.
'''
# Modules
import numpy as np
import pandas as pd
# Functions
def read_10X(fdict, make_dense=False):
import scipy.io
mat = scipy.io.mmread(fdict['matrix'])
genes = pd.read_csv(
fdict['genes'],
... |
'''
In Section 2.3.3, we note that our Vector class supports a syntax such as
v = u + [5, 3, 10, −2, 1], in which the sum of a vector and list returns
a new vector. However, the syntax v = [5, 3, 10, −2, 1] + u is illegal.
Explain how the Vector class definition can be revised so that this syntax
generates a new vector... |
""" Bootstrapping the yield curve """
from math import log, exp
from typing import List
from securities.bond import Bond
from term_structures.curve import Curve
class BootstrappedCurve(Curve):
"""
Bootstrap a curve of bond instruments to zero coupon rates
"""
def __init__(self):
self._instrum... |
import enum
class OrderStatusEdit(enum.Enum):
PENDING_STORE = 'PENDING_STORE'
PREPARING = 'PREPARING'
READY = 'READY'
ON_IT = 'ON_IT'
DONE = 'DONE'
class OrderStatus(enum.Enum):
COMPLETED = 'COMPLETED'
PREPARING = 'PREPARING'
PENDING_PICKUP = 'PENDING_PICKUP'
PICKED_UP = 'PICKE... |
#!/bin/python3
class Class1:
def collinear(x1, y1, x2, y2, x3, y3):
a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)
if (a == 0):
print('Yes')
else:
print('No')
def main():
cl1 = Class1
islinear = cl1.collinear(1, 1, 1, 1, 4, 5)
if __name__ == "__main__":
main()
|
from setuptools import setup
setup(
# Needed to silence warnings (and to be a worthwhile package)
name='DA_Functions',
url='https://github.com/armandotoledo/ibv_da_functions',
author='Armando Toledo',
author_email='armando.toledo.v@hotmail.com',
# Needed to actually package something
packag... |
"""Common loss functions package"""
from typing import Callable
# Type hinting
Loss = Callable[[float, float], float]
def difference(result: float, target: float) -> float:
return target - result
|
#!/usr/bin/python
#
# Copyright (c) 2016 Red Hat
# Luke Hinds (lhinds@redhat.com)
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 0.1: OpenS... |
from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
from . import views
discovery = SimpleRouter()
discovery.register('discovery', views.DiscoveryViewSet, base_name='discovery')
urlpatterns = [
url(r'', include(discovery.urls)),
]
|
from django.http import HttpResponseRedirect, JsonResponse,HttpResponse
from django.shortcuts import get_object_or_404, render,redirect
from django.urls import reverse, reverse_lazy
from django.contrib.auth.models import User
from datetime import datetime
from django.core import serializers
import requests
import rand... |
# 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, software
# distributed under t... |
#====================================================================
# Driver program
#====================================================================
import sys,os
sys.path.append('../../src/Python/Postprocessing/')
sys.path.append('../../src/Python/Stage_0/')
sys.path.append('../../src/Python/Stage_1/')
sys.p... |
import os
import redis
from rq import Worker, Queue, Connection
listen = ['default']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
q = Queue(connection=conn)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(list(map(Queue, listen)))
... |
#des_reg_BSTree.py
#DEVELOPER: Israel Bond
#implementation of classes needed for assignment
class BSTNode:
def __init__(self,number):
self.left = None
self.right = None
self.num = number
class BSTree:
def __init__(self):
self.root = None
def insert(self,number):
if... |
import numpy as np
from kipoi.data import Dataset
class SeqDataloader(Dataset):
"""
Args:
fasta_file: file path; Protein sequence(s)
"""
def __init__(self, fasta_file, split_char=' ', id_field=0):
seq_dict = self.read_fasta(fasta_file, split_char, id_field)
self.length = len(... |
#!/usr/bin/env python
import sys
import yaml
with open(sys.argv[1]) as fd:
print(yaml.safe_load(fd))
|
import cv2
import numpy as np
from scipy.ndimage import label
from src.tools.hog_window_search import generate_heatmap, combined_window_search, draw_labeled_bboxes
class VideoProcessor:
def __init__(self, svc, X_scaler):
self.heatmap_history = []
self.svc = svc
self.scaler = X_scaler
... |
# import code from your package here to make them available outside the module like:
from cythonbuilder.cython_builder import cy_init, cy_clean, cy_build, cy_list, cy_interface
from cythonbuilder.logs import LoggerSettings, create_logger, set_logger_debug_mode
__version__ = "0.1.13"
__last_build_datetime__ ="2022-06-0... |
from spaceone.core.error import *
class ERROR_JOB_STATE(ERROR_UNKNOWN):
_message = 'Only running jobs can be canceled. (job_state = {job_state})'
class ERROR_DUPLICATE_JOB(ERROR_UNKNOWN):
_message = 'The same job is already running. (data_source_id = {data_source_id})'
|
# Put whatever you want in this module and do whatever you want with it.
# It exists here as a place where you can "try out" things without harm.
# Joseph Law
##LOCK LABEL: 112
##Combo: 03-28-33
|
from datetime import date, timedelta
# from PyQt5.QtCore import QDate
from pandas_datareader import data
from pandas_datareader._utils import RemoteDataError
from numpy import polyval
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as ... |
from typing import Dict, List, Optional, Union
from urllib.parse import urljoin
import json
import requests
from tqdm import tqdm
HOST = "http://lookup-service-prod.mlb.com"
def get_teams(
season: Union[int, str],
sport_code: Optional[str] = "'mlb'",
all_star_sw: Optional[str] = "'N'",
sort_order: Op... |
import logging
from abc import ABC, abstractmethod
import torch.nn
logger = logging.getLogger(__name__)
class ArchitectureFactory(ABC):
""" Factory object that returns architectures (untrained models) for training. """
@abstractmethod
def new_architecture(self, **kwargs) -> torch.nn.Module:
"""
... |
import json
import sys
from pins.rsconnect.api import _HackyConnect
OUT_FILE = sys.argv[1]
def get_api_key(user, password, email):
rsc = _HackyConnect("http://localhost:3939")
return rsc.create_first_admin(user, password, email).api_key
api_keys = {
"admin": get_api_key("admin", "admin0", "admin@exam... |
import logging
import os
from time import sleep
from urllib.parse import urljoin
import requests
import telegram
from dotenv import load_dotenv
logger = logging.getLogger('Devman notify logger')
class MyLogsHandler(logging.Handler):
def __init__(self, bot, tg_chat_id):
super().__init__()
self.b... |
import os
import sys
import numpy as np
from flask import Flask, request, Response
sys.path.append("..")
from MCTS import MCTS
from dotsandboxes.DotsAndBoxesGame import DotsAndBoxesGame
from dotsandboxes.keras.NNet import NNetWrapper
from dotsandboxes.DotsAndBoxesPlayers import GreedyRandomPlayer
from utils import d... |
import os.path
from datetime import datetime
from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID, DATETIME
schema = Schema(title=TEXT(stored=True), url=TEXT(stored=True), date=DATETIME(stored=True), content=TEXT, hash=ID(stored=True, unique=True))
if not os.path.exists("index"):
os.mkdir... |
from enum import IntEnum
from tests.testcase import BaseTestCase
from clickhouse_driver import errors
class A(IntEnum):
hello = -1
world = 2
class B(IntEnum):
foo = -300
bar = 300
class EnumTestCase(BaseTestCase):
def test_simple(self):
columns = (
"a Enum8('hello' = -1, '... |
"""
Example website in Flask, with web forms.
This is a fully working example showing how to use web forms on a Flask-based website.
I've found this basic structure very useful in setting up annotation tools or demos.
"""
# Flask-related imports:
from flask import Flask, request, render_template
# Other imports go h... |
from django.apps import apps
from django.db.models.signals import post_migrate
from django.utils.translation import ugettext_lazy as _
from mayan.apps.acls.classes import ModelPermission
from mayan.apps.acls.links import link_acl_list
from mayan.apps.acls.permissions import permission_acl_edit, permission_acl_view
fro... |
from .slack import KolgaSlackPlugin as Plugin # noqa: F401
|
#!/usr/bin/env python
c = 33675163320727339095014837582281323840051859854289916825117629551395370823659955814681282315463016124619404443441584421368620981293595007310032397095407298209578830182966433145009839000500503505979590280517585607094925442822091170832715599815430442356320114799995161041937865531772135980336997... |
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=20, required=True, label='name', widget=forms.TextInput(attrs={'class':'form-field-control-above', 'placeholder':'Name'}))
email = forms.EmailField(required=True, label='email', widget=forms.TextInput(attrs={'class':'form... |
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import session
from sqlalchemy.sql.expression import null, table
from sqlalchemy.sql.functions import count
class GenericRepo:
def __init__(self, session, table):
self.session = session
self.table = table
def commit(self):
... |
'''
This module has our implementation of CG with error estimates
'''
import numpy as np
from scipy import linalg
def cgqs(A, b, x, mu = None, tol = 1e-6, max_it = None,\
delay = 5,reorth = False, NormA = None, xTrue = None):
'''Iteratively computes solution to Ax = b with error estimates.
This prog... |
import argparse
import datetime
import os
import pickle
import sys
import pandas as pd
from sklearn.linear_model import LinearRegression
sys.path.append('..')
from import_data import azure_repos
def save_model(model, filename):
with open(filename, 'wb') as fd:
pickle.dump(model, fd)
def load_model(filen... |
import tensorflow as tf
x_data = [[1., 1., 1., 1., 1.],
[1., 0., 3., 0., 5.],
[0., 2., 0., 4., 0.]]
y_data = [1, 2, 3, 4, 5]
W = tf.Variable(tf.random_uniform([1, 3], -1, 1))
hypothesis = tf.matmul(W, x_data)
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
learn_rate = 0.1
optimizer = tf... |
from django.db import models
from hknweb.academics.models.base_models import AcademicEntity
class Rating(AcademicEntity):
# reference attributes
rating_question = models.ForeignKey(
"Question", on_delete=models.PROTECT, related_name="rating_question"
)
rating_survey = models.ForeignKey(
... |
from mldesigner import command_component
from azure.ai.ml import TensorFlowDistribution
distribution = TensorFlowDistribution()
distribution.worker_count = 2
@command_component(distribution=distribution)
def basic_component(
port1: str,
param1: int,
):
""" module run logic goes here """
return port1
|
import __builtin__
# Dummy _() function instead of actual one from gettext.
__builtin__._ = lambda x: x
|
"""
Helper classes for creating maps in any Source Engine game that uses dod.fgd.
This file was auto-generated by import_fgd.py on 2020-01-19 09:11:10.324911.
"""
from vmflib2.vmf import *
class DodBombDispenser(Entity):
"""
Auto-generated from dod.fgd, line 255.
Bomb Dispenser Area
"""
def __ini... |
import torch
import numpy as np
import torchvision.transforms as trans
import math
from scipy.fftpack import dct, idct
from torch.distributions import Beta
# mean and std for different datasets
IMAGENET_SIZE = 224
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
IMAGENET_TRANSFORM = trans.C... |
from config import DB_URI
uri = DB_URI
if uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)
# rest of connection code using the connection string `uri`
|
from athena import gpu_ops as ad
from athena import initializers as init
def logreg(x, y_):
'''
Logistic Regression model, for MNIST dataset.
Parameters:
x: Variable(athena.gpu_ops.Node.Node), shape (N, dims)
y_: Variable(athena.gpu_ops.Node.Node), shape (N, num_classes)
Return:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The sentence-meter takes TEI documents, removes unnecessary elements from it,
divides the plain text into sentences, and outputs a graph.
By Andreas Dittrich, 2017
"""
import re,glob,textwrap,statistics,numpy
from bs4 import BeautifulSoup
import matplotlib.pyplot a... |
from collections import Counter
import copy
import hashlib
import json
from urllib.parse import quote, unquote, urlparse
from arrow import now
from base64 import b64encode
from boto3 import Session as BotoSession
from botocore.client import Config as BotoConfig
from clarifai.rest import ClarifaiApp
from iiif.request i... |
import os
from flask import Flask, render_template, request, send_file, flash
from flask_uploads import UploadSet, configure_uploads, IMAGES
from mosaic import get_result_image
app = Flask(__name__)
photos = UploadSet('photos', IMAGES)
app.config['UPLOADED_PHOTOS_DEST'] = 'static/img'
app.config['SEND_FILE_MAX_AGE_DEF... |
from abc import ABC
from typing import TypeVar, Generic, List, Optional
from tudelft.utilities.listener.Listenable import Listenable
from uri.uri import URI
from geniusweb.references.Reference import Reference
INTYPE = TypeVar('INTYPE')
OUTTYPE = TypeVar('OUTTYPE')
class ConnectionEnd(Listenable[INTYPE], Generic[I... |
#!/usr/bin/env python3
import json
import sys
from augmentation_instance import *
from util.instance_parser import *
from util.file_manager import *
from learning_task import *
if __name__ == '__main__':
if len(sys.argv) == 1:
params = json.load(open('params.json'))
else:
params = json.load(op... |
from PyQt4 import QtCore, QtGui
from gui import Ui_MainWindow
from ImageUpdate import ImageUpdate
from DataProcessing.Writer import Writer
from DataProcessing.Controller import Controller
from multiprocessing import Manager, Event, Queue
from subgui import Ui_Dialog
import sys
from subprocess import Popen, PIPE
try:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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 cop... |
from SCons.Script import *
from os import path
def GetVars(vars):
vars.Add(ListVariable('arch', 'Build architectures', 'all',
['ppc','i386','x86_64']))
def DoUniversal(env, command, target, source, *args, **kw):
envs = []
builder = env['BUILDERS'][command]
exe = (command == 'Loada... |
# [Backward compatibility]: keep importing modules functions
from ..utils.deprecation import deprecation
from ..utils.importlib import func_name
from ..utils.importlib import module_name
from ..utils.importlib import require_modules
deprecation(
name='ddtrace.contrib.util',
message='Use `ddtrace.utils.importl... |
import argparse
import decimal
import logging
from decimal import Decimal, ROUND_DOWN, ROUND_UP
class CLI:
def __init__(self):
self.args = None
self.requirement = None
self.tax_rate = None
self.tolerance = None
logging.basicConfig(level=logging.INFO)
... |
# Generated by Django 2.0.5 on 2018-05-14 13:45
from django.db import migrations
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('zconnect', '0005_org_device_related_name'),
]
operations = [
migrations.AddField(
model_name='user'... |
import pygame,sys,time
SCREEN_WIDTH,SCREEN_HEIGHT = 800,680
BOARD_ORDER,BOARD_SIZE = 19,30
BOARD_X0,BOARD_Y0 = 15,15
GRID_NULL,GRID_BLACK,GRID_WHITE = 0,1,2
SPEED_X = [1,0,1,-1]
SPEED_Y = [0,1,1,1]
def is_five(grid,x,y,flag):
# print(grid)
try:
for i in range(4):
# print(i)
isF = True
cx,cy = x,y
# is =... |
p = float(input('Digite o seu peso: '))
a = float(input('Digite sua altura: '))
imc = p/a**2
if imc < 18.5:
print('Abaixo do peso!')
elif 18.5 <= imc < 25:
print('Peso ideal!')
elif 25 <= imc < 30:
print('Sobrepeso!')
elif 30 <= imc < 40:
print('Obesidade!')
else:
print('Obesidade mórbida!')
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.template.defaultfilters import safe
from django.utils.translation import ugettext_lazy as _
from backend.plugins.mailchimp.models import MailchimpPluginModel
from backend.plugins.module_name import MODULE_NAME
@plugin_pool.... |
# -*_ coding: utf-8 -*-
# chris 073015
from HTMLParser import HTMLParser
from argparse import ArgumentParser
from contextlib import closing
from os.path import commonprefix
from urllib2 import urlopen
base = 'http://www.fileformat.info/info/unicode/category'
htmlunescape = HTMLParser().unescape
# Get characters.
d... |
# Parameter modes:
# 0 - position mode (parameter is position)
# 1 - immediate mode (parameter is value)
#
# Opcodes:
# 1 - add: Read three next cells (x, y, z) read memory at adresses x and y,
# add them and store at address z, then move instruction pointer
# 2 - multiply: like 1, but multiply instead of add
# 3 -... |
from functools import partial
from typing import Any, Dict, Iterable, Union
from sqlalchemy.schema import Table
from todolist.infra.database.models.todo_item import TodoItem
from todolist.infra.database.models.user import User
from todolist.infra.database.sqlalchemy import metadata
ValuesType = Dict[str, Any]
def... |
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
ones = [sum(row) for row in mat]
return heapq.nsmallest(k, range(len(mat)), key=lambda x : (ones[x], x))
|
import logging
import numpy as np
from .analysis import Idealizer
from ..constants import CURRENT_UNIT_FACTORS, TIME_UNIT_FACTORS
from ..utils import round_off_tables
debug_logger = logging.getLogger("ascam.debug")
ana_logger = logging.getLogger("ascam.analysis")
class IdealizationCache:
def __init__(
... |
#!/usr/bin/python
import os
import sys
import xml.etree.ElementTree as ET
def read_xml_labels(labelfn):
tree = ET.parse(labelfn)
labs = tree.getroot()
a = labs[1]
b = a.getchildren()
labs = {"ind": [], "name": []}
for tb in b:
labs["ind"].append(int(tb.attrib["index"]))
labs[... |
from astropy.timeseries import LombScargle
from hydroDL.post import axplot, figplot
import matplotlib.pyplot as plt
import importlib
import pandas as pd
import numpy as np
import os
import time
# test
xd = np.arange('1990-01-01', '2000-01-01', dtype='datetime64[D]')
xx = (xd-np.datetime64('1990-01-01')).astype(np.f... |
import flask
from groups import *
from constants import *
from sqlalchemy.orm import aliased
@app.route('/plots/statistics', methods=['GET'])
@flask_login.login_required
def get_statistic_plots():
group = flask_login.current_user.group
if group is None:
return 'You are not in a group.'
plots = St... |
img_file = open('MARG Python Assignment 3 (Data).csv', 'r')
img = img_file.read()
img_file.close()
img = img[:-1].split('\n')
img = [x.split(',') for x in img]
img = img[::2]
for i in range(len(img)):
img[i] = img[i][::2]
for j in range(len(img[i])):
img[i][j] = int(img[i][j]) / 255
data = ''
for row in img:... |
from __future__ import division
from menpo.transform import AlignmentSimilarity, Similarity
import numpy as np
from menpo.visualize import progress_bar_str, print_dynamic
def name_of_callable(c):
try:
return c.__name__ # function
except AttributeError:
return c.__class__.__name__ # callable ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script de actualizacion automatica para Hurricane Electric DNS
# Testeado en Python 3.4 windows, Debian
#BSD
#Copyright (c) 2016, Ales Daniel alesdaniel77@gmail.com
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modif... |
import logging
import re
import xml.etree.ElementTree
import requests
from .csl_item import CSL_Item
from .citekey import regexes
from manubot.util import get_manubot_user_agent
class CSL_Item_arXiv(CSL_Item):
def _set_invariant_fields(self):
# Set journal/publisher to arXiv
self["container-titl... |
from rest_framework import viewsets
from .models import Account
from .serializers import AccountSerializer
class AccountViewSet(viewsets.ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
|
'''
Created on Sep 13, 2017
@author: mmullero
'''
import os
# configuration
class Config(object):
MONGODB_URI = "mongodb://localhost:27017/"
MONGODB_DB = "stjoern-scrapper"
basedir = os.path.abspath(os.path.dirname(__file__))
logpath = os.path.join(basedir, 'stjoern-scrapper.log')
chromedriver_lo... |
from pgso.evaluate import error, evaluate, update_velocity, update_position
from multiprocessing import Manager, Process, Lock
from pgso.init_particles import create_n_particles
from sklearn.utils import shuffle
from tqdm import tqdm
from numba import jit
import numpy as np
import copy
def sample_data(X_train, y_trai... |
from classes.PathManager import PathManager
temp = PathManager(file_name="index.m3u8")
print(temp.__dict__)
|
#!/usr/bin/env python
import sys
import math
# The PYTHONPATH should contain the location of moose.py and _moose.so
# files. Putting ".." with the assumption that moose.py and _moose.so
# has been generated in ${MOOSE_SOURCE_DIRECTORY}/pymoose/ (as default
# pymoose build does) and this file is located in
# ${MOOSE_S... |
from django.db.models.signals import post_save
from django.contrib.auth import get_user_model
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.dispatch import receiver
from schools.models import AuditEntry
User = get_user_model()
# https://stackoverflow.com/a/37... |
from types import StringType, ListType
from oldowan.polymorphism import Polymorphism
def sites2str(sites):
"""Transform a list of Polymorphisms to a string.
"""
processing = []
for x in sites:
# unnested (unambiguous) sites get directly pushed to the string
if isinstance(x,Polymorphism... |
from slovodel_bot.view import keyboard
from slovodel_bot.model import word_maker
def test_get_keyboard():
kb_dict_referense = {
"keyboard": [["Существительное", "Прилагательное", "Глагол"]],
"resize_keyboard": True,
"one_time_keyboard": False,
"selective": False,
}
assert ... |
#! /usr/bin/env python3
"""
Scan blockchain transactions, and find JM transactions.
This script prints JMTXs IDs, and optionally dumps them to a pickle file.
"""
import os
from argparse import ArgumentParser
from jm_unmixer.misc import pkl_append, map_with_progressbar
from jm_unmixer.btccommon import BLOCKCHAIN, Bloc... |
import tensorflow as tf
from tensorflow.keras.layers import Layer
"""
The name of this isn't exactly right, but using `selection` as a placeholder for
now. This file will contain the function for "applying" a selection
score/weights to a sequence (typically the values in standard attention)
"""
class SelectionApply(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.