• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python recordtype.recordtype函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中recordtype.recordtype函数的典型用法代码示例。如果您正苦于以下问题:Python recordtype函数的具体用法?Python recordtype怎么用?Python recordtype使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了recordtype函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, params):
        """
        `__init__()` initializes the necessary objects for using the
        Constraint.

        Attributes:
        `height`                         --     Board heigh.
        `widt`                           --    Board width.
        `count`         int              --     Number of solutions found.
        `board`         []position       --     List of currently allocated pieces.
        `board_index`   int              --     Index in the list of allocated pieces.
        `pieces`        []int            --     List of given pieces to allocate.
        `last_xy`       [][]coordinate   --     List of last used position
                                         --     per every type of piece.
        `last_index`    []int            --     Index in the list of last positions.
        `used_cols`     []int            --     Attacked columns.
        `used_rows`     []int            --     Attacked rows.
        `used_diag_l`   []int            --     Attacked diagonals (left)
        `used_diag_r`   []int            --     Attacked diagonals (right)
        `used_cells`    []int            --     Map of cells "under attack".
        `king_rules`    [8]coordinate    --     Permitted moves for king
        `knight_rules`  [8]coordinate    --     Permitted moves for knight
        """
        position = recordtype("position", ["x", "y", "kind"])
        coordinate = recordtype("coordinate", ["x", "y"])

        self.width = params["m"]
        self.height = params["n"]
        self.count = 0
        self.pieces = params["pieces"]

        self.board = []
        for _ in self.pieces:
            self.board.append(position(0, 0, 0))

        self.board_index = 0
        self.last_xy = []
        self.last_index = [0] * number_of_types

        for _ in range(number_of_types):
            coord_list = []
            for _ in range(len(self.pieces) + 1):
                coord_list.append(coordinate(0, 0))
            self.last_xy.append(coord_list)

        self.attacked_cols = [0] * self.width
        self.attacked_rows = [0] * self.height
        self.attacked_diag_l = [0] * (self.width + self.height)
        self.attacked_diag_r = [0] * (self.width + self.height)
        self.attacked_cells = [0] * ((self.width+4) * (self.height+4))

        self.king_rules = [
            coordinate(-1, 0), coordinate(1, 0), coordinate(0, -1), coordinate(0, 1),
            coordinate(-1, -1), coordinate(1, 1), coordinate(1, -1), coordinate(-1, 1)
        ]

        self.knight_rules = [
            coordinate(-2, -1), coordinate(-2, 1), coordinate(2, -1), coordinate(2, 1),
            coordinate(-1, -2), coordinate(-1, 2), coordinate(1, -2), coordinate(1, 2)
        ]
开发者ID:antalakas,项目名称:chess,代码行数:60,代码来源:constraint.py


示例2: out_dir

def out_dir(basename=""):
    """
    Essentially will perform os.path.join(Task.output_dir, basename)

    :param str basename: The basename of the output_file
    """
    return recordtype("OutputDir", "basename", default=None)
开发者ID:yanding,项目名称:COSMOS-2.0,代码行数:7,代码来源:files.py


示例3: forward

def forward(input_parameter_name):
    """
    Forwards a Task's input as an output

    :param input_parameter_name: The name of this cmd_fxn's input parameter to forward
    """
    return recordtype("Forward", "input_parameter_name", default=None)
开发者ID:yanding,项目名称:COSMOS-2.0,代码行数:7,代码来源:files.py


示例4: recordtype_row_strategy

def recordtype_row_strategy(column_names):
    """ Recordtype row strategy, rows returned as recordtypes

    Column names that are not valid Python identifiers will be replaced
    with col<number>_
    """
    import recordtype  # optional dependency
    # replace empty column names with placeholders
    column_names = [name if is_valid_identifier(name) else 'col%s_' % idx for idx, name in enumerate(column_names)]
    recordtype_row_class = recordtype.recordtype('Row', column_names)

    # custom extension class that supports indexing
    class Row(recordtype_row_class):
        def __getitem__(self, index):
            if isinstance(index, slice):
                return tuple(getattr(self, x) for x in self.__slots__[index])
            return getattr(self, self.__slots__[index])

        def __setitem__(self, index, value):
            setattr(self, self.__slots__[index], value)

    def row_factory(row):
        return Row(*row)

    return row_factory
