text stringlengths 3.07k 22.1k |
|---|
import datetime
import sys
import os
import numpy as np
import nltk
nltk.download('punkt')
from nltk.tokenize import sent_tokenize
import matplotlib.pyplot as plt
import pandas as pd
def average_len_reddit_postings(reddit_data):
"""
calculate the average length of reddit postings
"""
df = reddit_data.... |
"""
For fetching and scanning URLs from ICANN CZDS
"""
import asyncio
import json
import zlib
from collections.abc import AsyncIterator
from dotenv import dotenv_values
from modules.utils.feeds import generate_hostname_expressions
from modules.utils.http_requests import get_async, get_async_stream, post_async
from mo... |
from nltk.tree import Tree
import numpy as np
import pytest
from sklearn.metrics import accuracy_score
from sklearn.model_selection import RandomizedSearchCV, cross_validate
import tempfile
import torch
import torch.nn as nn
import utils
from test_torch_model_base import PARAMS_WITH_TEST_VALUES as BASE_PARAM... |
"""Classes and utilities for mutliple alignments from the EPO pipeline"""
from __future__ import with_statement
import logging, re, cPickle, os
from collections import namedtuple
from itertools import imap
from _epo import rem_dash, fastLoadChain, bed_union, cummulative_intervals
log = logging.getLogger(__name__)... |
import argparse
#from typing_extensions import Required
import numpy as np
import torch
import torch.nn as nn
# from tensorboardX import SummaryWriter
# from time import time
# from torch.utils.data import DataLoader, Subset
import torch.optim as optim
from tqdm import tqdm
import os
import random
import sys
import l... |
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
##############################################################... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in complianc... |
# -*- coding: utf8 -*-
# Copyright (C) 2015 - <NAME> <<EMAIL>>
# This program is Free Software see LICENSE file for details
import urllib
import xbmc
import xbmcvfs
import os
from Utils import *
from PIL import Image, ImageFilter, ImageOps
THUMBS_CACHE_PATH = xbmc.translatePath("special://profile/Thumbnails/Video")
... |
import numpy as np
import pandas as pd
import statsmodels.api as sm
from ..univariate.metrics import t_value
__eps = np.finfo(np.float32).eps
def fit_robust_lm(x: np.ndarray, y: np.ndarray) -> list:
"""
Fits a robust linear model between Numpy vectors `x` and `y`, with an
intercept. Returns a list: [int... |
"""
Tabs management module
Provide a class holding the current tabs of the application.
Supported list modification operations:
- Appending a tab
- Deleting a tab (and going back to the previous one)
- Inserting a tab from a position to another
- Replacing the whole tab list with another (used for rear... |
# -*- coding: utf-8 -*-
"""ConfusionMatrix handlers."""
from __future__ import division
from .pycm_class_func import class_statistics
from .pycm_error import pycmVectorError, pycmMatrixError
from .pycm_overall_func import overall_statistics
from .pycm_util import *
from .pycm_param import *
import json
import types
imp... |
import cert_scanner.util.certificate_scanner_utility as \
certificate_scanner_utility
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
"""
Contains all the code that either derives new fields, filters records
or aggregates them.
"""
def enhance_certificates(configuration_manag... |
# The MIT License
#
# Copyright (c) 2009-2011 the bpython authors.
# Copyright (c) 2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitat... |
import argparse
import os
import pickle
import random
import time
import matplotlib.pyplot as plt
import numpy as np
import ot
import pandas as pd
import pyabc
import utils
from scipy.stats import invgamma
np.random.seed(1)
random.seed(1)
def distance_fn(type, k=2, m=32):
if type == "bombOT":
return l... |
import json
from django.views.decorators.http import require_http_methods
from django.shortcuts import redirect, render
from django.http import HttpResponseBadRequest
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.db import transaction
fro... |
import functools
import math
import random
from dataclasses import dataclass
from typing import Dict, List, Tuple
import geometry_msgs.msg
import rospy
import std_msgs
from simulation_brain_link.msg import State as StateEstimationMsg
from simulation_groundtruth.srv import LaneSrv, SectionSrv
from tf2_msgs.msg import T... |
import typing
import discord
from enum import IntEnum
from discord.ext import commands
from . import http
from . import error
class SlashContext:
"""
Context of the slash command.\n
Kinda similar with discord.ext.commands.Context.
.. warning::
Do not manually init this model.
:ivar name:... |
import pdb
from functools import partial
import os.path
from pathlib import Path
DBG = pdb.set_trace
tmpdir = Path("/var/tmp/")
logger_level = 2
DO_MP = True # use multiprocessing
DO_SIMPLIFY = True # simplify results, e.g., removing weaker invariants
DO_FILTER = True # remove ieqs and min/max terms that unlikely ... |
import time
import numpy as np
import pandas as pd
import os
import PIL
from collections import OrderedDict
from finch import FINCH
import cv2
import json
import argparse
import pickle
import copy
import gc
import torch
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from ti... |
# Python framework
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import re, os, os.path, random
from pprint import pprint
# Plex native
import Media, VideoFiles, Stack, Utils
# Local package
from Constants import *
from Matching import *
from StringUtils import *
from Teams import *
from Metad... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import discord
import contextlib
from discord.ext import commands, tasks
from discord import Interaction, app_commands, ui
from typing import Literal
# Local
from utils.valorant.useful import get_season_by_content
from utils.valorant.embed import Embed, Generate_Embed
from utils.valorant.view import TwoFA_UI, BaseBun... |
# Copyright 2020 <NAME>
import importlib
import json
import multiprocessing
from pbr.version import VersionInfo
import random
import re
import requests
import secrets
import string
import sys
import time
import traceback
from oslo_concurrency import processutils
from shakenfist import db
from shakenfist.config impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
# Import `matplotlib` JIT
# import matplotlib.pyplot as plt
global plt
plt = None
# __TensorFlow logging level__
# 0 = all messages are logged (default behavior)
# 1 = INFO messages are not printed
# 2 = INFO and WARNING messages are not p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, <NAME>
# Copyright: (c) 2019, <NAME> (@Andersson007) <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_... |
"""
Created on Jan 25, 2016
@author: xiao
"""
import collections
import logging
from builtins import range
from itertools import chain
import numpy as np
from pdfminer.layout import LTAnno
from pdftotree.utils.pdf.vector_utils import inside, intersect
def traverse_layout(root, callback):
"""
Tree walker an... |
import json
import os
import pickle
import ulmo
import param
import pandas as pd
import geopandas as gpd
from shapely.geometry import box, Point
from quest import util
reserved_catalog_entry_fields = [
'name',
'service',
'service_id',
'publisher_id',
'display_name',
'description',
'reser... |
import numpy as np
from .indep_sim import SIMULATIONS
def _2samp_rotate(sim, x, y, p, degree=90, pow_type="samp"):
"""Generate an independence simulation, rotate it to produce another."""
angle = np.radians(degree)
data = np.hstack([x, y])
same_shape = [
"joint_normal",
"logarithmic",... |
import pygame
import os
import time
import random
pygame.font.init()
WIDTH, HEIGHT = 1280, 720
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")
# Load images
RED_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png"))
GREEN_SPACE_SHIP = pygame.imag... |
#!/usr/bin/env python
import os
import os.path
import json
import logging
from datetime import datetime
import mimetypes
import subprocess
import re
import copy
import six
from six.moves.urllib.parse import urlparse
import click
STATIC_DATA_ROOT_FOLDER = 'static-data' # Root folder on S3
@click.group(context_set... |
import requests
import copy
import os
import json
from urllib.parse import urlparse
from webfetch.fsutils import Fs, Action, Exists, Make, MakeDirs, View
from webfetch.identifier import Identify, IdentifyUri, IdentifyHead, IdentifyBase
""" GDWF? Global Data Web Fetcher? Version -= 2.0 =- """
class Version(object):
... |
import time
import struct
import datetime
import requests
import pickle
import xml.etree.ElementTree as ET
import math
def ToSigned(Num, signedbitB):
if signedbitB > 0:
# positive
if ( Num%(0x01<<signedbitB)/(0x01<<(signedbitB-1)) ) < 1:
return Num%(0x01<<signedbitB-1)
# negati... |
import time
import pathlib
import logging as lg
import numpy as np
lg.basicConfig(
level=lg.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%H:%M:%S")
_logger = lg.getLogger(__name__)
class TrackTypeDetermine:
type_names = (None, "vert", "horz", "upright", "downright", "d... |
import atexit
import http.client
import json
import re
import socket
import threading
import urllib.parse
from weakref import WeakValueDictionary
from .download_lt import download_lt
from .language_tag import LanguageTag
from .match import Match
from .utils import *
DEBUG_MODE = False
# Keep track of running server ... |
import numpy as np
# np.random.seed(2)
# solution = [w1, w2, ..., wn]
class Individual(object): # create individual
def __init__(self, w_shape):
self.solution = np.random.randn(w_shape[0], w_shape[1])
self.fitness = 0
# train(x) -> cal_error(y_hat) -> fitness or cost(y_hat) -> update_with_ga(y_hat... |
from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from inspect import signature
import copy
from module.recurrent_units import RTNRnn
from module.weight_init import weight_init, manual_init
def model_config(func):
def set_config(*args, **kwargs)... |
import logging
import typing
import torch
import torch.nn as nn
import torch.nn.functional as F
from .modeling_utils import ProteinConfig
from .modeling_utils import ProteinModel
from .modeling_utils import ValuePredictionHead
from .modeling_utils import SequenceClassificationHead
from .modeling_utils import SequenceT... |
# .____ ___________________
# | | \_ _____/\______ \ ______
# | | | __)_ | | \ / ___/
# | |___ | \ | ` \\___ \
# |_______ \/_______ //_______ /____ >
# \/ \/ \/ \/
"""
Signifier module to manage communication with the Arduino LED system.... |
#!/usr/bin/env python
import autopy3
import math
import time
import sys
pos = autopy3.mouse.get_pos()
xx = pos[0]
yy = pos[1]
xx1 = pos[0]
yy1 = pos[1]
# = [,] , [,] , [,] , [,] , [,] , [,] , [,] , [,] , [,] , [,] , [,]
A = [3,22] , [10,0] , [18,22] , [15,14] , [4,14]
B = [3,1] , [11,1] , [16,5] , [12,10] , [3,11] ... |
import cv2
import json
from matplotlib import pyplot as plt
import numpy as np
import draw
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
# retrieve saved values
with open('trackbarValues.json') as json_file:
raw = json.load(json_file)
hsv_green = raw[str(3)] # green colour
lowerHSV_green = np.arr... |
#!/usr/bin/env python
# load libraries
from __future__ import print_function
import argparse
from openpyxl import load_workbook
import coloredlogs
import logging
import re
import couchdb
import numbers
import yaml
# global variables
WARNINGS = 0
NONNUMERIC = []
EMPTY = []
BADRIN = []
OUTCONC = []
OUTVOL = []
# Set u... |
# 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
# distributed under th... |
"""
Mask R-CNN
The main Mask R-CNN model implemenetation.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by <NAME>
"""
import os
import sys
import glob
import random
import math
import datetime
import itertools
import json
import re
import logging
from collections... |
#!/usr/bin/env python3
import subprocess
import requests
import socket
import json
import time
from tabulate import tabulate
import argparse
config = json.load(open("data/config.json"))
miners = json.load(open('data/miners.json'))
pools = json.load(open('data/pools.json'))
algos = json.load(open('data/algos.json'))
#... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from contextlib import contextmanager
import io
from os import path
import sys
from . import config
from .helpers import get_stream
from .resource import resource_exists
from .injectors import model_admin_py
indent = " " * 4
def create_model(blueprint_nam... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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... |
import multiprocessing
import os
import pickle
import tempfile
import time
import unittest
import uuid
from hypothesis import given
from hypothesis.strategies import text
try:
import pymongo
except ImportError:
pymongo = None
from chocolate import SQLiteConnection, MongoDBConnection, DataFrameConnection, Spa... |
import json
from unittest.mock import Mock
import django
import pytest
from django.db import models
from django.db.models import Manager
from ninja_schema import ModelSchema
def test_inheritance():
class ParentModel(models.Model):
parent_field = models.CharField()
class Meta:
app_la... |
"""``kedro.framework.project`` module provides utitlity to
configure a Kedro project and access its settings."""
# pylint: disable=redefined-outer-name,unused-argument,global-statement
import importlib
import logging.config
import operator
from collections.abc import MutableMapping
from typing import Any, Dict, Optiona... |
from numba import njit, boolean, int64, float64
from numba.experimental import jitclass
import numpy as np
from .utils import isin
@jitclass([
('value', float64[:]),
('sign', float64[:]),
('size', int64)
])
class signed:
def __init__(self, value, sign=None):
""" If sign is None, init from val... |
from os import environ, path, walk
from statistics import mean
from time import time
from typing import Dict, List
from flask import g, json, request, jsonify
from flask_cors import CORS
from app import app
import numpy as np
import os
import shutil
from preprocess import preprocess_darryl_V1
from rapidfuzz import fuz... |
import json
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
from src.deps.p... |
# 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 (t... |
# -*- coding: utf-8 -*-
"""Graph utilities."""
from io import open
from algorithms import *
from algorithms_distances import *
from collections import defaultdict
class Graph():
def __init__(self, d, is_directed, workers, bfs_workers = None, until_layer=None, in_degrees=None, ou... |
#!/usr/bin/env python3.6
"""Creates VGG16-based model with (optional) average pooling, and regularizers."""
# -- Third-party modules -- #
import keras_spiking
import numpy as np
import tensorflow as tf
# -- File info -- #
__author__ = '<NAME>'
__copyright__ = 'European Space Agency'
__contact__ = '<EMAIL>'
__version... |
#
# Copyright (c) 2019. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#
from enum import Enum
from typing import Union, Optional, List
from .geom import _geom
from .util import is_geo_data_regions, map_join_regions
from .._global_settings import has_gl... |
import os
from pathlib import Path
import shutil
import glob
import logging
import json
import random
import numpy as np
from tempfile import TemporaryDirectory
from collections import namedtuple
from tqdm import tqdm
import torch
from torch.utils.data import Dataset
from pytorch_transformers.modeling_utils import WEI... |
"""\
Helpers for build scripts under `scripts` directory (these are not build
rule templates for helping you write build rules).
"""
__all__ = [
'Builder',
'RuleIndex',
'find_default_path',
'find_input_path',
'get_build_image_rules',
'get_build_volume_rules',
'get_specify_app_rule',
'ge... |
#!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
import tempfile
from typing import List, Dict, Any
import venv # type: ignore
import yaml
def main():
parser = argparse.ArgumentParser(prog=__name__,
description='Builds and publishes Lambda layers... |
# 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... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
import copy
import time
from imageio import imwrite
from receptive_field import compute_rf_prototype
from helpers import makedir, find_high_activation_crop
# push each prototype to the nearest patch in the training set
def push_proto... |
"""This module contains the classes which pass on database functionality
Note on terminology:
In ixdat, we seek to use the following naming conventions:
`load` grabs *an object* from a database backend given its class or table name
and the name of the specific object desired (see DataBase.load)... |
"""Task definitions for machine translation tasks."""
import codecs
import collections
import math
import os
from typing import Iterable, List, Sequence, Type
from allennlp.data import Instance
from allennlp.data.token_indexers import SingleIdTokenIndexer
from allennlp.training.metrics import Average
from ..utils.dat... |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2019
import unittest
import unittest.mock
import sys
import os
import time
import requests
import random
from glob import glob
import json
from pathlib import Path
import re
import subprocess
from streamsx.build import BuildService
import xml.etree.ElementTr... |
# MIT License
#
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... |
from functools import reduce
from pathlib import Path
from tqdm import tqdm
from constants import FEATURE_MAP
import fire
import logging
import math
import numpy as np
import pandas as pd
logging.basicConfig(
filename='preprocess.logs',
filemode='a',
format='%(asctime)s [%(levelname)s] %(message)s',
... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 Salesforce and The HuggingFace Inc. team.
#
# 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.a... |
"""Bookmark-node manager.
The bookmark node manager supports requesting subsets of the bookmark
collection by URI components. This is useful for locating a node in the
database which needs to be updated when the user interface successfully
'visits' a node and needs to update the last-visited and last-modified
informa... |
import pygame
import random
# creating the data structure for pieces
# setting up global vars
# functions
# - create_grid
# - draw_grid
# - draw_window
# - rotating shape in main
# - setting up the main
"""
10 x 20 square grid
shapes: S, Z, I, O, J, L, T
represented in order by 0 - 6
"""
pygame.font.init()
# GLOBAL... |
import hoki.age_utils as au
import hoki.load as load
import pkg_resources
import numpy as np
import pandas as pd
import pytest
from hoki.utils.exceptions import HokiFatalError, HokiUserWarning, HokiFormatError
# Loading Data
data_path = pkg_resources.resource_filename('hoki', 'data')
hr_file = data_path + '/hrs-sin-i... |
"""
Configuration reader and defaults.
Author: <NAME> <<EMAIL>>
Copyright: NORDUnet (2011)
"""
import os
import configparser
from opennsa import constants as cnt
# defaults
DEFAULT_CONFIG_FILE = '/etc/opennsa.conf'
DEFAULT_LOG_FILE = '/var/log/opennsa.log'
DEFAULT_TLS = 'true'
DEFAULT_TOPOLOGY_FILE = '/usr/local/s... |
import copy
import shutil
from pathlib import Path
from typing import List, Dict, Text, Any, Tuple, Optional, Union
import rasa.shared.utils.io
import rasa.shared.utils.cli
from rasa.shared.constants import (
REQUIRED_SLOTS_KEY,
IGNORED_INTENTS,
)
from rasa.shared.core.constants import ACTIVE_LOOP, REQUESTED_S... |
#!/usr/bin/env python
"""mriqc_fit command line interface definition."""
import sys
from os.path import isfile, abspath
import warnings
import logging
from pkg_resources import resource_filename as pkgrf
import matplotlib
matplotlib.use("Agg")
try:
from sklearn.metrics.base import UndefinedMetricWarning
except I... |
from abc import ABC, abstractmethod
import random
from typing import Union
import numpy as np
from chunkflow.lib.bounding_boxes import BoundingBox, Cartesian
from .patch import Patch
from chunkflow.chunk import Chunk
from chunkflow.lib.synapses import Synapses
class AbstractGroundTruthSample(ABC):
def __init__... |
import sys
import subprocess
import re
from tabulate import tabulate
import textwrap
import warnings
import datetime as dt
import numpy as np
from scipy.interpolate import interp1d
from ._exceptions import InterfaceError, AdapterUnaccessibleError
from .utils import db2dbm, RealTimePlot, spin, rssi_to_colour_str
from .... |
import time
from psycopg2.extras import NumericRange
from pytest import mark
@mark.flaky(reruns=3)
def test_browse_matching(browser, scenario):
scenario.add_period(title="Ferienpass 2016")
for i in range(2):
scenario.add_activity(title=f"A {i}", state='accepted')
scenario.add_occasion(age=(0... |
import numpy as np
from knn import KNNs
def f1_score(real_labels, predicted_labels):
"""
Information on F1 score - https://en.wikipedia.org/wiki/F1_score
:param real_labels: List[int]
:param predicted_labels: List[int]
:return: float
"""
assert len(real_labels) == len(predicted_labels)
... |
import json
from decouple import config
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
import discord
from dotenv import load_dotenv
import passwordgen_program as PassGen
from main import UUIDFetch
from GamesAPI import GamesList as GamesAPI
from Session import MainProcess as Sess... |
import warnings
from collections import OrderedDict, defaultdict
from typing import (
Any,
Callable,
Collection,
DefaultDict,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
cast,
)
import torch
from torch import nn
import pystiche
from ..misc import build_deprec... |
#!/usr/bin/env python3
"""
/*******************************************************************************
* Ledger Nano S - Secure firmware
* (c) 2021 Ledger
*
* 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... |
#!/usr/bin/env python
# encoding: utf-8
"""
This module contains unit tests of the rmgpy.molecule.atomtype module.
"""
import unittest
import rmgpy.molecule
from rmgpy.molecule import atomtype, Molecule
from rmgpy.molecule.atomtype import AtomType, getAtomType
#######################################################... |
from itertools import chain, combinations
from time import time
import collections
from random import randint
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
... |
"""
Utility to manage a configuration fileand provide an easy way to modify it.
To use the configlib in your project, just create a file name `conf.py` awith the following code
import configlib
class Config(configlib.Config):
__config_path__ = 'my/path/to/the/config/file.json
# you can defin... |
"""
Sphinx plugin to run example scripts and create a gallery page.
Lightly modified from the seaborn project, which modified the mpld3 project.
"""
import os
import os.path as op
import re
import glob
import token
import tokenize
import shutil
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
... |
import argparse
import sys
from stix_shifter.stix_translation import stix_translation
from stix_shifter.stix_transmission import stix_transmission
from flask import Flask, request
from stix_shifter.utils.error_response import ErrorResponder
import json
import time
TRANSLATE = 'translate'
TRANSMIT = 'transmit'
EXECUTE ... |
#!/usr/bin/python
from optparse import OptionParser
import xml.etree.ElementTree as ET
from mininet.clean import cleanup
from mininet.net import Mininet
from mininet.log import lg, LEVELS, info, error, setLogLevel
from mininet.link import TCLink
from subprocess import PIPE
from seed_topo import build_seed_topo, star... |
"""
@author: <NAME>, <NAME>
@date: 20201019
@contact: <EMAIL>
"""
# based on:
# https://github.com/biubug6/Pytorch_Retinaface/blob/master/models/retinaface.py
import torch
import torch.nn as nn
import torchvision.models._utils as _utils
import torch.nn.functional as F
def conv_bn(inp, oup, stride=1, leaky=0):
r... |
import numpy as np
import networkx as nx
from random import shuffle
import igraph
def extract_attributes(G, attr=None):
"""
extract the matrix of given atributes from graph
:param G: [networkx graph object]
:param attr: [string] given attribute
:return: [ndarray] matrix of given attribute
"""... |
from __future__ import print_function, unicode_literals, with_statement, division
import binascii
import random
import string
from django.db.models import fields
from django.template.defaultfilters import slugify
from django.db import models
from django.core.serializers.json import DjangoJSONEncoder
try:
import j... |
import argparse
import torch
import torch_geometric.transforms as T
from torch_geometric.nn import GAE, VGAE
from utils import ARAPPI
from utils import PMESPEncoder,GcnEncoder,proteinEncoder,cross_validation_with_val_set
import os.path as osp
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
im... |
from functools import partial
import tensorflow as tf
import tensorflow_addons as tfa
import tensorflow_gan as tfgan
from tensorflow import keras
from tensorflow.keras import layers, losses, optimizers
IMG_SHAPE = (128, 128, 3)
LR = 0.0002
BATCH_SIZE = 12 or 8
EPOCHS_DECAY_THRESHOLD = 100
LAMBDA_A2B = 10.0
LAMBDA_... |
load(
"@bazel_tools//tools/build_defs/repo:utils.bzl",
"patch",
"read_netrc",
"update_attrs",
"use_netrc",
"workspace_and_buildfile",
)
load("@bazel_skylib//lib:versions.bzl", "versions")
NETRC_FORMAT = """
machine {hostname}
password {token}
"""
NETRC_ERROR = """
{path} file not found, pl... |
from __future__ import absolute_import
from past.builtins import basestring
import re
from ckan.common import _
import ckan.lib.navl.dictization_functions as df
from ckanext.fluent.validators import fluent_text
from ckan.common import config
import ckan.plugins.toolkit as toolkit
import ckan.logic.validators as validat... |
import os
import random
import cv2
import numpy as np
import torchvision.datasets as datasets
from PIL import Image
from torch.utils.data.dataset import Dataset
def rand(a=0, b=1):
return np.random.rand()*(b-a) + a
class FacenetDataset(Dataset):
def __init__(self, input_shape, dataset_path, ... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
import tkinter as tk
from tkinter import ttk
from urllib.parse import urlparse, urljoin
import time
import requests
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
import colorama
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome ... |
from sqlalchemy import create_engine, Column, Date, String, Integer, Float, exc, and_
from sqlalchemy.orm import Session, declarative_base
import requests
from datetime import datetime
from selectorlib import Extractor
import requests
from time import sleep
# Create an Extractor by reading from the YAML file
def scr... |
# coding=utf-8
from asdl.transition_system import TransitionSystem, GenTokenAction
try:
from cStringIO import StringIO
except:
from io import StringIO
from collections import Iterable
from asdl.asdl import *
from asdl.asdl_ast import RealizedField, AbstractSyntaxTree
def prolog_node_to_ast(grammar, prolog_t... |
from fastapi import APIRouter, Query, Response, Request, Body, Path
from typing import Optional, List
from .schema import *
from .examples import analysis_examples, index_analyze_examples
import json
api = APIRouter()
### Basic analyze index
@api.post("/_analyze",
status_code=200,
responses={
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.