content
stringlengths
4
20k
# coding=utf-8 from django.conf.urls import url from .views import ( AliTemplateView, AliVideoconferenciasDetailView, AreaDetailView, AulaDetailView, CuerpoDetailView, IndexView, LaboratorioDetailView, LaboratorioInformaticoDetailView, LaboratorioInformaticoListView, NivelDetai...
#!/usr/bin/env python import codecs def getisocodes_dict(data_path): # Provide a map from ISO code (both bibliographic and terminologic) # in ISO 639-2 to a dict with the two letter ISO 639-2 codes (alpha2) # English and french names # # "bibliographic" iso codes are derived from English word for ...
""" Django settings for CartaAlFuturo project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ....
import time, urllib.parse import requests, tldextract from . import common from ..lib import log_response class RackspaceDns(common.BaseDns): def __init__(self, RACKSPACE_USERNAME, RACKSPACE_API_KEY, **kwargs): self.RACKSPACE_DNS_ZONE_ID = None self.RACKSPACE_USERNAME = RACKSPACE_USERNAME ...
# -*- coding: utf-8 -*- """ odeExample - example of integration of ordinary differential equations in the form of an understandable physical system that can be visualized by middle and high school students Equations of motion of a shot put and plastic-like ball with drag in 2-dimensi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Module for rebuilding all atom representation from reduced, 3 atom representation. """ import os DIRNAME = os.path.dirname(__file__) from subprocess import Popen from shutil import copyfile, rmtree from tempfile import mkdtemp from .SingleLineUtils import get_res_num fr...
from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from django import forms from django.contrib.contenttypes.models import ContentType from dcim.models import Device from extras.forms import ( AddRemoveTagsForm, CustomFieldBulkEditForm, CustomFieldFilterForm, CustomFieldModelForm, CustomFieldMod...
""" Test various MRO scenarios w.r.t. multiple inheritance. Not a real test, but demonstrates some Python 3.x concepts. """ import unittest from abc import abstractmethod, ABCMeta TRACE = '' # an abstract class A class A(metaclass=ABCMeta): @abstractmethod def close(self): pass # B is an A with a ...
import nest import unittest class TestStringMethods(unittest.TestCase): # test circular buffer def test_circular_buffer(self): nest.ResetKernel() nest.CopyModel("spore_test_node", "test_circular_buffer", {"test_name": "test_circular_buffer"}) nest.Create("test_circular_buffer", 1) ...
import io from http import client import pytest import aiohttpretty from waterbutler.core import streams from waterbutler.core import exceptions from waterbutler.core.path import WaterButlerPath from waterbutler.providers.nextcloud import NextcloudProvider from waterbutler.providers.nextcloud.metadata import (Nextclo...
""" Wraps scheduling functionality. """ from sleekxmpp.plugins.base import base_plugin import uuid import logging logger = logging.getLogger(__name__) def _generate_cancel_method(scheduler_name, scheduler): """ Handler that will be used to interact with the tasks that are going to be executed or not. """...
import os from collections import OrderedDict from distutils.util import strtobool from hurumap.settings import * # noqa # insert our overrides before both census and hurumap INSTALLED_APPS = ['hurumap_ke'] + INSTALLED_APPS DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://hu...
DEBUG = False PER_AI = True # if True, generate random_samples on each Ai MCZERO = False # if True, McD[i] == 0 when STATUS[i] = SUCCESS ####################################################################### # scaling and mpi info; also optimizer configuration parameters # hard-wired: use DE solver, don't use mpi, F-F...
# encoding: utf-8 # pylint: disable=missing-docstring import logging from six import itervalues from flask_marshmallow import Schema, base_fields from marshmallow import validate, validates_schema, ValidationError log = logging.getLogger(__name__) # pylint: disable=invalid-name class Parameters(Schema): cla...
from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from extuser.models import CustomUser # модель марки автомобиля class CarMark(models.Model): name = models.CharField(max_length=32) def __str__(self): return '{}'.format(self.name) # модель модели а...
#https://raw.githubusercontent.com/bslatkin/effectivepython/master/example_code/item_37.py # 37 Use Threads for Blocking I/O, Avoid for Parallelism import logging from pprint import pprint from sys import stdout as STDOUT # Example 1 def factorize(number): for i in range(1, number + 1): if number % i =...
from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit from crispy_forms.bootstrap import FormActions from ..models import Student class StudentEditFo...
import os import threading import time import uuid import random import traceback from cryptography import fernet from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import strutils from oslo_utils import timeutils from tacker._i18n import _ from tacker.comm...
""" CloudInitCustomeNetwork - file ``/etc/cloud/cloud.cfg.d/99-custom-networking.cfg`` ================================================================================== This module provides parsing for cloudinit custom networking configuration file. ``CloudInitCustomNetworking`` is a parser for ``/etc/cloud/cloud.cfg...
from dipy.denoise.enhancement_kernel import EnhancementKernel from dipy.denoise.shift_twist_convolution import convolve, convolve_sf from dipy.reconst.shm import sh_to_sf, sf_to_sh from dipy.core.sphere import Sphere from dipy.data import get_sphere import numpy as np import numpy.testing as npt def test_enhancement_...
from portage import os from portage.util import grabfile_package, stack_lists from portage._sets.base import PackageSet class ProfilePackageSet(PackageSet): _operations = ["merge"] def __init__(self, profiles, debug=False): super(ProfilePackageSet, self).__init__() self._profiles = profiles if profiles: de...
{ 'name': 'Account Fiscal Position Rule Stock', 'version': '1.1', 'category': 'Generic Modules/Accounting', 'description': """Include a rule to decide the correct fiscal position for Stock""", 'author': "Akretion,Odoo Community Association (OCA)", 'license': 'AGPL-3', 'website': 'http://...
"""HTTP-specific traversers For straight HTTP, we need to be able to create null resources. We also never traverse to views. $Id: traversal.py 28261 2004-10-26 22:22:37Z jim $ """ __docformat__ = 'restructuredtext' from zope.publisher.interfaces.http import IHTTPPublisher from zope.app.container.interfaces import IS...
from oslo_log import log as logging from sqlalchemy import Boolean from sqlalchemy.schema import Column, MetaData, Table, Index from designate.i18n import _LI LOG = logging.getLogger(__name__) meta = MetaData() def upgrade(migrate_engine): LOG.info(_LI("Adding boolean column delayed_notify to table 'zones'")) ...
# coding: utf-8 from celery import shared_task from django.core.management import call_command @shared_task def import_in_background(import_task_uid): from kpi.models.import_export_task import ImportTask # avoid circular imports import_task = ImportTask.objects.get(uid=import_task_uid) import_task.run()...
import os import random import string import unittest import requests from tethys_dataset_services.engines import CkanDatasetEngine try: from tethys_dataset_services.tests.test_config import TEST_CKAN_DATASET_SERVICE except ImportError: print('ERROR: To perform tests, you must create a file in the "tests" pac...
""" Some Python Text Analysis Do not Run this program, copy the appropriate tests to something like ipython Notebook. """ """Clean up and Loop documents""" import os import nltk import glob import matplotlib.pyplot as plt import re from os import listdir from bs4 import BeautifulSoup from textblob import T...
from django import http from django.core.urlresolvers import reverse from mox import IsA from openstack_dashboard import api from openstack_dashboard.api import cinder from openstack_dashboard.api import keystone from openstack_dashboard.test import helpers as test class VolumeTests(test.BaseAdminViewTests): @te...
from neutron_lib.api import converters from neutron_lib.api.definitions import subnet from neutron_lib import constants from neutron_lib.db import constants as db_const NAME = 'Neutron L2 Network' ALIAS = 'network' DESCRIPTION = "Layer 2 network abstraction" UPDATED_TIMESTAMP = "2012-01-01T10:00:00-00:00" RESOURCE_...
import os import sys import codecs import re # make sure we have the right number of arguments if len(sys.argv) < 3: print "Wrong number of arguments" exit(1) # get dock and menubar names dockname = sys.argv[1].decode('utf-8') menuname = sys.argv[2].decode('utf-8') # compile the regular expression re_strings...
from dockit.core.serializers.python import Serializer, Deserializer from django.utils import unittest from django.contrib.contenttypes.models import ContentType from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema class PythonSerializerTestCase(unittest.TestCase): def setUp(sel...
# -*- coding: utf-8 -*- # noinspection PyMethodMayBeStatic from abc import ABCMeta, abstractmethod from collections import namedtuple from sipa.model.fancy_property import active_prop, UnsupportedProperty from sipa.model.misc import PaymentDetails # noinspection PyMethodMayBeStatic class AuthenticatedUserMixin: ...
import warnings warnings.warn("For now this file is deprecated " "in future it will be part of Solar repository logic", DeprecationWarning) from fabric import api as fabric_api import os import requests import StringIO import zipfile from solar import utils GIT_TPL = """ --- - hosts: all...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy3 Experiment Builder (v3.1.1), on Thu May 9 17:56:54 2019 If you publish work using this script please cite the PsychoPy publications: Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of N...
# `isWordGuessed` takes in two parameters - a string, `secretWord`, and a list # of letters, `lettersGuessed` This function returns a boolean - True if # `secretWord` has been guessed (ie, all the letters of `secretWord` are in # `lettersGuessed`) and False otherwise. # Example Usage: # >>> secretWord = 'apple' # >>...
import socket import mock import testtools import webob from neutron.agent.metadata import agent from neutron.common import utils from neutron.tests import base class FakeConf(object): admin_user = 'neutron' admin_password = 'password' admin_tenant_name = 'tenant' auth_url = 'http://127.0.0.1' a...
import unittest from batotodownloader import BatotoDownloader class TestDownloader(unittest.TestCase): def setUp(self): self.downloader = BatotoDownloader("","") self.soup = self.downloader.get_page_soup("http://www.batoto.net/read/_/1496/iris-zero_v1_ch2_by_ala-atra-scans") def test_omake_nu...
import unittest from Src.BioDataManagement.CrossCutting.DTOs.DnaMethylationLevelDto import DnaMethylationLevelDto class DnaMethylationLevelDtoTest(unittest.TestCase): def test_instance(self): dna_methylation_level_dto = DnaMethylationLevelDto(id_entrez=1, ...
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- import os from chimera.util.catalog import Catalog from chimera.util.scat import SCatWrapper class PPM (Catalog): def __init__(self): Catalog.__init__(self) self.scat = SCatWrapper() def getName(self): return "PPM" def getMet...
import collections from oslo_config import cfg import psutil import six from six.moves.urllib import parse import yaml from spectrometer.openstack.common import log as logging from spectrometer.processor import config from spectrometer.processor import default_data_processor from spectrometer.processor import mls fro...
#!/usr/bin/python """Test of object navigation.""" from macaroon.playback import * import utils sequence = MacroSequence() # Work around some new quirk in Gecko that causes this test to fail if # run via the test harness rather than manually. sequence.append(KeyComboAction("<Control>r")) sequence.append(utils.Star...
""" WSGI config for craken_project project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICA...
""" globals attached to frappe module + some utility functions that should probably be moved """ from __future__ import unicode_literals from werkzeug.local import Local, release_local import os, importlib, inspect, logging, json # public from frappe.__version__ import __version__ from .exceptions import * from .util...
#!/bin/python import sys class Bif: def __init__(self): self.tape = [0] * 10000 # pre-allocate a finite-size tape (sorry Alan Turing) self.data_pointer = 0 self.instruction_pointer = 0 def interpret(self, program): '''Interprets a Brainfuck program. This function does not ...
# Game of Life written in 100 lines of Taichi # In memory of John Horton Conway (1937 - 2020) import numpy as np import taichi as ti ti.init() n = 64 cell_size = 8 img_size = n * cell_size alive = ti.field(int, shape=(n, n)) # alive = 1, dead = 0 count = ti.field(int, shape=(n, n)) # count of neighbours @ti.fun...
from __future__ import absolute_import from __future__ import print_function from future.utils import itervalues from twisted.internet import defer from twisted.python import failure from zope.interface import implementer from buildbot.interfaces import ITriggerableScheduler from buildbot.process.properties import Pr...
#!/usr/bin/env python import sys import socket import fcntl import struct import os import re import time # DNSQuery class from http://code.activestate.com/recipes/491264-mini-fake-dns-server/ class DNSPacket(object): def __init__(self, data): self.data = data #16-bit identifier @property def...
import os from setuptools import setup from codecs import open readme = open('README.rst').read() here = os.path.abspath(os.path.dirname(__file__)) about = {} with open(os.path.join(here, 'facepy', '__version__.py'), 'r', 'utf-8') as f: exec(f.read(), about) setup( name='facepy', version=about['__versio...
""" Signal handlers that should be use from the other apps update the search index. """ from django.conf import settings import threading import time import requests import logging logger = logging.getLogger(__name__) def search_index_update(index_type, index_id): IndexDocumentThread(index_id, index_type).start(...
#! /usr/bin/python import re import getopt import sys def usage(): print >> sys.stderr, ( "Usage: %s <input> [output]\n" "Summary:\n" " Creates a quoted string suitable for inclusion in a C char*\n\n" "Options:\n" " <input> Input file to quote\n" " <output> Output quoted string [stdout]\n" ...
from nose import SkipTest from numpy.testing import assert_ from statsmodels.tsa.base.datetools import dates_from_range from statsmodels.tsa.x13 import _find_x12, x13_arima_select_order x13path = _find_x12() if x13path is False: _have_x13 = False else: _have_x13 = True class TestX13(object): @classmetho...
# -*- coding: utf-8 -*- ############################################################################# # # syntax.py # # description: examples of syntax # # # Authors: # Cody Roux # # # ############################################################################## import boole.core.expr as expr from boole import * ...
from subprocess import call, check_output, check_call import socket import logging import logging.handlers import os import errno import sys import uuid from netaddr import IPNetwork, IPAddress from pycalico.datastore import IF_PREFIX from pycalico.datastore_datatypes import Endpoint, VETH_NAME _log = logging.getLog...
def get_array_list(self, item_id, side, is_order): ''' Calculate array for dental position: u(p) or d(own) at least 1 line is returned (for graphic rapresentation) item_id: id of partner (is_order=False) or id of order (is_order=True) side: U or D, stand for Up or Down is_or...
# Vimeo (Videos) # # @website https://vimeo.com/ # @provide-api yes (http://developer.vimeo.com/api), # they have a maximum count of queries/hour # # @using-api no (TODO, rewrite to api) # @results HTML (using search portal) # @stable no (HTML can change) # @parse url, title, publishe...
"""Tests for observation.observation_updater.""" import collections import itertools import math from absl.testing import absltest from absl.testing import parameterized from dm_control.composer.observation import fake_physics from dm_control.composer.observation import observable from dm_control.composer.observation...
#!/usr/bin/env python from ncclient import manager import sys from lxml import etree # Set the device variables DEVICES = ['172.16.30.101', '172.16.30.102'] USER = 'admin' PASS = 'admin' PORT = 830 PREFIX = {'172.16.30.101': '10.101.1.0/24', '172.16.30.102': '10.102.1.0/24' } DEVICE_NAMES = {'172.16.30.1...
""" Interpolative decomposition (ID) """ # Authors: N. Benjamin Erichson # Joseph Knox # License: GNU General Public License v3.0 from __future__ import division import numpy as np from scipy import linalg from .qb import compute_rqb from .utils import conjugate_transpose _VALID_MODES = ('row', 'column') ...
# -*- coding: utf-8 -*- """ lantz_core.features.util ~~~~~~~~~~~~~~~~~~~~~~~~ Tools to customize feature and help in their writings. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import (division, unicode_literals...
from tries import tries from tries.exception import ambiguousPathException from pyshell.arg.checker.string43 import StringArgChecker from pyshell.utils.string65 import isString TYPENAME = "token" class TokenValueArgChecker(StringArgChecker): def __init__(self, token_dict): StringArgChecker.__init__(self...
import logging from xml.etree import ElementTree as etree from xml.parsers import expat from oslo.serialization import jsonutils import six from neutronclient.common import constants from neutronclient.common import exceptions as exception from neutronclient.i18n import _ LOG = logging.getLogger(__name__) if six.PY...
#!/usr/bin/python import json import os import sys somedir = '../data' files = [f for f in os.listdir(somedir) if os.path.isfile(os.path.join(somedir, f))] for file_name in files: print(file_name) notes = [] data = {} try: with open(os.path.join(somedir, file_name), 'r') as tr_file: ...
""" AWS X-Ray backed implementation of the python OpenTracing API. https://github.com/opentracing/basictracer-python See the API definition for comments. """ import atexit import sys import threading import time import traceback import warnings from basictracer.recorder import SpanRecorder from . import constants,...
from __future__ import division, unicode_literals import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( encodeFilename, error_to_compat_str, decodeArgument, format_bytes, timeconvert, ) class FileDownloader(object): """File Downloa...
# # This sets up how models are displayed # in the web admin interface. # from django import forms from django.conf import settings from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from evennia.playe...
#!/usr/bin/env python import socket import sys from time import sleep def login(host, port, username, password): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) sock.sendall(username+" "+password+"\n") return sock except socket....
import socket import urllib import urlparse import os import urllib2 import sys import json import httplib import ssl from ansible import utils, errors VAULT_URL = '' VAULT_APP_ID = '' VAULT_SECRET = '' if os.getenv('VAULT_URL') is not None: VAULT_URL = os.environ['VAULT_URL'] if os.getenv('VAULT_APP_ID') is ...
"""Test BIP65 (CHECKLOCKTIMEVERIFY). Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height 1351. """ from test_framework.blocktools import create_coinbase, create_block, create_transaction from test_framework.messages import CTransaction, msg_block, ToHex from test_framework.mininode import ...
from pymaptools import uniq """ the get_class_attrs and get_object_attrs methods below are based on http://stackoverflow.com/a/10313703/597371 """ def get_class_attrs(klass): """Get attributes of a class """ ret = dir(klass) if hasattr(klass, '__bases__'): for base in klass.__bases__: ...
import functools from sentry.utils.strings import ( is_valid_dot_atom, iter_callsign_choices, soft_break, soft_hyphenate, tokens_from_name ) ZWSP = u'\u200b' # zero width space SHY = u'\u00ad' # soft hyphen def test_soft_break(): assert soft_break('com.example.package.method(argument).anotherMethod(ar...
import config import sys, unittest, os sys.path.insert(0, "../") import duplicity.backend try: import duplicity.backends.giobackend gio_available = True except Exception: gio_available = False from duplicity.errors import * #@UnusedWildImport from duplicity import path, file_naming, dup_time, globals, gpg ...
import errno import os import yaml # TODO[mike]: This should be removed once we've updated python to 2.7.9 # This tells urllib3 to use pyopenssl, which has the latest tls protocols and is # more secure than the default python ssl module in python 2.7.4 import requests import urllib3.contrib.pyopenssl urllib3.contrib.p...
__author__ = "Antonio Hernández <<EMAIL>>" __copyright__ = "Copyright (C) 2011, Junta de Andalucía <<EMAIL>>" __license__ = "GPL-2" import os import dbus import syslog import lsb_release import traceback import time if 'Lite' in lsb_release.get_distro_information()['DESCRIPTION']: # Use org.lxde.SessionManager ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import urllib import urllib2 import sys try: import xml.etree.cElementTree as ET except ImportError: try: import elementtree.ElementTree as ET except ImportError: sys.exit("poodledo requires either Python 2.5+, or the ElementTree modu...
''' Unit tests for neo.io.blackrockio.BlackrockIO ''' # needed for python 3 compatibility from __future__ import absolute_import, division try: import unittest2 as unittest except ImportError: import unittest from neo.io.blackrockio import BlackrockIO from neo.test.iotest.common_io_test import BaseTestIO im...
# -*- coding: utf-8 -*- # vim: set ts=4 sw=4 fdm=indent : */ # some code from http://www.djangosnippets.org/snippets/310/ by simon # and from examples/djopenid from python-openid-2.2.4 import logging import hashlib import urlparse from django.core.urlresolvers import reverse from django.http import HttpResponseRedire...
import pickle import re import bsddb from geopy import geocoders from dbtruck.util import to_utf re_addr2 = re.compile(r'^\s*\d{1,6}(\s+[a-zA-Z\-]+){1,3}\s*$') def distance_func(pt1, pt2): return ((float(pt1[0]) - float(pt2[0])) ** 2 + (float(pt1[1]) - float(pt2[1])) ** 2) ** 0.5 class DBTruckGeocod...
# -*- coding: utf-8 -*- import requests import sys import os import base64 class ZabbixImage(object): """For get graph image""" def __init__(self, server, api_user, api_pass): super(ZabbixImage, self).__init__() #self.arg = arg self.server = server self.api_user = api_user self.api_pass =api_pass self.ve...
from django.conf import settings from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.utils import importlib from django.utils.translation import ugettext_lazy as _ from django.views.generic.base import TemplateResponseM...
import datetime as dt import jsonschema from rally.common.i18n import _, _LW from rally.common import db from rally.common import logging from rally import consts from rally.deployment import credential from rally import exceptions LOG = logging.getLogger(__name__) CREDENTIALS_SCHEMA = { "type": "object", ...
# vim:shiftwidth=2:tabstop=2:expandtab:textwidth=80:softtabstop=2:ai: import os VERSION = '2.1.1' MODE_INTERACTIVE = 0 MODE_CACHE_PASSPHRASE = 1 MODE_AGENT = 2 HOME = os.environ.get('HOME') GNUPGHOME = os.environ.get('GNUPGHOME', os.path.join(HOME, '.gnupg')) DEFAULT_GPG_PATH = '/usr/bin/gpg' DEFAULT_KEYRING = os.pat...
from base_handler import BaseDataHandler, DataHandlerException import glob import os class ImdbDataHandler(BaseDataHandler): """ Works with the original Large Movie Review Dataset - IMDB data as downloaded from http://ai.stanford.edu/~amaas/data/sentiment/ source defines the folder where the data is ...
import pyamf from pyamf import remoting import httplib class BrightCoveHelper: """ BrightCoveHelper is used to get video info of videos that use the BrightCover SWF player. """ def __init__(self, logger, playerKey, contentId, url, seed, experienceId=0, amfVersion=3, proxy=None): ...
#!/usr/bin/env python3 """Home Assistant setup script.""" from datetime import datetime as dt from setuptools import find_packages, setup import homeassistant.const as hass_const PROJECT_NAME = "Home Assistant" PROJECT_PACKAGE_NAME = "homeassistant" PROJECT_LICENSE = "Apache License 2.0" PROJECT_AUTHOR = "The Home A...
from openerp import fields, models, api from openerp.exceptions import Warning as UserError class HrPublicHolidaysLine(models.Model): _name = 'hr.holidays.public.line' _description = 'Public Holidays Lines' _order = "date, name desc" name = fields.Char( 'Name', required=True, ) ...
def gather_all(c): # Number of nodes? c.execute('SELECT COUNT(*) FROM node') nbr_of_nodes = c.fetchone()[0] # Number of hosts? c.execute('SELECT COUNT(*) FROM host') nbr_of_hosts = c.fetchone()[0] # Number of networks? c.execute('SELECT COUNT(*) FROM network') nbr_of_networks = c.f...
# -*- coding: UTF-8 -*- import re import urllib import urlparse from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import tvmaze from resources.lib.modules import source_utils from resources.lib.modules import dom_parser class source: def __init__(s...
import os from ..geoextent import GeoExtent from ..image import AbstractTiledImage, ImagePyramid from ..tilingscheme import TilingScheme __author__ = "Norman Fomferra (Brockmann Consult GmbH)" class NaturalEarth2Image(AbstractTiledImage): """ A `TiledImage` implementation which provides 'Natural Earth v2' i...
from setuptools import setup, find_packages import os from io import open import re # example setup.py Feel free to copy the entire "azure-template" folder into a package folder named # with "azure-<yourpackagename>". Ensure that the below arguments to setup() are updated to reflect # your package. # this setup.py is...
from oslo_db.sqlalchemy import models from oslo_utils import timeutils from sqlalchemy import Column, Integer, String, Text, TIMESTAMP from sqlalchemy import BLOB from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ForeignKey, DateTime, Boolean from sqlalchemy.orm import relationship BASE =...
"""Support for PlayStation 4 consoles.""" import logging import os from pyps4_2ndscreen.ddp import async_create_ddp_endpoint from pyps4_2ndscreen.media_art import COUNTRIES import voluptuous as vol from homeassistant.components.media_player.const import ( ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_TITLE, MEDIA_T...
import textwrap from conans.client.graph.graph import CONTEXT_HOST, CONTEXT_BUILD from conans.model.profile import Profile from conans.test.integration.graph.core.cross_build.protoc_basic_test import ClassicProtocExampleBase class ProtocWithGTestExample(ClassicProtocExampleBase): """ Built on top of the ClassicP...
import numpy as np import pandas as pd from numba import njit @njit def series_rolling_count(): series = pd.Series([4, 3, 2, np.nan, 6]) # Series of 4, 3, 2, np.nan, 6 out_series = series.rolling(3).count() return out_series # Expect series of 1.0, 2.0, 3.0, 2.0, 2.0 print(series_rolling_count())
# -*- coding: utf-8 -*- import time from add_contact.model.group import Info def test_a_add_new_contact(app): #app.contact.clean_contactlist() app.contact.giving_names(Info(firstname="Yuriy", lastname="Jurayev", nickname="Treka4" ,middlename="DM")) app.contact.additional_info(Info(title="Engineer", compan...
"""HTD21D module driver.""" import math from copper import delegate I2C_ADDR = 0x40 TRIGGER_TEMP_HOLD = 0xE3 TRIGGER_HUM_HOLD = 0xE5 TRIGGER_TEMP_NOHOLD = 0xF3 TRIGGER_HUM_NOHOLD = 0xF5 WRITE_USER = 0xE6 READ_USER = 0xE7 SOFT_RESET = 0xFE # Partial pressure constants for dew point calculation K_PP = dict(A=8.1332,...
#! /usr/bin/env python # encoding: utf-8 import os,re import Utils,TaskGen,Task,Runner,Build from TaskGen import feature,before from Logs import error,warn,debug re_tex=re.compile(r'\\(?P<type>include|input|import|bringin){(?P<file>[^{}]*)}',re.M) def scan(self): node=self.inputs[0] env=self.env nodes=[] names=[] ...
#!/usr/bin/env python # rh2mr.py import numpy as num from satvap import satvap from satmix import satmix from e2mr import e2mr def rh2mr(p,t,rh,Tconvert=None): """(w1,w2) = rh2mr(p,t,rh,Tconvert) determine H2O mixing ratio (w, g/kg) given reference pressure (mbar), temperature (t,K), and relative humidity (rh,%) T...
#!/home/eswitzer/local/bin/python import inspect import os import sys import time import numpy as np import healpy as hp import calculations.calibration_gain as cg import lib calcpath = os.path.abspath(os.path.dirname(os.path.abspath(inspect.getfile( lib))) + '/../calculations/') + '/' datapath = os.path.abspath...
# -*- coding: utf-8 -*- """ Fix annotations for 1000488 """ # Import statements import re def main(): with open('sms_corpus.txt', 'r') as infile: text = infile.read() with open('sms_corpus.ann_', 'r') as infile: anns = [ann.strip('\n') for ann in infile.readlines()] the_list = [ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings from actstream.settings import USE_JSONFIELD if USE_JSONFIELD: from jsonfield.fields import JSONField as DataField else: DataField = models.Te...