text stringlengths 3.07k 22.1k |
|---|
import numpy as np
def batch_culture_self_replicator(params,
time,
gamma_max,
nu_max,
omega,
phi_R,
phi_P,
... |
# <NAME>
# 2/5/16
#
# Script to find ordered sets of points for robot arm to draw given black and white image
# assumed to be mainly comprised of lines.
# Useage:
# python find_strokes <image_filename> <scale> <comp_factor> [<image_output_filename>]
# <image_filename>
# <scale> floating point number to scale pixel coor... |
import networkx as nx
from queue import Queue
from networkx.algorithms.efficiency_measures import efficiency
from numpy.core.fromnumeric import shape
import pandas as pd
import numpy as np
from pandas.core.frame import DataFrame
from sklearn import preprocessing
import matplotlib.pyplot as plt
def readCsv():
path... |
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from evo_spotis.mcda_methods import SPOTIS
from evo_spotis.stochastic_algorithms import DE_algorithm
from evo_spotis.additions import rank_preferences
from evo_spotis import correlations as corrs
from evo_spotis im... |
from keras.models import *
from keras.layers import *
import keras.backend as K
import keras
IMAGE_ORDERING = 'channels_last'
def relu6(x):
return K.relu(x, max_value=6)
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
channel_axis = 1 if IMAGE_ORDERING == 'channels_first' else ... |
import os
import sys
import re
import six
from queue import Queue, Empty
from subprocess import PIPE, check_call
from psutil import Popen, NoSuchProcess
from threading import Thread
from mock import MagicMock
from time import sleep
from py_tools.common import replace_bad_chars
from py_tools.concurrency import ExcToQu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 12:28:50 2019
@author: Esraa
"""
import numpy as np
from xlrd import open_workbook
import pandas as pd
from gensim.models import KeyedVectors
from nltk.tokenize import wordpunct_tokenize
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.co... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Implementation of the "fetcher" module of HMA.
Fetching involves connecting to the ThreatExchange API and downloading
signals to synchronize a local copy of the database, which will then
be fed into various indices.
"""
import collections
imp... |
from os.path import isfile, join
from glob import glob
from sys import argv
from optparse import OptionParser
def get_unique_samples(filelist):
sample_names = set()
for name in filelist:
name = name.split("Ch.")[-1]
name = name.split(".")[0]
sample_names.add(name)
return sample_... |
#!/usr/bin/env python
from optparse import OptionParser
from collections import OrderedDict
import json
import os
import pdb
import sys
import numpy as np
import pickle
import pybedtools
import pysam
import tensorflow as tf
import pygene
from basenji import dna_io
from basenji import rnann
from basenji import vcf as... |
"""
Utilities for calling and parsing calls to various Blast+ programs, BLOSUM
similarity calclations, and calculating SNebula scores.
See the documentation for BLAST:
https://blast.ncbi.nlm.nih.gov/Blast.cgi
The blast helpers are largely wrappers around the blast modules from BioPython.
http://biopython.org/... |
"""Defines various container and running state types for the Discord API."""
import asyncio
import discord
from typing import Dict, List, Optional
import uita.audio
import uita.utils
import logging
log = logging.getLogger(__name__)
class DiscordState():
"""Container for active Discord data.
Attributes:
... |
#!/usr/bin/env python
# coding: utf-8
import os
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-fs','--folder_to_save', type=str, default=None)
ap.add_argument('-fl','--folder_to_load', type=str, default=None)
ap.add_argument('-g', '--gpus', type=str, default='0')
args = ap.parse_args()
if a... |
#! /usr/bin/env python
from tollan.utils.log import get_logger
from astropy.table import Table, MaskedColumn, vstack, unique, join
import numpy as np
# from astropy.io import registry
from tollan.utils.log import logged_dict_update
from astropy.utils.decorators import sharedmethod
from ..io.registry import open_file
f... |
"""Climate Datasets Downloader
This script allows the user to download climate datasets from the Coperniucs Climate Change Serivice
by cdsapi package and terminal commands.
Actually class retrieves ERA5 hourly data on single levels from 1979 to present, for all months,
all days in a month, and all hours in a day in the... |
import os
import sys
import subprocess
import pathlib
from dotenv import load_dotenv
import json
import time
import requests
import urllib
load_dotenv(os.path.join('.', 'config.env'))
VERBOSE=True
AZ_SUBSCRIPTION=os.getenv("AZ_SUBSCRIPTION_ID")
AZ_WORKSPACE=os.getenv("AZ_WORKSPACE")
AZ_POOL=os.getenv("AZ_POOL")
AZ_... |
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import display, HTML
from .room import find_echoes, find_dir, irstats
from .process import spectrum, spectrogram, fconvolve
plt.style.use('dark_background')
def pars_print(pars, keys=None, cols=None, chan=0):
'''
Imprime una tabla ... |
#!/usr/bin/python
#####################################################################
# Cloud Routes: Actioner (aka Sink)
# ------------------------------------------------------------------
# Description:
# ------------------------------------------------------------------
# This process will recieve messages from t... |
import collections
from collections import defaultdict
import sys
import json
import random
from jsmin import jsmin
from io import StringIO
import numpy as np
import copy
import importlib
from functools import partial
# import scipy
# import matplotlib.pyplot as plt
# import pandas as pd
sys.path.insert(0, '/n/group... |
import logging
from PIL import Image, ImageChops, ImageEnhance, ImageOps
from io import BytesIO
from os import path
import tempfile
import subprocess
import pgmagick
import cv2
import numpy as np
def gmagick_from_pil(img, fmt="jpeg"):
""" Convert a PIL Image into a GraphicsMagick Image.
Currently we do th... |
"""
key functions from <NAME>'s Basenji (https://github.com/calico/basenji)
used to build scBasset architecture.
"""
import random
import sys
import tensorflow as tf
import numpy as np
import pysam
##############
# preprocess #
##############
def dna_1hot(seq, seq_len=None, n_uniform=False):
"""dna_1hot
Args:... |
"""
Copyright (C) 2018 University of Massachusetts Amherst.
This file is part of "coref_tools"
http://github.com/nmonath/coref_tools
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.... |
"""Vulnerability schema."""
import enum
from sqlalchemy import (Column, String, Integer, Date, Enum, Float, Boolean,
DateTime, Interval, String, Text, ForeignKey, VARCHAR)
from sqlalchemy.orm import relationship
from geoalchemy2 import Geometry, Raster
from .base import Base, LiberalBoolean
f... |
from __future__ import print_function
import argparse
import torch
import torch.utils.data
import os
import yaml
import numpy as np
from functools import partial
from tqdm import tqdm
from torch.nn import functional as f
from torchvision import transforms
from dataload.action_dataset import RolloutSequenceDataset
from ... |
import numpy as np
import os
import sys
import traceback
from enum import Enum
from source import networking
from source import utils
from source import plots
from source import settings
# from source.dr1.game_dr1 import GameDr1
from source.dirt_rally.game_dirt_rally import GameDirtRally
class GameState(Enum):
i... |
import os
import sys
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from tabulate import tabulate
######################################################
# All problems represented in the paper's main table #
######################################################
BENCHMARK = [
(1, "max"),
(2... |
from typing import Tuple, List, Optional
from flask_login import current_user
from models import SERIES_TYPES, BYE_SERIES_TYPES, FINAL_SERIES_TYPES, Standing, Series, Match, Player, WINNER, \
DECIDER, INITIAL1, INITIAL2, FINAL
class MatchGroup:
def __init__(self):
self.past_matches: List[MatchPlayer... |
import math as _math
# Author: <NAME>
# Date: 2016
# Apr 2018: modified for Python 3
def _homogenous_line(A,B):
"""Return line through A and B in homogenous coordinates (a,b,c) with ax+by+c=0."""
if A==B: raise ValueError('Degenerate line through %s and %s' % (repr(A),repr(B)))
Ax,Ay=A
Bx,By=B
... |
import copy
import json
import os
from datetime import date
from decimal import Decimal
import pytest
import requests
from tests.erica_legacy.samples.grundsteuer_sample_data import get_grundsteuer_sample_data
ERICA_TESTING_URL = os.environ.get("ERICA_TESTING_URL", "http://0.0.0.0:8000")
@pytest.fixture()
def full_... |
import simplejson as json
from flask.ext.api import status
import flask as fk
from marketdb.common import crossdomain
from market import app, SERVICE_URL, service_response, get_user_city, get_country, get_one_number, get_cities, menu
from marketdb.common.models import Market
from time import gmtime, strftime
import ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch.nn import functional as F
import copy
import math
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.structures.bounding_box import ObjectList
from maskrcnn_benchmark.modeling.box_coder import BoxC... |
import os, sys
import subprocess
import glob
import re
from .generate_separate_unit import lookup_function_path
from clang.cindex import Index, CursorKind
import binascii
def read_ktest(ktest_path):
sym_vars = {}
if not ktest_path.endswith('.ktest'):
print(ktest_path)
print('The filename i... |
"""
Implementation of Zabbix API objects.
"""
import json
from datetime import datetime
class MetaApiObject(type):
"""
Metaclass for ApiObject provides:
- dynamic doc string based on ApiObject.PROPS
"""
@property
def __doc__(self):
l = ['API Properties:']
for name, prop in ... |
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, GRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D, MaxPooling1D
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate
from keras.layers import Reshape, Fl... |
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
import pandas as pd
import time, os, sys
import argparse
# User-defined
from network import Network
from utils import Utils
from data import Data
from model import Model
from config import config_test, directories
tf.logging.set_verbosity(tf.logging.ERROR)... |
import os
import copy
import six
from six.moves.urllib.parse import urlparse
from ruamel.yaml.comments import CommentedMap, CommentedSeq
from .scriptcwl import load_cwl
from .reference import Reference
class PackedWorkflowException(Exception):
"""Error raised when trying to load a packed workflow."""
pass
... |
import paddle
import paddlenlp
from paddlenlp.data import Stack, Dict, Pad
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import ErnieForQuestionAnswering
from paddlenlp.metrics.squad import squad_evaluate, compute_prediction
import time
import argparse
from functools import partial
from utils ... |
import time
import uuid
import typing
import logging
import asyncio
import websockets
from enum import Enum
from io import StringIO
from async_signalr_client import protocols, exceptions
from async_signalr_client.models import messages, futures
from async_signalr_client.transports import BaseTransport, WebSocketTransp... |
# Copyright (C) 2019 Alibaba Group Holding Limited.
# All Rights Reserved.
# ==============================================================================
"""Startup script for TensorFlow.
See the README for more information.
"""
from __future__ import division
from __future__ import print_function
import os
import ... |
"""
Utility function that creates an HTML page from the penalty dicts
(e.g. head_table.py).
Each penalty dict becomes an HTML table. The dicts look like:
Weapon type:
body part:
level1_penalties
level2_penalties
body part2:
level1_penalties
level2_penalties
Weapon type2:
... |
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,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
# http://www.apache.org/licenses/LICE... |
# -*- coding: utf-8 -*-
import warnings
import datetime
from dateutil.relativedelta import relativedelta
from six import string_types, binary_type, text_type
from rqdatac.utils import listify, to_date
def ensure_list_of_string(s, name=""):
if isinstance(s, string_types):
return [s]
result = list(s)... |
#! /usr/bin/env python
from __future__ import division, print_function
from collections import defaultdict
from copy import copy, deepcopy
import random
class IntcodeComputer(object):
def __init__(self, raw_intcode_list, initial_inputs=[]):
self.pc = 0 # program counter
self.rb = 0 # relative base... |
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
def compute_execution_risk(collisions: []):
"""
Compute execution risk given a sequence of collision probabilities through dynamic programming.
Parameters
----------
collisions : []
A list of ste... |
import os
import struct
import logging
import binascii
from textwrap import dedent
import angr
from angr.storage.file import SimFileDescriptorDuplex
from ..enums import CrashInputType
from ..scripter import Scripter
from .actions import RexSendAction
l = logging.getLogger("rex.exploit.exploit")
class ExploitExcep... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Mersenne Twister pseudo-random number generator
Provides the MersenneTwister class and mt_genrand function for generating
pseudo-random numbers using the 1999-10-28 integer variant of the Mersenne
Twister engine. Has methods for generating reals [0,1] [0,1) (0,1) intervals.... |
import pandas as pd
import random,time
import numpy as np
import math,copy
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from skle... |
import gensim
import nltk
import black
import textwrap
import datetime
import inspect
import re
import numpy as np
import warnings
import abc
import importlib
import enlighten
from pathlib import Path
from autogoal.kb import *
from autogoal.grammar import Discrete, Continuous, Categorical, Boolean
from autogoal.cont... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 <NAME> <<EMAIL>>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, thi... |
# coding:utf-8
from typing import Dict, TypeVar, Union, Type, Optional, Mapping, Any, NewType
from collections import OrderedDict
from functools import singledispatch, lru_cache
from itertools import repeat
from typing_inspect import get_constraints, get_bound
from .compat import get_generic_origin, get_generic_params,... |
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# 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, publi... |
"""
Utilities for rock chemistry and mineral abundance classification.
Todo
-------
* Petrological classifiers: QAPF (aphanitic/phaneritic),
gabbroic Pyroxene-Olivine-Plagioclase,
ultramafic Olivine-Orthopyroxene-Clinopyroxene
"""
import os
import json
from pathlib import Path
import numpy as np
import pandas as ... |
#!/usr/bin/env python3
"""
FILE: stop_job.py
DESCRIPTION: Gearman worker that handles the manual termination of other OVDM
data transfers and OVDM tasks.
BUGS:
NOTES:
AUTHOR: <NAME>
VERSION: 2.6
CREATED: 2015-01-01
REVISION: 2021-02-13
"""
import argparse
import json
import logging
import... |
import pandas as pd
import os
import Orange
import matplotlib.pyplot as plt
import itertools
from utils.model_evaluation.bayesiantests import signtest, signtest_MC, plot_posterior
from multiprocessing import Pool
from functools import partial
def read_experiment_data(dir, use_cols = ['ROC', 'Resample', 'model', 'feat_... |
#!/usr/bin/env python3
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
from tf.transformations import quaternion_from_euler
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list
from sensor_msgs.msg import... |
# Copyright (C) 2019-2021, <NAME>.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
'''
Training script for object detection
'''
import math
import datetime
import time
from pathlib import Path
from fastp... |
"""The conductor delegates messages from the consumer to the streams."""
import asyncio
import os
import typing
from collections import defaultdict
from typing import (
Any,
Callable,
Iterable,
Iterator,
List,
MutableMapping,
MutableSet,
Optional,
Set,
Tuple,
cast,
)
from mo... |
"""
This module has a class for specifying a problem from just
a smooth function and a single penalty.
"""
from __future__ import print_function, division, absolute_import
import numpy as np, warnings
from ..problems.composite import composite
from ..affine import identity, scalar_multiply, astransform, adjoint
from ... |
#VERSION: 1.0
INFO = {"netscan":("icy_shadow_net_scanner","ISPY TCP scanner")}
RLTS = {"cls":("temp_struck","threading","socket","time"),"funcs":("echo","get_args"),"vars":()}
ISPY_VERSION = "1.3"
def icy_shadow_net_scanner(cmd): # main cmd part
opts = get_args(cmd)
if opts == {}:
echo(1,"[ERROR] syntax error,... |
# Copyright 2016, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import base64
from copy import deepcopy
import json
import os
try:
from urllib.parse import urlparse
except ImportE... |
# Core django imports
from django.conf import settings
from django import VERSION as DJANGO_VERSION
from django.utils.encoding import python_2_unicode_compatible
from django.core.validators import RegexValidator
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
if DJANGO_VERSION[:2] < (... |
import argparse
import random
import warnings
import time
import os
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim as optim
import torch.multiprocessing as mp
from torchvision import datasets, transforms
from model import LeNet5
parser = arg... |
# 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, overload
from . import ... |
import click
from dateutil import parser
import json
import sqlite3
import sqlite_utils
import tqdm
sqlite3.enable_callback_tracebacks(True)
def common_options(fn):
click.option("-s", "--silent", is_flag=True, help="Don't show a progress bar")(fn)
click.option("--drop", is_flag=True, help="Drop original colu... |
import argparse
import cv2
import numpy as np
from alignment_fixer import find_matching_point_between_patch_and_reference, filter_and_draw_contours, \
align_template_to_image, PreProcess, prepare_for_matching
from simple_manipulations import crop_image_by_size, crop_image_by_coordinates
def could_be_defect(cont... |
#! /usr/bin/env python3
import sqlite3
import ctypes
import time
import threading
from queue import Queue
from f1_2020_telemetry.types import (TeamIDs, TrackIDs, ButtonFlag, InfringementTypes, NationalityIDs, PenaltyTypes, SurfaceTypes)
from ..types import TableID,DriverIDs
#
class DbHandler(threading.Thread):
... |
# -*- coding: utf-8 -*-
#
# This software may be modified and distributed under the terms
# of the Apache License, Version 2.0 license. See the LICENSE file for details.
"""
PyLogBeat is a simple, incomplete implementation of the Beats protocol
used by Elastic Beats and Logstash.
"""
from collections.abc import Mapp... |
"""
the model translates Chinese to English
"""
import random
import torch.cuda
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.nn.utils.rnn import pad_sequence
from data import load_data
from nltk.tokenize import word_tokenize
device = torch.device('cuda' if torch.cuda.is_av... |
# -*- coding: utf-8 -*-
"""Test for the csdm object
1) sin, cos, tan, arcsin, arccos, arctan,
2) sinh, cosh, tanh, arcsinh, arccosh, arctanh
3) exp, exp2, expm1, log, log2, log10, log1p
4) negative, positive, absolute, fabs, rint, sign, conj, conjugate
5) sqrt, square, cbrt, reciprocal, power
"""
im... |
# 从app模块中即从__init__.py中导入创建的webapp应用
import base64
import json
import os
from datetime import datetime
import cv2
import requests
from werkzeug.urls import url_parse
from werkzeug.utils import secure_filename
from app.models import db
from flask import render_template, flash, redirect, url_for, request, Blueprint, g
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 9 19:46:21 2018
@author: galengao
"""
import sys
import multiprocessing
from itertools import chain
import numpy as np
import pandas as pd
from sklearn.decomposition import TruncatedSVD
def get_tumor_list(sif_file):
# df = pd.read_table(sif_f... |
# coding=utf-8
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Copyright (c) 2019, NVIDIA CORPORAT... |
"""
Calculation of the terms in the tendency of mesoscale aggregation from
Narenpitak at al. (2021). The terms are derived from the equations of
Bretherton and Blossey (2017)
Usage:
aggregation_terms.py
<path> <start_time> <resolution> <data_grid>
[<coarse_factor>]
aggregation_terms.py (-h | --... |
import sqlite3
import logging
import sys
import csv
import io
from dataclasses import dataclass, fields as get_fields, astuple, asdict, field, Field
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter as ADHFormatter, ArgumentTypeError, Namespace
from pathlib import Path
from datetime import datetime
fr... |
from collections import namedtuple
from functools import reduce
from math import ceil
from typing import Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
# where the x, x' and y, y' are located in the phase space coord vector
PLANE_INDICES = {"h": [0, 1], "v": [2, 3]}
PLANE_SLICES =... |
import time
import glob
import copy
import numpy as np
import awkward as ak
from ..logger import _logger
from .tools import _get_variable_names, _eval_expr
from .fileio import _read_files
def _apply_selection(table, selection):
if selection is None:
return table
selected = ak.values_astype(_eval_expr... |
import argparse
import os
import time
import csv
import traceback
import configparser
from os.path import basename
from utils import Config, Editor, Rubric
from javamarker import JavaMarker
from pythonmarker import PythonMarker
def convertPaths(path, join = False):
"""
Converts relative paths to absolute path... |
from inspect import isclass
from typing import NamedTuple, Tuple, Optional
from .data_types import Vec3, Vec4
from .packet_buffer import PacketBuffer
from .packet_component import PacketComponent
from .version import Version
class FramePrefix(PacketComponent, NamedTuple("FramePrefixDataFields", (
(... |
import re
from brmp.backend import Assets
from brmp.family import Family, LinkFn, Normal, args, free_param_names
from brmp.model import Group, ModelDesc
from brmp.utils import traceback_generated
def gen_expanded_scalar(val, shape):
assert type(val) in [float, int]
return 'torch.tensor({}).expand({})'.format... |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
# drop_path function & DropPath class & Attention class
# Modified from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
#
# Copyright 2019, Facebook, Inc
#
# Licensed under the Apache License, Version 2.0 (the... |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import cv2
import torch
import numpy as np
from tqdm import tqdm
from multiprocessing import P... |
from pydoc import cli
from threading import Thread
import time
import pickle
import socket
import struct
from threading import Thread
import sys
from dataclasses import dataclass
import keyboard
import os
import platform
from source.hardware.RobotData import RobotData
import cv2
vel_data = RobotData(linear=0.0, ang... |
from __future__ import print_function
import numpy as np
from heapq import nlargest
from time import time
import marshal
# TODO - FEATURES:
## TODO: sparse permanence like in the temporal_pooler
## TODO: boosting: firing uses b_dec boosting_factor, which restores by b_inc per cycle
## TODO: TEST dynamic threshold (ra... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import copy
import datetime
import numpy as np
import os.path as osp
import itertools, pkg_resources, sys
from distutils.version import LooseVersion
if LooseVersion(pkg_resources.get_distribution("chainer").version) >= LooseVersion('7.0.0') ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: software/jetson/fastmot/videoio.py
# By: <NAME>
# For: Myself
# Description: This file was adapted from FastMOT for uARM feedback control.
# Reference: https://github.com/GeekAlexis/FastMOT.git
from pathlib import Path
from enum import E... |
# 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... |
"""Queries used by pg-discuss core and available to extensions."""
import sqlalchemy as sa
import sqlalchemy.dialects.postgresql
from . import ext
from . import tables
from . import utils
from .db import db
class CommentNotFoundError(Exception):
pass
class ThreadNotFoundError(Exception):
pass
class Ident... |
# -*- coding: utf-8 -*-
from django.db import models
from skosxl.models import *
try:
from django.utils.encoding import python_2_unicode_compatible
except:
from six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from rdf_io.models import ImportedResource
try:... |
import os
from typing import Tuple, List, Callable
import numpy as np
import pandas as pd
from pathlib import Path
from . import problem_register
from xbbo.core.abstract_model import TestFunction
deepar = 'DeepAR'
fcnet = 'FCNET'
xgboost = 'XGBoost'
nas102 = 'nas_bench102'
svm = 'svm'
metric_error = 'metric_error'
m... |
# -*- coding: utf-8 -*-
from enum import Enum, unique
from functools import partial, wraps
from itertools import count, product, repeat, takewhile
from math import cos, isclose, radians, degrees, sin, sqrt, tan
import numpy as np
from numpy.linalg import norm
from .affine import change_basis_mesh, change_of_basis
#... |
from __future__ import print_function
import os
import torch
import numpy as np
import time
import feat
from feat.face_detectors.Retinaface.Retinaface_model import PriorBox, RetinaFace
from feat.face_detectors.Retinaface.Retinaface_utils import (
py_cpu_nms,
decode,
decode_landm,
)
from feat.utils import ge... |
from enum import Enum
import copy
from pgm_reader import pgmToBoard
# --------------------------------
# CHANGE ME!
# |
# V
# use '16x16.pgm', '64x64.pgm'...'512x512.pgm'
PGM_FILE = '16x16.txt'
ITER = 1
OUTPUT_ALIVE = True
# --------------------------------
# for testing
BOARD_SIZE = 16
BOARD = [
[0, 0,... |
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision.datasets.folder import ImageFolder
from .common import DatasetPrototypes, Subset, get_index_of_classes, split_dataset
import torchvision.transforms
import os
from .mnist_m import MNISTM
import logging
class DoubleDataset(torch.ut... |
"""Functions used for generating packed CSS sprite maps.
These are ported from the Binary Tree Bin Packing Algorithm:
http://codeincomplete.com/posts/2011/5/7/bin_packing/
"""
from __future__ import absolute_import
from __future__ import unicode_literals
# Copyright (c) 2011, 2012, 2013 <NAME> and contributors
# Copy... |
#!/usr/bin/env python2.7
################################################################################
# USAGE:
# DESCRIPTION: Script to write a telomere pipeline for a particular
# sample.
# Created by <NAME>, <NAME>, <NAME>
################################################################################
###... |
"""Tests for the :class:`AssertionManager<assertionlib.manager.AssertionManager>` class."""
from typing import Optional
import pytest
from assertionlib import assertion
try:
import numpy as np
NUMPY_EX: Optional[Exception] = None
except Exception as ex:
NUMPY_EX = ex
def test_abs() -> None:
"""Tes... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
#! /usr/bin/python
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it... |
from PIL import Image, ImageDraw
import numpy as np
from scipy.cluster.vq import vq, kmeans
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
# Computes the cost of given boundaries. Good boundaries have zero cost.
def get_boundaries_cost( boundaries, good_boundaries ):
return np.sum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.