text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import pandas as pd
import numpy as np
# Momentum Indicators
# Momentum indicators are tools utilized by traders to get a better understanding of the speed or rate at which the
# price of a security changes. Momentum indicators are best used with other indicators and tools because they don’t work
# to identify... |
"""
Create an interactive map for selecting satellite imagery and exporting image files.
"""
# Load modules
import datacube
import itertools
import numpy as np
import matplotlib.pyplot as plt
from odc.ui import select_on_a_map
from datacube.utils.geometry import CRS
from datacube.utils import masking
from skimage impo... |
# -*- coding: utf-8 -*-
"""This is the entry point for the application.
main() does basic setup (readline, command history), and runs the
input_loop(). Commands are passed to the parser.execute() function for parsing
and processing. All application output is handled by the output() function.
See elsec.__init__ for... |
from keras.optimizers import RMSprop, Adam
from models.CNN import build_discriminator
from models.DRUNet32f import get_model
from keras.models import Model
from keras.layers import Input,Concatenate
import numpy as np
import SimpleITK as sitk
import skimage.io as io
import os
import re
from keras import backend as K
f... |
import time
import json
import zlib
import urllib.parse
import hmac
import sys
from typing import Optional, Dict, Any, List, DefaultDict, Deque, Tuple
from requests import Request, Session, Response
from ciso8601 import parse_datetime
from datetime import datetime, timezone
from collections import defaultdict... |
# Copyright 2020 Petuum, Inc. All Rights Reserved.
#
# It includes the derived work based on:
#
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of ... |
#!/usr/bin/python3
"""
Part of RedELK
Script to check if there are alarms to be sent
Authors:
- <NAME>. / <NAME> (@xychix)
- <NAME> (@fastlorenzo)
"""
import copy
import importlib
import logging
import os
import traceback
from config import alarms, LOGLEVEL, notifications
from modules.helpers import (add_alarm_data... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python3
# Copyright (c) 2015-2021 Agalmic Ventures LLC (www.agalmicventures.com)
#
# 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... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2017 SML
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... |
import json
from json.decoder import JSONDecodeError
import logging
import os
import pyotp
import time
import traceback
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, \
NoSuchElementException, WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdr... |
# coding: utf-8
# In[3]:
# Implementation from https://github.com/dougalsutherland/opt-mmd
import sys, os
import numpy as np
from math import sqrt
CHANNEL_MEANS = (129.30402159690857/255, 124.06998485326767/255, 112.43405923247337/255)
CHANNEL_STDS = (68.17022681236267/255, 65.3918083012104/255, 70.41839897632599... |
from decimal import Decimal
import json
import urllib
from mock import Mock, patch
from nose.tools import eq_
import test_utils
from lib.paypal import constants
from lib.paypal.ipn import IPN
from lib.paypal.tests import samples
from lib.sellers.models import Seller, SellerPaypal
from lib.sellers.tests.utils import ... |
from osbot_aws.apis.Lambda import Lambda
from pbx_gs_python_utils.utils.Lambdas_Helpers import slack_message
from pbx_gs_python_utils.utils.Misc import Misc
from osbot_jupyter.api.Live_Notebook import Live_Notebook
def send_message(message, channel, team_id):
if channel:
slack_messag... |
import re
from typing import Union
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops, control_flow_ops
import modeling
class PRONTOOptimizer(object):
def __init__(self, model, sparse, learning_rate):
"""
Creates a new PRONTOOptimizer ... |
import numpy as np
import pandas as pd
from pathlib import Path
from keras.layers import Input, Embedding, Flatten, concatenate, GlobalAveragePooling1D, GlobalMaxPooling1D, Dense, Dropout, BatchNormalization
from keras.regularizers import l2
from keras.optimizers import SGD, Adam
from keras.models import Model, load_mo... |
import sys
import numpy as np
np.set_printoptions(threshold=sys.maxsize)
from PIL import Image
import matplotlib.pyplot as plt
import seaborn as sns
import time
from crypt_utils import generate_keypair
from image_utils import Im_encrypt, Im_decrypt, Brighten, Negation, LPF, Sharpen, Edge, Dilation, Hist_equal
def t... |
# -*- coding: utf-8 -*-
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions for calculating compatible binhosts."""
from __future__ import print_function
import collections
import jso... |
from copy import deepcopy
import re
import numpy as np
'''
Board class for the game of TicTacToe.
Default board size is 3x3.
Board data:
1=white(O), -1=black(X), 0=empty
first dim is column , 2nd is row:
pieces[0][0] is the top left square,
pieces[2][0] is the bottom left square,
Squares are stored and ma... |
# Author : @jimmg35
import datetime
import schedule
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
class Storer():
"""
Storing processed data from Parser.
"""
data_list = []
storage = {}
def __init__(self, dbcontext):
self.dbcontext = dbcontext
de... |
import pygame
import enemies
from ui import text, infobubble
from utils import utility, vector
from utils.settings import *
def load_data():
World.bonus_tally_sound = utility.load_sound('bonusTally')
World.boss_fight_music = utility.load_sound('bossMusic')
World.get_ready_sound = utility.load_sound('getR... |
"""
Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.0 (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 wi... |
import ErrorHandler
import Utilities
import configuration
import timeit
import green_screen as gs
import guitar_rotation
from PIL import Image
import os
# Get all sizes that this image will need
sizes = dict(configuration.config.items('sizes'))
# Get the max and min rotation angles from the configuration file
min_ang... |
import numpy as np
from scipy.signal import savgol_filter, find_peaks
from collections import OrderedDict
import copy
import scipy
import neidspec
import json
import astropy
from astropy.stats import biweight_location, sigma_clip, mad_std
from skimage import filters
from skimage import morphology
from scipy import inte... |
# Standard Imports
import ctypes
import string
import time
# kitir Imports
from kitir import *
# External Imports
log = logging.getLogger('kitir.kits.virtual_interface')
# convenience
user32 = ctypes.windll.user32
# Thanks to GameMaster's post here https://stackoverflow.com/a/54729193/1561176
# for inspiring me t... |
#!/usr/bin/env python
# coding: utf-8
"""Importing python libraries"""
import argparse
import json
import os
import subprocess
"""Importing google-cloud packages"""
from google.cloud import bigquery
from google.cloud.exceptions import NotFound
from google.oauth2 import service_account
from google.cloud import secretma... |
"""
Trainer code for 2D and 3D Noise2Void (https://arxiv.org/abs/1811.10980)
Adapted from https://github.com/juglab/pn2v/blob/master/pn2v/training.py,
ported from NumPy to PyTorch and generalized to support 3D.
"""
from typing import Callable
import torch
from torch import nn
import numpy as np
import itertools
from... |
import xgboost as xgb
from xgboost import XGBRegressor
import numpy as np
from ..xgboost import XGBModelHypster
class XGBTreeRegressorHypster(XGBModelHypster):
def get_tags(self):
self.tags = {'name' : "XGBoost Tree-Based Regressor",
'model type': "tree",
'supports r... |
import numpy as np
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import gensim
import pickle
import os
from collections import Counter
# tokenize and anonymize one tweet
def token_tweet(tweet):
'''The data has been tokenized during build... |
from PIL import Image
import numpy as np
import colorsys
#from asprise_ocr_api import *
from pytesseract import image_to_string
import os.path
def check_program(progname):
path = os.getenv('PATH')
for p in path.split(';'):
if os.path.exists(os.path.join(p, progname)):
return True
retur... |
import os
import logging
import csv
import warnings
import yaml
import joblib
from scipy import io
import numpy as np
from matplotlib import pyplot as plt
# Stop numba from throwing a bunch of warnings when it compiles LCTM
from numba import NumbaWarning; warnings.filterwarnings('ignore', category=NumbaWarning)
impor... |
"""
This module deals with database connections, engine creation, and session creation.
It exposes methods and variables according to SQLAlchemy best practices (hopefully).
It has the ability to connect to multiple mediawiki databases.
It uses Flask's handy config module to configure itself.
"""
import json
import os
... |
from bson.objectid import ObjectId
from models import Website, app, mongo, Image
from flask import Flask, render_template, request, redirect, url_for, session
from werkzeug.security import generate_password_hash, check_password_hash
def format(unformat):
lenght = len(unformat)
count = 0
formated_list = []
... |
#!/usr/bin/env python3
"""
Copyright (C) 2021 Semi-Auto bot tool
made by c0del1ar a.k.a <NAME> and it is licensed
"""
from re import findall
from datetime import date,timedelta
from time import sleep
import json, socket
from requests import get
from config import *
from random import shuffle
from tqdm import t... |
import asyncio
import json
import os.path
import time
from flask import Flask, abort, redirect
from common import file, page, console, post_map
system_config = dict()
page_list = list()
rss = None
menu_list = list()
template_config = dict()
page_name_list = list()
cache_index = dict()
cache_post = dict()
i18n = dict... |
import os
import time
import types
import tempfile
from collections import OrderedDict
from logging import getLogger
import shutil
from scipy import stats
import pandas as pd
from starkit.fitkit.priors import PriorCollection
logger = getLogger(__name__)
import numpy as np
try:
import pymultinest
except Import... |
#!/usr/bin/env python
import math
import rospy
import struct
import random
import string
import tf2_ros
import numpy as np
import tf2_geometry_msgs
from std_srvs.srv import Empty
from nav_msgs.msg import OccupancyGrid
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import Range, PointCloud2, PointField
from... |
import sys
from sage.misc.temporary_file import tmp_filename
from sage.plot.colors import rainbow
import os, sys
#Setup the html page for d3js and for hosting the graph
def gen_html_code(JSONgraph):
try :
js_code_file = open(pathRepo+"/JS_Graph_Sage/src/HTML/base_html.html", 'r') #Open the html page whic... |
import copy
import torch
from torch import nn
from torch.nn import functional as F
from transformers import BertPreTrainedModel, BertModel, BertConfig
from transformers.modeling_bert import BertEncoder
from general_util.utils import AverageMeter
from modules import layers
class KnowledgeSSPConfig(BertConf... |
#!/usr/bin/env python3
"""
Author: <NAME> <<EMAIL>>
"""
import http
import io
import logging
import os
import platform
import random
import time
import zipfile
from os.path import dirname, realpath
from typing import Optional
from zipfile import ZipFile, ZipInfo
import cv2
# from flask_latency import Latency
import num... |
from rest_framework import serializers
from . import models
from utils.serializers import raise_field_validation_error
class RunSerializer(serializers.ModelSerializer):
url = serializers.CharField(
source='get_absolute_url', read_only=True)
url_update = serializers.CharField(
source='get_upda... |
#%%
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.contrib.distributions import Bernoulli
from sklearn.model_selection import train_test_split
from sklearn.preprocessing impor... |
import os
import stat
import types
from . import misc, record
paths = {}
stats = 0
tasks = set()
class File:
def __init__(self, path):
self.path = path
self.producer = None
self.dependants = set()
self.timestamp = None
self.exists = None
self.phony = False
de... |
"""
1. 技术指标讲解.
微信:bitquant51
火币交易所推荐码:asd43
币安推荐码: 22795115
币安推荐链接:https://www.binance.co/?ref=22795115
Gateio交易所荐码:1100714
Bitmex交易所推荐码:SzZBil 或者 https://www.bitmex.com/register/SzZBil
代码地址: https://github.com/ramoslin02/51bitqunt
视频更新:首先在Youtube上更新,搜索51bitquant 关注我
"""
import cc... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 11:48:03 2018
@author: <NAME>
"""
from sklearn.ensemble import RandomForestClassifier as RndFC
from sklearn import svm
from sklearn import metrics as met
from sklearn.neural_network import MLPClassifier as ffp
from sklearn.neighbors import KNeighborsClassifier as KNN
... |
import platform
import re
from dnload.common import is_verbose
########################################
# PlatformVar ##########################
########################################
class PlatformVar:
"""Platform-dependent variable."""
def __init__(self, name, osname = None, osarch = None):
"""I... |
import os
from typing import Dict, List, Tuple, Union
import numpy as np
from scipy.spatial.transform import Rotation
from h5datacreator.structure import SUBTYPE_ROTATION, SUBTYPE_TRANSLATION
PLY_PROPERTIES_DTYPE = {
'char': 'i1',
'uchar': 'u1',
'short': 'i2',
'ushort': 'u2',
'int': 'i4',
'uin... |
"""
The equilibrium module defines routines for interacting with
calculated phase equilibria.
"""
import warnings
import pycalphad.variables as v
from pycalphad.core.utils import unpack_components, unpack_condition, unpack_phases, filter_phases, instantiate_models, get_state_variables
from pycalphad import calculate
fr... |
from tkinter import *
from ElectrospraySimulator.Tools.CreateMesh import create_mesh, write_mesh
from ElectrospraySimulator.GUI_scripts.ToolTip_creator import CreateToolTip
"""
Options for the mesh can be found at:
http://transit.iut2.upmf-grenoble.fr/cgi-bin/info2www?(gmsh)Mesh+options+list
"""
class MeshApp(Frame... |
import base64
import io
import os
import time
from datetime import datetime
from threading import Thread
import socket
import email.utils as eut
from geolite2 import geolite2
from newspaper import Article
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_compo... |
from cProfile import label
import os
import json
import cv2
import tqdm
import logging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import seaborn as sns
from imblearn.over_sampling import SMOTE
from argparse import ArgumentParser
from sklearn.model_selection import tr... |
"""
Authentication Servers represent server definitions used to authenticate remote
users.
If you need to use Active Directory for user authentication, you can use these
modules to provision AD servers and LDAP domains.
An example of creating an Active Directory Server instance with additional
domain controllers (yo... |
import pandas as pd
import pytest
import numpy as np
import dask.dataframe as dd
from dask.dataframe.utils import assert_eq
from dask.utils import ignoring
def mad(x):
return np.fabs(x - x.mean()).mean()
def rolling_functions_tests(p, d):
# Old-fashioned rolling API
assert_eq(pd.rolling_count(p, 3), dd... |
#!/usr/bin/env python3
# The MIT License (MIT)
#
# Copyright (c) 2013-2016 <NAME> <<EMAIL>>
#
# 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 limitatio... |
"""
python recursive.py ../data/emoji_rgb/validate/0/240px-Noto_Emoji_KitKat_1f60f.svg.png --num_paths 3,3,3,3
"""
import pydiffvg
import torch
import os
import skimage
import skimage.io
import random
import argparse
import math
import errno
from tqdm import tqdm
from torch.optim.lr_scheduler import CosineAnnealingLR
... |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import sys
import random
import time
def update_progress(msg, progress):
text = "\r{0} {1:>7.2%}".format(msg, progress)
sys.stdout.write(text)
sys.stdout.flush()
class Agent(object):
"""
DQN agent
... |
#!/usr/bin/env python
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import base64
import binascii
import string
from Crypto.Cipher import AES
from collections import Counter
from itertools import cycle
### Challenge 1 ###
def hex_to_base64(hex):
"""
Takes a unicod... |
"""
testing utilities
"""
#-----------------------------------------------------------------------------
# Copyright (c) ytree development team. All rights reserved.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module which contains afk-related commands """
from random import choice, randint
from asyncio import slee... |
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import json
import os
import librosa
import numpy as np
import tensorflow as tf
import midi
from wavenet import WaveNetModel, MidiMapper, mu_law_decode, mu_law_encode, audio_reader
TEMPERATURE = 1.0
L... |
#!/usr/bin/python
import os
import sys
from Bio.Blast import NCBIXML
from Bio import SeqIO
from collections import Counter, defaultdict
def SeqFilter(input_fas,output_fas,length):
input_records = SeqIO.parse(input_fas, "fasta")
filtered_records = (record for record in input_records if len(record.seq) == int(length)... |
import adsk.core
import adsk.fusion
import adsk.cam
import traceback
## Global variable used to maintain a reference to all event handlers.
handlers = []
## global variable to maintain reference to the fusion ui
ui = None
## global variable to maintain reference to the fusion application
app = None
## global variable ... |
import pandas as pd
import datetime as datetime
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess
def importdexcom(filename):
data = pd.read_csv(filename)
df = pd.DataFrame()
df['Time'] = data['Timestamp (YYYY-MM-DDThh:mm:ss)']
df['Glucose... |
#!/usr/bin/env python
#
# Copyright (c) 2014-2016 <NAME>, The Sainsbury Laboratory
#
# 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 righ... |
import os
import threading
import uuid
from time import sleep
import yaml
from django.db import models
from ansible_api.models.mixins import AbstractExecutionModel
from cloud_provider import get_cloud_client
from common import models as common_models
from fit2ansible import settings
from django.utils.translation impo... |
"""simple_lines.py: functions for handling simple lines in relation to a resqml grid."""
version = '19th January 2021'
# line is represented as 2D numpy array of shape (NP, 3): [point index, xyz]
import logging
log = logging.getLogger(__name__)
import numpy as np
def read_lines(filename):
"""Returns a list o... |
import click
from prettytable import PrettyTable
import json
import os
import tempfile
from nexuscli.cli import cli
from nexuscli import utils
from nexuscli.helpers import schemahelper
@cli.group()
def schemas():
"""Schemas operations"""
@schemas.command(name='create', help='Create a new schemas')
@click.option... |
# Common functions and definitions
#
# This file defines commonly used parts for ease of programming.
# Import as follows:
#
# > from common import *
#
# Private notation(s):
# - mels = melspectrogram
#
# # Basic definitions
import warnings
warnings.simplefilter('ignore')
import numpy as np
np.warnings.filterwarnings(... |
# -*- coding: utf-8 -*-
"""Functions to load data from the corpus."""
from __future__ import absolute_import, division, print_function, unicode_literals
import re
#from unidecode import unidecode
from collections import Counter
# All capitalized constants come from this file
import config as cfg
def split_to_chunks(o... |
import daskutils.math
import daskutils.base
import daskutils.io.msgpack
import dask.bag
import dask.distributed
import os.path
import uuid
import msgpack
import itertools
import contextlib
import socket
import subprocess
import base64
@contextlib.contextmanager
def worker_client(*arg, **kw):
started = False
tr... |
import numpy as np
import scipy.ndimage as ndimage
import networkx
from shapely.geometry import Polygon
from skimage.draw import polygon2mask
from skimage.morphology import skeletonize
from sklearn.neighbors import kneighbors_graph
from numba import njit, prange
import matplotlib.pyplot as plt
def find_distance_to_c... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# Copyright 2020, Futurewei Technologies
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, V... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2017 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""
Run embedded integration tests from GTClang DSL code.
"""
import sys
import os.path
import re
import subprocess
import filecmp
import argparse
from json import loads as load_json
from difflib import unified_diff
patterns = {
"RUN": re.compile(r"//\s*RUN:\s*(?P<command>[^\n]+)"),
"EXPECTED_LINE": re.compile... |
'''
This module provides a base Tag class for a OLECF file.
'''
from supyr_struct.tag import Tag
from supyr_struct.buffer import Buffer, SEEK_SET, SEEK_CUR, SEEK_END
__all__ = ("OlecfDataStream", "OlecfTag", )
class OlecfDataStream(Buffer):
'''
A class which allows accessing data within a storage data stream... |
# -*- coding: UTF-8 -*-
import struct
import zlib
import hashlib
import re
from subprocess import check_call
import argparse
import os
from xml.dom.minidom import parse
import xml.dom.minidom
import zipfile
from PIL import Image
import shutil
stApkToolPt = r'D:\Android\Apktool\apktool_2.4.1\apktool.jar' ... |
# Copyright (c) 2019-2020 <NAME>
# License: MIT License
import pytest
import math
import pickle
# Import from 'ezdxf.math._vector' to test Python implementation
from ezdxf.math._vector import Vec2, Vec3
from ezdxf.acc import USE_C_EXT
all_vec_classes = [Vec2, Vec3]
vec2_only = [Vec2]
if USE_C_EXT:
from ezdxf.acc.... |
import re
def symbol_underline_fun(keyword, gap=5):
return keyword.replace('_', '.{0,%s}' % gap)
def strict_en_fun(keyword):
"""
英文名称需要正则保证前后无英文字母
:param keyword:
:return:
"""
pattern_all_en = re.compile(r'[^\w+._\s()]', re.A)
items = re.findall(pattern_all_en, keyword)
is_all... |
from io import BufferedWriter
from typing import Any
import bpy
from mathutils import Matrix
from struct import pack
import bmesh
import ntpath
import os
import sys
from collections import OrderedDict
from bpy_extras.io_utils import (
orientation_helper,
axis_conversion,
)
import pprint
from . import data_types... |
try:
import neopixel
HAVE_NEOPIXEL = True
except ImportError:
HAVE_NEOPIXEL = False
import math
from abc import ABC, abstractmethod, abstractproperty
try:
import pygame
HAVE_PYGAME = True
except ImportError:
HAVE_PYGAME = False
from . import map_dict
from .sprites import OutOfBoundsError
... |
# Import all packages
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Reshape
class QmixNet(tf.keras.Model):
def __init__(self, dims, input_shape, name='Qmix', **kwargs):
super(QmixNet, self).__init__(... |
# -*- coding=utf-8 -*-
import pkg_resources
import sys
import random
import pygame
from pygame.locals import *
from idiom_lib import IdiomLib, resource_path
def get_font_file():
return resource_path('syht.otf')
def run(mode):
if sys.version_info < (3,0):
reload(sys)
sys.setdefaultencoding('utf-8')
elif sys.ver... |
# coding=utf-8
from imutils.video import VideoStream
import face_recognition
import argparse
import imutils
import pickle
import time
import concurrent.futures
import cv2
import os
import serial
import tkinter as tk
from PIL import Image, ImageTk
import numpy as np
import tkinter.font as tkFont
ap = ar... |
import math
import os
import random
from PIL import Image, ImageDraw
# Some Geometric Functions we'll need later.
# Standard euclidean distance between two points on the plane.
def distance(p1,p2):
return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
# Intersection points of two circles.
def get_intersections(x0,... |
"""
README.
==================
This is the demo file that puts all the pieces together.
It creates a data object (ie the problem to be solved) and a model;
it wraps the model in functions that HF knows how to use.
Then these functions, together with the initial vaule of the parameters
and the initial value of the... |
import sys
import json
from typing import Union, Optional
from PySide2.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PySide2.QtWebEngineWidgets import (QWebEngineDownloadItem,
QWebEngineSettings,
QWebEngineProfile,
... |
# coding=utf-8
"""apyfal.client.syscall tests"""
from contextlib import contextmanager
from copy import deepcopy
import json
import os
from threading import Lock
try:
# Python 2
from StringIO import StringIO
except ImportError:
# Python 3
from io import StringIO
import pytest
def test_call(tmpdir):... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn.inits import glorot
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, softmax, degree
class GIN(MessagePassing):
def __init__(self, emb_dim):
super(GIN, self).__init__()... |
import numpy as np
from tqdm import tqdm
from poseutils.constants import *
from poseutils.common import calc_angle_360
from poseutils.common import normalize_a_to_b
def calculate_limb_lengths(jnts_xd, cvt_mm=False):
assert len(jnts_xd.shape) == 2
assert jnts_xd.shape[-1] == 2 or jnts_xd.shape[-1] == 3
as... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License
#
# Copyright 2012 Sony Mobile Communications. All rights reserved.
#
# 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 ... |
###################################################
#
# Script to
# - Calculate prediction of the test dataset
# - Calculate the parameters to evaluate the prediction
#
##################################################
#Python
from PIL import Image
import numpy as np
np.set_printoptions(threshold=np.inf)
import... |
"""Parse BUFR files with the help of ecCodes' bufr_dump.
Specialized on radiosounding data. Calls bufr_dump -jf on a bufr file, reads
the JSON output and uses a crude state machine to convert the contents into
a pandas dataframe and a dictionary containing additional metadata.
The performance bottleneck is bufr_dump,... |
# Copyright 2020 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
from weakref import WeakKeyDictionary
from functools import partial
from itertools import count
import ctypes
import numpy as... |
from dataclasses import dataclass
from typing import Any, DefaultDict, Dict, List, NamedTuple, Optional, Set, Tuple, Union, cast
from eth_typing.evm import ChecksumAddress
from rotkehlchen.accounting.structures.balance import Balance
from rotkehlchen.assets.asset import EthereumToken, UnderlyingToken
from rotkehlchen... |
# Lint as: python3
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import argparse
import warnings
import os
import sys
import numpy as np
sys.path.append('/home/daniel/Documents/DeepLearningOpenCV/libsvm-3.23/python')
from svmutil import svm_train
from svmutil import svm_save_model
from svmutil import svm_load_model
from svmutil import svm_predict
warnings.simplefilter(action='ignore... |
import asyncio
import traceback
import time
import re
from pyrogram import filters
from bot import alemiBot
from util.permission import is_allowed, is_superuser, allow, disallow, serialize, list_allowed, ALLOWED
from util.user import get_username
from util.message import edit_or_reply, get_text, is_me
from util.text... |
import asyncio
import socket
import ssl
import time
from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Tuple
import aiohttp
import dateutil.parser
import pytest
import trustme
from aiohttp import web
from aiohttp.abc import AbstractResolver
from aiohttp.test_utils import unused_port
from neuro_sdk... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.