开发者ID:VLADYRON,项目名称:pytds,代码行数:25,代码来源:__init__.py


示例5: find

def find(regex, n="==1", tags=None):
    """
    Used to set an input_file's default behavior to finds output_files from a Task's parents using a regex

    :param str regex: a regex to match the file path
    :param str n: (cardinality) the number of files to find
    :param dict tags: filter parent search space using these tags
    """
    return recordtype("FindFromParents", "regex n tags", default=None)
开发者ID:yanding,项目名称:COSMOS-2.0,代码行数:9,代码来源:files.py


示例6: get_record

def get_record(recordtype, record_url):
    """
    Given a record url and a recordtype, fetch the record from the and build the record.
    Assume there's just one record at the location and everything goes well
    """

    resp = session.get(record_url)

    new_record = recordtype(**resp.json())
    return new_record
开发者ID:PyClass,项目名称:PyClassLessons,代码行数:10,代码来源:ghiblister.py


示例7: __init__

    def __init__(self, sensor_id, stream_names):
        """
        sensor_id: the ID of the sensor that generates the stream
        stream_names: list of the stream names that the sensor generates 
        """

        Model = recordtype("Stream", "sensor_id timestamp streams")

        streams = dict((stream_names[i], 0) for i in range(0, len(stream_names)))

        self.stream = Model(sensor_id=sensor_id, timestamp=0, streams=streams)
开发者ID:dmazzer,项目名称:nors,代码行数:11,代码来源:stream.py


示例8: setFromModule

def setFromModule(moduleIn,mutable=False):
    """Construct the global context object from a module"""
    global context
    fields = {}
    for key, value in moduleIn.__dict__.iteritems():
        if  key[:2] != "__":
            fields[key]=value
    if mutable:
        Context = recordtype(moduleIn.__name__.split('.')[-1], fields.iteritems())
        context = Context()
    else:
        Context = namedtuple(moduleIn.__name__.split('.')[-1], fields.keys())
        context = Context._make(fields.values())
开发者ID:arnsong,项目名称:proteus,代码行数:13,代码来源:Context.py


示例9: Options

def Options(optionsList=None,mutable=False):
    """Construct an o
    from proteus.LinearAlgebraToptions object (named tuple)
    
    :param optionsList: An iterable of options tuples. Each option is
                        a 3-tuple, with the first entry the option
                        name string, the second entry the default
                        value, and the third entry a help string

    Example::

      opts=Context.Options([("nnx", 11, "number of mesh nodes in x-direction"),
                            ("nny", 21, "number of mesh nodes in y-direction"])
      nnx = opts.nnx
      nny = opts.nny

    """
    import ast, sys
    global contextOptionsString
    contextOptionsDict = {}
    help="Context input options:\n"
    for optTuple  in optionsList:
        help += """{0}[{1}] {2}\n\n""".format(optTuple[0], optTuple[1], optTuple[2])
        contextOptionsDict[optTuple[0]] = optTuple[1]
    logEvent(help)
    if contextOptionsString=="?":
        print(help)
        contextOptionsString=None
    if contextOptionsString is not None:
        option_overides=contextOptionsString.split(" ")
        for option in option_overides:
            lvalue, rvalue = option.split("=")
            if contextOptionsDict.has_key(lvalue):
                logEvent("Processing context input options from commandline")
                try:
                    contextOptionsDict[lvalue] = ast.literal_eval(rvalue)
                    logEvent(lvalue+" = "+rvalue)
                except:
                    sys.stderr.write("Failed setting context options from command line string.")
                    raise 
            else:
                logEvent("IGNORING CONTEXT OPTION; DECLARE "+lvalue+" IF YOU WANT TO SET IT")
    #now set named tuple merging optionsList and opts_cli_dihelpct
    if mutable:
        ContextOptions = recordtype("ContextOptions", contextOptionsDict.iteritems())
        return ContextOptions()
    else:
        ContextOptions = namedtuple("ContextOptions", contextOptionsDict.keys())
        return ContextOptions._make(contextOptionsDict.values())
