text stringlengths 2 999k |
|---|
# Copyright 2017 The TensorFlow Authors. 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.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
#!/usr/bin/python
import sys
import glob
if sys.version_info[0] < 3:
pVer = 2
else:
pVer = 3
import requests
try:
from nested_lookup import nested_lookup
except ImportError:
print("Nested_lookup import not found.")
if pVer == 3:
print("please execute the command: pip3 install nested_looku... |
from dataclasses import dataclass
from typing import List, Optional, Set
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.foliage import Foliage, FoliageTransactionBlock, TransactionsInfo
from chia.types.blockchain_format.program import SerializedProgram
from chia.types.blockchain_f... |
"""
The functions from this file originate from https://github.com/FZJ-IEK3-VSA/glaes/blob/master/create_prior.py
"""
import geokit as gk
import numpy as np
from os.path import join, isdir
from os import mkdir
from collections import OrderedDict
from json import dumps
from typing import List
def edgesByProximity(re... |
"""
Django settings for goodchat project.
Generated by 'django-admin startproject' using Django 3.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
... |
# -*- Python -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
__version__ = '$Revision: 1.5 $'[11:-2]
from twisted.trial import unittest
from twisted.protocols import pcp
# Goal:
# Take a Protocol instance. Own all outgoing data - anything that
# would go to p.transport.write. Own all ... |
# import the necessary packages
from scipy.spatial import distance as dist
from imutils.video import FileVideoStream
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
import time
import math as ma
def ... |
# Copyright 2017 The TensorFlow Authors 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.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2019, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
import codecs
import os
import platform
import re
import sys
from setuptools import find_packages, setup
###############################################################################
NAME = "attrs"
PACKAGES = find_packages(where="src")
META_PATH = os.path.join("src", "attr", "__init__.py")
KEYWORDS = ["class", "a... |
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python Motion Writer module of the piCAMTracker package
# Copyright (c) 2017-2018 Axel Barnitzke <barney@xkontor.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# ... |
# !/usr/bin/env python
"""This module does blah blah."""
import time
from io import BytesIO
from urllib.parse import urljoin, quote
import requests
from bs4 import BeautifulSoup
from common import airtab_mdoc as airtab, dc, tw, muh_headers, wrap_from_module
wrap_it_up = wrap_from_module('mdoc_scraper/mdoc_scraper.py')... |
"""Support for Radarr."""
from datetime import datetime, timedelta
import logging
import time
from pytz import timezone
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_MONITORED_CONDITIONS,... |
"""Test Home Assistant json utility functions."""
from json import JSONEncoder
import os
import unittest
from unittest.mock import Mock
import sys
from tempfile import mkdtemp
import pytest
from homeassistant.util.json import (
SerializationError, load_json, save_json)
from homeassistant.exceptions import HomeAss... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
import functools
import itertools
from abc import ABC, abstractmethod
from dataclasses import dataclass
from traceback import FrameSummary
from typing import Callable, Any, Tuple, List
from rxbp.flowables.mapflowable import MapFlowable
from rxbp.flowables.reduceflowable import ReduceFlowable
from rxbp.flowables.refcou... |
# 自然言語処理による感情分析(BERT)
import glob
import os
import io
import string
import re
import sys
import random
import spacy
import torchtext
import mojimoji
import string
#import MeCab
from torchtext.vocab import Vectors
from utils.bert import BertTokenizer, load_vocab
# 単語分割用のTokenizerを用意
tokenizer_bert = BertTokenizer(voc... |
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is
# licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... |
#!/usr/bin/env python3
# ==============================================================================
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
import argparse
import errno
import os
from subprocess im... |
import unittest
import torch
from torch import nn
import sys
import kgbench as kg
from kgbench import tic, toc
import torch
import numpy as np
class TestUtil(unittest.TestCase):
def test_batching(self):
amplus = kg.load('amplus')
batched = kg.to_tensorbatches(amplus.get_pil_images(), use_torc... |
#!/usr/bin/python
# Copyright (c) 2019 OpenStack Foundation
# 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.org/licenses/LICENSE-... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
###########################################################################
#Filename :HD44780.py
#Description :i2c lcd library
#Author :Takao Akaki
#Website :https://raspberrypi.mongonta.com
#Update :2018/9/9
########################################... |
import json
from django.contrib.gis.geos import Point
from rest_framework import serializers
from onadata.apps.eventlog.models import FieldSightLog, CeleryTaskProgress
class LogSerializer(serializers.ModelSerializer):
source_uid = serializers.ReadOnlyField(source='source_id', read_only=True)
source_name = seri... |
import math
import ctypes
import pyglet
pyglet.options["shadow_window"] = False
pyglet.options["debug_gl"] = False
import pyglet.gl as gl
import matrix
import shader
import block_type # import block_type.py file
import texture_manager # import texture_manager.py file
class Window(pyglet.window.Window):
def __in... |
import sys
sys.path.append("..")
import database.dbConn as dbConn
import spider.rssSpider as rssSpider
import spider.rsshubServers as rsshubServers
def dict_factory(cursor, row):
d = {}
for index, col in enumerate(cursor.description):
d[col[0]] = row[index]
return d
def countOneRecords(rssName):
... |
import time
import os
import datetime
import json
import base64
import ast
import logging
import threading
from urllib import request, parse
import requests
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado.websocket import WebSocketHandler
from ast import literal_eval
... |
# gamemain/consumers.py
import json
import redis
import logging
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from gamemain.consumer import responseFormatter
from gamemain.consumer.requestPatterns import RequestPatterns
from gamemain.consumer.SinglePlayModeAssets.EnemyM... |
import os
import logging
from pathlib import Path
import numpy as np
from sklearn.model_selection import train_test_split
from finetune import Classifier
from finetune.datasets import Dataset, generic_download
logging.basicConfig(level=logging.DEBUG)
SST_FILENAME = "SST-binary.csv"
DATA_PATH = os.path.join('Data',... |
# Copyright (c) 2009-2014 Upi Tamminen <desaster@gmail.com>
# See the COPYRIGHT file for more information
from __future__ import absolute_import, division
from twisted.conch.interfaces import ISession
from twisted.conch.ssh import session
from twisted.python import log
from zope.interface import implementer
from co... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: build.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf impor... |
import json
import jsonpickle
import pytest
import rasa.utils.io
from rasa.core.conversation import Dialogue
from rasa.core.domain import Domain
from rasa.core.tracker_store import InMemoryTrackerStore
from tests.core.conftest import TEST_DIALOGUES, EXAMPLE_DOMAINS
from tests.core.utilities import tracker_from_dialog... |
"""Test BackPACK's KFLR extension."""
from test.extensions.implementation.backpack import BackpackExtensions
from test.extensions.problem import make_test_problems
from test.extensions.secondorder.hbp.kflr_settings import NOT_SUPPORTED_SETTINGS
import pytest
NOT_SUPPORTED_PROBLEMS = make_test_problems(NOT_SUPPORTED_... |
from stupidArtnet.StupidArtnet import StupidArtnet
import time
import random
# THESE ARE MOST LIKELY THE VALUES YOU WILL BE NEEDING
target_ip = '255.255.255.255' # typically in 2.x or 10.x range
universe = 0 # see docs
packet_size = 100 # it is not necessary to send whole universe
# CREATING A STUPI... |
from collections import defaultdict
posts = defaultdict(dict)
while True:
inp = input()
if inp == 'drop the media':
break
inp = inp.split(' ')
command = inp[0]
rest_input = inp[1:]
if command == 'post':
posts[rest_input[0]] = {'likes': 0, 'dislikes': 0, 'comments': []}
el... |
from __future__ import annotations
import pytest
from bqskit.ir.circuit import Circuit
from bqskit.ir.gates import CircuitGate
from bqskit.ir.gates import CNOTGate
from bqskit.ir.gates import IdentityGate
from bqskit.ir.gates import TaggedGate
from bqskit.ir.gates.constant.unitary import ConstantUnitaryGate
from bqsk... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use:
# post_build.py $(ProjectDir) $(TargetDir) $(TargetFramework) $(PlatformName) $(ConfigurationName)
import sys, os, shutil
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "script")))
import RylogicAssembly as RA
import Rylogic as... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 8
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_2_1
from i... |
"""Maps the wavelet name to the Wavelet Class object"""
from . import (db2, db3, db4, db5, db6, db7, db8, db9, db10,
db11, db12, db13, db14, db15, db16, db17, db18, db19, db20,
sym2, sym3, sym4, sym5, sym6, sym7, sym8, sym9, sym10,
sym11, sym12, sym13, sym14, sym15, sym16, ... |
from datetime import datetime
def salvar(nomeArquivoEntrada):
arquivoEntrada =open(nomeArquivoEntrada,'r')
nomeAluno =str(input('Qual é o seu nome? ')).strip()
nomeAtividade = str(input('Qual é a atividade? ')).strip()
if '.py' in nomeAtividade:
nomeAtividade = nomeAtividade.replace('.py','')
... |
import numpy as np
import math
import matplotlib.pyplot as plt
from lib.math import gershgorin_norm, ssvd_min
def main(
plot,
matrix: np.matrix,
eps: np.array,
step: float =0.5,
update = lambda: True,
progresstick =.01):
A = matrix
n, _ = A.shape
# 1 find the search... |
import numpy as np
np_2D = np.array([[1.73,1.68,1.71,1.89,1.79],[65.4,59.2,63.6,88.4,68.7]])
print(np_2D)
print(np_2D.shape)
print(np_2D[0][2])
print(np_2D[0,2])
print(np_2D[:,1:3])
print(np_2D[1,:])
|
# -*- coding: utf-8 -*-
"""
@brief: Extract judicial acts from `bsr.sudrf.ru`
@file: settings.py
@author: dmryutov (dmryutov@gmail.com)
@date: 23.04.2017 -- 29.04.2017
"""
import re
import os
ALL_ACTS = r'https://bsr.sudrf.ru/bigs/portal.html#%7B%22mode%22:%22QUERY_HISTORY%22,%22historyQueryId%22:%22B6A74295-C7E... |
import os
from pathlib import Path
from typing import Dict
from . import ModelPreprocessor
from ..schema import ModelSchema
class DefaultValuesModelPreprocessor(ModelPreprocessor):
TYPE = 'default'
def transform(self, schema: ModelSchema, settings: Dict):
self.set(settings, 'package', lambda: os.pat... |
# qubit number=4
# total number=41
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += CNOT(0,3) # number=13
... |
#!usr/bin/python
#########################################################################################################
# Author: Keagan Peet
# Purpose: To create standard alerting policies, conditions, notification channels for new deployments.
# Note: Using python 3
###############################################... |
from asciimatics.exceptions import ResizeScreenError
from asciimatics.screen import Screen
from th.state import GameState
from th.screens import stage
if __name__ == "__main__":
game_state = GameState()
while True:
try:
Screen.wrapper(stage, catch_interrupt=False, arguments=[game_state])
... |
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def email_user(subject, context, text_template_path, html_template_path, attachments=[]):
"""
Dispatch a notification email to a user.
Args:
subject (str): Email su... |
# coding: utf-8
from __future__ import unicode_literals
import itertools
import json
import os.path
import random
import re
import traceback
from .common import InfoExtractor, SearchInfoExtractor
from ..compat import (
compat_chr,
compat_HTTPError,
compat_parse_qs,
compat_str,
compat_urllib_parse... |
#!/usr/bin/env python
from __future__ import print_function
import sys, os, subprocess
srcdir = os.environ.get ("srcdir", ".")
EXEEXT = os.environ.get ("EXEEXT", "")
top_builddir = os.environ.get ("top_builddir", ".")
hb_fuzzer = os.path.join (top_builddir, "hb-fuzzer" + EXEEXT)
if not os.path.exists (hb_fuzzer):
i... |
from .polar import Polar
from .query import Query, QueryResult
from .variable import Variable
from .predicate import Predicate
from .expression import Expression, Pattern
from .data_filtering import Relation
from .data import DataFilter, Condition, Projection
|
"""locallibrary URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
'''
Quick Knight
Have the function QuickKnight(str) read str which will be a string consisting of the
location of a knight on a standard 8x8 chess board with no other pieces on the board
and another space on the chess board. The structure of str will be the following: "(x y)(a b)"
where (x y) represents the position... |
class PDL1Net:
"""
class represents a PDL1 net architecture
"""
pass
|
import unittest
import memoization.func_analyzer as func_analyzer
g1 = 1
g2 = 2
g3 = 3
abs = lambda i: i if i >= 0 else -i # hide builtin function
class TestFuncAnalyzer(unittest.TestCase):
a1 = 1
a2 = 2
def test_load_globals(self):
global g1, g2, g3
l1 = 1
def get():
... |
#! /bin/python
import os
import argparse
print(os.path.getcwd)
|
from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
from librespot.audio import AbsChunkedInputStream
from librespot.audio.format import SuperAudioFormat
class GeneralAudioStream:
def stream(self) -> AbsChunkedInputStream:
pass
def codec(self) -> SuperAudioFormat:
... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
# -*- coding: utf-8 -*-
import xlwt as xw
import matplotlib.pyplot as plt
# Excel New Bookを作成
wb = xw.Workbook()
# セルに値をセットする
xw.Range('A1').value = 'Foo 1'
# 値を取得する
str = xw.Range('A1').value
print(str)
# 指定したセルを基準に表データをセットする
xw.Range('A1').value = [['Foo1','Foo2', 'Foo3'], [10, 20, 30]]
# 指定したセルを基準に表データを取得する
tab... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import time,os
def p(n,k,p0,d):
return (p0+(d*k*(n-k)/n**2))
def Psum(W,n,k,m):
result=0
for i in xrange(n+1,m.N+1):
for j in xrange(max(k,i-m.N2),min(k+i-n,m.N1)+1):
result = result + (2*p(i,j,m.P0,m.d)*W[i][j])/((j+1)*(i-j+1)-2)
retur... |
# downscale cru data in a CLI way
if __name__ == '__main__':
import glob, os, itertools, rasterio
from downscale import DeltaDownscale, Baseline, Dataset, utils, Mask
from functools import partial
import numpy as np
import argparse
# parse the commandline arguments
parser = argparse.ArgumentParser( description... |
# coding: utf-8
"""
Argo
Python client for Argo Workflows # noqa: E501
OpenAPI spec version: master
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class V1alpha1WorkflowSuspendRequest(object):
"""NOTE: This class is... |
from collections import deque
graph = dict() # 定义字典
graph['your'] = ['alice', 'boob', 'claire']
graph['boob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph['thom'] = []
graph['jonny'] = []
def person_is_seller(name)... |
# This file is part of the History Store (histore).
#
# Copyright (C) 2018-2021 New York University.
#
# The History Store (histore) is released under the Revised BSD License. See
# file LICENSE for full license details.
"""Unit tests for the command-line archive commands."""
import os
import pytest
from click.testi... |
# -*- coding: utf-8 -*-
# This file was generated
import sys # noqa: F401 - Not all mock_helpers will need this
class MockFunctionCallError(Exception):
def __init__(self, function, param=None):
self.function = function
self.param = param
msg = "{0} called without setting side_effect".fo... |
"""
内存图
列表嵌套
浅拷贝
深拷贝
拷贝:将数据由一份复制为多份,数据改变互不影响.
浅拷贝:
优点:占用内存较少
缺点:修改深层数据,互相影响
适用性:优先,没有深层数据或者深层数据不会被修改
深拷贝:
优点:一份数据发生变化,另外一份数据绝对不受影响
缺点:占用内存过多
适用性:深层数据会被修改
"""
list01 = [10, [20, 30]]
list02 = list01[:] # 浅拷贝
list02[0] = 100
list02[1... |
#!/usr/bin/env python
#
# GAMBIT: Global and Modular BSM Inference Tool
#*********************************************
# \file
#
# Script to find scanner (and test function)
# libraries and write various ScannerBit-
# related config and compilation files.
#
#*********************************************
#
# Authors... |
from __future__ import absolute_import, print_function, unicode_literals
import json
import logging
import os
import shutil
import sys
from abc import ABCMeta, abstractmethod
from argparse import ArgumentTypeError
from ast import literal_eval
from collections import OrderedDict
from stat import S_IWUSR
from six impor... |
from unittest import TestCase
import jsons
from jsons import UnfulfilledArgumentError, DecodeError, DeserializationError
class TestException(TestCase):
def test_exception_unfulfilled_arg(self):
class C:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get('MAIL_USE... |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
from mock import patch, call
from testtools import TestCase
from tests.helpers import patch_open, FakeRelation
import charmhelpers.contrib.hahelpers.apache as apache_utils
cert = '''
-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAMO1fWOu8ntUMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0Y... |
#!/usr/bin/python2.4
#
# Copyright 2007-2013 The Python-Twitter Developers
#
# 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 requir... |
import base64
from ocs_ci.framework import config
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs import constants
from ocs_ci.helpers.helpers import storagecluster_independent_check
class RGW(object):
"""
Wrapper class for interaction with a cluster's RGW service
"""
def __init__(self, namespace=Non... |
import builtins
import typing as ty
import strax
export, __all__ = strax.exporter()
# Placeholder value for omitted values.
# Use instead of None since None might be a proper value/default
OMITTED = '<OMITTED>'
__all__.append('OMITTED')
@export
class InvalidConfiguration(Exception):
pass
@export
def takes_con... |
from cs.algorithms.string.sais import (
build_suffix_array,
build_suffix_array_naive,
get_suffix_annotations,
induced_sort,
to_rank_array,
)
from cs.structures import SuffixArray
def test_build_suffix_array() -> None:
text = "AAAAACACAG"
s = SuffixArray(text)
assert str(s) == str(sorte... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 18:09:18 2019
@author: hindesa
"""
from numpy import random
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# X = prey, Y = predators
n = 100000 # samples
# Timescales
alphax = random.uniform(1, 2, size=n)
alphay = random.uniform(0, 1, siz... |
"""
Link Scraper Facade Class
"""
from typing import Set, Iterator
from dataclasses import dataclass, field
from .constants import Types
from .request_manager import RequestManager
from .results_cleaner import ResultsCleaner
from .link_extractor import extract_links_with_beautiful_soup
from .cleaner import left_only_... |
import sys
import ip6w.src.ip6words
def main(args=None):
if args is None:
args = sys.argv
ip6w.src.ip6words.main(args)
sys.exit()
if __name__ == "__main__":
main() |
import json
import uuid
from datetime import date, datetime, timedelta
from typing import Tuple, Union
from flask import current_app
from notifications_utils.clients.redis import service_cache_key
from notifications_utils.statsd_decorators import statsd
from notifications_utils.timezones import convert_utc_to_local_ti... |
import rosbag
import numpy as np
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("bag",help = "ROS bag file to extract")
parser.add_argument("--time_output_file",default="time_extracted_data",help="binary file to extract the time data")
pa... |
# Copyright 2015, Gustavo Narea.
#
# 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 writi... |
import tornado.escape
import tornado.web
from astropy import units as u
from panoptes.utils import current_time
class BaseHandler(tornado.web.RequestHandler):
"""
BaseHandler is inherited by all Handlers and is responsible for any
global operations. Provides the `db` property and the `get_current_user`... |
def multiclass_accuracy(prediction, ground_truth):
"""
Computes metrics for multiclass classification
Arguments:
prediction, np array of int (num_samples) - model predictions
ground_truth, np array of int (num_samples) - true labels
Returns:
accuracy - ratio of accurate predictions to tota... |
# Copyright 2017 The TensorFlow Authors. 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.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# Plotting utils
import glob
import math
import os
from copy import copy
from pathlib import Path
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sn
import torch
import yaml
from PIL import Image, ImageDraw, ImageFont
from yolov5.utils.general imp... |
import numpy as np
from astropy.coordinates import SkyCoord, FK5, Latitude, Angle
from astropy import units as u
def time_latitude():
Latitude(3.2, u.degree)
ANGLES = Angle(np.ones(10000), u.deg)
def time_angle_array_repr():
# Prior to Astropy 3.0, this was very inefficient
repr(ANGLES)
def time_ang... |
import torch.nn as nn
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-22 09:12
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
import tensorflow as tf
from adain.layer import upsample_nearest, vgg_preprocess
_VGG19 = [
('prep', 'prep', {}),
('conv', 'conv1_1', {'filters': 64}),
('conv', 'conv1_2', {'filters': 64}),
('pool', 'pool1', {}),
('conv', 'conv2_1', {'filters': 128}),
('conv', 'conv2_2', {'filters': 128}... |
#!/usr/bin/env python
import logging
import sys
import pyBigWig
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
if __name__ == "__main__":
files = sys.argv[1:]
bws = [pyBigWig.open(x) for x in files]
# obtain some chroms. Hope all sets are identical!
k = bws[0].chroms().keys()
... |
import PySimpleGUI as sg
# Add a touch of color
sg.theme('DarkAmber')
# All the stuff inside your window.
layout = [ [sg.Text('Hello world!!!!')],
[sg.Text('Insert your name:'), sg.InputText()],
[sg.Button('Ok'), sg.Button('Cancel')] ]
# Create the Window
window = sg.Window('Window Title',... |
from graphene_django import DjangoObjectType
from .models import BlogPost as BlogPostModel, Blog as BlogModel
class BlogType(DjangoObjectType):
class Meta:
model = BlogModel
fields = [
"id",
"description",
"organization",
"name",
"blog_p... |
import os
import pytest
from hydra.experimental import compose, initialize_config_dir
from hypothesis import given, settings
from hypothesis.strategies import booleans
from scripts.efficientnets.run import main as efficientnets_main
@pytest.mark.parametrize(
["name", "dm", "num_classes"],
[
pytest.p... |
import unittest
import os
import io
import tempfile
from d20.Manual.Temporary import (TemporaryHandler,
TemporaryObjectStream,
TemporaryObjectOnDisk,
PlayerDirectoryHandler)
from d20.Manual.Exceptions import Temporary... |
# -*- coding: utf-8 -*-
"""App configuration for trivia app."""
# Part of Trebek (https://github.com/whutch/trebek)
# :copyright: (c) 2018 Will Hutcheson
# :license: MIT (https://github.com/whutch/trebek/blob/master/LICENSE.txt)
from django.apps import AppConfig
class TriviaConfig(AppConfig):
default_auto_field ... |
#!/usr/bin/python2.7
# -*- coding=utf-8 -*-
# # Describe hypercubes (in high dimensional) with DTM Gaussian distribution
# DTM Gaussian: Discrete Truncate Multivariate Normal Gaussian.
# Author: wenchieh
#
# Project: eaglemine
# dtmnorm.py
# Version: 1.0
# Date: December 1 2017
# Main Cont... |
__author__ = "Maxim Ziatdinov"
__copyright__ = "Copyright Maxim Ziatdinov (2020)"
__maintainer__ = "Maxim Ziatdinov"
__email__ = "maxim.ziatdinov@ai4microcopy.com"
from setuptools import setup, find_packages
import os
module_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(module_dir, 'atomai/... |
password="pbkdf2(1000,20,sha512)$8b71e6e9f7011c55$c689bbf4a78dba8abb5e4e2e95d9baa5cc7820da"
|
from stringstring.ascii_letters import ascii_letters
def stringstring(string):
base = ''
for i in range(6):
for j in string:
base += ascii_letters[i][j]
base += '\n'
string = string.replace(' ', '')
result = ''
counter = 0
for i in base:
if i == '~':
... |
class Solution:
def XXX(self, nums: List[int]) -> int:
res = 0
ans = nums[0]
for n in nums:
if res < 0:
res = 0
res += n
ans = max(ans, res)
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.