code
stringlengths
1
199k
import os from wit import Wit from config import config from util import get_summarized_entities, get_message_text from story import Stories from sessions import Session from bot.constants import LOGGER WIT_ACCESS_TOKEN = os.environ.get('WIT_ACCESS_TOKEN', None) client = Wit(access_token=WIT_ACCESS_TOKEN) def process_m...
import asyncio import functools import io import json import unittest import zlib from unittest import mock import pytest import aiohttp.multipart from aiohttp import helpers, payload from aiohttp.hdrs import (CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_TRANSFER_ENCODING, CONTENT_TYPE) from...
"""The output file handler for click""" import click from l2tscaffolder.frontend import output_handler class OutputHandlerClick(output_handler.BaseOutputHandler): """Output handler for click.""" def Confirm(self, text: str, default=True, abort=True): """Returns a bool from a yes/no question presented to the end...
"""No U-Turn Sampler. The implementation closely follows [1; Algorithm 3], with Multinomial sampling on the tree (instead of slice sampling) and a generalized No-U-Turn termination criterion [2; Appendix A]. Achieves batch execution across chains by precomputing the recursive tree doubling data access patterns and then...
from nltk import word_tokenize,pos_tag from nltk.corpus import stopwords from read_ppdb import read_ppdb from nltk.util import ngrams from math import ceil ''' * python file to drive the program using PPDB word distribution * * Copyright 2015 Vedsar * * Licensed under the Apache License, Version 2.0 (the "License"...
from dronedemo.main import app def cli_entry(): app.run(host='0.0.0.0', port=5000)
"""Test cmdline.py for coverage.py.""" import pprint import re import shlex import sys import textwrap import mock import coverage import coverage.cmdline from coverage.config import CoverageConfig from coverage.data import CoverageData, CoverageDataFiles from coverage.misc import ExceptionDuringRun from tests.coverage...
from mock import patch, Mock import pytest from aeon.exceptions import ProbeError from aeon.base.device import BaseDevice @patch('pylib.aeon.base.device.socket.socket') def test_base_device_probeerror(mock_socket): mock_socket.return_value.connect.side_effect = Exception() target = '1.1.1.1' user = 'test_us...
"""Resource Descriptors for the `Google Monitoring API (V3)`_. .. _Google Monitoring API (V3): https://cloud.google.com/monitoring/api/ref_v3/rest/v3/\ projects.monitoredResourceDescriptors """ import collections from gcloud.monitoring.label import LabelDescriptor class ResourceDescriptor(object): """Specif...
import unittest import numpy as np from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers.activations_tf import get_tf_activation @require_tf class TestTFActivations(unittest.TestCase): def test_gelu_10(self)...
from rdmo.core.renderers import BaseXMLRenderer class ConditionsRenderer(BaseXMLRenderer): def render_condition(self, xml, condition): xml.startElement('condition', {'dc:uri': condition['uri']}) self.render_text_element(xml, 'uri_prefix', {}, condition['uri_prefix']) self.render_text_element...
import pymongo import bson from bson import json_util import warnings from cStringIO import StringIO from pymongo import Connection, uri_parser, ReadPreference import bson.son as son import json import logging ''' File: scheme_mongo_clean.py Description: ''' def open(uri, task=None): #parses a mongodb uri and retur...
from google.cloud import tasks_v2beta2 def sample_renew_lease(): # Create a client client = tasks_v2beta2.CloudTasksClient() # Initialize request argument(s) request = tasks_v2beta2.RenewLeaseRequest( name="name_value", ) # Make the request response = client.renew_lease(request=reque...
import random import unittest import numpy as np from sklearn import metrics from fate_arch.session import computing_session as session from federatedml.loss import SigmoidBinaryCrossEntropyLoss from federatedml.loss import SoftmaxCrossEntropyLoss from federatedml.util import consts class TestSigmoidBinaryCrossEntropyL...
from collections import OrderedDict from Queue import Queue, Empty from types import MethodType import threading import sys import io from parser import Parser from lib.model.Elements import Statement, Block, IfStatement, WhileStatement, LogicalOperator, CompareOperator from util.Res import Res from util.log import * f...
import json import logging from google.datacatalog_connectors.apache_atlas.scrape import \ apache_atlas_event_facade from google.datacatalog_connectors.apache_atlas.scrape import \ metadata_event_enricher from google.datacatalog_connectors.apache_atlas.scrape import \ metadata_enricher from google.datacatal...
import BeautifulSoup import ccss import json from xml.sax import saxutils LOG = None DEBUG = False def application(environ, start_response): global LOG LOG = environ["wsgi.errors"] global DEBUG output = [ "============", "Test Results", "============"] queriesOpts = [ ...
"""Module containing python 3 dev installation and cleanup functions.""" def YumInstall(vm): """Installs the package on the VM.""" vm.InstallPackages('python3-devel') def AptInstall(vm): """Installs the package on the VM.""" vm.InstallPackages('python3-dev')
"""Runs wrk2 clients against replicated nginx servers behind a load balancer.""" import functools import os import shutil import tempfile from absl import flags from perfkitbenchmarker import configs from perfkitbenchmarker import data from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_benchmarks impo...
print('Герой нашей сегодняшней программы - Алексей Максимович Пешков') name = input('Под каким именем мы знаем этого человека? Ваш ответ:') print(name) print('Всё верно:Алексей Максимович Пешков - Максим Горький') print('\nНажмите Enter для завершения программы') input()
import os print "################################description##################################" print "# Setup environment for all python modules under current path, by appending path item for the" print "# subdirectory to environment variable called PYTHONPATH in ~/.bash_profile." print "#" print "# [Note] After this ...
from __future__ import division import numpy as np from ..constants import molwt def regress(emissions, beta=np.array([2.8249e-4, 1.0695e-4, -9.3604e-4, 99.7831e-4])): """Calculates tropospheric ozone forcing from precursor emissions. Inputs: (nt x 40) emissions array Keywords: beta: 4-e...
"""OSF mailing utilities. Email templates go in website/templates/emails Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails. You can then create a `Mail` object given the basename of the template and the email subject. :: CONFIRM_EMAIL = Mail(tpl_prefix='confirm', subject="Con...
import inspect import os import pickle import subprocess import sys import types from inspect import signature from itertools import islice from textwrap import dedent from typing import Callable, Dict, Iterable, List, Optional import dill from airflow.exceptions import AirflowException from airflow.models import BaseO...
"""Application mode plugin.""" import gettext from otopi import plugin, util from ovirt_engine_setup import constants as osetupcons from ovirt_engine_setup.engine import constants as oenginecons from ovirt_engine_setup.engine import vdcoption from ovirt_engine_setup.engine_common import constants as oengcommcons def _(...
""" Fibre channel Cinder volume driver for Hitachi storage. """ from contextlib import nested import os import threading from oslo.utils import excutils from oslo_config import cfg import six from cinder import exception from cinder.i18n import _LW from cinder.openstack.common import log as logging from cinder import u...
from __future__ import unicode_literals from cesiumpy.base import _CesiumEnum class VerticalOrigin(_CesiumEnum): BOTTOM = 'Cesium.VerticalOrigin.BOTTOM' CENTER = 'Cesium.VerticalOrigin.CENTER' TOP = 'Cesium.VerticalOrigin.TOP' class HorizontalOrigin(_CesiumEnum): CENTER = 'Cesium.HorizontalOrigin.CENTER...
''' Created on 2016. 11. 19 Updated on 2016. 01. 09 ''' from __future__ import print_function import os import shutil import codecs import cgi import re from dateutil import parser as dateparser from commons import VersionUtil from pytz import timezone from utils import Progress from bs4 import BeautifulSoup class BugF...
import sys sys.path.append('/home/uperetz/sources/py-modules') from ccfdefs import PICCF from interpolations import Curve from plotInt import plt, Iplot from binpeak import Phistogram import randomizers import code class ICCF: def __init__( self, LC1 = None, LC2 = None ): LCs = [] names = ("First",...
from entity import Entity import task class Section(task.Task): _matchon = None @classmethod def _filter_result_item(cls, entity, query): return Entity._filter_result_item(entity, query) @classmethod def _get_api_endpoint(cls): """Point to tasks""" return task.Task._get_api_endpoint() @classmethod def _bui...
""" openconfig_inventory_types This module defines data types (e.g., YANG identities) to support the OpenConfig component inventory model. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError...
from stromx import runtime, cvimgproc, cvsupport factory = runtime.Factory() runtime.register(factory) cvimgproc.register(factory) cvsupport.register(factory) stream = runtime.XmlReader().readStream("camera.xml", factory) stream.start() camera = stream.operators()[0] canny = stream.operators()[2] for i in range(5): ...
import datetime import webob from nova.api.openstack.compute.contrib import flavormanage from nova.compute import instance_types from nova import exception from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes def fake_get_instance_type_by_flavor_id(flavorid, ctxt=...
"""Simple text browser for IDLE """ from tkinter import Toplevel, Text, TclError,\ HORIZONTAL, VERTICAL, NS, EW, NSEW, NONE, WORD, SUNKEN from tkinter.ttk import Frame, Scrollbar, Button from tkinter.messagebox import showerror from functools import update_wrapper from idlelib.colorizer import color_config class Au...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( _delete_=True, type='RegNet', arch='regnetx_3.2gf', out_indices=(0, 1, 2, 3), ...
"""Flags used by uflow training and evaluation.""" from absl import flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'no_tf_function', False, 'If True, run without' ' tf functions. This incurs a performance hit, but can' ' make debugging easier.') flags.DEFINE_string('train_on', '', '"format...
import arrays,re,db,client def IsRegister(user): try: InDB=re.compile(r'%s' % user, re.IGNORECASE) except sre_constants.error: InDB=re.compile(r'Fgt5dR5s333', re.IGNORECASE) isRegister=False while isRegister == False: for i in arrays.DB_user: if InDB.match(i[0][0]): posc=arrays.DB_user.index(i) isR...
import rospy import sys import json from interactivespaces_msgs.msg import GenericMessage from lg_msg_defs.srv import USCSMessage, USCSMessageResponse, InitialUSCS, InitialUSCSResponse try: rospy.init_node('director_messager') rospy.sleep(1) service = rospy.ServiceProxy('/uscs/message', USCSMessage, persist...
__author__ = 'Joe Linn' import urllib3 import json import pylastica.transport import pylastica.exception.connection class Http(pylastica.transport.AbstractTransport): _scheme = 'http' METHOD_GET = 'GET' METHOD_POST = 'POST' METHOD_PUT = 'PUT' METHOD_DELETE = 'DELETE' def __init__(self, connectio...
from oslo_policy import policy rules = [ policy.RuleDefault( 'get_loggable_resource', 'rule:admin_only', description='Access rule for getting loggable resource'), policy.RuleDefault( 'create_log', 'rule:admin_only', description='Access rule for creating network lo...
from models.tridentnet.builder import TridentFasterRcnn as Detector from models.tridentnet.builder import TridentMXNetResNetV2 as Backbone from models.tridentnet.builder import TridentRpnHead as RpnHead from models.tridentnet.builder import process_branch_outputs, process_branch_rpn_outputs from symbol.builder import N...
def test_multiple_argument_options(run_line, go_ep1_id): """ Runs endpoint create with two --shared options Confirms exit code is 2 after click.BadParamater is raised """ result = run_line( ( "globus endpoint create ep_name " "--shared {0}:/ --shared {0}:/".format(go_...
from gcloud.datastore import demo demo.initialize() from gcloud import datastore key = datastore.Key('Thing') toy = datastore.Entity(key) toy.update({'name': 'Toy'}) datastore.put([toy]) print(datastore.get([toy.key])) datastore.delete([toy.key]) print(datastore.get([toy.key])) SAMPLE_DATA = [ (1234, 'Computer', 10...
from testlib import mox import unittest from google.appengine.ext import ndb import unittest from google.appengine.api import datastore from google.appengine.ext import db from mapreduce import context from testlib import testutil class TestEntity(db.Model): """Test entity class to test db operations.""" tag = db.T...
import datetime import os import sys import edx_theme from unittest import mock MOCK_MODULES = [ 'webob', 'lxml' ] for mod_name in MOCK_MODULES: sys.modules[mod_name] = mock.Mock(class_that_is_extended=object) sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('..xblock',)) from xb...
from distutils.core import setup, Extension import glob import numpy import config import sys import os import os.path from config import ROOT import re includes = [os.path.join(ROOT,"Include"),os.path.join(ROOT,"PrivateInclude"),os.path.join("cmsisdsp_pkg","src")] if sys.platform == 'win32': cflags = ["-DWIN",config...
import os import os.path import shutil import time from dtest import Tester from tools import sslkeygen from tools.decorators import since _LOG_ERR_HANDSHAKE = "javax.net.ssl.SSLHandshakeException" _LOG_ERR_GENERAL = "javax.net.ssl.SSLException" @since('3.6') class TestNodeToNodeSSLEncryption(Tester): def ssl_enabl...
""" Copyright 2012 GroupDocs. 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 writ...
"""Common FoglampProcess Class""" from abc import ABC, abstractmethod import argparse import time from foglamp.common.storage_client.storage_client import StorageClientAsync, ReadingsStorageClientAsync from foglamp.common import logger from foglamp.common.microservice_management_client.microservice_management_client im...
from typing import Callable from typing import Dict from typing import List from typing import Type from typing import Union from nacl.encoding import HexEncoder from nacl.signing import SigningKey from nacl.signing import VerifyKey import torch as th from .....common.group import VerifyAll from .....common.message imp...
try: import json except ImportError: import simplejson as json import time from django.contrib.auth.models import User from django.core.urlresolvers import reverse from nose.tools import assert_true, assert_equal from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant...
""" :maintainer: SaltStack :maturity: new :platform: all Utilities supporting modules for Hashicorp Vault. Configuration instructions are documented in the execution module docs. """ import base64 import logging import os import time import requests import salt.crypt import salt.exceptions import salt.util...
"""Manage servers Usage: haproxytool server [-D DIR | -F SOCKET] (-A | -r | -s | -e | -R | -p | -W | -i | -c | -C | -S | -X) [--backend=<name>...] [NAME...] haproxytool server [-D DIR | -F SOCKET] -w VALUE [--backend=<name>...] [NAME...] haproxytool server [-D D...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eu_elections_analytics.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
class Solution: def numTrees(self, n: int) -> int: cache = [None for _ in range(n+1)] res = self.countTrees(n, cache) return res def countTrees(self, n: int, cache: list) -> int: # Base cases if n == 0: return 1 if cache[n]: return cache[n]...
import warnings from collections import Counter, defaultdict from great_expectations.core.profiler_types_mapping import ProfilerTypeMapping from great_expectations.render.renderer.renderer import Renderer from great_expectations.render.types import ( CollapseContent, RenderedBulletListContent, RenderedHeade...
"""Utilities for generating input embeddings and output embedding table.""" import math from language.xsp.model import bert_utils from language.xsp.model import common_layers from language.xsp.model import constants import tensorflow.compat.v1 as tf import tensorflow.compat.v1.gfile as gfile EPSILON = 0.00000001 def _g...
import sys class Solution(object): chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def convertToTitle(self, n): """ :type n: int :rtype: str """ if n <= 26: return Solution.chars[n-1] d = 26 t = 26 while t + d * 26 < n: d *= 26 t += d s = '' while d > 0: # print >>sys.stderr, s, d, n, t, Solution...
print ("Hello, World!") print ("Hellp anain") print ("I like typing this.") print ("This is fun.") print ('Yay! Printing') print ("I'd much rather you 'not'.") print ('I "said" do not touch this.')
"""Mobilenet Base Class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import contextlib import copy import os import contextlib2 import tensorflow as tf slim = tf.contrib.slim @slim.add_arg_scope def apply_activation(x, name=None, act...
from testrunner.testhelp import context import copy import sys from StringIO import StringIO import time from conary.build import errors as cvcerrors, packagerecipe, source from conary import checkin from conary import deps from conary import errors from conary import files, keymgmt from conary import state from conary...
import os import re import time from dataclasses import dataclass from pathlib import Path from textwrap import dedent from typing import Any from pants.backend.codegen.antlr.java.antlr_java_gen import AntlrJavaGen from pants.backend.codegen.antlr.java.java_antlr_library import JavaAntlrLibrary from pants.base.exceptio...
"""ThreatConnect SecurityLabel Object""" import json from typing import Optional class SecurityLabel: """ThreatConnect Batch SecurityLabel Object.""" __slots__ = ['_label_data'] def __init__(self, name: str, description: Optional[str] = None, color: Optional[str] = None): """Initialize Class Propert...
""" Copyright 2017-present Airbnb, 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, softwa...
"""Openstack logging handler. This module adds to logging functionality by adding the option to specify a context object when calling the various log methods. If the context object is not specified, default formatting is used. Additionally, an instance uuid may be passed as part of the log message, which is intended t...
import mock from heat.engine.clients.os import zaqar from heat.tests import common from heat.tests import utils class ZaqarClientPluginTests(common.HeatTestCase): def test_create(self): context = utils.dummy_context() plugin = context.clients.client_plugin('zaqar') client = plugin.client() ...
from __future__ import division from builtins import map, str, zip from future.utils import native from collections import deque import h5py import inspect import logging import numpy as np import os import signal import sys import time import math from timeit import default_timer import weakref from neon import Nervan...
''' Copyright 2017, Fujitsu Network Communications, 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 w...
""" this module holds methods for dealing with LDAP this should only, generally speaking, be used to talk with an LDAP server all user interaction should be done in the mothership.users module """ import os import ldap import mothership.validate import mothership.users import mothership.kv from mothership.mothership_mo...
from __future__ import absolute_import try: import unittest2 as unittest except ImportError: import unittest # noqa from datetime import datetime from uuid import uuid4 from packaging.version import Version import uuid from cassandra.cluster import Session from cassandra import InvalidRequest from tests.integr...
"""Defines an eval actor.""" import os from absl import logging from ibc.environments.d4rl import metrics as d4rl_metrics from ibc.ibc import tasks from ibc.ibc.utils import strategy_policy from tf_agents.train import actor def log_episode_complete(traj): if traj.is_boundary(): logging.info('Completed episode.') ...
"""settings.py Udacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ WEB_CLIENT_ID = '615693265950\ -eiaunrfdk04amm7t9ifagbmoaiqff3p2.apps.googleusercontent.com' ANDROID_CLIENT_ID = 'replace with Android client ID' IOS_CLIENT_ID = 'replace w...
import numpy as np import gym from typing import Dict, Optional, Sequence from ray.rllib.models.tf.misc import normc_initializer from ray.rllib.models.tf.tf_modelv2 import TFModelV2 from ray.rllib.models.utils import get_activation_fn from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils.framework ...
from random import randint def swap(l, a, b): t = l[a] l[a] = l[b] l[b] = t def partition(l, left, right, p_idx): """ Used by quicksort and quickselect. l: the entire list left: the smallest index to partition right: the largest index to partition p_idx: the pivit's initial index Returns the pivot's final ind...
import django from cobra.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('organization', 'Organization'): class Organization(AbstractOrganization): pass __all__.append('Organization') if not is_model_registered('organization', 'Organ...
import datetime from django import forms from django.core import urlresolvers from django.db import models from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from purr import managers class Base(models.Model): #---------------------------------- # All data...
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u...
import sys import numpy as np, math import matplotlib.pyplot as pp import roslib; roslib.load_manifest('hrl_common_code_darpa_m3') import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu def draw_obstacles(ctype_list, pos_list, dimen_list, color): if len(pos_list) == 0: return pos_arr = np.array...
import sys,getopt,struct,signal from pydbg import * from pydbg.defines import * from pydbg.pydbg_core import * from IPython.Shell import IPShellEmbed import time from subprocess import * def convert_be(buffer): i = 0 i = ord(buffer[0]) & 0x0ff i += ord(buffer[1]) << 8 & 0xff00 i += ord(buffer[2]) << 16 & 0x0FF0000 ...
""" PCP provides MPI-based parallel data transfer functionality. Author: Feiyi Wang (fwang2@ornl.gov) """ from __future__ import print_function, division import time import stat import os import shutil import os.path import hashlib import sys import signal import resource import sqlite3 import math import cPickle as pi...
import unittest import pytz from mobly import logger class LoggerTest(unittest.TestCase): """Verifies code in mobly.logger module. """ def test_epoch_to_log_line_timestamp(self): actual_stamp = logger.epoch_to_log_line_timestamp( 1469134262116, time_zone=pytz.utc) self.assertEqua...
from warnings import warn from .checks import check_user_id class User(object): """ The User class can be used to call user specific functions. """ def __init__(self, api, user_id, displayname=None): check_user_id(user_id) self.user_id = user_id self.displayname = displayname ...
"""Support for August sensors.""" import logging from yalexs.activity import ActivityType from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, SensorEntity from homeassistant.const import ATTR_ENTITY_PICTURE, PERCENTAGE, STATE_UNAVAILABLE from homeassistant.core import callback from homeassistant.helpers.e...
"""added tenant informations Revision ID: 792b438b663 Revises: 17fd1b237aa3 Create Date: 2014-12-02 13:12:11.328534 """ revision = '792b438b663' down_revision = '17fd1b237aa3' from alembic import op # noqa: E402 import sqlalchemy as sa # noqa: E402 def upgrade(): op.add_column('rated_data_frames', ...
import os import paramiko from clearstack.controller import Controller from clearstack.common import util from clearstack.common.util import LOG from clearstack.common.singleton import Singleton @Singleton class SshHandler(object): def __init__(self): conf = Controller.get().CONF path = os.path.expa...
input = """ :- not a. a :- c. c | b | e. c | b. d | e. :- a, d, e. """ output = """ :- not a. a :- c. c | b | e. c | b. d | e. :- a, d, e. """
from datetime import datetime import calendar from direct.gui.DirectGui import DirectFrame, DirectLabel from toontown.toonbase import TTLocalizer from direct.showbase import PythonUtil from direct.fsm.FSM import FSM from toontown.parties import PartyGlobals from toontown.parties import PartyUtils from toontown.toonbase...
from sqlalchemy import MetaData, Table, String, Text meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine records_table = Table('records', meta, autoload=True) records_table.c.content.alter(type=Text) def downgrade(migrate_engine): meta.bind = migrate_engine records_table = Tabl...
from __future__ import absolute_import from itertools import islice def normalize_reference(cell_range): # Normalize range to a str or None if not cell_range: cell_range = None elif isinstance(cell_range, str): cell_range = cell_range.upper() else: # Assume a row generator cell_...
from django.db import models class Genres(models.Model): genre = models.CharField(max_length=100, verbose_name="Genre") def __str__(self): return self.genre class Films(models.Model): title = models.CharField(max_length=100, verbose_name="Film Title") genre = models.ForeignKey(Genres, default=1) def __s...
import binascii import dis import marshal import struct import sys import time import types def show_pyc_file(fname): f = open(fname, "rb") magic = f.read(4) print("magic %s" % (binascii.hexlify(magic))) read_date_and_size = True if sys.version_info >= (3, 7): # 3.7 added a flags word ...
"""Views tests for the OSF.""" from __future__ import absolute_import import datetime as dt import httplib as http import json import math import time import unittest import urllib import datetime import mock from nose.tools import * # noqa PEP8 asserts from modularodm import Q from modularodm.exceptions import Valida...
from __future__ import unicode_literals from moto import mock_xray_client, XRaySegment, mock_dynamodb2 import sure # noqa import boto3 from moto.xray.mock_client import MockEmitter import aws_xray_sdk.core as xray_core import aws_xray_sdk.core.patcher as xray_core_patcher import botocore.client import botocore.endpoin...
from django.db import models from django.contrib.auth.models import UserManager, AbstractUser from tinymce.models import HTMLField class Course(models.Model): ''' A course has: * a name * a description Furthermore, a course is linked by a many-to-many relationship with: ...
from __future__ import absolute_import, division, print_function, unicode_literals import os.path from zipfile import ZIP_DEFLATED from pants.fs.archive import ZipArchiver from pants.task.task import Task from pants.util.dirutil import safe_mkdir from fsqio.pants.node.targets.webpack_module import NpmResource from fsqi...
""" This is the default grains matcher function. """ import logging import salt.utils.data from salt.defaults import DEFAULT_TARGET_DELIM log = logging.getLogger(__name__) def match(tgt, delimiter=DEFAULT_TARGET_DELIM, opts=None, minion_id=None): """ Reads in the grains glob match """ if not opts: ...
__author__ = """Chris Tabor (dxdstudio@gmail.com)""" from Queue import Queue import threading if __name__ == '__main__': from os import getcwd from os import sys sys.path.append(getcwd()) from MOAL.helpers.text import gibberish from MOAL.helpers.display import Section COUNT_LOCK = threading.Lock() DEBUG = T...
import sys, os sys.path.insert(1, os.path.join("..","..")) import h2o from tests import pyunit_utils def deep_learning_metrics_test(): # connect to existing cluster df = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) df.drop("ID") # remove ID df['CAPSULE'...
from django.shortcuts import render, HttpResponseRedirect, HttpResponse from usuario.models import Usuario from rest_framework import status, viewsets, filters from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAdminUser from django.short...
import io import sys import typing import click @click.command() @click.option('--request', type=click.File('rb'), default=sys.stdin.buffer, help='Location of the `CodeGeneratorRequest` to be dumped. ' 'This defaults to stdin (which is what protoc uses) ' 'but this op...