content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import torch
from torch import nn
import clinicaldg.eicu.Constants as Constants
class FlattenedDense(nn.Module):
def __init__(self, ts_cat_levels, static_cat_levels, emb_dim, num_layers, num_hidden_units,
t_max = 48, dropout_p = 0.2):
super().__init__()
self.ts_... | python |
'''
Copyright University of Minnesota 2020
Authors: Mohana Krishna, Bryan C. Runck
'''
import math
# Formulas specified here can be found in the following document:
# https://www.mesonet.org/images/site/ASCE_Evapotranspiration_Formula.pdf
# Page number of each formula is supplied with each function.
def get_delta(t... | python |
from pathlib import Path
from cosmology import Cosmology
from instruments import Instrument
class Simulation:
def __init__(self, data_path, save_path, field, sim_type='src_inj',
cosmo='Planck18'):
self.data_path = Path(data_path)
self.save_path = Path(save_path)
self.field... | python |
# -*- coding: utf-8 -*-
class Solution:
def countPrimes(self, n):
if n == 0 or n == 1:
return 0
result = [1] * n
result[0] = result[1] = 0
for i, el in enumerate(result):
if el:
for j in range(i * i, n, i):
result[j] = 0... | python |
import logging
import os
from nose.plugins import Plugin
log = logging.getLogger('nose.plugins.helloworld')
class HelloWorld(Plugin):
name = 'helloworld'
def options(self, parser, env=os.environ):
super(HelloWorld, self).options(parser, env=env)
def configure(self, options, conf):
super... | python |
from __future__ import absolute_import
from pyramid.view import view_config
from sqlalchemy import func, and_, or_
from . import timestep_from_request
import tangos
from tangos import core
def add_urls(halos, request, sim, ts):
for h in halos:
h.url = request.route_url('halo_view', simid=sim.escaped_basen... | python |
#!/usr/bin/python3
#
# Copyright © 2017 jared <jared@jared-devstation>
#
# Generates data based on source material
import analyze
markov_data = analyze.data_gen()
| python |
#!/usr/bin/env python3
# coding = utf8
import datetime
import pytz
import time
import copy
import sys
def get_utc_datetime():
"""
获取utc时间
"""
utc_datetime_str = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
return utc_datetime_str
def get_utc_timestamp():
"""
获取utc时间的时间戳
... | python |
# -*- coding: utf-8 -*-
"""
Configurations
--------------
Specifies the set of configurations for a marksim package
"""
import os
class Configs:
"""
Configurations
"""
# TODO This might be not the best design decision to pack all variables under one class.
# tpm configs
MARKOV_ORDER = 1
... | python |
def test_dbinit(db):
pass
| python |
# https://leetcode.com/problems/random-pick-with-weight
import random
import bisect
class Solution:
def __init__(self, ws: List[int]):
s = sum(ws)
v = 0
self.cumsum = [v := v + w / s for w in ws]
def pickIndex(self) -> int:
return bisect.bisect_left(self.cumsum, random.unifor... | python |
from django.apps import AppConfig
default_app_config = 'mozillians.groups.GroupConfig'
class GroupConfig(AppConfig):
name = 'mozillians.groups'
def ready(self):
import mozillians.groups.signals # noqa
| python |
'''
Created on Jan 19, 2016
@author: elefebvre
'''
| python |
from django.apps import AppConfig
class GqlConfig(AppConfig):
name = 'gql'
| python |
from django.db.models import Q
from django.db.models.manager import Manager
class WorkManager(Manager):
def match(self, data):
"""
Try to match existing Work instance in the best way possible by the data.
If iswc is in data, try to find the match using the following tries:
1. Matc... | python |
from .bmk_semihost import *
| python |
"""
The borg package contains modules that assimilate large quantities of data into
pymatgen objects for analysis.
"""
| python |
from django.utils import timezone
from django.contrib import admin
from django.urls import path
from .models import Post, Category, Tag, Comment, Commenter
from . import views
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author','status', 'last_edition_date']
readonly_fie... | python |
import matplotlib.pyplot as plt
import numpy as np
import random as rd
dim = 100
def reward(i, j):
string = dim/2
bp = complex(dim/2, dim/2)
bp = (bp.real, bp.imag)
cp = complex(i, j)
cp = (cp.real, cp.imag)
xdiff = cp[0]-bp[0]
if bp[1] < cp[1]:
s = 1/(1 + 10*abs(bp[0]-cp[0])/stri... | python |
import gi
import enum
import g13gui.model.bindings as bindings
from g13gui.observer.gtkobserver import GtkObserver
from g13gui.model.bindingprofile import BindingProfile
from g13gui.model.bindings import StickMode
from g13gui.model.bindings import ALL_STICK_MODES
gi.require_version('Gtk', '3.0')
gi.require_version('G... | python |
import numpy as np
from Matrices import *
print("Determinant of diagonal matrix:")
print(np.linalg.det(diag_A))
diag_A_rev = np.linalg.inv(diag_A)
print("Condition number of diagonal matrix:")
print(np.linalg.norm(diag_A_rev) * np.linalg.norm(diag_A))
print("Determinant of random matrix:")
print(np.linalg.det(random... | python |
import sys
import time
import threading
import queue
from hashlib import sha256
from secrets import token_bytes
import grpc
from lnd_grpc.protos import invoices_pb2 as invoices_pb2, rpc_pb2
from loop_rpc.protos import loop_client_pb2
from test_utils.fixtures import *
from test_utils.lnd import LndNode
impls = [LndNo... | python |
#!c:/Python26/ArcGIS10.0/python.exe
# -*- coding: utf-8 -*-
#COPYRIGHT 2016 igsnrr
#
#MORE INFO ...
#email:
"""The tool is designed to convert Arcgis Grid file to Series."""
# ######!/usr/bin/python
import sys,os
import numpy as np
import arcpy
from arcpy.sa import *
from arcpy import env
import shutil
import time
fr... | python |
# Generated by Django 2.0.7 on 2018-09-03 02:40
from django.db import migrations
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('zinnia-threaded-comments', '0002_migrate_comments'),
]
operations = [
migrations.AlterField(
... | python |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.2321
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class QuoteSeriesId(object):
"""NOTE: This class is... | python |
import unittest
from messages.message import Message
from messages.option import Option
from messages import Options
import defines
class Tests(unittest.TestCase):
# def setUp(self):
# self.server_address = ("127.0.0.1", 5683)
# self.current_mid = random.randint(1, 1000)
# self.server_mid... | python |
from django.core.validators import MinLengthValidator
from django.db import models
class Design(models.Model):
TYPE_CHOICE_INTERIOR = 'interior'
TYPE_CHOICE_PRODUCT = 'product'
TYPE_CHOICE_3D = '3d'
TYPE_CHOICE_OTHER = 'other'
TYPE_CHOICES = (
(TYPE_CHOICE_INTERIOR, 'Interior design'),
... | python |
from abc import ABC, abstractmethod
from typing import List
import numpy as np
from scipy.stats import t, spearmanr
from scipy.special import erfinv
from chemprop.uncertainty.uncertainty_calibrator import UncertaintyCalibrator
from chemprop.train import evaluate_predictions
class UncertaintyEvaluator(ABC):
"""
... | python |
import json
import glob
import luigi
import os
from dlib.task_helpers import parse_yaml, extract_task_config
from dlib.task_helpers import read_data, generate_output_filename, run_init
from dlib.identifier import Identify
from dlib.parser import Parser
from dlib.process_router import Processor
from dlib.btriples import... | python |
# -*- coding: utf-8 -*-
# @version : ??
# @Time : 2017/3/29 17:31
# @Author : Aries
# @Site :
# @File : shutil_0329.py
# @Software: PyCharm
import zipfile
"""
压缩 解压 .zip包
"""
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('test.txt')
z.write('test2.xml')
z.close()
# 解压
z = zipfile.ZipFile('laxi.zip', 'r... | python |
# Time: O(r * c)
# Space: O(1)
# Given a matrix A, return the transpose of A.
#
# The transpose of a matrix is the matrix flipped over it's main diagonal,
# switching the row and column indices of the matrix.
#
# Example 1:
#
# Input: [[1,2,3],[4,5,6],[7,8,9]]
# Output: [[1,4,7],[2,5,8],[3,6,9]]
# Example 2:
#
# Inpu... | python |
import logging
from typing import List
from api.token.service import Token
from api.calendar.service import CalendarService, Calendar
LOG = logging.getLogger(__name__)
class GoogleCalendarService(CalendarService):
IGNORED_CALENDARS = {'addressbook#contacts@group.v.calendar.google.com',
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
import codecs
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_pa... | python |
import os
import re
from string import letters
import random
import hashlib
import hmac
import webapp2
import jinja2
from jinja2 import Environment
from google.appengine.ext import db
from Handler import Handler
class Logout(Handler):
""" handles user logout safely """
def get(self):
self.logout()
... | python |
import numpy as np
import inspect # Used for storing the input
from .element import Element
from .equation import PotentialEquation
__all__ = ['Constant', 'ConstantStar']
class ConstantBase(Element, PotentialEquation):
def __init__(self, model, xr=0, yr=0, hr=0.0, layer=0, \
name='ConstantBase',... | python |
from mangofmt import MangoFile, EncryptionType, CompressionType, Language
def test_title():
mango = MangoFile()
meta = mango.meta_data
assert meta.title == None
meta.title = "test"
assert meta.title == "test"
def test_author():
mango = MangoFile()
meta = mango.meta_data
assert meta.a... | python |
import simplejson as json
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
import directory.models as directory
from appcon... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Tests of deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import base64
import mock
from asyncat.client import GithubError
from hindsight.finder import N... | python |
def mdc(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
def separadorFrac(frac):
novoNum = frac.getNum()
inteiro = 0
while novoNum > frac.getDen():
novoNum -= frac.getDen()
inteiro += 1
return inteiro, novoNum
def ... | python |
# -*- coding:utf-8 -*-
# 数据库定义
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cache import Cache
import memcache
import os
curdir = os.getcwd()
static_dir = curdir+'/static'
template_dir = curdir+'/templates'
app = Flask(__name__,static_folder=static_dir,template_folder=template_dir)
cac... | python |
SYMBOLS = \
[
# 1
'?', '!', '¿', '¡', ',', '.', '@', '#', '%', '&', '-',
'(', ')', '[', ']', ';', ':', '′', '‘', '’', '‚', '‛',
'\\', '/', '{', '}', '•', '…', '″', '“', '”', '„', '_',
'<', '>', '«', '»', '←', '→', '↑', '↓', '⇒', '⇔', '˜',
'$', '¢', '€', '£', '¥', '₽',... | python |
"""
DriverFactory class
Note: Change this class as you add support for:
1. SauceLabs/BrowserStack
2. More browsers like Opera
"""
import dotenv,os,sys,requests,json
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabil... | python |
from django.test import TestCase
from django.urls import reverse, resolve
from media_server.views import (
VideoListCreateView,
VideoRetrieveUpdateDestroyView,
GenreListCreateView,
GenreRetrieveUpdateDestroyView
)
class VideoListCreateViewUrlsTests(TestCase):
def test_urls(self):
url = re... | python |
# Copyright (C) 2018 Intel Corporation
#
# 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 wri... | python |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import os
import torch
import numpy as np
from dgp.datasets.synchronized_dataset import SynchronizedSceneDataset
from dgp.utils.camera import Camera, generate_depth_map
from dgp.utils.geometry import Pose
from packnet_sfm.geometry.pose_utils import inv... | python |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy_doubanmovie.scrapy_doubanmovie.items import ScrapyDoubanmovieItem
from urllib.parse import urljoin
# 通过scrapy genspider douban_spider movie.douban.com生成的
class DoubanSpiderSpider(scrapy.Spider):
#... | python |
from base64 import b64encode, b64decode
from random import randint
class UtilityService:
@staticmethod
def decode_bytes(s):
return b64decode(s).decode('utf-8')
@staticmethod
def encode_string(s):
return str(b64encode(s.encode()), 'utf-8')
@staticmethod
def jitter(fraction):
... | python |
"""Compare two HTML documents."""
from html.parser import HTMLParser
from django.utils.regex_helper import _lazy_re_compile
# ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020
# SPACE.
# https://infra.spec.whatwg.org/#ascii-whitespace
ASCII_WHITESPACE = _lazy_re_compile(r'[\t\n\f\r ]+')
de... | python |
# coding:utf-8
import MeCab
import codecs
from model import Seq2Seq
import chainer
import json
import sys
import io
class Chatbot:
def __init__(self, dirname):
self.dir = 'model/' + dirname + '/'
self.dict_i2w = self.dir + 'dictionary_i2w.json'
self.dict_w2i = self.dir + 'dictionary_w2i.jso... | python |
#!/usr/bin/python
#coding: utf-8 -*-
#
# (c) 2014, Craig Tracey <craigtracey@gmail.com>
#
# This module 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) an... | python |
# Obfuscated by Py Compile
# Created by Wh!73 D3v!1 (https://github.com/WHI73-D3VI1)
# Facebook : (https://www.facebook.com/WHI73.D3VI1)
# Don't try to edit or modify this tool
import marshal,zlib,base64
exec(marshal.loads(zlib.decompress(base64.b64decode("eJzNVd1PG0cQn7vDGBscvsJHoE2XUiduUr4bSFHUBoWGoDaUAirSIYQMt9hnfD... | python |
import datetime
import hashlib
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from tldr import app
from urllib.parse import urlparse
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
db = SQLAlchemy(app)
def baseN(num, b, numerals='0123456789abcdefghijklmnopqrstuvwxyz... | python |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpat... | python |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright 2019, GeoSolutions Sas.
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE.txt file in the root directory of this source tree.
#
#############################... | python |
# Generated by Django 2.2.13 on 2020-11-10 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0139_team_subtitle'),
]
operations = [
migrations.AlterField(
model_name='team',
name='subtitle',
... | python |
import time
from locust import HttpUser, between, task
class QuickstartUser(HttpUser):
wait_time = between(1, 2)
@task
def get_users(self):
self.client.get("/api/users/") | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data
# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP
# (c) 07/2019-present : DESY PHOTON SCIENCE
# authors:
# Jerome Carnis, carnis_jerome@yahoo.fr
import numpy as np
from numpy... | python |
from django.shortcuts import render
from django.views.generic import View
class IndexView(View):
""" An index view"""
template_name = "base.html"
def get(self, request):
""" GET to return a simple template """
return render(
request, self.template_name
)
| python |
"""
Tests for ESMTP extension parsing.
"""
from aiosmtplib.esmtp import parse_esmtp_extensions
def test_basic_extension_parsing():
response = """size.does.matter.af.MIL offers FIFTEEN extensions:
8BITMIME
PIPELINING
DSN
ENHANCEDSTATUSCODES
EXPN
HELP
SAML
SEND
SOML
TURN
XADR
XSTA
ETRN
XGEN
SIZE 51200000
"""
... | python |
import pytest
from liquid import *
def test_register_filter():
@filter_manager.register(mode='python')
def incr(base, inc=1):
return base + inc
liq = Liquid('{{ 2 | incr}}', dict(mode='python'))
assert liq.render() == '3'
liq = Liquid('{{ 2 | incr:2}}', dict(mode='python'))
assert liq.... | python |
#!/usr/bin/env python
import os
import json
with open(os.path.join(os.environ['BOOST_CI_SRC_FOLDER'], 'meta', 'libraries.json')) as jsonFile:
lib_data = json.load(jsonFile)
print(lib_data['key'])
| python |
#!/usr/bin/env python2.7
import sys
import argparse
import gzip
import clsnaputil
#assumes you already have the AUCs
#pulled out using:
#wiggletools print non_unique_base_coverage.bw.auc AUC non_unique_base_coverage.bw
RECOUNT_TARGET = 40 * 1000000
SNAPTRON_FORMAT_CHR_COL = 1
SNAPTRON_FORMAT_COUNT_COL = 11
def load_... | python |
from optparse import make_option
import os
import shutil
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import MySQLdb
from blog.models import Blog, Post, Asset
class Command(BaseCommand):
help = 'Import blog posts from Movable Type'
option_list = BaseCommand... | python |
"""Programa 8_5.py
Descrição: Reescrever a função da listagem 8.5 de forma a utilizar os métodos de pesquisa em lista vistos no cap 7.
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
valor = int (0)
# Entrada de dados
L = [10, 20, 25, 30]
# Processamento
def pesquise (lista, valor)... | python |
import asyncio
import logging
from timeit import default_timer as timer
from podping_hivewriter.async_context import AsyncContext
from podping_hivewriter.models.podping_settings import PodpingSettings
from podping_hivewriter.podping_settings import get_podping_settings
from pydantic import ValidationError
class Podp... | python |
from rest_framework import permissions
from API.models import *
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
... | python |
WORD_EMBEDDING_FILE = './data/GoogleNews-vectors-negative300.txt'
WORD_EMBEDDING_BIN_FILE = './bin/unigram_embedding.pkl'
LOW_FREQ_TOKEN_FILE = './bin/unigram_low_freq_voc.pkl'
EMBEDDING_SIZE = 300
if __name__ == "__main__":
from preprocess.data import GigawordRaw, ParaphraseWikiAnswer
from gensim.models impo... | python |
print('Vamos somar alguns números: ')
for c in range(1, 501):
if c % 3 == 0:
print(c)
| python |
#!/usr/bin/python
"""
Check current Husky battery status (via ROS)
usage:
./battery.py [<node IP> <master IP> | -m <metalog> [F]]
"""
import sys
import os
from huskyros import HuskyROS
# apyros should be common lib - now in katarina code
from apyros.sourcelogger import SourceLogger
from apyros.metalog import... | python |
import os
import tkinter.filedialog as tk
import natsort
pot = '/media/vid/DLS DATA/seq4Amod35/2112'
seznam = os.listdir(pot)
seznam = natsort.natsorted(seznam)
key = 'OHL'
temp = []
for i in seznam:
if key in i:
print(i)
if '.txt' in i:
continue
with open(pot ... | python |
#Will take a directory full of covariance models and feed them to Infernal's cmcalibrate one at a time.
#The resulting covariance models are put in sys.argv[3].
#This script may take several days to complete. Calibrating models of large alignments is slow.
#Necessary modules: biopython, infernal
#Usage: python Infer... | python |
outputText = """Yesterday I went to see {0}.
To be honest, I thought it was pretty good.
It's a good effort by {1}.
I hadn't seen a plot move quite as fluidly as it did in {0},
but {1} does have a good hand for it."""
print('What movie are we reviewing')
movie = input().title()
print('And who directs it?')
director ... | python |
class ControllerSettings:
def __init__(self, powerslide, air_roll, air_roll_left, air_roll_right, boost, jump, ball_cam, brake, throttle):
self.powerslide = powerslide
self.air_roll = air_roll
self.air_roll_left = air_roll_left
self.air_roll_right = air_roll_right
self.boost ... | python |
import os
import nbformat
def get_cur_dir():
return os.path.abspath(os.path.dirname(__file__))
def get_par_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
def gen_items(path):
for item in os.listdir(path):
path_item = os.path.abspath(os.path.join(path, item))... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# File name: test.py
# First Edit: 2020-03-19
# Last Change: 19-Mar-2020.
"""
This scrip is for test
"""
amount_dict = {"high": 1.2, "normal": 1.0, "low": 0.8}
def main():
factorya = AbstractPizzaFactory(PizzaFactoryA())
pizza1 = factorya.make... | python |
'''
最长公共子序列
描述
给定两个字符串,返回两个字符串的最长公共子序列(不是最长公共子字符串),可能是多个。
输入
输入为两行,一行一个字符串
输出
输出如果有多个则分为多行,先后顺序不影响判断。
输入样例
1A2BD3G4H56JK
23EFG4I5J6K7
输出样例
23G456K
23G45JK
'''
'''
d为方向矩阵
1:上
2:左上
3:左
4:左or上
'''
def LCS (a, b):
C = [[0 for i in range(len(b) + 1)] for i in range(len(a) + 1)] # 定义矩阵C保存最长公共子序列长度
d = [[0 for i in ra... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to convert YOLO keras model to an integer quantized tflite model
using latest Post-Training Integer Quantization Toolkit released in
tensorflow 2.0.0 build
"""
import os, sys, argparse
import numpy as np
import tensorflow as tf
from tensorflow.keras.mo... | python |
from taskcontrol.lib import EPubSubBase
def run(data):
print("Running Pubsub ", data)
def publisher(data):
print("Running publisher ", data)
def subscriber(data):
print("Running subscriber ", data)
config = {"name": "new", "handler": run, "queue": None, "maxsize": 10,
"queu... | python |
import numpy as np
import os
import sys
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.style.use('araa')
from matplotlib import rc
rc('text.latex', preamble=r'\usepackage{amsmath}')
rc("font", **{"family": "serif", "serif": ["Palatino"]})
rc("text", usetex = True... | python |
from collections import OrderedDict
from functools import partial
from unittest import TestCase
import os
import os.path as osp
import numpy as np
from datumaro.components.annotation import (
AnnotationType, LabelCategories, Mask, MaskCategories,
)
from datumaro.components.dataset import Dataset
from datumaro.com... | python |
"""
Django 1.10.5 doesn't support migrations/updates for fulltext fields, django-pg-fts isn't
actively maintained and current codebase is broken between various versions of Django.
Because of that I decided to implement our migrations with intent to drop it when django develops
its own solution.
"""
import copy
from ... | python |
import os
import argparse
import shutil
from datetime import datetime,timedelta
def main():
'''
the driver
'''
args = parse()
files = get_files(args)
if confirm(files):
copy_files(files,args)
def parse():
'''
sets the args needed to run and returns them
'''
#default... | python |
import yaml
from pathlib import Path
from .repo import serialize_repo, deserialize_repo
from .validation import validate_manifest
from ..exception import AppException
from ..env import MANIFEST_PATH_DEFAULT
from ..logger import get_logger
from ..utils import to_absolute_path, validate_writable_directory
def seriali... | python |
import logging
import sqlite3
from phizz.database import get_cursor
from . import GENE_DB
logger = logging.getLogger(__name__)
def query_hpo(hpo_terms, database=None, connection=None):
"""Query with hpo terms
If no databse is given use the one that follows with package
Args:
... | python |
import numpy as np
def gaussian_KL(mu0, Sig0, mu1, Sig1inv):
t1 = np.dot(Sig1inv, Sig0).trace()
t2 = np.dot((mu1-mu0),np.dot(Sig1inv, mu1-mu0))
t3 = -np.linalg.slogdet(Sig1inv)[1] - np.linalg.slogdet(Sig0)[1]
return 0.5*(t1+t2+t3-mu0.shape[0])
def weighted_post_KL(th0, Sig0inv, sigsq, X, Y, w, reverse=True):... | python |
# <editor-fold desc="Description">
x = 'foo' + 'bar'
# </editor-fold> | python |
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sb
from utils.data_handling import load_config
def get_colors():
cfg = load_config()
sb.set_style(cfg['plotting']['seaborn']['style'])
sb.set_context(cfg['plotting']['seaborn']['context']['context'],
font_scale=c... | python |
# -*- coding: utf-8 -*-
"""
Created on 2021/1/12 16:51
@author: Irvinfaith
@email: Irvinfaith@hotmail.com
""" | python |
# Generated by Django 3.1.4 on 2020-12-12 22:01
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("peeringdb", "0014_auto_20201208_1856"),
("peering", "0065_auto_20201025_2137"),
]
operations = [
mi... | python |
r"""
Hypergraphs
This module consists in a very basic implementation of :class:`Hypergraph`,
whose only current purpose is to provide method to visualize them. This is
done at the moment through `\LaTeX` and TikZ, and can be obtained from Sage
through the ``view`` command::
sage: H = Hypergraph([{1,2,3},{2,3,4},{... | python |
# coding: utf-8
# **In this simple kernel, I will attempt to predict whether customers will be "Charged Off" on a loan using Random Forests Classifier.**
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/... | python |
from rater import generate_pokemon_list_summary
from common import pokemon_base_stats
from pokedex import pokedex
excluded_pokemon_name_list = []
def find_bad_pokemons(pokemon_list):
pokemon_summary = generate_pokemon_list_summary(pokemon_list)
bad_pokemons_ids = []
for pokemon_name in sorted(pokemon_summary.k... | python |
app = """
library(dash)
app <- Dash$new()
app$layout(
html$div(
list(
dccInput(id='input-1-state', type='text', value='Montreal'),
dccInput(id='input-2-state', type='text', value='Canada'),
html$button(id='submit-button', n_clicks=0, 'Submit'),
html$div(id='output-state'),
dccGraph... | python |
class Solution:
def wordPattern(self, pattern, str):
map_letter_to_word = dict()
map_word_to_letter = dict()
words = str.split()
if len(words) != len(pattern):
return False
for letter, word in zip(pattern, words):
if l... | python |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Mostly taken from PasteDeploy and stripped down for Galaxy
import inspect
import os
import re
import sys
import pkg_resources
from six import ite... | python |
from numpy import sin, cos, pi, fabs, sign, roll, arctan2, diff, cumsum, hypot, logical_and, where, linspace
from scipy import interpolate
import matplotlib.pyplot as plt
# Cross-section class that stores x, y points for the cross-section
# and calculates various geometry data
d = 1000
class CrossSection:
"""
Cla... | python |
#! python2.7
## -*- coding: utf-8 -*-
## kun for Apk View Tracking
## ParseElement.py
from DeviceManagement.Device import Device
from TreeType import CRect
from Utility import str2int
class ParseElement():
def __init__(self, element_data):
self.class_name = ""
self.hash_code = ""
... | python |
#Crie um progama que tenha uma tupla totalmente preenchida com uma contagem por extensão de Zero até Vinte.
#Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostra-lo por extenso.
numeros = ('zero','um', 'dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quatorze',
... | python |
import sys
import logging
import logging.handlers
from command_tree import CommandTree, Config
from voidpp_tools.colors import ColoredLoggerFormatter
from .core import Evolution, Chain
from .revision import REVISION_NUMBER_LENGTH
tree = CommandTree(Config(
prepend_double_hyphen_prefix_if_arg_has_default = True,
... | python |
import os
import pandapower as pp
import pandapower.networks as pn
from pandapower.plotting.plotly import pf_res_plotly
from preparation import NetworkBuilder
import_rules = dict()
aemo_data = r"data/aemo_data_sources.json"
tnsp_buses = r"data/electranet_buses.json"
if __name__ == "__main__":
builder = NetworkBui... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.