开发者ID:arnsong,项目名称:proteus,代码行数:49,代码来源:Context.py


示例10: dicts_to_namedrecords

def dicts_to_namedrecords(dicts, class_name=None):
    """ Takes list of dictionaries and converts to list of recordtype objects"""
    from recordtype import recordtype
    from random import randint
    from sets import Set
    all_keys = []
    for dic in dicts:
        all_keys += dic.keys()
    unique_keys = list(Set(all_keys))
    key_defaults = [(key, None) for key in unique_keys]
    if not class_name:
        class_name = 'FB_Record_Type_'
    Record = recordtype(class_name + str(randint(1,9999999)), key_defaults)
    data = [Record(**dic) for dic in dicts]
    return data
开发者ID:danishabdullah,项目名称:facebookadspy,代码行数:15,代码来源:facebookadspy.py


示例11: attributes_class_constructor

def attributes_class_constructor(name, fields, identity=True, *args, **kwargs):
    if not identity:
        return recordtype.recordtype(name, fields, *args, **kwargs)

    # Create the new class, inheriting from the record type and from this
    # class
    class IdentityClass(recordtype.recordtype(name, fields, *args, **kwargs)):
        def __init__(self, id=None, created_at=None, updated_at=None,
                     *init_args, **init_kwargs):
            super(IdentityClass, self).__init__(*init_args, **init_kwargs)
            self.id = id
            self.created_at = created_at
            self.updated_at = updated_at

        @property
        def id(self):
            return self._id

        @id.setter
        def id(self, value):
            if value is not None:
                value = int(value)

            self._id = value

        @property
        def created_at(self):
            return self._created_at

        @created_at.setter
        def created_at(self, value):
            if value is not None and not isinstance(value, datetime):
                value = dateutil.parser.parse(value)

            self._created_at = value

        @property
        def updated_at(self):
            return self._updated_at

        @updated_at.setter
        def updated_at(self, value):
            if value is not None and not isinstance(value, datetime):
                value = dateutil.parser.parse(value)

            self._updated_at = value

    return IdentityClass
开发者ID:mezuro,项目名称:kalibro_client_py,代码行数:48,代码来源:base.py


示例12: namedtuple

# Tolerance on convergence test
tol = 1e-2

NUM_PRINCIPLE_COMPONENTS = 5

from recordtype import recordtype  #for mutable namedtuple (dict might also work)

SettingsStruct = recordtype('SettingsStruct',
                            ['shape_learning',  #String representing the shape which the object is learning
                             'initDatasetFile',  #Path to the dataset file that will be used to initialize the matrix for PCA
                             'updateDatasetFiles',  #List of path -- or single path-- to dataset that will be updated with demo shapes
                             'paramFile', #Path to the dataset file 'params.dat' inside which we save the learned parameters
                             'paramsToVary',
                             #Natural number between 1 and number of parameters in the associated ShapeModeler, representing the parameter to learn
                             'doGroupwiseComparison',  #instead of pairwise comparison with most recent two shapes
                             'initialBounds',
                             #Initial acceptable parameter range (if a value is NaN, the initialBounds_stdDevMultiples setting will be used to set that value)
                             'initialBounds_stdDevMultiples',
                             #Initial acceptable parameter range in terms of the standard deviation of the parameter
                             'initialParamValue',
                             #Initial parameter value (NaN if to be drawn uniformly from initialBounds)
                             'minParamDiff']) #How different two shapes' parameters need to be to be published for comparison
#@todo: make groupwise comparison/pairwise comparison different implementations of shapeLearner class

class ShapeLearner:
    def __init__(self, settings):

        self.paramsToVary = settings.paramsToVary
        #self.numPrincipleComponents = max(self.paramsToVary)
        self.numPrincipleComponents = NUM_PRINCIPLE_COMPONENTS
开发者ID:alexis-jacq,项目名称:drawing,代码行数:30,代码来源:shape_learner.py


示例13: set

SIL_LABEL = 'SIL'
NOISES = set(['SIL', 'SPN'])

# FILE1 = 's0101a'
# FILE2 = FILE1
# FILE2 = 's2001a'

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e:
        if e.errno != errno.ENOENT:
            # errno.ENOENT = no such file or directory
            raise

