text stringlengths 1 927k |
|---|
#!/usr/bin/env python
# This code was adapted from http://sfepy.org/doc-devel/mat_optim.html.
from __future__ import print_function
from __future__ import absolute_import
import sys
sys.path.append('.')
import matplotlib as mlp
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mp... |
#!/usr/bin/env python
"""
This script is used to run tests, create a coverage report and output the
statistics at the end of the tox run.
To run this script just execute ``tox``
"""
import re
from fabric.api import local, warn
from fabric.colors import green, red
if __name__ == '__main__':
local('flake8 --ignore... |
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY', 'SECRET')
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contri... |
"ts_project rule"
load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "ExternalNpmPackageInfo", "declaration_info", "js_module_info", "run_node")
load("@build_bazel_rules_nodejs//internal/linker:link_node_modules.bzl", "module_mappings_aspect")
load("@build_bazel_rules_nodejs//internal/node:node.bzl",... |
#MIT License
#Copyright (c) 2021 subinps
#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, publish, dis... |
__all__ = ["odeCFL1"]
import cupy as cp
import numpy as np
from LevelSetPy.Utilities import *
from .ode_cfl_set import odeCFLset
from .ode_cfl_call import odeCFLcallPostTimestep
def odeCFL1(schemeFunc, tspan, y0, options=None, schemeData=None):
"""
odeCFL1: integrate a CFL constrained ODE (eg a PDE by method... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from pybio.torch.training.simple import simple_training |
import sys
import os
import pathlib
import unittest
import coverage
import argparse
import subprocess
import site
# Ensure source directory is in python path
project_dir = str(pathlib.Path(__file__).parents[1].resolve())
sys.path.append(os.path.join(project_dir, 'src'))
# for keras
sys.path.append(project_dir)
""" -... |
# -*- coding: utf-8 -*-
"""
Created on December 30, 2020
@author: Siqi Miao
"""
import torch
from torch_sparse import SparseTensor
import torch_geometric.transforms as T
from pathlib2 import Path
import scipy.io as sio
from sklearn.metrics import f1_score, accuracy_score
from sklearn.model_selection import train_te... |
"""
Copyrigt Dendi Suhubdy, 2018
All rights reserved
"""
from loss import loss_function
def train(args, model, optimizer, train_loader, device, epoch):
model.train()
train_loss = 0
for batch_idx, (data, _) in enumerate(train_loader):
data = data.to(device)
optimizer.zero_grad()
r... |
"""
146. LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if
the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the ... |
import collections
import csv
import datetime
import grp
import os
import stat
import optparse
import pwd
import StringIO
import sys
from pysh.shell.pycmd import register_pycmd
from pysh.shell.pycmd import pycmd
from pysh.shell.pycmd import IOType
from pysh.shell.table import PyshTable, CreateTableFromIterableRows
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'leetcode'
__file__ = '__init__.py'
__author__ = 'king'
__time__ = '2020/2/23 21:09'
_ooOoo_
o8888888o
88" . "88
(| -_- |)
... |
# coding: utf-8
# # Estimating the fraction of plant biomass which is not woody
# To estimate the total non-woody plant biomass, we rely on two methods. The first is to estimate the global average leaf and root mass fractions, and the second is by estimating the total biomass of roots and leaves.
#
# ## Method1 - fra... |
# Class definition for Book entity
class Book:
bookId = 1
def __init__(self, title, publisher, author, edition, publishedOn):
self.__title = title
self.__publisher = publisher
self.__author = author
self.__edition = edition
self.__publishedOn = publishedOn
self._... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import numpy as np
from modules.imageRW import Image
from typing import Iterator, Optional, List
from __future__ import annotations
class InputException(Exception):
pass
def mean(images: Iterator[Image], group_size: int) -> Iterator[Image|None]:
stackImage: Image|None = None
while True:
try:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.CommonPrizeModelVo import CommonPrizeModelVo
class AlipayFundCouponWufuLiveAcceptResponse(AlipayResponse):
def __init__(self):
super(AlipayFundCouponWufu... |
#!/usr/bin/env python
import argparse
import pyDNase
import numpy as np
import matplotlib as mpl
from clint.textui import progress, puts
#Required for headless operation
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import rcParams
parser = argparse.ArgumentParser(description='Plots average profile of... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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... |
from __future__ import division
import random
import Adafruit_PCA9685
import thread
import sys
from time import sleep
from inputs import get_gamepad
pwmL = Adafruit_PCA9685.PCA9685(0x41)
pwmR = Adafruit_PCA9685.PCA9685(0x40)
pwmL.set_pwm_freq(50)
pwmR.set_pwm_freq(50)
motors = [12, 13, 14, 3, 2, 1]
start = [160, 130,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import json
import os
import re
import unittest
from django.contrib.admin import AdminSite, ModelAdmin
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.models import ADDITION, DELETION, LogEntry
from... |
#!/usr/bin/env python
# History
# v01 : adaptation from the one given by Udacity to work
# v02 : adapt to commonFunctions_v10.py to use generator.
# Start adding again everything from model_v12.py (image augmentation)
import os
import csv
import cv2
import numpy as np
import sklearn
from math import ceil
from ... |
"""
Unit test for babelscan
"""
import numpy as np
import matplotlib.pyplot as plt
import babelscan
print('####################################################')
print('############## babelscan unit tests ################')
print('####################################################')
print('\n')
print(babelscan.mod... |
#
# Copyright 2021 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
import asyncio
import discord
from redbot.vendored.discord.ext import menus
from .game import Game
TRANS = {
0: "\N{BLACK LARGE SQUARE}",
1: "\N{RED APPLE}",
2: "\N{LARGE GREEN CIRCLE}",
3: "\N{LARGE GREEN SQUARE}",
}
GET_DIR = {
"w": "up",
"s": "down",
"a": "left",
"d": "right",
... |
"""
Qualitative analysis of dataset generated using CADS vs NDS approach.
"""
import sys
import glob
import json
import gzip
def sentence_id(json_sentence):
"""
Return the unique if of a sentence.
"""
return '_'.join([
str(json_sentence['did']),
str(json_sentence['pid']),
str(j... |
"""
This file offers the methods to automatically retrieve the graph dbpedia-occupation.
The graph is automatically retrieved from the NetworkRepository repository.
References
---------------------
Please cite the following if you use the data:
```bib
@inproceedings{nr,
title = {The Network Data Repository wit... |
from tkinter import *
from odf_query import *
from app_tools import *
from app_selector import *
from app_dictionary import _, load_dictionary
class AppFilter(Toplevel):
"""Window for managing a filter (for adding or modifying a filter)
Arguments:
Toplevel {Toplevel (tkinter)} -- Window preventing... |
"""
CAR CONFIG
This file is read by your car application's manage.py script to change the car
performance.
EXMAPLE
-----------
import dk
cfg = dk.load_config(config_path='~/mycar/config.py')
print(cfg.CAMERA_RESOLUTION)
"""
import os
#PATHS
CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
DAT... |
import os
import json
import cv2 as cv
import numpy as np
from tqdm import tqdm
try:
from pandas import json_normalize
except:
from pandas.io.json import json_normalize
def load_dict(fname):
with open(fname, "r") as fp:
o = json.load(fp, )
return o
def save_dict(fname, d, mode='w', **kw... |
# -*- coding: utf-8 -*-
"""The extractor class definitions.
An extractor is a class used to extract information from "raw" data.
"""
import copy
import re
import pysigscan
from dfvfs.helpers import file_system_searcher
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.lib import errors as dfvfs_erro... |
# Copyright (c) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
"""
Provides access to /etc/cwlogd.ini config values
"""
import configparser
CONFIG_PATH = "/etc/cwlogd.ini"
_config = None
def _get_config():
"""
Either returns an already loaded configparser
Or creates a configparser and loads ini config at /etc/cwlogd.ini
"""
global _config
if _config is N... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/04_radarcfg_v1.ipynb (unless otherwise specified).
__all__ = ['logger', 'read_radar_params', 'parse_commands', 'dict_to_list', 'channelStr_to_dict', 'profileStr_to_dict',
'chirp_to_dict', 'power_to_dict', 'frameStr_to_dict', 'adcStr_to_dict', 'command_handlers... |
import itertools
import re
import sys
import traceback
from instruction import Instruction
class MIPSProg:
def __init__(self, lines=None):
self.text_base = 0
self.data_base = 0x00400000
self.instructions = []
self.data = []
self.labels = {}
self.defines = {}
... |
# pylint: disable=unused-import
# -*- coding: utf-8 -*-
#
# ramstk.models.mechanism.__init__.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""The RAMSTK failure Mechanism model package.""" |
"""Added Macros table
Revision ID: b7ab14de6d0f
Revises: 183d3f0348eb
Create Date: 2017-11-28 11:54:23.897000
"""
# revision identifiers, used by Alembic.
revision = 'b7ab14de6d0f'
down_revision = '183d3f0348eb'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Ale... |
"""
WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_... |
__author__ = 'Todd.Hay'
# -------------------------------------------------------------------------------
# Name: StateMachine.py
# Purpose:
#
# Author: Todd.Hay
# Email: Todd.Hay@noaa.gov
#
# Created: Feb 03, 2016
# License: MIT
#-------------------------------------------------------------... |
import click
import time
import glob
import json
import tarfile
import requests
import os
from shutil import copyfile
_FOLDER = "_experiments"
@click.group(help="""
Base QiskitFlow cli function.
""")
def qiskitflow():
click.echo(click.style("== QiskitFlow. Reproducible quantum experiments ==", fg='magenta'))
... |
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Toxine project
#
# Copyright (C) 2019-present by Sergei Ternovykh
# License: BSD, see LICENSE for details
"""
Example: Tokenize Wikipedia and save articles as CoNLL-U.
"""
from corpuscula import Conllu
from corpuscula.wikipedia_utils import download_wikipedia
from toxine.wiki... |
import uuid as _uuid
import itertools as _itertools
import random as _random
import collections as _collections
import inspect as _inspect
import copy as _copy
import _collections_abc
UUID_PATTERN = "\
^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
def _curry(n, fn, carryover_args=()... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : fedhf\api\dpm\laplace_noise.py
# @Time : 2022-05-02 22:39:42
# @Author : Bingjie Yan
# @Email : bj.yan.pa@qq.com
# @License : Apache License 2.0
import numpy as np
import torch
def laplace_noise(sensitivity, size, epsilon, **kwargs):
"""
... |
from json import loads
from ..models.response import ErrorMessage
class WebsiteContactsApiError(Exception):
def __init__(self, message):
self.message = message
@property
def message(self):
return self._message
@message.setter
def message(self, message):
self._message = me... |
import unittest
import sys
sys.path.append('../')
import d01_p1 as d01
class TestFindNumbers(unittest.TestCase):
def test_with_only_one_matching_pair(self):
testData = [10, 2010]
expected = (10, 2010)
result = d01.findNumbers(testData)
self.assertEqual(result, expected)
de... |
# create an empty set
s = set()
# add elements to the sets
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
print(s)
s.remove(2)
print(s)
# print out how many elements are in the set
print(f"there are {len(s)} elements in the set") |
r"""
vanilla pseudo-labeling implementation
"""
from collections import defaultdict
from alr.utils import timeop, manual_seed
from alr.data.datasets import Dataset
from alr.data import UnlabelledDataset
from alr.training import VanillaPLTrainer
from alr.training.samplers import RandomFixedLengthSampler
from alr import... |
import argparse
import numpy
import pandas as pd
import os
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
from ngram_classifier import NGramClassifier
from sklearn.metrics import precision_recall_fscore_support
CLASS_WEIGHTS = ... |
from ..model import Model
from . import loadDefaultParams as dp
from . import timeIntegration as ti
class ThalamicMassModel(Model):
"""
Two population thalamic model
Reference:
Costa, M. S., Weigenand, A., Ngo, H. V. V., Marshall, L., Born, J.,
Martinetz, T., & Claussen, J. C. (2016). A thala... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Datalist(Component):
"""A Datalist component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The children of this component
- id (string; optio... |
#!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2019 msloniewski <marcin.sloniewski@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause
import os
import argparse
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.build.io import DDROutput
from li... |
# -*- coding: utf-8 -*-
# Copyright (C) 2019-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Custom exceptions for this framework"""
class FailedStepError(Exception):
"""Generic non-specific exception"""
pass
class FailedBuildError(Exception):
"""Exception on failed Docker image build"""... |
from numpy import *
from matplotlib.pyplot import *
figure()
A = loadtxt('flopsext.txt', usecols={3})
B = loadtxt('flopsint.txt', usecols={3})
A = cumsum(A)
Awow = A / 100;
B = cumsum(B)
semilogy(A, '+', Awow, '_', B, 'o')
show() |
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""
IDLNamespace for PPAPI
This file defines the behavior of the AST namespace which allows for resolving
a symbol as one or more ... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from past.utils import old_div
from math import *
import proteus.MeshTools
from proteus import Domain
from proteus.default_n import *
from proteus.Profiling import logEvent
from .parameters import *
manufacture... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from codecs import open
from os import path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open('transmission_telegram_bot/__init__.py') as f:
for line in f:
if line.find("__version__") >= 0:
version =... |
"""
ModInfo - Commands ``modinfo <module_name>``
============================================
Parsers to parse the output of ``modinfo <module_name>`` commands.
ModInfoI40e - Command ``modinfo i40e``
--------------------------------------
ModInfoVmxnet3 - Command ``modinfo vmxnet3``
----------------------------------... |
import time
import numpy as np
from metadrive import MetaDriveEnv
from metadrive.utils import setup_logger
if __name__ == '__main__':
print("Start to profile the efficiency of MetaDrive with 1000 maps and ~8 vehicles!")
setup_logger(debug=False)
env = MetaDriveEnv(dict(
environment_num=1000,
... |
# 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 ... |
import argparse
import os
import sys
import time
import datetime
from copy import deepcopy
import numpy as np
CONTINOUS_COLUMNS = [0, 2, 3, 9, 10, 11]
TTL = 30
class Node:
def __init__(self, prediction, continuous=None, unqs=None, column=None, median=None):
self.children = []
self.column = colum... |
import datetime
import random
from operator import eq
import dateutil.parser
class Param(object):
"""
Wraps a property on an object and optionally how it corresponds to a
parameter of some sort.
"""
def __init__(self, *, property, parameter=None, operator=eq, bucket=None, discrete=True):
... |
import ctypes
lib = ctypes.cdll['./FibonacciLib.so']
fib = lib['fib']
for j in range(15):
x = 3*j + 3
print "fib(%d) = %d" %( x,fib(x) ) |
# Copyright 2017 Google 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 required by applicable law or ag... |
# 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 ... |
import os
import shutil
import errno
import subprocess
import tempfile
from tempfile import mkdtemp
try:
from PIL import Image
except ImportError:
print('Error: You need to install the "Image" package. Type the following:')
print('pip install Image')
try:
import pytesseract
except ImportError:
pri... |
# Generated by Django 3.2.7 on 2021-09-06 06:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('galleria', '0007_rename_cats_cat'),
]
operations = [
migrations.CreateModel(
name='Location',
... |
from __future__ import annotations
from numpy import int32
from pentagram.interpret.block import interpret_block
from pentagram.interpret.test import init_test_frame_stack
from pentagram.machine import MachineExpressionStack
from pentagram.machine import MachineFrameStack
from pentagram.machine import MachineNumber
fr... |
"""
.. Dstl (c) Crown Copyright 2019
"""
import inspect
class SavedInitStatement:
"""Init statement saving mixin, introspects on object instantiation arguments and
saves them to the final object"""
def __init__(self, *args, **kwargs):
frame = inspect.currentframe()
_, _, _, values = inspe... |
# -*- coding: utf-8 -*-
"""This module defines various constants that describe the vocabulary of the used ontology."""
__author__ = "Patrick Hohenecker"
__copyright__ = (
"Copyright (c) 2018, Patrick Hohenecker\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and bin... |
from zope.interface import implements
from twisted.cred import portal, checkers, credentials
from nevow import inevow, rend, tags, guard, loaders
### Renderers
class NotLoggedIn(rend.Page):
"""The resource that is returned when you are not logged in"""
addSlash = True
docFactory = loaders.stan(
tags... |
#crypto.py
from urllib.request import urlopen as req
from bs4 import BeautifulSoup as soup
def rangeprice(name='bitcoin',start='20200101',end='20200131'):
url = 'https://coinmarketcap.com/currencies/{}/historical-data/?start={}&end={}'.format(name,start,end)
webopen = req(url)
page_html = webopen.read()
webopen... |
__author__ = 'anonymous'
import unittest
import json
from config_loader import ConfigLoader
class LoaderTest(unittest.TestCase):
def test_settings_1(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('26214400')
actual = loader.get('common.basic_si... |
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from scraper import scrape
import sys
from app import app, db
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
... |
#
# Copyright (c) 2021 salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
import os
import sys
import logging
import requests
import tarfile
import numpy as np
import pandas ... |
_base_ = [
'../../../../_base_/default_runtime.py',
'../../../../_base_/datasets/coco.py'
]
evaluation = dict(interval=10, metric='mAP', save_best='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='l... |
import modi
import time
"""
Example script for the usage of dial module
Make sure you connect 1 dial module and 1 speaker module to your network module
"""
if __name__ == "__main__":
bundle = modi.MODI()
dial = bundle.dials[0]
speak = bundle.speakers[0]
while True:
speak.tune = 800, dial.degr... |
# -*- coding: utf-8 -*-
from xarmedbandits import TreeNode
import random
import math
"""
This class is built around the ideas that are thoroughly explained in the paper
"X-armed Bandits" by Bubeck et al., 2011.
"""
class HOO(object):
"""
The hierarchical optimistic optimization algorithm.
"""
... |
from __future__ import unicode_literals, division, absolute_import
import logging
import re
import urllib
import feedparser
from flexget.plugin import register_plugin, PluginWarning
from flexget.entry import Entry
from flexget.utils.search import torrent_availability, normalize_unicode
from flexget import validator
l... |
# vst.py Demo/test program for vertical slider class for Pyboard RA8875 GUI
# Released under the MIT License (MIT). See LICENSE.
# Copyright (c) 2019-2020 Peter Hinch
# Updated for uasyncio V3
import uasyncio as asyncio
from math import pi
from micropython_ra8875.py.ugui import Screen
from micropython_ra8875.py.col... |
from __future__ import unicode_literals
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from common import MayanAppConfig, menu_object, menu_sidebar
from navigation import SourceColumn
from .links import (
link_transformation_create, link_transformation_delet... |
"""
YOLO_v3 Model Defined in Keras.
Reference: https://github.com/qqwweee/keras-yolo3.git
"""
from config import kerasTextModel,IMGSIZE,keras_anchors,class_names,GPU,GPUID
from .keras_yolo3 import yolo_text,box_layer,K
from apphelper.image import resize_im,letterbox_image
from PIL import Image
import numpy as np
impor... |
from .cdn import return_cdn_avatar
# Set interaction opcodes
DISPATCH = 0
HEARTBEAT = 1
IDENTIFY = 2
RESUME = 6
RECONNECT = 7
INVALID_SESSION = 9
HELLO = 10
HEARTBEAT_ACK = 11
# Set application command types
SLASH = 2
USER = 2
MESSAGE = 3
# Set message response types
CHANNEL_WITH_SOURCE = 4
DEFERRED_CHANNEL_WITH_SOU... |
import streamlit as st
from utils.constants import NAVIGATION, NAV_VIZ
from pages.data_visualization import sidebar_filter
def navbar():
st.subheader("Navigation")
st.radio("Go to...", options=NAVIGATION, key="page")
def show_sidebar():
sidebar = st.sidebar
with sidebar:
navbar()
if s... |
'''
Code courtesy of Ben Feinstein & Assaf Shocher
Please see their work:
https://github.com/assafshocher/PyTorch-Resizer
https://github.com/feinsteinben
'''
import numpy as np
import torch
from math import pi
from torch import nn
class Resizer(nn.Module):
def __init__(self, in_shape, scale_factor=None, output_sh... |
"""
The debug wrapper script.
"""
import argparse
import os
import sys
_ARG_PARSER = argparse.ArgumentParser(description="我的实验,需要指定配置文件")
_ARG_PARSER.add_argument('--cuda', '-c', type=str, default='0', help='gpu ids, like: 1,2,3')
_ARG_PARSER.add_argument('--name', '-n', type=str, default='debug', help='save name.')
... |
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.factory import get_problem, get_termination
from pymoo.optimize import minimize
problem = get_problem("zdt3")
algorithm = NSGA2(pop_size=100)
termination = get_termination("n_gen", 10)
res = minimize(problem,
algorithm,
termination,... |
import time
import json
import socket
import sys
SEGMENT_DOC = json.loads(sys.argv[1])
del SEGMENT_DOC["in_progress"]
END_TIME = time.time()
SEGMENT_DOC["end_time"] = END_TIME
HEADER=json.dumps({"format": "json", "version": 1})
TRACE_DATA = HEADER + "\n" + json.dumps(SEGMENT_DOC)
UDP_IP= "127.0.0.1"
UDP_PORT=2000
soc... |
from __future__ import print_function
import sys
import logging
import pubdns
logging.basicConfig(level=logging.DEBUG)
try:
pd = pubdns.pubdns()
servers = pd.servers('US', 'los angeles')
rs = pubdns.dns.resolver(servers, 'amazon.com', ['A'])
for r in rs:
print(r)
except pubdns.UpdateError as ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import logging
import os
import time
import sys
import multiprocessing
import signal
# Import salt libs
import salt.defaults.exitcodes
import salt.utils
import salt.ext.six as six
log = logging.getLogger(__name__)
HAS_PSUTIL = Fals... |
import sys
import six
import functools
from dbt.compat import builtins
from dbt.logger import GLOBAL_LOGGER as logger
import dbt.flags
class Exception(builtins.Exception):
CODE = -32000
MESSAGE = "Server Error"
def data(self):
# if overriding, make sure the result is json-serializable.
r... |
import pytest
import time
from tests.live import testlib
from pandevice import base
class TestUserID_FW(object):
"""Tests UserID on live Firewall."""
def test_01_fw_login(self, fw, state_map):
state = state_map.setdefault(fw)
user, ip = testlib.random_name(), testlib.random_ip()
fw.u... |
# -*-coding:utf-8 -*
class DomainException(Exception):
"""
Exception levée lors d'une erreur sur le nom de domaine
:ivar message: message à afficher
"""
def __init__(self, message):
self.msg = message |
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=20, required=True) |
from __future__ import print_function, division, absolute_import
import copy
import time
import numpy as np
import sys
class Bridge(object):
def __init__(self, initial_components, available_components):
self.components = list(initial_components)
self.score = sum([sum(tup) for tup in self.compone... |
# 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 un... |
import logging
import os
import shutil
import subprocess
logger = logging.getLogger("Main")
def configure_argument_parser(environment, configuration, subparsers): # pylint: disable = unused-argument
parser = subparsers.add_parser("test", help = "run the test suite")
parser.add_argument("--configuration", required... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.