text stringlengths 8.04k 46.5k |
|---|
import os
import pygame
import random
import settings as s
vec = pygame.math.Vector2
class SpriteSheet:
"""Utility class for loading and parsing spritesheets.
"""
def __init__(self, filename):
"""Loads the spritesheet.
Args:
filename (str): Filename of the spritesheet to be ... |
#!/usr/bin/env python
import copy
import glob
import os
import time
import numpy as np
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from envs import MGEnv, CleanupEnv, HarvestEnv, GridWorldEnv,multi_GridWorldEnv
from algorithm.ppo ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/31 10:02
# @Author : kimmy-pan
# @File : GET_TAPD.py
import requests
import tablib
from io import BytesIO
from requests.auth import HTTPBasicAuth
from model.util.PUB_DATABASEOPT import *
from model.util.PUB_LOG import *
from model.FUNC.... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import argparse
import csv
import inspect
import os
import re
import signal
from enum import Enum
from pathlib import Path
from shutil import copytree, SameFileError, copy
from happy_python import HappyLog
from happy_python import HappyPyException
from happy_python import... |
import arrayfire as af
import cupy as np
import numpy
import scipy.sparse as sp
import warnings
import numbers
from numpy.core.numeric import ComplexWarning
from inspect import signature, isclass, Parameter
from af_type_utils import typemap
from sklearn.utils.validation import _deprecate_positional_args
from sklearn._... |
from collections import Counter
import logging
import string
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic.base import TemplateResponseMixin, View
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.edit import ProcessFormView... |
import argparse
import math
import random
import os
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from tqdm import tqdm
import torchvision.da... |
import numpy as np
import astropy.table as at
import astropy.coordinates as ac
import astropy.units as au
"""
This module defines the RMTable class and all the methods necessary to read and write
RMTables into ASCII (tsv) or FITStable formats as well as convert new catalogs in the
form of a numpy ndarray into new RM... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 09:31:05 2021
@author: sam
"""
import git
import yaml
import glob
import shutil
import ast
import os
from astropy.table import QTable, Table
from astropy.io import fits
import pandas as pd
import numpy as np
from astropy import units as u
from as... |
#!/usr/bin/env python3
import json
from pathlib import Path
import platform
import os
import subprocess
from time import time, sleep, monotonic
import cv2
import numpy as np
import depthai
import consts.resource_paths
from depthai_helpers import utils
from depthai_helpers.cli_utils import cli_print, parse_args, Pri... |
#!/usr/bin/env python
"""
============
Image Target
============
Create continuum and spectral line images for the ALMA targets.
NOTE: Run with `execfile` in CASA to use this script.
"""
from __future__ import (print_function, division)
import os
import glob
import shutil
import datetime
from collections import namedt... |
# Uncomment and run the appropriate command for your operating system, if required
# Linux / Binder / Windows (No GPU)
# !pip install numpy matplotlib torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# Linux / Windows (GPU)
# pip install torch==1.7.1+cu11... |
import tensorflow as tf
from buildModel.hyperparameters import *
from scipy.signal import gaussian
import numpy as np
"""
All tensor objects will be defined as global variables.
Any source can access to these values for restoring or
saving or training tensors.
"""
def tensorSummaries(tensor,name):
with tf.name_scop... |
import random
import time
from dataclasses import dataclass
from typing import Optional
import cv2
import numpy as np
import textdistance
from Arknights.addons.common import CommonAddon
from automator import AddonBase, cli_command
from imgreco import imgops, resources, ocr
import imgreco.ocr.tesseract as tesseract
im... |
import asyncio
import json
import logging
import random
import string
import typing
from datetime import datetime
import discord
from discord import Embed, Colour
from discord.ext import commands, tasks
logger = logging.getLogger('discord')
logger.setLevel(logging.WARNING)
try:
handler = logging.FileHandler(fil... |
class GameState():
def __init__(self):
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
... |
"""Finds duplicate files and generates a script to deduplicate them"""
# Copyright (c) 2017 <NAME>. This is free software released
# under the MIT License. See `LICENSE.txt` for details.
from enum import Enum
import collections
import datetime
import hashlib
import inspect
import itertools as itools
import operato... |
import abc
import argparse
import collections
import io
import locale
import re
import shlex
import lldb
import six
ENCODING_RE = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
# Objects
class PyObject(object):
def __init__(self, lldb_value):
self.lldb_value = lldb_value
def __repr... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
HERE_RTTI_Archive_Miner
A QGIS plugin
This plugin can mapping gps traces and points to HERE RTTI Archive.
-------------------
begin ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 13:01:47 2020
@author: yazdsous
"""
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
# In[ ]:
#WHERE WE EXTRACT TABLE NAME FROM CSV
from bs4 import BeautifulSoup
from tika import parser
import os
import camelot
from fuzzywuzzy import fuzz
from... |
from meraki_sdk.meraki_sdk_client import MerakiSdkClient
from meraki_sdk.exceptions.api_exception import APIException
from operator import itemgetter
import copy
from _config import *
import json
client = MerakiSdkClient(apikey)
def show_enabled(e_stat):
if e_stat is True:
return "Yes"
else:
... |
import json
import re
from datetime import datetime
from math import floor
import re
import requests
from django.http import HttpResponse
from django.utils.encoding import uri_to_iri
from django.views.generic.base import View
from Core.models import Archive, Configuration, Cost, CostCategory, History, ShoppingList, S... |
"""
Training script. Should be pretty adaptable to whatever.
"""
import argparse
import os
import shutil
import json
from copy import deepcopy
import multiprocessing
import numpy as np
import pandas as pd
import torch
from allennlp.common.params import Params
from allennlp.training.learning_rate_schedule... |
from __future__ import print_function
import cv2
import PIL.Image
import numpy as np
import scipy.stats
import sys
import itertools
from line_intersection import *
np.set_printoptions(suppress=True, precision=2)
def scaleImageIfNeeded(img, max_width=1024, max_height=1024):
"""Scale image down to max_width / max_heig... |
from subprocess import call, PIPE, Popen, check_output, CalledProcessError
from sys import stdin, stdout, platform, version_info
from os import system
from re import search
from termios import tcgetattr, tcsetattr, TCSADRAIN
from time import sleep
from tty import setcbreak
from dialog import Dialog
d = Dialog(dialog="... |
from LL1 import *
import copy
import traceback
import sys
idsAfns = 0 # Servirá para asignar IDs a los AFNs que vayan siendo creados
afns = {} # Servirá para ir guardando los AFNs creados
analizador = AnalizadorLexico()
afds = {} # Guardará los AFDs
idsAfds = 0 # Servirá para asignar IDs a los AFDs que vayan siendo cr... |
import ctypes
import enum
def decode_utf16_from_address(address, byteorder='little',
c_char=ctypes.c_char):
if not address:
return None
if byteorder not in ('little', 'big'):
raise ValueError("byteorder must be either 'little' or 'big'")
chars = []
while Tr... |
import asyncio
import functools
import logging
import multiprocessing
import os
import textwrap
import time
from queue import Empty as QueueEmpty
import tweepy
import discord
import discord.ext.commands as commands
import discord.utils as dutils
from discord.ext.commands.formatter import Paginator
import paths
from ... |
#!/usr/bin/python
import os
import sys
import re
from . options import SymbioticOptions
from . utils import err, dbg, enable_debug, print_elapsed_time, restart_counting_time
from . utils.process import ProcessRunner, runcmd
from . utils.watch import ProcessWatch, DbgWatch
from . utils.utils import print_stdout, print... |
import numpy as np
import scipy.sparse as sparse
from tqdm import tqdm
def compute_normals(vertices, faces):
"""
Compute normals of a triangular mesh
Parameters
-----------------------------
vertices : (n,3) array of vertices coordinates
faces : (m,3) array of vertex indices defining face... |
#VoidFinder Function to do just about everything
import numpy as np
from astropy.table import Table
import time
from .hole_combine import combine_holes, combine_holes_2
from .voidfinder_functions import mesh_galaxies, \
in_mask, \
not_in_mask, \
... |
#!/usr/bin/env python3
import cv2
import gzip
import math
import numpy as np
import stretch_funmap.numba_height_image as nh
import struct
import sys
import threading
import yaml
from collections import deque
from copy import deepcopy
from scipy.spatial.transform import Rotation
from stretch_funmap.numba_create_plane_i... |
# Copyright International Business Machines Corp, 2020
#
# 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 ... |
import os
import pkgutil
import socket
import sys
import typing as t
import warnings
from datetime import datetime
from functools import lru_cache
from functools import update_wrapper
from threading import RLock
import werkzeug.utils
from werkzeug.exceptions import abort as _wz_abort
from werkzeug.utils import redirec... |
#利用加噪声的图像进行降噪自编码器的测试
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import glob
import numpy as np
from PIL import Image
... |
import logging
import traceback
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django.utils.timezone import localtime
from django import forms
logger = logging.getLogger(__name__)
# Create your models here.
class... |
#!/usr/bin/env python
import os
constants = {
# physical units
"kBoltz" : 1.38064852e-23, # Boltzmann constant, J/K
"rho" : 1000., # water density, kg/m^3
"Ndumps" : 250, # dumber of dumps
# numerical approximations
"Cdt" : 0.25, # ti... |
# -*- coding: utf-8 -*-
"""
@author: <NAME> <<EMAIL>>
@brief: extreme ensemble selection module
@note:
- support multiprocessing (set multiprocessing = True and multiprocessing_num_cores = #cores)
- support random weight in greedy forward model selection (set weight_opt_max_evals = 1)
"""
"""
Implemen... |
# needs:fix_opt_description
# needs:check_deprecation_status
# needs:check_opt_group_and_type
# needs:fix_opt_description_indentation
# needs:fix_opt_registration_consistency
# Copyright 2016 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... |
import numpy as np
import pickle as pkl
import networkx as nx
from networkx.readwrite import json_graph
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
from sklearn.metrics import f1_score
import sys
import tensorflow as tf
import json
from time import time
import os, copy
flags = tf.app.f... |
"""The main lagrangian-filtering module.
This module contains the crucial datastructure for
lagrangian-filtering, `LagrangeFilter`. See project documentation
for examples on how to construct a filtering workflow using this
library.
"""
import dask.array as da
import numpy as np
from datetime import timedelta, dateti... |
"""
Dipper AST implementation
"""
from rpython.rlib.objectmodel import we_are_translated
import typesystem as types
import py
from dip.builtins import has_builtin, get_builtin
from dip.bytecode import INST
from dip.common import CompileError
def infix_to_prefix(tokens):
ops = set(("+", "-", "*",... |
## Data processing
## Processing JSON file
import csv
import os
import collections
import json
import logging
from copy import deepcopy
import numpy as np
import torch
PAD = '<pad>'
UNK = '<unk>'
USR = 'YOU:'
SYS = 'THEM:'
BOD = '<d>'
EOD = '</d>'
BOS = '<s>'
EOS = '<eos>'
SEL = '<selection>'
#SPECIAL_TOKENS_DEAL = [... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 2 18:02:17 2016
@author: denis
"""
from math import pi
from itertools import islice
import numpy as np
import pandas as pd
import copy
import matplotlib.pyplot as plt
from pytrx.utils import z_str2num, z_num2str
import pkg_resources
from pytrx import hydro
from pytrx.t... |
# Copyright (c) 2018 <NAME>.
# Uranium is released under the terms of the LGPLv3 or higher.
import datetime
import os
import os.path
import re
import shutil
import tempfile
from typing import Dict, Generator, List, Optional, Union, cast
from UM.Logger import Logger
from UM.Platform import Platform
from UM.Version imp... |
import copy
import datetime
import os
import re
import shutil
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Iterable, List, Optional, Union
from urllib.request import urlretrieve
import boto3
from botocore.exceptions import ClientError
from glue_job_runner.utils import (
C... |
#############################################################################
# Analysis codes for mBLA_UF code #
# #
# Used in the paper: #
# [1] ... |
from tkinter.constants import CENTER, DISABLED, FLAT, SOLID, GROOVE, RAISED, RIDGE, SUNKEN
from tkinter import filedialog as fd
from tkinter import ttk
from typing import Text
import RPi.GPIO as GPIO
import tkinter as tk
from datetime import datetime
from PIL import ImageTk, Image
from pathlib import Path
import time
i... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from typing import List, Dict
import random
import logging
from tqdm import tqdm
from collections import namedtuple
import pdb
from miso.metrics.s_metric.candidate_mappings import CandidateMappings
from miso.metrics.s_met... |
import sys, os, re
import json
from dateutil.parser import parse as duparse
from pyspark.sql import Row
sc, spark # in attendence?
# Load all Github events for the year spanning 04-01-2018 to 03-31-2019
github_lines = sc.textFile('s3://github-dataset/*.json.gz') # Change me to entire bucket!
# Apply the function to... |
""" Copyright © - 2020 - UMONS
CONQUESTO of University of Mons - <NAME>, <NAME>, and <NAME> - is free software : you can redistribute it and/or modify it under the terms of the BSD-3 Clause license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied wa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 15:52:02 2018
@author: branko
"""
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from utils import tile_raster_images
import math
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] =... |
import unittest
import pyrtl
import pyrtl_extras as pe
class TestCore(unittest.TestCase):
def setUp(self):
pyrtl.reset_working_block()
def test_gray_code_encoder_4_bits(self):
i = pyrtl.Input(4, 'i')
o = pe.gray_code(i)
pyrtl.probe(o, 'o')
sim = pyrtl.Simulation()
... |
# coding: utf-8
# In[1]:
from __future__ import print_function
import os
os.environ["PATH"] += os.pathsep + 'E:/Graphviz2.38/bin'
import tensorflow as tf
# import keras.backend.tensorflow_backend as KTF
# 指定第一块GPU可用
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"# config = tf... |
from __future__ import annotations
from collections import defaultdict
from typing import Callable, Iterable, Optional, cast
from code_gen_config import Config, ConfigImport
from datetime import datetime, time
from ast import literal_eval
class PythonScript:
def __init__(self, parent_script: Optional[PythonScript... |
"""
Utilities for iterating constructing data sets and iterating over
DNA sequence data.
Pybedtools code from:
https://github.com/uci-cbcl/FactorNet/blob/master/utils.py
Pseudo code structure:
1. Construct a random training set (start with a random negative,
account for data augmentations later?)
2. Load the data & ... |
import numpy as np
from utils import *
from tensorflow import keras
from tensorflow.keras.layers import Conv2D, AvgPool2D, MaxPool2D
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.losses import CategoricalCrossentropy, SparseCategoricalCrossentropy
from tensorflow.keras.metrics ... |
from pathlib import Path
import dadmatools.pipeline.download as dl
import time
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F
from tqdm import tqdm
import os, sys
import pickle
import numpy as np
import transformers
################### helpers ##########... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
The plotting module contains various classes to generate typical SymEnergy
output plots. Data update callbacks are implemented in JavaScript. This allows
for interactive standalone plots, suited for Jupyter Notebooks.
Plots are arranged in 2D arrays. The two dimensio... |
#!/usr/bin/env python3
# ######################## Imports
import sys
import math
import pyglet # INSTALL
import pyglet.gl
from pyglet.window import key
from queue import Queue, PriorityQueue # ,LifoQueue
import random
from timeit import default_timer as timer
import cProfile
# ######################## Globals
# ... |
# Copyright 2022, The TensorFlow Federated Authors.
#
# 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 o... |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
########## Keras imports ###########
from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout, Input, Activation, Reshape
from keras.models import Sequential, load_model, Model
from keras.layers.convolutional import Co... |
'''
script to decide on the nominal exposure time based on the survey strategy
simulation and completeness simulations.
1. Compile 8 exposures from the v2 strategy simulation outputs.
2. Construct spectral completeness simulations for the 8 exposures using the
CMX updated sky model for t_nominal = 130, 150, 180, 2... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# A tf.keras implementation of Google efficientnet,
# ported from https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py
#
"""EfficientNet models for Keras.
# Reference paper
- [EfficientNet: Rethinking Model Scaling for Convolut... |
# pylint: disable=redefined-outer-name, comparison-with-callable
"""Test helper functions."""
import gzip
import importlib
import logging
import os
import pickle
import sys
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pytest
from _pytest.outcomes import Skipped
from... |
# flake8: noqa
# @TODO: code formatting issue for 20.07 release
from typing import Any, Callable, Dict, Mapping, Optional, Tuple, Union
from abc import ABC, abstractmethod
from collections import defaultdict, OrderedDict
from pathlib import Path
import torch
from torch import nn
from torch.utils.data import DataLoader... |
import mmcv
import numpy as np
from mmcv.utils import deprecated_api_warning, is_tuple_of
from numpy import random
from torchvision.transforms import ColorJitter
from ..builder import PIPELINES
from PIL import Image
@PIPELINES.register_module()
class Resize(object):
"""Resize images & seg.
This transform resi... |
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from sklearn.utils import shuffle
import input_data
random_numer = 42
np.random.seed(random_numer)
def ReLu(x):
mask = (x > 0) * 1.0
return mask * x
def d_ReLu(x):
mask = (x > 0) * 1.0
return mask
def arcta... |
# This is part of Python source code with Eventlet-specific modifications.
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
# 2011, 2012, 2013, 2014, 2015, 2016 Python Software Foundation; All Rights
# Reserved
#
# PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
# -----------------------------... |
""" Tools for doing common subexpression elimination.
"""
from sympy.core import Basic, Mul, Add, Pow, sympify, Symbol
from sympy.core.compatibility import iterable
from sympy.core.containers import Tuple, OrderedSet
from sympy.core.exprtools import factor_terms
from sympy.core.function import _coeff_isneg
from sympy.c... |
# -*- coding: utf-8 -*-
# exdoc.py
# Copyright (c) 2013-2019 <NAME>
# See LICENSE for details
# pylint: disable=C0111,C0411,C0413,E0012,E0611,E1101,E1103,F0401,R0201,R0205,R0903
# pylint: disable=R0913,R0914,W0105,W0122,W0212,W0611,W0613
# Standard library imports
from __future__ import print_function
import collectio... |
import re
import json
import logging
import pytest
import time
from tests.common.utilities import wait, wait_until
from tests.common.dualtor.mux_simulator_control import toggle_all_simulator_ports, get_mux_status, reset_simulator_port
from tests.common.dualtor.constants import UPPER_TOR, LOWER_TOR, NIC
from tests.comm... |
# Copyright 2018-2022 Streamlit 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 applicable law or agreed to in wr... |
"""
A top-level linear programming interface. Currently this interface solves
linear programming problems via the Simplex and Interior-Point methods.
.. versionadded:: 0.15.0
Functions
---------
.. autosummary::
:toctree: generated/
linprog
linprog_verbose_callback
linprog_terse_callback
"""
import ... |
"""show_lag.py
supported commands:
* show lacp system-id
* show bundle
* show bundle <interface>
* show bundle reasons
* show bundle <interface> reasons
* show lacp
* show lacp <interface>
"""
# Python
import re
# Metaparser
from genie.metaparser import MetaParser
from ge... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Author: <NAME>
# Created: 25/06/2009
#
import os
import re
import copy
from array import array
from ..common import *
from gaps import gappify, deGappify, length_ungapped, isGap, Gappifier
def _entryIsMaster(entry):
t = entry.type
return t == "structure" or t ==... |
##
## controlpanels.py - part of wxfalsecolor
##
## $Id$
## $URL$
import os
import wx
import wx.lib.foldpanelbar as fpb
# work around for bug in some new wxPython versions
if not 'FPB_DEFAULT_STYLE' in dir(fpb):
fpb.FPB_DEFAULT_STYLE = fpb.FPB_VERTICAL
import wx.lib.buttons as buttons
class BaseControlPanel(wx.... |
from django.conf import settings
from django.utils import translation
from django.utils.http import urlsafe_base64_decode
from django.utils.translation import ugettext
import colorgram
from elasticsearch_dsl import Q, query
from rest_framework import serializers
from rest_framework.filters import BaseFilterBackend
fr... |
import logging
import re
from collections import defaultdict
from . import Analysis, register_analysis
from ..knowledge_base import KnowledgeBase
from .. import SIM_PROCEDURES
from ..codenode import HookNode
from ..sim_variable import SimConstantVariable, SimRegisterVariable, SimMemoryVariable, SimStackVariable
l =... |
"""
Implements custom ufunc dispatch mechanism for non-CPU devices.
"""
from __future__ import print_function, absolute_import
import operator
import warnings
from functools import reduce
import numpy as np
from numba.utils import longint, OrderedDict
from numba.utils import IS_PY3
from numba.npyufunc.ufuncbuilder i... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The Index class can use several implementations as its
engine. Any implementation should implement the following:
__init__(data, row_index) : initialize index based on key/row list pairs
add(key, row) -> None : add (key, row) to existing data
remove(... |
#!/usr/bin/env python
'''
This module implements a simple and naive Gramps XML file (.gramps) parser.
Author: <NAME>
'''
from __future__ import unicode_literals
from future.builtins import str
import datetime
import dateutil.parser
import gzip
import logging
try:
from xml.etree import cElementTree as etree
exce... |
__copyright__ = "Copyright (C) 2018 <NAME>"
__license__ = """
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, mer... |
"""
Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You
may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompany... |
"""
Implementation of the method proposed in the paper:
'Adversarial Attacks on Neural Networks for Graph Data'
by <NAME>, <NAME> and <NAME>,
published at SIGKDD'18, August 2018, London, UK
Copyright (C) 2018
<NAME>
Technical University of Munich
"""
import numpy as np
import scipy.sparse as sp
from nettack import ut... |
from typing import ForwardRef, Tuple
from deepspeed.runtime.activation_checkpointing import checkpointing
from deepspeed.runtime.pipe.module import LayerSpec, PipelineModule
from transformers.modeling_utils import PreTrainedModel
from transformers.models.auto.configuration_auto import model_type_to_module_name
from tra... |
#!/usr/bin/env python
# Copyright (c) 2019 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Summary of useful helper functions for scenarios
"""
import math
import shapely.geometry
import shapely.affinity
import numpy as np
... |
#!/usr/bin/python3
# Copyright 2018 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_vk_internal_shaders.py:
# Code generation for internal Vulkan shaders. Should be run when an internal
# shader program is ch... |
"""Unaligned Packed Encoding Rules (UPER) codec.
"""
import logging
import string
from . import EncodeError
from . import DecodeError
from . import per
from .per import integer_as_number_of_bits
from .per import CLASS_PRIO
from .per import PermittedAlphabet
from .per import Encoder
from .per import Type
from .per im... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 a... |
#
# 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, software
# ... |
import pyfastnoisesimd.extension as ext
import concurrent.futures as cf
import numpy as np
from enum import Enum
_MIN_CHUNK_SIZE = 8192
def empty_aligned(shape, dtype=np.float32, n_byte=ext.SIMD_ALIGNMENT):
"""
Provides an memory-aligned array for use with SIMD accelerated instructions.
Should b... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import os
import time
import face_recognition as fr
import cv2
import numpy
import matplotlib.pyplot as plt
from PIL import ImageFont, ImageDraw, Image
class RecButton:
r"""
This class is used to draw a button on the video loop of opencv. This class was created to make the drawing
of buttons easier and mo... |
#!/usr/bin/env python
"""GRR specific AFF4 objects."""
import re
import time
import logging
from grr.lib import access_control
from grr.lib import aff4
from grr.lib import flow
from grr.lib import queue_manager
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib import utils
from grr.lib.aff4_obj... |
"""
The is the experimental framework associated with the Roam blog post
'Prescription-based prediction': URL
"""
from collections import Counter
from colour import Color
import json
import matplotlib.pyplot as plt
import numpy as np
from operator import itemgetter
import pandas as pd
from scipy import stats
import six... |
# -*- coding: utf-8 -*-
import json
import attr
import jinja2
import typing
import requests
from pprint import pprint
from pathlib_mate import PathCls as Path
from collections import OrderedDict
_ = pprint
here = Path(__file__).parent
# --- Spec file data handling
spec_file = here.parent.parent.append_parts("cft-s... |
import os
import sys
import time
import shutil
import json
import argparse
import numpy as np
from PIL import Image
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import figure
from skimage import io
import cv2
import torch
import torc... |
#!/usr/bin/env python3
"""
This module contains the make-toc function which tries to create a
valid table of contents file for SE projects.
Strictly speaking, the generate_toc() function should be a class member of SeEpub. But
the function is very big and it makes editing easier to put in a separate file.
"""
from en... |
#!/usr/bin/env python3
# tab-width:4
# pylint: disable=missing-docstring
# MIT License
# https://github.com/jakeogh/dnsgate/blob/master/LICENSE
#
# "psl domain" is "Public Second Level domain"
# extracted using https://publicsuffix.org/
# essentially this is the first level at which
# the public could register domains... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.