text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
from optparse import OptionParser, make_option
import os, sys, logging
import dbus, dbus.service, dbus.mainloop.glib
from gi.repository import GLib
mainloop = None
BUF_SIZE = 1024
HSP_AG_UUID = '00001112-0000-1000-8000-00805f9b34fb'
HFP_AG_UUID = '0000111f-0000-1000-8000-00805f9b34fb'
HF_NREC... |
"""Sensor for displaying the number of result from Flume."""
from datetime import timedelta
import logging
from numbers import Number
from pyflume import FlumeData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.config_entries import SOURCE_IMPORT
from homeassis... |
import numpy as np
from numpy import pi, exp
from scipy.special import gamma as gamma_func
from scipy.spatial import distance
class Distribution:
_parameter_names = ''
multi = False
"""Base probability distribution class"""
def __init__(self, **kwargs):
pass
@property
def rvs(self):
... |
#! /Library/Frameworks/Python.framework/Versions/2.7/bin/python
docstr = """
Polyjuice
Usage:
polyjuice.py (-h | --help)
polyjuice.py [-vz] (<input_path> <output_path>) [<config_file>]
polyjuice.py [-vzc] [<config_file>]
Options:
-h --help Show this message and exit
-z --zip ... |
# Discord Imports
import discord
from discord.ext import commands
# Other Imports
import random
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.db = bot.db
self.START_BAL = 250
@commands.command()
async def shop(self, ctx):
e = discord.Embed(... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
import os
import numpy as np
import pytest
from napari import Viewer, layers
from napari._tests.utils import (
add_layer_by_type,
check_view_transform_consistency,
check_viewer_functioning,
layer_test_data,
)
from napari.utils._tests.test_naming import eval_with_filename
def test_viewer(make_test_vi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, <NAME>
# Written by <NAME> <<EMAIL>>
# Based on pkgng module written by bleader <<EMAIL>>
# that was based on pkgin module written by <NAME> <shaun.zinck at gmail.com>
# that was based on pacman module written by Afterburn <https://github.com/afterburn>
# that was ... |
# Copyright 2020 Xanadu Quantum Technologies 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 agre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 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-... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import windtools.util as util
class Weibull(object):
def __init__(self, data, ws_field='ws', wd_field='wd', wd_bin_size=30, ws_bin_size=1, prepare_data=True):
self.data = pd.DataFrame(data)
self.dat... |
"""
inheritance-diagram:: dfo.optimizer.direct
:parts: 1
"""
from misc.debug import DbgMsgOut, DbgMsg
from .base import BoxConstrainedOptimizer
from numpy import max, min, abs, array
import numpy as np
import heapq
__all__ = ['Cube', 'DIRECT']
class Cube(object):
def __init__(self, x, f, depth):
se... |
import argparse
import atexit
import crc16
import serial
import sys
import time
import threading
import traceback
magicpacket = [0xde, 0xad, 0xbe, 0xef]
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", help="Serial port name")
parser.add_argument("-b", "--baud", help="Baud rate for serial port",... |
import base64
import six
from google.protobuf.message import Message
from google.protobuf.descriptor import FieldDescriptor
__all__ = ["protobuf_to_dict", "TYPE_CALLABLE_MAP", "dict_to_protobuf",
"REVERSE_TYPE_CALLABLE_MAP"]
EXTENSION_CONTAINER = '___X'
TYPE_CALLABLE_MAP = {
Field... |
import time
import cv2
import numpy as np
from PIL import ImageGrab
import win32gui
import win32con
import win32api
import win32com, win32com.client
import re
from playsound import playsound
import jstyleson as json
from os import path
import sys
from collections import deque
import builtins as __builtin__
from datetim... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.trial import unittest
from twisted.news import database
from twisted.news import nntp
from twisted.protocols import loopback
from twisted.test import proto_helpers
ALL_GROUPS = ('alt.test.nntp', 0, 1, 'y'),
GROUP = ('0', '1', '0', 'a... |
"""
Simple Q-Learning
=================
This module provides a basic implementation of the DQN algorithm without any
optimizations.
This file defines the distributed Trainer class for the Simple Q algorithm.
See `simple_q_[tf|torch]_policy.py` for the definition of the policy loss.
"""
import logging
from typing imp... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from __future__ import absolute_i... |
__author__ = '<NAME>'
import logging
import cv2
import numpy
import sys
from combining_classifications import combine_majority_vote, combine_mean_rule, combine_minimum_rule
from loading_images import load_face_vectors_from_disk, extract_color_channels
from pca import PCA
from plotting import plot_results
def main(... |
"""
Helioviewer Client tests
"""
import os
import urllib
from collections import OrderedDict
import pytest
import sunpy
import sunpy.map
from sunpy.net.helioviewer import HelioviewerClient
from sunpy.tests.helpers import figure_test, skip_glymur
@pytest.fixture(scope="function")
@pytest.mark.remote_data
def client(... |
import mmcv
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from .recall import eval_recalls
def coco_eval(result_files, result_types, coco, max_dets=(100, 300, 1000)):
for res_type in result_types:
assert res_type in [
'proposal', 'pr... |
import json
import pytest
import grpclib.const
import grpclib.server
from grpclib.client import UnaryUnaryMethod
from grpclib.events import _DispatchServerEvents
from grpclib.exceptions import GRPCError
from grpclib.encoding.base import CodecBase
from grpclib.encoding.proto import ProtoCodec
from conn import Client... |
#
# grid_spline.py
#
# Code for one-dimensional cubic splines on a
# uniform grid, including analytic slope, curvature,
# and extremum evaluation.
#
# Most convenient interface is via GridSpline class,
# which encapsulates the low-level routines.
#
# <NAME>, <NAME>, 2010-2014
#
import numpy as n
def tri_diag(a, b, c,... |
from matrixstore.db import get_db
def simplify_bnf_codes(bnf_codes):
"""Given list of BNF codes, return list of BNF prefixes for BNF subsections such
that:
1. every BNF code that belongs to one of these prefixes is in the original list,
2. every code in the original list belongs to exactly on... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from future.utils import text_to_native_str
import logging
import smtplib
import socket
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text i... |
# -*- coding: utf-8 -*-
'''
Watch files and translate the changes into salt events
:depends: - pyinotify Python module >= 0.9.5
:Caution: Using generic mask options like open, access, ignored, and
closed_nowrite with reactors can easily cause the reactor
to loop on itself.
'''
# Import Py... |
import json
import random
import sys
import os
import getopt
from action_batches import create_action_batch, check_until_completed
from time import sleep
import csv
import meraki
dashboard = meraki.DashboardAPI()
def check_batch_completion(org,batch_id):
counter = 0
while True:
batch = dashboard.organ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import get_user_model
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers imp... |
# Generated by Selenium IDE
from operator import index
import time
import json
import base64
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.sup... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: <NAME> <<EMAIL>>, <<EMAIL>>
# author: <NAME> <<EMAIL>>
import json
import urllib.request
from urllib.parse import urlparse
from collections import OrderedDict
import boto3
import tabulate
from ruamel.yaml import YAML
def getTemplateText(file_url):
try:
... |
from typing import List, Tuple, Union, Any
import numpy as np
from collections import defaultdict
import itertools
import matplotlib.pyplot as plt
T_untokenized = Union[List[str], Tuple[List[str], List[Any]]]
def untokenize(raw: str, tokens: List[str],
return_mask: bool = False,
toke... |
import os
import shutil
from zipfile import ZipFile
from flask import flash
import webapp.auth.user_data as user_data
from webapp.home.load_data_table import get_md5_hash
from webapp.home.metapype_client import list_files_in_dir
def check_ezeml_manifest(zipfile_name):
zip_object = ZipFile(zipfile_name, 'r')
... |
import os
import struct
import numpy as np
import torch
import torch.utils.data
from functools import lru_cache
def read_longs(f, n):
a = np.empty(n, dtype=np.int64)
f.readinto(a)
return a
def write_longs(f, a):
f.write(np.array(a, dtype=np.int64))
dtypes = {
1: np.uint8,
2: np.int8,
3... |
import os
import glob
import importlib
import logging
from six import string_types
from jinja2 import DictLoader
import jsonschema
import nbconvert # noqa: F401
from ipypublish.utils import (
pathlib,
handle_error,
get_module_path,
read_file_from_directory,
read_file_from_module,
)
from ipypublis... |
#!/usr/bin/env python3
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# Copyright (c) 2019 Gunakar Pvt Ltd
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
# * Redistributions of source code must retain the ... |
"""
Copyright (c) 2018-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
# Lint as: python3
# 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
# -*- coding: utf-8 -*-
"""
Unit tests for analytics logic in framework/analytics/__init__.py
"""
import re
import unittest
import mock
import pytest
from django.utils import timezone
from nose.tools import * # flake8: noqa (PEP8 asserts)
from flask import Flask
from datetime import datetime
from addons.osfstorage... |
import hashlib
import logging
from pathlib import Path
from urllib import request
import numpy as np
import pytest
from jfibsem_dat.read import HEADER_LENGTH, parse_metadata
logger = logging.getLogger(__name__)
TEST_DIR = Path(__file__).resolve().parent
FIXTURE_DIR = TEST_DIR / "fixtures"
BLOCKSIZE = 2**20
EXAMPLE... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import datetime
import logging
import hashlib
import hmac
import json
from django.template import Library
from django.conf import settings
register = Library()
log = logging.getLogger(__name__)
INTERCOM_APPID =... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
from collections import OrderedDict
from torch.autograd import Variable
from options.test_options import TestOptions
from models.models import create_model
from models.mapping_model import Pix2PixHDModel_Mapping
import util.util as util... |
#!/usr/bin/python
"""
This module provides high-level wrapper functions for bluepy bluetooth handling of DashAgents.
It exposes several functions that can be used to find nearby devices, pair with them and communicate the status and data of DashAgents to the shelve database.
It also exposes several mock versions of th... |
import shlex
import aiohttp
import uvloop
import asyncio
import discord
import logging
import argparse
import commands
import datetime
from cmd_manager import dispatcher
from config import config, help_text
from cmd_manager.bot_args import parser, HelpException, UnkownCommandException
from handle_messages import privat... |
# 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 t... |
from __future__ import division
import struct
import zlib
from PIL import Image
import gameduino2.base
import gameduino2.registers as reg
from gameduino2 import convert
try:
# noinspection PyUnresolvedReferences,PyCompatibility
from StringIO import StringIO # Python 2
except ImportError:
from io import... |
import re
from cli.export import api_to_dict
def _cli_to_schema(
api_dict,
target,
):
pod_api = None
for d in api_dict['methods']:
if d['name'] == target:
pod_api = d['options']
break
_schema = {
'properties': {},
'required': [],
}
for p ... |
from metagov.core.utils import SaferDraft7Validator
plugin_registry = {}
class Parameters:
def __init__(self, values={}, schema=None):
if schema:
from metagov.core.utils import validate_and_fill_defaults
validate_and_fill_defaults(values, schema)
for k, v in values.items... |
import sys
import time
import numpy as np
from gym.spaces.discrete import Discrete
from tianshou.data import Batch
from tianshou.env import DummyVectorEnv, RayVectorEnv, ShmemVectorEnv, SubprocVectorEnv
if __name__ == '__main__':
from env import MyTestEnv, NXEnv
else: # pytest
from test.base.env import MyTe... |
##########################################
# File: util.py
# Author: <NAME>
# Co-Author: <NAME>
# Last modified: Jan 17, 2017
##########################################
import copy
from PIL import Image, ImageDraw
# Debug echo flag.
DEBUG = False
# True represents light pixels and Fal... |
"""
Plotting convenience functions.
"""
from math import ceil
import ipywidgets as widgets
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from model_base import get_ext_input
# define basics
prop_cycle = plt.rcParams["axes.prop_cycle"]
colors = prop_cycle.by_key()["color"]... |
import logging
import time
log = logging.getLogger(__name__)
TEST_DIR = {
"v2": {
"script": "/ceph-qe-scripts/rgw/v2/tests/s3_swift/",
"lib": "/ceph-qe-scripts/rgw/v2/lib/",
"config": "/ceph-qe-scripts/rgw/v2/tests/s3_swift/multisite_configs/",
}
}
def run(**kw):
log.info("Runnin... |
import os
import sys
import random
import itertools
import colorsys
import numpy as np
from skimage.measure import find_contours
import matplotlib.pyplot as plt
from matplotlib import patches, lines
from matplotlib.patches import Polygon
# import IPython.display
def random_colors(N, bright=True):
'''
Generat... |
## test_attack.py -- sample code to test attack procedure
##
## Copyright (C) 2016, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import tensorflow as tf
import numpy as np
import time
import random
import argparse
from cv2 import i... |
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import random
def print_classification_reports(test_Accuracies , test_Losses , hidden_units , epochs , batches , learning_rates , test_set , test_labels , predictions ):
for i in range(0,len(test_Accuracies)): #ektypwsh olwn twn classi... |
#coding=utf-8
#created by SamLee 2018/10/14
import os
import sys
import json
import shlex
import apk_util
import walle_reader as reader
def writeSignIdValues(apkFile,idValues):
if idValues is None:
return
#24 = 8(size of block in bytes—same as the very first field (uint64)) + 16 (magic “APK Sig Block 4... |
"""Click customizations for Celery."""
import json
from collections import OrderedDict
from functools import update_wrapper
from pprint import pformat
import click
from click import ParamType
from kombu.utils.objects import cached_property
from celery._state import get_current_app
from celery.signals import user_prel... |
import sys
sys.path.append('..')
from utils import *
class Cascade:
# --------------------------
# Initiate Cascade
# --------------------------
def __init__(self, root_tweet_id, cascade_path, label=None):
self.file_id = root_tweet_id # For label.txt
self.root_tweet_id = root_tw... |
import json, geojson, requests
import random, os, sys, shutil
import GeodesignHub, ShapelyHelper, config
from shapely.geometry.base import BaseGeometry
from shapely.geometry import shape, mapping, shape, asShape
from shapely.geometry import MultiPolygon, MultiPoint, MultiLineString
from shapely.ops import unary_union
f... |
"""Tests for module `petibmpy.grid`."""
import copy
import numpy
import pathlib
import unittest
import petibmpy
class GridIOTestCase(unittest.TestCase):
"""Tests related to the I/O grid."""
def setUp(self):
"""Setup."""
self.x = numpy.sort(numpy.random.rand(5))
self.y = numpy.sort(n... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
import logging
import requests
import yaml
from bot.listeners import TelegramListener, AlertListener
from bot.protocol import SendExpedition
from ogame.game.const import Ship, CoordsType, Resource
from ogame.game.model import Coordinates
from ogame.util import find_unique
def parse_bot_config(config):
""" @retu... |
import copy
import json
from collections import defaultdict
from jsonschema import ValidationError
from trapi_model.base import TrapiBaseClass
from trapi_model.biolink.constants import get_biolink_entity
from trapi_model.exceptions import *
from reasoner_validator import validate
def merge_meta_knowledge_graphs(list... |
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.imputation.bayes_mi import BayesGaussMI, MI
from numpy.testing import assert_allclose
def test_pat():
x = np.asarray([[1, np.nan, 3], [np.nan, 2, np.nan], [3, np.nan, 0],
[np.nan, 1, np.nan], [3, 2, 1]])
... |
#! /usr/bin/env python
"""Extract and plot channel long profiles.
Plotting functions to extract and plot channel long profiles.
Call all three functions in sequence from the main code.
The functions will return the long profile nodes, return distances upstream of
those nodes, and plot the long profiles, respectively.... |
'''
We'll put utility functions here - timing decorators, exiting functions, and maths stuff are here atm.
<NAME>
28/10/2019
'''
#------------------------------------------------------------------
import time
from math import sqrt
import sys
from ast import literal_eval as lit
import random
from pathlib import Path
... |
#
# 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 us... |
import logging
from django.conf import settings
from django.contrib import auth
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exe... |
import random
class BayesNet:
def __init__(self):
self.variables = {}
self.letters = []
self.query = None
self.letters = None
def add_children(self, variable, parents):
# Adds variable to the children list of each parent
for parent in parents:
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2019 Bitcoin Association
# Distributed under the Open BSV software license, see the accompanying file LICENSE.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.mininode import *
from test_fram... |
from datetime import datetime
from pathlib import Path
import pytz
import json
import yaml
import pandas as pd
from sqlalchemy.dialects.postgresql import JSONB
from app import db
from sqlalchemy.orm import deferred
class GCMS_DataAccessLink(db.Model):
__tablename__ = 'gcmsDataAccessLink'
__table_args__ = (d... |
"""
Author: <NAME>
Copyright (c) 2019, <NAME>
All rights reserved.
Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights on this
computer program.
You can only use this computer program if you have closed a license agreement with MPG or you get the right to use
the c... |
"""
Convert tabular data from
Tabular Benchmarks for Joint Architecture and Hyperparameter Optimization
<NAME> <NAME>
https://arxiv.org/pdf/1905.04970.pdf.
"""
import urllib
import tarfile
from pathlib import Path
from typing import Optional
import pandas as pd
import numpy as np
import ast
import h5py
from syne_t... |
import nltk
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
import re
import string
from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory, ArrayDictionary, StopWordRemover
from Sastrawi.Stemmer.StemmerFactory import StemmerF... |
from functools import wraps
from typing import Callable, List, Optional, Tuple
from sanic.request import Request
from sanic_jwt_extended.exceptions import (
AccessDeniedError,
ConfigurationConflictError,
CSRFError,
FreshTokenRequiredError,
InvalidHeaderError,
NoAuthorizationError,
RevokedT... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import BCEWithLogitsLoss
class BCEWithWeights(BCEWithLogitsLoss):
def __init__(self, reduction="none", **kwargs):
super().__init__(reduction="none", **kwargs)
self._w_reduction = reduction
def forward(self, input... |
# Standard library imports
import json
import logging
# Third party imports
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.con... |
# 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
# d... |
# Description: Cog that houses owner-only commands (inspired by EvieePy)
import app_logger
import config
import discord
from datetime import datetime
from discord.ext import commands
from importlib import reload as importlib_reload
from typing import Optional
from utils import tools
logger = app_logger.get_logger(__... |
import asyncio
import filecmp
import logging
import os
import pickle
import tempfile
import warnings
import re
from asyncio import AbstractEventLoop
from pathlib import Path
from typing import Text, Any, Union, List, Type, Callable, TYPE_CHECKING, Pattern
import rasa.shared.constants
import rasa.shared.utils.io
if TY... |
"""AOC 2020 Day 19"""
import pathlib
import time
import re
TEST_INPUT = """0: 4 1 5
1: 2 3 | 3 2
2: 4 4 | 5 5
3: 4 5 | 5 4
4: "a"
5: "b"
ababbb
bababa
abbbab
aaabbb
aaaabbb"""
TEST_INPUT_2 = """42: 9 14 | 10 1
9: 14 27 | 1 26
10: 23 14 | 28 1
1: "a"
11: 42 31
5: 1 14 | 15 1
19: 14 1 | 14 14
12: 24 14 | 19 1
16: 15 ... |
import glob
import os
import pickle
import shlex
import tarfile
import tempfile
import threading
from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Union
import boto3
from redun.file import File
from redun.hashing import hash_stream
from redun.scheduler import Job
# Constants.
REDUN_PROG... |
import networkx as nx
from entity.entity import Graph, Node
from node2vec import Node2Vec
import numpy as np
from gensim.models.word2vec import Word2Vec
from flask import current_app
from sklearn.decomposition import PCA
from sklearn import manifold
from algorithm.search_community import PyLouvain
from algorithm.simila... |
# Copyright 2020 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
"""
Lecture 15: Linear Programming
------------------------------
Linear programming is a method of optimization,
in this case minimization, of a set of parameters.
The goal is to find a vector
x in R^n
where given a vector
c in R^n
you want to minimize the scalar
product of x and c, given by
inner_product(x, c)
... |
import glob
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
import fire
def _get_info_from_anaconda_info(info, split=":"):
info = info.strip("\n").replace(" ", "")
info_dict = {}
latest_key = ""
for line in info.splitlines():
if split in line:
... |
import json
import torch
import numpy as np
from typing import Optional
from datasets.arrow_dataset import Dataset
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from seq2seq.utils.dataset import DataTrainingArguments, normalize, serialize_schema
from seq2seq.utils.trainer import Seq2SeqTraine... |
import pygame
import os
import time
import random
pygame.font.init()
#Fenstergröße
WIDTH, HEIGHT = 750, 750
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Attack")
#Hintergrund
BG = pygame.transform.scale(pygame.image.load(os.path.join("assets","bg_02_h.png")),(WIDTH, HEIGH... |
import io
import csv
import json
import logging
import hashlib
from django.utils.html import escape
from dojo.models import Finding
logger = logging.getLogger(__name__)
class TwistlockCSVParser(object):
def get_field_from_row_or_default(self, row, column, default_value):
field = row[column]
if ... |
"""OctreeLevelInfo and OctreeLevel classes.
"""
import logging
import math
from typing import Dict, List, Optional
import numpy as np
from ....types import ArrayLike
from .octree_chunk import OctreeChunk, OctreeChunkGeom, OctreeLocation
from .octree_util import OctreeMetadata
LOGGER = logging.getLogger("napari.octre... |
# -*- coding: utf-8 -*-
from io import BytesIO, BufferedReader
from pytest import raises
from unittest.mock import Mock
from watson.di.container import IocContainer
from watson.events import types
from watson.http.messages import Request, Response
from watson.http import sessions
from watson.framework import controller... |
import matplotlib.pyplot as plt
import networkx as nx
class TreeNode(object):
def __init__(self, name, so_labels, st_predicate, score, subj_tracklet, obj_tracklet, duration):
self.name = name
self.so_labels = so_labels
self.score = score
self.id = '{}_{}_{}_{}_{}'.format(name, st_p... |
import json
import phonenumbers
from django import forms
from django.contrib import messages
from django.core import validators
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils import six
from django.utils... |
# Copyright (c) 2014, <NAME>. Please see the AUTHORS file for details.
# All rights reserved. Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.)
import sublime
import sublime_plugin
from subprocess import check_output
from subprocess import Popen
import glob
import js... |
# Copyright 1999-2020 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... |
import matplotlib.pyplot as plt
import os
import pandas as pd
import geopandas as gpd
import numpy as np
import networkx as nx
def map_setup(n_communities, area, small_network=False):
# directory of data
areas = ['London', 'UK']
if area not in areas:
raise ValueError("Invalid area name. Expect... |
"""Bouncing Lines, by <NAME> <EMAIL>
A bouncing line animation. Press Ctrl-C to stop.
NOTE: Do not resize the terminal window while this program is running."""
__version__ = 1
import sys, random, time
try:
import bext
except ImportError:
print('''This program requires the bext module, which you can
install ... |
import sys
import unittest
from random import randint
import numpy as np
import crocoddyl
import pinocchio
from crocoddyl.utils import DDPDerived
class SolverAbstractTestCase(unittest.TestCase):
MODEL = None
SOLVER = None
SOLVER_DER = None
def setUp(self):
# Set up the solvers
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.