content
string
import utils from twisted.words.xish.domish import Element import legacy import config from debug import LogEvent, INFO, WARN, ERROR import sys import globals import twisted.copyright class VersionTeller: def __init__(self, pytrans): self.pytrans = pytrans self.pytrans.disco.addFeature(globals.IQVERSION, self.inc...
single = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens = ["", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] multiTens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] hundred = ...
""" Copyright 2013 Steven Diamond 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...
import falcon import json from .test_base import Base, BaseTestCase from .test_fixtures import Account from .resource import CollectionResource, SingleResource class AccountCollectionResource(CollectionResource): model = Account class AccountResource(SingleResource): model = Account proof = {} count = 0 ...
from boar.mailing_lists.models import MailingList from boar.mailing_lists.tokens import default_token_generator from django import template from django.contrib.auth.models import User from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response def unsubscribe(request, user_id, ma...
#! /usr/bin/python # -*- coding: utf-8 -*- import os from tensorlayer import logging from tensorlayer import visualize from tensorlayer.files.utils import del_file from tensorlayer.files.utils import folder_exists from tensorlayer.files.utils import load_file_list from tensorlayer.files.utils import load_folder_list...
"""AccountNotifications API Tests for Version 1.0. This is a testing template for the generated AccountNotificationsAPI Class. """ import unittest import requests import secrets from pycanvas.apis.account_notifications import AccountNotificationsAPI from pycanvas.apis.account_notifications import Accountnotifi...
import wizard import time import pooler _lang_form = '''<?xml version="1.0"?> <form string="Choose catalog preferencies"> <separator string="Select a printing language " colspan="4"/> <field name="report_lang"/> <separator string="Select a Product Categories " colspan="4"/> <field name="categories" cols...
#!/usr/bin/python # -*- coding: utf-8 -*- """ 将文本整合到 train、test、val 三个文件中 """ import os def _read_file(filename): """读取一个文件并转换为一行""" with open(filename, 'r', encoding='utf-8') as f: return f.read().replace('\n', '').replace('\t', '').replace('\u3000', '') def save_file(dirname): """ 将多个文件整合并...
import subprocess import sys import eventlet.queue import eventlet.tpool import eventlet.green.subprocess from eventlet import green from eventlet.greenpool import GreenPool from .BaseTerminal import BaseTerminal import logging logger = logging.getLogger(__name__) class SubprocessTerminal(BaseTerminal): def __...
from .logrequest import LogRequest class PutLogsRequest(LogRequest): """ The request used to send data to log. :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type topic: string :param topic: topic name ...
import sys import os import getopt import core.levDriver as driver import core.levSystem as level # Level-PY experimental compiler from core.levConfig import * # Compiler entry point. def main(argv): #reading parameters in "config" attributes #config is un-instantiated class holding some attributes c...
import argparse import yaml import pprint PLAYER_FILE="player.yml" from thing import * from room import * from item import * from player import * def status(args): print("I have some status") def move(args): if len(args) == 0: print("You didn't specify anywhere to move to.") else: destina...
# -*- coding: utf-8 -*- import unittest import webracer class UrlencodeUtf8Test(unittest.TestCase): def test_urlencode_simple(self): input = dict(a='a', b='b') output = webracer.urlencode_utf8(input) # dictionary keys are not ordered self.assertTrue(output == 'a=a&b=b' or output ==...
try: import weechat,re except Exception: print("This script must be run under WeeChat.") print("Get WeeChat now at: http://www.weechat.org/") quit() SCRIPT_NAME = "server_autoswitch" SCRIPT_AUTHOR = "nils_2 <<EMAIL>>" SCRIPT_VERSION = "0.4" SCRIPT_LICENSE = "GPL" SCRIPT_DESC = "cycle to cu...
"""This code example gets all active content categorized as a "comedy" using the network's content browse custom targeting key. This feature is only available to DFP video publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in y...
#!/usr/bin/python #coding=utf-8 ''' 工具类 ''' import datetime from datetime import timedelta import MySQLdb import pandas as pd ''' 获取mysql的链接 ''' def getConnection(): # conn = MySQLdb.connect(host='192.168.2.31', user='root', passwd='1qaz@WSX+!', db='strategy', port=3306) conn = MySQLdb.connect(host='47.104....
#!/usr/bin/python """ This example shows how to add an interface (for example a real hardware interface) to a network after the network is created. """ import re from mininet.cli import CLI from mininet.log import setLogLevel, info, error from mininet.net import Mininet from mininet.link import Intf from mininet.top...
#! /usr/bin/env python assert __name__ == "__main__" import sys from macro import Macro, writeFile tmpl = """\ %(url)s # %(obsolete)s# SYNOPSIS # %(synopsis)s # # DESCRIPTION # %(description)s # # LICENSE # %(authors)s # %(license)s %(body)s""" def formatParagraph(para): assert para assert para[0] assert par...
''' Top level of the nuancier Flask application. ''' import logging import logging.handlers import os import sys import urlparse import flask import dogpile.cache from functools import wraps ## pylint cannot import flask extension correctly # pylint: disable=E0611,F0401 from flask.ext.fas_openid import FAS from sqla...
''' Created on Jul 7, 2014 @author: viejoemer What is a frozenset data structure and how it works? ¿Qué es la estructura de datos frozenset y como funciona? frozenset Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Profile.currency' db.add_column(u'quitter_profile', 'curr...
# ------------------------------------------ # BDS 1,0 # Data link capability report # ------------------------------------------ from pyModeS import common def is10(msg): """Check if a message is likely to be BDS code 1,0 Args: msg (str): 28 hexdigits string Returns: bool: True or Fals...
#!/usr/bin/env python3 """Cronjob for triggering bcl2fastq runs """ # standard library imports import logging import sys import os import argparse import subprocess # project specific imports # # add lib dir for this pipeline installation to PYTHONPATH LIB_PATH = os.path.abspath( os.path.join(os.path.dirname(os....
from distutils.core import setup pluginPkgs = [] pluginPkgs.append('stamp.plugins') pluginPkgs.append('stamp.plugins.common') pluginPkgs.append('stamp.plugins.common.multipleComparisonCorrections') pluginPkgs.append('stamp.plugins.groups') pluginPkgs.append('stamp.plugins.groups.effectSizeFilters') pluginPkgs.append('...
# Standard python modules. import logging import time import sys # citest modules. import citest.gcp_testing as gcp import citest.json_predicate as jp import citest.service_testing as st from citest.json_contract import ObservationPredicateFactory ov_factory = ObservationPredicateFactory() # Spinnaker modules. import...
""" La empresa ABC está interesada en una calculadora de comisiones. La calculadora de comisiones es una plataforma web que calcula cuánto dinero le corresponde a un vendedor dada las ventas mensuales. ABC ha definido algunas reglas que indican cómo se distribuye la comisión: Para ventas que superan los $100,00...
""" Kivy-iconfonts ============== Simple helper functions to make easier to use icon fonts in Labels and derived widgets. """ from .iconfonts import * if __name__ == '__main__': from kivy.lang import Builder from kivy.base import runTouchApp from kivy.animation import Animation from os.path import jo...
r""" =============================================================================== Submodule -- pore_surface_area =============================================================================== """ import scipy as _sp def sphere(geometry, network, pore_diameter='pore.diameter', throat_area='t...
from setuptools import setup, find_packages import os import uwsgi_it_api CLASSIFIERS = [ 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Langu...
# -*- coding: utf-8 -*- from mamba import description, context, it from expects import expect, be, have_len, be_above, equal import os from infcommon.mysql import mysql TEST_TABLE = 'integration_test_table' with description('MySQLClientTest'): with before.each: self.mysql_client = mysql.MySQLClient(os...
from katello.client.api.base import KatelloAPI class ErrataAPI(KatelloAPI): def errata_filter(self, repo_id=None, environment_id=None, prod_id=None, type=None, severity=None): path = "/api/errata" params = {} if not repo_id == None: params['repoid'] = repo_id if not env...
import pickle import weakref import numpy as np import pyarrow as pa import pytest class IntegerType(pa.PyExtensionType): def __init__(self): pa.PyExtensionType.__init__(self, pa.int64()) def __reduce__(self): return IntegerType, () class UuidType(pa.PyExtensionType): def __init__(s...
"""implement a simple url path improvement to a wsgi app. got from http://flask.pocoo.org/snippets/35/ Thanks to Peter Hansen. """ class ReverseProxied(object): """implement utl path feature in wsgi. Wrap the application in this middleware and configure the front-end server to add these headers, to let ...
import time import requests from requests.auth import HTTPBasicAuth from hq_settings import HQTransaction from datetime import datetime import uuid import os from django.core.files.uploadedfile import UploadedFile from random import random, sample try: from localsettings import URL_TEMPLATE except ImportError: ...
# -*- coding: utf-8 -*- import Image, ImageDraw, ImageFont from head.models import Book from django.utils.encoding import smart_str BUFF = 87 PADDING = 15 TWIDTH = 325 END_XPOS = 340 MAIN_WIDTH = 300 CALL_NO_CORD = (15,15) FONT_PATH = "" FONT_NAME = "LiberationMono-Regular.ttf" FONT_SIZE = 11 CURSOR = (15,15) d...
from optparse import OptionParser import dockpulp log = dockpulp.log def get_opts(): usage="""%prog [options] environment create the everything repository in the given environment""" parser = OptionParser(usage=usage) parser.add_option('-d', '--debug', default=False, action='store_true', help='tu...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from recruit_app.app import create_app # from recruit_app.wsgi import app from recruit_app.user.models import User, Role from recruit_app.setting...
import io # TODO: Move this to docs # # d1_pyore Examples # ================= # # A. Create an OAI-ORE document from a list of PIDs # ------------------------------------------------- # # Given the text file pids.txt:: # # # Comment line, separate the # from text with a space. # # These are example values for pids2...
{ 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': "", 'depends': ['web', 'web_editor', 'web_planner', 'http_routing', 'portal'], 'ins...
##Load libs import getopt import sys import argparse import os import gzip import time import shutil import re import csv ##Parser parser = argparse.ArgumentParser(description='Statistics on Doubletons, Singletons and Tripletons Variants') parser.add_argument('--freq-input', type=str, default=None, help='Freq file inpu...
from typing import TYPE_CHECKING, Union from pandas.api.types import CategoricalDtype from pyspark.sql import functions as F from pyspark.sql.types import IntegralType, StringType from pyspark.pandas.base import column_op, IndexOpsMixin from pyspark.pandas.data_type_ops.base import DataTypeOps from pyspark.pandas.sp...
import lxml.etree as ET import yaml import sys import os class CXML: def __init__(self, dzc_file, data_dir, config): self.dzc_file = dzc_file self.data_dir = data_dir self.name = config['name'] self.facets = config['facets'] dzc_root = ET.parse(self.dzc_file).getroot() self.dzc_items =...
# -*- coding: utf-8 -*- from storm.expr import Join, Ne from stoqlib.database.properties import UnicodeCol, DateTimeCol, IdCol from stoqlib.lib.dateutils import localnow from stoqlib.migration.domainv3 import Domain class Sale(Domain): __storm_table__ = 'sale' open_date = DateTimeCol() notes = UnicodeC...
import xml.sax import urllib, base64 import time import boto.utils from boto.connection import AWSAuthConnection from boto import handler from boto.s3.bucket import Bucket from boto.s3.key import Key from boto.resultset import ResultSet from boto.exception import BotoClientError from boto.s3.connection import * import...
import matplotlib.pyplot as pyplot import numpy class Task: """Straightforward jobs representation.""" def __init__(self, id, d, tau): """Constructor for a task. Arguments: id -- unique identifier d -- instant cost tau -- duration (number of slotes) """ ...
""" Unittests for the SublimeTerminalBuffer module """ import unittest # Import sublime stub import sublime # Module to test from TerminalView import sublime_terminal_buffer # still some stuff todo with this testcase - lacks color tests and more edge # cases class line_updates(unittest.TestCase): def setUp(self...
# !/usr/bin/python # -*- coding:utf-8 -*- # Email: <EMAIL> # 总控程序 # 系统内部所有数据都是 unicode,处理好的文件都以 utf8 编码保存 from preprocess import * from candidate import * from disambiguation import * from sameas import * from result import * from mark import * # Step 1: 原始数据预处理 def preprocess(): # baidubaike kb_name = 'baid...
#coding: utf-8 #文件大小类 class FileSize(): SIZE_UNIT={"Byte":1,"KB":1024,"MB":1048576,"GB":1073741824,"TB":1099511627776L} def __init__(self,size): self.size=long(FileSize.Format(size)) @staticmethod def Format(size): import re if isinstance(size,int) or isinstance(size...
from pyrsklib.pra.ui.root import * class zzGUI( Root ): def welcome( self, layout, lay, name ): buttonClick( lay, 'bNew', lambda: self._gui.PopUp('newgui') ) buttonClick( lay, 'bExit', self._app.Quit ) def newgui( self, layout, lay, name ): diagButtClick( lay, 'dConfirm', self._NewGU...
""" sudo.views ~~~~~~~~~~ :copyright: (c) 2014 by Matt Robenolt. :license: BSD, see LICENSE for more details. """ try: from urllib.parse import urlparse, urlunparse except ImportError: # pragma: no cover # Python 2 fallback from urlparse import urlparse, urlunparse # noqa from django.contrib.auth.decora...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import sys import argparse import numpy as np np.set_printoptions(precision=3, suppress=True) from numpy import cos, sin # fix imports sys.path.append('../src') from vehicle_core.path import trajectory_tools as tt # constants T_TYPES ...
#!/usr/bin/env python3 from distutils.core import setup import os import shutil PO_DIR = 'po' LOCALE_DIR = 'locale' APP_ID = 'indicator-docker' def compile_lang_files() -> list: """(Re)generate .mo files from the available .po files, if any. :return: a list of .mo files to be packaged or installed ...
import diff import win32com.client import os import json import itertools import sys import re #vss constants STATUS_CHECKEDOUT = 0x1 # from enum VSSFileStatus STATUS_CHECKEDOUT_ME = 0x2 # from enum VSSFileStatus STATUS_NOTCHECKEDOUT = 0x0 # from enum VSSFileStatus TYPE_F...
import unittest, json from etk.extractors.inferlink_extractor import InferlinkExtractor, InferlinkRuleSet class TestInferlinkExtractor(unittest.TestCase): def test_inferlink_extractor(self) -> None: with open('etk/unit_tests/ground_truth/sample_html.jl', 'r') as f: sample_html = json.load(f)[...
def get_number(): number=int(raw_input("Please input a number: ")) return number def odd_or_even(n): if n % 2 == 0: return "Even" else: return "Odd" def for_loop1(n): sum = 0 for x in range (1,n+1): sum += x return sum def for_loop2(n): sum = 0 for x in xrange (1,n+1): sum += x return sum def f...
#!/usr/bin/env python3 """Module providing functions for parsetree creation.""" __all__ = [ 'fromfile', 'fromliteral', 'fromstring', 'fromtuple', ] import parser from .. tokenizer import generate_tokens from . import NonTerminalNode from . import TerminalNode ## TODO - I used to need this addit...
from decimal import Decimal import datetime import unittest import pytz from dsmr_parser import obis_references as obis from dsmr_parser import telegram_specifications from dsmr_parser.exceptions import InvalidChecksumError, ParseError from dsmr_parser.objects import CosemObject, MBusObject from dsmr_parser.parsers ...
APIURL_ENDPOINT = "https://www.bookingsync.com/api/v3" APIURL_TOKEN = "https://www.bookingsync.com/oauth/token" REQUEST_DEFAULT_TIMEOUT = 30 REQUESTED_SCOPE = "bookings_write%20bookings_read%20rentals_read%20rentals_write%20clients_read%20clients_write%20rates_write%20rates_read%20rates_read%20clients_read%20clients_wr...
from os import path from datetime import datetime import sys __version__ = "DEVELOPMENT_VERSION" LIBFAKETIME_DIR = path.dirname(path.realpath(__file__)) class FaketimeError(Exception): pass class Faketime(object): def __init__(self, faketime_filename): self._faketime_filename = path.abspath(faket...
""" Simple eventfilter that makes Home and Shift+Home in text editor widgets go to the first non-space character of a line, instead of the very beginning. """ from PyQt5.QtCore import QEvent, QObject from PyQt5.QtGui import QKeySequence, QTextCursor def handle(edit, ev): """Returns True if a Home/Shift+Home key...
from generativepy.drawing import make_image from generativepy.color import Color ''' In this example, similar to color.py, we set colours using CSS names. See the color module for a list of colours, or look up "CSS named colours" on the web. ''' def draw(ctx, width, height, frame_no, frame_count): # Set the back...
from io import StringIO from pysmt.shortcuts import Or, And, Not, Plus, Iff, Implies from pysmt.shortcuts import Exists, ForAll, Ite, ExactlyOne from pysmt.shortcuts import Bool, Real, Int, Symbol, Function from pysmt.shortcuts import Times, Minus, Equals, LE, LT, ToReal, FreshSymbol from pysmt.typing import REAL, INT...
#!/usr/bin/env python __doc__=""" """; import sys import json import numpy as np def usage(): print("Usage: %s logfile") % sys.argv[0] #print __doc__ def main(): # input parsing filename = sys.argv[1] try: logfile = open(filename) except (KeyError, IndexError): usage() ...
# -*- coding: utf-8 -*- """ Task 706 """ from bicluster import Bicluster, average_vector_cluster_distance import distances from Task701 import initialize_clusters from Task702 import closest_pair from Task703 import average_vectors def hcluster( data, distance=distances.pearson, cluster_dista...
from zeit.content.article.interfaces import IBookRecensionContainer import transaction import zeit.cms.interfaces import zeit.cms.testing import zeit.content.article.recension import zeit.content.article.testing class RecensionTest(zeit.content.article.testing.SeleniumTestCase): def create_recension(self): ...
''' Test about monitor trigger on host disk writing iops in one minute @author: Songtao,Haochen ''' import os import test_stub import random import threading import time import zstacklib.utils.ssh as ssh import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operat...
"""Drastic Exceptions """ __copyright__ = "Copyright (C) 2016 University of Maryland" __license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3" class BaseError(Exception): """Drastic Base Exception.""" pass class NoReadAccessError(BaseError): """ACL Exception for read access.""" pass class NoW...
from django import forms from django.utils.translation import npgettext, pgettext_lazy from django_filters import CharFilter, ChoiceFilter, OrderingFilter from ...core.filters import SortedFilterSet from ...product.models import Collection SORT_BY_FIELDS = { 'name': pgettext_lazy('Collection list sorting option',...
import unittest from textx.exceptions import TextXSyntaxError from expremigen.io.constants import PhraseProperty as PP from expremigen.mispel.mispel import Mispel from expremigen.patterns.pchord import Pchord from expremigen.patterns.pseq import Pseq class TestPat2Midi(unittest.TestCase): def test_header1(self)...
from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE VARCHAR2 = VARCHAR class CommitProfitSummary(BaseModel): """ 4.102 中国A股盈利承诺汇总表 Attributes ---------- object_id: VARCHAR2(100) 对象ID event_id: VARCHAR2(40) 事件ID ...
""" Implementation module for the I{mailmail} command. """ import os import sys import rfc822 import getpass from ConfigParser import ConfigParser try: import cStringIO as StringIO except: import StringIO from twisted.copyright import version from twisted.internet import reactor from twisted...
from couchpotato.core.logger import CPLog from string import ascii_letters, digits from urllib import quote_plus import re import traceback import unicodedata log = CPLog(__name__) def toSafeString(original): valid_chars = "-_.() %s%s" % (ascii_letters, digits) cleanedFilename = unicodedata.normalize('NFKD',...
""" Testing suite for the PyTorch ConvBERT model. """ import unittest from tests.test_modeling_common import floats_tensor from transformers import is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from .test_configuration_com...
import numpy as np from sklearn.metrics.pairwise import cosine_similarity from collections import Counter import sys import math from difflib import SequenceMatcher import Levenshtein from utils import np_utils sys.path.append("..") import config def _es_cosine_sim(a, b): # Calculates cosine sim based on tokeni...
# # Python interface to Aleph. # # import os.path import shutil import logging import re import tempfile import json from StringIO import StringIO from stat import S_IREAD, S_IEXEC from subprocess import PIPE if __name__ != '__main__': from ..security import SafePopen else: import os parent_dir = os.path.d...
#!/usr/bin/python """Phosim utility/convenience functions.""" from __future__ import with_statement import csv import datetime import getpass import glob import logging import os import shutil import subprocess import time __author__ = 'Jeff Gardner (<EMAIL>)' logger = logging.getLogger(__name__) # ***************...
# -*- coding: utf-8 -*- from random import choice from tests.helper.Stubs import Core from tests.helper.BenchmarkTest import BenchmarkTest from module.database import DatabaseBackend # disable asyncronous queries DatabaseBackend.async = DatabaseBackend.queue from module.Api import DownloadState from module.FileMana...
#!/usr/bin/env python # encoding: utf-8 import zlib import six from pfp.native import native import pfp.fields from pfp.dbg import PfpDbg import pfp.utils as utils import pfp.errors as errors @native(name="PackerGZip", ret=pfp.fields.Array) def packer_gzip(params, ctxt, scope, stream, coord): """``PackerGZip`` ...
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
from rest_framework import serializers from services.models import ( SKU, Category, Department, Location, SubCategory ) class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = "__all__" class DepartmentSerializer(serializers.ModelSerialize...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
"""Commonly used queries on the database""" # imports import sys import os import sqlalchemy import datetime sys.path.append(os.path.dirname(os.getcwd())) # Add .. to path from backend.ldaplogin import (get_member_with_real_name, DuplicateNamesException, PersonNotFoundException) from backend import connect f...
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcadd...
from pybrain.structure import FeedForwardNetwork from pybrain.structure import LinearLayer from pybrain.structure import FullConnection from pybrain.tools.shortcuts import buildNetwork class NeuralNetwork(): def insomnia(self, falling_asleep, awakenings, cant_fall_back, low_sleep_hours): parameters = [fall...
#!/usr/bin/env python import itertools import re from collections import defaultdict class Grammar(dict): """ """ def __init__(self, training, sigma=None, max_k=2): """ Attributes: lexicon sigma max_k tiers grammatical ungrammatical "...
from .base import Predicate from .to_pred import to_pred from .is_nothing import is_nothing class is_if(Predicate): """ Generates a predicate that given a predicate as condition will based on the result of this condition on the data evaluate the data with either ``if_predicate`` or ``else_predicate``....
from __future__ import print_function import getpass import os import sys import textwrap try: from inspect import getfullargspec as get_args except ImportError: from inspect import getargspec as get_args from oslo_utils import encodeutils from oslo_utils import strutils import prettytable import six from si...
''' New Integration Test for imagecache cleanup on primarystorate. @author: Quarkonics ''' import os import time import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.resource_opera...
import sys import logging import lxml.etree as etree import antd.garmin as garmin import antd.tcx as tcx import antd.cfg as cfg cfg.init_loggers(logging.DEBUG, out=sys.stderr) if len(sys.argv) != 2: print "usage: %s <file>" % sys.argv[0] sys.exit(1) with open(sys.argv[1]) as file: host = garmin.MockHost(file.rea...
""" Django settings for main project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) impor...
""" Converts british national grid to lat lon Author: Hannah Fry http://www.hannahfry.co.uk/blog/2012/02/01/converting-british-national-grid-to-latitude-and-longitude-ii """ from math import sqrt, pi, sin, cos, tan, atan2 def OSGB36toWGS84(E, N): """ Accept The Ordnance Survey National Grid eastings and northing...
import django_filters from .models import AssignmentName class CorrelationFilter(django_filters.FilterSet): assignment = django_filters.ModelChoiceFilter(queryset= AssignmentName.objects, required=None, label...
from django.apps import AppConfig from django.db.models.signals import post_migrate from . import group_names def _check_group(group_name): from django.contrib.auth.models import Group field = Group.objects.filter(name=group_name).first() if field is None: group = Group(name=group_name) g...
from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict import numpy as np from .external.neo_pixels import NeoPixels from .external.console import Console from .external.unicorn import Unicorn from .pixel import Pixel from .output import Output class ...
from ceilometer.dispatcher.resources import base class Image(base.ResourceBase): @staticmethod def get_resource_extra_attributes(sample): metadata = sample['resource_metadata'] params = { "name": metadata['name'], "container_format": metadata["container_format"], ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Miguel Domingo" __license__ = "MIT License" __email__ = "<EMAIL>" import sys, os, subprocess def commonWords(hyp, pe): """ This function computes the longest common subsequence between a translation hypothesis and its post-edited version. The fu...
#!/usr/bin/python from __future__ import print_function from RPi import GPIO import Queue # https://pymotw.com/2/Queue/ import MySQLdb import time import sys mysqlHost = '127.0.0.1' mysqlPort = 3306 mysqlLogin = 'root' mysqlPass = 'raspberry' mysqlDatabase = 'volkszaehler' gpio_list = [2, 3, 4, 17, 27, 22, 10, 9, 11...
""" Copyright 2017 Nicholas Moehle This file is part of CVXPY-CODEGEN. CVXPY-CODEGEN is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY...
#!/usr/bin/python # refile.py # Move messages # import sys import imh class Refile(imh.IMH_mixin): def run(self): # If there's one arg, it's the destination for # the current message in the current folder if len(self.args) == 1: destf = self.args[0] if not d...