code
stringlengths
1
199k
from dtest import Tester, debug from ccmlib.cluster import Cluster from ccmlib.common import get_version_from_build from tools import since import random, os, time, re @since('2.0') class TestSCUpgrade(Tester): def __init__(self, *args, **kwargs): self.ignore_log_patterns = [ # This one occurs i...
import os import re import shutil import pickle import glob import util import logging import threading import time __doc__ = """post_submit_cleanup.py A threaded cleanup implementation. This module is launched as a separate thread when the CondorAgent is started if, and only if, the agent is set to do local Condor sub...
import glob import gzip import os import subprocess from find_intersecting_snps import * from filter_remapped_reads import * def read_bam(bam): """ Read a bam file into a list where each element of the list is a line from the bam file (with the newline stripped). The header is discarded. """ res = s...
from __future__ import print_function from airflow import DAG, configuration, operators from airflow.utils.tests import skipUnlessImported from airflow.utils import timezone configuration.load_test_config() import unittest DEFAULT_DATE = timezone.datetime(2015, 1, 1) DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat() DEFAULT_...
"""This tries to dream so that an activation vector gets reproduced.""" from absl import app from absl import flags import torch import torch.nn.functional as F import sys sys.path.insert(1, 'helpers') import activation_helper import attention_mask_helper import embeddings_helper import folder_helper import inference_h...
from CommonClasses import * from solution import Solution class TestSuite: def run(self): self.test000() def test000(self): print 'test 000\n' n = 5 startTime = time.clock() r = Solution().generate(n) timeUsed = time.clock() - startTime print ' input:\t{0...
import unittest import numpy as np from pyscf import lib from pyscf.pbc import gto as pbcgto from pyscf.pbc import scf as pscf from pyscf.pbc.scf import khf from pyscf.pbc.scf import kuhf from pyscf.pbc import df import pyscf.pbc.tools def finger(a): return np.dot(np.cos(np.arange(a.size)), a.ravel()) def make_prim...
__doc__=""" Align selected paths (and parts of paths) to the next sidebearing or glyph center to the right. """ import GlyphsApp Font = Glyphs.font Doc = Glyphs.currentDocument Master = Font.selectedFontMaster selectedLayer = Font.selectedLayers[0] allMetrics = [ 0.0, selectedLayer.width, selectedLayer.width//2 ] try: ...
import diventi.accounts.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0166_auto_20190531_0748'), ] operations = [ migrations.AlterModelManagers( name='diventiuser', managers=[ ('objects', ...
print('Howdy!')
"""Site administration functionality.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import cgi import cStringIO import datetime import os import sys import time import urllib import messages import webapp2 import appengine_config from common import jinja_utils from common import safe_dom from common import tags...
""" Module for managing monitors. """ import os import itertools from rmake.cmdline import monitor from updatebot.build.common import AbstractStatusMonitor from updatebot.build.common import AbstractWorkerThread as AbstractWorker from updatebot.build.constants import WorkerTypes from updatebot.build.constants import Me...
"""General channels module for Zigbee Home Automation.""" from __future__ import annotations import asyncio from typing import Any, Coroutine import zigpy.exceptions import zigpy.zcl.clusters.general as general from zigpy.zcl.foundation import Status from homeassistant.core import callback from homeassistant.helpers.ev...
''' Created on 4 Nov 2014 @author: nikolay ''' import sys import time import logging from autoscale.AppServer import AppServer from autoscale.Util import convertMem, scriptPath, vmManagerJarPath from autoscale.VMType import VMType from autoscale.VMFactory import VMFactory from autoscale.AWSBillingPolicy import AWSBilli...
import httpretty from keystoneclient import exceptions from keystoneclient.tests.v2_0 import utils from keystoneclient.v2_0 import tenants class TenantTests(utils.TestCase): def setUp(self): super(TenantTests, self).setUp() self.TEST_TENANTS = { "tenants": { "values": [ ...
import httplib import netaddr import os import socket import time from eventlet import greenthread from novaclient.v1_1 import client as novaclient from oslo.config import cfg from dnrm.drivers import base from dnrm import exceptions from dnrm.resources import base as resources cfg.CONF.register_opts([ cfg.IntOpt('...
from django.conf.urls import patterns, include, url import views from allauth.account.views import LogoutView urlpatterns = patterns('', url(r'^login/$', views.login_view, name="login"), url(r'^logout/$', LogoutView.as_view(), name="logout"), )
import dweepy import logging import time import serial class emTelemetry(object): def __init__(self, device): logging.info('Telemetry') self.device = device if self.device is "dweetio": pass elif self.device is "xbee": self.serial = serial.Serial(port='/dev/tt...
"""Contains definitions for Residual Networks. Residual networks ('v1' ResNets) were originally proposed in: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 The full preactivation 'v2' ResNet variant was introduced by: [2] Kaiming He, Xiangyu Zhan...
"""Drivers for volumes.""" import abc import time from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils import six from cinder import exception from cinder.i18n import _, _LE, _LW from cinder.image import image_utils from cinder import ...
"""Define the arguments for a single repository.""" from __future__ import absolute_import import argparse def parse_config_file_list(repo_config_path_list): """Return a list of parsed configs fom supplied 'repo_config_path_list'. :repo_config_path_list: list of string paths to config files :returns: list o...
import glob import os import shutil import zipfile import mock import pytest from pyleus import __version__ from pyleus import exception from pyleus.cli import build class TestBuild(object): @mock.patch.object(os.path, 'exists', autospec=True) def test__open_jar_jarfile_not_found(self, mock_exists): moc...
__author__ = 'Binson Zhang <bin183cs@gmail.com>' __date__ = '2013-8-30' from collections import defaultdict import console import logutil import logging class DependencyAnalyzer(object): def __init__(self, targets, target_map): self.targets = targets self.target_map = target_map self.out_deg...
from __future__ import absolute_import import datetime import logging from typing import Any from django.conf import settings from django.core.management.base import BaseCommand from django.utils import timezone from zerver.lib.queue import queue_json_publish from zerver.models import UserActivity, UserProfile, Realm l...
"""Dropout layer which doesn't rescale the kept elements.""" from kws_streaming.layers.compat import tf from tensorflow.python.keras.utils import control_flow_util # pylint: disable=g-direct-tensorflow-import from tensorflow.python.ops import array_ops # pylint: disable=g-direct-tensorflow-import class NonScalingDrop...
import socket import threading def server(sock, addr): print('connection from %s:%s' %addr) buffer = [] while True: d = sock.recv(4096) if not d: break buffer.append(d) data = b''.join(buffer) print(data.decode('utf-8')) with open('server.py', 'r') as f: ...
""" This package provides the github client/screen scraping for pull requests which allows us to query a list of commit hashes for which to cherry-pick into the repo when we do the merge """
from helpers import * # includes music21 import math import time import sys import os from ordered_set import OrderedSet from glob import glob from random import shuffle import numpy as npy import h5py def in_range(v, l, h): return l <= v and v <= h def _contains(s, seq): for c in seq: if c not in s: return Fals...
import os import sys sys.path.insert(0, os.path.abspath('../..')) extensions = [ 'sphinx.ext.autodoc', #'sphinx.ext.intersphinx', 'oslosphinx', 'reno.sphinxext' ] source_suffix = '.rst' master_doc = 'index' project = u'dragonflow' copyright = u'2013, OpenStack Foundation' add_function_parentheses = True...
from __future__ import print_function from __future__ import absolute_import import sys import six from six.moves import input from six.moves import range from six.moves import zip if sys.hexversion < 0x02040000: # The limiter is the subprocess module sys.stderr.write("git-p4: requires Python 2.4 or later.\n") ...
import bpy import numpy as np def makeMaterial(name, diffuse, specular, alpha, transparent=False, t_alpha = 0.5): mat = bpy.data.materials.new(name) mat.diffuse_color = diffuse mat.diffuse_shader = 'LAMBERT' mat.diffuse_intensity = 1.0 mat.specular_intensity = 0.5 mat.alpha = alpha mat.ambie...
"""Support for Meteoclimatic sensor.""" from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import D...
from six.moves import cPickle as pickle from ibeis_cnn import abstract_models from ibeis_cnn.abstract_models import * def check_external_training_paths(): """ Notes: http://cs231n.github.io/neural-networks-3/#distr """ checkpoints_dir = '.' checkpoints_dir = '/home/joncrall/.config/ibeis_cnn...
"""Main experiments script for pre-training MMV model OR vatt.""" from typing import Optional from absl import logging import numpy as np import tensorflow as tf from vatt.data import dataloaders from vatt.data import processing from vatt.experiments import base from vatt.modeling import factory as model_factory from v...
import unittest from mldb import mldb class BucketizeTest(unittest.TestCase): def test_it(self): url = '/v1/datasets/input' mldb.put(url, { 'type' : 'sparse.mutable' }) mldb.post(url + '/rows', { 'rowName' : 'row1', 'columns' : [['score', 5, 6]] ...
''' Block (DMRG) program has two branches. The OpenMP/MPI hybrid implementation Block-1.5 (stackblock) code is more efficient than the old pure MPI implementation Block-1.1 in both the computing time and memory footprint. This example shows how to input new defined keywords for stackblock program. Block-1.5 (stackbloc...
import os import stacktrain.config.general as conf conf.provider = "virtualbox" conf.share_name = "osbash" conf.share_dir = conf.top_dir conf.vm_ui = "headless" def get_base_disk_path(): return os.path.join(conf.img_dir, conf.get_base_disk_name() + ".vdi")
import argparse import logging from typing import Text, Union, Optional from rasa.shared.constants import ( DEFAULT_CONFIG_PATH, DEFAULT_DOMAIN_PATH, DEFAULT_MODELS_PATH, DEFAULT_DATA_PATH, DEFAULT_ENDPOINTS_PATH, ) def add_model_param( parser: argparse.ArgumentParser, model_name: Text = "Ra...
class Params(object): def __init__(self): self.addon_paths = [] self.cli_commands = [] params = Params()
from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.ca_common import is_containerized, \ generate_ceph_cmd, \ ...
import sys, os here = os.path.dirname(sys.argv[0]) sys.path.insert(0, os.path.join(here, "../../third_party/myelin-kicad.pretty")) import myelin_kicad_pcb Pin = myelin_kicad_pcb.Pin cart_front = myelin_kicad_pcb.Component( footprint="myelin-kicad:acorn_electron_cartridge_edge_connector", identifier="CART", ...
"""Module for measuring mutual information using kNN method. Using binning method for computing mutual information of ordinal features is not applicable in real use cases due to the bad accuracy. Instead, this module implements: (1) the algorithm in PRE paper 10.1103/PhysRevE.69.066138 (See the paper online at http://a...
''' Main package for greeterpy '''
""" :mod:`compute.cloudpipe` -- VPN Server Management ===================================================== .. automodule:: compute.cloudpipe :platform: Unix :synopsis: An OpenVPN server for every compute user. """
""" Views for managing Images and Snapshots. """ import logging from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tables from horizon import tabs from openstack_dashboard import api from .images.tables import ImagesTable from .snapshots.tables import SnapshotsTab...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('person', '0022_auto_20160225_2037'), ] operations = [ migrations.AlterField( model_name='patient', name='subsidiary_number', ...
import c4d from c4d import gui from c4d.modules import colorchooser as cc def main(): #Retrieves active object if op is None: return # Checks active object is a light if not op.IsInstanceOf(c4d.Olight): return # Initializes Kelvin temperature kelvin = 2600.0 # Light bulb # Co...
from setuptools import setup setup( name='remote_storage_finder', version='0.0.1', license='Apache 2', author=u'shandymora', description=('A plugin for connecting graphite-web with remote graphite-webs'), py_modules=('remote_storage_finder',), zip_safe=False, include_package_data=True, ...
import google.cloud.security.privateca_v1 as privateca_v1 def disable_certificate_authority( project_id: str, location: str, ca_pool_name: str, ca_name: str ) -> None: """ Disable a Certificate Authority which is present in the given CA pool. Args: project_id: project ID or project number of the...
from numpy import * from nn.base import NNBase from nn.math import softmax, make_onehot from misc import random_weight_matrix from sklearn import metrics def full_report(y_true, y_pred, tagnames): cr = metrics.classification_report(y_true, y_pred, target_names=tagnames) print cr def eval_performance(y_true, y_p...
import json import os import time import six from subprocess import check_output, CalledProcessError from .. import base from girder.api.describe import API_VERSION from girder.constants import SettingKey, SettingDefault, ROOT_DIR from girder.utility import config def setUpModule(): base.startServer() def tearDownM...
from locust import HttpLocust, TaskSet, task tlsJson = """ { "clientId":"13", "command":"security tls google.com", "responseAddress":"http://104.155.61.52:8008/jobFinished", "processors":[ "XmlToJsonConverter", "security.TlsCiphersuitesFilter" ], "adapter":"adapters.EventHubAdapter" } """ ...
from __future__ import absolute_import from pychron.entry.export.base_irradiation_exporter import BaseIrradiationExporter class XLSIrradiationExporter(BaseIrradiationExporter): """ export irradiations from pychron database to an xls file """
""" Helper functions for processing cloudwatch events. .. module: historical.cloudwatch :platform: Unix :copyright: (c) 2017 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. author:: Kevin Glisson <kglisson@netflix.com> """ import logging from datetime import datetime...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.natural_ventilation_and_duct_leakage import AirflowNetworkDistributionLinkage log = logging.getLogger(__name__) class TestAirflowNetworkDistributionLinkage(unittest.TestCase): ...
import threading, logging, time, signal from kafka import KafkaConsumer from kafka.errors import KafkaTimeoutError from .common import WoofNotSupported, CURRENT_PROD_BROKER_VERSION log = logging.getLogger("woof") class FeedConsumer(threading.Thread): """Threaded gomsg feed consumer callbacks are called on a sep...
a = 5 b = 5 print(id(a) == id(b)) c = 10000 d = 10000 print(id(c) == id(d))
""" This module is for writing files that summarize the results of the pipeline. """ """ Copyright 2010 Jarl Haggerty 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/LI...
import unittest import datetime import sys from airflow import DAG, configuration from airflow.models import TaskInstance from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator DEFAULT_DATE = datetime.datetime(2017, 1, 1) class TestSparkSubmitOperator(unittest.TestCase): _config = { ...
import mock import pytest import datetime from framework.auth.core import Auth from framework.exceptions import PermissionsError from osf.exceptions import UserNotAffiliatedError, DraftRegistrationStateError, NodeStateError from osf.models import RegistrationSchema, DraftRegistration, DraftRegistrationContributor, Node...
import os import sys import urllib2 import re from HTMLParser import HTMLParser import requests import time import commands UPSTREAM_URL = "http://192.168.3.251/ocselected-appliance/" DEST_DIR = "/data/testing/OCselected oVirt/" APPLIANCE_NAME = "OCselected oVirt-Engine-Appliance-4.1" pattern = re.compile(APPLIANCE_NAM...
import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../')) sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../example_project/')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings") from nuit.version import __VERSION__ intersphinx_mapping = { 'django': ('ht...
""" KubeVirt API This is KubeVirt API an add-on for Kubernetes. OpenAPI spec version: 1.0.0 Contact: kubevirt-dev@googlegroups.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubevirt from kub...
""" Copyright 2010-2012 Asidev s.r.l. 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, softwar...
import csv import re import sys NONALPHA_REX = re.compile('[^\d^\w]') MEDIAN_REX = re.compile(' median: ([\-?\d\.]+)') CATEGORY_REX = re.compile('\[(\(.+)\]$') ITEM_REX = re.compile("\(\'(.*?)\', \d+\)") KILL_X = re.compile(r"\\x\w\d") def safe_key(key, value): if not value: value = 'emptycat' return '%...
''' Test of the cost functions ''' import numpy as np from neon import NervanaObject from neon.transforms import (CrossEntropyBinary, CrossEntropyMulti, SumSquared, MeanSquared, Misclassification) def compare_tensors(func, y, t, outputs, deriv=False, tol=0.): be = NervanaObject.be t...
"""Collect information from various sources into Memory Map DataFrames.""" import bisect from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple from elftools.elf.constants import SH_FLAGS # type: ignore import pandas as pd # type: ignore import memdf.collector.bloaty import memdf.collector.csv im...
from __future__ import annotations from textwrap import dedent import pytest from pants.backend.python import target_types_rules from pants.backend.python.mixed_interpreter_constraints.py_constraints import PyConstraintsGoal from pants.backend.python.mixed_interpreter_constraints.py_constraints import ( rules as py...
from insights.parsers import nginx_conf from insights.tests import context_wrap NGINXCONF = """ user root; worker_processes 5; error_log logs/error.log; pid logs/nginx.pid; worker_rlimit_nofile 8192; events { worker_connections 4096; } mail { server_name mail.example.com; auth_http localhost:9000...
"""A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '2.1.3' import struct class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A...
from django.apps import AppConfig from actstream import registry from django.contrib.auth.models import User class JournalConfig(AppConfig): name = 'journal' def ready(self): registry.register(User, self.get_model('Entry'), self.get_model('Activity'), ...
from django import forms from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.forms import ModelForm, Form, ValidationError from django.forms.models import modelform_factory from django.utils.translation import ugettext as _ from bookswap.models import BookSwapPerson...
"""Network helpers.""" from ipaddress import ip_address from typing import Optional, cast import yarl from homeassistant.components.http import current_request from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.loader import bind_hass from homeassista...
"""Depthwise convolution schedule for ARM CPU""" import tvm from tvm import autotvm from ..generic import schedule_depthwise_conv2d_nchw from ..nn import depthwise_conv2d_nchw from ..util import traverse_inline autotvm.register_topi_compute(depthwise_conv2d_nchw, ['arm_cpu', 'cpu'], 'direct', ...
def handler(context, event): # modify the event body event.body['caller_body_value'] = 'caller_body' # modify event headers event.headers = { 'x-caller-header-value': 'caller_header' } # modify method event.method = 'PUT' # modify path event.path = '/caller/path' # return...
from __future__ import print_function from __future__ import division from __future__ import absolute_import import copy import json import jsonschema import os from oslo_config import cfg from oslo_db import exception as db_exc from oslo_log import log as logging import yaml from congress.datalog import compile from c...
import pytest from google.api_core import client_options def test_constructor(): options = client_options.ClientOptions(api_endpoint="foo.googleapis.com") assert options.api_endpoint == "foo.googleapis.com" def test_from_dict(): options = client_options.from_dict({"api_endpoint": "foo.googleapis.com"}) ...
import os import subprocess import nodechecker.control.nodemanager import nodechecker.main import daemon NODECHECKER_PID_FILE = 'nodechecker/var/run/oi3-nodechecker.pid' START_SCRIPT = "bin/start.sh" STOP_SCRIPT = "bin/stop.sh" COLLECTD_STOP_SCRIPT = 'sbin/stop.sh' SUDO = 'sudo' class NodecheckerDaemon(daemon.Daemon): ...
"""A script to export the BERT core model as a TF-Hub SavedModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags from absl import logging import tensorflow as tf from typing import Text from official.nlp.bert im...
""" Load Config in commands """ import os import sys from argparse import ArgumentParser from paste.deploy import appconfig from ebetl.config.environment import load_environment from ebetl import model from ebetl.lib.etl.filconad import FilconadObj from paste.script.command import Command def load_config(args): if ...
from __future__ import absolute_import import logging import tkp.steps from tkp.steps.misc import ImageMetadataForSort from tkp.steps.forced_fitting import perform_forced_fits logger = logging.getLogger(__name__) def extract_metadatas(accessors, sigma, f): logger.debug("running extract metadatas task") return t...
''' Created by auto_sdk on 2015.04.21 ''' from aliyun.api.base import RestApi class Ecs20140526AllocatePublicIpAddressRequest(RestApi): def __init__(self,domain='ecs.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.InstanceId = None self.IpAddress = None self.VlanId = None def getapiname(self)...
"""Script for doing QA on Ganeti. """ import copy import datetime import optparse import sys from qa import colors from qa import qa_cluster from qa import qa_config from qa import qa_daemon from qa import qa_env from qa import qa_error from qa import qa_filters from qa import qa_group from qa import qa_instance from q...
from .benchmark import run_pyexcelerate_value_fastest, run_xlsxwriter_value, run_openpyxl from nose.tools import ok_ import nose def test_vs_xlsxwriter(): raise nose.SkipTest('Skipping speed test') ours = run_pyexcelerate_value_fastest() theirs = run_xlsxwriter_value() ok_(ours / theirs <= 0.67, msg='PyExcelerate i...
""" Going Down! This is the first level. Zort has been shot out of orbit and crashlanded here. This level should be relatively straight forward and take no more than 2 minutes to complete. There should be no monsters, an obvious path, one door and one switch to go through. """ from zort.entity import * from zort.enemie...
from django.contrib import admin from payway.webmoney.models import Purse, ResultResponsePayment __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' admin.site.register(Purse) admin.site.register(ResultResponsePayment)
import copy from saml2 import samlp, SamlBase from saml2 import NAMEID_FORMAT_EMAILADDRESS from saml2 import BINDING_HTTP_REDIRECT from saml2 import BINDING_HTTP_POST from saml2.s_utils import rndstr from saml2.saml import SCM_BEARER, Condition, XSI_TYPE, Audience from saml2.saml import NAMEID_FORMAT_PERSISTENT from sa...
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('utils', parent_package, top_path) config.add_subpackage('math') config.add_subpackage('tests') config.add_subpackage('randomkit') config.add_subpackage('recsys') r...
from setuptools import setup, find_packages from os import path pwd = lambda f: path.join(path.abspath(path.dirname(__file__)), f) contents = lambda f: open(pwd(f)).read().strip() package = 'disposable_consul' setup( name=package, version=contents('VERSION'), py_modules=[package], author='EverythingMe',...
import sys, getopt sys.path.insert(0, '/home/tzeng/caffe_flx_kernel/python') import os import leveldb import numpy as np import hdf5storage import time import caffe print os.path.dirname(caffe.__file__) from caffe.proto import caffe_pb2 db_path_label ='/home/tzeng/ABA/autoGenelable_multi_lables_proj/code/caffe/models/v...
from HelloWorld import cute_split_line from PIL import Image img = Image.open('Saturn.jpg') w, h = img.size print("Original image size: %s*%s"%(w, h)) img.thumbnail((w/2, h/2)) print("resize image size to: %s*%s"%(w/2, h/2)) img.save('thumbnail.jpg', 'jpg')
from django.urls import reverse from django.contrib import admin from django.db import models from django.forms import TextInput, Textarea from django.utils.safestring import mark_safe from taggit.forms import TagField from taggit_labels.widgets import LabelWidget from conference import admin as cadmin from conference ...
""" Floyd-Warshall algorithmf or shortest paths. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __all__ = ['floyd_warshall', 'floyd_warshall_predecessor_and_distance', 'floyd_warshall_numpy'] import networkx as nx def floyd_warshall_numpy(G,nodelist=None): """Find all-pairs shortest pa...
from JumpScale import j import os def _setup_stacktrace_hook(): '''Set up SIGUSR2 signal handler which dumps stack traces of all threads''' try: import signal except ImportError: # No signal support on current platform, ignore return sig = signal.SIGUSR2 def stderr(): ...
import sys import unittest from .. import utils from ..apps import kitchen_sink_app if utils.py3: import urllib.request as urllib_request import http.cookiejar as cookielib def decode_str(str): return str.decode('utf8') else: import urllib2 as urllib_request import cookielib def decode_s...
import builtins import datetime as dt import io import re import sys import tempfile import typing as tg import pytest import typecheck as tc import typecheck.framework as fw from typecheck.testhelper import expected X = tg.TypeVar('X') Tb = tg.TypeVar('Tb', bound=dt.date) Tc = tg.TypeVar('Tc', str, bytes) def test_typ...
from datetime import date from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_date05.xlsx') ...
from distutils.core import setup setup(name='pma', version='0.1', description='A simple script to create email backends on SQLite/PSQL/MySQL', author='fim', scripts=['pma'] )
from pygments.style import Style from pygments.token import (Keyword, Name, Comment, String, Error, Number, Operator, Generic, Whitespace, Punctuation, Other, Literal) class FlaskyStyle(Style): background_color = "#f8f8f8" default_style = "" styles = {...
import os import dj_database_url from .base import * # noqa: F401,F403 DEBUG = False SECRET_KEY = os.environ['SECRET_KEY'] DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME', None) # noqa: F405 SENDGRID_PASSWORD = os.environ.get('SENDGRID_PAS...