text stringlengths 3.07k 22.1k |
|---|
""" Deals with image acquiring and manipulation. """
import httplib
import logging
import os
import re
import socket
import ssl
import urllib2
import urlparse
import time
import cv2
import numpy as np
logger = logging.getLogger(__name__)
# The error_images directory should be included in the same location that t... |
import json
import os
import re
import subprocess
import time
from typing import Optional, List
from platypush.backend import Backend
from platypush.message.event.joystick import JoystickConnectedEvent, JoystickDisconnectedEvent, JoystickStateEvent, \
JoystickButtonPressedEvent, JoystickButtonReleasedEvent, Joysti... |
import numpy as np
import pandas as pd
import multiprocessing
import time
from sklearn.metrics import pairwise_distances
import scanpy as sc
from sklearn.metrics.pairwise import pairwise_kernels
import json
from random import sample
import random
from . import iONMF
import sys
import re
import umap
from datetime import... |
"""
Fits PSPL model for MB08310 with finite source effect using EMCEE sampler and
reports posterior flux parameters. The flux parameters are found by regression
for each model and cached using EMCEE blobs mechanism.
This example uses config file:
python example_10_fitting_and_fluxes.py example_10.cfg
Data from `Janc... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... |
import logging
import math
import numpy as np
#TODO: Remove this line
from PySide.QtGui import QGraphicsPolygonItem, QImage
from PySide.QtGui import QColor, QGraphicsPixmapItem, QPixmap
from PySide.QtCore import QPoint, QPointF, Qt
from traits.api import Bool, Enum, DelegatesTo, Dict, HasTraits, Instance, Int, List... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch.nn import functional as F
from torch import nn
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
f... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ i... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from PyQt5.QtCore import QThread
from PyQt5.QtCore import QUrl
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QActionEvent
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets ... |
"""
This plugin creates a CMakeLists file, that contains all testsetups of the
first (failed) test.
To avoid overwriting this File the "--keep-first-failed-pytest" command line
option can be set.
The content of this file is used by testlibs/debug_failed.py
to run only one test.
In contrary to the builtin cache plugin... |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
from .value import BitVectorValue, ListValue
from .pycde_types import BitVectorType, dim
from pycde.dialects import hw... |
# -*- coding: utf-8 -*-
"""
Python wrapper for LazyMole
<NAME>, University of Tübingen 2018 (<EMAIL>)
Uses LazyMole by <NAME>, University of Southern California (<EMAIL>)
"""
import os
from os.path import join
import numpy as np
import yaml
import subprocess
import errno
class model():
def __init_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Frogtoss Games, Inc.
#
"""Generate an .ico or .icns file from a directory of square pngs.
Pngs are downsized to fit (never scaled up), so the largest should be
1024x1024.
You can get away with one image or include more than one if you want
to han... |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... |
"""
character_map
This submodule contains a specification of character map data and useful text drawing functions
A character map is a mutable rectangular array of characters akin to a bitmap. Basically you have characters instead of pixels. Drawing fuhctions render
text and shapes onto character maps and can draw one ... |
import math as m
import datetime
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import planetary_data as pd
d2r = np.pi / 180.0
r2d = 180.0 / np.pi
def plot_n_orbits(rs, labels, cb=pd.earth, show_plot=False, save_plot=False, title='Many Orbits'):
# 3D plot
f... |
# -*- coding: utf-8 -*-
# ===========================================
# author: <NAME>
# email: <EMAIL>
# github: https://github.com/QDucasse
# ===========================================
# Simulator: Process instructions one by one and show the results of their execution
from sdvs.constants import *
impor... |
import torch
import pyredner
import math
import os
import sys
pyredner.render_pytorch.print_timing = False
def simplify(inputmesh, outputmesh, target):
simp_str = """<!DOCTYPE FilterScript>
<FilterScript>
<filter name="Quadric Edge Collapse Decimation">
<Param t... |
import tensorflow.compat.v1 as tf
import pdb
import collections
import random
import itertools
from tqdm import tqdm
import os
import glob
from optimizer import Optimizer, LineSF, CircleNF
from diagram import Diagram
from util import get_random_string
class TfPoint(collections.namedtuple("TfPoint", ["x", "y"])):
... |
"""
Code for Ordered-Neurons Sentence encoder
Modules re-used from: https://github.com/yikangshen/Ordered-Neurons
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as f
from ...utils.locked_dropout import LockedDropout
def embedded_dropout(embed, words, dropout=0.1, scale=None):
... |
# -*- coding: utf-8 -*-
"""Gtk.PrintOperation()."""
import gi
gi.require_version(namespace='Gtk', version='3.0')
gi.require_version(namespace='PangoCairo', version='1.0')
from gi.repository import Gio, Gtk, Pango, PangoCairo
text = """<span size="xx-large">Lorem</span>
Lorem <b>ipsum</b> <span foreground="red">dolo... |
import unittest
from richkit import analyse
from os import path
import requests
import tempfile
import logging
import os
logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
level=logging.DEBUG)
logger = logging.getLogger(__... |
from __future__ import absolute_import, division, print_function
import re
import warnings
from datetime import datetime
import linecache
import numpy as np
import pandas as pd
if not "time_of_reset" in pd.DataFrame._metadata:
pd.DataFrame._metadata.append("time_of_reset")
from .utilities import (
Path,
... |
import re
import argparse
import numpy as np
import torch
from pathlib import Path
import sys
sys.path.append('waveglow/')
from hparams import create_hparams
from model import Tacotron2
from layers import TacotronSTFT, STFT
from audio_processing import griffin_lim
from train import load_model
from text import text_t... |
#!/usr/bin/env python
# Exercise some of the functionality. Probably not a unit test per-se
from portfolio import *
from transactions import *
from tracker import *
from fetch import *
from datetime import datetime
def valueToPounds():
from decimal import Decimal
with open('prices/0263494.csv') as f:
n = 0
fir... |
from bs4 import BeautifulSoup
import re
from typing import List, Tuple, Union, Optional
from collections import defaultdict
from npmrd_curator.parsers.html_table_parser import utils
MULTI_REGEX = re.compile(
r"(?:(?:hept|sept|sex|qui|s\s?br|(?!\whown)(?=\s)?\bs|\bt+d*|\bd+t*d*|\btt*|\bt|\bd|qd?|\bh|br\s?s|br\s?d... |
import os
from flask import Flask, render_template, request, redirect, jsonify
from flask import url_for, flash, session, g
from sqlalchemy import create_engine, asc
from sqlalchemy.orm import sessionmaker
from database_setup import User, Strategy, Tactic, Base
from flask import session as login_session
import random
i... |
# Copyright (c) 2019, NVIDIA CORPORATION.
#
# 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... |
from math import ceil
import numba as nb
import numpy as np
from numba import cuda
from ._cell_list_cu import cu_cell_id
from ._cell_list_cu import cu_cell_list_argsort
from ._utils import add_local_arr_mois_1
from ._utils import cu_max_int
from ._utils import cu_set_to_int
from ._utils import pbc_dist_cu
from ._util... |
"""Management utilities."""
from fabric.contrib.console import confirm
from fabric.api import abort, env, local, settings, task, sudo, cd, lcd, put, run, prefix, get
from fabric.contrib.files import exists
from etapi.settings import ProdConfig
########## CONFIG
local_app_dir = '.'
local_config_dir = './config'
r... |
#!/usr/bin/env python
# ENCODE DCC bwa wrapper
# Author: <NAME> (<EMAIL>), <NAME>
import sys
import os
import re
import argparse
import multiprocessing
from encode_common_genomic import *
def parse_arguments():
parser = argparse.ArgumentParser(prog='ENCODE DCC bwa aligner.',
... |
import types
import logging
from .utils import slurp
logger = logging.getLogger(__file__)
def list_accepted_portfolio_shares_single_page(self, **kwargs):
"""
This will continue to call list_accepted_portfolio_shares until there are no more pages left to retrieve. It will return
the aggregated response... |
from collections import Counter
from mongo import *
from analysis import CorpusAnalysis
# Converted all API functions to class for faster processing. This way, the Analysis class doesn't need to load the models from disk on each api request.
# On systems with a lot of available memory both models can be kept in memory... |
import re
import six
import ast
import json
import global_params
from utils import run_command
from ast_helper import AstHelper
class Source:
def __init__(self, filename):
self.filename = filename
self.content = self._load_content()
self.line_break_positions = self._load_line_break_positi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gmprocess.waveform_processing.phase import (
PowerPicker, pphase_pick, pick_ar,
pick_kalkan, pick_power, pick_baer,
pick_yeck, pick_travel,
create_travel_time_dataframe
)
from gmprocess.io.read import read_data
from gmprocess.io.test_utils import read_... |
from distutils.version import LooseVersion
import django
from django.conf import settings
from django.db import DatabaseError, transaction
from django.db.models import query
from django.db.models.fields.related import ForeignKey
from django.db.models.query_utils import Q
from django.utils import timezone
from .config... |
import pandas as pd
from gurobipy import *
import gurobipy as grb
import matplotlib.pyplot as plt
import numpy as np
from Curve import *
from CurrModelPara import *
# class Folder_Info():
# def __init__(self, Input_folder_parent, Output_folder, curr_model):
# self.curr_model = curr_model
# self... |
"""Encrypting and decrypting files with AES.
Tries to be safe, portable and fast.
Safety: uses AES keyed by sha256 hash of the original password.
Portability: uses only pycrypto and base CPython
Speed: uses CBC mode, so whole blocks are encrypted with pycrypto.
Because of the CBC mode, files are amended with random ... |
"""
Here a list for testing neo.rawio API compliance.
This is called automatically by `BaseTestRawIO`
All rules are listed as function so it should be easier to:
* identify the rawio API
* debug
* discuss rules
"""
import time
if not hasattr(time, 'perf_counter'):
time.perf_counter = time.time
import loggi... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import joblib as jl
from matplotlib.patches import ConnectionPatch
plt.style.use('figstyle.mplstyle')
def style_plot(fig, axes):
fig.subplots_adjust(hspace=0.1)
for i, ax in enumerate(axes):
ax.patch.set_alpha(0.0)
side = ... |
"""
Copyright (C) 2018 SunSpec Alliance
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, merg... |
#!/usr/bin/env python3
import argparse
from lib import *
market_mode = "bull"
leverage = "5:1"
refresh_time = 30
# 1d: 86400
# 1h: 3600
adj_wait_secs = 2 * 3600
buy_discount_rate = 0.99
sell_to_curr_gap = Decimal(1.5)
sell_to_buy_gap = Decimal(1)
curr_to_buy_gap = Decimal(1)
target_price_offset = 50
max_buy_price =... |
from telegram.ext.conversationhandler import ConversationHandler
from telegram.ext import CommandHandler, CallbackQueryHandler, MessageHandler, Filters, Dispatcher
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, ReplyKeyboardMarkup, ChatAction, Bot
from telegram.ext.dispatcher import run_asy... |
"""Image series header
"""
import copy
import logging
import pydicom.dataset
import pydicom.datadict
import imagedata.formats
import imagedata.formats.dicomlib.uid
logger = logging.getLogger(__name__)
header_tags = ['input_format',
'seriesNumber',
'seriesDescription', 'imageType', 'fra... |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
###
# Project : SubLime
# FileName : core.py
# -----------------------------------------------------------------------------
# Author : sham
# E-Mail : <EMAIL>
# -------------------------------------------------------------------------... |
#coding:utf-8
"""transform for classification
"""
import random
import numpy as np
import numbers
import collections
from . import functional as F
class Compose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Exa... |
import argparse
import inspect
import numpy as np
import theano
from matplotlib import pyplot as plt
from scipy.signal import convolve2d
from scipy.stats import multivariate_normal
from time import time
from theano import d3viz
from kusanagi.ghost import regression
from kusanagi import utils
np.set_printoptions(linew... |
# coding:utf-8
'''
answer to question
bot engine module
'''
import math
import nltk
import re, random
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet as wn
from nltk.stem.porter import PorterStemmer as PS
from nltk.corpus import wordnet as wn
import subprocess, sys, os
sys.path.append("./engine"... |
from collections import namedtuple
from typing import NamedTuple
from ztom import core
from ztom import errors
from ztom import TradeOrder
import copy
import uuid
import time
class ActionOrderSnapshot(NamedTuple):
symbol: str = ""
amount: float = 0.0
price: float = 0.0
side: str = ""
status: str =... |
import json
import pytest
from broker.config import config_from_env, env_mappings
@pytest.fixture()
def vcap_application():
data = {
"application_id": "my-app-id",
"application_name": "my-app-name",
"application_uris": ["my-app-uri"],
"application_version": "my-app-version",
... |
from pysolr import *
import socket
import logging
log = logging.getLogger('solr')
from contextlib import contextmanager
class SolrResultsPaginator(object):
"""Offers an iterator on Solr results. You simply provide a
configured pysolr `Solr` instance, a query, and the default parameters.
This class takes c... |
import time
import numpy as np
from scipy import sparse
import sys
from skimage import measure
from skimage import io
from threading import Thread
import traceback
def get_matrix_filename(algorithm, variant, size):
return "radon_server/static/npz/" + algorithm + "." + variant + "." + str(size) + ".npz"
class Ra... |
import inspect
import numpy as np
import pytest
from pytest import approx
from scipy.spatial import Delaunay, Voronoi
from landlab.graph.voronoi.voronoi_to_graph import (
VoronoiDelaunay,
VoronoiDelaunayToGraph,
)
XY_OF_NODE = {
"rect-horizontal-3-3": [
[0.0, 0.0],
[1.0, 0.0],
[2.... |
import datetime
import pickle
from random import shuffle, randint
import numpy as np
def floater(val):
try:
return float(val)
except:
return 0.0
def parameter_divider(params, para_name):
lower_params = []
for p in params:
lower_params.append(p.lower())
selected_parameter = []
for i in range(0,... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import gym
import matplotlib.pyplot as plt
import random
from collections import OrderedDict
from copy import copy
import argparse
import sys
import os
sys.path.append("../utility/")
from torch.utils.tensorboard import SummaryWriter
f... |
from bs4 import BeautifulSoup
import requests
import json
import re
from .base import ScribdBase
from .. import internals
from .. import const
from .. import exceptions
class Track:
"""
A class for an audio chapter in a Scribd audiobook playlist.
Parameters
----------
track: `dict`
A dic... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from anchor import MODALITY_TO_COLOR, MODALITY_TO_CMAP, NULL_MODEL, \
NEAR_ZERO, NEAR_ONE
def switchy_score(array):
"""Transform a 1D array of data scores to a vector of "switchy scores"
Calculates std deviation and mean of sine- a... |
import logging
import os.path
import random
import socket
import string
import time
import uuid
import docker
import pytest
from bitshares import BitShares
from bitshares.account import Account
from bitshares.asset import Asset
from bitshares.exceptions import AccountDoesNotExistsException, AssetDoesNotExistsException... |
from django.test import TestCase
from django.contrib.auth.models import User
from eatit.api.serializers import AddressSerializer, ActiveOrdersSerializer, UserSerializer, RestaurantSerializer, FoodItemSerializer
from eatit.models import Cart, MobileNumber, Address, ActiveOrders
from restaurants.models import FoodItem, R... |
# __ __ _ __ __ _ __
# / / / /____(_) /_/ /_ _ __(_) /__
# / /_/ / ___/ / __/ __ \ | / / / //_/
# / __ / / / / /_/ / / / |/ / / ,<
# /_/ /_/_/ /_/\__/_/ /_/|___/_/_/|_|
# ______ __ __ _
# /_ __... |
# Author: <NAME> <<EMAIL>>
from time import time
import os, sys
import pandas as pd
import gensim
import pickle
import random
import pyLDAvis
import pyLDAvis.gensim
# These are the import statements for the custom modules. If you want to run this file seperately, switch imports.
from . import data_nl_processing
from ... |
"""DS3221 Precision RTC I2C Driver for Raspberry PI & MicroPython
https://datasheets.maximintegrated.com/en/ds/DS3231.pdf
https://www.adafruit.com/product/3013
"""
from meerkat.base import I2C, time
from meerkat.data import Meta, CSVWriter, JSONWriter
def bcd2dec(bcd):
"""Binary Coded Decimal to Decimal conversi... |
import types
def deprecated(cls): return cls
class ContextManager(object):
def __init__(self, methods):
assert isinstance(methods, (str, unicode))
assert " " in methods
self.om, self.cm = methods.split(" ")
def __call__(self, cls):
setattr(cls, "__enter__", lambda obj: getattr(cls, self.om... |
'''
This file is for Genetic Algorithm modules it has
all functions needed for the Algorithm.
The list of functions:
1. initial population
2. cross over 'main function'
3. survive population
4. chromosome selection
5. chromosome mutation
6. intial chromosome
7. sort population
8. no depl... |
import ast
import inspect
import types
from typing import List, Union, Callable
from earthdragon.typecheck import typecheck
from .common import get_source, quick_parse
from .repr import ast_source
def klass_grabber(ns, func_name):
return getattr(ns['klass'], func_name)
def getitem_grabber(ns, func_name):
... |
import xlrd
# from paddlenlp.embeddings import TokenEmbedding
import paddlehub as hub
import numpy as np
concernKey1 = ['n', 'nr', 'nz', 'PER', 'ns', 'LOC', 's', 'nt', 'ORG', 'nw']
concernKey2 = ['v']
lac = hub.Module(name="lac")
# test_text = "还记得你之前跟我说,我能及格猪都能上树。可教练我拿到驾照了,猪不仅能上树还能上高速,我再给你来个倒车入库,压线了难受不?以前... |
import sys
import os.path
sys.path.insert(1,
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from geopy.distance import geodesic
import os
import pandas as pd
from utils.io import write_json, read_json
from graph.populate_graph import load_member_summaries
def clean_up_json(d):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn import Sequential
import torch_geometric
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree, scatter_
import torch_geometric.transforms as T
import torch_clust... |
import copy
import numpy as np
from autoarray.structures import arrays
from autoarray.structures import grids
from autoarray.structures import kernel
from autoarray.dataset import imaging
from autogalaxy.plane import plane as pl
class SettingsMaskedImaging(imaging.SettingsMaskedImaging):
def __init__(... |
import os
from sklearn.metrics.pairwise import euclidean_distances
import numpy as np
from random import sample
def gen_centroids(data, k):
"""
Choose random k samples as initial centroids
:param data: data samples
:type data: numpy matrix, shape(n_samples, n_features)
:param k: number of cluster... |
"""Parsing plugin implementation for SPHEREx LaTeX documents."""
from __future__ import annotations
import datetime
from collections import UserDict
from logging import getLogger
from typing import Any, Dict, List, Optional
import dateutil.parser
from lander.ext.parser import CiPlatform, Contributor, Parser
from lan... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
TheLMA response renderers.
"""
import os
from pyramid.compat import bytes_
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.interfaces import ... |
import os.path as osp
from tqdm import tqdm
from copy import deepcopy
import torch
import dgl
from torch.utils.data import DataLoader, Dataset
from dgl import DGLGraph, NID
from dgl.dataloading.negative_sampler import Uniform
from dgl import add_self_loop
from utils import drnl_node_labeling
class GraphDataSet(Datase... |
#!python
# pyright: reportUnknownVariableType=false, reportUnknownMemberType=false
from dataclasses import dataclass
import cv2
import random
import os
from PIL import Image as pilImage
import piexif
from pathlib import Path
from typing import Any, Callable
from src import model
from src import data_serialization_json... |
# test fbchat api
import sys
from unittest.mock import patch
from pathlib import Path
import pytest
from postr import fbchat_api
from postr import config
sys.path.insert(0, '../postr')
my_file = Path('../postr_config.ini')
if not my_file.is_file():
pytest.skip('If there is no config_file, then all these tests wi... |
import pandas as pd
import numpy as np
import geopandas as gpd
# class Correction():
# def __init__(self):
# print("Initializing class 'Correction'")
def flag_faulty_percentages(df, setValueToNan=True, dropColumns=True, dropFlag=False):
'''
Aim:
Inspect if there are faulty per... |
import cv2
import numpy as np
import os
import tensorflow as tf
import sys
import skimage
import json
import datetime
import time
import time
import argparse
def reframe_box_masks_to_image_masks(box_masks, boxes, image_height,
image_width):
"""Transforms the box masks back to full... |
from . import models
from collections import Counter
from collections import defaultdict
from django.db.models import Count, Avg
import numpy as np
import plotly.graph_objs as go
import plotly.subplots as subplots
import plotly.offline as opy
from scripts.linear_map import linear_map
def _iplot(*args, **kwargs):
re... |
# ===============================================================================
# Copyright 2013 <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/... |
# pylint: disable=E0611,E0401
from typing import (
Any,
Dict,
Generator,
List,
NamedTuple,
Optional,
Tuple,
Union,
cast,
)
from distutils.version import StrictVersion
__all__ = ['bump_version']
_BUMP_VERSION_MAJOR: int = 0
_BUMP_VERSION_MINOR: int = 1
_BUMP_VERSION_PATCH: int = ... |
import os
from collections import defaultdict
from datetime import datetime
import random
import requests
import json
import logging, logging.config
import signal
from multiprocessing.dummy import Pool as ThreadPool
from bs4 import BeautifulSoup
from Levenshtein import ratio
from constants import PLS_HEADERS, USER_AGE... |
"""
learning threading and subprocess
on a windows machine
python 3 implementation
vatsamail @ github
<EMAIL>
"""
import subprocess
proc = subprocess.Popen(
['dir', '..\\'],
stdout=subprocess.PIPE
)
out, err = proc.communicate()
print(out.decode('utf-8'))
################
import time
proc = subpro... |
desc = """Animations of black hole spin evolution for precessing binary black holes.
Example usage:
python precession_tracking_updown.py -r pn_instability/Case_002
Where Case_002 contains Horizons.h5.
"""
import numpy as np
import matplotlib.pyplot as P
import argparse
import h5py
from scipy.interpolate import Uni... |
# Copyright 2021 Ocean (<EMAIL>)
# All rights reserved.
import sys
import string
import os
# skip all whitespace character
def skipwhite(line, pos):
while(pos < len(line)):
if line[pos] in string.whitespace:
pos += 1
else:
break
return pos
# scan unti... |
# -*- coding: utf-8 -*-
"""
Lightweight Functional interface to wrap access to Deep Learning, RLearning models.
Logic follows Scikit Learn API and simple for easy extentions logic.
Goal to facilitate Jupyter to Prod. models.
Models are stored in model_XX/ or in folder XXXXX
module : folder/mymodel.py, contains ... |
#!/usr/bin/env python
"""This is a suite of CLI tests that should pass before releasing a new version of terra-notebook-utils.
The following steps are performed:
1. A python virtual environment is created in a temporary location
2. terra-notebook-utils is installed into the virtual environment using the local r... |
# -*- coding: utf-8 -*-
__all__ = ['match', 'method', 'static_files', 'prefix',
'subdomain', 'namespace', 'by_method']
import six
import logging
import os
from os import path
from six.moves.urllib.parse import unquote
from webob.exc import HTTPMethodNotAllowed, HTTPNotFound
from webob.static import FileAp... |
from __future__ import annotations
import hashlib
import logging
import os
import re
import socket
import threading
import typing
from asyncio import Event
from asyncio import PriorityQueue
from asyncio import create_task
from asyncio import get_event_loop
from asyncio import iscoroutinefunction
from functools import ... |
from enum import Enum
from typing import Dict
from uuid import uuid4
import numpy as np
import plotly.graph_objects as pgo
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from .exceptions import InvalidTrendLine
from .properties import PlotProperties, PlotSeriesKind... |
import torch
from torch import nn
def conv3x3(in_channels, out_channels, stride=1, groups=1, dilation=1):
"""3x3 conv with padding"""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=dilation, groups=groups,
bias=False, dilation=dilation)
def conv1x1(in... |
"""
Load ADV measurements and calculate TKE with plot options
Originally coded in Matlab at Nepf Lab (MIT)
Re-written in Python by <NAME> (2022)
"""
# import standard Python libraries
import sys
import os
# import particular Python libraries
try:
import pandas as _pd
import numpy as _np
except Imp... |
from __future__ import division
import numpy as np
import six
from chainer import function
from chainer.utils import type_check
def _roi_pooling_slice(size, stride, max_size, roi_offset):
start = int(np.floor(size * stride))
end = int(np.ceil((size + 1) * stride))
start = min(max(start + roi_offset, 0)... |
#!/usr/bin/env python
from __future__ import division, absolute_import, print_function
import skopt
import argparse
import matplotlib.pyplot as plt
import matplotlib.font_manager
import numpy as np
from rospkg.rospack import RosPack
from skopt.acquisition import gaussian_ei
# from skopt.plots import plot_convergence
m... |
#!/bin/python
# path to python
# where is your writable directory? Jobs will be managed in a .queue directory here.
SCRATCH="FULL_PATH_TO_YOUR_SCRATCH_SPACE"
# username
USER="YOUR_USERNAME_HERE"
# how big is one batch of jobs? ex 10 means there must be 10 free slots to run another batch.
JOB_ARRAY_MAX=20
# max tota... |
"""
Parses raw log output from CWS to intermediate format
that is used by validating and visualising scripts.
Example of usage:
$ python -m log_parser.parse_experiment_log raw.log preprocessed.log
"""
import argparse
from itertools import groupby
from operator import attrgetter
import log_parser
from execution_log... |
"""
classifier.py
~~~~~~~
Functions for building a target classifier.
"""
import os
os.environ['PYTHONHASHSEED'] = '0'
from numpy.random import seed
import random
random.seed(1)
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
from keras import backend as K
import tensorflow as tf
import sys
impor... |
# Copyright (c) 2021. <NAME>. All Rights Reserved
import calendar
from datetime import datetime
from dash import Dash, dash_table, html
import dash_bootstrap_components as dbc
from hardio.dashapp import UserConfig
from iobrocker import IO
from logic import Activity, PresentationActivity
WEEK_DAYS = ['Mon', 'Tue', ... |
###############################################################################
# #
# This file is part of IfcOpenShell. #
# #
... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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... |
from oeda.databases import db
from math import isnan
from oeda.log import *
from oeda.utilities.MathUtility import take_inverse
class RTXDefinition:
name = None
_oeda_experiment = None
_oeda_target = None
_oeda_callback = None
_oeda_stop_request = None
primary_data_provider = None
secondar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.