repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CodeReclaimers/neat-python | neat/checkpoint.py | Checkpointer.save_checkpoint | def save_checkpoint(self, config, population, species_set, generation):
""" Save the current simulation state. """
filename = '{0}{1}'.format(self.filename_prefix, generation)
print("Saving checkpoint to {0}".format(filename))
with gzip.open(filename, 'w', compresslevel=5) as f:
data = (generation, config, population, species_set, random.getstate())
pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) | python | def save_checkpoint(self, config, population, species_set, generation):
""" Save the current simulation state. """
filename = '{0}{1}'.format(self.filename_prefix, generation)
print("Saving checkpoint to {0}".format(filename))
with gzip.open(filename, 'w', compresslevel=5) as f:
data = (generation, config, population, species_set, random.getstate())
pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) | [
"def",
"save_checkpoint",
"(",
"self",
",",
"config",
",",
"population",
",",
"species_set",
",",
"generation",
")",
":",
"filename",
"=",
"'{0}{1}'",
".",
"format",
"(",
"self",
".",
"filename_prefix",
",",
"generation",
")",
"print",
"(",
"\"Saving checkpoin... | Save the current simulation state. | [
"Save",
"the",
"current",
"simulation",
"state",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/checkpoint.py#L64-L71 | train | 215,100 |
CodeReclaimers/neat-python | neat/checkpoint.py | Checkpointer.restore_checkpoint | def restore_checkpoint(filename):
"""Resumes the simulation from a previous saved point."""
with gzip.open(filename) as f:
generation, config, population, species_set, rndstate = pickle.load(f)
random.setstate(rndstate)
return Population(config, (population, species_set, generation)) | python | def restore_checkpoint(filename):
"""Resumes the simulation from a previous saved point."""
with gzip.open(filename) as f:
generation, config, population, species_set, rndstate = pickle.load(f)
random.setstate(rndstate)
return Population(config, (population, species_set, generation)) | [
"def",
"restore_checkpoint",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"generation",
",",
"config",
",",
"population",
",",
"species_set",
",",
"rndstate",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"... | Resumes the simulation from a previous saved point. | [
"Resumes",
"the",
"simulation",
"from",
"a",
"previous",
"saved",
"point",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/checkpoint.py#L74-L79 | train | 215,101 |
CodeReclaimers/neat-python | neat/distributed.py | host_is_local | def host_is_local(hostname, port=22): # no port specified, just use the ssh port
"""
Returns True if the hostname points to the localhost, otherwise False.
"""
hostname = socket.getfqdn(hostname)
if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "1.0.0.127.in-addr.arpa",
"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"):
return True
localhost = socket.gethostname()
if hostname == localhost:
return True
localaddrs = socket.getaddrinfo(localhost, port)
targetaddrs = socket.getaddrinfo(hostname, port)
for (ignored_family, ignored_socktype, ignored_proto, ignored_canonname,
sockaddr) in localaddrs:
for (ignored_rfamily, ignored_rsocktype, ignored_rproto,
ignored_rcanonname, rsockaddr) in targetaddrs:
if rsockaddr[0] == sockaddr[0]:
return True
return False | python | def host_is_local(hostname, port=22): # no port specified, just use the ssh port
"""
Returns True if the hostname points to the localhost, otherwise False.
"""
hostname = socket.getfqdn(hostname)
if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "1.0.0.127.in-addr.arpa",
"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"):
return True
localhost = socket.gethostname()
if hostname == localhost:
return True
localaddrs = socket.getaddrinfo(localhost, port)
targetaddrs = socket.getaddrinfo(hostname, port)
for (ignored_family, ignored_socktype, ignored_proto, ignored_canonname,
sockaddr) in localaddrs:
for (ignored_rfamily, ignored_rsocktype, ignored_rproto,
ignored_rcanonname, rsockaddr) in targetaddrs:
if rsockaddr[0] == sockaddr[0]:
return True
return False | [
"def",
"host_is_local",
"(",
"hostname",
",",
"port",
"=",
"22",
")",
":",
"# no port specified, just use the ssh port",
"hostname",
"=",
"socket",
".",
"getfqdn",
"(",
"hostname",
")",
"if",
"hostname",
"in",
"(",
"\"localhost\"",
",",
"\"0.0.0.0\"",
",",
"\"12... | Returns True if the hostname points to the localhost, otherwise False. | [
"Returns",
"True",
"if",
"the",
"hostname",
"points",
"to",
"the",
"localhost",
"otherwise",
"False",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L105-L124 | train | 215,102 |
CodeReclaimers/neat-python | neat/distributed.py | _determine_mode | def _determine_mode(addr, mode):
"""
Returns the mode which should be used.
If mode is MODE_AUTO, this is determined by checking if 'addr' points to the
local host. If it does, return MODE_PRIMARY, else return MODE_SECONDARY.
If mode is either MODE_PRIMARY or MODE_SECONDARY,
return the 'mode' argument. Otherwise, a ValueError is raised.
"""
if isinstance(addr, tuple):
host = addr[0]
elif type(addr) == type(b"binary_string"):
host = addr
else:
raise TypeError("'addr' needs to be a tuple or an bytestring!")
if mode == MODE_AUTO:
if host_is_local(host):
return MODE_PRIMARY
return MODE_SECONDARY
elif mode in (MODE_SECONDARY, MODE_PRIMARY):
return mode
else:
raise ValueError("Invalid mode {!r}!".format(mode)) | python | def _determine_mode(addr, mode):
"""
Returns the mode which should be used.
If mode is MODE_AUTO, this is determined by checking if 'addr' points to the
local host. If it does, return MODE_PRIMARY, else return MODE_SECONDARY.
If mode is either MODE_PRIMARY or MODE_SECONDARY,
return the 'mode' argument. Otherwise, a ValueError is raised.
"""
if isinstance(addr, tuple):
host = addr[0]
elif type(addr) == type(b"binary_string"):
host = addr
else:
raise TypeError("'addr' needs to be a tuple or an bytestring!")
if mode == MODE_AUTO:
if host_is_local(host):
return MODE_PRIMARY
return MODE_SECONDARY
elif mode in (MODE_SECONDARY, MODE_PRIMARY):
return mode
else:
raise ValueError("Invalid mode {!r}!".format(mode)) | [
"def",
"_determine_mode",
"(",
"addr",
",",
"mode",
")",
":",
"if",
"isinstance",
"(",
"addr",
",",
"tuple",
")",
":",
"host",
"=",
"addr",
"[",
"0",
"]",
"elif",
"type",
"(",
"addr",
")",
"==",
"type",
"(",
"b\"binary_string\"",
")",
":",
"host",
... | Returns the mode which should be used.
If mode is MODE_AUTO, this is determined by checking if 'addr' points to the
local host. If it does, return MODE_PRIMARY, else return MODE_SECONDARY.
If mode is either MODE_PRIMARY or MODE_SECONDARY,
return the 'mode' argument. Otherwise, a ValueError is raised. | [
"Returns",
"the",
"mode",
"which",
"should",
"be",
"used",
".",
"If",
"mode",
"is",
"MODE_AUTO",
"this",
"is",
"determined",
"by",
"checking",
"if",
"addr",
"points",
"to",
"the",
"local",
"host",
".",
"If",
"it",
"does",
"return",
"MODE_PRIMARY",
"else",
... | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L127-L149 | train | 215,103 |
CodeReclaimers/neat-python | neat/distributed.py | chunked | def chunked(data, chunksize):
"""
Returns a list of chunks containing at most ``chunksize`` elements of data.
"""
if chunksize < 1:
raise ValueError("Chunksize must be at least 1!")
if int(chunksize) != chunksize:
raise ValueError("Chunksize needs to be an integer")
res = []
cur = []
for e in data:
cur.append(e)
if len(cur) >= chunksize:
res.append(cur)
cur = []
if cur:
res.append(cur)
return res | python | def chunked(data, chunksize):
"""
Returns a list of chunks containing at most ``chunksize`` elements of data.
"""
if chunksize < 1:
raise ValueError("Chunksize must be at least 1!")
if int(chunksize) != chunksize:
raise ValueError("Chunksize needs to be an integer")
res = []
cur = []
for e in data:
cur.append(e)
if len(cur) >= chunksize:
res.append(cur)
cur = []
if cur:
res.append(cur)
return res | [
"def",
"chunked",
"(",
"data",
",",
"chunksize",
")",
":",
"if",
"chunksize",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Chunksize must be at least 1!\"",
")",
"if",
"int",
"(",
"chunksize",
")",
"!=",
"chunksize",
":",
"raise",
"ValueError",
"(",
"\"Chun... | Returns a list of chunks containing at most ``chunksize`` elements of data. | [
"Returns",
"a",
"list",
"of",
"chunks",
"containing",
"at",
"most",
"chunksize",
"elements",
"of",
"data",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L152-L169 | train | 215,104 |
CodeReclaimers/neat-python | neat/distributed.py | _ExtendedManager.start | def start(self):
"""Starts or connects to the manager."""
if self.mode == MODE_PRIMARY:
i = self._start()
else:
i = self._connect()
self.manager = i | python | def start(self):
"""Starts or connects to the manager."""
if self.mode == MODE_PRIMARY:
i = self._start()
else:
i = self._connect()
self.manager = i | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"MODE_PRIMARY",
":",
"i",
"=",
"self",
".",
"_start",
"(",
")",
"else",
":",
"i",
"=",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"manager",
"=",
"i"
] | Starts or connects to the manager. | [
"Starts",
"or",
"connects",
"to",
"the",
"manager",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L195-L201 | train | 215,105 |
CodeReclaimers/neat-python | neat/distributed.py | _ExtendedManager.set_secondary_state | def set_secondary_state(self, value):
"""Sets the value for 'secondary_state'."""
if value not in (_STATE_RUNNING, _STATE_SHUTDOWN, _STATE_FORCED_SHUTDOWN):
raise ValueError(
"State {!r} is invalid - needs to be one of _STATE_RUNNING, _STATE_SHUTDOWN, or _STATE_FORCED_SHUTDOWN".format(
value)
)
if self.manager is None:
raise RuntimeError("Manager not started")
self.manager.set_state(value) | python | def set_secondary_state(self, value):
"""Sets the value for 'secondary_state'."""
if value not in (_STATE_RUNNING, _STATE_SHUTDOWN, _STATE_FORCED_SHUTDOWN):
raise ValueError(
"State {!r} is invalid - needs to be one of _STATE_RUNNING, _STATE_SHUTDOWN, or _STATE_FORCED_SHUTDOWN".format(
value)
)
if self.manager is None:
raise RuntimeError("Manager not started")
self.manager.set_state(value) | [
"def",
"set_secondary_state",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"(",
"_STATE_RUNNING",
",",
"_STATE_SHUTDOWN",
",",
"_STATE_FORCED_SHUTDOWN",
")",
":",
"raise",
"ValueError",
"(",
"\"State {!r} is invalid - needs to be one of _STATE_RUNNIN... | Sets the value for 'secondary_state'. | [
"Sets",
"the",
"value",
"for",
"secondary_state",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L207-L216 | train | 215,106 |
CodeReclaimers/neat-python | neat/distributed.py | _ExtendedManager._get_manager_class | def _get_manager_class(self, register_callables=False):
"""
Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments.
"""
class _EvaluatorSyncManager(managers.BaseManager):
"""
A custom BaseManager.
Please see the documentation of `multiprocessing` for more
information.
"""
pass
inqueue = queue.Queue()
outqueue = queue.Queue()
namespace = Namespace()
if register_callables:
_EvaluatorSyncManager.register(
"get_inqueue",
callable=lambda: inqueue,
)
_EvaluatorSyncManager.register(
"get_outqueue",
callable=lambda: outqueue,
)
_EvaluatorSyncManager.register(
"get_state",
callable=self._get_secondary_state,
)
_EvaluatorSyncManager.register(
"set_state",
callable=lambda v: self._secondary_state.set(v),
)
_EvaluatorSyncManager.register(
"get_namespace",
callable=lambda: namespace,
)
else:
_EvaluatorSyncManager.register(
"get_inqueue",
)
_EvaluatorSyncManager.register(
"get_outqueue",
)
_EvaluatorSyncManager.register(
"get_state",
)
_EvaluatorSyncManager.register(
"set_state",
)
_EvaluatorSyncManager.register(
"get_namespace",
)
return _EvaluatorSyncManager | python | def _get_manager_class(self, register_callables=False):
"""
Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments.
"""
class _EvaluatorSyncManager(managers.BaseManager):
"""
A custom BaseManager.
Please see the documentation of `multiprocessing` for more
information.
"""
pass
inqueue = queue.Queue()
outqueue = queue.Queue()
namespace = Namespace()
if register_callables:
_EvaluatorSyncManager.register(
"get_inqueue",
callable=lambda: inqueue,
)
_EvaluatorSyncManager.register(
"get_outqueue",
callable=lambda: outqueue,
)
_EvaluatorSyncManager.register(
"get_state",
callable=self._get_secondary_state,
)
_EvaluatorSyncManager.register(
"set_state",
callable=lambda v: self._secondary_state.set(v),
)
_EvaluatorSyncManager.register(
"get_namespace",
callable=lambda: namespace,
)
else:
_EvaluatorSyncManager.register(
"get_inqueue",
)
_EvaluatorSyncManager.register(
"get_outqueue",
)
_EvaluatorSyncManager.register(
"get_state",
)
_EvaluatorSyncManager.register(
"set_state",
)
_EvaluatorSyncManager.register(
"get_namespace",
)
return _EvaluatorSyncManager | [
"def",
"_get_manager_class",
"(",
"self",
",",
"register_callables",
"=",
"False",
")",
":",
"class",
"_EvaluatorSyncManager",
"(",
"managers",
".",
"BaseManager",
")",
":",
"\"\"\"\n A custom BaseManager.\n Please see the documentation of `multiprocessing` ... | Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments. | [
"Returns",
"a",
"new",
"Manager",
"subclass",
"with",
"registered",
"methods",
".",
"If",
"register_callable",
"is",
"True",
"defines",
"the",
"callable",
"arguments",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L225-L282 | train | 215,107 |
CodeReclaimers/neat-python | neat/distributed.py | _ExtendedManager._connect | def _connect(self):
"""Connects to the manager."""
cls = self._get_manager_class(register_callables=False)
ins = cls(address=self.addr, authkey=self.authkey)
ins.connect()
return ins | python | def _connect(self):
"""Connects to the manager."""
cls = self._get_manager_class(register_callables=False)
ins = cls(address=self.addr, authkey=self.authkey)
ins.connect()
return ins | [
"def",
"_connect",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"_get_manager_class",
"(",
"register_callables",
"=",
"False",
")",
"ins",
"=",
"cls",
"(",
"address",
"=",
"self",
".",
"addr",
",",
"authkey",
"=",
"self",
".",
"authkey",
")",
"ins",... | Connects to the manager. | [
"Connects",
"to",
"the",
"manager",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L284-L289 | train | 215,108 |
CodeReclaimers/neat-python | neat/distributed.py | _ExtendedManager._start | def _start(self):
"""Starts the manager."""
cls = self._get_manager_class(register_callables=True)
ins = cls(address=self.addr, authkey=self.authkey)
ins.start()
return ins | python | def _start(self):
"""Starts the manager."""
cls = self._get_manager_class(register_callables=True)
ins = cls(address=self.addr, authkey=self.authkey)
ins.start()
return ins | [
"def",
"_start",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"_get_manager_class",
"(",
"register_callables",
"=",
"True",
")",
"ins",
"=",
"cls",
"(",
"address",
"=",
"self",
".",
"addr",
",",
"authkey",
"=",
"self",
".",
"authkey",
")",
"ins",
... | Starts the manager. | [
"Starts",
"the",
"manager",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L291-L296 | train | 215,109 |
CodeReclaimers/neat-python | neat/distributed.py | DistributedEvaluator._start_primary | def _start_primary(self):
"""Start as the primary"""
self.em.start()
self.em.set_secondary_state(_STATE_RUNNING)
self._set_shared_instances() | python | def _start_primary(self):
"""Start as the primary"""
self.em.start()
self.em.set_secondary_state(_STATE_RUNNING)
self._set_shared_instances() | [
"def",
"_start_primary",
"(",
"self",
")",
":",
"self",
".",
"em",
".",
"start",
"(",
")",
"self",
".",
"em",
".",
"set_secondary_state",
"(",
"_STATE_RUNNING",
")",
"self",
".",
"_set_shared_instances",
"(",
")"
] | Start as the primary | [
"Start",
"as",
"the",
"primary"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L452-L456 | train | 215,110 |
CodeReclaimers/neat-python | neat/distributed.py | DistributedEvaluator._set_shared_instances | def _set_shared_instances(self):
"""Sets attributes from the shared instances."""
self.inqueue = self.em.get_inqueue()
self.outqueue = self.em.get_outqueue()
self.namespace = self.em.get_namespace() | python | def _set_shared_instances(self):
"""Sets attributes from the shared instances."""
self.inqueue = self.em.get_inqueue()
self.outqueue = self.em.get_outqueue()
self.namespace = self.em.get_namespace() | [
"def",
"_set_shared_instances",
"(",
"self",
")",
":",
"self",
".",
"inqueue",
"=",
"self",
".",
"em",
".",
"get_inqueue",
"(",
")",
"self",
".",
"outqueue",
"=",
"self",
".",
"em",
".",
"get_outqueue",
"(",
")",
"self",
".",
"namespace",
"=",
"self",
... | Sets attributes from the shared instances. | [
"Sets",
"attributes",
"from",
"the",
"shared",
"instances",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L463-L467 | train | 215,111 |
CodeReclaimers/neat-python | neat/distributed.py | DistributedEvaluator._reset_em | def _reset_em(self):
"""Resets self.em and the shared instances."""
self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False)
self.em.start()
self._set_shared_instances() | python | def _reset_em(self):
"""Resets self.em and the shared instances."""
self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False)
self.em.start()
self._set_shared_instances() | [
"def",
"_reset_em",
"(",
"self",
")",
":",
"self",
".",
"em",
"=",
"_ExtendedManager",
"(",
"self",
".",
"addr",
",",
"self",
".",
"authkey",
",",
"mode",
"=",
"self",
".",
"mode",
",",
"start",
"=",
"False",
")",
"self",
".",
"em",
".",
"start",
... | Resets self.em and the shared instances. | [
"Resets",
"self",
".",
"em",
"and",
"the",
"shared",
"instances",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L469-L473 | train | 215,112 |
CodeReclaimers/neat-python | neat/distributed.py | DistributedEvaluator._secondary_loop | def _secondary_loop(self, reconnect=False):
"""The worker loop for the secondary nodes."""
if self.num_workers > 1:
pool = multiprocessing.Pool(self.num_workers)
else:
pool = None
should_reconnect = True
while should_reconnect:
i = 0
running = True
try:
self._reset_em()
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
continue
while running:
i += 1
if i % 5 == 0:
# for better performance, only check every 5 cycles
try:
state = self.em.secondary_state
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
if not reconnect:
raise
else:
break
if state == _STATE_FORCED_SHUTDOWN:
running = False
should_reconnect = False
elif state == _STATE_SHUTDOWN:
running = False
if not running:
continue
try:
tasks = self.inqueue.get(block=True, timeout=0.2)
except queue.Empty:
continue
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
break
except (managers.RemoteError, multiprocessing.ProcessError) as e:
if ('Empty' in repr(e)) or ('TimeoutError' in repr(e)):
continue
if (('EOFError' in repr(e)) or ('PipeError' in repr(e)) or
('AuthenticationError' in repr(e))): # Second for Python 3.X, Third for 3.6+
break
raise
if pool is None:
res = []
for genome_id, genome, config in tasks:
fitness = self.eval_function(genome, config)
res.append((genome_id, fitness))
else:
genome_ids = []
jobs = []
for genome_id, genome, config in tasks:
genome_ids.append(genome_id)
jobs.append(
pool.apply_async(
self.eval_function, (genome, config)
)
)
results = [
job.get(timeout=self.worker_timeout) for job in jobs
]
res = zip(genome_ids, results)
try:
self.outqueue.put(res)
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
break
except (managers.RemoteError, multiprocessing.ProcessError) as e:
if ('Empty' in repr(e)) or ('TimeoutError' in repr(e)):
continue
if (('EOFError' in repr(e)) or ('PipeError' in repr(e)) or
('AuthenticationError' in repr(e))): # Second for Python 3.X, Third for 3.6+
break
raise
if not reconnect:
should_reconnect = False
break
if pool is not None:
pool.terminate() | python | def _secondary_loop(self, reconnect=False):
"""The worker loop for the secondary nodes."""
if self.num_workers > 1:
pool = multiprocessing.Pool(self.num_workers)
else:
pool = None
should_reconnect = True
while should_reconnect:
i = 0
running = True
try:
self._reset_em()
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
continue
while running:
i += 1
if i % 5 == 0:
# for better performance, only check every 5 cycles
try:
state = self.em.secondary_state
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
if not reconnect:
raise
else:
break
if state == _STATE_FORCED_SHUTDOWN:
running = False
should_reconnect = False
elif state == _STATE_SHUTDOWN:
running = False
if not running:
continue
try:
tasks = self.inqueue.get(block=True, timeout=0.2)
except queue.Empty:
continue
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
break
except (managers.RemoteError, multiprocessing.ProcessError) as e:
if ('Empty' in repr(e)) or ('TimeoutError' in repr(e)):
continue
if (('EOFError' in repr(e)) or ('PipeError' in repr(e)) or
('AuthenticationError' in repr(e))): # Second for Python 3.X, Third for 3.6+
break
raise
if pool is None:
res = []
for genome_id, genome, config in tasks:
fitness = self.eval_function(genome, config)
res.append((genome_id, fitness))
else:
genome_ids = []
jobs = []
for genome_id, genome, config in tasks:
genome_ids.append(genome_id)
jobs.append(
pool.apply_async(
self.eval_function, (genome, config)
)
)
results = [
job.get(timeout=self.worker_timeout) for job in jobs
]
res = zip(genome_ids, results)
try:
self.outqueue.put(res)
except (socket.error, EOFError, IOError, OSError, socket.gaierror, TypeError):
break
except (managers.RemoteError, multiprocessing.ProcessError) as e:
if ('Empty' in repr(e)) or ('TimeoutError' in repr(e)):
continue
if (('EOFError' in repr(e)) or ('PipeError' in repr(e)) or
('AuthenticationError' in repr(e))): # Second for Python 3.X, Third for 3.6+
break
raise
if not reconnect:
should_reconnect = False
break
if pool is not None:
pool.terminate() | [
"def",
"_secondary_loop",
"(",
"self",
",",
"reconnect",
"=",
"False",
")",
":",
"if",
"self",
".",
"num_workers",
">",
"1",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"self",
".",
"num_workers",
")",
"else",
":",
"pool",
"=",
"None",
"shou... | The worker loop for the secondary nodes. | [
"The",
"worker",
"loop",
"for",
"the",
"secondary",
"nodes",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L475-L555 | train | 215,113 |
CodeReclaimers/neat-python | neat/distributed.py | DistributedEvaluator.evaluate | def evaluate(self, genomes, config):
"""
Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode.
"""
if self.mode != MODE_PRIMARY:
raise ModeError("Not in primary mode!")
tasks = [(genome_id, genome, config) for genome_id, genome in genomes]
id2genome = {genome_id: genome for genome_id, genome in genomes}
tasks = chunked(tasks, self.secondary_chunksize)
n_tasks = len(tasks)
for task in tasks:
self.inqueue.put(task)
tresults = []
while len(tresults) < n_tasks:
try:
sr = self.outqueue.get(block=True, timeout=0.2)
except (queue.Empty, managers.RemoteError):
continue
tresults.append(sr)
results = []
for sr in tresults:
results += sr
for genome_id, fitness in results:
genome = id2genome[genome_id]
genome.fitness = fitness | python | def evaluate(self, genomes, config):
"""
Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode.
"""
if self.mode != MODE_PRIMARY:
raise ModeError("Not in primary mode!")
tasks = [(genome_id, genome, config) for genome_id, genome in genomes]
id2genome = {genome_id: genome for genome_id, genome in genomes}
tasks = chunked(tasks, self.secondary_chunksize)
n_tasks = len(tasks)
for task in tasks:
self.inqueue.put(task)
tresults = []
while len(tresults) < n_tasks:
try:
sr = self.outqueue.get(block=True, timeout=0.2)
except (queue.Empty, managers.RemoteError):
continue
tresults.append(sr)
results = []
for sr in tresults:
results += sr
for genome_id, fitness in results:
genome = id2genome[genome_id]
genome.fitness = fitness | [
"def",
"evaluate",
"(",
"self",
",",
"genomes",
",",
"config",
")",
":",
"if",
"self",
".",
"mode",
"!=",
"MODE_PRIMARY",
":",
"raise",
"ModeError",
"(",
"\"Not in primary mode!\"",
")",
"tasks",
"=",
"[",
"(",
"genome_id",
",",
"genome",
",",
"config",
... | Evaluates the genomes.
This method raises a ModeError if the
DistributedEvaluator is not in primary mode. | [
"Evaluates",
"the",
"genomes",
".",
"This",
"method",
"raises",
"a",
"ModeError",
"if",
"the",
"DistributedEvaluator",
"is",
"not",
"in",
"primary",
"mode",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/distributed.py#L557-L583 | train | 215,114 |
CodeReclaimers/neat-python | neat/reproduction.py | DefaultReproduction.reproduce | def reproduce(self, config, species, pop_size, generation):
"""
Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents.
"""
# TODO: I don't like this modification of the species and stagnation objects,
# because it requires internal knowledge of the objects.
# Filter out stagnated species, collect the set of non-stagnated
# species members, and compute their average adjusted fitness.
# The average adjusted fitness scheme (normalized to the interval
# [0, 1]) allows the use of negative fitness values without
# interfering with the shared fitness scheme.
all_fitnesses = []
remaining_species = []
for stag_sid, stag_s, stagnant in self.stagnation.update(species, generation):
if stagnant:
self.reporters.species_stagnant(stag_sid, stag_s)
else:
all_fitnesses.extend(m.fitness for m in itervalues(stag_s.members))
remaining_species.append(stag_s)
# The above comment was not quite what was happening - now getting fitnesses
# only from members of non-stagnated species.
# No species left.
if not remaining_species:
species.species = {}
return {} # was []
# Find minimum/maximum fitness across the entire population, for use in
# species adjusted fitness computation.
min_fitness = min(all_fitnesses)
max_fitness = max(all_fitnesses)
# Do not allow the fitness range to be zero, as we divide by it below.
# TODO: The ``1.0`` below is rather arbitrary, and should be configurable.
fitness_range = max(1.0, max_fitness - min_fitness)
for afs in remaining_species:
# Compute adjusted fitness.
msf = mean([m.fitness for m in itervalues(afs.members)])
af = (msf - min_fitness) / fitness_range
afs.adjusted_fitness = af
adjusted_fitnesses = [s.adjusted_fitness for s in remaining_species]
avg_adjusted_fitness = mean(adjusted_fitnesses) # type: float
self.reporters.info("Average adjusted fitness: {:.3f}".format(avg_adjusted_fitness))
# Compute the number of new members for each species in the new generation.
previous_sizes = [len(s.members) for s in remaining_species]
min_species_size = self.reproduction_config.min_species_size
# Isn't the effective min_species_size going to be max(min_species_size,
# self.reproduction_config.elitism)? That would probably produce more accurate tracking
# of population sizes and relative fitnesses... doing. TODO: document.
min_species_size = max(min_species_size,self.reproduction_config.elitism)
spawn_amounts = self.compute_spawn(adjusted_fitnesses, previous_sizes,
pop_size, min_species_size)
new_population = {}
species.species = {}
for spawn, s in zip(spawn_amounts, remaining_species):
# If elitism is enabled, each species always at least gets to retain its elites.
spawn = max(spawn, self.reproduction_config.elitism)
assert spawn > 0
# The species has at least one member for the next generation, so retain it.
old_members = list(iteritems(s.members))
s.members = {}
species.species[s.key] = s
# Sort members in order of descending fitness.
old_members.sort(reverse=True, key=lambda x: x[1].fitness)
# Transfer elites to new generation.
if self.reproduction_config.elitism > 0:
for i, m in old_members[:self.reproduction_config.elitism]:
new_population[i] = m
spawn -= 1
if spawn <= 0:
continue
# Only use the survival threshold fraction to use as parents for the next generation.
repro_cutoff = int(math.ceil(self.reproduction_config.survival_threshold *
len(old_members)))
# Use at least two parents no matter what the threshold fraction result is.
repro_cutoff = max(repro_cutoff, 2)
old_members = old_members[:repro_cutoff]
# Randomly choose parents and produce the number of offspring allotted to the species.
while spawn > 0:
spawn -= 1
parent1_id, parent1 = random.choice(old_members)
parent2_id, parent2 = random.choice(old_members)
# Note that if the parents are not distinct, crossover will produce a
# genetically identical clone of the parent (but with a different ID).
gid = next(self.genome_indexer)
child = config.genome_type(gid)
child.configure_crossover(parent1, parent2, config.genome_config)
child.mutate(config.genome_config)
new_population[gid] = child
self.ancestors[gid] = (parent1_id, parent2_id)
return new_population | python | def reproduce(self, config, species, pop_size, generation):
"""
Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents.
"""
# TODO: I don't like this modification of the species and stagnation objects,
# because it requires internal knowledge of the objects.
# Filter out stagnated species, collect the set of non-stagnated
# species members, and compute their average adjusted fitness.
# The average adjusted fitness scheme (normalized to the interval
# [0, 1]) allows the use of negative fitness values without
# interfering with the shared fitness scheme.
all_fitnesses = []
remaining_species = []
for stag_sid, stag_s, stagnant in self.stagnation.update(species, generation):
if stagnant:
self.reporters.species_stagnant(stag_sid, stag_s)
else:
all_fitnesses.extend(m.fitness for m in itervalues(stag_s.members))
remaining_species.append(stag_s)
# The above comment was not quite what was happening - now getting fitnesses
# only from members of non-stagnated species.
# No species left.
if not remaining_species:
species.species = {}
return {} # was []
# Find minimum/maximum fitness across the entire population, for use in
# species adjusted fitness computation.
min_fitness = min(all_fitnesses)
max_fitness = max(all_fitnesses)
# Do not allow the fitness range to be zero, as we divide by it below.
# TODO: The ``1.0`` below is rather arbitrary, and should be configurable.
fitness_range = max(1.0, max_fitness - min_fitness)
for afs in remaining_species:
# Compute adjusted fitness.
msf = mean([m.fitness for m in itervalues(afs.members)])
af = (msf - min_fitness) / fitness_range
afs.adjusted_fitness = af
adjusted_fitnesses = [s.adjusted_fitness for s in remaining_species]
avg_adjusted_fitness = mean(adjusted_fitnesses) # type: float
self.reporters.info("Average adjusted fitness: {:.3f}".format(avg_adjusted_fitness))
# Compute the number of new members for each species in the new generation.
previous_sizes = [len(s.members) for s in remaining_species]
min_species_size = self.reproduction_config.min_species_size
# Isn't the effective min_species_size going to be max(min_species_size,
# self.reproduction_config.elitism)? That would probably produce more accurate tracking
# of population sizes and relative fitnesses... doing. TODO: document.
min_species_size = max(min_species_size,self.reproduction_config.elitism)
spawn_amounts = self.compute_spawn(adjusted_fitnesses, previous_sizes,
pop_size, min_species_size)
new_population = {}
species.species = {}
for spawn, s in zip(spawn_amounts, remaining_species):
# If elitism is enabled, each species always at least gets to retain its elites.
spawn = max(spawn, self.reproduction_config.elitism)
assert spawn > 0
# The species has at least one member for the next generation, so retain it.
old_members = list(iteritems(s.members))
s.members = {}
species.species[s.key] = s
# Sort members in order of descending fitness.
old_members.sort(reverse=True, key=lambda x: x[1].fitness)
# Transfer elites to new generation.
if self.reproduction_config.elitism > 0:
for i, m in old_members[:self.reproduction_config.elitism]:
new_population[i] = m
spawn -= 1
if spawn <= 0:
continue
# Only use the survival threshold fraction to use as parents for the next generation.
repro_cutoff = int(math.ceil(self.reproduction_config.survival_threshold *
len(old_members)))
# Use at least two parents no matter what the threshold fraction result is.
repro_cutoff = max(repro_cutoff, 2)
old_members = old_members[:repro_cutoff]
# Randomly choose parents and produce the number of offspring allotted to the species.
while spawn > 0:
spawn -= 1
parent1_id, parent1 = random.choice(old_members)
parent2_id, parent2 = random.choice(old_members)
# Note that if the parents are not distinct, crossover will produce a
# genetically identical clone of the parent (but with a different ID).
gid = next(self.genome_indexer)
child = config.genome_type(gid)
child.configure_crossover(parent1, parent2, config.genome_config)
child.mutate(config.genome_config)
new_population[gid] = child
self.ancestors[gid] = (parent1_id, parent2_id)
return new_population | [
"def",
"reproduce",
"(",
"self",
",",
"config",
",",
"species",
",",
"pop_size",
",",
"generation",
")",
":",
"# TODO: I don't like this modification of the species and stagnation objects,",
"# because it requires internal knowledge of the objects.",
"# Filter out stagnated species, ... | Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents. | [
"Handles",
"creation",
"of",
"genomes",
"either",
"from",
"scratch",
"or",
"by",
"sexual",
"or",
"asexual",
"reproduction",
"from",
"parents",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/reproduction.py#L84-L188 | train | 215,115 |
CodeReclaimers/neat-python | neat/population.py | Population.run | def run(self, fitness_function, n=None):
"""
Runs NEAT's genetic algorithm for at most n generations. If n
is None, run until solution is found or extinction occurs.
The user-provided fitness_function must take only two arguments:
1. The population as a list of (genome id, genome) tuples.
2. The current configuration object.
The return value of the fitness function is ignored, but it must assign
a Python float to the `fitness` member of each genome.
The fitness function is free to maintain external state, perform
evaluations in parallel, etc.
It is assumed that fitness_function does not modify the list of genomes,
the genomes themselves (apart from updating the fitness member),
or the configuration object.
"""
if self.config.no_fitness_termination and (n is None):
raise RuntimeError("Cannot have no generational limit with no fitness termination")
k = 0
while n is None or k < n:
k += 1
self.reporters.start_generation(self.generation)
# Evaluate all genomes using the user-provided function.
fitness_function(list(iteritems(self.population)), self.config)
# Gather and report statistics.
best = None
for g in itervalues(self.population):
if best is None or g.fitness > best.fitness:
best = g
self.reporters.post_evaluate(self.config, self.population, self.species, best)
# Track the best genome ever seen.
if self.best_genome is None or best.fitness > self.best_genome.fitness:
self.best_genome = best
if not self.config.no_fitness_termination:
# End if the fitness threshold is reached.
fv = self.fitness_criterion(g.fitness for g in itervalues(self.population))
if fv >= self.config.fitness_threshold:
self.reporters.found_solution(self.config, self.generation, best)
break
# Create the next generation from the current generation.
self.population = self.reproduction.reproduce(self.config, self.species,
self.config.pop_size, self.generation)
# Check for complete extinction.
if not self.species.species:
self.reporters.complete_extinction()
# If requested by the user, create a completely new population,
# otherwise raise an exception.
if self.config.reset_on_extinction:
self.population = self.reproduction.create_new(self.config.genome_type,
self.config.genome_config,
self.config.pop_size)
else:
raise CompleteExtinctionException()
# Divide the new population into species.
self.species.speciate(self.config, self.population, self.generation)
self.reporters.end_generation(self.config, self.population, self.species)
self.generation += 1
if self.config.no_fitness_termination:
self.reporters.found_solution(self.config, self.generation, self.best_genome)
return self.best_genome | python | def run(self, fitness_function, n=None):
"""
Runs NEAT's genetic algorithm for at most n generations. If n
is None, run until solution is found or extinction occurs.
The user-provided fitness_function must take only two arguments:
1. The population as a list of (genome id, genome) tuples.
2. The current configuration object.
The return value of the fitness function is ignored, but it must assign
a Python float to the `fitness` member of each genome.
The fitness function is free to maintain external state, perform
evaluations in parallel, etc.
It is assumed that fitness_function does not modify the list of genomes,
the genomes themselves (apart from updating the fitness member),
or the configuration object.
"""
if self.config.no_fitness_termination and (n is None):
raise RuntimeError("Cannot have no generational limit with no fitness termination")
k = 0
while n is None or k < n:
k += 1
self.reporters.start_generation(self.generation)
# Evaluate all genomes using the user-provided function.
fitness_function(list(iteritems(self.population)), self.config)
# Gather and report statistics.
best = None
for g in itervalues(self.population):
if best is None or g.fitness > best.fitness:
best = g
self.reporters.post_evaluate(self.config, self.population, self.species, best)
# Track the best genome ever seen.
if self.best_genome is None or best.fitness > self.best_genome.fitness:
self.best_genome = best
if not self.config.no_fitness_termination:
# End if the fitness threshold is reached.
fv = self.fitness_criterion(g.fitness for g in itervalues(self.population))
if fv >= self.config.fitness_threshold:
self.reporters.found_solution(self.config, self.generation, best)
break
# Create the next generation from the current generation.
self.population = self.reproduction.reproduce(self.config, self.species,
self.config.pop_size, self.generation)
# Check for complete extinction.
if not self.species.species:
self.reporters.complete_extinction()
# If requested by the user, create a completely new population,
# otherwise raise an exception.
if self.config.reset_on_extinction:
self.population = self.reproduction.create_new(self.config.genome_type,
self.config.genome_config,
self.config.pop_size)
else:
raise CompleteExtinctionException()
# Divide the new population into species.
self.species.speciate(self.config, self.population, self.generation)
self.reporters.end_generation(self.config, self.population, self.species)
self.generation += 1
if self.config.no_fitness_termination:
self.reporters.found_solution(self.config, self.generation, self.best_genome)
return self.best_genome | [
"def",
"run",
"(",
"self",
",",
"fitness_function",
",",
"n",
"=",
"None",
")",
":",
"if",
"self",
".",
"config",
".",
"no_fitness_termination",
"and",
"(",
"n",
"is",
"None",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot have no generational limit with no... | Runs NEAT's genetic algorithm for at most n generations. If n
is None, run until solution is found or extinction occurs.
The user-provided fitness_function must take only two arguments:
1. The population as a list of (genome id, genome) tuples.
2. The current configuration object.
The return value of the fitness function is ignored, but it must assign
a Python float to the `fitness` member of each genome.
The fitness function is free to maintain external state, perform
evaluations in parallel, etc.
It is assumed that fitness_function does not modify the list of genomes,
the genomes themselves (apart from updating the fitness member),
or the configuration object. | [
"Runs",
"NEAT",
"s",
"genetic",
"algorithm",
"for",
"at",
"most",
"n",
"generations",
".",
"If",
"n",
"is",
"None",
"run",
"until",
"solution",
"is",
"found",
"or",
"extinction",
"occurs",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/population.py#L59-L136 | train | 215,116 |
CodeReclaimers/neat-python | neat/genes.py | BaseGene.crossover | def crossover(self, gene2):
""" Creates a new gene randomly inheriting attributes from its parents."""
assert self.key == gene2.key
# Note: we use "a if random() > 0.5 else b" instead of choice((a, b))
# here because `choice` is substantially slower.
new_gene = self.__class__(self.key)
for a in self._gene_attributes:
if random() > 0.5:
setattr(new_gene, a.name, getattr(self, a.name))
else:
setattr(new_gene, a.name, getattr(gene2, a.name))
return new_gene | python | def crossover(self, gene2):
""" Creates a new gene randomly inheriting attributes from its parents."""
assert self.key == gene2.key
# Note: we use "a if random() > 0.5 else b" instead of choice((a, b))
# here because `choice` is substantially slower.
new_gene = self.__class__(self.key)
for a in self._gene_attributes:
if random() > 0.5:
setattr(new_gene, a.name, getattr(self, a.name))
else:
setattr(new_gene, a.name, getattr(gene2, a.name))
return new_gene | [
"def",
"crossover",
"(",
"self",
",",
"gene2",
")",
":",
"assert",
"self",
".",
"key",
"==",
"gene2",
".",
"key",
"# Note: we use \"a if random() > 0.5 else b\" instead of choice((a, b))",
"# here because `choice` is substantially slower.",
"new_gene",
"=",
"self",
".",
"... | Creates a new gene randomly inheriting attributes from its parents. | [
"Creates",
"a",
"new",
"gene",
"randomly",
"inheriting",
"attributes",
"from",
"its",
"parents",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genes.py#L60-L73 | train | 215,117 |
CodeReclaimers/neat-python | examples/circuits/evolve.py | CircuitGenome.distance | def distance(self, other, config):
"""
Returns the genetic distance between this genome and the other. This distance value
is used to compute genome compatibility for speciation.
"""
# Compute node gene distance component.
node_distance = 0.0
if self.nodes or other.nodes:
disjoint_nodes = 0
for k2 in iterkeys(other.nodes):
if k2 not in self.nodes:
disjoint_nodes += 1
for k1, n1 in iteritems(self.nodes):
n2 = other.nodes.get(k1)
if n2 is None:
disjoint_nodes += 1
else:
# Homologous genes compute their own distance value.
node_distance += n1.distance(n2, config)
max_nodes = max(len(self.nodes), len(other.nodes))
node_distance = (node_distance + config.compatibility_disjoint_coefficient * disjoint_nodes) / max_nodes
# Compute connection gene differences.
connection_distance = 0.0
if self.connections or other.connections:
disjoint_connections = 0
for k2 in iterkeys(other.connections):
if k2 not in self.connections:
disjoint_connections += 1
for k1, c1 in iteritems(self.connections):
c2 = other.connections.get(k1)
if c2 is None:
disjoint_connections += 1
else:
# Homologous genes compute their own distance value.
connection_distance += c1.distance(c2, config)
max_conn = max(len(self.connections), len(other.connections))
connection_distance = (connection_distance + config.compatibility_disjoint_coefficient * disjoint_connections) / max_conn
distance = node_distance + connection_distance
return distance | python | def distance(self, other, config):
"""
Returns the genetic distance between this genome and the other. This distance value
is used to compute genome compatibility for speciation.
"""
# Compute node gene distance component.
node_distance = 0.0
if self.nodes or other.nodes:
disjoint_nodes = 0
for k2 in iterkeys(other.nodes):
if k2 not in self.nodes:
disjoint_nodes += 1
for k1, n1 in iteritems(self.nodes):
n2 = other.nodes.get(k1)
if n2 is None:
disjoint_nodes += 1
else:
# Homologous genes compute their own distance value.
node_distance += n1.distance(n2, config)
max_nodes = max(len(self.nodes), len(other.nodes))
node_distance = (node_distance + config.compatibility_disjoint_coefficient * disjoint_nodes) / max_nodes
# Compute connection gene differences.
connection_distance = 0.0
if self.connections or other.connections:
disjoint_connections = 0
for k2 in iterkeys(other.connections):
if k2 not in self.connections:
disjoint_connections += 1
for k1, c1 in iteritems(self.connections):
c2 = other.connections.get(k1)
if c2 is None:
disjoint_connections += 1
else:
# Homologous genes compute their own distance value.
connection_distance += c1.distance(c2, config)
max_conn = max(len(self.connections), len(other.connections))
connection_distance = (connection_distance + config.compatibility_disjoint_coefficient * disjoint_connections) / max_conn
distance = node_distance + connection_distance
return distance | [
"def",
"distance",
"(",
"self",
",",
"other",
",",
"config",
")",
":",
"# Compute node gene distance component.",
"node_distance",
"=",
"0.0",
"if",
"self",
".",
"nodes",
"or",
"other",
".",
"nodes",
":",
"disjoint_nodes",
"=",
"0",
"for",
"k2",
"in",
"iterk... | Returns the genetic distance between this genome and the other. This distance value
is used to compute genome compatibility for speciation. | [
"Returns",
"the",
"genetic",
"distance",
"between",
"this",
"genome",
"and",
"the",
"other",
".",
"This",
"distance",
"value",
"is",
"used",
"to",
"compute",
"genome",
"compatibility",
"for",
"speciation",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/circuits/evolve.py#L227-L273 | train | 215,118 |
CodeReclaimers/neat-python | neat/ctrnn/__init__.py | CTRNN.advance | def advance(self, inputs, advance_time, time_step=None):
"""
Advance the simulation by the given amount of time, assuming that inputs are
constant at the given values during the simulated time.
"""
final_time_seconds = self.time_seconds + advance_time
# Use half of the max allowed time step if none is given.
if time_step is None: # pragma: no cover
time_step = 0.5 * self.get_max_time_step()
if len(self.input_nodes) != len(inputs):
raise RuntimeError("Expected {0} inputs, got {1}".format(len(self.input_nodes), len(inputs)))
while self.time_seconds < final_time_seconds:
dt = min(time_step, final_time_seconds - self.time_seconds)
ivalues = self.values[self.active]
ovalues = self.values[1 - self.active]
self.active = 1 - self.active
for i, v in zip(self.input_nodes, inputs):
ivalues[i] = v
ovalues[i] = v
for node_key, ne in iteritems(self.node_evals):
node_inputs = [ivalues[i] * w for i, w in ne.links]
s = ne.aggregation(node_inputs)
z = ne.activation(ne.bias + ne.response * s)
ovalues[node_key] += dt / ne.time_constant * (-ovalues[node_key] + z)
self.time_seconds += dt
ovalues = self.values[1 - self.active]
return [ovalues[i] for i in self.output_nodes] | python | def advance(self, inputs, advance_time, time_step=None):
"""
Advance the simulation by the given amount of time, assuming that inputs are
constant at the given values during the simulated time.
"""
final_time_seconds = self.time_seconds + advance_time
# Use half of the max allowed time step if none is given.
if time_step is None: # pragma: no cover
time_step = 0.5 * self.get_max_time_step()
if len(self.input_nodes) != len(inputs):
raise RuntimeError("Expected {0} inputs, got {1}".format(len(self.input_nodes), len(inputs)))
while self.time_seconds < final_time_seconds:
dt = min(time_step, final_time_seconds - self.time_seconds)
ivalues = self.values[self.active]
ovalues = self.values[1 - self.active]
self.active = 1 - self.active
for i, v in zip(self.input_nodes, inputs):
ivalues[i] = v
ovalues[i] = v
for node_key, ne in iteritems(self.node_evals):
node_inputs = [ivalues[i] * w for i, w in ne.links]
s = ne.aggregation(node_inputs)
z = ne.activation(ne.bias + ne.response * s)
ovalues[node_key] += dt / ne.time_constant * (-ovalues[node_key] + z)
self.time_seconds += dt
ovalues = self.values[1 - self.active]
return [ovalues[i] for i in self.output_nodes] | [
"def",
"advance",
"(",
"self",
",",
"inputs",
",",
"advance_time",
",",
"time_step",
"=",
"None",
")",
":",
"final_time_seconds",
"=",
"self",
".",
"time_seconds",
"+",
"advance_time",
"# Use half of the max allowed time step if none is given.",
"if",
"time_step",
"is... | Advance the simulation by the given amount of time, assuming that inputs are
constant at the given values during the simulated time. | [
"Advance",
"the",
"simulation",
"by",
"the",
"given",
"amount",
"of",
"time",
"assuming",
"that",
"inputs",
"are",
"constant",
"at",
"the",
"given",
"values",
"during",
"the",
"simulated",
"time",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/ctrnn/__init__.py#L53-L87 | train | 215,119 |
CodeReclaimers/neat-python | neat/stagnation.py | DefaultStagnation.update | def update(self, species_set, generation):
"""
Required interface method. Updates species fitness history information,
checking for ones that have not improved in max_stagnation generations,
and - unless it would result in the number of species dropping below the configured
species_elitism parameter if they were removed,
in which case the highest-fitness species are spared -
returns a list with stagnant species marked for removal.
"""
species_data = []
for sid, s in iteritems(species_set.species):
if s.fitness_history:
prev_fitness = max(s.fitness_history)
else:
prev_fitness = -sys.float_info.max
s.fitness = self.species_fitness_func(s.get_fitnesses())
s.fitness_history.append(s.fitness)
s.adjusted_fitness = None
if prev_fitness is None or s.fitness > prev_fitness:
s.last_improved = generation
species_data.append((sid, s))
# Sort in ascending fitness order.
species_data.sort(key=lambda x: x[1].fitness)
result = []
species_fitnesses = []
num_non_stagnant = len(species_data)
for idx, (sid, s) in enumerate(species_data):
# Override stagnant state if marking this species as stagnant would
# result in the total number of species dropping below the limit.
# Because species are in ascending fitness order, less fit species
# will be marked as stagnant first.
stagnant_time = generation - s.last_improved
is_stagnant = False
if num_non_stagnant > self.stagnation_config.species_elitism:
is_stagnant = stagnant_time >= self.stagnation_config.max_stagnation
if (len(species_data) - idx) <= self.stagnation_config.species_elitism:
is_stagnant = False
if is_stagnant:
num_non_stagnant -= 1
result.append((sid, s, is_stagnant))
species_fitnesses.append(s.fitness)
return result | python | def update(self, species_set, generation):
"""
Required interface method. Updates species fitness history information,
checking for ones that have not improved in max_stagnation generations,
and - unless it would result in the number of species dropping below the configured
species_elitism parameter if they were removed,
in which case the highest-fitness species are spared -
returns a list with stagnant species marked for removal.
"""
species_data = []
for sid, s in iteritems(species_set.species):
if s.fitness_history:
prev_fitness = max(s.fitness_history)
else:
prev_fitness = -sys.float_info.max
s.fitness = self.species_fitness_func(s.get_fitnesses())
s.fitness_history.append(s.fitness)
s.adjusted_fitness = None
if prev_fitness is None or s.fitness > prev_fitness:
s.last_improved = generation
species_data.append((sid, s))
# Sort in ascending fitness order.
species_data.sort(key=lambda x: x[1].fitness)
result = []
species_fitnesses = []
num_non_stagnant = len(species_data)
for idx, (sid, s) in enumerate(species_data):
# Override stagnant state if marking this species as stagnant would
# result in the total number of species dropping below the limit.
# Because species are in ascending fitness order, less fit species
# will be marked as stagnant first.
stagnant_time = generation - s.last_improved
is_stagnant = False
if num_non_stagnant > self.stagnation_config.species_elitism:
is_stagnant = stagnant_time >= self.stagnation_config.max_stagnation
if (len(species_data) - idx) <= self.stagnation_config.species_elitism:
is_stagnant = False
if is_stagnant:
num_non_stagnant -= 1
result.append((sid, s, is_stagnant))
species_fitnesses.append(s.fitness)
return result | [
"def",
"update",
"(",
"self",
",",
"species_set",
",",
"generation",
")",
":",
"species_data",
"=",
"[",
"]",
"for",
"sid",
",",
"s",
"in",
"iteritems",
"(",
"species_set",
".",
"species",
")",
":",
"if",
"s",
".",
"fitness_history",
":",
"prev_fitness",... | Required interface method. Updates species fitness history information,
checking for ones that have not improved in max_stagnation generations,
and - unless it would result in the number of species dropping below the configured
species_elitism parameter if they were removed,
in which case the highest-fitness species are spared -
returns a list with stagnant species marked for removal. | [
"Required",
"interface",
"method",
".",
"Updates",
"species",
"fitness",
"history",
"information",
"checking",
"for",
"ones",
"that",
"have",
"not",
"improved",
"in",
"max_stagnation",
"generations",
"and",
"-",
"unless",
"it",
"would",
"result",
"in",
"the",
"n... | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/stagnation.py#L30-L79 | train | 215,120 |
CodeReclaimers/neat-python | neat/threaded.py | ThreadedEvaluator.start | def start(self):
"""Starts the worker threads"""
if self.working:
return
self.working = True
for i in range(self.num_workers):
w = threading.Thread(
name="Worker Thread #{i}".format(i=i),
target=self._worker,
)
w.daemon = True
w.start()
self.workers.append(w) | python | def start(self):
"""Starts the worker threads"""
if self.working:
return
self.working = True
for i in range(self.num_workers):
w = threading.Thread(
name="Worker Thread #{i}".format(i=i),
target=self._worker,
)
w.daemon = True
w.start()
self.workers.append(w) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"working",
":",
"return",
"self",
".",
"working",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_workers",
")",
":",
"w",
"=",
"threading",
".",
"Thread",
"(",
"name",
"=",
... | Starts the worker threads | [
"Starts",
"the",
"worker",
"threads"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/threaded.py#L51-L63 | train | 215,121 |
CodeReclaimers/neat-python | neat/threaded.py | ThreadedEvaluator.stop | def stop(self):
"""Stops the worker threads and waits for them to finish"""
self.working = False
for w in self.workers:
w.join()
self.workers = [] | python | def stop(self):
"""Stops the worker threads and waits for them to finish"""
self.working = False
for w in self.workers:
w.join()
self.workers = [] | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"working",
"=",
"False",
"for",
"w",
"in",
"self",
".",
"workers",
":",
"w",
".",
"join",
"(",
")",
"self",
".",
"workers",
"=",
"[",
"]"
] | Stops the worker threads and waits for them to finish | [
"Stops",
"the",
"worker",
"threads",
"and",
"waits",
"for",
"them",
"to",
"finish"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/threaded.py#L65-L70 | train | 215,122 |
CodeReclaimers/neat-python | neat/threaded.py | ThreadedEvaluator._worker | def _worker(self):
"""The worker function"""
while self.working:
try:
genome_id, genome, config = self.inqueue.get(
block=True,
timeout=0.2,
)
except queue.Empty:
continue
f = self.eval_function(genome, config)
self.outqueue.put((genome_id, genome, f)) | python | def _worker(self):
"""The worker function"""
while self.working:
try:
genome_id, genome, config = self.inqueue.get(
block=True,
timeout=0.2,
)
except queue.Empty:
continue
f = self.eval_function(genome, config)
self.outqueue.put((genome_id, genome, f)) | [
"def",
"_worker",
"(",
"self",
")",
":",
"while",
"self",
".",
"working",
":",
"try",
":",
"genome_id",
",",
"genome",
",",
"config",
"=",
"self",
".",
"inqueue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"0.2",
",",
")",
"except"... | The worker function | [
"The",
"worker",
"function"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/threaded.py#L72-L83 | train | 215,123 |
CodeReclaimers/neat-python | neat/threaded.py | ThreadedEvaluator.evaluate | def evaluate(self, genomes, config):
"""Evaluate the genomes"""
if not self.working:
self.start()
p = 0
for genome_id, genome in genomes:
p += 1
self.inqueue.put((genome_id, genome, config))
# assign the fitness back to each genome
while p > 0:
p -= 1
ignored_genome_id, genome, fitness = self.outqueue.get()
genome.fitness = fitness | python | def evaluate(self, genomes, config):
"""Evaluate the genomes"""
if not self.working:
self.start()
p = 0
for genome_id, genome in genomes:
p += 1
self.inqueue.put((genome_id, genome, config))
# assign the fitness back to each genome
while p > 0:
p -= 1
ignored_genome_id, genome, fitness = self.outqueue.get()
genome.fitness = fitness | [
"def",
"evaluate",
"(",
"self",
",",
"genomes",
",",
"config",
")",
":",
"if",
"not",
"self",
".",
"working",
":",
"self",
".",
"start",
"(",
")",
"p",
"=",
"0",
"for",
"genome_id",
",",
"genome",
"in",
"genomes",
":",
"p",
"+=",
"1",
"self",
"."... | Evaluate the genomes | [
"Evaluate",
"the",
"genomes"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/threaded.py#L85-L98 | train | 215,124 |
CodeReclaimers/neat-python | neat/iznn/__init__.py | IZNeuron.advance | def advance(self, dt_msec):
"""
Advances simulation time by the given time step in milliseconds.
v' = 0.04 * v^2 + 5v + 140 - u + I
u' = a * (b * v - u)
if v >= 30 then
v <- c, u <- u + d
"""
# TODO: Make the time step adjustable, and choose an appropriate
# numerical integration method to maintain stability.
# TODO: The need to catch overflows indicates that the current method is
# not stable for all possible network configurations and states.
try:
self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
self.u += dt_msec * self.a * (self.b * self.v - self.u)
except OverflowError:
# Reset without producing a spike.
self.v = self.c
self.u = self.b * self.v
self.fired = 0.0
if self.v > 30.0:
# Output spike and reset.
self.fired = 1.0
self.v = self.c
self.u += self.d | python | def advance(self, dt_msec):
"""
Advances simulation time by the given time step in milliseconds.
v' = 0.04 * v^2 + 5v + 140 - u + I
u' = a * (b * v - u)
if v >= 30 then
v <- c, u <- u + d
"""
# TODO: Make the time step adjustable, and choose an appropriate
# numerical integration method to maintain stability.
# TODO: The need to catch overflows indicates that the current method is
# not stable for all possible network configurations and states.
try:
self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
self.u += dt_msec * self.a * (self.b * self.v - self.u)
except OverflowError:
# Reset without producing a spike.
self.v = self.c
self.u = self.b * self.v
self.fired = 0.0
if self.v > 30.0:
# Output spike and reset.
self.fired = 1.0
self.v = self.c
self.u += self.d | [
"def",
"advance",
"(",
"self",
",",
"dt_msec",
")",
":",
"# TODO: Make the time step adjustable, and choose an appropriate",
"# numerical integration method to maintain stability.",
"# TODO: The need to catch overflows indicates that the current method is",
"# not stable for all possible netwo... | Advances simulation time by the given time step in milliseconds.
v' = 0.04 * v^2 + 5v + 140 - u + I
u' = a * (b * v - u)
if v >= 30 then
v <- c, u <- u + d | [
"Advances",
"simulation",
"time",
"by",
"the",
"given",
"time",
"step",
"in",
"milliseconds",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/iznn/__init__.py#L90-L118 | train | 215,125 |
CodeReclaimers/neat-python | neat/iznn/__init__.py | IZNeuron.reset | def reset(self):
"""Resets all state variables."""
self.v = self.c
self.u = self.b * self.v
self.fired = 0.0
self.current = self.bias | python | def reset(self):
"""Resets all state variables."""
self.v = self.c
self.u = self.b * self.v
self.fired = 0.0
self.current = self.bias | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"v",
"=",
"self",
".",
"c",
"self",
".",
"u",
"=",
"self",
".",
"b",
"*",
"self",
".",
"v",
"self",
".",
"fired",
"=",
"0.0",
"self",
".",
"current",
"=",
"self",
".",
"bias"
] | Resets all state variables. | [
"Resets",
"all",
"state",
"variables",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/iznn/__init__.py#L120-L125 | train | 215,126 |
CodeReclaimers/neat-python | neat/iznn/__init__.py | IZNN.set_inputs | def set_inputs(self, inputs):
"""Assign input voltages."""
if len(inputs) != len(self.inputs):
raise RuntimeError(
"Number of inputs {0:d} does not match number of input nodes {1:d}".format(
len(inputs), len(self.inputs)))
for i, v in zip(self.inputs, inputs):
self.input_values[i] = v | python | def set_inputs(self, inputs):
"""Assign input voltages."""
if len(inputs) != len(self.inputs):
raise RuntimeError(
"Number of inputs {0:d} does not match number of input nodes {1:d}".format(
len(inputs), len(self.inputs)))
for i, v in zip(self.inputs, inputs):
self.input_values[i] = v | [
"def",
"set_inputs",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"len",
"(",
"inputs",
")",
"!=",
"len",
"(",
"self",
".",
"inputs",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Number of inputs {0:d} does not match number of input nodes {1:d}\"",
".",
"format",
"... | Assign input voltages. | [
"Assign",
"input",
"voltages",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/iznn/__init__.py#L136-L143 | train | 215,127 |
CodeReclaimers/neat-python | examples/xor/evolve-spiking.py | compute_output | def compute_output(t0, t1):
'''Compute the network's output based on the "time to first spike" of the two output neurons.'''
if t0 is None or t1 is None:
# If neither of the output neurons fired within the allotted time,
# give a response which produces a large error.
return -1.0
else:
# If the output neurons fire within 1.0 milliseconds of each other,
# the output is 1, and if they fire more than 11 milliseconds apart,
# the output is 0, with linear interpolation between 1 and 11 milliseconds.
response = 1.1 - 0.1 * abs(t0 - t1)
return max(0.0, min(1.0, response)) | python | def compute_output(t0, t1):
'''Compute the network's output based on the "time to first spike" of the two output neurons.'''
if t0 is None or t1 is None:
# If neither of the output neurons fired within the allotted time,
# give a response which produces a large error.
return -1.0
else:
# If the output neurons fire within 1.0 milliseconds of each other,
# the output is 1, and if they fire more than 11 milliseconds apart,
# the output is 0, with linear interpolation between 1 and 11 milliseconds.
response = 1.1 - 0.1 * abs(t0 - t1)
return max(0.0, min(1.0, response)) | [
"def",
"compute_output",
"(",
"t0",
",",
"t1",
")",
":",
"if",
"t0",
"is",
"None",
"or",
"t1",
"is",
"None",
":",
"# If neither of the output neurons fired within the allotted time,",
"# give a response which produces a large error.",
"return",
"-",
"1.0",
"else",
":",
... | Compute the network's output based on the "time to first spike" of the two output neurons. | [
"Compute",
"the",
"network",
"s",
"output",
"based",
"on",
"the",
"time",
"to",
"first",
"spike",
"of",
"the",
"two",
"output",
"neurons",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/xor/evolve-spiking.py#L19-L30 | train | 215,128 |
CodeReclaimers/neat-python | neat/species.py | DefaultSpeciesSet.speciate | def speciate(self, config, population, generation):
"""
Place genomes into species by genetic similarity.
Note that this method assumes the current representatives of the species are from the old
generation, and that after speciation has been performed, the old representatives should be
dropped and replaced with representatives from the new generation. If you violate this
assumption, you should make sure other necessary parts of the code are updated to reflect
the new behavior.
"""
assert isinstance(population, dict)
compatibility_threshold = self.species_set_config.compatibility_threshold
# Find the best representatives for each existing species.
unspeciated = set(iterkeys(population))
distances = GenomeDistanceCache(config.genome_config)
new_representatives = {}
new_members = {}
for sid, s in iteritems(self.species):
candidates = []
for gid in unspeciated:
g = population[gid]
d = distances(s.representative, g)
candidates.append((d, g))
# The new representative is the genome closest to the current representative.
ignored_rdist, new_rep = min(candidates, key=lambda x: x[0])
new_rid = new_rep.key
new_representatives[sid] = new_rid
new_members[sid] = [new_rid]
unspeciated.remove(new_rid)
# Partition population into species based on genetic similarity.
while unspeciated:
gid = unspeciated.pop()
g = population[gid]
# Find the species with the most similar representative.
candidates = []
for sid, rid in iteritems(new_representatives):
rep = population[rid]
d = distances(rep, g)
if d < compatibility_threshold:
candidates.append((d, sid))
if candidates:
ignored_sdist, sid = min(candidates, key=lambda x: x[0])
new_members[sid].append(gid)
else:
# No species is similar enough, create a new species, using
# this genome as its representative.
sid = next(self.indexer)
new_representatives[sid] = gid
new_members[sid] = [gid]
# Update species collection based on new speciation.
self.genome_to_species = {}
for sid, rid in iteritems(new_representatives):
s = self.species.get(sid)
if s is None:
s = Species(sid, generation)
self.species[sid] = s
members = new_members[sid]
for gid in members:
self.genome_to_species[gid] = sid
member_dict = dict((gid, population[gid]) for gid in members)
s.update(population[rid], member_dict)
gdmean = mean(itervalues(distances.distances))
gdstdev = stdev(itervalues(distances.distances))
self.reporters.info(
'Mean genetic distance {0:.3f}, standard deviation {1:.3f}'.format(gdmean, gdstdev)) | python | def speciate(self, config, population, generation):
"""
Place genomes into species by genetic similarity.
Note that this method assumes the current representatives of the species are from the old
generation, and that after speciation has been performed, the old representatives should be
dropped and replaced with representatives from the new generation. If you violate this
assumption, you should make sure other necessary parts of the code are updated to reflect
the new behavior.
"""
assert isinstance(population, dict)
compatibility_threshold = self.species_set_config.compatibility_threshold
# Find the best representatives for each existing species.
unspeciated = set(iterkeys(population))
distances = GenomeDistanceCache(config.genome_config)
new_representatives = {}
new_members = {}
for sid, s in iteritems(self.species):
candidates = []
for gid in unspeciated:
g = population[gid]
d = distances(s.representative, g)
candidates.append((d, g))
# The new representative is the genome closest to the current representative.
ignored_rdist, new_rep = min(candidates, key=lambda x: x[0])
new_rid = new_rep.key
new_representatives[sid] = new_rid
new_members[sid] = [new_rid]
unspeciated.remove(new_rid)
# Partition population into species based on genetic similarity.
while unspeciated:
gid = unspeciated.pop()
g = population[gid]
# Find the species with the most similar representative.
candidates = []
for sid, rid in iteritems(new_representatives):
rep = population[rid]
d = distances(rep, g)
if d < compatibility_threshold:
candidates.append((d, sid))
if candidates:
ignored_sdist, sid = min(candidates, key=lambda x: x[0])
new_members[sid].append(gid)
else:
# No species is similar enough, create a new species, using
# this genome as its representative.
sid = next(self.indexer)
new_representatives[sid] = gid
new_members[sid] = [gid]
# Update species collection based on new speciation.
self.genome_to_species = {}
for sid, rid in iteritems(new_representatives):
s = self.species.get(sid)
if s is None:
s = Species(sid, generation)
self.species[sid] = s
members = new_members[sid]
for gid in members:
self.genome_to_species[gid] = sid
member_dict = dict((gid, population[gid]) for gid in members)
s.update(population[rid], member_dict)
gdmean = mean(itervalues(distances.distances))
gdstdev = stdev(itervalues(distances.distances))
self.reporters.info(
'Mean genetic distance {0:.3f}, standard deviation {1:.3f}'.format(gdmean, gdstdev)) | [
"def",
"speciate",
"(",
"self",
",",
"config",
",",
"population",
",",
"generation",
")",
":",
"assert",
"isinstance",
"(",
"population",
",",
"dict",
")",
"compatibility_threshold",
"=",
"self",
".",
"species_set_config",
".",
"compatibility_threshold",
"# Find t... | Place genomes into species by genetic similarity.
Note that this method assumes the current representatives of the species are from the old
generation, and that after speciation has been performed, the old representatives should be
dropped and replaced with representatives from the new generation. If you violate this
assumption, you should make sure other necessary parts of the code are updated to reflect
the new behavior. | [
"Place",
"genomes",
"into",
"species",
"by",
"genetic",
"similarity",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/species.py#L65-L139 | train | 215,129 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.get_average_cross_validation_fitness | def get_average_cross_validation_fitness(self): # pragma: no cover
"""Get the per-generation average cross_validation fitness."""
avg_cross_validation_fitness = []
for stats in self.generation_cross_validation_statistics:
scores = []
for fitness in stats.values():
scores.extend(fitness)
avg_cross_validation_fitness.append(mean(scores))
return avg_cross_validation_fitness | python | def get_average_cross_validation_fitness(self): # pragma: no cover
"""Get the per-generation average cross_validation fitness."""
avg_cross_validation_fitness = []
for stats in self.generation_cross_validation_statistics:
scores = []
for fitness in stats.values():
scores.extend(fitness)
avg_cross_validation_fitness.append(mean(scores))
return avg_cross_validation_fitness | [
"def",
"get_average_cross_validation_fitness",
"(",
"self",
")",
":",
"# pragma: no cover",
"avg_cross_validation_fitness",
"=",
"[",
"]",
"for",
"stats",
"in",
"self",
".",
"generation_cross_validation_statistics",
":",
"scores",
"=",
"[",
"]",
"for",
"fitness",
"in"... | Get the per-generation average cross_validation fitness. | [
"Get",
"the",
"per",
"-",
"generation",
"average",
"cross_validation",
"fitness",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L62-L71 | train | 215,130 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.best_unique_genomes | def best_unique_genomes(self, n):
"""Returns the most n fit genomes, with no duplication."""
best_unique = {}
for g in self.most_fit_genomes:
best_unique[g.key] = g
best_unique_list = list(best_unique.values())
def key(genome):
return genome.fitness
return sorted(best_unique_list, key=key, reverse=True)[:n] | python | def best_unique_genomes(self, n):
"""Returns the most n fit genomes, with no duplication."""
best_unique = {}
for g in self.most_fit_genomes:
best_unique[g.key] = g
best_unique_list = list(best_unique.values())
def key(genome):
return genome.fitness
return sorted(best_unique_list, key=key, reverse=True)[:n] | [
"def",
"best_unique_genomes",
"(",
"self",
",",
"n",
")",
":",
"best_unique",
"=",
"{",
"}",
"for",
"g",
"in",
"self",
".",
"most_fit_genomes",
":",
"best_unique",
"[",
"g",
".",
"key",
"]",
"=",
"g",
"best_unique_list",
"=",
"list",
"(",
"best_unique",
... | Returns the most n fit genomes, with no duplication. | [
"Returns",
"the",
"most",
"n",
"fit",
"genomes",
"with",
"no",
"duplication",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L73-L83 | train | 215,131 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.best_genomes | def best_genomes(self, n):
"""Returns the n most fit genomes ever seen."""
def key(g):
return g.fitness
return sorted(self.most_fit_genomes, key=key, reverse=True)[:n] | python | def best_genomes(self, n):
"""Returns the n most fit genomes ever seen."""
def key(g):
return g.fitness
return sorted(self.most_fit_genomes, key=key, reverse=True)[:n] | [
"def",
"best_genomes",
"(",
"self",
",",
"n",
")",
":",
"def",
"key",
"(",
"g",
")",
":",
"return",
"g",
".",
"fitness",
"return",
"sorted",
"(",
"self",
".",
"most_fit_genomes",
",",
"key",
"=",
"key",
",",
"reverse",
"=",
"True",
")",
"[",
":",
... | Returns the n most fit genomes ever seen. | [
"Returns",
"the",
"n",
"most",
"fit",
"genomes",
"ever",
"seen",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L85-L90 | train | 215,132 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.save_genome_fitness | def save_genome_fitness(self,
delimiter=' ',
filename='fitness_history.csv',
with_cross_validation=False):
""" Saves the population's best and average fitness. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
best_fitness = [c.fitness for c in self.most_fit_genomes]
avg_fitness = self.get_fitness_mean()
if with_cross_validation: # pragma: no cover
cv_best_fitness = [c.cross_fitness for c in self.most_fit_genomes]
cv_avg_fitness = self.get_average_cross_validation_fitness()
for best, avg, cv_best, cv_avg in zip(best_fitness,
avg_fitness,
cv_best_fitness,
cv_avg_fitness):
w.writerow([best, avg, cv_best, cv_avg])
else:
for best, avg in zip(best_fitness, avg_fitness):
w.writerow([best, avg]) | python | def save_genome_fitness(self,
delimiter=' ',
filename='fitness_history.csv',
with_cross_validation=False):
""" Saves the population's best and average fitness. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
best_fitness = [c.fitness for c in self.most_fit_genomes]
avg_fitness = self.get_fitness_mean()
if with_cross_validation: # pragma: no cover
cv_best_fitness = [c.cross_fitness for c in self.most_fit_genomes]
cv_avg_fitness = self.get_average_cross_validation_fitness()
for best, avg, cv_best, cv_avg in zip(best_fitness,
avg_fitness,
cv_best_fitness,
cv_avg_fitness):
w.writerow([best, avg, cv_best, cv_avg])
else:
for best, avg in zip(best_fitness, avg_fitness):
w.writerow([best, avg]) | [
"def",
"save_genome_fitness",
"(",
"self",
",",
"delimiter",
"=",
"' '",
",",
"filename",
"=",
"'fitness_history.csv'",
",",
"with_cross_validation",
"=",
"False",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"w",
"=",
"csv",... | Saves the population's best and average fitness. | [
"Saves",
"the",
"population",
"s",
"best",
"and",
"average",
"fitness",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L101-L122 | train | 215,133 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.save_species_count | def save_species_count(self, delimiter=' ', filename='speciation.csv'):
""" Log speciation throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_sizes():
w.writerow(s) | python | def save_species_count(self, delimiter=' ', filename='speciation.csv'):
""" Log speciation throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_sizes():
w.writerow(s) | [
"def",
"save_species_count",
"(",
"self",
",",
"delimiter",
"=",
"' '",
",",
"filename",
"=",
"'speciation.csv'",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"w",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"delimiter",
... | Log speciation throughout evolution. | [
"Log",
"speciation",
"throughout",
"evolution",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L124-L129 | train | 215,134 |
CodeReclaimers/neat-python | neat/statistics.py | StatisticsReporter.save_species_fitness | def save_species_fitness(self, delimiter=' ', null_value='NA', filename='species_fitness.csv'):
""" Log species' average fitness throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_fitness(null_value):
w.writerow(s) | python | def save_species_fitness(self, delimiter=' ', null_value='NA', filename='species_fitness.csv'):
""" Log species' average fitness throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_fitness(null_value):
w.writerow(s) | [
"def",
"save_species_fitness",
"(",
"self",
",",
"delimiter",
"=",
"' '",
",",
"null_value",
"=",
"'NA'",
",",
"filename",
"=",
"'species_fitness.csv'",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"w",
"=",
"csv",
".",
"... | Log species' average fitness throughout evolution. | [
"Log",
"species",
"average",
"fitness",
"throughout",
"evolution",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/statistics.py#L131-L136 | train | 215,135 |
CodeReclaimers/neat-python | neat/genome.py | DefaultGenome.configure_new | def configure_new(self, config):
"""Configure a new genome based on the given configuration."""
# Create node genes for the output pins.
for node_key in config.output_keys:
self.nodes[node_key] = self.create_node(config, node_key)
# Add hidden nodes if requested.
if config.num_hidden > 0:
for i in range(config.num_hidden):
node_key = config.get_new_node_key(self.nodes)
assert node_key not in self.nodes
node = self.create_node(config, node_key)
self.nodes[node_key] = node
# Add connections based on initial connectivity type.
if 'fs_neat' in config.initial_connection:
if config.initial_connection == 'fs_neat_nohidden':
self.connect_fs_neat_nohidden(config)
elif config.initial_connection == 'fs_neat_hidden':
self.connect_fs_neat_hidden(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = fs_neat will not connect to hidden nodes;",
"\tif this is desired, set initial_connection = fs_neat_nohidden;",
"\tif not, set initial_connection = fs_neat_hidden",
sep='\n', file=sys.stderr);
self.connect_fs_neat_nohidden(config)
elif 'full' in config.initial_connection:
if config.initial_connection == 'full_nodirect':
self.connect_full_nodirect(config)
elif config.initial_connection == 'full_direct':
self.connect_full_direct(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = full with hidden nodes will not do direct input-output connections;",
"\tif this is desired, set initial_connection = full_nodirect;",
"\tif not, set initial_connection = full_direct",
sep='\n', file=sys.stderr);
self.connect_full_nodirect(config)
elif 'partial' in config.initial_connection:
if config.initial_connection == 'partial_nodirect':
self.connect_partial_nodirect(config)
elif config.initial_connection == 'partial_direct':
self.connect_partial_direct(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = partial with hidden nodes will not do direct input-output connections;",
"\tif this is desired, set initial_connection = partial_nodirect {0};".format(
config.connection_fraction),
"\tif not, set initial_connection = partial_direct {0}".format(
config.connection_fraction),
sep='\n', file=sys.stderr);
self.connect_partial_nodirect(config) | python | def configure_new(self, config):
"""Configure a new genome based on the given configuration."""
# Create node genes for the output pins.
for node_key in config.output_keys:
self.nodes[node_key] = self.create_node(config, node_key)
# Add hidden nodes if requested.
if config.num_hidden > 0:
for i in range(config.num_hidden):
node_key = config.get_new_node_key(self.nodes)
assert node_key not in self.nodes
node = self.create_node(config, node_key)
self.nodes[node_key] = node
# Add connections based on initial connectivity type.
if 'fs_neat' in config.initial_connection:
if config.initial_connection == 'fs_neat_nohidden':
self.connect_fs_neat_nohidden(config)
elif config.initial_connection == 'fs_neat_hidden':
self.connect_fs_neat_hidden(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = fs_neat will not connect to hidden nodes;",
"\tif this is desired, set initial_connection = fs_neat_nohidden;",
"\tif not, set initial_connection = fs_neat_hidden",
sep='\n', file=sys.stderr);
self.connect_fs_neat_nohidden(config)
elif 'full' in config.initial_connection:
if config.initial_connection == 'full_nodirect':
self.connect_full_nodirect(config)
elif config.initial_connection == 'full_direct':
self.connect_full_direct(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = full with hidden nodes will not do direct input-output connections;",
"\tif this is desired, set initial_connection = full_nodirect;",
"\tif not, set initial_connection = full_direct",
sep='\n', file=sys.stderr);
self.connect_full_nodirect(config)
elif 'partial' in config.initial_connection:
if config.initial_connection == 'partial_nodirect':
self.connect_partial_nodirect(config)
elif config.initial_connection == 'partial_direct':
self.connect_partial_direct(config)
else:
if config.num_hidden > 0:
print(
"Warning: initial_connection = partial with hidden nodes will not do direct input-output connections;",
"\tif this is desired, set initial_connection = partial_nodirect {0};".format(
config.connection_fraction),
"\tif not, set initial_connection = partial_direct {0}".format(
config.connection_fraction),
sep='\n', file=sys.stderr);
self.connect_partial_nodirect(config) | [
"def",
"configure_new",
"(",
"self",
",",
"config",
")",
":",
"# Create node genes for the output pins.",
"for",
"node_key",
"in",
"config",
".",
"output_keys",
":",
"self",
".",
"nodes",
"[",
"node_key",
"]",
"=",
"self",
".",
"create_node",
"(",
"config",
",... | Configure a new genome based on the given configuration. | [
"Configure",
"a",
"new",
"genome",
"based",
"on",
"the",
"given",
"configuration",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genome.py#L175-L232 | train | 215,136 |
CodeReclaimers/neat-python | neat/genome.py | DefaultGenome.configure_crossover | def configure_crossover(self, genome1, genome2, config):
""" Configure a new genome by crossover from two parent genomes. """
assert isinstance(genome1.fitness, (int, float))
assert isinstance(genome2.fitness, (int, float))
if genome1.fitness > genome2.fitness:
parent1, parent2 = genome1, genome2
else:
parent1, parent2 = genome2, genome1
# Inherit connection genes
for key, cg1 in iteritems(parent1.connections):
cg2 = parent2.connections.get(key)
if cg2 is None:
# Excess or disjoint gene: copy from the fittest parent.
self.connections[key] = cg1.copy()
else:
# Homologous gene: combine genes from both parents.
self.connections[key] = cg1.crossover(cg2)
# Inherit node genes
parent1_set = parent1.nodes
parent2_set = parent2.nodes
for key, ng1 in iteritems(parent1_set):
ng2 = parent2_set.get(key)
assert key not in self.nodes
if ng2 is None:
# Extra gene: copy from the fittest parent
self.nodes[key] = ng1.copy()
else:
# Homologous gene: combine genes from both parents.
self.nodes[key] = ng1.crossover(ng2) | python | def configure_crossover(self, genome1, genome2, config):
""" Configure a new genome by crossover from two parent genomes. """
assert isinstance(genome1.fitness, (int, float))
assert isinstance(genome2.fitness, (int, float))
if genome1.fitness > genome2.fitness:
parent1, parent2 = genome1, genome2
else:
parent1, parent2 = genome2, genome1
# Inherit connection genes
for key, cg1 in iteritems(parent1.connections):
cg2 = parent2.connections.get(key)
if cg2 is None:
# Excess or disjoint gene: copy from the fittest parent.
self.connections[key] = cg1.copy()
else:
# Homologous gene: combine genes from both parents.
self.connections[key] = cg1.crossover(cg2)
# Inherit node genes
parent1_set = parent1.nodes
parent2_set = parent2.nodes
for key, ng1 in iteritems(parent1_set):
ng2 = parent2_set.get(key)
assert key not in self.nodes
if ng2 is None:
# Extra gene: copy from the fittest parent
self.nodes[key] = ng1.copy()
else:
# Homologous gene: combine genes from both parents.
self.nodes[key] = ng1.crossover(ng2) | [
"def",
"configure_crossover",
"(",
"self",
",",
"genome1",
",",
"genome2",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"genome1",
".",
"fitness",
",",
"(",
"int",
",",
"float",
")",
")",
"assert",
"isinstance",
"(",
"genome2",
".",
"fitness",
"... | Configure a new genome by crossover from two parent genomes. | [
"Configure",
"a",
"new",
"genome",
"by",
"crossover",
"from",
"two",
"parent",
"genomes",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genome.py#L234-L265 | train | 215,137 |
CodeReclaimers/neat-python | neat/genome.py | DefaultGenome.connect_full_direct | def connect_full_direct(self, config):
""" Create a fully-connected genome, including direct input-output connections. """
for input_id, output_id in self.compute_full_connections(config, True):
connection = self.create_connection(config, input_id, output_id)
self.connections[connection.key] = connection | python | def connect_full_direct(self, config):
""" Create a fully-connected genome, including direct input-output connections. """
for input_id, output_id in self.compute_full_connections(config, True):
connection = self.create_connection(config, input_id, output_id)
self.connections[connection.key] = connection | [
"def",
"connect_full_direct",
"(",
"self",
",",
"config",
")",
":",
"for",
"input_id",
",",
"output_id",
"in",
"self",
".",
"compute_full_connections",
"(",
"config",
",",
"True",
")",
":",
"connection",
"=",
"self",
".",
"create_connection",
"(",
"config",
... | Create a fully-connected genome, including direct input-output connections. | [
"Create",
"a",
"fully",
"-",
"connected",
"genome",
"including",
"direct",
"input",
"-",
"output",
"connections",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genome.py#L541-L545 | train | 215,138 |
CodeReclaimers/neat-python | neat/config.py | ConfigParameter.interpret | def interpret(self, config_dict):
"""
Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors.
"""
value = config_dict.get(self.name)
if value is None:
if self.default is None:
raise RuntimeError('Missing configuration item: ' + self.name)
else:
warnings.warn("Using default {!r} for '{!s}'".format(self.default, self.name),
DeprecationWarning)
if (str != self.value_type) and isinstance(self.default, self.value_type):
return self.default
else:
value = self.default
try:
if str == self.value_type:
return str(value)
if int == self.value_type:
return int(value)
if bool == self.value_type:
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
else:
raise RuntimeError(self.name + " must be True or False")
if float == self.value_type:
return float(value)
if list == self.value_type:
return value.split(" ")
except Exception:
raise RuntimeError("Error interpreting config item '{}' with value {!r} and type {}".format(
self.name, value, self.value_type))
raise RuntimeError("Unexpected configuration type: " + repr(self.value_type)) | python | def interpret(self, config_dict):
"""
Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors.
"""
value = config_dict.get(self.name)
if value is None:
if self.default is None:
raise RuntimeError('Missing configuration item: ' + self.name)
else:
warnings.warn("Using default {!r} for '{!s}'".format(self.default, self.name),
DeprecationWarning)
if (str != self.value_type) and isinstance(self.default, self.value_type):
return self.default
else:
value = self.default
try:
if str == self.value_type:
return str(value)
if int == self.value_type:
return int(value)
if bool == self.value_type:
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
else:
raise RuntimeError(self.name + " must be True or False")
if float == self.value_type:
return float(value)
if list == self.value_type:
return value.split(" ")
except Exception:
raise RuntimeError("Error interpreting config item '{}' with value {!r} and type {}".format(
self.name, value, self.value_type))
raise RuntimeError("Unexpected configuration type: " + repr(self.value_type)) | [
"def",
"interpret",
"(",
"self",
",",
"config_dict",
")",
":",
"value",
"=",
"config_dict",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"value",
"is",
"None",
":",
"if",
"self",
".",
"default",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'... | Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors. | [
"Converts",
"the",
"config_parser",
"output",
"into",
"the",
"proper",
"type",
"supplies",
"defaults",
"if",
"available",
"and",
"needed",
"and",
"checks",
"for",
"some",
"errors",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/config.py#L47-L84 | train | 215,139 |
CodeReclaimers/neat-python | examples/xor/visualize.py | plot_spikes | def plot_spikes(spikes, view=False, filename=None, title=None):
""" Plots the trains for a single spiking neuron. """
t_values = [t for t, I, v, u, f in spikes]
v_values = [v for t, I, v, u, f in spikes]
u_values = [u for t, I, v, u, f in spikes]
I_values = [I for t, I, v, u, f in spikes]
f_values = [f for t, I, v, u, f in spikes]
fig = plt.figure()
plt.subplot(4, 1, 1)
plt.ylabel("Potential (mv)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, v_values, "g-")
if title is None:
plt.title("Izhikevich's spiking neuron model")
else:
plt.title("Izhikevich's spiking neuron model ({0!s})".format(title))
plt.subplot(4, 1, 2)
plt.ylabel("Fired")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, f_values, "r-")
plt.subplot(4, 1, 3)
plt.ylabel("Recovery (u)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, u_values, "r-")
plt.subplot(4, 1, 4)
plt.ylabel("Current (I)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, I_values, "r-o")
if filename is not None:
plt.savefig(filename)
if view:
plt.show()
plt.close()
fig = None
return fig | python | def plot_spikes(spikes, view=False, filename=None, title=None):
""" Plots the trains for a single spiking neuron. """
t_values = [t for t, I, v, u, f in spikes]
v_values = [v for t, I, v, u, f in spikes]
u_values = [u for t, I, v, u, f in spikes]
I_values = [I for t, I, v, u, f in spikes]
f_values = [f for t, I, v, u, f in spikes]
fig = plt.figure()
plt.subplot(4, 1, 1)
plt.ylabel("Potential (mv)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, v_values, "g-")
if title is None:
plt.title("Izhikevich's spiking neuron model")
else:
plt.title("Izhikevich's spiking neuron model ({0!s})".format(title))
plt.subplot(4, 1, 2)
plt.ylabel("Fired")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, f_values, "r-")
plt.subplot(4, 1, 3)
plt.ylabel("Recovery (u)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, u_values, "r-")
plt.subplot(4, 1, 4)
plt.ylabel("Current (I)")
plt.xlabel("Time (in ms)")
plt.grid()
plt.plot(t_values, I_values, "r-o")
if filename is not None:
plt.savefig(filename)
if view:
plt.show()
plt.close()
fig = None
return fig | [
"def",
"plot_spikes",
"(",
"spikes",
",",
"view",
"=",
"False",
",",
"filename",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"t_values",
"=",
"[",
"t",
"for",
"t",
",",
"I",
",",
"v",
",",
"u",
",",
"f",
"in",
"spikes",
"]",
"v_values",
"... | Plots the trains for a single spiking neuron. | [
"Plots",
"the",
"trains",
"for",
"a",
"single",
"spiking",
"neuron",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/xor/visualize.py#L42-L88 | train | 215,140 |
carpedm20/fbchat | fbchat/_client.py | Client.isLoggedIn | def isLoggedIn(self):
"""
Sends a request to Facebook to check the login status
:return: True if the client is still logged in
:rtype: bool
"""
# Send a request to the login url, to see if we're directed to the home page
r = self._cleanGet(self.req_url.LOGIN, allow_redirects=False)
return "Location" in r.headers and "home" in r.headers["Location"] | python | def isLoggedIn(self):
"""
Sends a request to Facebook to check the login status
:return: True if the client is still logged in
:rtype: bool
"""
# Send a request to the login url, to see if we're directed to the home page
r = self._cleanGet(self.req_url.LOGIN, allow_redirects=False)
return "Location" in r.headers and "home" in r.headers["Location"] | [
"def",
"isLoggedIn",
"(",
"self",
")",
":",
"# Send a request to the login url, to see if we're directed to the home page",
"r",
"=",
"self",
".",
"_cleanGet",
"(",
"self",
".",
"req_url",
".",
"LOGIN",
",",
"allow_redirects",
"=",
"False",
")",
"return",
"\"Location\... | Sends a request to Facebook to check the login status
:return: True if the client is still logged in
:rtype: bool | [
"Sends",
"a",
"request",
"to",
"Facebook",
"to",
"check",
"the",
"login",
"status"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L426-L435 | train | 215,141 |
carpedm20/fbchat | fbchat/_client.py | Client.setSession | def setSession(self, session_cookies):
"""Loads session cookies
:param session_cookies: A dictionay containing session cookies
:type session_cookies: dict
:return: False if `session_cookies` does not contain proper cookies
:rtype: bool
"""
# Quick check to see if session_cookies is formatted properly
if not session_cookies or "c_user" not in session_cookies:
return False
try:
# Load cookies into current session
self._session.cookies = requests.cookies.merge_cookies(
self._session.cookies, session_cookies
)
self._postLogin()
except Exception as e:
log.exception("Failed loading session")
self._resetValues()
return False
return True | python | def setSession(self, session_cookies):
"""Loads session cookies
:param session_cookies: A dictionay containing session cookies
:type session_cookies: dict
:return: False if `session_cookies` does not contain proper cookies
:rtype: bool
"""
# Quick check to see if session_cookies is formatted properly
if not session_cookies or "c_user" not in session_cookies:
return False
try:
# Load cookies into current session
self._session.cookies = requests.cookies.merge_cookies(
self._session.cookies, session_cookies
)
self._postLogin()
except Exception as e:
log.exception("Failed loading session")
self._resetValues()
return False
return True | [
"def",
"setSession",
"(",
"self",
",",
"session_cookies",
")",
":",
"# Quick check to see if session_cookies is formatted properly",
"if",
"not",
"session_cookies",
"or",
"\"c_user\"",
"not",
"in",
"session_cookies",
":",
"return",
"False",
"try",
":",
"# Load cookies int... | Loads session cookies
:param session_cookies: A dictionay containing session cookies
:type session_cookies: dict
:return: False if `session_cookies` does not contain proper cookies
:rtype: bool | [
"Loads",
"session",
"cookies"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L445-L467 | train | 215,142 |
carpedm20/fbchat | fbchat/_client.py | Client.logout | def logout(self):
"""
Safely logs out the client
:param timeout: See `requests timeout <http://docs.python-requests.org/en/master/user/advanced/#timeouts>`_
:return: True if the action was successful
:rtype: bool
"""
if not hasattr(self, "_fb_h"):
h_r = self._post(self.req_url.MODERN_SETTINGS_MENU, {"pmid": "4"})
self._fb_h = re.search(r'name=\\"h\\" value=\\"(.*?)\\"', h_r.text).group(1)
data = {"ref": "mb", "h": self._fb_h}
r = self._get(self.req_url.LOGOUT, data)
self._resetValues()
return r.ok | python | def logout(self):
"""
Safely logs out the client
:param timeout: See `requests timeout <http://docs.python-requests.org/en/master/user/advanced/#timeouts>`_
:return: True if the action was successful
:rtype: bool
"""
if not hasattr(self, "_fb_h"):
h_r = self._post(self.req_url.MODERN_SETTINGS_MENU, {"pmid": "4"})
self._fb_h = re.search(r'name=\\"h\\" value=\\"(.*?)\\"', h_r.text).group(1)
data = {"ref": "mb", "h": self._fb_h}
r = self._get(self.req_url.LOGOUT, data)
self._resetValues()
return r.ok | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_fb_h\"",
")",
":",
"h_r",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"MODERN_SETTINGS_MENU",
",",
"{",
"\"pmid\"",
":",
"\"4\"",
"}",
")",
"self",... | Safely logs out the client
:param timeout: See `requests timeout <http://docs.python-requests.org/en/master/user/advanced/#timeouts>`_
:return: True if the action was successful
:rtype: bool | [
"Safely",
"logs",
"out",
"the",
"client"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L506-L524 | train | 215,143 |
carpedm20/fbchat | fbchat/_client.py | Client._getThread | def _getThread(self, given_thread_id=None, given_thread_type=None):
"""
Checks if thread ID is given, checks if default is set and returns correct values
:raises ValueError: If thread ID is not given and there is no default
:return: Thread ID and thread type
:rtype: tuple
"""
if given_thread_id is None:
if self._default_thread_id is not None:
return self._default_thread_id, self._default_thread_type
else:
raise ValueError("Thread ID is not set")
else:
return given_thread_id, given_thread_type | python | def _getThread(self, given_thread_id=None, given_thread_type=None):
"""
Checks if thread ID is given, checks if default is set and returns correct values
:raises ValueError: If thread ID is not given and there is no default
:return: Thread ID and thread type
:rtype: tuple
"""
if given_thread_id is None:
if self._default_thread_id is not None:
return self._default_thread_id, self._default_thread_type
else:
raise ValueError("Thread ID is not set")
else:
return given_thread_id, given_thread_type | [
"def",
"_getThread",
"(",
"self",
",",
"given_thread_id",
"=",
"None",
",",
"given_thread_type",
"=",
"None",
")",
":",
"if",
"given_thread_id",
"is",
"None",
":",
"if",
"self",
".",
"_default_thread_id",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_... | Checks if thread ID is given, checks if default is set and returns correct values
:raises ValueError: If thread ID is not given and there is no default
:return: Thread ID and thread type
:rtype: tuple | [
"Checks",
"if",
"thread",
"ID",
"is",
"given",
"checks",
"if",
"default",
"is",
"set",
"and",
"returns",
"correct",
"values"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L534-L548 | train | 215,144 |
carpedm20/fbchat | fbchat/_client.py | Client.setDefaultThread | def setDefaultThread(self, thread_id, thread_type):
"""
Sets default thread to send messages to
:param thread_id: User/Group ID to default to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
"""
self._default_thread_id = thread_id
self._default_thread_type = thread_type | python | def setDefaultThread(self, thread_id, thread_type):
"""
Sets default thread to send messages to
:param thread_id: User/Group ID to default to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
"""
self._default_thread_id = thread_id
self._default_thread_type = thread_type | [
"def",
"setDefaultThread",
"(",
"self",
",",
"thread_id",
",",
"thread_type",
")",
":",
"self",
".",
"_default_thread_id",
"=",
"thread_id",
"self",
".",
"_default_thread_type",
"=",
"thread_type"
] | Sets default thread to send messages to
:param thread_id: User/Group ID to default to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType | [
"Sets",
"default",
"thread",
"to",
"send",
"messages",
"to"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L550-L559 | train | 215,145 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchThreads | def fetchThreads(self, thread_location, before=None, after=None, limit=None):
"""
Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""
threads = []
last_thread_timestamp = None
while True:
# break if limit is exceeded
if limit and len(threads) >= limit:
break
# fetchThreadList returns at max 20 threads before last_thread_timestamp (included)
candidates = self.fetchThreadList(
before=last_thread_timestamp, thread_location=thread_location
)
if len(candidates) > 1:
threads += candidates[1:]
else: # End of threads
break
last_thread_timestamp = threads[-1].last_message_timestamp
# FB returns a sorted list of threads
if (before is not None and int(last_thread_timestamp) > before) or (
after is not None and int(last_thread_timestamp) < after
):
break
# Return only threads between before and after (if set)
if before is not None or after is not None:
for t in threads:
last_message_timestamp = int(t.last_message_timestamp)
if (before is not None and last_message_timestamp > before) or (
after is not None and last_message_timestamp < after
):
threads.remove(t)
if limit and len(threads) > limit:
return threads[:limit]
return threads | python | def fetchThreads(self, thread_location, before=None, after=None, limit=None):
"""
Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""
threads = []
last_thread_timestamp = None
while True:
# break if limit is exceeded
if limit and len(threads) >= limit:
break
# fetchThreadList returns at max 20 threads before last_thread_timestamp (included)
candidates = self.fetchThreadList(
before=last_thread_timestamp, thread_location=thread_location
)
if len(candidates) > 1:
threads += candidates[1:]
else: # End of threads
break
last_thread_timestamp = threads[-1].last_message_timestamp
# FB returns a sorted list of threads
if (before is not None and int(last_thread_timestamp) > before) or (
after is not None and int(last_thread_timestamp) < after
):
break
# Return only threads between before and after (if set)
if before is not None or after is not None:
for t in threads:
last_message_timestamp = int(t.last_message_timestamp)
if (before is not None and last_message_timestamp > before) or (
after is not None and last_message_timestamp < after
):
threads.remove(t)
if limit and len(threads) > limit:
return threads[:limit]
return threads | [
"def",
"fetchThreads",
"(",
"self",
",",
"thread_location",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"threads",
"=",
"[",
"]",
"last_thread_timestamp",
"=",
"None",
"while",
"True",
":",
"# break if limit ... | Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed | [
"Get",
"all",
"threads",
"in",
"thread_location",
".",
"Threads",
"will",
"be",
"sorted",
"from",
"newest",
"to",
"oldest",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L577-L628 | train | 215,146 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchAllUsersFromThreads | def fetchAllUsersFromThreads(self, threads):
"""
Get all users involved in threads.
:param threads: models.Thread: List of threads to check for users
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed
"""
users = []
users_to_fetch = [] # It's more efficient to fetch all users in one request
for thread in threads:
if thread.type == ThreadType.USER:
if thread.uid not in [user.uid for user in users]:
users.append(thread)
elif thread.type == ThreadType.GROUP:
for user_id in thread.participants:
if (
user_id not in [user.uid for user in users]
and user_id not in users_to_fetch
):
users_to_fetch.append(user_id)
for user_id, user in self.fetchUserInfo(*users_to_fetch).items():
users.append(user)
return users | python | def fetchAllUsersFromThreads(self, threads):
"""
Get all users involved in threads.
:param threads: models.Thread: List of threads to check for users
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed
"""
users = []
users_to_fetch = [] # It's more efficient to fetch all users in one request
for thread in threads:
if thread.type == ThreadType.USER:
if thread.uid not in [user.uid for user in users]:
users.append(thread)
elif thread.type == ThreadType.GROUP:
for user_id in thread.participants:
if (
user_id not in [user.uid for user in users]
and user_id not in users_to_fetch
):
users_to_fetch.append(user_id)
for user_id, user in self.fetchUserInfo(*users_to_fetch).items():
users.append(user)
return users | [
"def",
"fetchAllUsersFromThreads",
"(",
"self",
",",
"threads",
")",
":",
"users",
"=",
"[",
"]",
"users_to_fetch",
"=",
"[",
"]",
"# It's more efficient to fetch all users in one request",
"for",
"thread",
"in",
"threads",
":",
"if",
"thread",
".",
"type",
"==",
... | Get all users involved in threads.
:param threads: models.Thread: List of threads to check for users
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed | [
"Get",
"all",
"users",
"involved",
"in",
"threads",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L630-L654 | train | 215,147 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchAllUsers | def fetchAllUsers(self):
"""
Gets all users the client is currently chatting with
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed
"""
data = {"viewer": self._uid}
j = self._post(
self.req_url.ALL_USERS, query=data, fix_request=True, as_json=True
)
if j.get("payload") is None:
raise FBchatException("Missing payload while fetching users: {}".format(j))
users = []
for data in j["payload"].values():
if data["type"] in ["user", "friend"]:
if data["id"] in ["0", 0]:
# Skip invalid users
continue
users.append(User._from_all_fetch(data))
return users | python | def fetchAllUsers(self):
"""
Gets all users the client is currently chatting with
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed
"""
data = {"viewer": self._uid}
j = self._post(
self.req_url.ALL_USERS, query=data, fix_request=True, as_json=True
)
if j.get("payload") is None:
raise FBchatException("Missing payload while fetching users: {}".format(j))
users = []
for data in j["payload"].values():
if data["type"] in ["user", "friend"]:
if data["id"] in ["0", 0]:
# Skip invalid users
continue
users.append(User._from_all_fetch(data))
return users | [
"def",
"fetchAllUsers",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"viewer\"",
":",
"self",
".",
"_uid",
"}",
"j",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"ALL_USERS",
",",
"query",
"=",
"data",
",",
"fix_request",
"=",
"True",
... | Gets all users the client is currently chatting with
:return: :class:`models.User` objects
:rtype: list
:raises: FBchatException if request failed | [
"Gets",
"all",
"users",
"the",
"client",
"is",
"currently",
"chatting",
"with"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L656-L678 | train | 215,148 |
carpedm20/fbchat | fbchat/_client.py | Client.searchForPages | def searchForPages(self, name, limit=10):
"""
Find and get page by its name
:param name: Name of the page
:return: :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_PAGE, params=params))
return [Page._from_graphql(node) for node in j[name]["pages"]["nodes"]] | python | def searchForPages(self, name, limit=10):
"""
Find and get page by its name
:param name: Name of the page
:return: :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_PAGE, params=params))
return [Page._from_graphql(node) for node in j[name]["pages"]["nodes"]] | [
"def",
"searchForPages",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"10",
")",
":",
"params",
"=",
"{",
"\"search\"",
":",
"name",
",",
"\"limit\"",
":",
"limit",
"}",
"j",
"=",
"self",
".",
"graphql_request",
"(",
"GraphQL",
"(",
"query",
"=",
"Gr... | Find and get page by its name
:param name: Name of the page
:return: :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed | [
"Find",
"and",
"get",
"page",
"by",
"its",
"name"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L695-L707 | train | 215,149 |
carpedm20/fbchat | fbchat/_client.py | Client.searchForGroups | def searchForGroups(self, name, limit=10):
"""
Find and get group thread by its name
:param name: Name of the group thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.Group` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_GROUP, params=params))
return [Group._from_graphql(node) for node in j["viewer"]["groups"]["nodes"]] | python | def searchForGroups(self, name, limit=10):
"""
Find and get group thread by its name
:param name: Name of the group thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.Group` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_GROUP, params=params))
return [Group._from_graphql(node) for node in j["viewer"]["groups"]["nodes"]] | [
"def",
"searchForGroups",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"10",
")",
":",
"params",
"=",
"{",
"\"search\"",
":",
"name",
",",
"\"limit\"",
":",
"limit",
"}",
"j",
"=",
"self",
".",
"graphql_request",
"(",
"GraphQL",
"(",
"query",
"=",
"G... | Find and get group thread by its name
:param name: Name of the group thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.Group` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed | [
"Find",
"and",
"get",
"group",
"thread",
"by",
"its",
"name"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L709-L722 | train | 215,150 |
carpedm20/fbchat | fbchat/_client.py | Client.searchForThreads | def searchForThreads(self, name, limit=10):
"""
Find and get a thread by its name
:param name: Name of the thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.User`, :class:`models.Group` and :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_THREAD, params=params))
rtn = []
for node in j[name]["threads"]["nodes"]:
if node["__typename"] == "User":
rtn.append(User._from_graphql(node))
elif node["__typename"] == "MessageThread":
# MessageThread => Group thread
rtn.append(Group._from_graphql(node))
elif node["__typename"] == "Page":
rtn.append(Page._from_graphql(node))
elif node["__typename"] == "Group":
# We don't handle Facebook "Groups"
pass
else:
log.warning(
"Unknown type {} in {}".format(repr(node["__typename"]), node)
)
return rtn | python | def searchForThreads(self, name, limit=10):
"""
Find and get a thread by its name
:param name: Name of the thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.User`, :class:`models.Group` and :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed
"""
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_THREAD, params=params))
rtn = []
for node in j[name]["threads"]["nodes"]:
if node["__typename"] == "User":
rtn.append(User._from_graphql(node))
elif node["__typename"] == "MessageThread":
# MessageThread => Group thread
rtn.append(Group._from_graphql(node))
elif node["__typename"] == "Page":
rtn.append(Page._from_graphql(node))
elif node["__typename"] == "Group":
# We don't handle Facebook "Groups"
pass
else:
log.warning(
"Unknown type {} in {}".format(repr(node["__typename"]), node)
)
return rtn | [
"def",
"searchForThreads",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"10",
")",
":",
"params",
"=",
"{",
"\"search\"",
":",
"name",
",",
"\"limit\"",
":",
"limit",
"}",
"j",
"=",
"self",
".",
"graphql_request",
"(",
"GraphQL",
"(",
"query",
"=",
"... | Find and get a thread by its name
:param name: Name of the thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.User`, :class:`models.Group` and :class:`models.Page` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed | [
"Find",
"and",
"get",
"a",
"thread",
"by",
"its",
"name"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L724-L754 | train | 215,151 |
carpedm20/fbchat | fbchat/_client.py | Client.searchForMessageIDs | def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None):
"""
Find and get message IDs by query
:param query: Text to search for
:param offset: Number of messages to skip
:param limit: Max. number of messages to retrieve
:param thread_id: User/Group ID to search in. See :ref:`intro_threads`
:type offset: int
:type limit: int
:return: Found Message IDs
:rtype: generator
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"query": query,
"snippetOffset": offset,
"snippetLimit": limit,
"identifier": "thread_fbid",
"thread_fbid": thread_id,
}
j = self._post(
self.req_url.SEARCH_MESSAGES, data, fix_request=True, as_json=True
)
result = j["payload"]["search_snippets"][query]
snippets = result[thread_id]["snippets"] if result.get(thread_id) else []
for snippet in snippets:
yield snippet["message_id"] | python | def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None):
"""
Find and get message IDs by query
:param query: Text to search for
:param offset: Number of messages to skip
:param limit: Max. number of messages to retrieve
:param thread_id: User/Group ID to search in. See :ref:`intro_threads`
:type offset: int
:type limit: int
:return: Found Message IDs
:rtype: generator
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"query": query,
"snippetOffset": offset,
"snippetLimit": limit,
"identifier": "thread_fbid",
"thread_fbid": thread_id,
}
j = self._post(
self.req_url.SEARCH_MESSAGES, data, fix_request=True, as_json=True
)
result = j["payload"]["search_snippets"][query]
snippets = result[thread_id]["snippets"] if result.get(thread_id) else []
for snippet in snippets:
yield snippet["message_id"] | [
"def",
"searchForMessageIDs",
"(",
"self",
",",
"query",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"5",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"dat... | Find and get message IDs by query
:param query: Text to search for
:param offset: Number of messages to skip
:param limit: Max. number of messages to retrieve
:param thread_id: User/Group ID to search in. See :ref:`intro_threads`
:type offset: int
:type limit: int
:return: Found Message IDs
:rtype: generator
:raises: FBchatException if request failed | [
"Find",
"and",
"get",
"message",
"IDs",
"by",
"query"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L756-L786 | train | 215,152 |
carpedm20/fbchat | fbchat/_client.py | Client.search | def search(self, query, fetch_messages=False, thread_limit=5, message_limit=5):
"""
Searches for messages in all threads
:param query: Text to search for
:param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only
:param thread_limit: Max. number of threads to retrieve
:param message_limit: Max. number of messages to retrieve
:type thread_limit: int
:type message_limit: int
:return: Dictionary with thread IDs as keys and generators to get messages as values
:rtype: generator
:raises: FBchatException if request failed
"""
data = {"query": query, "snippetLimit": thread_limit}
j = self._post(
self.req_url.SEARCH_MESSAGES, data, fix_request=True, as_json=True
)
result = j["payload"]["search_snippets"][query]
if fetch_messages:
search_method = self.searchForMessages
else:
search_method = self.searchForMessageIDs
return {
thread_id: search_method(query, limit=message_limit, thread_id=thread_id)
for thread_id in result
} | python | def search(self, query, fetch_messages=False, thread_limit=5, message_limit=5):
"""
Searches for messages in all threads
:param query: Text to search for
:param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only
:param thread_limit: Max. number of threads to retrieve
:param message_limit: Max. number of messages to retrieve
:type thread_limit: int
:type message_limit: int
:return: Dictionary with thread IDs as keys and generators to get messages as values
:rtype: generator
:raises: FBchatException if request failed
"""
data = {"query": query, "snippetLimit": thread_limit}
j = self._post(
self.req_url.SEARCH_MESSAGES, data, fix_request=True, as_json=True
)
result = j["payload"]["search_snippets"][query]
if fetch_messages:
search_method = self.searchForMessages
else:
search_method = self.searchForMessageIDs
return {
thread_id: search_method(query, limit=message_limit, thread_id=thread_id)
for thread_id in result
} | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"fetch_messages",
"=",
"False",
",",
"thread_limit",
"=",
"5",
",",
"message_limit",
"=",
"5",
")",
":",
"data",
"=",
"{",
"\"query\"",
":",
"query",
",",
"\"snippetLimit\"",
":",
"thread_limit",
"}",
"j",... | Searches for messages in all threads
:param query: Text to search for
:param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only
:param thread_limit: Max. number of threads to retrieve
:param message_limit: Max. number of messages to retrieve
:type thread_limit: int
:type message_limit: int
:return: Dictionary with thread IDs as keys and generators to get messages as values
:rtype: generator
:raises: FBchatException if request failed | [
"Searches",
"for",
"messages",
"in",
"all",
"threads"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L811-L839 | train | 215,153 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchUserInfo | def fetchUserInfo(self, *user_ids):
"""
Get users' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param user_ids: One or more user ID(s) to query
:return: :class:`models.User` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*user_ids)
users = {}
for id_, thread in threads.items():
if thread.type == ThreadType.USER:
users[id_] = thread
else:
raise FBchatUserError("Thread {} was not a user".format(thread))
return users | python | def fetchUserInfo(self, *user_ids):
"""
Get users' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param user_ids: One or more user ID(s) to query
:return: :class:`models.User` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*user_ids)
users = {}
for id_, thread in threads.items():
if thread.type == ThreadType.USER:
users[id_] = thread
else:
raise FBchatUserError("Thread {} was not a user".format(thread))
return users | [
"def",
"fetchUserInfo",
"(",
"self",
",",
"*",
"user_ids",
")",
":",
"threads",
"=",
"self",
".",
"fetchThreadInfo",
"(",
"*",
"user_ids",
")",
"users",
"=",
"{",
"}",
"for",
"id_",
",",
"thread",
"in",
"threads",
".",
"items",
"(",
")",
":",
"if",
... | Get users' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param user_ids: One or more user ID(s) to query
:return: :class:`models.User` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed | [
"Get",
"users",
"info",
"from",
"IDs",
"unordered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L878-L898 | train | 215,154 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchPageInfo | def fetchPageInfo(self, *page_ids):
"""
Get pages' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param page_ids: One or more page ID(s) to query
:return: :class:`models.Page` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*page_ids)
pages = {}
for id_, thread in threads.items():
if thread.type == ThreadType.PAGE:
pages[id_] = thread
else:
raise FBchatUserError("Thread {} was not a page".format(thread))
return pages | python | def fetchPageInfo(self, *page_ids):
"""
Get pages' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param page_ids: One or more page ID(s) to query
:return: :class:`models.Page` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*page_ids)
pages = {}
for id_, thread in threads.items():
if thread.type == ThreadType.PAGE:
pages[id_] = thread
else:
raise FBchatUserError("Thread {} was not a page".format(thread))
return pages | [
"def",
"fetchPageInfo",
"(",
"self",
",",
"*",
"page_ids",
")",
":",
"threads",
"=",
"self",
".",
"fetchThreadInfo",
"(",
"*",
"page_ids",
")",
"pages",
"=",
"{",
"}",
"for",
"id_",
",",
"thread",
"in",
"threads",
".",
"items",
"(",
")",
":",
"if",
... | Get pages' info from IDs, unordered
.. warning::
Sends two requests, to fetch all available info!
:param page_ids: One or more page ID(s) to query
:return: :class:`models.Page` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed | [
"Get",
"pages",
"info",
"from",
"IDs",
"unordered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L900-L920 | train | 215,155 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchGroupInfo | def fetchGroupInfo(self, *group_ids):
"""
Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*group_ids)
groups = {}
for id_, thread in threads.items():
if thread.type == ThreadType.GROUP:
groups[id_] = thread
else:
raise FBchatUserError("Thread {} was not a group".format(thread))
return groups | python | def fetchGroupInfo(self, *group_ids):
"""
Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threads = self.fetchThreadInfo(*group_ids)
groups = {}
for id_, thread in threads.items():
if thread.type == ThreadType.GROUP:
groups[id_] = thread
else:
raise FBchatUserError("Thread {} was not a group".format(thread))
return groups | [
"def",
"fetchGroupInfo",
"(",
"self",
",",
"*",
"group_ids",
")",
":",
"threads",
"=",
"self",
".",
"fetchThreadInfo",
"(",
"*",
"group_ids",
")",
"groups",
"=",
"{",
"}",
"for",
"id_",
",",
"thread",
"in",
"threads",
".",
"items",
"(",
")",
":",
"if... | Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed | [
"Get",
"groups",
"info",
"from",
"IDs",
"unordered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L922-L939 | train | 215,156 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchThreadInfo | def fetchThreadInfo(self, *thread_ids):
"""
Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
queries = []
for thread_id in thread_ids:
params = {
"id": thread_id,
"message_limit": 0,
"load_messages": False,
"load_read_receipts": False,
"before": None,
}
queries.append(GraphQL(doc_id="2147762685294928", params=params))
j = self.graphql_requests(*queries)
for i, entry in enumerate(j):
if entry.get("message_thread") is None:
# If you don't have an existing thread with this person, attempt to retrieve user data anyways
j[i]["message_thread"] = {
"thread_key": {"other_user_id": thread_ids[i]},
"thread_type": "ONE_TO_ONE",
}
pages_and_user_ids = [
k["message_thread"]["thread_key"]["other_user_id"]
for k in j
if k["message_thread"].get("thread_type") == "ONE_TO_ONE"
]
pages_and_users = {}
if len(pages_and_user_ids) != 0:
pages_and_users = self._fetchInfo(*pages_and_user_ids)
rtn = {}
for i, entry in enumerate(j):
entry = entry["message_thread"]
if entry.get("thread_type") == "GROUP":
_id = entry["thread_key"]["thread_fbid"]
rtn[_id] = Group._from_graphql(entry)
elif entry.get("thread_type") == "ONE_TO_ONE":
_id = entry["thread_key"]["other_user_id"]
if pages_and_users.get(_id) is None:
raise FBchatException("Could not fetch thread {}".format(_id))
entry.update(pages_and_users[_id])
if entry["type"] == ThreadType.USER:
rtn[_id] = User._from_graphql(entry)
else:
rtn[_id] = Page._from_graphql(entry)
else:
raise FBchatException(
"{} had an unknown thread type: {}".format(thread_ids[i], entry)
)
return rtn | python | def fetchThreadInfo(self, *thread_ids):
"""
Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
queries = []
for thread_id in thread_ids:
params = {
"id": thread_id,
"message_limit": 0,
"load_messages": False,
"load_read_receipts": False,
"before": None,
}
queries.append(GraphQL(doc_id="2147762685294928", params=params))
j = self.graphql_requests(*queries)
for i, entry in enumerate(j):
if entry.get("message_thread") is None:
# If you don't have an existing thread with this person, attempt to retrieve user data anyways
j[i]["message_thread"] = {
"thread_key": {"other_user_id": thread_ids[i]},
"thread_type": "ONE_TO_ONE",
}
pages_and_user_ids = [
k["message_thread"]["thread_key"]["other_user_id"]
for k in j
if k["message_thread"].get("thread_type") == "ONE_TO_ONE"
]
pages_and_users = {}
if len(pages_and_user_ids) != 0:
pages_and_users = self._fetchInfo(*pages_and_user_ids)
rtn = {}
for i, entry in enumerate(j):
entry = entry["message_thread"]
if entry.get("thread_type") == "GROUP":
_id = entry["thread_key"]["thread_fbid"]
rtn[_id] = Group._from_graphql(entry)
elif entry.get("thread_type") == "ONE_TO_ONE":
_id = entry["thread_key"]["other_user_id"]
if pages_and_users.get(_id) is None:
raise FBchatException("Could not fetch thread {}".format(_id))
entry.update(pages_and_users[_id])
if entry["type"] == ThreadType.USER:
rtn[_id] = User._from_graphql(entry)
else:
rtn[_id] = Page._from_graphql(entry)
else:
raise FBchatException(
"{} had an unknown thread type: {}".format(thread_ids[i], entry)
)
return rtn | [
"def",
"fetchThreadInfo",
"(",
"self",
",",
"*",
"thread_ids",
")",
":",
"queries",
"=",
"[",
"]",
"for",
"thread_id",
"in",
"thread_ids",
":",
"params",
"=",
"{",
"\"id\"",
":",
"thread_id",
",",
"\"message_limit\"",
":",
"0",
",",
"\"load_messages\"",
":... | Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed | [
"Get",
"threads",
"info",
"from",
"IDs",
"unordered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L941-L1003 | train | 215,157 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchThreadMessages | def fetchThreadMessages(self, thread_id=None, limit=20, before=None):
"""
Get the last messages in a thread
:param thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
:param limit: Max. number of messages to retrieve
:param before: A timestamp, indicating from which point to retrieve messages
:type limit: int
:type before: int
:return: :class:`models.Message` objects
:rtype: list
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
params = {
"id": thread_id,
"message_limit": limit,
"load_messages": True,
"load_read_receipts": True,
"before": before,
}
j = self.graphql_request(GraphQL(doc_id="1860982147341344", params=params))
if j.get("message_thread") is None:
raise FBchatException("Could not fetch thread {}: {}".format(thread_id, j))
messages = [
Message._from_graphql(message)
for message in j["message_thread"]["messages"]["nodes"]
]
messages.reverse()
read_receipts = j["message_thread"]["read_receipts"]["nodes"]
for message in messages:
for receipt in read_receipts:
if int(receipt["watermark"]) >= int(message.timestamp):
message.read_by.append(receipt["actor"]["id"])
return messages | python | def fetchThreadMessages(self, thread_id=None, limit=20, before=None):
"""
Get the last messages in a thread
:param thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
:param limit: Max. number of messages to retrieve
:param before: A timestamp, indicating from which point to retrieve messages
:type limit: int
:type before: int
:return: :class:`models.Message` objects
:rtype: list
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
params = {
"id": thread_id,
"message_limit": limit,
"load_messages": True,
"load_read_receipts": True,
"before": before,
}
j = self.graphql_request(GraphQL(doc_id="1860982147341344", params=params))
if j.get("message_thread") is None:
raise FBchatException("Could not fetch thread {}: {}".format(thread_id, j))
messages = [
Message._from_graphql(message)
for message in j["message_thread"]["messages"]["nodes"]
]
messages.reverse()
read_receipts = j["message_thread"]["read_receipts"]["nodes"]
for message in messages:
for receipt in read_receipts:
if int(receipt["watermark"]) >= int(message.timestamp):
message.read_by.append(receipt["actor"]["id"])
return messages | [
"def",
"fetchThreadMessages",
"(",
"self",
",",
"thread_id",
"=",
"None",
",",
"limit",
"=",
"20",
",",
"before",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"params",
"=",
... | Get the last messages in a thread
:param thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
:param limit: Max. number of messages to retrieve
:param before: A timestamp, indicating from which point to retrieve messages
:type limit: int
:type before: int
:return: :class:`models.Message` objects
:rtype: list
:raises: FBchatException if request failed | [
"Get",
"the",
"last",
"messages",
"in",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1005-L1045 | train | 215,158 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchThreadList | def fetchThreadList(
self, offset=None, limit=20, thread_location=ThreadLocation.INBOX, before=None
):
"""Get thread list of your facebook account
:param offset: Deprecated. Do not use!
:param limit: Max. number of threads to retrieve. Capped at 20
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: A timestamp (in milliseconds), indicating from which point to retrieve threads
:type limit: int
:type before: int
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""
if offset is not None:
log.warning(
"Using `offset` in `fetchThreadList` is no longer supported, "
"since Facebook migrated to the use of GraphQL in this request. "
"Use `before` instead."
)
if limit > 20 or limit < 1:
raise FBchatUserError("`limit` should be between 1 and 20")
if thread_location in ThreadLocation:
loc_str = thread_location.value
else:
raise FBchatUserError('"thread_location" must be a value of ThreadLocation')
params = {
"limit": limit,
"tags": [loc_str],
"before": before,
"includeDeliveryReceipts": True,
"includeSeqID": False,
}
j = self.graphql_request(GraphQL(doc_id="1349387578499440", params=params))
rtn = []
for node in j["viewer"]["message_threads"]["nodes"]:
_type = node.get("thread_type")
if _type == "GROUP":
rtn.append(Group._from_graphql(node))
elif _type == "ONE_TO_ONE":
rtn.append(User._from_thread_fetch(node))
else:
raise FBchatException(
"Unknown thread type: {}, with data: {}".format(_type, node)
)
return rtn | python | def fetchThreadList(
self, offset=None, limit=20, thread_location=ThreadLocation.INBOX, before=None
):
"""Get thread list of your facebook account
:param offset: Deprecated. Do not use!
:param limit: Max. number of threads to retrieve. Capped at 20
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: A timestamp (in milliseconds), indicating from which point to retrieve threads
:type limit: int
:type before: int
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""
if offset is not None:
log.warning(
"Using `offset` in `fetchThreadList` is no longer supported, "
"since Facebook migrated to the use of GraphQL in this request. "
"Use `before` instead."
)
if limit > 20 or limit < 1:
raise FBchatUserError("`limit` should be between 1 and 20")
if thread_location in ThreadLocation:
loc_str = thread_location.value
else:
raise FBchatUserError('"thread_location" must be a value of ThreadLocation')
params = {
"limit": limit,
"tags": [loc_str],
"before": before,
"includeDeliveryReceipts": True,
"includeSeqID": False,
}
j = self.graphql_request(GraphQL(doc_id="1349387578499440", params=params))
rtn = []
for node in j["viewer"]["message_threads"]["nodes"]:
_type = node.get("thread_type")
if _type == "GROUP":
rtn.append(Group._from_graphql(node))
elif _type == "ONE_TO_ONE":
rtn.append(User._from_thread_fetch(node))
else:
raise FBchatException(
"Unknown thread type: {}, with data: {}".format(_type, node)
)
return rtn | [
"def",
"fetchThreadList",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"20",
",",
"thread_location",
"=",
"ThreadLocation",
".",
"INBOX",
",",
"before",
"=",
"None",
")",
":",
"if",
"offset",
"is",
"not",
"None",
":",
"log",
".",
"warnin... | Get thread list of your facebook account
:param offset: Deprecated. Do not use!
:param limit: Max. number of threads to retrieve. Capped at 20
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: A timestamp (in milliseconds), indicating from which point to retrieve threads
:type limit: int
:type before: int
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed | [
"Get",
"thread",
"list",
"of",
"your",
"facebook",
"account"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1047-L1097 | train | 215,159 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchUnread | def fetchUnread(self):
"""
Get the unread thread list
:return: List of unread thread ids
:rtype: list
:raises: FBchatException if request failed
"""
form = {
"folders[0]": "inbox",
"client": "mercury",
"last_action_timestamp": now() - 60 * 1000
# 'last_action_timestamp': 0
}
j = self._post(
self.req_url.UNREAD_THREADS, form, fix_request=True, as_json=True
)
payload = j["payload"]["unread_thread_fbids"][0]
return payload["thread_fbids"] + payload["other_user_fbids"] | python | def fetchUnread(self):
"""
Get the unread thread list
:return: List of unread thread ids
:rtype: list
:raises: FBchatException if request failed
"""
form = {
"folders[0]": "inbox",
"client": "mercury",
"last_action_timestamp": now() - 60 * 1000
# 'last_action_timestamp': 0
}
j = self._post(
self.req_url.UNREAD_THREADS, form, fix_request=True, as_json=True
)
payload = j["payload"]["unread_thread_fbids"][0]
return payload["thread_fbids"] + payload["other_user_fbids"] | [
"def",
"fetchUnread",
"(",
"self",
")",
":",
"form",
"=",
"{",
"\"folders[0]\"",
":",
"\"inbox\"",
",",
"\"client\"",
":",
"\"mercury\"",
",",
"\"last_action_timestamp\"",
":",
"now",
"(",
")",
"-",
"60",
"*",
"1000",
"# 'last_action_timestamp': 0",
"}",
"j",
... | Get the unread thread list
:return: List of unread thread ids
:rtype: list
:raises: FBchatException if request failed | [
"Get",
"the",
"unread",
"thread",
"list"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1099-L1118 | train | 215,160 |
carpedm20/fbchat | fbchat/_client.py | Client.fetchImageUrl | def fetchImageUrl(self, image_id):
"""Fetches the url to the original image from an image attachment ID
:param image_id: The image you want to fethc
:type image_id: str
:return: An url where you can download the original image
:rtype: str
:raises: FBchatException if request failed
"""
image_id = str(image_id)
data = {"photo_id": str(image_id)}
j = self._get(
ReqUrl.ATTACHMENT_PHOTO, query=data, fix_request=True, as_json=True
)
url = get_jsmods_require(j, 3)
if url is None:
raise FBchatException("Could not fetch image url from: {}".format(j))
return url | python | def fetchImageUrl(self, image_id):
"""Fetches the url to the original image from an image attachment ID
:param image_id: The image you want to fethc
:type image_id: str
:return: An url where you can download the original image
:rtype: str
:raises: FBchatException if request failed
"""
image_id = str(image_id)
data = {"photo_id": str(image_id)}
j = self._get(
ReqUrl.ATTACHMENT_PHOTO, query=data, fix_request=True, as_json=True
)
url = get_jsmods_require(j, 3)
if url is None:
raise FBchatException("Could not fetch image url from: {}".format(j))
return url | [
"def",
"fetchImageUrl",
"(",
"self",
",",
"image_id",
")",
":",
"image_id",
"=",
"str",
"(",
"image_id",
")",
"data",
"=",
"{",
"\"photo_id\"",
":",
"str",
"(",
"image_id",
")",
"}",
"j",
"=",
"self",
".",
"_get",
"(",
"ReqUrl",
".",
"ATTACHMENT_PHOTO"... | Fetches the url to the original image from an image attachment ID
:param image_id: The image you want to fethc
:type image_id: str
:return: An url where you can download the original image
:rtype: str
:raises: FBchatException if request failed | [
"Fetches",
"the",
"url",
"to",
"the",
"original",
"image",
"from",
"an",
"image",
"attachment",
"ID"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1135-L1153 | train | 215,161 |
carpedm20/fbchat | fbchat/_client.py | Client._getSendData | def _getSendData(self, message=None, thread_id=None, thread_type=ThreadType.USER):
"""Returns the data needed to send a request to `SendURL`"""
messageAndOTID = generateOfflineThreadingID()
timestamp = now()
data = {
"client": "mercury",
"author": "fbid:{}".format(self._uid),
"timestamp": timestamp,
"source": "source:chat:web",
"offline_threading_id": messageAndOTID,
"message_id": messageAndOTID,
"threading_id": generateMessageID(self._client_id),
"ephemeral_ttl_mode:": "0",
}
# Set recipient
if thread_type in [ThreadType.USER, ThreadType.PAGE]:
data["other_user_fbid"] = thread_id
elif thread_type == ThreadType.GROUP:
data["thread_fbid"] = thread_id
if message is None:
message = Message()
if message.text or message.sticker or message.emoji_size:
data["action_type"] = "ma-type:user-generated-message"
if message.text:
data["body"] = message.text
for i, mention in enumerate(message.mentions):
data["profile_xmd[{}][id]".format(i)] = mention.thread_id
data["profile_xmd[{}][offset]".format(i)] = mention.offset
data["profile_xmd[{}][length]".format(i)] = mention.length
data["profile_xmd[{}][type]".format(i)] = "p"
if message.emoji_size:
if message.text:
data["tags[0]"] = "hot_emoji_size:" + message.emoji_size.name.lower()
else:
data["sticker_id"] = message.emoji_size.value
if message.sticker:
data["sticker_id"] = message.sticker.uid
if message.quick_replies:
xmd = {"quick_replies": []}
for quick_reply in message.quick_replies:
q = dict()
q["content_type"] = quick_reply._type
q["payload"] = quick_reply.payload
q["external_payload"] = quick_reply.external_payload
q["data"] = quick_reply.data
if quick_reply.is_response:
q["ignore_for_webhook"] = False
if isinstance(quick_reply, QuickReplyText):
q["title"] = quick_reply.title
if not isinstance(quick_reply, QuickReplyLocation):
q["image_url"] = quick_reply.image_url
xmd["quick_replies"].append(q)
if len(message.quick_replies) == 1 and message.quick_replies[0].is_response:
xmd["quick_replies"] = xmd["quick_replies"][0]
data["platform_xmd"] = json.dumps(xmd)
if message.reply_to_id:
data["replied_to_message_id"] = message.reply_to_id
return data | python | def _getSendData(self, message=None, thread_id=None, thread_type=ThreadType.USER):
"""Returns the data needed to send a request to `SendURL`"""
messageAndOTID = generateOfflineThreadingID()
timestamp = now()
data = {
"client": "mercury",
"author": "fbid:{}".format(self._uid),
"timestamp": timestamp,
"source": "source:chat:web",
"offline_threading_id": messageAndOTID,
"message_id": messageAndOTID,
"threading_id": generateMessageID(self._client_id),
"ephemeral_ttl_mode:": "0",
}
# Set recipient
if thread_type in [ThreadType.USER, ThreadType.PAGE]:
data["other_user_fbid"] = thread_id
elif thread_type == ThreadType.GROUP:
data["thread_fbid"] = thread_id
if message is None:
message = Message()
if message.text or message.sticker or message.emoji_size:
data["action_type"] = "ma-type:user-generated-message"
if message.text:
data["body"] = message.text
for i, mention in enumerate(message.mentions):
data["profile_xmd[{}][id]".format(i)] = mention.thread_id
data["profile_xmd[{}][offset]".format(i)] = mention.offset
data["profile_xmd[{}][length]".format(i)] = mention.length
data["profile_xmd[{}][type]".format(i)] = "p"
if message.emoji_size:
if message.text:
data["tags[0]"] = "hot_emoji_size:" + message.emoji_size.name.lower()
else:
data["sticker_id"] = message.emoji_size.value
if message.sticker:
data["sticker_id"] = message.sticker.uid
if message.quick_replies:
xmd = {"quick_replies": []}
for quick_reply in message.quick_replies:
q = dict()
q["content_type"] = quick_reply._type
q["payload"] = quick_reply.payload
q["external_payload"] = quick_reply.external_payload
q["data"] = quick_reply.data
if quick_reply.is_response:
q["ignore_for_webhook"] = False
if isinstance(quick_reply, QuickReplyText):
q["title"] = quick_reply.title
if not isinstance(quick_reply, QuickReplyLocation):
q["image_url"] = quick_reply.image_url
xmd["quick_replies"].append(q)
if len(message.quick_replies) == 1 and message.quick_replies[0].is_response:
xmd["quick_replies"] = xmd["quick_replies"][0]
data["platform_xmd"] = json.dumps(xmd)
if message.reply_to_id:
data["replied_to_message_id"] = message.reply_to_id
return data | [
"def",
"_getSendData",
"(",
"self",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"messageAndOTID",
"=",
"generateOfflineThreadingID",
"(",
")",
"timestamp",
"=",
"now",
"(",
")",
... | Returns the data needed to send a request to `SendURL` | [
"Returns",
"the",
"data",
"needed",
"to",
"send",
"a",
"request",
"to",
"SendURL"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1247-L1314 | train | 215,162 |
carpedm20/fbchat | fbchat/_client.py | Client._doSendRequest | def _doSendRequest(self, data, get_thread_id=False):
"""Sends the data to `SendURL`, and returns the message ID or None on failure"""
j = self._post(self.req_url.SEND, data, fix_request=True, as_json=True)
# update JS token if received in response
fb_dtsg = get_jsmods_require(j, 2)
if fb_dtsg is not None:
self._payload_default["fb_dtsg"] = fb_dtsg
try:
message_ids = [
(action["message_id"], action["thread_fbid"])
for action in j["payload"]["actions"]
if "message_id" in action
]
if len(message_ids) != 1:
log.warning("Got multiple message ids' back: {}".format(message_ids))
if get_thread_id:
return message_ids[0]
else:
return message_ids[0][0]
except (KeyError, IndexError, TypeError) as e:
raise FBchatException(
"Error when sending message: "
"No message IDs could be found: {}".format(j)
) | python | def _doSendRequest(self, data, get_thread_id=False):
"""Sends the data to `SendURL`, and returns the message ID or None on failure"""
j = self._post(self.req_url.SEND, data, fix_request=True, as_json=True)
# update JS token if received in response
fb_dtsg = get_jsmods_require(j, 2)
if fb_dtsg is not None:
self._payload_default["fb_dtsg"] = fb_dtsg
try:
message_ids = [
(action["message_id"], action["thread_fbid"])
for action in j["payload"]["actions"]
if "message_id" in action
]
if len(message_ids) != 1:
log.warning("Got multiple message ids' back: {}".format(message_ids))
if get_thread_id:
return message_ids[0]
else:
return message_ids[0][0]
except (KeyError, IndexError, TypeError) as e:
raise FBchatException(
"Error when sending message: "
"No message IDs could be found: {}".format(j)
) | [
"def",
"_doSendRequest",
"(",
"self",
",",
"data",
",",
"get_thread_id",
"=",
"False",
")",
":",
"j",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"SEND",
",",
"data",
",",
"fix_request",
"=",
"True",
",",
"as_json",
"=",
"True",
")",... | Sends the data to `SendURL`, and returns the message ID or None on failure | [
"Sends",
"the",
"data",
"to",
"SendURL",
"and",
"returns",
"the",
"message",
"ID",
"or",
"None",
"on",
"failure"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1316-L1341 | train | 215,163 |
carpedm20/fbchat | fbchat/_client.py | Client.send | def send(self, message, thread_id=None, thread_type=ThreadType.USER):
"""
Sends a message to a thread
:param message: Message to send
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(
message=message, thread_id=thread_id, thread_type=thread_type
)
return self._doSendRequest(data) | python | def send(self, message, thread_id=None, thread_type=ThreadType.USER):
"""
Sends a message to a thread
:param message: Message to send
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(
message=message, thread_id=thread_id, thread_type=thread_type
)
return self._doSendRequest(data) | [
"def",
"send",
"(",
"self",
",",
"message",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"thread_type",
")",
"data",
"... | Sends a message to a thread
:param message: Message to send
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed | [
"Sends",
"a",
"message",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1343-L1359 | train | 215,164 |
carpedm20/fbchat | fbchat/_client.py | Client.wave | def wave(self, wave_first=True, thread_id=None, thread_type=None):
"""
Says hello with a wave to a thread!
:param wave_first: Whether to wave first or wave back
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(thread_id=thread_id, thread_type=thread_type)
data["action_type"] = "ma-type:user-generated-message"
data["lightweight_action_attachment[lwa_state]"] = (
"INITIATED" if wave_first else "RECIPROCATED"
)
data["lightweight_action_attachment[lwa_type]"] = "WAVE"
if thread_type == ThreadType.USER:
data["specific_to_list[0]"] = "fbid:{}".format(thread_id)
return self._doSendRequest(data) | python | def wave(self, wave_first=True, thread_id=None, thread_type=None):
"""
Says hello with a wave to a thread!
:param wave_first: Whether to wave first or wave back
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(thread_id=thread_id, thread_type=thread_type)
data["action_type"] = "ma-type:user-generated-message"
data["lightweight_action_attachment[lwa_state]"] = (
"INITIATED" if wave_first else "RECIPROCATED"
)
data["lightweight_action_attachment[lwa_type]"] = "WAVE"
if thread_type == ThreadType.USER:
data["specific_to_list[0]"] = "fbid:{}".format(thread_id)
return self._doSendRequest(data) | [
"def",
"wave",
"(",
"self",
",",
"wave_first",
"=",
"True",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"thread_type",
")",
"data",
"=",... | Says hello with a wave to a thread!
:param wave_first: Whether to wave first or wave back
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed | [
"Says",
"hello",
"with",
"a",
"wave",
"to",
"a",
"thread!"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1385-L1405 | train | 215,165 |
carpedm20/fbchat | fbchat/_client.py | Client.quickReply | def quickReply(self, quick_reply, payload=None, thread_id=None, thread_type=None):
"""
Replies to a chosen quick reply
:param quick_reply: Quick reply to reply to
:param payload: Optional answer to the quick reply
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type quick_reply: models.QuickReply
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
quick_reply.is_response = True
if isinstance(quick_reply, QuickReplyText):
return self.send(
Message(text=quick_reply.title, quick_replies=[quick_reply])
)
elif isinstance(quick_reply, QuickReplyLocation):
if not isinstance(payload, LocationAttachment):
raise ValueError(
"Payload must be an instance of `fbchat.models.LocationAttachment`"
)
return self.sendLocation(
payload, thread_id=thread_id, thread_type=thread_type
)
elif isinstance(quick_reply, QuickReplyEmail):
if not payload:
payload = self.getEmails()[0]
quick_reply.external_payload = quick_reply.payload
quick_reply.payload = payload
return self.send(Message(text=payload, quick_replies=[quick_reply]))
elif isinstance(quick_reply, QuickReplyPhoneNumber):
if not payload:
payload = self.getPhoneNumbers()[0]
quick_reply.external_payload = quick_reply.payload
quick_reply.payload = payload
return self.send(Message(text=payload, quick_replies=[quick_reply])) | python | def quickReply(self, quick_reply, payload=None, thread_id=None, thread_type=None):
"""
Replies to a chosen quick reply
:param quick_reply: Quick reply to reply to
:param payload: Optional answer to the quick reply
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type quick_reply: models.QuickReply
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
quick_reply.is_response = True
if isinstance(quick_reply, QuickReplyText):
return self.send(
Message(text=quick_reply.title, quick_replies=[quick_reply])
)
elif isinstance(quick_reply, QuickReplyLocation):
if not isinstance(payload, LocationAttachment):
raise ValueError(
"Payload must be an instance of `fbchat.models.LocationAttachment`"
)
return self.sendLocation(
payload, thread_id=thread_id, thread_type=thread_type
)
elif isinstance(quick_reply, QuickReplyEmail):
if not payload:
payload = self.getEmails()[0]
quick_reply.external_payload = quick_reply.payload
quick_reply.payload = payload
return self.send(Message(text=payload, quick_replies=[quick_reply]))
elif isinstance(quick_reply, QuickReplyPhoneNumber):
if not payload:
payload = self.getPhoneNumbers()[0]
quick_reply.external_payload = quick_reply.payload
quick_reply.payload = payload
return self.send(Message(text=payload, quick_replies=[quick_reply])) | [
"def",
"quickReply",
"(",
"self",
",",
"quick_reply",
",",
"payload",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
")",
":",
"quick_reply",
".",
"is_response",
"=",
"True",
"if",
"isinstance",
"(",
"quick_reply",
",",
"Quick... | Replies to a chosen quick reply
:param quick_reply: Quick reply to reply to
:param payload: Optional answer to the quick reply
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type quick_reply: models.QuickReply
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed | [
"Replies",
"to",
"a",
"chosen",
"quick",
"reply"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1407-L1444 | train | 215,166 |
carpedm20/fbchat | fbchat/_client.py | Client.sendLocation | def sendLocation(self, location, message=None, thread_id=None, thread_type=None):
"""
Sends a given location to a thread as the user's current location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
self._sendLocation(
location=location,
current=True,
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | python | def sendLocation(self, location, message=None, thread_id=None, thread_type=None):
"""
Sends a given location to a thread as the user's current location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
self._sendLocation(
location=location,
current=True,
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | [
"def",
"sendLocation",
"(",
"self",
",",
"location",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
")",
":",
"self",
".",
"_sendLocation",
"(",
"location",
"=",
"location",
",",
"current",
"=",
"True",
",",
... | Sends a given location to a thread as the user's current location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed | [
"Sends",
"a",
"given",
"location",
"to",
"a",
"thread",
"as",
"the",
"user",
"s",
"current",
"location"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1469-L1489 | train | 215,167 |
carpedm20/fbchat | fbchat/_client.py | Client.sendPinnedLocation | def sendPinnedLocation(
self, location, message=None, thread_id=None, thread_type=None
):
"""
Sends a given location to a thread as a pinned location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
self._sendLocation(
location=location,
current=False,
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | python | def sendPinnedLocation(
self, location, message=None, thread_id=None, thread_type=None
):
"""
Sends a given location to a thread as a pinned location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed
"""
self._sendLocation(
location=location,
current=False,
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | [
"def",
"sendPinnedLocation",
"(",
"self",
",",
"location",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
")",
":",
"self",
".",
"_sendLocation",
"(",
"location",
"=",
"location",
",",
"current",
"=",
"False",
... | Sends a given location to a thread as a pinned location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachment
:type message: models.Message
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent message
:raises: FBchatException if request failed | [
"Sends",
"a",
"given",
"location",
"to",
"a",
"thread",
"as",
"a",
"pinned",
"location"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1491-L1513 | train | 215,168 |
carpedm20/fbchat | fbchat/_client.py | Client._upload | def _upload(self, files, voice_clip=False):
"""
Uploads files to Facebook
`files` should be a list of files that requests can upload, see:
http://docs.python-requests.org/en/master/api/#requests.request
Returns a list of tuples with a file's ID and mimetype
"""
file_dict = {"upload_{}".format(i): f for i, f in enumerate(files)}
data = {"voice_clip": voice_clip}
j = self._postFile(
self.req_url.UPLOAD,
files=file_dict,
query=data,
fix_request=True,
as_json=True,
)
if len(j["payload"]["metadata"]) != len(files):
raise FBchatException(
"Some files could not be uploaded: {}, {}".format(j, files)
)
return [
(data[mimetype_to_key(data["filetype"])], data["filetype"])
for data in j["payload"]["metadata"]
] | python | def _upload(self, files, voice_clip=False):
"""
Uploads files to Facebook
`files` should be a list of files that requests can upload, see:
http://docs.python-requests.org/en/master/api/#requests.request
Returns a list of tuples with a file's ID and mimetype
"""
file_dict = {"upload_{}".format(i): f for i, f in enumerate(files)}
data = {"voice_clip": voice_clip}
j = self._postFile(
self.req_url.UPLOAD,
files=file_dict,
query=data,
fix_request=True,
as_json=True,
)
if len(j["payload"]["metadata"]) != len(files):
raise FBchatException(
"Some files could not be uploaded: {}, {}".format(j, files)
)
return [
(data[mimetype_to_key(data["filetype"])], data["filetype"])
for data in j["payload"]["metadata"]
] | [
"def",
"_upload",
"(",
"self",
",",
"files",
",",
"voice_clip",
"=",
"False",
")",
":",
"file_dict",
"=",
"{",
"\"upload_{}\"",
".",
"format",
"(",
"i",
")",
":",
"f",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"files",
")",
"}",
"data",
"=",
... | Uploads files to Facebook
`files` should be a list of files that requests can upload, see:
http://docs.python-requests.org/en/master/api/#requests.request
Returns a list of tuples with a file's ID and mimetype | [
"Uploads",
"files",
"to",
"Facebook"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1515-L1544 | train | 215,169 |
carpedm20/fbchat | fbchat/_client.py | Client._sendFiles | def _sendFiles(
self, files, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends files from file IDs to a thread
`files` should be a list of tuples, with a file's ID and mimetype
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(
message=self._oldMessage(message),
thread_id=thread_id,
thread_type=thread_type,
)
data["action_type"] = "ma-type:user-generated-message"
data["has_attachment"] = True
for i, (file_id, mimetype) in enumerate(files):
data["{}s[{}]".format(mimetype_to_key(mimetype), i)] = file_id
return self._doSendRequest(data) | python | def _sendFiles(
self, files, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends files from file IDs to a thread
`files` should be a list of tuples, with a file's ID and mimetype
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = self._getSendData(
message=self._oldMessage(message),
thread_id=thread_id,
thread_type=thread_type,
)
data["action_type"] = "ma-type:user-generated-message"
data["has_attachment"] = True
for i, (file_id, mimetype) in enumerate(files):
data["{}s[{}]".format(mimetype_to_key(mimetype), i)] = file_id
return self._doSendRequest(data) | [
"def",
"_sendFiles",
"(",
"self",
",",
"files",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
"... | Sends files from file IDs to a thread
`files` should be a list of tuples, with a file's ID and mimetype | [
"Sends",
"files",
"from",
"file",
"IDs",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1546-L1567 | train | 215,170 |
carpedm20/fbchat | fbchat/_client.py | Client.sendRemoteFiles | def sendRemoteFiles(
self, file_urls, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends files from URLs to a thread
:param file_urls: URLs of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
file_urls = require_list(file_urls)
files = self._upload(get_files_from_urls(file_urls))
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | python | def sendRemoteFiles(
self, file_urls, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends files from URLs to a thread
:param file_urls: URLs of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
file_urls = require_list(file_urls)
files = self._upload(get_files_from_urls(file_urls))
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | [
"def",
"sendRemoteFiles",
"(",
"self",
",",
"file_urls",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"file_urls",
"=",
"require_list",
"(",
"file_urls",
")",
"files",
"=",
"self"... | Sends files from URLs to a thread
:param file_urls: URLs of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed | [
"Sends",
"files",
"from",
"URLs",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1569-L1587 | train | 215,171 |
carpedm20/fbchat | fbchat/_client.py | Client.sendLocalFiles | def sendLocalFiles(
self, file_paths, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends local files to a thread
:param file_paths: Paths of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
file_paths = require_list(file_paths)
with get_files_from_paths(file_paths) as x:
files = self._upload(x)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | python | def sendLocalFiles(
self, file_paths, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends local files to a thread
:param file_paths: Paths of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
file_paths = require_list(file_paths)
with get_files_from_paths(file_paths) as x:
files = self._upload(x)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | [
"def",
"sendLocalFiles",
"(",
"self",
",",
"file_paths",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"file_paths",
"=",
"require_list",
"(",
"file_paths",
")",
"with",
"get_files_f... | Sends local files to a thread
:param file_paths: Paths of files to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed | [
"Sends",
"local",
"files",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1589-L1608 | train | 215,172 |
carpedm20/fbchat | fbchat/_client.py | Client.sendRemoteVoiceClips | def sendRemoteVoiceClips(
self, clip_urls, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends voice clips from URLs to a thread
:param clip_urls: URLs of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
clip_urls = require_list(clip_urls)
files = self._upload(get_files_from_urls(clip_urls), voice_clip=True)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | python | def sendRemoteVoiceClips(
self, clip_urls, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends voice clips from URLs to a thread
:param clip_urls: URLs of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
clip_urls = require_list(clip_urls)
files = self._upload(get_files_from_urls(clip_urls), voice_clip=True)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | [
"def",
"sendRemoteVoiceClips",
"(",
"self",
",",
"clip_urls",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"clip_urls",
"=",
"require_list",
"(",
"clip_urls",
")",
"files",
"=",
"... | Sends voice clips from URLs to a thread
:param clip_urls: URLs of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed | [
"Sends",
"voice",
"clips",
"from",
"URLs",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1610-L1628 | train | 215,173 |
carpedm20/fbchat | fbchat/_client.py | Client.sendLocalVoiceClips | def sendLocalVoiceClips(
self, clip_paths, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends local voice clips to a thread
:param clip_paths: Paths of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
clip_paths = require_list(clip_paths)
with get_files_from_paths(clip_paths) as x:
files = self._upload(x, voice_clip=True)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | python | def sendLocalVoiceClips(
self, clip_paths, message=None, thread_id=None, thread_type=ThreadType.USER
):
"""
Sends local voice clips to a thread
:param clip_paths: Paths of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed
"""
clip_paths = require_list(clip_paths)
with get_files_from_paths(clip_paths) as x:
files = self._upload(x, voice_clip=True)
return self._sendFiles(
files=files, message=message, thread_id=thread_id, thread_type=thread_type
) | [
"def",
"sendLocalVoiceClips",
"(",
"self",
",",
"clip_paths",
",",
"message",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"clip_paths",
"=",
"require_list",
"(",
"clip_paths",
")",
"with",
"get_fi... | Sends local voice clips to a thread
:param clip_paths: Paths of clips to upload and send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:return: :ref:`Message ID <intro_message_ids>` of the sent files
:raises: FBchatException if request failed | [
"Sends",
"local",
"voice",
"clips",
"to",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1630-L1649 | train | 215,174 |
carpedm20/fbchat | fbchat/_client.py | Client.forwardAttachment | def forwardAttachment(self, attachment_id, thread_id=None):
"""
Forwards an attachment
:param attachment_id: Attachment ID to forward
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"attachment_id": attachment_id,
"recipient_map[{}]".format(generateOfflineThreadingID()): thread_id,
}
j = self._post(
self.req_url.FORWARD_ATTACHMENT, data, fix_request=True, as_json=True
) | python | def forwardAttachment(self, attachment_id, thread_id=None):
"""
Forwards an attachment
:param attachment_id: Attachment ID to forward
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"attachment_id": attachment_id,
"recipient_map[{}]".format(generateOfflineThreadingID()): thread_id,
}
j = self._post(
self.req_url.FORWARD_ATTACHMENT, data, fix_request=True, as_json=True
) | [
"def",
"forwardAttachment",
"(",
"self",
",",
"attachment_id",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"attachment_id\"",
":",
"attachme... | Forwards an attachment
:param attachment_id: Attachment ID to forward
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Forwards",
"an",
"attachment"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1699-L1714 | train | 215,175 |
carpedm20/fbchat | fbchat/_client.py | Client.createGroup | def createGroup(self, message, user_ids):
"""
Creates a group with the given ids
:param message: The initial message
:param user_ids: A list of users to create the group with.
:return: ID of the new group
:raises: FBchatException if request failed
"""
data = self._getSendData(message=self._oldMessage(message))
if len(user_ids) < 2:
raise FBchatUserError("Error when creating group: Not enough participants")
for i, user_id in enumerate(user_ids + [self._uid]):
data["specific_to_list[{}]".format(i)] = "fbid:{}".format(user_id)
message_id, thread_id = self._doSendRequest(data, get_thread_id=True)
if not thread_id:
raise FBchatException(
"Error when creating group: No thread_id could be found"
)
return thread_id | python | def createGroup(self, message, user_ids):
"""
Creates a group with the given ids
:param message: The initial message
:param user_ids: A list of users to create the group with.
:return: ID of the new group
:raises: FBchatException if request failed
"""
data = self._getSendData(message=self._oldMessage(message))
if len(user_ids) < 2:
raise FBchatUserError("Error when creating group: Not enough participants")
for i, user_id in enumerate(user_ids + [self._uid]):
data["specific_to_list[{}]".format(i)] = "fbid:{}".format(user_id)
message_id, thread_id = self._doSendRequest(data, get_thread_id=True)
if not thread_id:
raise FBchatException(
"Error when creating group: No thread_id could be found"
)
return thread_id | [
"def",
"createGroup",
"(",
"self",
",",
"message",
",",
"user_ids",
")",
":",
"data",
"=",
"self",
".",
"_getSendData",
"(",
"message",
"=",
"self",
".",
"_oldMessage",
"(",
"message",
")",
")",
"if",
"len",
"(",
"user_ids",
")",
"<",
"2",
":",
"rais... | Creates a group with the given ids
:param message: The initial message
:param user_ids: A list of users to create the group with.
:return: ID of the new group
:raises: FBchatException if request failed | [
"Creates",
"a",
"group",
"with",
"the",
"given",
"ids"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1716-L1738 | train | 215,176 |
carpedm20/fbchat | fbchat/_client.py | Client.addUsersToGroup | def addUsersToGroup(self, user_ids, thread_id=None):
"""
Adds users to a group.
:param user_ids: One or more user IDs to add
:param thread_id: Group ID to add people to. See :ref:`intro_threads`
:type user_ids: list
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = self._getSendData(thread_id=thread_id, thread_type=ThreadType.GROUP)
data["action_type"] = "ma-type:log-message"
data["log_message_type"] = "log:subscribe"
user_ids = require_list(user_ids)
for i, user_id in enumerate(user_ids):
if user_id == self._uid:
raise FBchatUserError(
"Error when adding users: Cannot add self to group thread"
)
else:
data[
"log_message_data[added_participants][{}]".format(i)
] = "fbid:{}".format(user_id)
return self._doSendRequest(data) | python | def addUsersToGroup(self, user_ids, thread_id=None):
"""
Adds users to a group.
:param user_ids: One or more user IDs to add
:param thread_id: Group ID to add people to. See :ref:`intro_threads`
:type user_ids: list
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = self._getSendData(thread_id=thread_id, thread_type=ThreadType.GROUP)
data["action_type"] = "ma-type:log-message"
data["log_message_type"] = "log:subscribe"
user_ids = require_list(user_ids)
for i, user_id in enumerate(user_ids):
if user_id == self._uid:
raise FBchatUserError(
"Error when adding users: Cannot add self to group thread"
)
else:
data[
"log_message_data[added_participants][{}]".format(i)
] = "fbid:{}".format(user_id)
return self._doSendRequest(data) | [
"def",
"addUsersToGroup",
"(",
"self",
",",
"user_ids",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"self",
".",
"_getSendData",
"(",
"thread_id"... | Adds users to a group.
:param user_ids: One or more user IDs to add
:param thread_id: Group ID to add people to. See :ref:`intro_threads`
:type user_ids: list
:raises: FBchatException if request failed | [
"Adds",
"users",
"to",
"a",
"group",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1740-L1767 | train | 215,177 |
carpedm20/fbchat | fbchat/_client.py | Client.removeUserFromGroup | def removeUserFromGroup(self, user_id, thread_id=None):
"""
Removes users from a group.
:param user_id: User ID to remove
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"uid": user_id, "tid": thread_id}
j = self._post(self.req_url.REMOVE_USER, data, fix_request=True, as_json=True) | python | def removeUserFromGroup(self, user_id, thread_id=None):
"""
Removes users from a group.
:param user_id: User ID to remove
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"uid": user_id, "tid": thread_id}
j = self._post(self.req_url.REMOVE_USER, data, fix_request=True, as_json=True) | [
"def",
"removeUserFromGroup",
"(",
"self",
",",
"user_id",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"uid\"",
":",
"user_id",
",",
"\"... | Removes users from a group.
:param user_id: User ID to remove
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Removes",
"users",
"from",
"a",
"group",
"."
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1769-L1780 | train | 215,178 |
carpedm20/fbchat | fbchat/_client.py | Client.changeGroupApprovalMode | def changeGroupApprovalMode(self, require_admin_approval, thread_id=None):
"""
Changes group's approval mode
:param require_admin_approval: True or False
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"set_mode": int(require_admin_approval), "thread_fbid": thread_id}
j = self._post(self.req_url.APPROVAL_MODE, data, fix_request=True, as_json=True) | python | def changeGroupApprovalMode(self, require_admin_approval, thread_id=None):
"""
Changes group's approval mode
:param require_admin_approval: True or False
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"set_mode": int(require_admin_approval), "thread_fbid": thread_id}
j = self._post(self.req_url.APPROVAL_MODE, data, fix_request=True, as_json=True) | [
"def",
"changeGroupApprovalMode",
"(",
"self",
",",
"require_admin_approval",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"set_mode\"",
":",
... | Changes group's approval mode
:param require_admin_approval: True or False
:param thread_id: Group ID to remove people from. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Changes",
"group",
"s",
"approval",
"mode"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1814-L1825 | train | 215,179 |
carpedm20/fbchat | fbchat/_client.py | Client._changeGroupImage | def _changeGroupImage(self, image_id, thread_id=None):
"""
Changes a thread image from an image id
:param image_id: ID of uploaded image
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"thread_image_id": image_id, "thread_id": thread_id}
j = self._post(self.req_url.THREAD_IMAGE, data, fix_request=True, as_json=True)
return image_id | python | def _changeGroupImage(self, image_id, thread_id=None):
"""
Changes a thread image from an image id
:param image_id: ID of uploaded image
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"thread_image_id": image_id, "thread_id": thread_id}
j = self._post(self.req_url.THREAD_IMAGE, data, fix_request=True, as_json=True)
return image_id | [
"def",
"_changeGroupImage",
"(",
"self",
",",
"image_id",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"thread_image_id\"",
":",
"image_id",
... | Changes a thread image from an image id
:param image_id: ID of uploaded image
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Changes",
"a",
"thread",
"image",
"from",
"an",
"image",
"id"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1864-L1877 | train | 215,180 |
carpedm20/fbchat | fbchat/_client.py | Client.changeGroupImageRemote | def changeGroupImageRemote(self, image_url, thread_id=None):
"""
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
(image_id, mimetype), = self._upload(get_files_from_urls([image_url]))
return self._changeGroupImage(image_id, thread_id) | python | def changeGroupImageRemote(self, image_url, thread_id=None):
"""
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
(image_id, mimetype), = self._upload(get_files_from_urls([image_url]))
return self._changeGroupImage(image_id, thread_id) | [
"def",
"changeGroupImageRemote",
"(",
"self",
",",
"image_url",
",",
"thread_id",
"=",
"None",
")",
":",
"(",
"image_id",
",",
"mimetype",
")",
",",
"=",
"self",
".",
"_upload",
"(",
"get_files_from_urls",
"(",
"[",
"image_url",
"]",
")",
")",
"return",
... | Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Changes",
"a",
"thread",
"image",
"from",
"a",
"URL"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1879-L1888 | train | 215,181 |
carpedm20/fbchat | fbchat/_client.py | Client.changeGroupImageLocal | def changeGroupImageLocal(self, image_path, thread_id=None):
"""
Changes a thread image from a local path
:param image_path: Path of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
with get_files_from_paths([image_path]) as files:
(image_id, mimetype), = self._upload(files)
return self._changeGroupImage(image_id, thread_id) | python | def changeGroupImageLocal(self, image_path, thread_id=None):
"""
Changes a thread image from a local path
:param image_path: Path of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
with get_files_from_paths([image_path]) as files:
(image_id, mimetype), = self._upload(files)
return self._changeGroupImage(image_id, thread_id) | [
"def",
"changeGroupImageLocal",
"(",
"self",
",",
"image_path",
",",
"thread_id",
"=",
"None",
")",
":",
"with",
"get_files_from_paths",
"(",
"[",
"image_path",
"]",
")",
"as",
"files",
":",
"(",
"image_id",
",",
"mimetype",
")",
",",
"=",
"self",
".",
"... | Changes a thread image from a local path
:param image_path: Path of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed | [
"Changes",
"a",
"thread",
"image",
"from",
"a",
"local",
"path"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1890-L1901 | train | 215,182 |
carpedm20/fbchat | fbchat/_client.py | Client.changeThreadTitle | def changeThreadTitle(self, title, thread_id=None, thread_type=ThreadType.USER):
"""
Changes title of a thread.
If this is executed on a user thread, this will change the nickname of that user, effectively changing the title
:param title: New group thread title
:param thread_id: Group ID to change title of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
if thread_type == ThreadType.USER:
# The thread is a user, so we change the user's nickname
return self.changeNickname(
title, thread_id, thread_id=thread_id, thread_type=thread_type
)
data = {"thread_name": title, "thread_id": thread_id}
j = self._post(self.req_url.THREAD_NAME, data, fix_request=True, as_json=True) | python | def changeThreadTitle(self, title, thread_id=None, thread_type=ThreadType.USER):
"""
Changes title of a thread.
If this is executed on a user thread, this will change the nickname of that user, effectively changing the title
:param title: New group thread title
:param thread_id: Group ID to change title of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
if thread_type == ThreadType.USER:
# The thread is a user, so we change the user's nickname
return self.changeNickname(
title, thread_id, thread_id=thread_id, thread_type=thread_type
)
data = {"thread_name": title, "thread_id": thread_id}
j = self._post(self.req_url.THREAD_NAME, data, fix_request=True, as_json=True) | [
"def",
"changeThreadTitle",
"(",
"self",
",",
"title",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"thread_type",
")",
... | Changes title of a thread.
If this is executed on a user thread, this will change the nickname of that user, effectively changing the title
:param title: New group thread title
:param thread_id: Group ID to change title of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed | [
"Changes",
"title",
"of",
"a",
"thread",
".",
"If",
"this",
"is",
"executed",
"on",
"a",
"user",
"thread",
"this",
"will",
"change",
"the",
"nickname",
"of",
"that",
"user",
"effectively",
"changing",
"the",
"title"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1903-L1923 | train | 215,183 |
carpedm20/fbchat | fbchat/_client.py | Client.changeNickname | def changeNickname(
self, nickname, user_id, thread_id=None, thread_type=ThreadType.USER
):
"""
Changes the nickname of a user in a thread
:param nickname: New nickname
:param user_id: User that will have their nickname changed
:param thread_id: User/Group ID to change color of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = {
"nickname": nickname,
"participant_id": user_id,
"thread_or_other_fbid": thread_id,
}
j = self._post(
self.req_url.THREAD_NICKNAME, data, fix_request=True, as_json=True
) | python | def changeNickname(
self, nickname, user_id, thread_id=None, thread_type=ThreadType.USER
):
"""
Changes the nickname of a user in a thread
:param nickname: New nickname
:param user_id: User that will have their nickname changed
:param thread_id: User/Group ID to change color of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = {
"nickname": nickname,
"participant_id": user_id,
"thread_or_other_fbid": thread_id,
}
j = self._post(
self.req_url.THREAD_NICKNAME, data, fix_request=True, as_json=True
) | [
"def",
"changeNickname",
"(",
"self",
",",
"nickname",
",",
"user_id",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"ThreadType",
".",
"USER",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"thr... | Changes the nickname of a user in a thread
:param nickname: New nickname
:param user_id: User that will have their nickname changed
:param thread_id: User/Group ID to change color of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed | [
"Changes",
"the",
"nickname",
"of",
"a",
"user",
"in",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1925-L1947 | train | 215,184 |
carpedm20/fbchat | fbchat/_client.py | Client.reactToMessage | def reactToMessage(self, message_id, reaction):
"""
Reacts to a message, or removes reaction
:param message_id: :ref:`Message ID <intro_message_ids>` to react to
:param reaction: Reaction emoji to use, if None removes reaction
:type reaction: models.MessageReaction or None
:raises: FBchatException if request failed
"""
data = {
"action": "ADD_REACTION" if reaction else "REMOVE_REACTION",
"client_mutation_id": "1",
"actor_id": self._uid,
"message_id": str(message_id),
"reaction": reaction.value if reaction else None,
}
data = {"doc_id": 1491398900900362, "variables": json.dumps({"data": data})}
self._post(self.req_url.MESSAGE_REACTION, data, fix_request=True, as_json=True) | python | def reactToMessage(self, message_id, reaction):
"""
Reacts to a message, or removes reaction
:param message_id: :ref:`Message ID <intro_message_ids>` to react to
:param reaction: Reaction emoji to use, if None removes reaction
:type reaction: models.MessageReaction or None
:raises: FBchatException if request failed
"""
data = {
"action": "ADD_REACTION" if reaction else "REMOVE_REACTION",
"client_mutation_id": "1",
"actor_id": self._uid,
"message_id": str(message_id),
"reaction": reaction.value if reaction else None,
}
data = {"doc_id": 1491398900900362, "variables": json.dumps({"data": data})}
self._post(self.req_url.MESSAGE_REACTION, data, fix_request=True, as_json=True) | [
"def",
"reactToMessage",
"(",
"self",
",",
"message_id",
",",
"reaction",
")",
":",
"data",
"=",
"{",
"\"action\"",
":",
"\"ADD_REACTION\"",
"if",
"reaction",
"else",
"\"REMOVE_REACTION\"",
",",
"\"client_mutation_id\"",
":",
"\"1\"",
",",
"\"actor_id\"",
":",
"... | Reacts to a message, or removes reaction
:param message_id: :ref:`Message ID <intro_message_ids>` to react to
:param reaction: Reaction emoji to use, if None removes reaction
:type reaction: models.MessageReaction or None
:raises: FBchatException if request failed | [
"Reacts",
"to",
"a",
"message",
"or",
"removes",
"reaction"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1981-L1998 | train | 215,185 |
carpedm20/fbchat | fbchat/_client.py | Client.createPlan | def createPlan(self, plan, thread_id=None):
"""
Sets a plan
:param plan: Plan to set
:param thread_id: User/Group ID to send plan to. See :ref:`intro_threads`
:type plan: models.Plan
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"event_type": "EVENT",
"event_time": plan.time,
"title": plan.title,
"thread_id": thread_id,
"location_id": plan.location_id or "",
"location_name": plan.location or "",
"acontext": ACONTEXT,
}
j = self._post(self.req_url.PLAN_CREATE, data, fix_request=True, as_json=True) | python | def createPlan(self, plan, thread_id=None):
"""
Sets a plan
:param plan: Plan to set
:param thread_id: User/Group ID to send plan to. See :ref:`intro_threads`
:type plan: models.Plan
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"event_type": "EVENT",
"event_time": plan.time,
"title": plan.title,
"thread_id": thread_id,
"location_id": plan.location_id or "",
"location_name": plan.location or "",
"acontext": ACONTEXT,
}
j = self._post(self.req_url.PLAN_CREATE, data, fix_request=True, as_json=True) | [
"def",
"createPlan",
"(",
"self",
",",
"plan",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"event_type\"",
":",
"\"EVENT\"",
",",
"\"eve... | Sets a plan
:param plan: Plan to set
:param thread_id: User/Group ID to send plan to. See :ref:`intro_threads`
:type plan: models.Plan
:raises: FBchatException if request failed | [
"Sets",
"a",
"plan"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2000-L2020 | train | 215,186 |
carpedm20/fbchat | fbchat/_client.py | Client.editPlan | def editPlan(self, plan, new_plan):
"""
Edits a plan
:param plan: Plan to edit
:param new_plan: New plan
:type plan: models.Plan
:raises: FBchatException if request failed
"""
data = {
"event_reminder_id": plan.uid,
"delete": "false",
"date": new_plan.time,
"location_name": new_plan.location or "",
"location_id": new_plan.location_id or "",
"title": new_plan.title,
"acontext": ACONTEXT,
}
j = self._post(self.req_url.PLAN_CHANGE, data, fix_request=True, as_json=True) | python | def editPlan(self, plan, new_plan):
"""
Edits a plan
:param plan: Plan to edit
:param new_plan: New plan
:type plan: models.Plan
:raises: FBchatException if request failed
"""
data = {
"event_reminder_id": plan.uid,
"delete": "false",
"date": new_plan.time,
"location_name": new_plan.location or "",
"location_id": new_plan.location_id or "",
"title": new_plan.title,
"acontext": ACONTEXT,
}
j = self._post(self.req_url.PLAN_CHANGE, data, fix_request=True, as_json=True) | [
"def",
"editPlan",
"(",
"self",
",",
"plan",
",",
"new_plan",
")",
":",
"data",
"=",
"{",
"\"event_reminder_id\"",
":",
"plan",
".",
"uid",
",",
"\"delete\"",
":",
"\"false\"",
",",
"\"date\"",
":",
"new_plan",
".",
"time",
",",
"\"location_name\"",
":",
... | Edits a plan
:param plan: Plan to edit
:param new_plan: New plan
:type plan: models.Plan
:raises: FBchatException if request failed | [
"Edits",
"a",
"plan"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2022-L2040 | train | 215,187 |
carpedm20/fbchat | fbchat/_client.py | Client.deletePlan | def deletePlan(self, plan):
"""
Deletes a plan
:param plan: Plan to delete
:raises: FBchatException if request failed
"""
data = {"event_reminder_id": plan.uid, "delete": "true", "acontext": ACONTEXT}
j = self._post(self.req_url.PLAN_CHANGE, data, fix_request=True, as_json=True) | python | def deletePlan(self, plan):
"""
Deletes a plan
:param plan: Plan to delete
:raises: FBchatException if request failed
"""
data = {"event_reminder_id": plan.uid, "delete": "true", "acontext": ACONTEXT}
j = self._post(self.req_url.PLAN_CHANGE, data, fix_request=True, as_json=True) | [
"def",
"deletePlan",
"(",
"self",
",",
"plan",
")",
":",
"data",
"=",
"{",
"\"event_reminder_id\"",
":",
"plan",
".",
"uid",
",",
"\"delete\"",
":",
"\"true\"",
",",
"\"acontext\"",
":",
"ACONTEXT",
"}",
"j",
"=",
"self",
".",
"_post",
"(",
"self",
"."... | Deletes a plan
:param plan: Plan to delete
:raises: FBchatException if request failed | [
"Deletes",
"a",
"plan"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2042-L2050 | train | 215,188 |
carpedm20/fbchat | fbchat/_client.py | Client.changePlanParticipation | def changePlanParticipation(self, plan, take_part=True):
"""
Changes participation in a plan
:param plan: Plan to take part in or not
:param take_part: Whether to take part in the plan
:raises: FBchatException if request failed
"""
data = {
"event_reminder_id": plan.uid,
"guest_state": "GOING" if take_part else "DECLINED",
"acontext": ACONTEXT,
}
j = self._post(
self.req_url.PLAN_PARTICIPATION, data, fix_request=True, as_json=True
) | python | def changePlanParticipation(self, plan, take_part=True):
"""
Changes participation in a plan
:param plan: Plan to take part in or not
:param take_part: Whether to take part in the plan
:raises: FBchatException if request failed
"""
data = {
"event_reminder_id": plan.uid,
"guest_state": "GOING" if take_part else "DECLINED",
"acontext": ACONTEXT,
}
j = self._post(
self.req_url.PLAN_PARTICIPATION, data, fix_request=True, as_json=True
) | [
"def",
"changePlanParticipation",
"(",
"self",
",",
"plan",
",",
"take_part",
"=",
"True",
")",
":",
"data",
"=",
"{",
"\"event_reminder_id\"",
":",
"plan",
".",
"uid",
",",
"\"guest_state\"",
":",
"\"GOING\"",
"if",
"take_part",
"else",
"\"DECLINED\"",
",",
... | Changes participation in a plan
:param plan: Plan to take part in or not
:param take_part: Whether to take part in the plan
:raises: FBchatException if request failed | [
"Changes",
"participation",
"in",
"a",
"plan"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2052-L2067 | train | 215,189 |
carpedm20/fbchat | fbchat/_client.py | Client.createPoll | def createPoll(self, poll, thread_id=None):
"""
Creates poll in a group thread
:param poll: Poll to create
:param thread_id: User/Group ID to create poll in. See :ref:`intro_threads`
:type poll: models.Poll
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
# We're using ordered dicts, because the Facebook endpoint that parses the POST
# parameters is badly implemented, and deals with ordering the options wrongly.
# This also means we had to change `client._payload_default` to an ordered dict,
# since that's being copied in between this point and the `requests` call
#
# If you can find a way to fix this for the endpoint, or if you find another
# endpoint, please do suggest it ;)
data = OrderedDict([("question_text", poll.title), ("target_id", thread_id)])
for i, option in enumerate(poll.options):
data["option_text_array[{}]".format(i)] = option.text
data["option_is_selected_array[{}]".format(i)] = str(int(option.vote))
j = self._post(self.req_url.CREATE_POLL, data, fix_request=True, as_json=True) | python | def createPoll(self, poll, thread_id=None):
"""
Creates poll in a group thread
:param poll: Poll to create
:param thread_id: User/Group ID to create poll in. See :ref:`intro_threads`
:type poll: models.Poll
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
# We're using ordered dicts, because the Facebook endpoint that parses the POST
# parameters is badly implemented, and deals with ordering the options wrongly.
# This also means we had to change `client._payload_default` to an ordered dict,
# since that's being copied in between this point and the `requests` call
#
# If you can find a way to fix this for the endpoint, or if you find another
# endpoint, please do suggest it ;)
data = OrderedDict([("question_text", poll.title), ("target_id", thread_id)])
for i, option in enumerate(poll.options):
data["option_text_array[{}]".format(i)] = option.text
data["option_is_selected_array[{}]".format(i)] = str(int(option.vote))
j = self._post(self.req_url.CREATE_POLL, data, fix_request=True, as_json=True) | [
"def",
"createPoll",
"(",
"self",
",",
"poll",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"# We're using ordered dicts, because the Facebook endpoint that parses the POS... | Creates poll in a group thread
:param poll: Poll to create
:param thread_id: User/Group ID to create poll in. See :ref:`intro_threads`
:type poll: models.Poll
:raises: FBchatException if request failed | [
"Creates",
"poll",
"in",
"a",
"group",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2076-L2100 | train | 215,190 |
carpedm20/fbchat | fbchat/_client.py | Client.updatePollVote | def updatePollVote(self, poll_id, option_ids=[], new_options=[]):
"""
Updates a poll vote
:param poll_id: ID of the poll to update vote
:param option_ids: List of the option IDs to vote
:param new_options: List of the new option names
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
data = {"question_id": poll_id}
for i, option_id in enumerate(option_ids):
data["selected_options[{}]".format(i)] = option_id
for i, option_text in enumerate(new_options):
data["new_options[{}]".format(i)] = option_text
j = self._post(self.req_url.UPDATE_VOTE, data, fix_request=True, as_json=True) | python | def updatePollVote(self, poll_id, option_ids=[], new_options=[]):
"""
Updates a poll vote
:param poll_id: ID of the poll to update vote
:param option_ids: List of the option IDs to vote
:param new_options: List of the new option names
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
data = {"question_id": poll_id}
for i, option_id in enumerate(option_ids):
data["selected_options[{}]".format(i)] = option_id
for i, option_text in enumerate(new_options):
data["new_options[{}]".format(i)] = option_text
j = self._post(self.req_url.UPDATE_VOTE, data, fix_request=True, as_json=True) | [
"def",
"updatePollVote",
"(",
"self",
",",
"poll_id",
",",
"option_ids",
"=",
"[",
"]",
",",
"new_options",
"=",
"[",
"]",
")",
":",
"data",
"=",
"{",
"\"question_id\"",
":",
"poll_id",
"}",
"for",
"i",
",",
"option_id",
"in",
"enumerate",
"(",
"option... | Updates a poll vote
:param poll_id: ID of the poll to update vote
:param option_ids: List of the option IDs to vote
:param new_options: List of the new option names
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
:raises: FBchatException if request failed | [
"Updates",
"a",
"poll",
"vote"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2102-L2122 | train | 215,191 |
carpedm20/fbchat | fbchat/_client.py | Client.setTypingStatus | def setTypingStatus(self, status, thread_id=None, thread_type=None):
"""
Sets users typing status in a thread
:param status: Specify the typing status
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type status: models.TypingStatus
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = {
"typ": status.value,
"thread": thread_id,
"to": thread_id if thread_type == ThreadType.USER else "",
"source": "mercury-chat",
}
j = self._post(self.req_url.TYPING, data, fix_request=True, as_json=True) | python | def setTypingStatus(self, status, thread_id=None, thread_type=None):
"""
Sets users typing status in a thread
:param status: Specify the typing status
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type status: models.TypingStatus
:type thread_type: models.ThreadType
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, thread_type)
data = {
"typ": status.value,
"thread": thread_id,
"to": thread_id if thread_type == ThreadType.USER else "",
"source": "mercury-chat",
}
j = self._post(self.req_url.TYPING, data, fix_request=True, as_json=True) | [
"def",
"setTypingStatus",
"(",
"self",
",",
"status",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"thread_type",
")",
"data",
"=",
"{",
... | Sets users typing status in a thread
:param status: Specify the typing status
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type status: models.TypingStatus
:type thread_type: models.ThreadType
:raises: FBchatException if request failed | [
"Sets",
"users",
"typing",
"status",
"in",
"a",
"thread"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2124-L2143 | train | 215,192 |
carpedm20/fbchat | fbchat/_client.py | Client.markAsDelivered | def markAsDelivered(self, thread_id, message_id):
"""
Mark a message as delivered
:param thread_id: User/Group ID to which the message belongs. See :ref:`intro_threads`
:param message_id: Message ID to set as delivered. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {
"message_ids[0]": message_id,
"thread_ids[%s][0]" % thread_id: message_id,
}
r = self._post(self.req_url.DELIVERED, data)
return r.ok | python | def markAsDelivered(self, thread_id, message_id):
"""
Mark a message as delivered
:param thread_id: User/Group ID to which the message belongs. See :ref:`intro_threads`
:param message_id: Message ID to set as delivered. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {
"message_ids[0]": message_id,
"thread_ids[%s][0]" % thread_id: message_id,
}
r = self._post(self.req_url.DELIVERED, data)
return r.ok | [
"def",
"markAsDelivered",
"(",
"self",
",",
"thread_id",
",",
"message_id",
")",
":",
"data",
"=",
"{",
"\"message_ids[0]\"",
":",
"message_id",
",",
"\"thread_ids[%s][0]\"",
"%",
"thread_id",
":",
"message_id",
",",
"}",
"r",
"=",
"self",
".",
"_post",
"(",... | Mark a message as delivered
:param thread_id: User/Group ID to which the message belongs. See :ref:`intro_threads`
:param message_id: Message ID to set as delivered. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Mark",
"a",
"message",
"as",
"delivered"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2149-L2164 | train | 215,193 |
carpedm20/fbchat | fbchat/_client.py | Client.removeFriend | def removeFriend(self, friend_id=None):
"""
Removes a specifed friend from your friend list
:param friend_id: The ID of the friend that you want to remove
:return: Returns error if the removing was unsuccessful, returns True when successful.
"""
payload = {"friend_id": friend_id, "unref": "none", "confirm": "Confirm"}
r = self._post(self.req_url.REMOVE_FRIEND, payload)
query = parse_qs(urlparse(r.url).query)
if "err" not in query:
log.debug("Remove was successful!")
return True
else:
log.warning("Error while removing friend")
return False | python | def removeFriend(self, friend_id=None):
"""
Removes a specifed friend from your friend list
:param friend_id: The ID of the friend that you want to remove
:return: Returns error if the removing was unsuccessful, returns True when successful.
"""
payload = {"friend_id": friend_id, "unref": "none", "confirm": "Confirm"}
r = self._post(self.req_url.REMOVE_FRIEND, payload)
query = parse_qs(urlparse(r.url).query)
if "err" not in query:
log.debug("Remove was successful!")
return True
else:
log.warning("Error while removing friend")
return False | [
"def",
"removeFriend",
"(",
"self",
",",
"friend_id",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"friend_id\"",
":",
"friend_id",
",",
"\"unref\"",
":",
"\"none\"",
",",
"\"confirm\"",
":",
"\"Confirm\"",
"}",
"r",
"=",
"self",
".",
"_post",
"(",
"sel... | Removes a specifed friend from your friend list
:param friend_id: The ID of the friend that you want to remove
:return: Returns error if the removing was unsuccessful, returns True when successful. | [
"Removes",
"a",
"specifed",
"friend",
"from",
"your",
"friend",
"list"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2217-L2232 | train | 215,194 |
carpedm20/fbchat | fbchat/_client.py | Client.blockUser | def blockUser(self, user_id):
"""
Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {"fbid": user_id}
r = self._post(self.req_url.BLOCK_USER, data)
return r.ok | python | def blockUser(self, user_id):
"""
Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {"fbid": user_id}
r = self._post(self.req_url.BLOCK_USER, data)
return r.ok | [
"def",
"blockUser",
"(",
"self",
",",
"user_id",
")",
":",
"data",
"=",
"{",
"\"fbid\"",
":",
"user_id",
"}",
"r",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"BLOCK_USER",
",",
"data",
")",
"return",
"r",
".",
"ok"
] | Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Blocks",
"messages",
"from",
"a",
"specifed",
"user"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2234-L2244 | train | 215,195 |
carpedm20/fbchat | fbchat/_client.py | Client.unblockUser | def unblockUser(self, user_id):
"""
Unblocks messages from a blocked user
:param user_id: The ID of the user that you want to unblock
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {"fbid": user_id}
r = self._post(self.req_url.UNBLOCK_USER, data)
return r.ok | python | def unblockUser(self, user_id):
"""
Unblocks messages from a blocked user
:param user_id: The ID of the user that you want to unblock
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
data = {"fbid": user_id}
r = self._post(self.req_url.UNBLOCK_USER, data)
return r.ok | [
"def",
"unblockUser",
"(",
"self",
",",
"user_id",
")",
":",
"data",
"=",
"{",
"\"fbid\"",
":",
"user_id",
"}",
"r",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"UNBLOCK_USER",
",",
"data",
")",
"return",
"r",
".",
"ok"
] | Unblocks messages from a blocked user
:param user_id: The ID of the user that you want to unblock
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Unblocks",
"messages",
"from",
"a",
"blocked",
"user"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2246-L2256 | train | 215,196 |
carpedm20/fbchat | fbchat/_client.py | Client.moveThreads | def moveThreads(self, location, thread_ids):
"""
Moves threads to specifed location
:param location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param thread_ids: Thread IDs to move. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_ids = require_list(thread_ids)
if location == ThreadLocation.PENDING:
location = ThreadLocation.OTHER
if location == ThreadLocation.ARCHIVED:
data_archive = dict()
data_unpin = dict()
for thread_id in thread_ids:
data_archive["ids[{}]".format(thread_id)] = "true"
data_unpin["ids[{}]".format(thread_id)] = "false"
r_archive = self._post(self.req_url.ARCHIVED_STATUS, data_archive)
r_unpin = self._post(self.req_url.PINNED_STATUS, data_unpin)
return r_archive.ok and r_unpin.ok
else:
data = dict()
for i, thread_id in enumerate(thread_ids):
data["{}[{}]".format(location.name.lower(), i)] = thread_id
r = self._post(self.req_url.MOVE_THREAD, data)
return r.ok | python | def moveThreads(self, location, thread_ids):
"""
Moves threads to specifed location
:param location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param thread_ids: Thread IDs to move. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_ids = require_list(thread_ids)
if location == ThreadLocation.PENDING:
location = ThreadLocation.OTHER
if location == ThreadLocation.ARCHIVED:
data_archive = dict()
data_unpin = dict()
for thread_id in thread_ids:
data_archive["ids[{}]".format(thread_id)] = "true"
data_unpin["ids[{}]".format(thread_id)] = "false"
r_archive = self._post(self.req_url.ARCHIVED_STATUS, data_archive)
r_unpin = self._post(self.req_url.PINNED_STATUS, data_unpin)
return r_archive.ok and r_unpin.ok
else:
data = dict()
for i, thread_id in enumerate(thread_ids):
data["{}[{}]".format(location.name.lower(), i)] = thread_id
r = self._post(self.req_url.MOVE_THREAD, data)
return r.ok | [
"def",
"moveThreads",
"(",
"self",
",",
"location",
",",
"thread_ids",
")",
":",
"thread_ids",
"=",
"require_list",
"(",
"thread_ids",
")",
"if",
"location",
"==",
"ThreadLocation",
".",
"PENDING",
":",
"location",
"=",
"ThreadLocation",
".",
"OTHER",
"if",
... | Moves threads to specifed location
:param location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param thread_ids: Thread IDs to move. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Moves",
"threads",
"to",
"specifed",
"location"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2258-L2286 | train | 215,197 |
carpedm20/fbchat | fbchat/_client.py | Client.markAsSpam | def markAsSpam(self, thread_id=None):
"""
Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
r = self._post(self.req_url.MARK_SPAM, {"id": thread_id})
return r.ok | python | def markAsSpam(self, thread_id=None):
"""
Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
r = self._post(self.req_url.MARK_SPAM, {"id": thread_id})
return r.ok | [
"def",
"markAsSpam",
"(",
"self",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"r",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"MARK_SPAM... | Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Mark",
"a",
"thread",
"as",
"spam",
"and",
"delete",
"it"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2307-L2317 | train | 215,198 |
carpedm20/fbchat | fbchat/_client.py | Client.deleteMessages | def deleteMessages(self, message_ids):
"""
Deletes specifed messages
:param message_ids: Message IDs to delete
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
message_ids = require_list(message_ids)
data = dict()
for i, message_id in enumerate(message_ids):
data["message_ids[{}]".format(i)] = message_id
r = self._post(self.req_url.DELETE_MESSAGES, data)
return r.ok | python | def deleteMessages(self, message_ids):
"""
Deletes specifed messages
:param message_ids: Message IDs to delete
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
message_ids = require_list(message_ids)
data = dict()
for i, message_id in enumerate(message_ids):
data["message_ids[{}]".format(i)] = message_id
r = self._post(self.req_url.DELETE_MESSAGES, data)
return r.ok | [
"def",
"deleteMessages",
"(",
"self",
",",
"message_ids",
")",
":",
"message_ids",
"=",
"require_list",
"(",
"message_ids",
")",
"data",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"message_id",
"in",
"enumerate",
"(",
"message_ids",
")",
":",
"data",
"[",
"... | Deletes specifed messages
:param message_ids: Message IDs to delete
:return: Whether the request was successful
:raises: FBchatException if request failed | [
"Deletes",
"specifed",
"messages"
] | f480d68b5773473e6daba7f66075ee30e8d737a8 | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2319-L2332 | train | 215,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.