text stringlengths 3.07k 12.6k |
|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
from copy import deepcopy
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Memory:
def __init__(self):
self.actions = []
self.states = []
self.logprobs... |
"""PBX path objects"""
import os
from typing import cast, List, Optional
import deserialize
from .pbxobject import PBXObject
# pylint: disable=no-member
@deserialize.key("source_tree", "sourceTree")
@deserialize.ignore("_parent_group_reference")
@deserialize.downcast_identifier(PBXObject, "PBXPathObject")
class P... |
__version__ = "$Revision: 1.1 $"
import sys,os
import sys
try:
import xml.etree.cElementTree as ET
except ImportError:
import cElementTree as ET
import shutil
import subprocess
import tempfile
import codecs
import tarfile
from GeniaSentenceSplitter import moveElements
sys.path.append(os.path.dirname(os.path... |
from typing import Union, Tuple
import torch
from torch import Tensor, device as Device
from torch.utils.data import DataLoader
from numpy import array as NDArray
from semi_orthogonal.utils import embeddings_concat
from semi_orthogonal.utils.distance import mahalanobis_sq
from semi_orthogonal.backbones import ResNet1... |
#!/usr/bin/python3
VIRTUAL_PI = False
try:
import RPi.GPIO as GPIO
except ImportError:
print("WARNING - Enabling virtual pi mode", flush=True)
VIRTUAL_PI = True
import time
import requests
import signal
import sys
# How often to poll the server.
POLL_SLEEP = 1000 # ms.
# How long to sleep on connecti... |
import numpy as np
import pandas as pd
import pickle
# from sklearn.cross_validation import train_test_split, cross_val_score
from sklearn.model_selection import cross_validate, train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accu... |
from multiprocessing import Process, Pool
import time
import uiautomator2 as u2
import random
import subprocess
#由于进程启动的开销比较大,使用多进程的时候会导致大量内存空间被消耗。为了防止这种情况发生可以使用进程池,(由于启动线程的开销比较小,所以不需要线程池这种概念,多线程只会频繁得切换cpu导致系统变慢,并不会占用过多的内存空间)
#进程池中常用方法:
#apply()
#同步执行(串行)
#apply_async()
#异步执行(并行)
#terminate()
#立刻关闭进程池
#join()
#主进程等待所... |
import subprocess, urllib.parse, collections, re, os, time
from weakref import proxy
from config import config
_brace_re = re.compile(r'(?<=[^\\])[\{\}]')
def validate_bibtex_value(txt):
'''
we only perform rudimentary validation - just check whether braces are
balanced. Otherwise, we assume the user know... |
import torch
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
def _flatten_helper(T, N, _tensor):
return _tensor.view(T * N, *_tensor.size()[2:])
class RolloutStorage(object):
def __init__(self, num_steps, mini_batch_num, obs_dim, action_dim, env_key, use_gae, gamma, gae_param, num_pro... |
# -*- coding: utf-8 -*-
import re
from collections import defaultdict
from twisted.internet import reactor, defer
from tipsip import aggregate_status
from ua import SIPUA, SIPError
from header import Header
s2p = {
'online': 'open',
'offline': 'closed',
}
def status2pidf(resource, statu... |
import math
import re
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
from torch.autograd import Variable
from .modules import initialize_filterbank
class Conv_2d(nn.Module):
def __init__(self, input_channels, output_channels, shape=3, stride=1, ... |
import numpy as np
def getOptimalMinimumSpacing(minVal, maxVal, scale=1):
dif = abs(maxVal - minVal)
if dif == 0:
return 0
size = dif * scale
# decide optimal minor tick spacing in pixels (this is just aesthetics)
pixelSpacing = np.log(size+10) * 5
#pixelSpacing = np.log(size+10) * 2
... |
import os
import shutil
from zipfile import ZipFile
import requests
from lxml import etree as et
from PIL import Image
import logging
from eurlex2lexparency.celex_manager import country_mapping
from eurlex2lexparency.extraction.generic import Retriever, FormatNotAvailable, img_2_base64
from eurlex2lexparency.utils imp... |
# Copyright 2013 Google 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from pathlib import Path, PurePath
import pandas as pd
import requests
from requests.exceptions import HTTPError, ConnectionError
from rank_bm25 import BM25Okapi
import nltk
from nltk.corpus import stopwords
nltk.... |
# -*- coding: utf-8 -*-
from itertools import chain
from django import forms
from django.template.loader import render_to_string
from django.urls import NoReverseMatch, reverse
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.contrib.admin.widgets import AdminFi... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
import math
from functools import partial
import numpy as np
import tensorflow as tf
def is_constant(*args):
return all(isinstance(a, (bool, int, float)) for a in args)
def is_numpy(*args):
if is_constant(*args):
return False
return all(isinstance(
a, (bool, int, float, np.ndarray, np.f... |
from pyg_timeseries._rolling import _rolling_window
from pyg_base import pd2np, loop_all
from pyg_timeseries._decorators import first_, compiled, _data_state
import numpy as np
__all__ = ['rolling_max', 'rolling_max_', 'expanding_max', 'expanding_max_']
def rolling_max(a, n, axis = 0, data = None, state = None):
... |
import pwn
registered = {}
# For the benefit of the shellcodes
from pwn import *
from socket import htons
class AssemblerBlock:
def __add__(self, other):
return AssemblerContainer(self, other)
def __radd__(self, other):
return AssemblerContainer(other, self)
def __eq__(self, other):
... |
from datetime import datetime, timezone
from pathlib import Path
from os import path
from enum import Enum
class FileInfo:
@staticmethod
def epoch_to_datetimeutc(epoch):
return datetime.fromtimestamp(epoch, tz=timezone.utc)
file_name: str
full_path: str
dir_name: str
dir_path: str
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import collections
import os
import random
import re
import time
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
# In[2]:
def clearstring(string):
string = re.sub("[^'\"A-Za-z0-9 ]+", "", string)
string = string.spli... |
import datetime
import numpy as np
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import user_passes_test
from django.db import ProgrammingError
from django.http import HttpResponseNotFound
from django.shortcuts import render, HttpResponse
from django.template import loade... |
import datetime
import inspect
import logging
import os
import six
import sys
import pkg_resources
# are we running python 3.x ?
PY3 = sys.version_info[0] >= 3
log = logging.getLogger(__name__)
def asbool(obj):
if isinstance(obj, six.string_types):
obj = obj.strip().lower()
if obj in ['true', 'y... |
import numpy as np
from ...constants import log
from ...constants import tol_path as tol
from ..entities import Line, Arc, BSpline
from ..util import angles_to_threepoint, is_ccw
from ...util import is_binary_file, multi_dict
from collections import deque
# unit codes
_DXF_UNITS = {1 : 'inches',
... |
# Copyright 2012 Nebula, Inc.
#
# 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 agree... |
from datetime import timedelta
import pytest
import random
from haydi.base.runtime.distributedcontext import DistributedContext
import haydi as hd
class DCluster(object):
def __init__(self, port):
self.port = port
self.cluster = None
self.ctx = None
def start(self, n_workers):
... |
# *****************************************************************************$
# Copyright 2021 Arm Limited and affiliates.
# SPDX-License-Identifier: Apache-2.0
#
# 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 co... |
import re, csv, json, os
from pprint import pprint
from dateutil import parser
from rdflib import URIRef, Literal, Namespace, Graph
from rdflib.namespace import RDF, OWL, SKOS, DCTERMS, XSD, RDFS, FOAF
ELI = Namespace("http://data.europa.eu/eli/ontology#")
OIR = Namespace("http://oireachtas.ie/ontology#")
CEN = Namesp... |
import importlib.util
import os
from typing import Type, Dict, Tuple
from .appconfig import Config
from .exceptions import AppMakerException
if False: # pragma: nocover
from .appmaker import AppMaker
class AppTemplate:
"""Represents an application template."""
config_filename = 'makeappconf.py'
co... |
__package__ = "blackhat.bin"
from ..helpers import Result, ResultMessages
from ..lib.input import ArgParser
from ..lib.output import output
from ..lib.sys.stat import chmod, stat
__COMMAND__ = "chmod"
__DESCRIPTION__ = ""
__DESCRIPTION_LONG__ = ""
__VERSION__ = "1.1"
def parse_characters(chars, current_perms):
... |
# Game of Life on the Novation Launchpad
import launchpad_py as launchpad
from pygame import time
L_SIZE = 8
color = (0, 64, 64)
def display_grid(grid, lp):
"""
display the grid on the launchpad
:param grid: the grid to display
:param lp: the launchpad object
:return: void
"""
for y in... |
# vectors2 and mapping functions
# possible todo: Add a menu system
#to create vectors and present
# possible todo: add numbering to graph line
import turtle as t
import math as m
import random
# this is to show the cursor
t.st()
# this is to stop the speed of the turtles movement from being
#painfully slow
t.spee... |
#!/usr/bin/env python3
"""
Advent of Code 2021 - Day 02
"Dive!"
"""
from os.path import join, dirname, realpath
from argparse import ArgumentParser
from functools import reduce
from sys import stderr
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
CHALLENGE = """
Now, you need to figure out how to p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) <NAME>.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from argparse import ArgumentParser, REMAINDER
import os
from copy import copy
from distutils.dir_util import copy_tree
f... |
try:
from .MonatsException import *
from .AnzahlTageImMonat import *
from .Monatscode import *
from .Monatsposition import *
from .Monatsname import *
from Kronos_heureka_code.__VergleichsStamm import *
except ImportError:
from Kronos_heureka_code.__VergleichsStamm import VergleichsStammZahl... |
import os
import time
import random
import shutil
import numpy as np
import pandas as pd
from pymatgen import MPRester
from pymatgen.core.structure import Structure
from pymatgen.core.periodic_table import Element
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
import diffraction_simulator.XRD_simulator as X... |
import numpy as np
Nt = 21
def dist(_t1, _t2):
_d = _t2 - _t1
if _d < 0:
_d += Nt - 1
return _d
def half_of(_d):
if _d in [1, 2]:
_h = 1
if _d in [3, 4]:
_h = 2
if _d in [5, 6]:
_h = 3
return _h
class Luvly:
def __init__(self, rudder, adv_rudder=0, ... |
# Copyright 2009, UCAR/Unidata and OPeNDAP, Inc.
# See the COPYRIGHT file for more information.
import saxeventtype
from xml.sax import SAXException
from saxeventhandler import SaxEventHandler
from lexeme import Lexeme
from Dap4Parser import *
def static () :
global elementmap, attributemap
elementmap = {}
att... |
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class BasicConv(nn.Module): # 把卷积,bn,relu结合到一个函数
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True,
bn=True, bias=False):
super(BasicConv, sel... |
import glob
import os
import re
import audioread as audioread
from nltk.metrics.distance import edit_distance, jaccard_distance
import pandas as pd
import hashlib
from nltk.tokenize import word_tokenize
paraphrasings = []
new = []
def get_file_duration(filename):
with audioread.audio_open("saved_audio/" + file... |
# Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, LLC
#
# 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 applicabl... |
"""Test priors."""
import math
import numpy as np
import pytest
import pypesto
import pypesto.optimize
from pypesto.C import MODE_FUN, MODE_RES
from pypesto.objective import NegLogParameterPriors
from pypesto.objective.priors import get_parameter_prior_dict
scales = ['lin', 'log', 'log10']
@pytest.fixture(params=... |
"""
Usage:
python wrangle_imdb.py tsv_to_json ../../data/imdb/name.basics.mini.tsv
python wrangle_imdb.py tsv_to_mongoexport ../../data/imdb/name.basics.mini.tsv
python wrangle_imdb.py tsv_to_mongoexport ../../data/imdb/name.basics.tsv
python wrangle_imdb.py transform_mongoexport_file ../../data/imdb/na... |
"""Interface to ADB server."""
from typing import List, Union
import logging
import os
from pathlib import Path
import subprocess
from enum import Enum, unique
from mass_apk import pkg_root, runtime_platform
from mass_apk.exceptions import MassApkError
from mass_apk.helpers import Platform
log = logging.getLogger(... |
import os
import pandas as pd
from os import listdir
from ast import literal_eval
import numpy as np
def find_csv_filenames(path_to_dir, result, suffix=".csv"):
filenames = listdir(path_to_dir)
for filename in filenames:
if os.path.isdir('{}/{}'.format(path_to_dir, filename)):
find_csv_filenames('{}/{}'.... |
"""
Scrapper implementation
"""
import datetime
import json
from pathlib import Path
import re
import shutil
from bs4 import BeautifulSoup
import requests
from constants import CRAWLER_CONFIG_PATH, ASSETS_PATH, ROOT_URL, HEADERS
from core_utils.article import Article
from core_utils.pdf_utils import PDFRawFile
clas... |
import random
import time
import datetime
import torch.nn as nn
from torch.autograd import Variable
import torch
import torchvision.transforms as transforms
import numpy as np
from skimage.filters import threshold_otsu
from skimage import io, color
to_pil = transforms.ToPILImage()
# 三通道彩色图像转单通道灰度图像
to_gra... |
from typing import List, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from mmderain.models.common import make_layer
from mmderain.models.registry import BACKBONES
def init_rain_kernel(size, norm, inner, std):
ax = np.arange(size, dtype=np.float32)
ax = ax - np.m... |
import unittest as ut
from ...functional import CompositionOf
from ...exceptions import CallableError
class TestCompositionOfInstantiation(ut.TestCase):
def setUp(self):
self.f = lambda x, name=None: x**2
self.g = lambda y, name=None: y - 3
def test_works_with_sane_callables(self):
_... |
"""
Conway's Game of Life
"""
import copy
import curses
import enum
import random
import time
from typing import List, Tuple
DISPLAY_DELAY = 0.1
DEAD_PROBABILITY = 0.92
class CellStatus(enum.Enum):
"""
Enum for a cell's status (alive or dead).
"""
dead = 0
alive = 1
class Cell:
"""
The... |
import tensorflow as tf
from tensorflow.contrib import slim
import sonnet as snt
import collections
__all__ = ['LayerSetup', 'LayerFunc', 'LayerCollection', 'SimpleStem', 'example_setups']
LayerSetup = collections.namedtuple('LayerSetup',
('layer_func', 'layer_kwargs'))
class Lay... |
"""
Monkey patching of distutils.
"""
import sys
import distutils.filelist
import platform
import types
import functools
from importlib import import_module
import inspect
from setuptools.extern import six
import setuptools
__all__ = []
"""
Everything is private. Contact the project team
if you think you need this ... |
# Import tasks from json, csv, zip, txt and more
import os
import csv
import hashlib
import shutil
import zipfile
import rarfile
import logging
import tempfile
import pandas as pd
try:
import ujson as json
except:
import json
from os.path import join
from urllib.request import urlopen
from .exceptions import... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 18-5-23 上午11:33
# @Author : MaybeShewill-CV
# @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection
# @File : test_lanenet.py
# @IDE: PyCharm Community Edition
"""
test LaneNet model on single image
"""
import argparse
import os.path as ops
... |
import copy
import sys
import math
from random import randint
import Reversi
class TreeNode(object):
"""A node in the MCTS tree"""
def __init__(self, parent, board):
self.parent = parent
self.children = [] # a map from action to TreeNode
self.N = 0
self.Q = 0
self.boa... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
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/L... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 _utilities, _tables
__a... |
"""Utilities for selecting and enumerating the Type Libraries installed on the system
"""
import win32api, win32con, pythoncom
class TypelibSpec:
def __init__(self, clsid, lcid, major, minor, flags=0):
self.clsid = str(clsid)
self.lcid = int(lcid)
# We avoid assuming 'major' or 'minor' are integers - ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# Copyright (C) 2006 <NAME>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/Licens... |
#!/usr/bin/env python
"""
Predict the number of halos that would be realised on a lightcone of given
area/depth, down to a given mass threshold.
"""
import numpy as np
import scipy.integrate as integrate
import pylab as plt
import pyccl as ccl
C_kms = 3e5 # km/s
fsky = 1.
MH_MIN, MH_MAX, MH_BINS = 1e12, 1e16, 200
de... |
#
# Copyright 2012 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import skimage
import ski... |
#!/usr/bin/env python3
"""
Scrapes the PG docs along with each specified vendor doc and creates
CSV mappings between our emulations and the functions.
"""
import os
import requests
from bs4 import BeautifulSoup
class PGScraper:
subindex_urls = [
'https://www.postgresql.org/docs/12/functions-string.htm... |
import pytest
import testit
from os.path import join, dirname
def setup_module():
with testit.step('Unittest test_case_1 setup module step 1'):
assert True
def teardown_module():
with testit.step('Unittest test_case_1 teardown module step 1'):
assert True
class Test1:
def setup_class(self):
with testit.s... |
"""
coding=utf-8
"""
import warnings, time
from . import NoDevice, postRequest, todayStamps, _BASE_URL
_GETMEASURE_REQ = _BASE_URL + "api/getmeasure"
_GETSTATIONDATA_REQ = _BASE_URL + "api/getstationsdata"
class WeatherStationData:
"""
List the Weather Station devices (stations and modules)
Args:
... |
import torch
import torch.nn as nn
from torch.distributions import MultivariateNormal
import numpy as np
from torch.distributions import Categorical
import sys
import os
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ActorCritic(nn.Module):
def __init__(self, state_dim, action_dim... |
"""Reusable utilities for the Bond component."""
from __future__ import annotations
import logging
from typing import Any, cast
from aiohttp import ClientResponseError
from bond_api import Action, Bond
from homeassistant.util.async_ import gather_with_concurrency
from .const import BRIDGE_MAKE
MAX_REQUESTS = 6
_L... |
# transformer_chatbot
# Copyright (C) 2018 Golovanov, Tselousov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... |
import numpy as np
from jesse.config import config, reset_config
from jesse.factories import fake_candle, range_candles
from jesse.services.candle import generate_candle_from_one_minutes
from jesse.store import store
def set_up():
reset_config()
from jesse.routes import router
router.set_routes([
... |
import numpy as np
import torch
from torch.utils.data import Dataset
from math import ceil
def conv_out_dim(dim, k, s):
return ceil((dim-k+1) / s)
def safe_update_dict(old_dict, new_dict):
"""Update dict only with keys it already has"""
for k in new_dict:
if k in old_dict:
old_dict[k... |
# encoding: utf-8
"""
Gherkin step implementations for presentation-level features.
"""
from __future__ import absolute_import
import os
from behave import given, when, then
from pptx import Presentation
from pptx.compat import BytesIO
from pptx.opc.constants import RELATIONSHIP_TYPE as RT
from pptx.parts.presenta... |
"""
Serializers for Galaxy config file data: ConfigSerializer for all users
and a more expanded set of data for admin in AdminConfigSerializer.
Used by both the API and bootstrapped data.
"""
# TODO: this is a bit of an odd duck. It uses the serializer structure from managers
# but doesn't have a model like them. It... |
import asyncio
import json
import logging
import logging.config
import re
from collections import Counter
from typing import Dict, List, Set
from aiohttp import ClientSession
from aiohttp.client_exceptions import (
ClientConnectorError,
ClientOSError,
ClientPayloadError,
ServerDisconnectedError,
)
from... |
# dir_editor.py
# code in shift-jis
import os, sys, platform
from tkinter import filedialog
# IMPORT module FROM LandmasterLibrary
import input_controller
def decide_save_file_name(dirname : str, list_of_ext : list) -> str:
'''
list_of_ext : List String extension
dirname : String abso... |
import numpy as np
import os
import sys
sys.path.append('../')
import tensorflow as tf
from utils import util
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
import matplotlib.pyplot as plt
import argparse
# MODEL_NAME='/home/jiachang/ssd_resnet50_v1... |
"""
setor:
Info from .../detalhes.php?setor=
"""
import requests
import requests_cache
import pandas as pd
import time, logging
from tabulate import tabulate
def list_papel_setor(setor=None):
"""
Setor: ...
Output:
List
"""
## GET: setor
url = 'http://www.fundamentus.com.br/... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
import ... |
#!/usr/bin/env python
#encoding: utf8
import rospy
import math
import RPi.GPIO as GPIO
from std_msgs.msg import Float32
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from adxl345 import ADXL345
from average_filter import AverageFilter
class AccelConverter():
def __init__(... |
# Copyright 2017 Google 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
""" Userbot module containing userid, chatid and log commands"""
from asyncio import sleep
from userbot import CMD_HELP,... |
"""Copyright (c) 2022 VIKTOR B.V.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute,... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LanguageInvariance:
"""Object to represent a language invariance
Args:
invariant_set (list): List of strings representing... |
import os
import random
import torch.utils.data as data
from torch import distributed
import torchvision as tv
import numpy as np
from .utils import Subset, filter_images, group_images
from PIL import Image
classes = {
0: 'background',
1: 'aeroplane',
2: 'bicycle',
3: 'bird',
4: 'boat',
5: 'bo... |
# -*- coding: utf-8 -*-
"""
filometro.enums
---------------
Fornece todas as enumerações constantes para facilitar a buscas dos dados.
"""
__all__ = [
'Zone',
'Modality',
'Situation',
'Immunizing',
'District'
]
from filometro import __version__
from filometro import __author__
from enum import E... |
import re
import string
from django.contrib.gis.db import models
from django.db.models import Func, Case, When, Q, Min, Max, Avg
from django.db.models.expressions import RawSQL
from django.db.models import Aggregate
from django.db.models import FloatField
from django.contrib.gis.db.models.query import GeoQuerySet
cla... |
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import seaborn as sns
def plot_length_distribution(filename, savename = None):
'''Plots the time averaged length distribution of molecules in the entire system. Shows plot unless a savename is specified '''
ts_df = pd.read_csv(filename)
static_d... |
def get_pixel_value(img, x, y):
"""
Utility function to get pixel value for coordinate
vectors x and y from a 4D tensor image.
Input
-----
- img: tensor of shape (B, H, W, C)
- x: flattened tensor of shape (B*H*W,)
- y: flattened tensor of shape (B*H*W,)
Returns
-------
- ... |
"""Enhanced python shell.
Includes all features from django-extension's shell_plus command plus OSF-specific
niceties.
By default, sessions run in a transaction, so changes won't be commited until
you execute `commit()`.
All models are imported by default, as well as common OSF and Django objects.
To add more object... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
from __future__ import absolute_import
import json
import os.path
from ocr4all.colors import ColorMap
from pkg_resources import resource_string
import numpy as np
from ocr4all_pixel_classifier.lib.pc_segmentation import RectSegment
from ocrd import Processor
from ocrd_modelfactory import page_from_file
from ocrd_mod... |
from typing import List
import re
from datetime import date, datetime, timedelta
from icalendar import Calendar, vText
import requests
from pytz import timezone, utc
from uqcsbot import bot, Command
from uqcsbot.utils.command_utils import UsageSyntaxException
CALENDAR_URL = "https://calendar.google.com/calendar/ical/q... |
"""The local runner for TensorFlow algorithms.
A runner setup context for algorithms during initialization and
pipelines data between sampler and algorithm during training.
"""
from dowel import logger
import psutil
from metarl.experiment import LocalRunner
from metarl.sampler import DefaultWorker
tf = False
TFWorke... |
# coding: utf-8
# In[1]:
import librosa
import os
import tensorflow as tf
import numpy as np
from tqdm import tqdm
# In[2]:
wav_files = [f for f in os.listdir('./data') if f.endswith('.wav')]
text_files = [f for f in os.listdir('./data') if f.endswith('.txt')]
# In[3]:
inputs, targets = [], []
for (wav_file,... |
# Copyright 2013 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-2.0
#
# Unless requ... |
"""
This code is copied from the original code of Werkzeug.
link : https://github.com/pallets/werkzeug/blob/main/src/werkzeug/_reloader.py
"""
import os
import sys
import time
import threading
import subprocess
import typing as t
from itertools import chain
from nc_console import Console
from werkzeug._reloader impor... |
import collections
from typing import Dict, Iterator, List, Union, Any, TypeVar, TYPE_CHECKING
import numpy as np
from ray.data.block import Block, BlockAccessor
from ray.data.row import TableRow
from ray.data._internal.block_builder import BlockBuilder
from ray.data._internal.size_estimator import SizeEstimator
if ... |
import functools
import json
import threading
import time
import logging
import urllib
from requests import Timeout
from ksql.builder import SQLBuilder
from ksql.errors import CreateError, KSQLError, InvalidQueryError
class BaseAPI(object):
def __init__(self, url, **kwargs):
self.url = url
self.m... |
"""
This module has a number of public methods which are useful for working
with licenses.
"""
from collections import namedtuple
import logging
from urllib.parse import urlparse
from common import urls
from common.licenses import constants
logger = logging.getLogger(__name__)
LICENSE_PATH_MAP = constants.get_licens... |
"""
All fields that are attached to the models.
The core design of django-parler is to attach descriptor fields
to the shared model, which then proxies the get/set calls to the translated model.
The :class:`TranslatedField` objects are automatically added to the shared model,
but may be added explicitly as well. This... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.