text stringlengths 3.07k 12.6k |
|---|
from skimage.io import imread
from skimage.io import imsave
from skimage.external.tifffile import TiffFile
import numpy as np
from os.path import join
import os
import argparse
import cv2 as cv
from typing import List
import tifffile
import matplotlib.pyplot as plt
def laplacian_variance(img):
return np.var(cv.Laplac... |
# VMware vCloud Director Python SDK
# Copyright (c) 2018 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... |
'''
Schema of extracellular information.
'''
import re
import os
from datetime import datetime
import pathlib
import numpy as np
import scipy.io as sio
import datajoint as dj
import h5py as h5
import tqdm
from . import reference, utilities, acquisition, analysis
schema = dj.schema(dj.config['custom'].get('database.pr... |
''' Check the serialization utils for complex data structures
'''
import unittest
import time
import numpy as np
import zmq
from zmq.tests import BaseZMQTestCase
from online_monitor.utils import utils
def get_test_raw_data(N=20000):
raw_data = np.array(range(N), dtype=np.uint32)
data = []
data.append(ra... |
import pandas as pd
from utils import *
def get_interaction2timestamp_with_words(dataset_name):
if dataset_name not in AMAZON_DATASETS:
print("The dataset chosen doesn't use text reviews.")
exit(-1)
user2timestamp = {}
item_idxs = {}
word_idxs = {}
file = open(DATASET_DIR[dataset_n... |
from ..utils import convert_query_params
from ..query import PaginatedQuery
from cbapi.connection import BaseAPI
import logging
log = logging.getLogger(__name__)
class CbEnterpriseProtectionAPI(BaseAPI):
"""The main entry point into the Carbon Black Enterprise Protection API.
:param str profile: (optional)... |
import cv2
import numpy as np
def _display_rgb(screen: np.ndarray):
cv2.imshow("main", cv2.cvtColor(screen, cv2.COLOR_RGB2BGR))
cv2.waitKey(1)
def _get_color_bitmask(color: [], image: np.ndarray) -> np.ndarray:
return cv2.inRange(image, color, color)
def _flatten_output(array: [np.ndarray]) -> [np.nda... |
# Read a WAV file and try to figure out what note is playing
# TODO: Figure out a constant threshold and use that instead of just taking the single strongest
import audioop
import bisect
import wave
import heapq
import clize # ImportError? pip install clize
import numpy as np
import matplotlib.pyplot as plt
def ms_to_... |
'''
Created on 21.08.2017
@author: falensaa
'''
from collections import deque
class Stack(object):
def __init__(self, l):
self.__stack = l
def front(self):
return self.__stack[0]
def pop(self):
return self.__stack.pop()
def top(self):
return self.__s... |
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.13.0
import sys, random, time, os, json
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import QThread, pyqtSignal
max = 501
min = 1
py = 0
i = 20
dic = 0
def load_json_data()... |
import pytest
from itertools import islice
from core import (
fibonacci,
divisors,
sequence_condition,
prime_divisors,
least_common_multiple,
is_prime,
partitions, normalized_prime_factors_with_powers,
)
def test_fibonacci():
f_seq = [0, 1, 1, 2, 3, 5, 8, 13]
assert list(islice(fib... |
import math
from _erfa import *
from _erfa import __doc__
def ir():
'''Initialize an r-matrix to the identity matrix.'''
return [[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
def zp():
'''Zero a p-vector.'''
return [0., 0., 0.]
def zpv():
'''Zero a pv-vector.'''
return [[0... |
import pickle
import os, re, sys
import shutil
import nibabel as nib
from scipy.fftpack import fftn, ifftn
import numpy as np
try:
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib import animation
except:
print ('matplotlib not imported')
def progress_bar... |
from itertools import chain
from helpers import (
shell_quote,
import_module,
create_array,
wrap,
OPERATOR_MAP,
INVERSE_OPERATOR_MAP
)
from lexer import (
MACRO_BACKTICKS,
MACRO_IF_ELSE,
MACRO_LET,
MACRO_EXPORT,
MACRO_PIPE,
MACRO_COMMENT,
MACRO_RAW,
MACRO_FOR,
... |
import asyncio
import time
from decimal import Decimal
from typing import Dict, Optional, List
from web3.contract import Contract
from blockchain import utils
from blockchain.async_web3.client import AsyncClient
from blockchain.async_web3.contract import AsyncToken, async_get_abi, AsyncContract, AsyncLPContract
from ... |
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from scipy import stats
import csv
import pandas as pd
def about(request):
print('About')
return render(request, 'about.html')
def contact(request):
print('Contact')
return render(request, 'contact... |
# -*- coding: utf-8 -*-
from typing import Iterable, Collection, Dict
import logging
import os
import sys
import json
import time
import datetime
import pytz
import dateutil.parser
import boto3
import util
from hour_usage import HourUsage
from uno import Session, DailyUsageExtractor
_NAME = 'uno-usage-scraper'
_VERS... |
from __future__ import absolute_import
from typing import Union, List, Any, Tuple, Type
import numpy as np
import tensorflow as tf
from .factory import AbstractTensor, AbstractFactory
class OddImplicitFactory:
def __init__(self, native_type: Union[Type['tf.int32'], Type['tf.int64']]) -> None:
self.nati... |
from urllib.parse import urlencode
import pytest
from django.conf import settings
from django.http import HttpResponse
from django.test.client import Client
from django.urls import reverse
from django.utils.crypto import get_random_string
from django.utils.translation import gettext_lazy as _
from httpretty import htt... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#!/usr/bin/env python3
import argparse
import subprocess
import defines
import helpers
import sys
import shutil
import time
import re
import os
OUT_FILE_PATH = defines.TMP_DIR + "/circuit.out"
VCD_FILE_PATH = defines.TMP_DIR + "/circuit.vcd"
VERILATOR = "verilator"
GCC = "gcc"
CLANG = "clang"
GCC_XX = "g++"
CLANG_... |
class Node():
def __init__(self, data):
self.data = data
self.right = None
self.left = None
self.height = 1
class BinaryTree:
def __init__(self):
self.root = None
self.diff = 0
def insert(self, data, root):
if data > root.data:
... |
# @title Define Loss function
from itertools import permutations
import torch
import torch.nn as nn
EPS = 1e-32
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class _Loss(nn.Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(_Loss, self).__init... |
# Copyright (c) 2020, <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
import udees.datasets.mitdb as mitdb
from udees.datasets.mitdb import Record
from udees.datasets.mitdb import interleave_record
import unittest
from unittest.mock import Mock
from unittest.mock import patch
@patch("udees.datasets.mitdb.np")
@patch("udees.datasets.mitdb.pd")
@patch("udees.datasets.mitdb.Path")
@patch(... |
import gym
import torch
import pprint
import argparse
import datetime
import numpy as np
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from tianshou.policy import PPOPolicy
from tianshou.env import SubprocVectorEnv
from tianshou.data import Collector, ReplayBuffer
if __name__ == '_... |
from comet_ml import Experiment
import warnings
warnings.simplefilter(action="ignore")
import os
import gc
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import torchnet as tnt
import logging
from data_loader.loader import *
from model.project_to_2d import *
from learning.loss_... |
import numpy as np
import pandas as pd
import pickle
from pathlib import Path
import sys
import statsmodels.api as sm
from bokeh.layouts import row
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.io import export_png
from aux_functions import cap_outliers
#################... |
#
# Copyright (c) 2015 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
"""The WRS PCI Device Extension."""
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.conf import CONF
from nova import objects
from nova.pci import devspec
from nova.pci import whitelist
fr... |
import gym
import torch
import torch.multiprocessing as mp
import torch.nn.functional as F
import numpy as np
import math
import time
from rlib.A2C.ActorCritic import ActorCritic
from rlib.networks.networks import NatureCNN
from rlib.utils.wrappers import AtariEnv
from rlib.utils.utils import stack_many, tonumpy, toto... |
"""Data access initialization and management."""
import logging
from datetime import datetime, timezone
from pathlib import Path
from tempfile import mkdtemp
import sqlalchemy
from anyio import Path as AsyncPath
from fastapi import Depends
from typing_extensions import Final
from robot_server.app_state import AppStat... |
import os.path
### def output_pathname(
### job_script_pathname):
###
### return "{}.out".format(job_script_pathname)
### # template = "{}-{{}}.out".format(job_script_pathname)
###
### # i = 0
### # result = template.format(i)
###
### # while os.path.exists(result):
### # i += ... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import ve... |
from models.archs.NonLocal_arch import NonLocalBlock
import torch.nn as nn
import math
def default_conv(in_channels, out_channels, kernel_size, bias=True):
return nn.Conv2d(
in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias
)
class Upsampler(nn.Sequential):
def __init... |
"""
Copyright: Intel Corp. 2018
Author: <NAME>
Email: <EMAIL>
Created Date: May 17th 2018
Updated Date: May 17th 2018
Training environment callbacks preset
"""
from pathlib import Path
from functools import partial
import numpy as np
from PIL.Image import Image
from ..Util.ImageProcess import array_to_img, img_to_ar... |
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from database.dbExecutor import... |
#PPO-LSTM
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import time
import numpy as np
import sys
sys.path.append(".")
from args.config import PPO_lstm_params as params
class PPO(nn.Module):
def __init__(self, ... |
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer, OrdinalEncoder
from marvinml.backend.utils import one_hot_encoder, label_encoder
from marvinml.backend.utils import minmax, standard_scaler, normalizer
from marvinml.backend.utils import imputation_mean, imputation_median, imputation_deletion_c... |
import os
import yaml
_recursion_paths = []
def avoid_recursion(func):
def wrapper(self, path, *args, **kwargs):
path = os.path.abspath(path)
if path in _recursion_paths:
raise RuntimeError('Recursion in depl files.')
_recursion_paths.append(path)
func(self, path, *ar... |
#!/usr/bin/env python
#
# Copyright (C) 2020 by The Board of Trustees of Stanford University
# This program is free software: you can redistribute it and/or modify it under
# the terms of the Modified BSD-3 License as published by the Open Source
# Initiative.
# If you use this program in your research, we request that... |
import os
import hashlib
import re
import shutil
import chardet
COMPONENTS_CONFIG_KEYWORD = "KEYWORD: PART2 COMPONENTS CONFIGURATION"
def get_md5sum(config_file):
""" Get MD5SUM_HEADER from config file .aos """
ret = None
with open(config_file, "r") as f:
for line in f.readlines():
lin... |
#!/usr/bin/env python3
import shutil
import sys
import os
import zipfile
import argparse
import re
import sqlite3
PWD = os.getcwd()
parser = argparse.ArgumentParser()
parser.add_argument(
"from_file",
help="import listbuilder objects (vlo) from file",
type=str,
default=os.path.abspath("test.vlb"),
)... |
"""
autor: <NAME>
autor: <NAME>
"""
from PIL import Image
import numpy as np
import basic_shapes as bs
def _generatorSphereTextureNormals(filename, nTheta, nPhi, min_theta=0, max_theta=np.pi, vertices=[], indices=[], start_index=0, texture_method = None):
image = Image.open(filename)
img_data = np.array(list... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.layers import *
class FPN(nn.Module):
def __init__(self, phase, cfg, base, extras, head, features_, feature_layer):
super(FPN, self).__init__()
self.phase = phase
self.num_classes = cfg['num_classes']
self.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["setup", "fetch", "build"]
import os
import json
import requests
import numpy as np
import pandas as pd
from geo import propose_position, compute_distance
SETTINGS_FILE = "lunch.json"
VENUES_FILE = "venues.json... |
""" Base classes for interfacing with iproute2. """
# -*- coding: utf-8 -*-
from __future__ import print_function
import functools
import netaddr
import re
import sys
import time
from sh import ErrorReturnCode
EUI = functools.partial(netaddr.EUI, dialect=netaddr.mac_unix_expanded)
IPAddress = netaddr.IPAddress
IPNet... |
import logging
import os
import re
import shutil
import subprocess
import yaml
import bs4
import mkdocs.commands.build
import test
import util
import website
def recursive_values(item):
if isinstance(item, dict):
for _, value in list(item.items()):
yield from recursive_values(value)
elif... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import argparse
import facenet
# import lfw
import os
import sys
from tensorflow.python.ops import data_flow_ops
from sklearn import metrics
fr... |
#!/usr/bin/env python
import botocore.session
import errno
import getopt
import os
import pprint
import shutil
import socket
import subprocess
import sys
import time
import urlparse
import urltools
# read env_local.sh
def source_env_local():
command = ['bash', '-c', 'source env_local.sh && env']
proc = subpro... |
# 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 agreed to in writing, ... |
from flask import Flask, request, render_template, Response
from auth490 import *
import qrcode
import base64
import os.path
import random
from typing import Union
app = Flask(__name__)
if os.path.exists(".pk"):
with open(".pk") as h:
main_authority_key = PrivateKey.deserialize(h.read())
else:
main_au... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from mock import patch, call
from nose.tools import assert_raises, assert_equals
import unit
import uuid
from synapseclient import Project, File
import sy... |
# -*- coding: utf-8 -*-
import io
import json
import os
import tarfile
import logging
from datetime import datetime
from os.path import join, relpath
from .asset import Asset, AssetSet
from .envelope import Envelope, EnvelopeSet
from .content_service import ContentService
SUCCESS = 'success'
NOOP = 'noop'
FAILURE = ... |
import attr
from twisted.internet import defer
from myutils.twisted_utils import print_method_call
from myutils import all_results
@attr.s
class P4Table(object):
controller = attr.ib()
name = attr.ib()
data = attr.ib(factory=dict, init=False)
def _convert_values(self, keys=[], action='', p... |
#!/usr/bin/python
import math
import numpy as np
from props import getNode
from .logger import log
from . import transformations
# camera parameters are stored in the global property tree, but this
# class provides convenient getter/setter functions
d2r = math.pi / 180.0
r2d = 180.0 / math.pi
camera_node = getNod... |
def string_coeffs(coeff_list):
string = ''
for k in coeff_list:
string += str(k) + ' '
return string.strip()
def moleculefile(outfile, m):
if m.ndihedrals != 0:
hasdihedrals = True
else:
hasdihedrals = False
try:
if m.nimpropers != 0:
hasimprope... |
#!/usr/bin/env python
# coding: utf-8
# Filepath: util.py
# Reference:
# Created: 2021-07-27_22:26:47
# Modified: 2021-08-23_21:18:12
# Author: <NAME> [https://github.com/dawnlh]
# Contact: <EMAIL>
# Copyright (c) 2021 <NAME>
import os
import json
import numpy as np
import argparse
def getObjInfoFromJson(... |
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import redis
import threading
import sys
import yaml
import time
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# 创建 handler 输出到文件
handler = logging.FileHandler("log/akyc_edge.log", mode='w')
handler.setLevel(logging.INFO)
# han... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import numpy as np
from PIL import Image
from scipy import special
# PSF functions
def scalar_a(x):
if x == 0:
return 1.0
else:
return (special.jn(1,2*np.pi*x)/(np.pi*x))**2
a = np.vectorize(scalar_a)
def s_b(x, NA=0.8, n=1.33):
if x == 0:
return 0
else:
return (NA/n)**... |
"""
oxasl_bids: BIDS interface for the oxford_asl pipeline
Usage:
oxasl_bids script --bidsdir <bids_directory> [... additional oxford_asl arguments]
oxasl_bids args --img <img file> --img-type <type>
oxasl_bids bidsout --oxasl-output <output folder>
'script' outputs commands to run oxasl or oxford_asl on a BIDS data ... |
# -*- coding: utf-8 -*-
# ToMaTo (Topology management software)
# Copyright (C) 2014 Integrated Communication Systems Lab, University of Kaiserslautern
#
# This file is part of the ToMaTo project
#
# ToMaTo is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... |
"""
Task definitions for prediction
"""
import abc
from typing import Any, Callable, List, Optional, Tuple, Union, cast
import joblib
import numpy as np
from eolearn.core import EOPatch, EOTask, execute_with_mp_lock, get_filesystem
from sentinelhub import SHConfig
from ..utils.types import Feature
class BasePredic... |
import typing
import json
import datetime
from testreportng.detail import NGCaseDetail
from testreportng.constants import Label
class NGResult(object):
""" result of suite """
def __init__(self, kls_name: str, data: typing.Dict[str, NGCaseDetail] = None):
self.kls_name: str = kls_name
self.d... |
# -*- coding: utf-8 -*-
#! /usr/bin/env python2
from __future__ import print_function
import os
import sys
import glob
from argparse import ArgumentParser
from concurrent.futures import ProcessPoolExecutor
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from tqdm import tqdm
fr... |
import math
import os
from typing import List, Tuple
import numpy as np
import pandas as pd
from tqdm import tqdm
import sketch.sketch_gen as board_sketch
import storyboard.board_gen as board_gen
# import storyboard.board_query as board_query
import storyboard.query_cy as board_query
import linear_board
def gen_wor... |
#
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Lead Developers: <NAME> and <NAME>
# Authors: <NAME>, <NAME>, <NAME>, <NAME>
# Research Leads: <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lic... |
import tensorflow as tf
def lrelu(x, leak=0.2, name="lrelu", alt_relu_impl=False):
with tf.variable_scope(name):
if alt_relu_impl:
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
else:
return tf.maximum(x, leak * x)
def inst... |
import plasma
from plasma import plasma2040
import time
import math
# Import helpers for RGB LEDs and Buttons
from pimoroni import RGBLED, Button
# Import bme68x and I2C helper
from breakout_encoder import BreakoutEncoder
from pimoroni_i2c import PimoroniI2C
# Press "B" to enable cycling.
# Press "A" to change the e... |
import cantera as ct
import os
import numpy as np
import sys
import matplotlib
# Use PySide instead of Qt4
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4'] = 'PySide'
import matplotlib.pylab as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from PySide import Q... |
"""
Script_processor.py extracts lines from ST: TNG scripts for a specific character and outputs them to a json file
This script downloads scripts from http://www.chakoteya.net/
"""
__author__ = "<NAME> <<EMAIL>>"
__license__ = "Apache V2"
__version__ = ".1"
__maintainer__ = "<NAME>"
__email__ = "<<EMAIL>>"
__status__... |
#!/usr/bin/env python3
#
# Copyright 2018-2021 Picovoice Inc.
#
# You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
# file accompanying this source.
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is ... |
"""
A simple Artificial Neural Network (ANN)
<NAME> @ University of Canberra for Soft Computing S2/2021
"""
# Installed libraries
import numpy as np
import pandas as pd
# Python 3.9+ Standard libraries
from abc import ABC, abstractmethod
from dataclasses import dataclass
from operator import attrgetter
import pickle
... |
"""This module implements a collector for the Python language.
It collects data with [`pytkdocs`](https://github.com/pawamoy/pytkdocs).
"""
import json
import os
import sys
import traceback
from collections import ChainMap
from subprocess import PIPE, Popen # noqa: S404 (what other option, more secure that PIPE do w... |
from flask import (
Blueprint, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
bp = Blueprint('math', __name__)
@bp.route('/', methods=("GET", "POST"))
def home():
return render_template("base.html")
@bp.route('/1', methods=("GET", "POST"))
def one():
if request.metho... |
# -*- coding: utf-8 -*-
import json
import numpy as np
from ..simulation.classfactory import with_metaclass
from ..math import noisepropagation
from ..utils import instance
from ..resources import resource_filename
from ..utils import units
from ..utils import lut
class AreaDetector(with_metaclass()):
def __ini... |
#!/usr/bin/env python3
"""
TODO:
-Sort csv in some way?
vendor, model?
latest?
"""
import argparse
stats = None
import os
import glob
def find_jl_dirs(root_dir):
if os.path.isdir(root_dir) and glob.glob(root_dir + "/*.jl"):
yield root_dir
# yield "prod/prod/2022-03-23_04_pe140t-2/2022-03-23_... |
import logging
from django.db.models import Prefetch
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _
from requests import codes
from rest_framework import parsers, viewsets
from rest_framework.exceptions import ParseError as DRFParseError
from rest_framework.permissions impo... |
#!/bin/python3
import unittest
class Node:
__slots__ = ('key','left','right')
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class SplayTree:
__slots__ = ('root','header')
def __init__(self):
self.root = None
self.header = Node(... |
# -*- coding: utf-8 -*-
import sys
import requests
from random import randint
import json
from time import sleep
import os
from os.path import join, dirname
from dotenv import load_dotenv
from configparser import SafeConfigParser
from TelegramBot import *
import logging, coloredlogs
from logging.handlers import Rotati... |
import re
import datetime
## Get the issue id from the user and search active issues first to find
## if there is no such issue then search for other lists to give an appropiate error message to the user
def closeissue(IssueId, ToDoList, DoingList, DoneList, CancelledList):
for issue in DoingList:
... |
#!/usr/bin/env python3
import datetime
import code
import serial
import asyncio
import binascii
import struct
import time
import logging
import warnings
from commands import Commands
if not logging.getLogger().handlers:
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def warn_unteste... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 10:50:16 2019
@author: ams_user
"""
from ukf import UKF
import csv
import numpy as np
import math
import matplotlib.pyplot as plt
def iterate_x(x_in, timestep, inputs):
'''this function is based on the x_dot and can be nonlinear as nee... |
from sys import exit
from modules.utils import ask, AskException, generate_unique_id, get_month
def create_new_event(con, invoker):
new_instance = True
try:
while True:
print(
"""
-*-*- Create a new event -*-*-
*-*-* Type ".stop" or ".s" to stop *-*-*"""
)
... |
#!/usr/bin/env python
# Python libs
import sys
import time
# numpy and scipy
import numpy as np
from scipy.ndimage import filters
import imutils
# OpenCV
import cv2
# Ros libraries
import roslib
import rospy
# Ros Messages
from sensor_msgs.msg import CompressedImage
from geometry_msgs.msg import Twist
from std_ms... |
import collections
import datetime
import os
import re
import time
import unicodedata
from django.conf import settings
from django.core.management import base
from django.db import transaction
from django.utils import timezone
from ...models import Album, Photo
from ...storages import get_storage
class Command(base... |
from soap.datatype import (
auto_type, int_type, float_type, double_type,
IntegerArrayType, FloatArrayType
)
from soap.expression import expression_factory, operators, Variable
from soap.parser.common import (
ParserError, _lift_child, _lift_middle, CommonVisitor
)
from soap.parser.grammar import compiled_g... |
import urllib.parse
import random
from datetime import datetime
import discord
from discord.ext import commands
from Utils import web
from discord.ext.commands.cooldowns import BucketType
class Utilities:
"""
Contains commands which help you in some simple tasks.
"""
def __init__(self, bot):
... |
# Loading the libraries we need
import ctypes # library to wrap C compatible data types, calling functions in DLLs or shared libraries in Python
import time
SendInput = ctypes.windll.user32.SendInput
# windll is used to loading dynamic link libraries for Windows
# DLL stands for Dynamic Link Library file.
# Unline e... |
import os
import pickle
import json
def triplet_stats(fin):
valid = 0
total = 0
for line in fin:
line = line.strip()
if not line:
continue
sentence = json.loads(line)
total += len(sentence["relationMentions"])
for relationMention in sentence["relationMen... |
import argparse
import enum
import glob
import os
import typing
import SimpleITK as sitk
import numpy as np
import pymia.data as data
import pymia.data.conversion as conv
import pymia.data.definition as defs
import pymia.data.creation as crt
import pymia.data.transformation as tfm
import pymia.data.creation.fileloade... |
import enum
import os
import re
PARSE_REGEX = r'(\S+)' # Get the mode atom
PARSE_REGEX += r'\s*' # Elmiinate white space
PARSE_REGEX += r'(\S+)' # Get the lhs atom
PARSE_REGEX += r'\s*' # Elmiinate white space
PARSE_REGEX += r'(\*?)' # Check for map atom
PARSE_REGEX += r'(\&?)' # Check for script local
PARS... |
#Importando as bibliotecas necessárias
from tkinter import *
#Definindo as funções para atribui-las aos botões
def adição():
top = Toplevel()
top.geometry("250x200")
AdiçãoTítuloLabel = Label(top, text="Adição", font="Roboto 14 bold italic underline")
AdiçãoTítuloLabel.place(rely=.1, relx=.5, a... |
from aocd import data, submit
import sys
from numbers import Integral
# https://adventofcode.com/2020/day/18
def test_operate():
assert operate(2,3,'*') == 6
assert operate(2,3,'+') == 5
def test_answer():
assert answer('1 + 2 * 3 + 4 * 5 + 6')['a'] == 71
assert answer('1 + (2 * 3) + (4 * (5 + 6))')[... |
# SPDX-FileCopyrightText: BioPAL <<EMAIL>>
# SPDX-License-Identifier: MIT
import logging
import numpy as np
from scipy.stats import chi2
def get_rho_omega(j, p, n):
# j is the number of covariance matrices being considered
# p is the dimension of the covariance matrix (.ie 2 for dual pol, 3 for full pol)
... |
from sklearn.metrics import *
from sklearn.model_selection import cross_val_score
from numpy import mean
from numpy import std
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
from scipy import interp
import matplotlib.patches as patches
import matplotlib.pylab as plt
import n... |
#!/usr/bin/env python3
import pygame
import field_and_pointer as fp
import instructions as i
import initialize as ini
def render_code(code):
'''
Renders each character in the code with a specific syntax highlighing
and blits the code to the background surface.
'''
for y, c in enumerate(code):
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
import urllib
from datetime import datetime
from accounts.permission import permission_verify
from cmdb.api import get_object
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponse, render
from cmdb.forms... |
#!/usr/bin/env python
import json
import datetime
import requests
from os import environ
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import *
import pandas as pd
SHOWINGS_ENDPOINT_FMT = "https://data.tmsapi.com/v1.1/mo... |
import functools
import inspect
import edict.edict as eded
import io
####
#params_dict
#curr_state,trigger_checker,trigger_checker_argnames
# :
#action,action_argnames,next_state
#curr_state,input_symbol
class FSM():
def __init__(self,**kwargs):
####
if('fsm_dict' in kwargs):
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.