text stringlengths 3.07k 22.1k |
|---|
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... |
import json
import os
from collections import Counter
from functools import partial
from multiprocessing import Pool
from typing import Dict, List
import torch
from nltk import sent_tokenize
from tqdm import tqdm
from transformers import PreTrainedTokenizer
from transformers.tokenization_utils_base import PaddingStrat... |
import tensorflow as tf
import csv
from bert_serving.client import BertClient
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
import numpy as np
from bert_serving.server.helper import get_args_parser
from bert_serving.server import BertServer
... |
# Copyright (c) 2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for Twisted's deprecation framework, L{twisted.python.deprecate}.
"""
import sys, types
from twisted.trial.unittest import TestCase
from twisted.python import deprecate
from twisted.python.deprecate import _appendToDocstring
from... |
"""contains classes and methos to read in an ansys database file"""
import mmap
import warnings
import numpy as np
from pyansys import _db_reader
from pyansys.common import read_table, parse_header, read_standard_header
from pyansys.vtk_helper import raw_to_grid
from pyansys._reader import component_interperter
DB_... |
from tkinter import *
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Stick Man -Brought to you by <EMAIL>")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, highlightthickness=0)
self.canvas.pack()
self.tk.update... |
import json
import copy
import threading
import array
import struct
import time
import csv
import os
import subprocess
import paho.mqtt.client as paho
import ssl
# FILL THIS WITH YOU CREDENTIALS AND CERTS FOLDER
EndPoint = "xxxxxxxxxxxxxx.iot.us-east-1.amazonaws.com"
topic = 'birds-detected'
caPath = "Certs/ca.cert"
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
from mock import Mock
from collections import defaultdict
import unittest
from blocks.extensions.predicates import OnLogRecord
from blocks.extensions.stopping import (FinishIfNoImprovementAfter,
EarlyStopping)
class FakeLog(defaultdict):
epoch_length = 4
def __init__(s... |
import os
import re
import json
import pickle
import string
import numpy as np
from collections import defaultdict
from sklearn.feature_extraction.text import TfidfVectorizer
from torch.utils.data import Dataset
class MyDataset(Dataset):
def __init__(self, dataset):
self._dataset = dataset
def __geti... |
import re
import csv
from openpyxl import load_workbook
import xlwt
import random
import ogr,os,osr,sys
from math import ceil
try:
from osgeo import gdal
from osgeo import ogr
except ImportError:
import gdal
import ogr
def get_Location(locationFileName):
#一、打开文件
f = open(loc... |
"""
Projecting the LEap Coordinates onto the Webcam image feed
1) The Rotation matrix = Identity Matrix, translation vector = Zeros
2) There is a slight misalignment between the Leap Motion and Webcam that is taken into consideration (40mm on the Oy axis)
3) Export (Leap 3D, Camera 2D) Coordinates into XML files
... |
#!/usr/bin/python
#
# Copyright 2020 Google 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 applicable law or ag... |
from __future__ import division
import numpy as np
import warnings
from numpy.linalg import inv
from .base import _check_declination, nortek_euler2orient as euler2orient, nortek_orient2euler as orient2euler
from . import base as rotb
def beam2inst(advo, reverse=False, force=False):
"""
Rotate data in an ADV o... |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
# Copyright 2021 <NAME> (@singletongue)
#
# 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/LICEN... |
# -*- coding: utf-8 -*-
import time
import socket
import subprocess
from mss import mss
from functools import wraps
from pywinauto.application import Application
from pywinauto import mouse, keyboard
from pywinauto.win32structures import RECT
from pywinauto.win32functions import SetForegroundWindow, GetSystemMetrics ... |
import bottle
import os
import hashlib
from model import Uporabnik, Dnevnik, seznam_zvrsti, seznam_ocen
from datetime import date
imenik_s_podatki = 'uporabniki'
uporabniki = {}
skrivnost = '<NAME>'
if not os.path.isdir(imenik_s_podatki):
os.mkdir(imenik_s_podatki)
for ime_datoteke in os.listdir(imenik_s_podatk... |
"""Test Axis event stream.
pytest --cov-report term-missing --cov=axis.event_stream tests/test_event_stream.py
"""
from asynctest import Mock
import pytest
from axis.event_stream import EventManager
from .event_fixtures import (
FIRST_MESSAGE,
AUDIO_INIT,
DAYNIGHT_INIT,
PIR_INIT,
PIR_CHANGE,
... |
from __future__ import absolute_import
import logging
import warnings
import sys
_log = logging.getLogger(__name__)
import cothread
from functools import partial
from . import raw
from .raw import Disconnected, RemoteError, Cancelled, Finished, LazyRepr
from .thread import TimeoutError
from ..wrapper import Value,... |
from __future__ import absolute_import
from email.utils import parsedate
from functools import partial, wraps
from time import mktime
import warnings
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import (
NoReverseMatch, reverse, get_script_prefix, set_script_p... |
import math
import torch
from torch import nn
class EncoderLayer(nn.Module):
def __init__(self, d_model, d_ff, num_heads, d_k, drop_out_rate):
super().__init__()
self.layer_norm_1 = LayerNormalization(d_model)
self.multihead_attention = MultiheadAttention(d_model, num_heads, d_k... |
# generate stats for each processing steps
import pandas as pd
from collections import Counter
from functools import reduce
import gzip
import re
import os, sys
def count_reads(in_fq, n=4):
# support either text or gzip file
try:
f = gzip.open(in_fq, "rt")
except:
f = open(in_fq, "rt")
# count reads
cou... |
import inspect
from dataclasses import dataclass, field, make_dataclass
from distutils.version import LooseVersion
from enum import Enum
from os.path import join
from typing import Any, List, Optional, Tuple, Type, Union
import pytorch_lightning as pl
import torch
from jsonargparse.typing import (
ClosedUnitInterv... |
from .components import *
import numpy as np
#######################################
#
# Generate a tree of unary & binary operations.
#
# Using the code from
# Deep Learning for Symbolic Mathematics(ICLR 2020)
# https://arxiv.org/abs/1912.01412
# https://github.com/facebookresearch/SymbolicMathematics
#
############... |
import torch
import numpy as np
import wandb
import torch.nn as nn
from models.gnn import EdgeGnn, NodeGnn, QNodeGnn, GlobalNodeGnn
from utils.distances import CosineDistance
from utils.sigmoid_normal import SigmNorm
class Agent(torch.nn.Module):
def __init__(self, cfg, StateClass, distance, device):
supe... |
import logging
import os
import threading
import time
import argparse
import matplotlib.pyplot as plt
import pandas as pd
import pathlib
import scipy.interpolate
import threading
import json
from .utils import run_command, _init_modes, _init_precs
from .timing import _aggregate_along_rows, _LINESTYLES, _COLORS
try:
... |
# Copyright: 2006-2007 <NAME> <<EMAIL>>
# License: GPL2/BSD
from pkgcore.restrictions import values
from pkgcore.test import TestCase, TestRestriction
class SillyBool(values.base):
"""Extra stupid version of AlwaysBool to test base.force_{True,False}."""
def __init__(self, negate=False):
object.__set... |
import json
import os
import platform
import random
import secrets
import subprocess
import trueskill
from serde import Choice, Dict, InstanceField, Int, List, Model, ModelField, Str
if platform.system() == 'Windows':
HALITEBIN = '.\\halite.exe'
else:
HALITEBIN = './halite'
if not os.path.exists(HALITEBIN):... |
"""
Module for identifying and parsing ALF file names.
An ALF file has the following components (those in brackets are optional):
(_namespace_)object.attribute(_timescale)(.extra.parts).ext
Note the following:
Object attributes may not contain an underscore unless followed by 'times' or 'intervals'.
A nam... |
import glob
import os
import numpy as np
import pytest
from sklearn.datasets import load_breast_cancer
from fedot.core.chains.chain import Chain
from fedot.core.chains.node import PrimaryNode, SecondaryNode
from fedot.core.composer.cache import OperationsCache
from fedot.core.data.data import InputData
from fedot.cor... |
# Needs keras version 1, with keras 2 does not work -> Merge option to merge 2 sequential models
# NOTE -> It worked with keras 2.0.8 and Tensorflow 1.10.1
import numpy as np
from skimage import io, color, exposure, transform
from sklearn.cross_validation import train_test_split
import os
import glob
import h5py
from t... |
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
#import requests
from io import BytesIO
from PIL import Image
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
import numpy as np
from coco import COCO
import os
import cv2
import json
def load(url):
"""
Given an url of an... |
"""
This file deals with processing and loading the IEMOCAP database. There are two
options to use this database:
- Load the database into RAM as a numpy array
- Process the database into .npy files of log-mel spectrogram
Use the first option if you want quick access to the database or if you need to
apply ope... |
r"""
.. _ref_vm6_example:
Pinched Cylinder
----------------
Problem Description:
- A thin-walled cylinder is pinched by a force :math:`F` at the middle
of the cylinder length. Determine the radial displacement :math:`\delta`
at the point where the force :math:`F` is applied.
The ends of the cylinder are free... |
#this utils class has multiple functions to ease up development etc.
#also especially for Samek et. al
from PIL import Image
from torchvision import transforms
import numpy as np
import torch
from dataclasses import dataclass
import operator
import matplotlib.pyplot as plt
@dataclass
class R_pix:
def __init__(s... |
import io
import json
import os
import pickle
import numpy as np
import pandas as pd
import scipy.stats
import pathlib
import PIL.Image
import cifar10
cifar10_label_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
def np_to_png(a, fmt='png', scale=1):
a = np.uin... |
#!/usr/bin/env python3
'''
Copyright 2017 The Regents of the University of Colorado
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
... |
from functools import partial
from django import forms
from django.core.cache import cache
from django.db import models
from django.db.models.fields import BLANK_CHOICE_DASH
from django.template.defaultfilters import slugify
from django.utils.translation import gettext_lazy as _
class Specification(models.Model):
... |
import contextlib
import errno
import json as jsonmodule
import logging
import sqlite3
import sys
import time
from http.cookies import Morsel, SimpleCookie
from types import SimpleNamespace
from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Sequence
import aiohttp
from aiohttp import WSMessage
from ... |
#!/usr/bin/env python
# coding: utf-8
from apns import *
from binascii import a2b_hex
from random import random
import hashlib
import os
import time
import unittest
TEST_CERTIFICATE = "certificate.pem" # replace with path to test certificate
NUM_MOCK_TOKENS = 10
mock_tokens = []
for i in range(0, NUM_MOCK_TOKENS):
... |
# -*- coding: utf-8 -*-
"""Helpline forms"""
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.forms import ModelForm
from django.conf import settings
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from selectable.forms import AutoComplete... |
# Copyright © 2020-2021 <NAME> and contributors
#
# 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, p... |
# !/usr/bin/env python3
import mxnet as mx, gluonnlp as nlp
from mxnet.gluon import nn, rnn
from mxnet import nd, autograd, gluon
import pandas as pd, numpy as np
import logging
np.random.seed(9102)
mx.random.seed(8064)
logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s')
logger = logging.Logger(__nam... |
#!/usr/bin/env python3
import sys
import numpy as np
import pathlib
import NeuralNet
import MCTS
import copy as cp
class utttgame:
NUMBER_OF_SAVED_GAME_STATES = 4
def __init__(self):
self.init_game()
def init_game(self):
#turn player 1 (x) == 1, player 2 (o) == 2
self.turn... |
# pylint: disable=useless-super-delegation,too-many-locals
# pylint doesn't recognize abstract methods
import logging
import shutil
from rpdk.core.data_loaders import resource_stream
from rpdk.core.exceptions import InternalError, SysExitRecommendedError
from rpdk.core.init import input_with_validation
from rpdk.core.... |
# this file is originally in exp_3_debiased folder
# plot predict dense map with true force point.
# show the changes of learning process from 1 point to 10 points
import numpy as np
import autosklearn.regression
import sklearn.model_selection
import sklearn.datasets
import sklearn.metrics
import scipy
import pickle
i... |
from pygame.locals import *
import pygame
import enum
import random
import argparse
from ai import *
from controller import *
import matplotlib.pyplot as plt
import numpy as np
import statistics
from sklearn.linear_model import LinearRegression
INITIAL_LENGTH = 1
WINDOW_TO_STEP_MULTIPLIER = 20
MAX_MOVES_COUNT = 150
... |
#
# Copyright 2017-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 ... |
import os
import glob
import torch
import numpy as np
from termcolor import colored
from .eventdataset import EventDataset, EventDetectionDataset
from .eventchunkdataset import EventChunkDataset, EventDetectionChunkDataset
from .filereader import (BinFileReader, AerFileReader, PropheseeReader,
... |
from SALib.sample import saltelli
from SALib.analyze import sobol
import pandas as pd
import numpy as np
# https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/sobol.html
# https://salib.readthedocs.io/en/latest/basics.html#what-is-sensitivity-analysis
def custom_cv_kfolds_testdataonly(X, kfolds):
n = X... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------.... |
"""Testing ccmap C extension
Usage:
threadTest.py (cmap|lcmap) <threadNum> <dataSize> --lib <pathToPyLib> (--inp <tranformationFile> [--gen <seed>] | --rec <filepathFirstPdbFile> [--lig <filepathFirstPdbFile>] ) [ --encode --atomic ] [ --dist <ccDist> ] [--out <fOut> --pref <PDBfolder>]
threadTest.py (zmap|lz... |
""" (c) 2015, Logentries.com, <NAME> <<EMAIL>>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... |
# Experiment 30 - Smooth Scrolling Tiles
#
# By <NAME> (https://github.com/Taffer)
# MIT license, see LICENSE.md for details.
import base64
import os
import pygame
import pygame.freetype
import pygame.gfxdraw
import struct
import sys
import time
import zlib
from xml.etree import ElementTree
SCREEN_TITLE = 'Experimen... |
"""
Store module level information like the API key, cache directory and the server
"""
# License: BSD 3-Clause
import logging
import logging.handlers
import os
from typing import cast
from io import StringIO
import configparser
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
def configure_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 17:29:22 2017
@author: dimitris
"""
import numpy as np
import h5py
#import scipy.io # used for exporting arrays to matlab (amongst othersf)
np.random.seed(1)
def load_data():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r... |
# Copyright (c) 2015-2019 The Botogram Authors (see AUTHORS)
#
# 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, mod... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 28 16:38:27 2018
@author: song
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 20:49:19 2018
@author: song
"""
# -*- coding: utf-8 -*-
"""
Created on Tue April 3 10:56:53 2018
Convolutional VAriational Autoencode
@a... |
from __future__ import print_function, absolute_import
import glob
import random
import os
import re
import sys
import json
import pickle
import numpy as np
from scipy.misc import imsave
import random
import pprint
from time import time
import torch
from torch.utils.data import Dataset, DataLoader
from... |
import os
from datetime import datetime
import numpy as np
import pandas as pd
from statsmodels.stats.proportion import proportion_confint
class InvalidSexException(Exception):
pass
class AgeFromName(object):
def __init__(self, mortality_df=None, year_of_birth_df=None):
'''
:param mortality... |
from routing import parse
import json
import threading
import socket
from .io import print_log
def log(message):
print_log("[Transport] {0}".format(message))
def info(message):
log("[INFO] {0}".format(message))
def error(message):
log("[ERROR] {0}".format(message))
class Transport:
"""
Trans... |
import pytest
from ethereum import tester
from functools import (
reduce
)
from fixtures import (
owner_index,
owner,
wallet_address,
get_bidders,
create_contract,
auction_contract,
auction_contract_fast_decline,
get_token_contract,
token_contract,
txnCost,
)
'''
Auct... |
"""
Contains the :class:`database <flata.database.Flata>` and
:class:`tables <flata.database.Table>` implementation.
"""
from . import JSONStorage, MemoryStorage
from .utils import LRUCache, iteritems, itervalues
class Element(dict):
"""
Represents an element stored in the database.
This is a transparent... |
import os
import pytest
import shutil
from unittest import mock
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_aws_config_template, ramp_config_template
from ramp_database.model import Model
from ramp_database.utils import setup_db
from r... |
"""
Plots Arctic sea ice extent from June 2002-present using JAXA metadata
Website : https://ads.nipr.ac.jp/vishop/vishop-extent.html
Author : <NAME>
Date : 4 August 2016
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib
impo... |
import numpy as np
np.set_printoptions(linewidth=320)
from numpy import zeros, ones, mod, conj, array, c_, r_, linalg, Inf, complex128
from itertools import product
from numpy.linalg import solve
from scipy.sparse.linalg import factorized
from scipy.sparse import issparse, csc_matrix as sparse
# Set the complex precis... |
import sys
import traceback
import os
import os.path
import datetime
import subprocess
import json
import re
import logging
import downloader_common
#
# Завантажувач архіву газет "Дзеркало тижня"
# https://dt.ua/gazeta/archive/
# починаючи з "Дзеркало тижня. Україна" №22 10 ЧЕРВНЯ-16 ЧЕРВНЯ 2017 (https://dt.ua/gazeta/... |
#!/usr/bin/python3
# Runs Moss on a Moodle submission file
#
# Usage:
# ./moodle_moss.py <moodle_zip_file>
#
# Installation Requirements:
# - Python 3
# - beautifulsoup4 (HTML parsing):
# pip3 install beautifulsoup4
# - mosspy (Python wrapper for MOSS webservice):
# [modified version vendored wi... |
from yasa import bandpower, spindles_detect_multi, sw_detect, spindles_detect, sw_detect_multi
import numpy as np
import pickle as pkl
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import pairwise_distances as pdist
import os
def estimate_med_dist(features, nu... |
import logging
import warnings
_log = logging.getLogger(__name__)
import unittest
import sys
import random
import weakref
import gc
from unittest.case import SkipTest
from ..nt import NTScalar, NTURI
from ..server import Server, StaticProvider
from .utils import RefTestCase
import cothread
from ..client.cothread i... |
import sys
import h5py
import numpy as np
from numpy.linalg import norm
from scipy.linalg import svd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import normalize
FLOAT = np.float32
# NOTE: filepath for Common Crawl GloVe embeddings goes here
CCGLOVE = '/n/fs/nlpdatasets/glove.840B/glo... |
"""
Start file for lasso of Big Data Summer 2017
The file is seperated into two parts:
1) the helper functions
2) the main driver.
The helper functions are all functions necessary to finish the problem.
The main driver will use the helper functions you finished to report and print
out the results you need for the p... |
# Modified: 2022-06-01
# Description: Implements a model for game info
#
import json
from typing import Optional
from pydantic import BaseModel, Field
from pymongo import ReturnDocument, CursorType
from marble_game import MarbleGame, MarbleGameEncoder, MarbleGameDecoder
from db import db
from .pydantic_object_id imp... |
#!/bin/env python3
"""
A lighter probe implementation.
"""
import collections
import inspect
import re
from functools import update_wrapper
from typing import Callable, Optional
from panopticon.predicate import Predicate
from panopticon.trace import DurationTraceEvent, Phase, Trace
from panopticon.tracer import Func... |
from __future__ import print_function
# std libs
import os
import sys
import copy
import time
from tqdm import tqdm
import random
import argparse
import numpy as np
from math import log10
from sklearn.metrics import f1_score
#AutoClassify
from ACTINN import Classifier, Scanpy_IO, CSV_IO
from ACTINN.utils import *
... |
"""
472. Concatenated Words
Hard
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example 1:
Input: words = ["cat","cats","ca... |
"""Rules.
This module contains functions to apply reaction rules to chemical compounds.
"""
__all__ = ["RuleLibrary"]
import json
import sqlite3 as sql
from collections import namedtuple
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from contextlib import AbstractContextManager
from itertools impor... |
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
from pdb import set_trace
import cvnn.layers as complex_layers
from cvnn.montecarlo import run_montecarlo
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) / 255., labe... |
# ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
# Copyright (c) 2018, <NAME>. This software is licensed under the BSD
# 3-Clause License. Please see the LICENSE file in the project root directory.
# ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
import... |
#!/usr/bin/env python3
import datetime
from os import listdir, path, getcwd
import json
import re
import time
from argparse import ArgumentParser
import yaml
from yaml.parser import ParserError
from cassandra.cluster import Cluster
from cassandra.query import BatchStatement
CONFIG_FILE = "config.yaml"
SCHEMA_FILE = ... |
import re
import time
from boto3 import Session
from datetime import datetime
from moto.core import ACCOUNT_ID, BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_without_milliseconds
from .exceptions import (
S3BucketDoesNotExistException,
InsufficientSnsTopicPolicyException,
TrailNameTo... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""Everyday use functions for array manipulation."""
import numpy as np
from scipy.optimize import curve_fit
from .model_functions import fwhmVoigt
def index(array, value):
"""Returns the index of the element in array which is closest to value.
Args:
a... |
import numpy as np
import copy
class MultiObjectiveOptimizer:
def __init__(self, x, fitness, n_generations=5, population_size=5, n_objectives=2, constraint=None,
generation_func=None, constraint_func_input="design", crossover_type="uniform",
mutation_type="unifom", use_genocide=F... |
#!/usr/bin/env python3
import sys
import os
from shutil import rmtree
from time import localtime, sleep
from subprocess import check_output, Popen
import argparse
try:
input = raw_input
except:
pass
def dict_replace(s, d):
for key in d:
s = s.replace(key, d[key])
return s
def extract(s,left=... |
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.path import Path
from matplotlib.gridspec import GridSpec
from PIL import Image
import csv
from hailo_model_zoo.core.postprocessing.visualize_3d.utils.correspondece_constraint import detectionInfo
ID_TY... |
import json
import logging
import os
import subprocess
from enum import Enum, unique
from typing import Dict, List, Optional, Tuple, Union
from localstack import config
from localstack.utils.bootstrap import PortMappings
from localstack.utils.common import TMP_FILES, rm_rf, safe_run, save_file, short_uid
LOG = loggin... |
''' Skeleton-based Abnormal Gait Detection (Sensors, MDPI 2016)
BSD 2-Clause "Simplified" License
Author: <NAME>'''
from __future__ import division
import numpy as np
from utils import *
from func_HMM import *
import argparse, sys
def HMMgait3_fullsequence(skel_dataset, test_subjects, n_subjects = 9... |
import torch
import numpy as np
from torch_geometric.utils import remove_self_loops, to_undirected
import networkx as nx
import graph_tool as gt
import graph_tool.topology as gt_topology
def automorphism_orbits(edge_list, print_msgs=True, **kwargs):
##### vertex automorphism orbits #####
directed=kwar... |
"""
Wear detection algorithms
<NAME>
Copyright (c) 2021. Pfizer Inc. All rights reserved.
"""
from numpy import (
mean,
diff,
sum,
insert,
append,
nonzero,
delete,
concatenate,
int_,
full,
)
from skdh.base import BaseProcess
from skdh.utility import moving_mean, moving_sd, get_... |
import git
import os
import shutil
import github
import fileinput
import yaml
import stat
import json
import time
import requests
import requests
from requests.exceptions import HTTPError
from pathlib import Path
from .app import AppStore as app
from .helpers import logger, send_notification, apply_template, parse_s... |
#! python
#
# Steps for matrix tests
#
from behave import given, then
from renderer.matrix import Matrix, IdentityMatrix
from renderer.bolts import Tuple
from math import isclose
def buildMatrixFromContextTable(context,rows=None,cols=None):
vals = [list(map(float,context.table.headings))]
for row in context.t... |
#!C:\Users\<NAME>\Documents\Anaconda3\envs\test\python.exe
"""Make hex structure libraries for all nif versions.
Installation
------------
Make sure you have PyFFI installed (see https://github.com/niftools/pyffi).
Then, copy makehsl.py to your Hex Workshop structures folder
C:\Program Files\BreakPoint Software\... |
#!/usr/bin/env python3
import os, sys, glob
import numpy as np
import matplotlib.pyplot as plt
np.set_printoptions(linewidth = 200)
if len(sys.argv) < 4:
print(f"usage: {sys.argv[0]} [proj?] [lattice_shape] [alpha] [max_manifold] [shells/spins]")
exit()
# determine whether to use data from "projected" simul... |
"""trains model, saves checkpoint files and csv files of best metrics"""
from datetime import datetime
import os
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from load_dataset import AudioDataset, TRAIN_WEIGHTS
from make_p... |
import numpy as np
from numba import jit, prange
from dautil.util import abs2
from tail.numba_wrap import fftfreq
from tail.util import fill_nan
# nu ###########################################################################
@jit(nopython=True, nogil=True, parallel=True)
def compute_nu4(pixel_size, lmax, mask_i, m... |
# Copyright 2011 <NAME>
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is distributed in... |
import numpy as np
import nibabel as nib
import pandas as pd
import os
import glob
import tensorflow as tf
from neuron.layers import SpatialTransformer
import multi_affine.eval as ae
from multi_affine.utils import load_multi_atlas
from pandas import ExcelWriter
import SimpleITK as sitk
def eval_nonrigid(data_file, ev_... |
# -*- coding: utf-8 -*-
"""
This provides a JavaScript "toolchain".
When I have a hammer every problem starts to look like JavaScript.
Honestly, it's a bit easier to deal with JavaScript when one treats that
as a compilation target.
How this supposed to work?
1) Write raw JS code without any UMD wrappers, but treat... |
import json
import config
import logging
import telebot
import ccxt
import pandas as pd
import dataframe_image as dfi
from DBHandler import DBHandler
import numpy as np
API_KEY = config.TELEGRAM_TOKEN
bot = telebot.TeleBot(API_KEY)
@bot.message_handler(commands=['help', 'start'])
def help(message):
msg = '/greet\n'+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.