text stringlengths 2 999k |
|---|
import setuptools
with open("README.md", "r") as fd:
long_description = fd.read()
with open("VERSION", "r") as fd:
version = fd.read().strip()
setuptools.setup(
name="expr",
version=version,
author="Julien Castiaux",
author_email="julien.castiaux@gmail.com",
description="A simple engine b... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news_skill.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Imp... |
from flask_socketio import Namespace
from Shared.Logger import Logger, LogVerbosity
from Shared.Threading import CustomThread
from Shared.Util import to_JSON
from Webserver.APIController import APIController, Request
class BaseWebsocketController(Namespace):
def __init__(self, namespace):
super().__init... |
import os
import sys
import re
import argparse
import pandas as pd
from utils import simplify_string_for_hdf5
parser = argparse.ArgumentParser(description='S-MultiXcan results processor.')
parser.add_argument('--smultixcan-file', required=True, type=str)
parser.add_argument('--smultixcan-file-pattern', required=True... |
"""Forest Fire Sim, by Al Sweigart al@inventwithpython.com
A simulation of wildfires spreading in a forest. Press Ctrl-C to stop.
Inspired by Nicky Case's Emoji Sim http://ncase.me/simulating/model/
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: short, bext, simulation"""
__versi... |
from typing import Optional
from peas.consensus.block_record import BlockRecord
from peas.consensus.constants import ConsensusConstants
from peas.util.ints import uint8, uint32
def calculate_deficit(
constants: ConsensusConstants,
height: uint32,
prev_b: Optional[BlockRecord],
overflow: bool,
num... |
# coding: utf-8
""" Test cases for .hist method """
import numpy as np
from numpy.random import randn
import pytest
import pandas.util._test_decorators as td
from pandas import DataFrame, Series
from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
import pandas.util.testing as tm
@td.skip_if_n... |
import math
import copy
from functools import reduce
# return True if p1 won the round
def simulate_round():
return True
def play_game(p1, p2):
prev = []
while len(p1) != 0 and len(p2) != 0:
# p1 instantly wins
if (p1, p2) in prev:
return True, p1
prev += [(p1, p2)]
c1... |
import os
import torch
from tqdm import tqdm
from os.path import sep as P_SEP
from search.rm_search.constants import *
from search.rm_search.utils.model_utils import model_load, model_save
def write_line_to_file(s, f_path="progress.txt", new_file=False, verbose=False):
code = "w" if new_file else "a"
if verb... |
# ABC071b
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
s = input()
for i in s:
# print(i)
alphabet = alphabet.replace(i, '')
print(alphabet[0] if len(alphabet) > 0 else 'None')
|
from __future__ import print_function
import datetime
import os
import shutil
import subprocess
import sys
from os.path import join
try:
from click.termui import secho
except ImportError:
warn = print
else:
def warn(text):
for line in text.splitlines():
secho(line, fg="white", bg="red"... |
import librosa
from librosa import display
import os
import scipy
import numpy as np
class Dataset:
def __init__(self, data_dir, upper_bound, lower_bound):
self.data_dir = data_dir
self.upper_bound = upper_bound
self.lower_bound = lower_bound
self.data = []
# Pre... |
from django.test import TestCase
from django.db import models
from django.utils import translation
from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg
from localized_fields.fields import LocalizedField
from localized_fields.value import LocalizedValue
from localized_fields.expressi... |
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitor
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_forecasting import TemporalFusionTransformer
from pytorch_forecasting.metrics import SMAPE, PoissonLoss, QuantileLoss
from data import dataloade... |
"""Hide/ show cursor on Windows."""
import ctypes
class _CursorInfo(ctypes.Structure):
_fields_ = [("size", ctypes.c_int),
("visible", ctypes.c_byte)]
def hide():
"""Hide cursor."""
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle(-11)
ctypes.windll.kernel32.GetCon... |
#
# 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... |
try:
import inspect
except:
try:
from _pydev_imps import _pydev_inspect as inspect
except:
import traceback;traceback.print_exc() #Ok, no inspect available (search will not work)
try:
import re
except:
try:
import sre as re # for older versions
except:
import tr... |
import pprint
from milecsa import Chain, config
#
# Print block state
#
def print_block(chain, block):
print("Block Id: ", block.block_id)
print("Version: ", block.version)
print("Timestamp: ", block.timestamp)
print("Trx count: ", block.transaction_count)
#
# Get bloc transaction
#
... |
#!/usr/bin/env python3
# Copyright (c) 2018-2020 The Bitnamicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the avoid_reuse and setwalletflag features."""
from test_framework.test_framework import Bitn... |
# Copyright 2021 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 typing import List, Tuple, Union, Optional
import numpy as np
import copy
from highway_env import utils
from highway_env.road.road import Road, LaneIndex, Route
from highway_env.utils import Vector
from highway_env.vehicle.kinematics import Vehicle
class ControlledVehicle(Vehicle):
"""
A vehicle piloted... |
# 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 applic... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from .. import mod1
from ..sub_package1 import sub_mod1
def func_parent():
print('from sub_mod2')
mod1.func()
def func_parent_sub():
print('from sub_mod2')
sub_mod1.func()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-26 19:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('profiles', '0008_change_num_security_que... |
#!/usr/bin/env python
#
# This is a module that gathers a list of serial ports including details on OSX
#
# code originally from https://github.com/makerbot/pyserial/tree/master/serial/tools
# with contributions from cibomahto, dgs3, FarMcKon, tedbrandston
# and modifications by cliechti, hoihu, hardkrash
#
# This file... |
""" define the IntervalIndex """
from functools import wraps
from operator import le, lt
import textwrap
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast
import numpy as np
from pandas._config import get_option
from pandas._libs import lib
from pandas._libs.interval import Interval, Interval... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
#!/usr/bin/python2.4
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''This file contains item formatters for resource_map_header and
resource_map_source files. A resource map is a mapping between re... |
# Copyright (C) Microsoft Corporation. All rights reserved.
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#!/usr/bin... |
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiv... |
import threading
import asyncio
@asyncio.coroutine
def hello():
print("Hello")
yield from asyncio.sleep(1)
print(" world")
async def new_hello():
print("Hello")
await asyncio.sleep(1)
print(" world")
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_... |
#!/usr/bin/env python3
#
# Copyright (C) 2019 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 applicabl... |
# Copyright 2016 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
import copy
import random
import argparse
topo_data = {}
parser = argparse.ArgumentParser("")
parser.add_argument("--k_port", type=int, default=4)
parser.add_argument("--loss_rate", type=float, default=0)
parser.add_argument("--base_delay", type=int, default=1000)
args = parser.parse_args()
loss_rate = args.loss_rate
... |
"""
Training a Binary Output model.
Impact Sounds = 1
Ambient SOunds = 0
"""
import sys
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelBinarizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from keras.models import Sequential
fro... |
# Copyright (c) Meta Platforms, Inc
import math
from typing import Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
from flowtorch.bijectors.fixed import Fixed
class LeakyReLU(Fixed):
# TODO: Setting the slope of Leaky ReLU as __init__ argument
def _forward(
self, x: torch.Ten... |
import itertools
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import torch
def randSelectBatch(input, num):
id_all = torch.randperm(input.size(0)).cuda()
id = id_all[:num]
return id, input[id]
def plot_confusion_matrix(path, cm, classes,
... |
import numpy as np
from numpy.lib.stride_tricks import as_strided
from paramz.transformations import Transformation, _lim_val, epsilon
def get_conv_1D(arr, win):
assert win>0
arr = arr.copy()
if win==1:
return arr
else:
return as_strided(arr, shape=(arr.shape[0]-win+1,win)+arr.shape[1:... |
import re
def run():
email_pattern = re.compile(r'^[a-z0-9_]+@[a-z]{1,10}\.[a-z]{2,10}$')
email = input('Enter an email: ').strip()
if email_pattern.match(email):
print('Valid')
else:
print('Invalid')
if __name__ == '__main__':
run()
|
# Copyright 2011 OpenStack Foundation
# 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 requ... |
import numpy as np
import theano.tensor as T
from numpy import linalg as la, random as rnd
import pymanopt
from pymanopt.manifolds import Sphere
from pymanopt.solvers import ConjugateGradient
def dominant_eigenvector(A):
"""
Returns the dominant eigenvector of the symmetric matrix A.
Note: For the same ... |
"""
Copyright (c) 2021 Dell Inc, or its subsidiaries.
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... |
import sys
inf = float("inf")
n, k, *xy = map(int, sys.stdin.read().split())
xy = list(zip(*[iter(xy)] * 2))
def minimize(xy, key):
xy = sorted(xy, key=lambda x: x[key])
x = []
y = []
for i in range(n):
x.append(xy[i][0])
y.append(xy[i][1])
if key == 1:
x,... |
# Copyright 2021-2022 NVIDIA 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 ... |
from collections import namedtuple
from enum import Enum
Algs = namedtuple('Algs', ['alg', 'enc'])
class AnonCryptAlg(Enum):
"""
Algorithms for anonymous encryption.
Attributes:
A256CBC_HS512_ECDH_ES_A256KW: AES256-CBC + HMAC-SHA512 with a 512 bit key content encryption,
ECDH-ES key agre... |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from pydiffmap import diffusion_map as dm
X=np.load('Data/4wells_traj.npy')
print(X.shape)
def DW1(x):
return 2.0 * (np.linalg.norm(x) ** 2 - 1.0) ** 2
def DW2(x):
return 4.0 * (np.linalg.norm(x) ** 2 - 1.0) ** 2
... |
from typing import Any
from django.db import models
class ModelWithMetadata(models.Model):
metadata = models.JSONField(
blank=True, null=True, default=dict, encoder="")
class Meta:
abstract = True
def get_value_from_private_metadata(self, key: str, default: Any = None) -> Any:
ret... |
# -*- coding: utf-8 -*-
"""
babel.core
~~~~~~~~~~
Core locale representation and locale data access.
:copyright: (c) 2013 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
import os
from babel import localedata
from babel._compat import pickle, string_types
from babel.plural im... |
import re
from enum import Enum
import utils
from test_shifts.base_shift import BaseShift
class BodyWeight(Enum):
MORBIDLY_OBESE = 1
OBESE = 2
OVERWEIGHT = 3
NORMAL = 4
UNDERWEIGHT = 5
NO_MENTION = 6
class BodyWeightShift(BaseShift):
weight_mentions = {BodyWeight.MORBIDLY_OBESE: ["morbi... |
"""SCons.Scanner.Fortran
This module implements the dependency scanner for Fortran code.
"""
#
# Copyright (c) 2001 - 2017 The SCons Foundation
#
# 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 Sof... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
salt.utils.validate.path
~~~~~~~~~~~~~~~~~~~~~~~~
Several path related validators
'''
# Import python libs
import os
def is_writeable(path, check_parent=False):
'''
Check if a given path is writeable by th... |
#
# Copyright (C) 2012 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
import anyconfig.backend.xml_ as TT
import os
import tempfile
import unittest
CONF_0 = """<?xml version="1.0" encoding="UTF-8"?>
<config name='foo'>
<a>0</a>
<b id="b0">bbb</b>
<sect0>
<c>x, y, z</c>
</sect0>
</config>
"""
class ... |
from django.contrib.auth import REDIRECT_FIELD_NAME, logout, login, authenticate
from django.contrib.auth.models import User, Group
from django.shortcuts import render
from django.http import HttpResponseRedirect
from authentication.forms import *
import json
from rest_framework import viewsets
from rest_framework.... |
"""BUILD rules to construct a java agent.
All this is unfortunately necessary. Some of the machinery is located at
//java/com/google/monitoring/runtime/instrumentation/BUILD
but you should be able to use the java_agent_binary by itself; just
add yourself to the java_agent_builddef_users package group.
"""
# expa... |
"""
Module to test plotly.utils with optional dependencies.
"""
from __future__ import absolute_import
import datetime
import math
import decimal
from datetime import datetime as dt
from unittest import TestCase
import pytest
import numpy as np
import pandas as pd
import pytz
from pandas.util.testing import assert_s... |
# Copyright 2010-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 law or agreed to in writing... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@londonappdev.com',
... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... |
import cv2
image_file = "../../material/lena.jpg"
print("read %s" % image_file)
lena = cv2.imread(image_file)
cv2.namedWindow("test")
cv2.imshow("test", lena)
cv2.waitKey()
cv2.destroyWindow("test") |
import unittest
def binary_search(data, target, low, high):
"""Return True if target is found in indicated potion of a Python list.
The searvh only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False # interval is empty; no match
els... |
#################################
# RAW-to-RGB Model architecture #
#################################
import tensorflow as tf
import numpy as np
#import utils for bfp
from bfp.lib.Utils_tf import bfp_quantize
MANTISSA_WIDTH = 8
EXPONENT_WIDTH = 10
#Increment this to make every layer have a different name
layer_name ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# from bokeh import palettes
def robust_avg(df_input):
df_input = df_input.reset_index(drop=True)
# robust average
avg = []
avg_weight = []
temp = []
#initial robust weight
newp = [1.0 / len(df_input.columns)] * len(d... |
import typing # noqa: F401
import datetime as _datetime # noqa: F401
from kubernetes import client # noqa: F401
from kuber import kube_api as _kube_api # noqa: F401
from kuber import definitions as _kuber_definitions # noqa: F401
from kuber import _types # noqa: F401
from kuber.v1_23.core_v1 import EventSource ... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flat
class BallBouncinessOption(object):
Default = 0
Low = 1
High = 2
Super_High = 3
|
# -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""api/jira_issues.py
Exposed jira_issues for autocomplete.... |
# Django settings for Userena demo project.
DEBUG = True
import os
import sys
import django
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(settings_dir)
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.d... |
import os
def list_of_files(folder_path):
"""
A method that finds the names of all files within the specified folder location.
:parameter folder_path - A string that represents the path to the folder.
:returns List of file names in the specified folder
"""
file_list = []
for dirpath, dirn... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from fnmatch import fnmatch
import os
import sys
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
try:
import pep8
except ImportError:
HAS_PEP8 = False
else:
... |
#############################################################################
# Copyright (c) 2021, Thorsten Beier #
# Copyright (c) 2021, QuantStack #
# #
# Distri... |
#!/usr/bin/env python
import pytest
"""
Test 2023. Number of Pairs of Strings With Concatenation Equal to Target
"""
@pytest.fixture(scope="session")
def init_variables_2023():
from src.leetcode_2023_number_of_pairs_of_strings_with_concatenation_equal_to_target import (
Solution,
)
solution = S... |
from glbase import *
newfile = genelist("simple_file.tsv", force_tsv=True)
print newfile
|
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth
import sys
from spotify_cred import CLIENT_ID, SECRET_KEY
## Get all albums from artist
birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP'
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=CLIENT_ID,
... |
#encoding: utf8
import datetime
import json
from unittest import TestCase
import mock
from dateutil.parser import parse as date_parse
from tests import BaseTestCase
from redash import models
from redash.models import db
from redash.utils import gen_query_hash, utcnow
class DashboardTest(BaseTestCase):
def test_ap... |
from MarkdownEditing.tests import DereferrablePanelTestCase
class TestConvertInlineLinkToReference(DereferrablePanelTestCase):
def setUp(self):
self.setBlockText(
"""
# Test 1
First [GitHub](https://github.com) inline link.
[Issues](https://github.com/user/r... |
import json
import logging
import os
import tempfile
from gippy import GeoImage, GeoVector, algorithms as algs
from satstac import Item
from satsearch import config
logger = logging.getLogger(__name__)
OPTS = {'COMPRESS': 'DEFLATE', 'PREDICTOR': '2', 'INTERLEAVE': 'BAND',
'TILED': 'YES', 'BLOCKXSIZE': '512'... |
#
# This is Seisflows
#
# See LICENCE file
#
#
###############################################################################
# Import system modules
from os.path import abspath
# Import numpy
import numpy as np
# Local imports
from seisflows.tools.array import count_zeros
class Base(object):
""" Abstract bas... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import numpy as np
from libs.configs._base_.models.retinanet_r50_fpn import *
from libs.configs._base_.datasets.dota_detection import *
from libs.configs._base_.schedules.schedule_1x import *
from dataloader.pretrained_weights.pr... |
#!/usr/bin/env python
import sys
import os
import functools
import itertools
from collections import defaultdict
import healpy
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot
import numpy
from lalinference.bayestar import fits as bfits
from lalinference.bayestar import plot as bplot
import RI... |
from functools import wraps
class lazy_property(property):
"""
A property that works with subclasses by wrapping the decorated
functions of the base class.
"""
def __new__(cls, fget=None, fset=None, fdel=None, doc=None):
if fget is not None:
@wraps(fget)
def fget(in... |
#
# PySNMP MIB module ONEACCESS-VRF-TO-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-VRF-TO-IF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# model settings
model = dict(
type='TTFNet',
pretrained=None,
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=-1,
norm_eval=False,
zero_init_residual=False,
style='pytorch'),
neck=None,
bbo... |
# test_quality.py - unit tests for the quality module
#
# Copyright 2015 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Unit tests for the :mod:`networkx.algorithms.community.quality`
module.
"""
from __future__ import... |
import unittest
import caffe
class TestLayerTypeList(unittest.TestCase):
@classmethod
def setUpClass(self):
super(TestLayerTypeList, self).setUpClass()
caffe.set_device(0)
print('TestLayerTypeList.setUpClass')
@classmethod
def tearDownClass(self):
super(TestLayerTypeLi... |
import tensorflow as tf
import renderer
import helpers
def DX(x):
return x[:,:,1:,:] - x[:,:,:-1,:] # so this just subtracts the image from a single-pixel shifted version of itself (while cropping out two pixels because we don't know what's outside the image)
def DY(x):
return x[:,1:,:,:] - x[:,:-1,:,:] ... |
import json
import numpy as np
from network import costs
import time
class NeuralNetwork:
def __init__(self, input_layer, hidden_layers, output_layer, cost=costs.CrossEntropy):
self.input_layer = input_layer
self.hidden_layers = hidden_layers
self.output_layer = output_layer
self.... |
from setuptools import find_packages, setup
from djrepo import __version__
setup(
name="djrepo",
version=__version__,
url="https://github.com/magocod/djrepo",
author="Yson",
author_email="androvirtual12@gmail.com",
description="Digital repository, UNEFA internship project",
python_requires... |
import graphene
from collections import defaultdict
from sqlalchemy import and_
from lingvodoc.models import (
DictionaryPerspective as dbPerspective,
Dictionary as dbDictionary,
TranslationAtom as dbTranslationAtom,
Language as dbLanguage,
LexicalEntry as dbLexicalEntry,
Client as dbClient,
... |
import requests
from bs4 import BeautifulSoup
import smtplib
import time
#Collect the price from amazon and send to email
def Main():
#Include the User Agent (can be found by typing "user agent" in google, just paste that in)
URL = 'https://www.XXXX.com/XXXX'
headers = {"User-Agent": 'XXXX'}
email = 'XXX... |
#!/usr/bin/env python
#ref: https://github.com/googleapis/python-iot
from google.cloud import storage
import paho.mqtt.client as mqtt
import jwt
import time
import ssl
import random
import os
import logging
import datetime
import argparse
import random
import time
import datetime
import json
logging.getLogger('goo... |
class <warning descr="Python version 3.7, 3.8 do not allow 'async' and 'await' as names">a<caret>wait</warning>(object):
pass |
#!/usr/bin/env python
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#! /usr/bin/env python3
#This script goes through the interproscan tsv output file to get the GO terms for the headers - it will write a file with 2 columns - the first
#will be the headers, the second will have the GO terms if any are present, if there are multiple they will be seperated by commas.
#import modules
... |
# -*- coding: utf-8 -*-
# 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... |
from iso8601 import parse_date
from datetime import date
class JSValueConverter:
"""I convert values from and to JavaScript, both sides."""
def __init__(self, jsName):
self.jsName = jsName
def existsIn(self, requestDict):
if self.jsName in requestDict:
return True
retu... |
import argparse
import os.path as osp
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.runner import load_checkpoint, get_dist_info
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmdet.apis import init_dist
from mmdet.core import results2json,... |
import numpy as np
import pandas as pd
from scipy.optimize import root
import matplotlib.pyplot as plt
import math
from scipy.integrate import trapz
from scipy import interpolate
import pprint
# Helper functions definition
# ----------------------------------------------------------
# Prandtl approximat... |
class Tcolors:
# credit blender build scripts
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.la... |
#!/usr/bin/env python3
from sys import stdout,stderr
import logging
SLEEP_EVENTS = 85
VALID_CREDENTIALS = 80
CREDENTIAL_EVENTS = 70
GENERAL_EVENTS = 60
FORMAT='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_FORMAT = logging.Formatter(FORMAT)
logging.addLevelName(SLEEP_EVENT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.