desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Checks types of input data before forward propagation.
Before :meth:`forward` is called, this function is called.
You need to validate types of input data in this function
using :ref:`the type checking utilities <type-check-utils>`.
Args:
in_types (~chainer.utils.type_check.TypeInfoTuple): The type
information of input data for :meth:`forward`.'
| def check_type_forward(self, in_types):
| pass
|
'Applies forward propagation to input arrays.
It delegates the procedure to :meth:`forward_cpu` or
:meth:`forward_gpu` by default. Which it selects is determined by the
type of input arrays.
Implementations of :class:`Function` must implement either CPU/GPU
methods or this method.
Args:
inputs: Tuple of input array(s).
Returns:
Tuple of output array(s).
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def forward(self, inputs):
| if any((isinstance(x, cuda.ndarray) for x in inputs)):
return self.forward_gpu(inputs)
else:
return self.forward_cpu(inputs)
|
'Applies forward propagation to input arrays on CPU.
Args:
inputs: Tuple of :class:`numpy.ndarray` object(s).
Returns:
tuple: Tuple of :class:`numpy.ndarray` object(s).
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def forward_cpu(self, inputs):
| raise NotImplementedError()
|
'Applies forward propagation to input arrays on GPU.
Args:
inputs: Tuple of :class:`cupy.ndarray` object(s).
Returns:
tuple: Tuple of :class:`cupy.ndarray` object(s).
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def forward_gpu(self, inputs):
| raise NotImplementedError()
|
'Applies backprop to output gradient arrays.
It delegates the procedure to :meth:`backward_cpu` or
:meth:`backward_gpu` by default. Which it selects is determined by the
type of input arrays and output gradient arrays. Implementations of
:class:`Function` must implement either CPU/GPU methods or this method,
if the function is intended to be backprop-ed.
Args:
inputs: Tuple of input arrays.
grad_outputs: Tuple of output gradient arrays.
Returns:
tuple: Tuple of input gradient arrays. Some or all of them can be
``None``, if the function is not differentiable on
inputs.
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def backward(self, inputs, grad_outputs):
| if any((isinstance(x, cuda.ndarray) for x in (inputs + grad_outputs))):
return self.backward_gpu(inputs, grad_outputs)
else:
return self.backward_cpu(inputs, grad_outputs)
|
'Applies backprop to output gradient arrays on CPU.
Args:
inputs: Tuple of input :class:`numpy.ndarray` object(s).
grad_outputs: Tuple of output gradient :class:`numpy.ndarray`
object(s).
Returns:
tuple: Tuple of input gradient :class:`numpy.ndarray` object(s).
Some or all of them can be ``None``, if the function is not
differentiable on corresponding inputs.
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def backward_cpu(self, inputs, grad_outputs):
| return tuple((None for _ in inputs))
|
'Applies backprop to output gradient arrays on GPU.
Args:
inputs: Tuple of input :class:`cupy.ndarray`
object(s).
grad_outputs: Tuple of output gradient
:class:`cupy.ndarray` object(s).
Returns:
tuple: Tuple of input gradient :class:`cupy.ndarray`
object(s). Some or all of them can be ``None``, if the function is
not differentiable on corresponding inputs.
.. warning::
Implementations of :class:`Function` must take care that the
return value must be a tuple even if it returns only one array.'
| def backward_gpu(self, inputs, grad_outputs):
| return tuple((None for _ in inputs))
|
'Purges in/out nodes and this function itself from the graph.
See :meth:`FunctionNode.unchain` for the detail.'
| def unchain(self):
| self.node.unchain()
|
'Registers a function hook.
See :meth:`FunctionNode.add_hook` for the detail.
Args:
hook(~chainer.function.FunctionHook):
Function hook to be registered.
name(str): Name of the function hook.
name must be unique among function hooks
registered to the function. If ``None``,
default name of the function hook is used.'
| def add_hook(self, hook, name=None):
| self.node.add_hook(hook, name)
|
'Unregisters the specified function hook.
Args:
name(str): the name of the function hook
to be unregistered.'
| def delete_hook(self, name):
| self.node.delete_hook(name)
|
'Lets specified input variable nodes keep data arrays.
By calling this method from :meth:`forward`, the function can specify
which inputs are required for backprop.
If this method is not called, the function keeps all input arrays. If
you want to release all input arrays, call this method by passing an
empty sequence. *Note that this behavior is different from that of*
:meth:`FunctionNode.retain_inputs`.
Note that **this method must not be called from the outside of
forward method.**
Args:
indexes (iterable of int): Indexes of input variables that the
function does not require for backprop.'
| def retain_inputs(self, indexes):
| self.node.retain_inputs(indexes)
|
'Lets specified output variable nodes keep data arrays.
By calling this method from :meth:`forward`, the function can specify
which outputs are required for backprop. If this method is not called,
any output variables are not marked to keep the data array at the point
of returning from :meth:`__call__`. The retained arrays are stored to
:attr:`output_data`.
.. note::
It is STRONGLY RECOMMENDED to use this method if the function
requires some or all output arrays in backprop. The function can
also use output arrays just by keeping references to them directly,
whereas it might influence on the performance of later function
applications to the output variables.
Note that **this method must not be called from the outside of
forward method.**
Args:
indexes (iterable of int): Indexes of input variables that the
function does not require for backprop.
retain_after_backward (bool): This option has no effect. It is
left only for the backward compatibility.'
| def retain_outputs(self, indexes, retain_after_backward=False):
| if retain_after_backward:
warnings.warn('retain_after_backward option has no effect', DeprecationWarning)
self.node.retain_outputs(indexes)
|
'The text that represents properties of the node.
Returns:
string: The text that represents the id and attributes of this
node.'
| @property
def label(self):
| attributes = [('%s="%s"' % (k, v)) for (k, v) in self.attribute.items()]
return ('%s [%s];' % (self.id_, ','.join(attributes)))
|
'Converts graph in dot format.
`label` property of is used as short description of each node.
Returns:
str: The graph in dot format.'
| def _to_dot(self):
| ret = ('digraph graphname{rankdir=%s;' % self.rankdir)
if self.remove_variable:
(self.nodes, self.edges) = _skip_variable(self.nodes, self.edges)
for node in self.nodes:
assert isinstance(node, (variable.VariableNode, function_node.FunctionNode))
if isinstance(node, variable.VariableNode):
if (not self.remove_variable):
ret += DotNode(node, self.variable_style, self.show_name).label
else:
ret += DotNode(node, self.function_style, self.show_name).label
drawn_edges = []
for edge in self.edges:
(head, tail) = edge
if (isinstance(head, variable.VariableNode) and isinstance(tail, function_node.FunctionNode)):
head_attr = self.variable_style
tail_attr = self.function_style
elif (isinstance(head, function_node.FunctionNode) and isinstance(tail, variable.VariableNode)):
head_attr = self.function_style
tail_attr = self.variable_style
elif (not self.remove_variable):
raise TypeError('head and tail should be the set of VariableNode and Function')
else:
head_attr = self.function_style
tail_attr = self.function_style
head_node = DotNode(head, head_attr, self.show_name)
tail_node = DotNode(tail, tail_attr, self.show_name)
edge = (head_node.id_, tail_node.id_)
if (edge in drawn_edges):
continue
ret += ('%s -> %s;' % edge)
drawn_edges.append(edge)
ret += '}'
return ret
|
'Dumps graph as a text.
Args:
format(str): The graph language name of the output.
Currently, it must be \'dot\'.
Returns:
str: The graph in specified format.'
| def dump(self, format='dot'):
| if (format == 'dot'):
return self._to_dot()
else:
NotImplementedError('Currently, only dot format is supported.')
|
'Make a sampler GPU mode.'
| def to_gpu(self):
| if (not self.use_gpu):
self.threshold = cuda.to_gpu(self.threshold)
self.values = cuda.to_gpu(self.values)
self.use_gpu = True
|
'Make a sampler CPU mode.'
| def to_cpu(self):
| if self.use_gpu:
self.threshold = cuda.to_cpu(self.threshold)
self.values = cuda.to_cpu(self.values)
self.use_gpu = False
|
'Generates a random sample based on given probabilities.
Args:
shape (tuple of int): Shape of a return value.
Returns:
Returns a generated array with the given shape. If a sampler is in
CPU mode the return value is a :class:`numpy.ndarray` object, and
if it is in GPU mode the return value is a :class:`cupy.ndarray`
object.'
| def sample(self, shape):
| if self.use_gpu:
return self.sample_gpu(shape)
else:
return self.sample_cpu(shape)
|
'Returns an expression representing its length.
Returns:
Expr: An expression object representing length of the tuple.'
| def size(self):
| return Variable(len(self), '{0}.size'.format(self.name))
|
'Returns its length.
Returns:
int: Length of the tuple.'
| def size(self):
| return len(self)
|
'Evaluates the tree to get actual value.
Behavior of this function depends on an implementation class.
For example, a binary operator ``+`` calls the ``__add__`` function
with the two results of :meth:`eval` function.'
| def eval(self):
| raise NotImplementedError()
|
''
| def __init__(self, subcommond, *args):
| self.subcommond = subcommond
self.args = args
|
''
| def execute(self):
| commmd = getattr(commands, self.subcommond)
commmd.execute(*self.args)
|
''
| def __init__(self, name, pk, data={}):
| MemObject.__init__(self, name, mclient)
self._state = MMODE_STATE_ORI
self._pk = pk
self.data = data
self._time = time.time()
|
''
| def delete(self):
| return MemObject.update(self, '_state', MMODE_STATE_DEL)
|
''
| def mdelete(self):
| self.syncDB()
MemObject.mdelete(self)
|
''
| def IsEffective(self):
| if (self.get('_state') == MMODE_STATE_DEL):
return False
return True
|
''
| def syncDB(self):
| state = self.get('_state')
tablename = self._name.split(':')[0]
if (state == MMODE_STATE_ORI):
return
elif (state == MMODE_STATE_NEW):
props = self.get('data')
pk = self.get('_pk')
result = util.InsertIntoDB(tablename, props)
elif (state == MMODE_STATE_UPDATE):
props = self.get('data')
pk = self.get('_pk')
prere = {pk: props.get(pk)}
util.UpdateWithDict(tablename, props, prere)
result = True
else:
pk = self.get('_pk')
props = self.get('data')
prere = {pk: props.get(pk)}
result = util.DeleteFromDB(tablename, prere)
if result:
MemObject.update(self, '_state', MMODE_STATE_ORI)
|
''
| def checkSync(self, timeout=TIMEOUT):
| ntime = time.time()
objtime = MemObject.get(self, '_time')
if (((ntime - objtime) >= timeout) and timeout):
self.mdelete()
else:
self.syncDB()
|
''
| def load(self):
| mmname = self._name
recordlist = util.ReadDataFromDB(mmname)
for record in recordlist:
pk = record[self._pk]
mm = MMode((self._name + (':%s' % pk)), self._pk, data=record)
mm.insert()
|
''
| def getAllPkByFk(self, fk):
| name = ('%s_fk:%s' % (self._name, fk))
fkmm = MFKMode(name)
pklist = fkmm.get('pklist')
if (pklist is not None):
return pklist
props = {self._fk: fk}
dbkeylist = util.getAllPkByFkInDB(self._name, self._pk, props)
name = ('%s_fk:%s' % (self._name, fk))
fkmm = MFKMode(name, pklist=dbkeylist)
fkmm.insert()
return dbkeylist
|
''
| def getObj(self, pk):
| mm = MMode((self._name + (':%s' % pk)), self._pk)
if (not mm.IsEffective()):
return None
if mm.get('data'):
return mm
props = {self._pk: pk}
record = util.GetOneRecordInfo(self._name, props)
if (not record):
return None
mm = MMode((self._name + (':%s' % pk)), self._pk, data=record)
mm.insert()
return mm
|
''
| def getObjData(self, pk):
| mm = MMode((self._name + (':%s' % pk)), self._pk)
if (not mm.IsEffective()):
return None
data = mm.get('data')
if mm.get('data'):
return data
props = {self._pk: pk}
record = util.GetOneRecordInfo(self._name, props)
if (not record):
return None
mm = MMode((self._name + (':%s' % pk)), self._pk, data=record)
mm.insert()
return record
|
''
| def getObjList(self, pklist):
| _pklist = []
objlist = []
for pk in pklist:
mm = MMode((self._name + (':%s' % pk)), self._pk)
if (not mm.IsEffective()):
continue
if mm.get('data'):
objlist.append(mm)
else:
_pklist.append(pk)
if _pklist:
recordlist = util.GetRecordList(self._name, self._pk, _pklist)
for record in recordlist:
pk = record[self._pk]
mm = MMode((self._name + (':%s' % pk)), self._pk, data=record)
mm.insert()
objlist.append(mm)
return objlist
|
''
| def deleteMode(self, pk):
| mm = self.getObj(pk)
if mm:
if self._fk:
data = mm.get('data')
if data:
fk = data.get(self._fk, 0)
name = ('%s_fk:%s' % (self._name, fk))
fkmm = MFKMode(name)
pklist = fkmm.get('pklist')
if (pklist and (pk in pklist)):
pklist.remove(pk)
fkmm.update('pklist', pklist)
mm.delete()
return True
|
''
| def deleteAllFk(self):
| key = ('%s:%s_fk:' % (mclient._hostname, self._name))
_fklist = util.getallkeys(key, mclient.connection)
for fk in _fklist:
name = ('%s_fk:%s' % (self._name, fk))
fkmm = MFKMode(name)
fkmm.mdelete()
|
''
| def new(self, data):
| incrkey = self._incrkey
if incrkey:
incrvalue = self.incr('_incrvalue', 1)
data[incrkey] = (incrvalue - 1)
pk = data.get(self._pk)
if (pk is None):
raise PKValueError(data)
mm = MMode((self._name + (':%s' % pk)), self._pk, data=data)
setattr(mm, incrkey, pk)
else:
pk = data.get(self._pk)
mm = MMode((self._name + (':%s' % pk)), self._pk, data=data)
if self._fk:
fk = data.get(self._fk, 0)
name = ('%s_fk:%s' % (self._name, fk))
fkmm = MFKMode(name)
pklist = fkmm.get('pklist')
if (pklist is None):
pklist = self.getAllPkByFk(fk)
pklist.append(pk)
fkmm.update('pklist', pklist)
setattr(mm, '_state', MMODE_STATE_NEW)
mm.insert()
return mm
|
''
| def __init__(self):
| self.admins = {}
|
''
| def registe(self, admin):
| self.admins[admin._name] = admin
|
''
| def dropAdmin(self, adminname):
| if self.admins.has_key(adminname):
del self.admins[adminname]
|
''
| def getAdmin(self, adminname):
| return self.admins.get(adminname)
|
''
| def checkAdmins(self):
| for admin in self.admins.values():
admin.checkAll()
|
'Creates a new SQLQuery.
>>> SQLQuery("x")
<sql: \'x\'>
>>> q = SQLQuery([\'SELECT * FROM \', \'test\', \' WHERE x=\', SQLParam(1)])
>>> q
<sql: \'SELECT * FROM test WHERE x=1\'>
>>> q.query(), q.values()
(\'SELECT * FROM test WHERE x=%s\', [1])
>>> SQLQuery(SQLParam(1))
<sql: \'1\'>'
| def __init__(self, items=None):
| if (items is None):
self.items = []
elif isinstance(items, list):
self.items = items
elif isinstance(items, SQLParam):
self.items = [items]
elif isinstance(items, SQLQuery):
self.items = list(items.items)
else:
self.items = [items]
for (i, item) in enumerate(self.items):
if (isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral)):
self.items[i] = item.value.v
|
'Returns the query part of the sql query.
>>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')])
>>> q.query()
\'SELECT * FROM test WHERE name=%s\'
>>> q.query(paramstyle=\'qmark\')
\'SELECT * FROM test WHERE name=?\''
| def query(self, paramstyle=None):
| s = []
for x in self.items:
if isinstance(x, SQLParam):
x = x.get_marker(paramstyle)
s.append(safestr(x))
else:
x = safestr(x)
if (paramstyle in ['format', 'pyformat']):
if (('%' in x) and ('%%' not in x)):
x = x.replace('%', '%%')
s.append(x)
return ''.join(s)
|
'Returns the values of the parameters used in the sql query.
>>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')])
>>> q.values()
[\'joe\']'
| def values(self):
| return [i.value for i in self.items if isinstance(i, SQLParam)]
|
'Joins multiple queries.
>>> SQLQuery.join([\'a\', \'b\'], \', \')
<sql: \'a, b\'>
Optinally, prefix and suffix arguments can be provided.
>>> SQLQuery.join([\'a\', \'b\'], \', \', prefix=\'(\', suffix=\')\')
<sql: \'(a, b)\'>
If target argument is provided, the items are appended to target instead of creating a new SQLQuery.'
| def join(items, sep=' ', prefix=None, suffix=None, target=None):
| if (target is None):
target = SQLQuery()
target_items = target.items
if prefix:
target_items.append(prefix)
for (i, item) in enumerate(items):
if (i != 0):
target_items.append(sep)
if isinstance(item, SQLQuery):
target_items.extend(item.items)
else:
target_items.append(item)
if suffix:
target_items.append(suffix)
return target
|
'Creates a database.'
| def __init__(self):
| pass
|
'Execute SQL query `sql_query` using dictionary `vars` to interpolate it.
If `processed=True`, `vars` is a `reparam`-style list to use
instead of interpolating.
>>> db = DB(None, {})
>>> db.query("SELECT * FROM foo", _test=True)
<sql: \'SELECT * FROM foo\'>
>>> db.query("SELECT * FROM foo WHERE x = $x", vars=dict(x=\'f\'), _test=True)
<sql: "SELECT * FROM foo WHERE x = \'f\'">
>>> db.query("SELECT * FROM foo WHERE x = " + sqlquote(\'f\'), _test=True)
<sql: "SELECT * FROM foo WHERE x = \'f\'">'
| def query(self, sql_query, processed=False, svars=None):
| if (svars is None):
svars = {}
if ((not processed) and (not isinstance(sql_query, SQLQuery))):
sql_query = reparam(sql_query, svars)
return sql_query
|
'Selects `what` from `tables` with clauses `where`, `order`,
`group`, `limit`, and `offset`. Uses vars to interpolate.
Otherwise, each clause can be a SQLQuery.
>>> db = DB(None, {})
>>> db.select(\'foo\', _test=True)
<sql: \'SELECT * FROM foo\'>
>>> db.select([\'foo\', \'bar\'], where="foo.bar_id = bar.id", limit=5, _test=True)
<sql: \'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5\'>'
| def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False):
| if (svars is None):
svars = {}
sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset)
clauses = [self.gen_clause(sql, val, svars) for (sql, val) in sql_clauses if (val is not None)]
qout = SQLQuery.join(clauses)
if _test:
return qout
return self.query(qout, processed=True)
|
'Inserts `values` into `tablename`. Returns current sequence ID.
Set `seqname` to the ID if it\'s not the default, or to `False`
if there isn\'t one.
>>> db = DB(None, {})
>>> q = db.insert(\'foo\', name=\'bob\', age=2, created=SQLLiteral(\'NOW()\'), _test=True)
>>> q
<sql: "INSERT INTO foo (age, name, created) VALUES (2, \'bob\', NOW())">
>>> q.query()
\'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())\'
>>> q.values()
[2, \'bob\']'
| def insert(self, tablename, seqname=None, _test=False, **values):
| def q(x):
return (('(' + x) + ')')
if values:
_keys = SQLQuery.join(values.keys(), ', ')
_values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ')
sql_query = (((('INSERT INTO %s ' % tablename) + q(_keys)) + ' VALUES ') + q(_values))
else:
sql_query = SQLQuery(self._get_insert_default_values_query(tablename))
return sql_query
|
'Inserts multiple rows into `tablename`. The `values` must be a list of dictioanries,
one for each row to be inserted, each with the same set of keys.
Returns the list of ids of the inserted rows.
Set `seqname` to the ID if it\'s not the default, or to `False`
if there isn\'t one.
>>> db = DB(None, {})
>>> db.supports_multiple_insert = True
>>> values = [{"name": "foo", "email": "[email protected]"}, {"name": "bar", "email": "[email protected]"}]
>>> db.multiple_insert(\'person\', values=values, _test=True)
<sql: "INSERT INTO person (name, email) VALUES (\'foo\', \'[email protected]\'), (\'bar\', \'[email protected]\')">'
| def multiple_insert(self, tablename, values, seqname=None, _test=False):
| if (not values):
return []
if (not self.supports_multiple_insert):
out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values]
if (seqname is False):
return None
else:
return out
keys = values[0].keys()
for v in values:
if (v.keys() != keys):
raise ValueError, 'Bad data'
sql_query = SQLQuery(('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))))
for (i, row) in enumerate(values):
if (i != 0):
sql_query.append(', ')
SQLQuery.join([SQLParam(row[k]) for k in keys], sep=', ', target=sql_query, prefix='(', suffix=')')
if _test:
return sql_query
db_cursor = self._db_cursor()
if (seqname is not False):
sql_query = self._process_insert_query(sql_query, tablename, seqname)
if isinstance(sql_query, tuple):
(q1, q2) = sql_query
self._db_execute(db_cursor, q1)
self._db_execute(db_cursor, q2)
else:
self._db_execute(db_cursor, sql_query)
try:
out = db_cursor.fetchone()[0]
out = range(((out - len(values)) + 1), (out + 1))
except Exception:
out = None
if (not self.ctx.transactions):
self.ctx.commit()
return out
|
'Update `tables` with clause `where` (interpolated using `vars`)
and setting `values`.
>>> db = DB(None, {})
>>> name = \'Joseph\'
>>> q = db.update(\'foo\', where=\'name = $name\', name=\'bob\', age=2,
... created=SQLLiteral(\'NOW()\'), vars=locals(), _test=True)
>>> q
<sql: "UPDATE foo SET age = 2, name = \'bob\', created = NOW() WHERE name = \'Joseph\'">
>>> q.query()
\'UPDATE foo SET age = %s, name = %s, created = NOW() WHERE name = %s\'
>>> q.values()
[2, \'bob\', \'Joseph\']'
| def update(self, tables, where, svars=None, _test=False, **values):
| if (svars is None):
svars = {}
where = self._where(where, svars)
query = ((((('UPDATE ' + sqllist(tables)) + ' SET ') + sqlwhere(values, ', ')) + ' WHERE ') + where)
if _test:
return query
db_cursor = self._db_cursor()
self._db_execute(db_cursor, query)
if (not self.ctx.transactions):
self.ctx.commit()
return db_cursor.rowcount
|
'Deletes from `table` with clauses `where` and `using`.
>>> db = DB(None, {})
>>> name = \'Joe\'
>>> db.delete(\'foo\', where=\'name = $name\', vars=locals(), _test=True)
<sql: "DELETE FROM foo WHERE name = \'Joe\'">'
| def delete(self, table, where, using=None, svars=None, _test=False):
| if (svars is None):
svars = {}
where = self._where(where, svars)
q = ('DELETE FROM ' + table)
if using:
q += (' USING ' + sqllist(using))
if where:
q += (' WHERE ' + where)
return q
|
''
| def initPool(self, **kw):
| self.config = kw
creator = DBCS.get(kw.get('engine', 'mysql'), MySQLdb)
self.pool = PooledDB(creator, 5, **kw)
|
''
| def __init__(self, timeout=0):
| self._hostname = ''
self._urls = []
self.connection = None
|
'memcached connect'
| def connect(self, urls, hostname):
| self._hostname = hostname
self._urls = urls
self.connection = memcache.Client(self._urls, debug=0)
if (not self.connection.set('__testkey__', 1)):
raise MemConnError()
|
''
| def produceKey(self, keyname):
| if isinstance(keyname, basestring):
return ''.join([self._hostname, ':', keyname])
else:
raise 'type error'
|
''
| def get(self, key):
| key = self.produceKey(key)
return self.connection.get(key)
|
''
| def get_multi(self, keys):
| keynamelist = [self.produceKey(keyname) for keyname in keys]
olddict = self.connection.get_multi(keynamelist)
newdict = dict(zip([keyname.split(':')[(-1)] for keyname in olddict.keys()], olddict.values()))
return newdict
|
''
| def set(self, keyname, value):
| key = self.produceKey(keyname)
result = self.connection.set(key, value)
if (not result):
self.connect(self._urls, self._hostname)
return self.connection.set(key, value)
return result
|
''
| def set_multi(self, mapping):
| newmapping = dict(zip([self.produceKey(keyname) for keyname in mapping.keys()], mapping.values()))
result = self.connection.set_multi(newmapping)
if result:
self.connect(self._urls, self._hostname)
return self.connection.set_multi(newmapping)
return result
|
''
| def incr(self, key, delta):
| key = self.produceKey(key)
return self.connection.incr(key, delta)
|
''
| def delete(self, key):
| key = self.produceKey(key)
return self.connection.delete(key)
|
''
| def delete_multi(self, keys):
| keys = [self.produceKey(key) for key in keys]
return self.connection.delete_multi(keys)
|
''
| def flush_all(self):
| self.connection.flush_all()
|
'@param name: str 对象çå称
@param _lock: int 对象é 䞺1æ¶è¡šç€ºå¯¹è±¡è¢«éå®æ æ³è¿è¡ä¿®æ¹'
| def __init__(self, name, mc):
| self._client = mc
self._name = name
self._lock = 0
|
'éæ°çækey'
| def produceKey(self, keyname):
| if isinstance(keyname, basestring):
return ''.join([self._name, ':', keyname])
else:
raise 'type error'
|
''
| def locked(self):
| key = self.produceKey('_lock')
return self._client.get(key)
|
''
| def lock(self):
| key = self.produceKey('_lock')
self._client.set(key, 1)
|
''
| def release(self):
| key = self.produceKey('_lock')
self._client.set(key, 0)
|
''
| def get(self, key):
| key = self.produceKey(key)
return self._client.get(key)
|
'äžæ¬¡è·åå€äžªkeyçåŒ
@param keys: list(str) keyçåè¡š'
| def get_multi(self, keys):
| keynamelist = [self.produceKey(keyname) for keyname in keys]
olddict = self._client.get_multi(keynamelist)
newdict = dict(zip([keyname.split(':')[(-1)] for keyname in olddict.keys()], olddict.values()))
return newdict
|
''
| def update(self, key, values):
| if self.locked():
return False
key = self.produceKey(key)
return self._client.set(key, values)
|
'åæ¶ä¿®æ¹å€äžªkeyåŒ'
| def update_multi(self, mapping):
| if self.locked():
return False
newmapping = dict(zip([self.produceKey(keyname) for keyname in mapping.keys()], mapping.values()))
return self._client.set_multi(newmapping)
|
'å é€memcacheäžçæ°æ®'
| def mdelete(self):
| nowdict = dict(self.__dict__)
del nowdict['_client']
keys = nowdict.keys()
keys = [self.produceKey(key) for key in keys]
self._client.delete_multi(keys)
|
''
| def incr(self, key, delta):
| key = self.produceKey(key)
return self._client.incr(key, delta)
|
''
| def insert(self):
| nowdict = dict(self.__dict__)
del nowdict['_client']
newmapping = dict(zip([self.produceKey(keyname) for keyname in nowdict.keys()], nowdict.values()))
self._client.set_multi(newmapping)
|
'@param HEAD_0: int å议倎0
@param HEAD_1: int å议倎1
@param HEAD_2: int å议倎2
@param HEAD_3: int å议倎3
@param protoVersion: int å议倎çæ¬å·
@param serverVersion: int æå¡çæ¬å·'
| def __init__(self, HEAD_0=0, HEAD_1=0, HEAD_2=0, HEAD_3=0, protoVersion=0, serverVersion=0):
| self.HEAD_0 = HEAD_0
self.HEAD_1 = HEAD_1
self.HEAD_2 = HEAD_2
self.HEAD_3 = HEAD_3
self.protoVersion = protoVersion
self.serverVersion = serverVersion
|
''
| def getHeadlength(self):
| return 17
|
''
| def unpack(self, dpack):
| try:
ud = struct.unpack('!sssss3I', dpack)
except DataPackError as de:
log.err(de)
return {'result': False, 'command': 0, 'length': 0}
HEAD_0 = ord(ud[0])
HEAD_1 = ord(ud[1])
HEAD_2 = ord(ud[2])
HEAD_3 = ord(ud[3])
protoVersion = ord(ud[4])
serverVersion = ud[5]
length = (ud[6] - 4)
command = ud[7]
if ((HEAD_0 != self.HEAD_0) or (HEAD_1 != self.HEAD_1) or (HEAD_2 != self.HEAD_2) or (HEAD_3 != self.HEAD_3) or (protoVersion != self.protoVersion) or (serverVersion != self.serverVersion)):
return {'result': False, 'command': 0, 'length': 0}
return {'result': True, 'command': command, 'length': length}
|
''
| def pack(self, response, command):
| HEAD_0 = chr(self.HEAD_0)
HEAD_1 = chr(self.HEAD_1)
HEAD_2 = chr(self.HEAD_2)
HEAD_3 = chr(self.HEAD_3)
protoVersion = chr(self.protoVersion)
serverVersion = self.serverVersion
length = (response.__len__() + 4)
commandID = command
data = struct.pack('!sssss3I', HEAD_0, HEAD_1, HEAD_2, HEAD_3, protoVersion, serverVersion, length, commandID)
data = (data + response)
return data
|
'@param _connections: dict {connID:conn Object}'
| def __init__(self):
| self._connections = {}
|
''
| def getNowConnCnt(self):
| return len(self._connections.items())
|
'@param _conn: Conn object'
| def addConnection(self, conn):
| _conn = Connection(conn)
if self._connections.has_key(_conn.id):
raise Exception('\xe7\xb3\xbb\xe7\xbb\x9f\xe8\xae\xb0\xe5\xbd\x95\xe5\x86\xb2\xe7\xaa\x81')
self._connections[_conn.id] = _conn
|
'æŽå è¿æ¥çidå é€è¿æ¥å®äŸ
@param connID: int è¿æ¥çid'
| def dropConnectionByID(self, connID):
| try:
del self._connections[connID]
except Exception as e:
log.msg(str(e))
|
'æ ¹æ®IDè·åäžæ¡è¿æ¥
@param connID: int è¿æ¥çid'
| def getConnectionByID(self, connID):
| return self._connections.get(connID, None)
|
'æ ¹æ®è¿æ¥IDäž»åšç«¯å£äžå®¢æ·ç«¯çè¿æ¥'
| def loseConnection(self, connID):
| conn = self.getConnectionByID(connID)
if conn:
conn.loseConnection()
|
''
| def pushObject(self, topicID, msg, sendList):
| for target in sendList:
try:
conn = self.getConnectionByID(target)
if conn:
conn.safeToWriteData(topicID, msg)
except Exception as e:
log.err(str(e))
|
'id è¿æ¥çID
transport è¿æ¥çéé'
| def __init__(self, _conn):
| self.id = _conn.transport.sessionno
self.instance = _conn
|
''
| def loseConnection(self):
| self.instance.transport.loseConnection()
|
''
| def safeToWriteData(self, topicID, msg):
| self.instance.safeToWriteData(msg, topicID)
|
''
| def connectionMade(self):
| log.msg(('Client %d login in.[%s,%d]' % (self.transport.sessionno, self.transport.client[0], self.transport.client[1])))
self.factory.connmanager.addConnection(self)
self.factory.doConnectionMade(self)
self.datahandler = self.dataHandleCoroutine()
self.datahandler.next()
|
''
| def connectionLost(self, reason):
| log.msg(('Client %d login out.' % self.transport.sessionno))
self.factory.doConnectionLost(self)
self.factory.connmanager.dropConnectionByID(self.transport.sessionno)
|
'@param data: str èŠå客æ·ç«¯åçæ°æ®'
| def safeToWriteData(self, data, command):
| if ((not self.transport.connected) or (data is None)):
return
senddata = self.factory.produceResult(data, command)
reactor.callFromThread(self.transport.write, senddata)
|
''
| def dataHandleCoroutine(self):
| length = self.factory.dataprotocl.getHeadlength()
while True:
data = (yield)
self.buff += data
while (self.buff.__len__() >= length):
unpackdata = self.factory.dataprotocl.unpack(self.buff[:length])
if (not unpackdata.get('result')):
log.msg('illegal data package --')
self.transport.loseConnection()
break
command = unpackdata.get('command')
rlength = unpackdata.get('length')
request = self.buff[length:(length + rlength)]
if (request.__len__() < rlength):
log.msg('some data lose')
break
self.buff = self.buff[(length + rlength):]
d = self.factory.doDataReceived(self, command, request)
if (not d):
continue
d.addCallback(self.safeToWriteData, command)
d.addErrback(DefferedErrorHandle)
|
'@param data: str 客æ·ç«¯äŒ éè¿æ¥çæ°æ®'
| def dataReceived(self, data):
| self.datahandler.send(data)
|
''
| def __init__(self, dataprotocl=DataPackProtoc()):
| self.service = None
self.connmanager = ConnectionManager()
self.dataprotocl = dataprotocl
|
''
| def setDataProtocl(self, dataprotocl):
| self.dataprotocl = dataprotocl
|
''
| def doConnectionMade(self, conn):
| pass
|
''
| def doConnectionLost(self, conn):
| pass
|
Subsets and Splits