LabelledInterval = recordtype('LabelledInterval' ,'label interval')


def load_gold(goldfile):
    res = {}
    current_file = ''
    prev_end = -1
    with open(goldfile) as fin:
        for line in fin:
            splitted = line.strip().split()
            if not splitted:
                # empty line
                continue
            elif len(splitted) == 1:
                # New file
                current_file = splitted[0]
开发者ID:bootphon,项目名称:ZRTools,代码行数:31,代码来源:precision_match.py


示例14: property

        assert 1 <= secret.exponent < SECP256k1.order, (u"encoded exponent "
            u"must be an integer x such that 1 <= x < 0x%x" % SECP256k1.order)

        # Return the newly generated Secret
        return secret

    # The exponent is stored as a 256-bit big endian integer, the first field
    # of the payload:
    exponent = property(lambda self:BigInteger.deserialize(BytesIO(self.payload[:32]), 32))
    # A compressed key is requested by suffixing 0x01 to the payload field. Note
    # that the following comparison only returns true if payload is exactly 33
    # bytes in length and the final byte is '\x01'.
    compressed = property(lambda self:self.payload[32:] == six.int2byte(1))

from recordtype import recordtype
BaseSignature = recordtype('BaseSignature', 'r s'.split())

class Signature(SerializableMixin, BaseSignature):
    def serialize(self):
        def _serialize_derint(n):
            n_str = BigNum(n).serialize()
            return b''.join([
                six.int2byte(0x02),
                six.int2byte(len(n_str)),
                n_str,
            ])
        r_str = _serialize_derint(self.r)
        s_str = _serialize_derint(self.s)
        return b''.join([
            six.int2byte(0x30),
            six.int2byte(len(r_str + s_str)),
开发者ID:monetizeio,项目名称:python-bitcoin,代码行数:31,代码来源:ecdsa_generic.py


示例15: Markup

from .util import GeoRange
import simplejson as json
from lxml import etree
from lxml.etree import ParseError
from markupsafe import Markup

RPC_URL = "http://webservices.nextbus.com/service/publicXMLFeed?"
# cache durations
SHORT = 20
HOUR = 3600
DAY = 86400

resource_uri = Markup("resource_uri")
template_id = Markup("{{id}}")

Point = recordtype("Point", ['lat', 'lng'])

AgencyRecord = recordtype("Agency", ['id', 'title', 'region',
    ('short_title', None), ('route_ids', [])])
class Agency(AgencyRecord):
    @property
    def url(self):
        return url_for('agency_detail', agency_id=self.id)

    def _as_url_dict(self):
        d = self._asdict()
        d[resource_uri] = self.url
        detail_uri_template = url_for('route_detail', agency_id=self.id, route_id=template_id)
        # unescape mustaches
        detail_uri_template = detail_uri_template.replace("%7B", "{").replace("%7D", "}")
        d['routes'] = dict(
开发者ID:singingwolfboy,项目名称:buscalling,代码行数:31,代码来源:nextbus.py


示例16: CPUInfo

system.

Part of 'Adaptor' framework.

Author: Michael Pankov, 2012-2013.

Please do not redistribute.
"""

import recordtype as rt
import collections as cl

from printable_structure import PrintableStructure


CPUInfoBase = rt.recordtype('CPUInfo',
    'cpu_name cpu_mhz cache_size flags')


class CPUInfo(PrintableStructure, CPUInfoBase):
    pass


HardwareInfoBase = rt.recordtype('HardwareInfo',
    'cpu_info')


class HardwareInfo(PrintableStructure, HardwareInfoBase):
    pass


BuildSettingsBase = rt.recordtype('BuildSettings',
开发者ID:mkpankov,项目名称:adaptor,代码行数:32,代码来源:data_types.py


示例17: recordtype

import random
import numpy as np
from numpy.linalg import norm
from collections import namedtuple
from recordtype import recordtype

Cluster = recordtype('Cluster', ('center', 'members', 'converged'))

class KMeans:
    def __init__(self, X, k, iters = 1):
        self.X = X
        self.k = k
        self.iters = iters
        self.cost = None
        self.clusters = []

    def fit(self):
        self.clusters = self.__find_centers(self.X, self.k, self.clusters)
        self.cost = self.__cost(self.clusters)

        for _ in xrange(self.iters - 1):
            new_clusters = self.__find_centers(self.X, self.k, self.clusters)
            new_cost = self.__cost(self.clusters)

            if (new_cost < self.cost):
                self.clusters = new_clusters
                self.cost = new_cost

        return self.clusters

    def __find_centers(self, X, k, clusters):
开发者ID:mottalrd,项目名称:k_means,代码行数:31,代码来源:k_means.py


示例18: attribute_repr


def attribute_repr(self, indent_level=0):
    """Pretty print for an attribute."""

    indent = '\t' * indent_level
    return '%s{Attribute: %s = %s}' % (indent, self.key, str(self.value))


def widget_repr(self, indent_level=0):
    """Pretty print for a widget."""

    indent = '\t' * indent_level
    attrs = '\n'.join([a.repr(indent_level + 1) for a in self.attributes])
    child_widgets = '\n\n'.join([c.repr(indent_level + 1) for c in self.child_widgets])
    if attrs and child_widgets:
        attrs += '\n\n'
    return '%s{Widget: %s\n%s%s\n%s}' % (indent, self.name, attrs, child_widgets, indent)


# AST nodes

# TODO: Make your changes here ################################################

Attribute = recordtype('Attribute', 'key, value')
Widget = recordtype('Widget', 'name, attributes, child_widgets')

# Give them a pretty print method
Attribute.repr = attribute_repr
Widget.repr = widget_repr
开发者ID:raaron,项目名称:funcparserlib_talk,代码行数:28,代码来源:pyml_ast.py


示例19: before_cursor_execute

@event.listens_for(Engine, 'before_cursor_execute')
def before_cursor_execute(conn, cursor, statement, 
                          parameters, context, executemany):
    global query_stats
    query_stats._begin = datetime.now()

@event.listens_for(Engine, 'after_cursor_execute')
def after_cursor_execute(conn, cursor, statement, 
                         parameters, context, executemany):
    global query_stats
    query_stats.num_queries += 1
    query_stats.time_database += (datetime.now() - query_stats._begin).total_seconds()

from recordtype import recordtype
TableStatistics = recordtype('TableStatistics',
    'num_inserts num_updates num_deletes'.split(), default=0)

@event.listens_for(Mapper, 'after_insert')
def after_insert(mapper, connection, target):
    global query_stats
    query_stats.table_stats.setdefault(target.__table__.name, TableStatistics())
    query_stats.table_stats[target.__table__.name].num_inserts += 1

@event.listens_for(Mapper, 'after_update')
def after_update(mapper, connection, target):
    global query_stats
    query_stats.table_stats.setdefault(target.__table__.name, TableStatistics())
    query_stats.table_stats[target.__table__.name].num_updates += 1

@event.listens_for(Mapper, 'after_delete')
def after_delete(mapper, connection, target):
开发者ID:aburan28,项目名称:utxo-ledger,代码行数:31,代码来源:utxosync.py


示例20: namedtuple

from collections import namedtuple
from os import access, path, W_OK

from flask import current_app
from recordtype import recordtype
from werkzeug.security import generate_password_hash, check_password_hash
from flask.ext.login import UserMixin

import models_jsonapi as mj
from . import db, login_manager, date_util
from datetime import timedelta


StateWarning = namedtuple('StateWarning', ['limit', 'value', 'created_ts', 'sensor', 'alarming_measurements'])

RRDDef = recordtype('RRDDef', 'name step path mmin mmax')


class Measurement(object):
    def __init__(self, sensor_code):
        self.sensor_code = sensor_code
        self.sensor = None

        self.value = None
        self.read_ts = None
        self.has_warning = False
        self.has_notification = False

    def init_sensor(self):
        self.sensor = db.session.query(Sensor).filter(Sensor.sensor_code == self.sensor_code).first()
开发者ID:greginvm,项目名称:farmcontrol,代码行数:30,代码来源:models.py



注:本文中的recordtype.recordtype函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python fsm.FSM类代码示例发布时间:2022-05-26
下一篇:
Python recorder.Recorder类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap