text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
"""
BioVis report is a tool for generating an interactive report.
"""
from __future__ import unicode_literals, absolute_import
import argcomplete
import argparse
import os
import sys
import logging
import coloredlogs
import verboselogs
from biovis_rep... |
# Copyright 2017 <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 ... |
'''Functions to calculate Liu-Liang method PBL estimates.
Section numbers are from 'Planetary Boundary Layer (PBL) Height Value
Added Product (VAP): Radiosonde Retrievals' from the US Department of
Energy.'''
from .utils import subsample_5mb, estimate_potential_temperature, find_first
import numpy as np
# Constants... |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
import argcomplete, argparse
import collections
import sys
import time
import pyftdi.spi
SpiFlashModel = collections.namedtuple("SpiFlashModel", (
"name",
"size",
"sect"
))
def KB(n):
return n << 10
def MB(n):
return n << 20
class SpiFlash(object... |
""" Utilities related to FRB galaxies"""
import os
import glob
from IPython import embed
from pkg_resources import resource_filename
import numpy as np
from scipy.interpolate import interp1d
import pandas
try:
from specdb.specdb import SpecDB
except ImportError:
flg_specdb = False
else:
flg_specdb = True... |
#!/usr/bin/env python
'''This program just reads some meta-data from the label of
an ISIS cube file and presents the text in a way that might help
someone get started on writing a figure caption.'''
# Copyright 2019, <NAME> (<EMAIL>)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use... |
import os
from datetime import datetime
import reframe.utility.sanity as sn
from reframe.core.pipeline import RegressionTest
class HelloWorldBaseTest(RegressionTest):
def __init__(self, name, lang, linkage, **kwargs):
super().__init__('hello_world_%s_%s_%s' % (name, linkage, lang),
... |
from config.abstractconfig import DBGConfig, ResourceConfig, yl
from flask import Response
from flask_restful import Resource
from functools import wraps
import json
from sms import rand_code, send_code
from uuid import uuid4
from ..util import get_logger, get_rcon, hash_passwd, exc, mycursor
from flask import request
... |
import threading
import queue
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.ticker as tkr
import argparse
import serial
from time import sleep
import os
import matplotlib.text as txt
class SerialReader(threading.Thread):
"""Serial Reader class that provides an interfac... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import numpy as np
from os.path import join, dirname
from sklearn.datasets.base import Bunch
from sklearn.preprocessing import LabelEncoder
from ..utils.validation import to_sparse_csr
__all__ = [
'load_lastfm'
]
class __BunchCache(dict):
"""... |
# coding: utf-8
"""
Simple law tasks that demonstrate how to build up a task tree with some outputs and dependencies.
The first task (FetchLoremIpsum) will download 1 of 6 different versions of a "lorem ipsum" text.
The next task (CountChars) determines and saves the frequency of every character in a json file.
After... |
# This file is an example on how to use the BEL1D codes using a simple 2-layer SNMR experiment (with noise)
from pyBEL1D import BEL1D
import cProfile # For debugging and timings measurements
import time # For simple timing measurements
import numpy as np # For the initialization of the parameters
from matplotlib import... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import json
import os
import pickle
import gym
from gym.envs.registration import register
from gym.spaces import Tuple
import ray
from ray.rllib.agents.registry import get_age... |
# 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... |
#!/usr/bin/env python
"""
"""
import os
import sys
import argparse
import numpy as np
from common_wrangler.common import (InvalidDataError, warning,
GOOD_RET, INPUT_ERROR, IO_ERROR, INVALID_DATA,
EHPART_TO_KCAL_MOL, DEF_FIG_HEIGHT, DEF_FIG_WIDTH,... |
import os
import itertools
import importlib
import numpy as np
import random
from darwinStrategy import *
import generation
STRATEGY_FOLDER = "exampleStrats"
RESULTS_FILE = "results.txt"
pointsArray = [[1,5],[0,3]] # The i-j-th element of this array is how many points you receive if you do play i, and your opponent d... |
from __future__ import annotations
import datetime
import logging
import os
from typing import (TYPE_CHECKING, Any, Dict, Generator,
List, Literal, Tuple, Type)
import minio
from .minio_creds import MinioPath, PullInformations
from .template_engine import NEVER_PULLED, TemplateEngine, template_en... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
import os
import matplotlib
font = {'size': 20}
matplotlib.rc('font', **font)
def radar_... |
import math
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
from PyQt5.QtWidgets import QWidget
from gym_electric_motor.visualization import MotorDashboard
import pytest
u_sup = 450.0
series_motor_parameter = {'motor_parameter': {'r_a': 3.78, 'r_e': 35, 'l_a': 6.3e-3, 'l_e': 160e-3, 'l_e_prim... |
import nltk
import string
from nltk import ngrams
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.corpus import gutenberg
from collections import Counter
#To compare other shakespeare's text, just change the file name.
file = open("Shakespea... |
"""
Copyright 2012 <NAME> (<EMAIL>)
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, softw... |
#!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
import optparse
import os
import shutil
import sys
import zipfile
from util import build_utils
def _Che... |
# MIT License
#
# Copyright (c) 2017
#
# 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, di... |
import importlib
from hydroDL.master import basins
from hydroDL.app import waterQuality
from hydroDL import kPath
from hydroDL.model import trainTS
from hydroDL.data import gageII, usgs
from hydroDL.post import axplot, figplot
import torch
import os
import json
import numpy as np
import pandas as pd
import matplotlib.... |
"""
Functions to verify the results of preprocessing (i.e. peak detection/splitting)
"""
import matplotlib.pyplot as plt
import numpy as np
import os
from src.utils import plotting_utils, dsp_utils, h5_interface
'''
Inputs : Index of the data to plot
Outputs : Histogram plot of heartbeat lengths
'''
def verify_de... |
import enum
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, Path, Query
from fastapi.encoders import jsonable_encoder
from fastapi.logger import logger
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
from app.api.errors.errors import (
... |
"""."""
import time as _time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as mpl_gs
from matplotlib.patches import Ellipse
import pyaccel
from siriuspy.devices import Screen
from apsuite.utils import MeasBaseClass as _BaseClass, \
ParamsBaseClass as _ParamsBaseClass
from pymodel... |
# Copyright (c) 2016-2019, <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the foll... |
# Seven-segment display
# https://github.com/mjspeck/advent-of-code-21/blob/main/day_08.py
import sys
from copy import copy
from collections import defaultdict, namedtuple
from typing import Dict, List, Set, Tuple
FILE = sys.argv[1]
LETTERS = "abcdefg"
DIGITS = {
"abcefg": "0",
"cf": "1",
"acdeg": "2",
... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import glob
def roi_sign(sign):
'''
The image must be thresholded
'''
w = sign.shape[1]
h = sign.shape[0]
upper_boundary = dict()
lower_boundary = dict()
for x in range(w):
# go down
for y in range(h):
if sign[y,x] <=0:
upper_bounda... |
import base64
import json
import struct
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes
)
from cryptography.hazmat.primi... |
# Simple Voxel Tracer
import math
import time
import taichi as ti
import numpy as np
ti.init(arch=ti.gpu)
res = 1280, 720
fov = 30 # unit: degree
inf = 1e10
max_ray_depth = 6
# 3D Vector field: [i, j][0|1|2]
color_buffer = ti.Vector.field(3, dtype=float, shape=res)
camera_pos = ti.Vector([0.0, 0.2, 10.0])
object_list... |
from .coroutine import coroutine
import inspect
class stream(object):
"""Base class for *pull* and *push* coroutines."""
def __rshift__(self, other):
return self.__join__(other)
class pull(stream):
"""A |pull| coroutine pulls from a source, yielding values.
|pull| Objects can be chained usin... |
'''
This module provides support for defining properties on your entities. It both
provides, the `Property` class which acts as a building block for common
properties such as fields and relationships (for those, please consult the
corresponding modules), but also provides some more specialized properties,
such as `Colu... |
import io
import struct
class BinaryReader:
def __init__(self, raw):
self.raw = raw
self.endianness = "<" # Little-endian
def __enter__(self):
self.reader = io.BufferedReader(self.raw)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.reader.close()... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 15 15:26:26 2021
@author: Shady
"""
#%% Import libraries
import numpy as np
from numpy import pi, sin, cos, exp
import matplotlib.pyplot as plt
import time
import os
#%%
def u(x,ipr):
if ipr == 1:
y = sin(10*pi*x)/(2*x) + (x-1)**4
... |
from past.builtins import basestring
from pyramid.settings import asbool
from pyramid.traversal import (
find_resource,
)
from pyramid.view import view_config
from uuid import (
UUID,
uuid4,
)
from .etag import if_match_tid
from .interfaces import (
COLLECTIONS,
CONNECTION,
Created,
BeforeMo... |
import os.path
import inspect
class Manager(object):
"""
Manage a text data file, with fixed lenght registers.
"""
def __init__(self, filename, structure, in_memory=False, debug=False):
"""
Initialize internal elements.
The structucture parameter is a tuple of fieldnames and le... |
# This module provides some utilties involving random generation. The
# provided functions in this module are:
#
# random_ranage -- Generates a random sample from a range-like object.
# cdf -- Generates a random cumulative distribution function
# (designed to be used as a random variab... |
import argparse
import logging
import glfw
import imgui
from imgui import extra
from imgui_datascience import imgui_fig
from pygl.context import WindowContext
from pygl.buffers import *
import pygl.shader as ShaderManager
from pygl.camera import Camera
from pygl.mesh import Mesh
from pygl import transform
from matp... |
# pylint: disable=arguments-differ
import sys
import traceback
import itertools
import base64
import logging
from collections import namedtuple
if 'exceptions' not in globals():
from . import exceptions
from . import compatibility
__copyright__ = 'Copyright (C) 2019, Nokia'
CHILD_MODULES = [exceptions, compa... |
import cv2 as cv
from visionhsv import Vision
from gamecapture import GameCapture
from time import time
import cons.cst
import gui.qtmap
import gui.qtgui
import threading
# Debugging parameters
detectionscreen = False # Display detection screen
processedscreen = None # Display processed image
hsv_sliders = False # ... |
#!/usr/bin/env python
import collections
from PyQt4 import QtCore, QtGui
class Notification(QtGui.QWidget):
aboutToClose = QtCore.pyqtSignal()
contentChanged = QtCore.pyqtSignal()
def __init__(self, text, parent, timeout=None, icon=None, links=None,
recyclable=None):
super(Notification, ... |
# mailstat.utils.testgen
# Generates Test Data from a Fixture for MailStat
#
# Author: <NAME> <<EMAIL>>
# Created: Sun Dec 29 17:28:46 2013 -0600
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: testgen.py [] <EMAIL> $
"""
Generates Test Data from a Fixture for MailStat
If you... |
import logging, os
from typing import Tuple, Optional
import pandas as pd
import dask
import dask.dataframe as dd
from dask.distributed import Client
from dask.distributed import LocalCluster
from .report_generator import combine_data_and_create_report
def read_bcl2fastq_stats_data_using_dask(x: dict) -> Tuple[list, ... |
import numpy as np
from one_step_kmeans_method import *
def get_val(x,y,z,t,r):
'''
A function to get the objective value.
:param x: The centroids. [n,m] array
:param y: The grids. [t,m] array
:param z: The samples. ... |
from __future__ import print_function
import uuid
import os
from google.cloud import bigquery
from multiprocessing import Process
import uuid
import logging
import redis
import json
import time
import stylelens_index
from bluelens_spawning_pool import spawning_pool
try:
from StringIO import StringIO
except Impor... |
"""The implementation of U-Net and FCRN-A models."""
from typing import Tuple
import numpy as np
import torch
from torch import nn
def conv_block(channels: Tuple[int, int],
size: Tuple[int, int],
stride: Tuple[int, int]=(1, 1),
N: int=1):
"""
Create a block with N... |
# -*- coding: utf-8 -*-
import logging
from typing import Dict, Text, Any, List, Union
from rasa_sdk import Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction
from rasa_sdk.events import SlotSet
import re
from actions.actions_base import ask_if_success
from actions.const... |
import sys
import numpy as np
import scipy.special as sc
from algorithms.anchor_detector import AnchorDetector
from algorithms.id_matcher import IDMatcher
from feedback.neural_solver import NeuralSolver
from algorithms.aaa_util import (
convert_df,
weighted_random_choice,
eval_results,
frame_loss,
)
... |
import netket as nk
import networkx as nx
import numpy as np
import pytest
from pytest import approx
samplers = {}
# TESTS FOR SPIN HILBERT
# Constructing a 1d lattice
g = nk.graph.Hypercube(length=6, n_dim=1)
# Hilbert space of spins from given graph
hi = nk.hilbert.Spin(s=0.5, graph=g)
ma = nk.machine.RbmSpin(hilb... |
puzzles = [
"rbrr rgb rb r brgrbrgb grrgbbg grg bgrg bbgrbg",
"rbr bbggrgrggb bggbb b b bbrbbgg gbrrbgrbbb g",
"rrbrb rg g bgrbgggr ggrgr gr rg brr b bggrbgbb",
]
PUZZLE = 0
def choose_empty(b, g, r):
if g != 0 or b != 0:
if b < g:
return 'g'
else:
re... |
# -*- coding: utf-8 -*-
"""Supports ACE Solar Isotope Spectrometer data
Properties
----------
platform
'ace' Advanced Composition Explorer
name
'sis' Solar Isotope Spectrometer
tag
- 'realtime' Real-time data from the Space Weather Prediction Center (SWPC)
- 'historic' Historic data from the SWPC
inst_... |
import os
from math import radians
import numpy as np
from sklearn.metrics import pairwise_distances
import trackintel as ti
from trackintel.geogr.distances import meters_to_decimal_degrees, calculate_distance_matrix
class TestCalculate_distance_matrix:
def test_shape_for_different_array_length(self):
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import random
import torch
import torchvision
from torchvision.transforms import functional as F
import torchvision.transforms.functional as tf
import numpy as np
from PIL import Image
class Compose(object):
def __init__(self, transforms):
... |
''' This script contains some examples of how to use the
various automata classes and image renderers in the vivludo package.
It contains several functions, each of which is a standalone
example of how to create and render images or animations of a particular
cellular automaton. The "Wirewold" example in particular i... |
# Copyright 2019 The Google Research Authors.
# Original repo:
# https://github.com/google-research/google-research/blob/master/frechet_video_distance/frechet_video_distance.py
"""Minimal Reference implementation for the Frechet Video Distance (FVD).
FVD is a metric for the quality of video generation models. It is ins... |
import tensorflow as tf
import os
from datasets.loader import Loader
import models.vgg16
import numpy as np
from tensorflow.contrib.slim.nets import vgg
slim = tf.contrib.slim
tf.logging.set_verbosity(tf.logging.INFO)
def optimizer(loss):
"""Add training operation, global_step and learning rate variable to Graph... |
'''
Contains the code for training the vocoder
This code is based off of the train_postnet.py in Transformer-TTS repo.
'''
from utils import *
from preprocess import get_post_dataset, collate_fn_postnet
from network import Vocoder
from train import get_linear_schedule_with_warmup, get_transformer_paper_schedule
import... |
import pandas as pd
from sankeyview.sankey_definition import SankeyDefinition, Ordering, ProcessGroup, Waypoint, Bundle
from sankeyview.sankey_view import sankey_view
from sankeyview.partition import Partition
from sankeyview.dataset import Dataset
def test_sankey_view_accepts_dataframe_as_dataset():
nodes = {
... |
import os
import numpy as np
import matplotlib.pyplot as plt
from skimage.exposure import equalize_adapthist
from PIL import Image
from util import load_filters, get_boxes, draw_boxes, binary_dilation, gray2rgb
from strategies import correlate_strategy, threshold_strategy
# RGB thresholds
# red light
# r_b = 180
#... |
#!/usr/bin/env python
from __future__ import print_function
try:
from setuptools import setup, Command, Extension
except ImportError:
from distutils.core import setup, Command, Extension
import os
import subprocess
from os.path import join, exists
# If you are creating a sdist from the full bllipparser code ... |
# -*- coding: utf-8 -*-
# file: train.py
# brief: YOLOv3 implementation based on PyTorch
# author: <NAME>
# date: 2019/7/18
import os
import torch
import utils
import yolov3
import darknet
import argparse
import numpy as np
import dataset as ds
import torch.utils.data
from progressbar import *
import m... |
'''
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
simple test for apds9960 sensor in combination with ssd1306 oled.
requires:
adafruit-circuitpython-apds9960
adafruit-circuitpython-ssd1306
"""
import time
import datetime
import board
import busio
import digitalio
import adafruit_apds9960.apds9960
impo... |
# x=b'\x08\x32'
# k = uio.BytesIO(x)
# d=protobuf.decode("m2s_SOR", k)
# encode data
# msg_fields = [{"entity_id":21, "data": 20.70, "unit_id": 2}, {"entity_id":2, "data": 20.70, "unit_id": 1}]
# stream = uio.BytesIO()
# msg = "s2m_data"
# encoded_msg = protobuf.encode(msg_fields, msg, stream).getvalue()
# print(enc... |
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import final, Literal, Optional
from explainaboard.constants import FileType, Source
from explainaboard.loaders.file_loader import (
DatalabLoaderOption,
FileLoader,
FileLoaderField,
JSONFileLoader,
TextFi... |
from collections import defaultdict
from datetime import timedelta
from datetime import datetime
import re
from .parse_date import parse_date
TIME_FORMAT = '%M'
DATETIME_FORMAT = '%Y-%m-%d %H:%M'
COMMENT_PREFIX = '# '
DESCRIPTION_SEPARATOR = '/'
WHITESPACED_DESCRIPTION_SEPARATOR = ' ' + DESCRIPTION_SEPARATOR + ' '
RE... |
#!/usr/bin/env pytest-3
"""
Introducing Essential Functional Concepts
We'll look at each of the following functional programming topics:
- First-class and higher-order functions, which are sometimes known as pure functions.
- Immutable data.
- Strict and non-strict evaluation. We can also call this eager versus lazy e... |
#!/usr/bin/env python3
import cv2
import numpy as np
import random
from scipy.interpolate import RectBivariateSpline
# Constants
INPUT_IMG_DIR = "./project_images/"
SIFT_OUT_IMG = "2.png"
RANSAC_OUT_IMG = "3.png"
STITCH_OUT_IMG = "4.png"
STITCH_OUT_ALL_IMG = "Output_AllStitched.png"
RATIO_TEST_THRESOLD = 0.77
def tr... |
import codematcher as cm
import re
import operator
import time
def api_check(parsed):
parsed = parsed.split(',')
n_prop = 0
n_all = 0
for api in parsed:
if '.' in api:
n_all += 1
api = api[:api.find('.')].strip()
if api in ['com', 'org', 'sun', 'jdk', 'java'... |
# -*- coding: utf-8 -*-
"""
Implements Issue Class resources
"""
from flask import request
from quantifiedcode.settings import backend
from quantifiedcode.backend.models import IssueCategory, Tag, Project, IssueClass, ProjectIssueClass
from .forms.issue_class import IssueClassForm
from ...utils.api import A... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from https://github.com/nkchenz/lhammer/blob/master/lhammer/xml2dict.py
Distributed under GPL2 Licence
CopyRight (C) 2009 <NAME>
Adapted for Prestapyt by <NAME>
Copyright 2012 Camptocamp SA
"""
import re
try:
import xml.etree.cElementTree as ET
exc... |
"""
A module implementing the block MC method from Zha (1999).
"""
from jax import random
import jax.numpy as np
def gen_samples_A_L(keys_A_ii_0, keys_C_i, samples_nb, T, S_C_hat, C_hat,
X_T_X_inv):
"""
Generate MC samples for the matrix form of
:math:`A\left(L\right)y\left(t\right)`... |
#roslaunch transparent_mission hiwin_robot_control.launch
import rospy
import sys
import time
import threading
import argparse
import numpy as np
import math
import enum
import time
from std_msgs.msg import Int32MultiArray
import os
from pushpin_mission.msg import ROI
from std_msgs.msg import String
from control_node ... |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. 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
#
# ... |
'''
.. versionadded:: 0.4.0
'''
from __future__ import absolute_import
import logging
import networkx as nx
import numpy as np
import pandas as pd
import six
from .load import draw
from .lib.tsp_local.base import TSP
from .lib.tsp_local.kopt import KOpt
from six.moves import range
logger = logging.getLogger(__name_... |
# -*- coding: utf-8 -*-
"""This module has maya animation utils
MIT License
Copyright (c) 2020 <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 limit... |
from scipy.io import netcdf_file
import numpy as np
from datetime import datetime
from scipy.interpolate import griddata
def grepValuesByMask(xi, data, mask):
"""
this grabs the values from data from entries with positive mask and interpolates it to numpy meshgrid xi
"""
X=data... |
import base64
import json
import os
import webbrowser
from datetime import datetime, timezone
from typing import Optional
from PyQt5 import QtWidgets
import yadisk
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import ha... |
# flake8: noqa: F405
import pytest
from rich.console import Console
from rich.table import Table
from pyinaturalist.formatters import *
from test.sample_data import *
# Lists of JSON records that can be formatted into tables
TABULAR_RESPONSES = [
j_comments,
[j_controlled_term_1, j_controlled_term_2],
[j... |
"""
Classification in noise or not noise the data from movies with
information about localization
"""
#Based on example:
#http://scikit-learn.org/stable/auto_examples/text/document_classification_20newsgroups.html#example-text-document-classification-20newsgroups-py
from __future__ import print_function
import logg... |
from bitcoingraph.neo4j import Neo4jController
from bitcoingraph.helper import to_time, to_json
def round_value(bitcoin_value):
return round(bitcoin_value, 8)
class GraphController:
rows_per_page_default = 20
def __init__(self, host, port, user, password):
self.graph_db = Neo4jController(host... |
from functools import wraps
import json
from django.contrib.auth.models import (AnonymousUser,
User,
check_password)
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import render
fro... |
"""Test utils for multiprocess functionality UT."""
# pylint: disable=no-self-use,too-many-public-methods,invalid-name
from __future__ import absolute_import
import os
import time
from multiprocessing import Process
import psutil
from rotest.core.case import request
from rotest.management.models.ut_resources import De... |
import argparse
import os
import time
import json
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.nn.parallel import DistributedDataParallel
from torchvision import transforms
from utils imp... |
import unittest
import os
import orca
import pandas as pd
import matplotlib.pyplot as plt
import os.path as path
import base64
from io import BytesIO
from setup.settings import *
class Csv(object):
pdf_csv = None
odf_csv = None
class PLottingTest(unittest.TestCase):
@classmethod
def setUpClass(cls):... |
from bson import json_util
from faker import Faker
from providers.image_url import SafeImageUrl
import argparse
import bson
import os
import yaml
import pymongo
fake = Faker()
fake.add_provider(SafeImageUrl)
client = pymongo.MongoClient("localhost", 27017)
def flatten(d, sep='_', parent_key=''):
"""Flattens a ne... |
import json
import requests
import re
import datetime
from pymongo.errors import DuplicateKeyError, BulkWriteError
from pytz import timezone
from config import setup_logging, setup_db
logger = setup_logging()
pattern_suc = re.compile("(\d+) Supercharger", flags=re.DOTALL | re.IGNORECASE)
pattern_dc = re.compile("(\d... |
import torch
from torch.utils.data import Dataset, DataLoader
from torch.distributions.multivariate_normal import MultivariateNormal
import numpy as np
from tqdm import tqdm
class UniformSampler:
"""
UniformSampler allows to sample batches in random manner without splitting the original data.
"""
def ... |
import datetime,os
import argparse
import numpy as np
from bunch import Bunch
import mygis
import io_routines as io
version="1.1"
def set_bounds(info):
atm_file=info.atmdir+info.atmfile
erai_file=atm_file.replace("_Y_","2000").replace("_M_","01").replace("_D_","01").replace("_h_","00")
varlist=["g4_lat... |
import unittest
import os
import io
import tempfile
import pytest
from click.testing import CliRunner
from ms_deisotope.data_source.mzml import MzMLLoader
from ms_deisotope.output import ProcessedMzMLDeserializer
from ms_deisotope.data_source import _compression
from ms_deisotope.tools import indexing, conversion, de... |
import sys
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, str) and not isinstance(el, tuple) and not isinstance(el, dict):
result.extend(flatten(el))
else:
result.append(el)
return result
def cfn(problem, isMinimization, i... |
from datetime import datetime, tzinfo, timedelta
from pytz import utc as utc_tz
from tzlocal import get_localzone
# Constants for time parsing/formatting
# This is a stub
XSDT_FMT = "%Y-%m-%dT%H:%M:%S"
# This should never change
XSDT_TZ_OFFSET = 19
# The str value to use for default local timezone
# In localization o... |
import logging
import numpy as np
import pandas as pd
from carball.json_parser.game import Game as JsonParserGame
from carball.output_generation.data_frame_generation.prefixes import DF_GAME_PREFIX
from carball.output_generation.field_constants import get_boost_collect_is_big_boost
BOOST_PER_SECOND = 80 * 1 / .93 * ... |
"""Implementation of algorithms proposed by:
<NAME> and <NAME>, "Streaming Anomaly Detection Using Randomized Matrix Sketching," http://bit.ly/1FaDw6S.
"""
import numpy as np
import numpy.linalg as ln
from sklearn import preprocessing
from ..base import BaseDetector
class StreamAnomalyDetector(BaseDetector):
... |
import json
# import math
import click
from textwrap import indent
from more_itertools import chunked
from ..cli import cli
from ..utils import group_by_gene_codons
from ..utils.codonutils import translate_codon
from .trim_by_ref import find_trim_slice
def group_gene_range_tuples(gene_range_tuples):
tuples = []... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Reference: http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python
"""
from __future__ import division
import ast
import numpy as np
np.set_printoptions(precision=3, suppress=True)
import rospy
import roslib
roslib.load_manif... |
import pygame
from pygame import mixer
import random
import math
# initialize pygame module
pygame.init()
# create screen (height x width)
screen = pygame.display.set_mode((640, 480))
# Title and Icon of window
# "Icon made by Smashicons from www.flaticon.com"
pygame.display.set_caption("Space Invaders ... |
import inspect
import itertools
import multiprocessing
from logging import getLogger
from remake.remake_exceptions import MissingTaskRuleProperty, TaskRuleNameError
from remake.task import Task
from remake.remake_base import Remake
from remake.task_query_set import TaskQuerySet
from remake.util import format_path
log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.