content stringlengths 5 1.05M |
|---|
from django.db import models
class Rating(models.Model):
full_name = models.CharField(max_length=255)
term = models.PositiveSmallIntegerField()
volume = models.PositiveIntegerField()
risk_level = models.PositiveSmallIntegerField()
credit_history = models.BooleanField()
wages = models.PositiveIn... |
# encoding: utf-8
import os, re, requests
import lxml.html
import workon.utils
__all__ = ["opengraph"]
def opengraph(url, *args, **kwargs):
metadata = {}
if not url:
return metadata
url = workon.utils.append_protocol(url)
try:
r = requests.get(url, *args, **kwargs)
except requests... |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
import serial
import numpy as np
import csv
import time
impo... |
import json
from pathlib import Path
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from opal_common.authentication.signer import JWTSigner
class JwksStaticEndpoint:
"""
configure a static files endpoint on a fastapi app, exposing JWKs.
"""
def __init__(
self,
... |
Inventory = {'tomatoes' : 5}
print(Inventory)
user_food = input("What food do you want to update?")
if user_food in Inventory :
user_operation = input("Do you want to 'add' or 'remove' %s from Inventory?" % user_food)
if user_operation == "add":
user_quantity = input("How many do you want to %s?" % user_operatio... |
# Generated by Django 2.2.10 on 2020-03-04 11:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agents', '0003_alter_agent_name'),
]
operations = [
migrations.AlterField(
model_name='agent',
name='based_near',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-02-24 21:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rentals', '0002_auto_20180224_2031'),
]
operations... |
import json
import datetime
from service import db
from service.model.user import User
from service.tests.base import BaseTestCase
from service.tests.utils import add_user, id_generator, add_random_user
class TestUserServiceGET(BaseTestCase):
''' Tests for GET on Users Service. '''
def test_get_... |
#!/usr/bin/python3
"""an instance of the specified class"""
def is_same_class(obj, a_class):
"""instance of theclass"""
return True if type(obj) == a_class else False
|
__title__ = 'pyfcm'
__summary__ = 'Python client for FCM - Firebase Cloud Messaging (Android, iOS and Web)'
__url__ = 'https://github.com/olucurious/pyfcm'
__version__ = '1.5.2'
__author__ = 'Emmanuel Adegbite'
__email__ = 'olucurious@gmail.com'
__license__ = 'MIT License'
|
#! /usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
# Written by Vasaant S/O Krishnan on Tuesday, 06 March 2018
# 03-dirac-vis.py "dirac visibility" plots aim to replicates figures from
# page 33 of "00 Fundamentals of Radio Interferometry 1 - Perley.pdf"
# https://science.nrao.edu/science/meet... |
from apps.repo.models import Answers
from apps.accounts.models import User
from django.db.models import Count
from apps.repo.models import Answers, User, Questions
from django.db.models import Count
def check_rank(data):
return data["id__count"]
def recent_user():
"""最近刷题的同学"""
# 按用户统计刷题的数量(新近刷的在后面)
... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys
filename = sys.argv[1]
data = pd.read_csv(filename, header=None,delim_whitespace=True)
data = np.array(data).flatten()
print(data)
fig, ax = plt.subplots()
ax.plot(range(0,int(data.shape[0])), data[:], '-o')
plt.show()
|
import datetime
import factory
from taggit import models as taggit_models
from . import models
from ..core.utils import datetime_now
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
nsid = factory.Sequence(lambda n: "%s@N01" % (n * 10000))
username = factory... |
import math
import locale
locale.setlocale(locale.LC_ALL, '')
def get_change(x, y):
return {"change": math.floor(x / y),
"left_over": (math.ceil((x - math.floor(x / y) * y) * 100) / 100)}
while 1:
cash = float(input("Enter amount: "))
if cash < 0:
print("Invalid input.")
cont... |
# coding: UTF-8
print(r'''
【程序51】题目: 小姐队列
本题是柏林大学的一次考试题,要求在30分钟内做出,不过只有少于10%的人完成了要求。计分是这样的,共150分,从1到30分钟,每加1分钟减2分,那么30分钟答出就是90分,是及格分;从30分钟以后每加1分钟减1分。我当时用了22分钟,大家也试试,看自己能得多少分。
原题:
有五位小姐排成一列,所有的小姐姓不同、穿的衣服颜色不同、喝不同的饮料、养不同的宠物、吃不同的水果。
钱小姐穿红色衣服;翁小姐养了一只狗;陈小姐喝茶;穿绿衣服的站在穿
白衣服的左边;穿绿衣服的小姐喝咖啡;吃西瓜的小姐养鸟;穿黄衣服的小姐吃
梨;站在中间的小姐喝牛奶;赵小姐站在最左... |
def command_ping(self, command, user):
self.send_message(self.CHAN, "Pong")
|
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ... |
#!/usr/bin/env python
import sys
import os
import os.path
import logging
import numpy
import icecube.icetray
import icecube.dataio
import icecube.clsim
import icecube.clsim.shadow
import icecube.clsim.shadow.cylinder_utils
import icecube.dataclasses
import icecube.phys_services
import icecube.simclasses
from I3Tra... |
# !!!! impoprtant !!!!
# be sure to add:
# nameofthefile-x-
# in front of every id, otherwise Dash will not work. Read more in readme.md
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id="template-x-graph"),
html.P("Title")... |
import pytest
import psycopg2
from sqlalchemist import get_config
@pytest.fixture
def config():
return get_config()
def test_configuration(config):
assert "database" in config
assert "DB_CONNECTION_STRING" in config.database
def test_connection(config):
config = get_config()
psycopg2.connect(... |
__all__ = [
"Embeddings", "FastText",
"FastTextEmbeddings", "GloveFormatEmbeddings", "HDF5Embeddings",
"BinaryEmbeddings"
]
from .embeddings import *
from .fasttext import *
from .glove import *
from .hdf5 import *
from .bin import *
|
from django.core.management.base import BaseCommand, CommandError
from build.management.commands.base_build import Command as BaseBuild
from django.conf import settings
from django.db import connection
from django.db import IntegrityError
from protein.models import (Protein, ProteinConformation, ProteinState, ProteinF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', ... |
import sys
import multiprocessing
import os
try:
from mpi4py import MPI
except ImportError:
MPI = None
import gym
from gym.wrappers import FlattenObservation, FilterObservation
from baselines import logger
from baselines.bench import Monitor
from baselines.common import set_global_seeds
from baselines.common.a... |
"""
REFERENCES:
[tra17] Tramer et al. "The Space of Transferable Adversarial Examples," 2017.
[tbd17a] "Decision Boundary Analysis of Adversarial Examples," blind ICRL submission 2017.
[tbd17b] "Visualizing the Loss Landscape of Neural Nets," blind ICLR submission 2017.
"""
__author__ = "mjp"
__date__ = "no... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
#-------------------------------------------------------------------------------
# Revc
#-------------------------------------------------------------------------------
def runRevc(inputFile):
fi = open(inputFile, 'r') #reads in the file that list the before/after file names
inputData = fi.read() #reads in fil... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2015 Red Hat, Inc.
# Author: Petr Spacek <pspacek@redhat.com>
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the ... |
import re
import yaml
FM_BOUNDARY = re.compile(r"^---$", re.MULTILINE)
def split(content):
try:
_, fm, body = FM_BOUNDARY.split(content, 2)
except ValueError:
raise ValueError("Invalid front matter content")
try:
fm_data = yaml.safe_load(fm)
except yaml.scanner.ScannerError:
... |
# -*- coding: utf-8 -*-
import xlrd
import xlwt
from datetime import date,datetime
from xlutils.copy import copy
def read_excel():
# # 打开文件
# workbook = xlrd.open_workbook(r'books.xls')
# # 获取所有sheet
# print workbook.sheet_names() # [u'sheet1', u'sheet2']
# sheet2_name = workbook.sheet_names()[1]
... |
import json
import unittest
from .. import address, slp
script_tests_json = r"""
[
{
"msg": "OK: minimal GENESIS",
"script": "6a04534c500001010747454e455349534c004c004c004c0001004c00080000000000000064",
"code": null
},
{
"msg": "OK: typical MINT without baton",
"script": "6a04534c50000101044d494e5420ffff... |
"""Expectations that can be held against metrics collected in Graphite"""
from abc import abstractmethod
SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60
SECONDS_PER_DAY = SECONDS_PER_HOUR * 24
def _avg(readings):
"""Python 2.7 does not have an average function"""
return sum(readings, 0.0)... |
#!/usr/bin/env python
import sys
import os
import socket
import string
import time
import locale
import codecs
import urllib2
import re
import HTMLParser
import json
import urllib
def decode(bytes):
try:
text = bytes.decode('utf-8')
except UnicodeDecodeError:
try:
text = bytes.de... |
CONTAINS_ADS_MESSAGES = {
"af": "Bevat advertensies",
"sq": "Contains Ads",
"en": "Contains Ads",
"ar": "تتضمن إعلانات",
"az": "Contains Ads",
"eu": "Contains Ads",
"be": "Утрымлівае аб'явы",
"bn": "Contains Ads",
"hi": "इसमें विज्ञापन शामिल हैं",
"bs": "Contains Ads",
"bg": ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*- ########################################################
# ____ _ __ #
# ___ __ __/ / /__ ___ ______ ______(_) /___ __ #
# / _ \/ // / / (_-</ -_) __/ // / __/ / __/ // / ... |
import os
import sys
import numpy as np
pairs = {
'}' : '{',
']' : '[',
')' : '(',
'>' : '<'
}
scores1 = {
'}': 1197,
')': 3,
']': 57,
'>': 25137,
}
def get_first_illegal(line):
stack = []
for char in line:
if char in pairs:
if stack and stack.pop() == p... |
import FWCore.ParameterSet.Config as cms
from DQM.TrackingMonitor.LogMessageMonitor_cfi import *
LocalRecoLogMessageMon = LogMessageMon.clone(
pluginsMonName = 'LocalReco',
modules = ('siPixelDigis', 'siStripDigis', 'siPixelClusters', 'siStripClusters',), # siPixelDigis : SiPixelRawToDigi, siStripDigis : SiSt... |
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"tool_path",
)
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_lib... |
import tobii_research as tr
class EyeTracker:
def __init__(self):
self.start = False
self.gaze = {"Left": [0, 0], "Right": [0, 0]}
found_eyetrackers = tr.find_all_eyetrackers()
if len(found_eyetrackers) > 0:
print(found_eyetrackers)
self.my_eyetracker = fo... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# 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.or... |
import pytest
from numpy.testing import assert_array_equal
from sparseba.indices import Indices, indices_are_unique
def test_indices_are_unique():
# unique
Indices([0, 1, 2, 0, 2, 1, 2, 0, 1],
[0, 0, 0, 1, 1, 2, 2, 3, 3])
with pytest.raises(ValueError):
# second and third are duplica... |
import itertools
import networkx as nx
import numpy as np
from arsenic import stats
from arsenic.stats import bootstrap_statistic
def test_mle_easy():
"""
Test that the MLE for a graph with an absolute
estimate on all nodes will recapitulate it
"""
input_absolutes: list = [-14.0, -13.0, -9.0]
... |
import pytest
@pytest.mark.parametrize("run", ["value_template.json"], indirect=True)
def test_value_template(run):
assert run == 0
with open("value_template_string.txt") as f:
assert f.read() == '42 42'
with open("value_template_file.txt") as f:
assert f.read() == '42\n42'
with open("... |
my_name = "Steveen Echeverri"
print("Hello and welcome " + my_name + "!") |
class Value(object):
def __init__(self, t, v, f=False):
'''
t = type (VARIABLE/CONSTANT/ ARRAY)
v = value (string / integer / tuple variable respectively)
f = flag, True if array is DIO, PWM, TMR, etc.
'''
self.type = t
self.val = v
self.flag = f
def is_arr_var(self):
'''
checks if the v... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Console script for pimkl."""
import sys
import click
from pimkl.cli.preprocess import preprocess_data_and_inducers
from pimkl.cli.analyse import analyse, kpca
@click.command()
@click.option('-fd', '--data_csv_file', 'data_csv_files', required=True, multiple=True, type=... |
data = [int(i) for i in input()]
width = 25
height = 6
num_in_layer = width * height
layers = []
for i, c in enumerate(data):
if (i % num_in_layer) is 0:
layers.append([])
layers[-1].append(c)
# for i, layer in enumerate(layers):
# print("Layer " + str(i) + ": " + str(layer))
image = [0] * num_... |
#!/usr/bin/env python
import os
import joblib
import argparse
from PIL import Image
from util import draw_bb_on_img
from constants import MODEL_PATH
from face_recognition import preprocessing
def parse_args():
parser = argparse.ArgumentParser(prog='Face Classifier',
description='Script for detecting and clas... |
#! /usr/bin/env python3
# Dump the cache to dump.txt (used for faster manual injection to skip generation for demos)
import argparse
import time
import sys
import logging
import pandas as pd
from getargs import getargs
from config import *
import config
import utils
import xmlutils
import montecarlo
import azlog
imp... |
import redis
def pace():
pass
def unpace():
pass
def run():
pacing = False
promt = "Press ENTER to {}"
try:
while True:
if pacing:
input(promt.format("unpace"))
unpace()
else:
input(promt.format("pace"))
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... |
import json
from unittest.mock import Mock
from urllib import parse
import pytest
from rest_framework.test import APIRequestFactory, APITestCase, force_authenticate
from django.test import override_settings
from django.urls import reverse
from authentication.factories import UserFactory, StaffUserFactory
from authent... |
#!/usr/bin/env python3
# Copyright (c) 2016 Iotic Labs Ltd. All rights reserved.
#
# 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
#
# https://github.com/Iotic-Labs/py-IoticAgent/blob/maste... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""iterator over an sdf files"""
from builtins import next
from builtins import object
from subprocess import Popen, PIPE
import re
class GzipFile(object):
def __init__(self, path):
self.p = Popen(
'zcat %s' % path,
bufsize=1024,
... |
import os
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn_instrumentation import SklearnInstrum... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import Queue
import signal
import sys
import os
import threading
import time
from ConfigParser import ConfigParser
from thread_manager import ThreadManager
from thread_mysql import ThreadMySQL
from thread_statsd import ThreadStatsd, ThreadFakeStatsd
clas... |
#!/usr/bin/env python
import boto
from boto.s3.key import Key
OrdinaryCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.OrdinaryCallingFormat')
s3 = boto.connect_s3(host='localhost', port=10001, calling_format=OrdinaryCallingFormat, is_secure=False)
b = s3.create_bucket('mocking')
keys = b.... |
from conekt import db
import json
SQL_COLLATION = 'NOCASE' if db.engine.name == 'sqlite' else ''
class ConditionTissue(db.Model):
__tablename__ = 'conditions_tissue'
id = db.Column(db.Integer, primary_key=True)
species_id = db.Column(db.Integer, db.ForeignKey('species.id', ondelete='CASCADE'))
data ... |
#!/usr/bin/env python
# encoding: utf-8
from pyxtal import print_logo
from pyxtal.symmetry import Group
from argparse import ArgumentParser
if __name__ == "__main__":
# -------------------------------- Options -------------------------
parser = ArgumentParser()
parser.add_argument(
"-s",
... |
# 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
# distrib... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.params import ParlaiParser
from parlai.mturk.tasks.light.light_chats.worlds import (
LightChatOnboar... |
from enum import IntEnum, Enum
from typing import Dict, Optional
from enocean.protocol.constants import PACKET
from enocean.protocol.packet import RadioPacket
from src.common.eep import Eep
from src.common.switch_state import SwitchState
from src.enocean_packet_factory import EnoceanPacketFactory
from src.common.eep... |
import unittest
from ..lib.data import register_data_generator, DataGenerator, data_generator_map
from ..lib.iterator import ConfigIterator, register_config_iterator, config_iterator_map
from ..lib.operator import (
register_operator,
register_operators,
OperatorInterface,
op_map,
)
class TestRegiste... |
import os
import urllib.parse as urlparse
from cgitb import text
import string
from flask import Flask, render_template, request, Response, redirect, url_for, abort
import psycopg2
from psycopg2 import pool
import toml
import math
from models import Page
from psycopg2.extras import DictCursor
from jinja2 import ... |
from myutils.utils import getConnection, cronlog
import pandas as pd
import numpy as np
import datetime
import requests
class TestRequest:
def __init__(self, url, method='GET', META=None, postdata=None):
self.method = method
u = url.split('?')
self.path_info = u[0]
self.META = META... |
# Generated by Django 3.0 on 2020-02-07 08:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hlwtadmin', '0008_venue_non_assignable'),
]
operations = [
migrations.AddField(
model_name='historicalorganisation',
n... |
#!/usr/bin/env python3
import math
import time
def is_prime(number):
if number < 2:
return False
for divisor in range(2, int(math.sqrt(number)) + 1):
if number % divisor == 0:
return False
return True
def main():
limit = 0.1
number = 9
side_length = 3
number_... |
import tensorflow as tf
from datetime import datetime
from logger.logger import Logger
from models.multimodal import JointTwomvae
from models.multimodal import AssociatorVideoAc
from models.multimodal import AssociatorAudio
from models.multimodal import AssociatorAudioAc
from models.multimodal import Jointmvae
from mod... |
from copy import copy
from doculabs.samon import registry
from doculabs.samon.loaders import BaseLoader
from doculabs.samon.parser import DefaultParser
from doculabs.samon.template import Template
class Environment:
DEFAULT_TEMPLATE_CLASS = Template
def __init__(self, loader: BaseLoader):
self.loade... |
import sys
sys.path.append('../')
import matplotlib.pyplot as plt
import json
from pprint import pprint
import numpy as np
Settings = json.load(open('settings.txt'))
from cabbage.features.ReId import StoredReId
pprint(Settings)
import numpy as np
import sys
sys.path.append('../')
from cabbage.regression.Regression impo... |
from django.apps import AppConfig
class SliderConfig(AppConfig):
name = 'Slider'
verbose_name = 'ماژول اسلایدر'
|
"Define stdlibs"
load("@io_bazel_rules_dotnet//dotnet/private:rules/stdlib.bzl", "core_stdlib_internal")
load("@io_bazel_rules_dotnet//dotnet/private:rules/libraryset.bzl", "core_libraryset")
def define_stdlib():
"Declares stdlibs"
core_libraryset(
name = "NETStandard.Library",
deps = [
... |
import os
import sys
import hashlib
from sys import platform
from banner import access
from menu import OPEN
from plat import check
########################################
# Educational purpose only #
########################################
# I'm not responsible for your actions #
###########... |
#!/usr/bin/python
# Run continuously, getting the auto-added names from the DB and adding them to the
import urllib3
import sys
from xml.dom.minidom import parseString
import json
from pymongo import MongoClient, ReturnDocument
import time
sandboxHost = 'https://api.sandbox.namecheap.com/xml.response'
sandboxAuthenti... |
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import pdb
from itertools import chain
def normalize(W):
W_norm = torch.norm(W)
W_norm = torch.relu(W_norm - 1) + 1
W = W/ W_norm
return W
class SamePadConv(nn.Module):
def __init__(self, in_channels, out_channel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# test_utilities.py
"""unittest cases for utilities."""
#
# Copyright (c) 2020 Dan Cutright
# This file is part of DVHA-Stats, released under a MIT license.
# See the file LICENSE included with this distribution, also
# available at https://github.com/cutright/DVHA-... |
from magpie import Magpie
import time
count = 10
magpie = Magpie()
while (count <= 500):
start = time.clock()
magpie.train_word2vec('data/hep-categories', vec_dim=count)
magpie.save_word2vec_model('save/embeddings/here'+str(count), overwrite=True)
end = time.clock()
runtime = end - start
print(... |
import enum
from app import db
from datetime import datetime
class MessageType(enum.Enum):
""" MessageType class """
USER = 'user'
BOT = 'bot'
class Message(db.Model):
""" Message model class """
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
msg_type = db.... |
from rest_framework.permissions import AllowAny
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from django.http import response
from django.shortcuts import redirect
from .models import UrlDetailes
from django.shortcuts import render, HttpResponse
from .models import UrlDe... |
from q2_pepsirf.actions.norm import norm
from q2_pepsirf.actions.info import infoSumOfProbes, infoSNPN
from q2_pepsirf.actions.enrich import enrich
from q2_pepsirf.actions.zscore import zscore
from q2_pepsirf.actions.bin import bin
__all__ = ['norm', 'infoSumOfProbes', 'infoSNPN', 'enrich', 'zscore', 'bin'] |
"""Module to handle initialization, imports, for DeepDAO class"""
from .deepdao import *
|
#!/usr/bin/python3
"""Recipe for training a classifier using the
mobvoihotwords Dataset.
To run this recipe, use the following command:
> python train.py {hyperparameter_file}
Using your own hyperparameter file or one of the following:
hyperparams/xvect.yaml (xvector system)
"""
import os
import sys
import torch... |
#!/home/loris/anaconda3/envs/py3/bin/python
import numpy as np
from numpy import pi
from math import sin,cos
import rospy
from beginner_tutorials.msg import o3d_coord_msg
from try_bayesian.msg import bayesian_msg
from scipy.spatial.transform import Rotation as R
import re
def normalizer(coord_to_be_norm, lower_limit... |
import os
import numpy as np
def softmax(logits):
"""Transforms predictions into probability values.
Parameters
----------
logits : array_like
The logits predicted by the model.
Returns
-------
`numpy.ndarray`
Probability values corresponding to the logits.
"""
... |
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
plugin_enable=False
try:
import subprocess
import plugin
print("Import plugin successfully")
plugin_enable=True
except (ImportError, RuntimeError, FileNotFoundError, subprocess.CalledProcess... |
# -*- coding:utf8 -*-
import time
import Article as art
# FIXME: 很多公众号一天可以推文很多次。需要改名为PublishArticle
class PublishArticle:
# 今天的发布的类型,只统计图文消息:49
type = 49
biz = ""
nickname = "" # 怎么获取,直接外部设置吧
# 发布时间,Unix时间戳
datetime = 0
# 今天的文章,idx:article
articles = {}
standardtime = ""
de... |
''' Override for function from built-in json module to allow formatting of JSON two container types
(arrays and objects), to be optionally specified separately by allowing `indent` to be a 2-tuple.
Copied this from v3.5.6 (Lib/json/encoder.py) but looks about the same in 3.4-3.6. Probably wont
work in >=3.7.
'''
d... |
#!/usr/bin/python
from datetime import datetime as dt
from sys import stdout
from requests import get
from time import sleep
from dbus import SessionBus
from multiprocessing import Process, Queue
notification_time = 10# notification display time, in seconds
wait_interval = 360# time between stream checks, in seconds
... |
import numpy as np
def spherical_to_cartesian(r, theta, phi):
x = r*np.sin(phi)*np.cos(theta)
y = r*np.sin(phi)*np.sin(theta)
z = r*np.cos(phi)
return x, y, z
def cylindrical_to_cartesian(r, theta, z):
x = r*np.cos(theta)
y = r*np.sin(theta)
z = z
return x, y, z
def spherical_uni... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: 0.1
@author: quantpy
@file: timeout.py
@time: 2018-07-03 14:16
"""
from functools import wraps
from contextlib import contextmanager
import threading
import _thread
@contextmanager
def timeout_context(seconds, msg=''):
"""超时环境管理器"""
timer ... |
import sys
from collections import defaultdict
if __name__ == '__main__':
feats_rspecifier = sys.argv[1]
train_dir = sys.argv[2]
val_dir = sys.argv[3]
num_valid_utts = int(sys.argv[4])
feats = defaultdict(list)
with open(feats_rspecifier, 'r') as f:
for line in f:
line = l... |
from argus.backend.models import ArgusEventTypes
def event_process_posted_comment(event: dict) -> dict:
return event["message"].format(**event)
def event_process_status_changed(event: dict) -> dict:
return event["message"].format(**event)
def event_process_assignee_changed(event: dict) -> dict:
return... |
# -*- coding: utf-8 -*-
"""Parse Archimate XML Exchange File Format into a MongoDB DB""" |
from qtpyvcp.widgets.form_widgets.main_window import VCPMainWindow
from qtpy.QtCore import Slot
from qtpy.QtWidgets import QAbstractButton
from PyQt5.QtSql import QSqlDatabase
# Setup logging
from qtpyvcp.utilities import logger
LOG = logger.getLogger('qtpyvcp.' + __name__)
import os
current_path = os.path.dirname(os... |
#! /usr/bin/env python3
################################################################################
# File Name : l6e6.py
# Created By : Félix Chiasson (7138723)
# Creation Date : [2015-10-20 13:15]
# Last Modified : [2015-10-20 13:47]
# Descriptio... |
# tkinter is the Python standard library which serves as an interface to Tk, a simple toolkit, for building GUI applications using event-driven programming.
# https://python-textbok.readthedocs.io/en/stable/Introduction_to_GUI_Programming.html
# https://docs.python.org/3.7/library/tkinter.html
# FIRST GUI APP WITH WI... |
#!/usr/bin/env python
import sys
from pyami import mrc
from pyami import correlator
from pyami import peakfinder
from pyami import imagefun
import scipy.fftpack
import scipy.ndimage
import scipy
import numpy
def makeMapping(output_shape, center, dr, dt):
key = (output_shape, center, dr, dt)
if key in mappings:
re... |
from rest_framework import serializers
from unicef_restlib.fields import (
CommaSeparatedExportField,
DynamicChoicesField,
FunctionRelatedField,
SeparatedReadWriteField,
WriteListSerializeFriendlyRecursiveField,
)
from unicef_restlib.serializers import (
DeletableSerializerMixin,
PKSerializ... |
"""
Mathhew Roughan et. al in 'The many facets of Internet topology and traffic':
Gravity Model for TM synthesizing:
X_ij = R_i * A_j / f_ij
R_i as the volume of incoming traffic
A_j as the outgoing traffic
The friction matrix (fij ) encodes the locality information specific to different source-destination pairs, howe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.