id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
234,000 | influxdata/influxdb-python | influxdb/line_protocol.py | make_lines | def make_lines(data, precision=None):
"""Extract points from given dict.
Extracts the points from the given dict and returns a Unicode string
matching the line protocol introduced in InfluxDB 0.9.0.
"""
lines = []
static_tags = data.get('tags')
for point in data['points']:
elements = []
# add measurement name
measurement = _escape_tag(_get_unicode(
point.get('measurement', data.get('measurement'))))
key_values = [measurement]
# add tags
if static_tags:
tags = dict(static_tags) # make a copy, since we'll modify
tags.update(point.get('tags') or {})
else:
tags = point.get('tags') or {}
# tags should be sorted client-side to take load off server
for tag_key, tag_value in sorted(iteritems(tags)):
key = _escape_tag(tag_key)
value = _escape_tag_value(tag_value)
if key != '' and value != '':
key_values.append(key + "=" + value)
elements.append(','.join(key_values))
# add fields
field_values = []
for field_key, field_value in sorted(iteritems(point['fields'])):
key = _escape_tag(field_key)
value = _escape_value(field_value)
if key != '' and value != '':
field_values.append(key + "=" + value)
elements.append(','.join(field_values))
# add timestamp
if 'time' in point:
timestamp = _get_unicode(str(int(
_convert_timestamp(point['time'], precision))))
elements.append(timestamp)
line = ' '.join(elements)
lines.append(line)
return '\n'.join(lines) + '\n' | python | def make_lines(data, precision=None):
lines = []
static_tags = data.get('tags')
for point in data['points']:
elements = []
# add measurement name
measurement = _escape_tag(_get_unicode(
point.get('measurement', data.get('measurement'))))
key_values = [measurement]
# add tags
if static_tags:
tags = dict(static_tags) # make a copy, since we'll modify
tags.update(point.get('tags') or {})
else:
tags = point.get('tags') or {}
# tags should be sorted client-side to take load off server
for tag_key, tag_value in sorted(iteritems(tags)):
key = _escape_tag(tag_key)
value = _escape_tag_value(tag_value)
if key != '' and value != '':
key_values.append(key + "=" + value)
elements.append(','.join(key_values))
# add fields
field_values = []
for field_key, field_value in sorted(iteritems(point['fields'])):
key = _escape_tag(field_key)
value = _escape_value(field_value)
if key != '' and value != '':
field_values.append(key + "=" + value)
elements.append(','.join(field_values))
# add timestamp
if 'time' in point:
timestamp = _get_unicode(str(int(
_convert_timestamp(point['time'], precision))))
elements.append(timestamp)
line = ' '.join(elements)
lines.append(line)
return '\n'.join(lines) + '\n' | [
"def",
"make_lines",
"(",
"data",
",",
"precision",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"static_tags",
"=",
"data",
".",
"get",
"(",
"'tags'",
")",
"for",
"point",
"in",
"data",
"[",
"'points'",
"]",
":",
"elements",
"=",
"[",
"]",
"# ad... | Extract points from given dict.
Extracts the points from the given dict and returns a Unicode string
matching the line protocol introduced in InfluxDB 0.9.0. | [
"Extract",
"points",
"from",
"given",
"dict",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/line_protocol.py#L119-L172 |
234,001 | influxdata/influxdb-python | examples/tutorial_pandas.py | main | def main(host='localhost', port=8086):
"""Instantiate the connection to the InfluxDB client."""
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014-11-16',
periods=30, freq='H'), columns=['0'])
print("Create database: " + dbname)
client.create_database(dbname)
print("Write DataFrame")
client.write_points(df, 'demo', protocol=protocol)
print("Write DataFrame with Tags")
client.write_points(df, 'demo',
{'k1': 'v1', 'k2': 'v2'}, protocol=protocol)
print("Read DataFrame")
client.query("select * from demo")
print("Delete database: " + dbname)
client.drop_database(dbname) | python | def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014-11-16',
periods=30, freq='H'), columns=['0'])
print("Create database: " + dbname)
client.create_database(dbname)
print("Write DataFrame")
client.write_points(df, 'demo', protocol=protocol)
print("Write DataFrame with Tags")
client.write_points(df, 'demo',
{'k1': 'v1', 'k2': 'v2'}, protocol=protocol)
print("Read DataFrame")
client.query("select * from demo")
print("Delete database: " + dbname)
client.drop_database(dbname) | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
")",
":",
"user",
"=",
"'root'",
"password",
"=",
"'root'",
"dbname",
"=",
"'demo'",
"protocol",
"=",
"'json'",
"client",
"=",
"DataFrameClient",
"(",
"host",
",",
"port",
",",
"... | Instantiate the connection to the InfluxDB client. | [
"Instantiate",
"the",
"connection",
"to",
"the",
"InfluxDB",
"client",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/examples/tutorial_pandas.py#L10-L38 |
234,002 | influxdata/influxdb-python | influxdb/client.py | _parse_dsn | def _parse_dsn(dsn):
"""Parse data source name.
This is a helper function to split the data source name provided in
the from_dsn classmethod
"""
conn_params = urlparse(dsn)
init_args = {}
scheme_info = conn_params.scheme.split('+')
if len(scheme_info) == 1:
scheme = scheme_info[0]
modifier = None
else:
modifier, scheme = scheme_info
if scheme != 'influxdb':
raise ValueError('Unknown scheme "{0}".'.format(scheme))
if modifier:
if modifier == 'udp':
init_args['use_udp'] = True
elif modifier == 'https':
init_args['ssl'] = True
else:
raise ValueError('Unknown modifier "{0}".'.format(modifier))
netlocs = conn_params.netloc.split(',')
init_args['hosts'] = []
for netloc in netlocs:
parsed = _parse_netloc(netloc)
init_args['hosts'].append((parsed['host'], int(parsed['port'])))
init_args['username'] = parsed['username']
init_args['password'] = parsed['password']
if conn_params.path and len(conn_params.path) > 1:
init_args['database'] = conn_params.path[1:]
return init_args | python | def _parse_dsn(dsn):
conn_params = urlparse(dsn)
init_args = {}
scheme_info = conn_params.scheme.split('+')
if len(scheme_info) == 1:
scheme = scheme_info[0]
modifier = None
else:
modifier, scheme = scheme_info
if scheme != 'influxdb':
raise ValueError('Unknown scheme "{0}".'.format(scheme))
if modifier:
if modifier == 'udp':
init_args['use_udp'] = True
elif modifier == 'https':
init_args['ssl'] = True
else:
raise ValueError('Unknown modifier "{0}".'.format(modifier))
netlocs = conn_params.netloc.split(',')
init_args['hosts'] = []
for netloc in netlocs:
parsed = _parse_netloc(netloc)
init_args['hosts'].append((parsed['host'], int(parsed['port'])))
init_args['username'] = parsed['username']
init_args['password'] = parsed['password']
if conn_params.path and len(conn_params.path) > 1:
init_args['database'] = conn_params.path[1:]
return init_args | [
"def",
"_parse_dsn",
"(",
"dsn",
")",
":",
"conn_params",
"=",
"urlparse",
"(",
"dsn",
")",
"init_args",
"=",
"{",
"}",
"scheme_info",
"=",
"conn_params",
".",
"scheme",
".",
"split",
"(",
"'+'",
")",
"if",
"len",
"(",
"scheme_info",
")",
"==",
"1",
... | Parse data source name.
This is a helper function to split the data source name provided in
the from_dsn classmethod | [
"Parse",
"data",
"source",
"name",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L1059-L1097 |
234,003 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.from_dsn | def from_dsn(cls, dsn, **kwargs):
r"""Generate an instance of InfluxDBClient from given data source name.
Return an instance of :class:`~.InfluxDBClient` from the provided
data source name. Supported schemes are "influxdb", "https+influxdb"
and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient`
constructor may also be passed to this method.
:param dsn: data source name
:type dsn: string
:param kwargs: additional parameters for `InfluxDBClient`
:type kwargs: dict
:raises ValueError: if the provided DSN has any unexpected values
:Example:
::
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
.. note:: parameters provided in `**kwargs` may override dsn parameters
.. note:: when using "udp+influxdb" the specified port (if any) will
be used for the TCP connection; specify the UDP port with the
additional `udp_port` parameter (cf. examples).
"""
init_args = _parse_dsn(dsn)
host, port = init_args.pop('hosts')[0]
init_args['host'] = host
init_args['port'] = port
init_args.update(kwargs)
return cls(**init_args) | python | def from_dsn(cls, dsn, **kwargs):
r"""Generate an instance of InfluxDBClient from given data source name.
Return an instance of :class:`~.InfluxDBClient` from the provided
data source name. Supported schemes are "influxdb", "https+influxdb"
and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient`
constructor may also be passed to this method.
:param dsn: data source name
:type dsn: string
:param kwargs: additional parameters for `InfluxDBClient`
:type kwargs: dict
:raises ValueError: if the provided DSN has any unexpected values
:Example:
::
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
.. note:: parameters provided in `**kwargs` may override dsn parameters
.. note:: when using "udp+influxdb" the specified port (if any) will
be used for the TCP connection; specify the UDP port with the
additional `udp_port` parameter (cf. examples).
"""
init_args = _parse_dsn(dsn)
host, port = init_args.pop('hosts')[0]
init_args['host'] = host
init_args['port'] = port
init_args.update(kwargs)
return cls(**init_args) | [
"def",
"from_dsn",
"(",
"cls",
",",
"dsn",
",",
"*",
"*",
"kwargs",
")",
":",
"init_args",
"=",
"_parse_dsn",
"(",
"dsn",
")",
"host",
",",
"port",
"=",
"init_args",
".",
"pop",
"(",
"'hosts'",
")",
"[",
"0",
"]",
"init_args",
"[",
"'host'",
"]",
... | r"""Generate an instance of InfluxDBClient from given data source name.
Return an instance of :class:`~.InfluxDBClient` from the provided
data source name. Supported schemes are "influxdb", "https+influxdb"
and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient`
constructor may also be passed to this method.
:param dsn: data source name
:type dsn: string
:param kwargs: additional parameters for `InfluxDBClient`
:type kwargs: dict
:raises ValueError: if the provided DSN has any unexpected values
:Example:
::
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
.. note:: parameters provided in `**kwargs` may override dsn parameters
.. note:: when using "udp+influxdb" the specified port (if any) will
be used for the TCP connection; specify the UDP port with the
additional `udp_port` parameter (cf. examples). | [
"r",
"Generate",
"an",
"instance",
"of",
"InfluxDBClient",
"from",
"given",
"data",
"source",
"name",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L159-L197 |
234,004 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.switch_user | def switch_user(self, username, password):
"""Change the client's username.
:param username: the username to switch to
:type username: str
:param password: the password for the username
:type password: str
"""
self._username = username
self._password = password | python | def switch_user(self, username, password):
self._username = username
self._password = password | [
"def",
"switch_user",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"_username",
"=",
"username",
"self",
".",
"_password",
"=",
"password"
] | Change the client's username.
:param username: the username to switch to
:type username: str
:param password: the password for the username
:type password: str | [
"Change",
"the",
"client",
"s",
"username",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L207-L216 |
234,005 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.request | def request(self, url, method='GET', params=None, data=None,
expected_response_code=200, headers=None):
"""Make a HTTP request to the InfluxDB API.
:param url: the path of the HTTP request, e.g. write, query, etc.
:type url: str
:param method: the HTTP method for the request, defaults to GET
:type method: str
:param params: additional parameters for the request, defaults to None
:type params: dict
:param data: the data of the request, defaults to None
:type data: str
:param expected_response_code: the expected response code of
the request, defaults to 200
:type expected_response_code: int
:param headers: headers to add to the request
:type headers: dict
:returns: the response from the request
:rtype: :class:`requests.Response`
:raises InfluxDBServerError: if the response code is any server error
code (5xx)
:raises InfluxDBClientError: if the response code is not the
same as `expected_response_code` and is not a server error code
"""
url = "{0}/{1}".format(self._baseurl, url)
if headers is None:
headers = self._headers
if params is None:
params = {}
if isinstance(data, (dict, list)):
data = json.dumps(data)
# Try to send the request more than once by default (see #103)
retry = True
_try = 0
while retry:
try:
response = self._session.request(
method=method,
url=url,
auth=(self._username, self._password),
params=params,
data=data,
headers=headers,
proxies=self._proxies,
verify=self._verify_ssl,
timeout=self._timeout
)
break
except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
requests.exceptions.Timeout):
_try += 1
if self._retries != 0:
retry = _try < self._retries
if method == "POST":
time.sleep((2 ** _try) * random.random() / 100.0)
if not retry:
raise
# if there's not an error, there must have been a successful response
if 500 <= response.status_code < 600:
raise InfluxDBServerError(response.content)
elif response.status_code == expected_response_code:
return response
else:
raise InfluxDBClientError(response.content, response.status_code) | python | def request(self, url, method='GET', params=None, data=None,
expected_response_code=200, headers=None):
url = "{0}/{1}".format(self._baseurl, url)
if headers is None:
headers = self._headers
if params is None:
params = {}
if isinstance(data, (dict, list)):
data = json.dumps(data)
# Try to send the request more than once by default (see #103)
retry = True
_try = 0
while retry:
try:
response = self._session.request(
method=method,
url=url,
auth=(self._username, self._password),
params=params,
data=data,
headers=headers,
proxies=self._proxies,
verify=self._verify_ssl,
timeout=self._timeout
)
break
except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
requests.exceptions.Timeout):
_try += 1
if self._retries != 0:
retry = _try < self._retries
if method == "POST":
time.sleep((2 ** _try) * random.random() / 100.0)
if not retry:
raise
# if there's not an error, there must have been a successful response
if 500 <= response.status_code < 600:
raise InfluxDBServerError(response.content)
elif response.status_code == expected_response_code:
return response
else:
raise InfluxDBClientError(response.content, response.status_code) | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"\"{0}/{1}\"",
".",
"format",
... | Make a HTTP request to the InfluxDB API.
:param url: the path of the HTTP request, e.g. write, query, etc.
:type url: str
:param method: the HTTP method for the request, defaults to GET
:type method: str
:param params: additional parameters for the request, defaults to None
:type params: dict
:param data: the data of the request, defaults to None
:type data: str
:param expected_response_code: the expected response code of
the request, defaults to 200
:type expected_response_code: int
:param headers: headers to add to the request
:type headers: dict
:returns: the response from the request
:rtype: :class:`requests.Response`
:raises InfluxDBServerError: if the response code is any server error
code (5xx)
:raises InfluxDBClientError: if the response code is not the
same as `expected_response_code` and is not a server error code | [
"Make",
"a",
"HTTP",
"request",
"to",
"the",
"InfluxDB",
"API",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L218-L286 |
234,006 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.write | def write(self, data, params=None, expected_response_code=204,
protocol='json'):
"""Write data to InfluxDB.
:param data: the data to be written
:type data: (if protocol is 'json') dict
(if protocol is 'line') sequence of line protocol strings
or single string
:param params: additional parameters for the request, defaults to None
:type params: dict
:param expected_response_code: the expected response code of the write
operation, defaults to 204
:type expected_response_code: int
:param protocol: protocol of input data, either 'json' or 'line'
:type protocol: str
:returns: True, if the write operation is successful
:rtype: bool
"""
headers = self._headers
headers['Content-Type'] = 'application/octet-stream'
if params:
precision = params.get('precision')
else:
precision = None
if protocol == 'json':
data = make_lines(data, precision).encode('utf-8')
elif protocol == 'line':
if isinstance(data, str):
data = [data]
data = ('\n'.join(data) + '\n').encode('utf-8')
self.request(
url="write",
method='POST',
params=params,
data=data,
expected_response_code=expected_response_code,
headers=headers
)
return True | python | def write(self, data, params=None, expected_response_code=204,
protocol='json'):
headers = self._headers
headers['Content-Type'] = 'application/octet-stream'
if params:
precision = params.get('precision')
else:
precision = None
if protocol == 'json':
data = make_lines(data, precision).encode('utf-8')
elif protocol == 'line':
if isinstance(data, str):
data = [data]
data = ('\n'.join(data) + '\n').encode('utf-8')
self.request(
url="write",
method='POST',
params=params,
data=data,
expected_response_code=expected_response_code,
headers=headers
)
return True | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"params",
"=",
"None",
",",
"expected_response_code",
"=",
"204",
",",
"protocol",
"=",
"'json'",
")",
":",
"headers",
"=",
"self",
".",
"_headers",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/oc... | Write data to InfluxDB.
:param data: the data to be written
:type data: (if protocol is 'json') dict
(if protocol is 'line') sequence of line protocol strings
or single string
:param params: additional parameters for the request, defaults to None
:type params: dict
:param expected_response_code: the expected response code of the write
operation, defaults to 204
:type expected_response_code: int
:param protocol: protocol of input data, either 'json' or 'line'
:type protocol: str
:returns: True, if the write operation is successful
:rtype: bool | [
"Write",
"data",
"to",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L288-L329 |
234,007 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.query | def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
raise_errors=True,
chunked=False,
chunk_size=0,
method="GET"):
"""Send a query to InfluxDB.
.. danger::
In order to avoid injection vulnerabilities (similar to `SQL
injection <https://www.owasp.org/index.php/SQL_Injection>`_
vulnerabilities), do not directly include untrusted data into the
``query`` parameter, use ``bind_params`` instead.
:param query: the actual query string
:type query: str
:param params: additional parameters for the request,
defaults to {}
:type params: dict
:param bind_params: bind parameters for the query:
any variable in the query written as ``'$var_name'`` will be
replaced with ``bind_params['var_name']``. Only works in the
``WHERE`` clause and takes precedence over ``params['params']``
:type bind_params: dict
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
:type epoch: str
:param expected_response_code: the expected status code of response,
defaults to 200
:type expected_response_code: int
:param database: database to query, defaults to None
:type database: str
:param raise_errors: Whether or not to raise exceptions when InfluxDB
returns errors, defaults to True
:type raise_errors: bool
:param chunked: Enable to use chunked responses from InfluxDB.
With ``chunked`` enabled, one ResultSet is returned per chunk
containing all results within that chunk
:type chunked: bool
:param chunk_size: Size of each chunk to tell InfluxDB to use.
:type chunk_size: int
:param method: the HTTP method for the request, defaults to GET
:type method: str
:returns: the queried data
:rtype: :class:`~.ResultSet`
"""
if params is None:
params = {}
if bind_params is not None:
params_dict = json.loads(params.get('params', '{}'))
params_dict.update(bind_params)
params['params'] = json.dumps(params_dict)
params['q'] = query
params['db'] = database or self._database
if epoch is not None:
params['epoch'] = epoch
if chunked:
params['chunked'] = 'true'
if chunk_size > 0:
params['chunk_size'] = chunk_size
if query.lower().startswith("select ") and " into " in query.lower():
method = "POST"
response = self.request(
url="query",
method=method,
params=params,
data=None,
expected_response_code=expected_response_code
)
if chunked:
return self._read_chunked_response(response)
data = response.json()
results = [
ResultSet(result, raise_errors=raise_errors)
for result
in data.get('results', [])
]
# TODO(aviau): Always return a list. (This would be a breaking change)
if len(results) == 1:
return results[0]
return results | python | def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
raise_errors=True,
chunked=False,
chunk_size=0,
method="GET"):
if params is None:
params = {}
if bind_params is not None:
params_dict = json.loads(params.get('params', '{}'))
params_dict.update(bind_params)
params['params'] = json.dumps(params_dict)
params['q'] = query
params['db'] = database or self._database
if epoch is not None:
params['epoch'] = epoch
if chunked:
params['chunked'] = 'true'
if chunk_size > 0:
params['chunk_size'] = chunk_size
if query.lower().startswith("select ") and " into " in query.lower():
method = "POST"
response = self.request(
url="query",
method=method,
params=params,
data=None,
expected_response_code=expected_response_code
)
if chunked:
return self._read_chunked_response(response)
data = response.json()
results = [
ResultSet(result, raise_errors=raise_errors)
for result
in data.get('results', [])
]
# TODO(aviau): Always return a list. (This would be a breaking change)
if len(results) == 1:
return results[0]
return results | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"params",
"=",
"None",
",",
"bind_params",
"=",
"None",
",",
"epoch",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"database",
"=",
"None",
",",
"raise_errors",
"=",
"True",
",",
"chunked",
... | Send a query to InfluxDB.
.. danger::
In order to avoid injection vulnerabilities (similar to `SQL
injection <https://www.owasp.org/index.php/SQL_Injection>`_
vulnerabilities), do not directly include untrusted data into the
``query`` parameter, use ``bind_params`` instead.
:param query: the actual query string
:type query: str
:param params: additional parameters for the request,
defaults to {}
:type params: dict
:param bind_params: bind parameters for the query:
any variable in the query written as ``'$var_name'`` will be
replaced with ``bind_params['var_name']``. Only works in the
``WHERE`` clause and takes precedence over ``params['params']``
:type bind_params: dict
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
:type epoch: str
:param expected_response_code: the expected status code of response,
defaults to 200
:type expected_response_code: int
:param database: database to query, defaults to None
:type database: str
:param raise_errors: Whether or not to raise exceptions when InfluxDB
returns errors, defaults to True
:type raise_errors: bool
:param chunked: Enable to use chunked responses from InfluxDB.
With ``chunked`` enabled, one ResultSet is returned per chunk
containing all results within that chunk
:type chunked: bool
:param chunk_size: Size of each chunk to tell InfluxDB to use.
:type chunk_size: int
:param method: the HTTP method for the request, defaults to GET
:type method: str
:returns: the queried data
:rtype: :class:`~.ResultSet` | [
"Send",
"a",
"query",
"to",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L345-L452 |
234,008 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.ping | def ping(self):
"""Check connectivity to InfluxDB.
:returns: The version of the InfluxDB the client is connected to
"""
response = self.request(
url="ping",
method='GET',
expected_response_code=204
)
return response.headers['X-Influxdb-Version'] | python | def ping(self):
response = self.request(
url="ping",
method='GET',
expected_response_code=204
)
return response.headers['X-Influxdb-Version'] | [
"def",
"ping",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"url",
"=",
"\"ping\"",
",",
"method",
"=",
"'GET'",
",",
"expected_response_code",
"=",
"204",
")",
"return",
"response",
".",
"headers",
"[",
"'X-Influxdb-Version'",
"]"
... | Check connectivity to InfluxDB.
:returns: The version of the InfluxDB the client is connected to | [
"Check",
"connectivity",
"to",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L516-L527 |
234,009 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.create_retention_policy | def create_retention_policy(self, name, duration, replication,
database=None,
default=False, shard_duration="0s"):
"""Create a retention policy for a database.
:param name: the name of the new retention policy
:type name: str
:param duration: the duration of the new retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. For infinite retention - meaning the data will
never be deleted - use 'INF' for duration.
The minimum retention period is 1 hour.
:type duration: str
:param replication: the replication of the retention policy
:type replication: str
:param database: the database for which the retention policy is
created. Defaults to current client's database
:type database: str
:param default: whether or not to set the policy as default
:type default: bool
:param shard_duration: the shard duration of the retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. Infinite retention is not supported. As a workaround,
specify a "1000w" duration to achieve an extremely long shard group
duration. Defaults to "0s", which is interpreted by the database
to mean the default value given the duration.
The minimum shard group duration is 1 hour.
:type shard_duration: str
"""
query_string = \
"CREATE RETENTION POLICY {0} ON {1} " \
"DURATION {2} REPLICATION {3} SHARD DURATION {4}".format(
quote_ident(name), quote_ident(database or self._database),
duration, replication, shard_duration)
if default is True:
query_string += " DEFAULT"
self.query(query_string, method="POST") | python | def create_retention_policy(self, name, duration, replication,
database=None,
default=False, shard_duration="0s"):
query_string = \
"CREATE RETENTION POLICY {0} ON {1} " \
"DURATION {2} REPLICATION {3} SHARD DURATION {4}".format(
quote_ident(name), quote_ident(database or self._database),
duration, replication, shard_duration)
if default is True:
query_string += " DEFAULT"
self.query(query_string, method="POST") | [
"def",
"create_retention_policy",
"(",
"self",
",",
"name",
",",
"duration",
",",
"replication",
",",
"database",
"=",
"None",
",",
"default",
"=",
"False",
",",
"shard_duration",
"=",
"\"0s\"",
")",
":",
"query_string",
"=",
"\"CREATE RETENTION POLICY {0} ON {1} ... | Create a retention policy for a database.
:param name: the name of the new retention policy
:type name: str
:param duration: the duration of the new retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. For infinite retention - meaning the data will
never be deleted - use 'INF' for duration.
The minimum retention period is 1 hour.
:type duration: str
:param replication: the replication of the retention policy
:type replication: str
:param database: the database for which the retention policy is
created. Defaults to current client's database
:type database: str
:param default: whether or not to set the policy as default
:type default: bool
:param shard_duration: the shard duration of the retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. Infinite retention is not supported. As a workaround,
specify a "1000w" duration to achieve an extremely long shard group
duration. Defaults to "0s", which is interpreted by the database
to mean the default value given the duration.
The minimum shard group duration is 1 hour.
:type shard_duration: str | [
"Create",
"a",
"retention",
"policy",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L648-L688 |
234,010 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.alter_retention_policy | def alter_retention_policy(self, name, database=None,
duration=None, replication=None,
default=None, shard_duration=None):
"""Modify an existing retention policy for a database.
:param name: the name of the retention policy to modify
:type name: str
:param database: the database for which the retention policy is
modified. Defaults to current client's database
:type database: str
:param duration: the new duration of the existing retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. For infinite retention, meaning the data will
never be deleted, use 'INF' for duration.
The minimum retention period is 1 hour.
:type duration: str
:param replication: the new replication of the existing
retention policy
:type replication: int
:param default: whether or not to set the modified policy as default
:type default: bool
:param shard_duration: the shard duration of the retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. Infinite retention is not supported. As a workaround,
specify a "1000w" duration to achieve an extremely long shard group
duration.
The minimum shard group duration is 1 hour.
:type shard_duration: str
.. note:: at least one of duration, replication, or default flag
should be set. Otherwise the operation will fail.
"""
query_string = (
"ALTER RETENTION POLICY {0} ON {1}"
).format(quote_ident(name),
quote_ident(database or self._database), shard_duration)
if duration:
query_string += " DURATION {0}".format(duration)
if shard_duration:
query_string += " SHARD DURATION {0}".format(shard_duration)
if replication:
query_string += " REPLICATION {0}".format(replication)
if default is True:
query_string += " DEFAULT"
self.query(query_string, method="POST") | python | def alter_retention_policy(self, name, database=None,
duration=None, replication=None,
default=None, shard_duration=None):
query_string = (
"ALTER RETENTION POLICY {0} ON {1}"
).format(quote_ident(name),
quote_ident(database or self._database), shard_duration)
if duration:
query_string += " DURATION {0}".format(duration)
if shard_duration:
query_string += " SHARD DURATION {0}".format(shard_duration)
if replication:
query_string += " REPLICATION {0}".format(replication)
if default is True:
query_string += " DEFAULT"
self.query(query_string, method="POST") | [
"def",
"alter_retention_policy",
"(",
"self",
",",
"name",
",",
"database",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"replication",
"=",
"None",
",",
"default",
"=",
"None",
",",
"shard_duration",
"=",
"None",
")",
":",
"query_string",
"=",
"(",
"... | Modify an existing retention policy for a database.
:param name: the name of the retention policy to modify
:type name: str
:param database: the database for which the retention policy is
modified. Defaults to current client's database
:type database: str
:param duration: the new duration of the existing retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. For infinite retention, meaning the data will
never be deleted, use 'INF' for duration.
The minimum retention period is 1 hour.
:type duration: str
:param replication: the new replication of the existing
retention policy
:type replication: int
:param default: whether or not to set the modified policy as default
:type default: bool
:param shard_duration: the shard duration of the retention policy.
Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
respectively. Infinite retention is not supported. As a workaround,
specify a "1000w" duration to achieve an extremely long shard group
duration.
The minimum shard group duration is 1 hour.
:type shard_duration: str
.. note:: at least one of duration, replication, or default flag
should be set. Otherwise the operation will fail. | [
"Modify",
"an",
"existing",
"retention",
"policy",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L690-L737 |
234,011 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.drop_retention_policy | def drop_retention_policy(self, name, database=None):
"""Drop an existing retention policy for a database.
:param name: the name of the retention policy to drop
:type name: str
:param database: the database for which the retention policy is
dropped. Defaults to current client's database
:type database: str
"""
query_string = (
"DROP RETENTION POLICY {0} ON {1}"
).format(quote_ident(name), quote_ident(database or self._database))
self.query(query_string, method="POST") | python | def drop_retention_policy(self, name, database=None):
query_string = (
"DROP RETENTION POLICY {0} ON {1}"
).format(quote_ident(name), quote_ident(database or self._database))
self.query(query_string, method="POST") | [
"def",
"drop_retention_policy",
"(",
"self",
",",
"name",
",",
"database",
"=",
"None",
")",
":",
"query_string",
"=",
"(",
"\"DROP RETENTION POLICY {0} ON {1}\"",
")",
".",
"format",
"(",
"quote_ident",
"(",
"name",
")",
",",
"quote_ident",
"(",
"database",
"... | Drop an existing retention policy for a database.
:param name: the name of the retention policy to drop
:type name: str
:param database: the database for which the retention policy is
dropped. Defaults to current client's database
:type database: str | [
"Drop",
"an",
"existing",
"retention",
"policy",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L739-L751 |
234,012 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.get_list_retention_policies | def get_list_retention_policies(self, database=None):
"""Get the list of retention policies for a database.
:param database: the name of the database, defaults to the client's
current database
:type database: str
:returns: all retention policies for the database
:rtype: list of dictionaries
:Example:
::
>> ret_policies = client.get_list_retention_policies('my_db')
>> ret_policies
[{u'default': True,
u'duration': u'0',
u'name': u'default',
u'replicaN': 1}]
"""
if not (database or self._database):
raise InfluxDBClientError(
"get_list_retention_policies() requires a database as a "
"parameter or the client to be using a database")
rsp = self.query(
"SHOW RETENTION POLICIES ON {0}".format(
quote_ident(database or self._database))
)
return list(rsp.get_points()) | python | def get_list_retention_policies(self, database=None):
if not (database or self._database):
raise InfluxDBClientError(
"get_list_retention_policies() requires a database as a "
"parameter or the client to be using a database")
rsp = self.query(
"SHOW RETENTION POLICIES ON {0}".format(
quote_ident(database or self._database))
)
return list(rsp.get_points()) | [
"def",
"get_list_retention_policies",
"(",
"self",
",",
"database",
"=",
"None",
")",
":",
"if",
"not",
"(",
"database",
"or",
"self",
".",
"_database",
")",
":",
"raise",
"InfluxDBClientError",
"(",
"\"get_list_retention_policies() requires a database as a \"",
"\"pa... | Get the list of retention policies for a database.
:param database: the name of the database, defaults to the client's
current database
:type database: str
:returns: all retention policies for the database
:rtype: list of dictionaries
:Example:
::
>> ret_policies = client.get_list_retention_policies('my_db')
>> ret_policies
[{u'default': True,
u'duration': u'0',
u'name': u'default',
u'replicaN': 1}] | [
"Get",
"the",
"list",
"of",
"retention",
"policies",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L753-L782 |
234,013 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.create_user | def create_user(self, username, password, admin=False):
"""Create a new user in InfluxDB.
:param username: the new username to create
:type username: str
:param password: the password for the new user
:type password: str
:param admin: whether the user should have cluster administration
privileges or not
:type admin: boolean
"""
text = "CREATE USER {0} WITH PASSWORD {1}".format(
quote_ident(username), quote_literal(password))
if admin:
text += ' WITH ALL PRIVILEGES'
self.query(text, method="POST") | python | def create_user(self, username, password, admin=False):
text = "CREATE USER {0} WITH PASSWORD {1}".format(
quote_ident(username), quote_literal(password))
if admin:
text += ' WITH ALL PRIVILEGES'
self.query(text, method="POST") | [
"def",
"create_user",
"(",
"self",
",",
"username",
",",
"password",
",",
"admin",
"=",
"False",
")",
":",
"text",
"=",
"\"CREATE USER {0} WITH PASSWORD {1}\"",
".",
"format",
"(",
"quote_ident",
"(",
"username",
")",
",",
"quote_literal",
"(",
"password",
")"... | Create a new user in InfluxDB.
:param username: the new username to create
:type username: str
:param password: the password for the new user
:type password: str
:param admin: whether the user should have cluster administration
privileges or not
:type admin: boolean | [
"Create",
"a",
"new",
"user",
"in",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L802-L817 |
234,014 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.drop_user | def drop_user(self, username):
"""Drop a user from InfluxDB.
:param username: the username to drop
:type username: str
"""
text = "DROP USER {0}".format(quote_ident(username), method="POST")
self.query(text, method="POST") | python | def drop_user(self, username):
text = "DROP USER {0}".format(quote_ident(username), method="POST")
self.query(text, method="POST") | [
"def",
"drop_user",
"(",
"self",
",",
"username",
")",
":",
"text",
"=",
"\"DROP USER {0}\"",
".",
"format",
"(",
"quote_ident",
"(",
"username",
")",
",",
"method",
"=",
"\"POST\"",
")",
"self",
".",
"query",
"(",
"text",
",",
"method",
"=",
"\"POST\"",... | Drop a user from InfluxDB.
:param username: the username to drop
:type username: str | [
"Drop",
"a",
"user",
"from",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L819-L826 |
234,015 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.set_user_password | def set_user_password(self, username, password):
"""Change the password of an existing user.
:param username: the username who's password is being changed
:type username: str
:param password: the new password for the user
:type password: str
"""
text = "SET PASSWORD FOR {0} = {1}".format(
quote_ident(username), quote_literal(password))
self.query(text) | python | def set_user_password(self, username, password):
text = "SET PASSWORD FOR {0} = {1}".format(
quote_ident(username), quote_literal(password))
self.query(text) | [
"def",
"set_user_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"text",
"=",
"\"SET PASSWORD FOR {0} = {1}\"",
".",
"format",
"(",
"quote_ident",
"(",
"username",
")",
",",
"quote_literal",
"(",
"password",
")",
")",
"self",
".",
"query",
... | Change the password of an existing user.
:param username: the username who's password is being changed
:type username: str
:param password: the new password for the user
:type password: str | [
"Change",
"the",
"password",
"of",
"an",
"existing",
"user",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L828-L838 |
234,016 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.delete_series | def delete_series(self, database=None, measurement=None, tags=None):
"""Delete series from a database.
Series must be filtered by either measurement and tags.
This method cannot be used to delete all series, use
`drop_database` instead.
:param database: the database from which the series should be
deleted, defaults to client's current database
:type database: str
:param measurement: Delete all series from a measurement
:type measurement: str
:param tags: Delete all series that match given tags
:type tags: dict
"""
database = database or self._database
query_str = 'DROP SERIES'
if measurement:
query_str += ' FROM {0}'.format(quote_ident(measurement))
if tags:
tag_eq_list = ["{0}={1}".format(quote_ident(k), quote_literal(v))
for k, v in tags.items()]
query_str += ' WHERE ' + ' AND '.join(tag_eq_list)
self.query(query_str, database=database, method="POST") | python | def delete_series(self, database=None, measurement=None, tags=None):
database = database or self._database
query_str = 'DROP SERIES'
if measurement:
query_str += ' FROM {0}'.format(quote_ident(measurement))
if tags:
tag_eq_list = ["{0}={1}".format(quote_ident(k), quote_literal(v))
for k, v in tags.items()]
query_str += ' WHERE ' + ' AND '.join(tag_eq_list)
self.query(query_str, database=database, method="POST") | [
"def",
"delete_series",
"(",
"self",
",",
"database",
"=",
"None",
",",
"measurement",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"database",
"=",
"database",
"or",
"self",
".",
"_database",
"query_str",
"=",
"'DROP SERIES'",
"if",
"measurement",
":"... | Delete series from a database.
Series must be filtered by either measurement and tags.
This method cannot be used to delete all series, use
`drop_database` instead.
:param database: the database from which the series should be
deleted, defaults to client's current database
:type database: str
:param measurement: Delete all series from a measurement
:type measurement: str
:param tags: Delete all series that match given tags
:type tags: dict | [
"Delete",
"series",
"from",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L840-L864 |
234,017 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.get_list_privileges | def get_list_privileges(self, username):
"""Get the list of all privileges granted to given user.
:param username: the username to get privileges of
:type username: str
:returns: all privileges granted to given user
:rtype: list of dictionaries
:Example:
::
>> privileges = client.get_list_privileges('user1')
>> privileges
[{u'privilege': u'WRITE', u'database': u'db1'},
{u'privilege': u'ALL PRIVILEGES', u'database': u'db2'},
{u'privilege': u'NO PRIVILEGES', u'database': u'db3'}]
"""
text = "SHOW GRANTS FOR {0}".format(quote_ident(username))
return list(self.query(text).get_points()) | python | def get_list_privileges(self, username):
text = "SHOW GRANTS FOR {0}".format(quote_ident(username))
return list(self.query(text).get_points()) | [
"def",
"get_list_privileges",
"(",
"self",
",",
"username",
")",
":",
"text",
"=",
"\"SHOW GRANTS FOR {0}\"",
".",
"format",
"(",
"quote_ident",
"(",
"username",
")",
")",
"return",
"list",
"(",
"self",
".",
"query",
"(",
"text",
")",
".",
"get_points",
"(... | Get the list of all privileges granted to given user.
:param username: the username to get privileges of
:type username: str
:returns: all privileges granted to given user
:rtype: list of dictionaries
:Example:
::
>> privileges = client.get_list_privileges('user1')
>> privileges
[{u'privilege': u'WRITE', u'database': u'db1'},
{u'privilege': u'ALL PRIVILEGES', u'database': u'db2'},
{u'privilege': u'NO PRIVILEGES', u'database': u'db3'}] | [
"Get",
"the",
"list",
"of",
"all",
"privileges",
"granted",
"to",
"given",
"user",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L922-L942 |
234,018 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.get_list_continuous_queries | def get_list_continuous_queries(self):
"""Get the list of continuous queries in InfluxDB.
:return: all CQs in InfluxDB
:rtype: list of dictionaries
:Example:
::
>> cqs = client.get_list_cqs()
>> cqs
[
{
u'db1': []
},
{
u'db2': [
{
u'name': u'vampire',
u'query': u'CREATE CONTINUOUS QUERY vampire ON '
'mydb BEGIN SELECT count(dracula) INTO '
'mydb.autogen.all_of_them FROM '
'mydb.autogen.one GROUP BY time(5m) END'
}
]
}
]
"""
query_string = "SHOW CONTINUOUS QUERIES"
return [{sk[0]: list(p)} for sk, p in self.query(query_string).items()] | python | def get_list_continuous_queries(self):
query_string = "SHOW CONTINUOUS QUERIES"
return [{sk[0]: list(p)} for sk, p in self.query(query_string).items()] | [
"def",
"get_list_continuous_queries",
"(",
"self",
")",
":",
"query_string",
"=",
"\"SHOW CONTINUOUS QUERIES\"",
"return",
"[",
"{",
"sk",
"[",
"0",
"]",
":",
"list",
"(",
"p",
")",
"}",
"for",
"sk",
",",
"p",
"in",
"self",
".",
"query",
"(",
"query_stri... | Get the list of continuous queries in InfluxDB.
:return: all CQs in InfluxDB
:rtype: list of dictionaries
:Example:
::
>> cqs = client.get_list_cqs()
>> cqs
[
{
u'db1': []
},
{
u'db2': [
{
u'name': u'vampire',
u'query': u'CREATE CONTINUOUS QUERY vampire ON '
'mydb BEGIN SELECT count(dracula) INTO '
'mydb.autogen.all_of_them FROM '
'mydb.autogen.one GROUP BY time(5m) END'
}
]
}
] | [
"Get",
"the",
"list",
"of",
"continuous",
"queries",
"in",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L944-L974 |
234,019 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.create_continuous_query | def create_continuous_query(self, name, select, database=None,
resample_opts=None):
r"""Create a continuous query for a database.
:param name: the name of continuous query to create
:type name: str
:param select: select statement for the continuous query
:type select: str
:param database: the database for which the continuous query is
created. Defaults to current client's database
:type database: str
:param resample_opts: resample options
:type resample_opts: str
:Example:
::
>> select_clause = 'SELECT mean("value") INTO "cpu_mean" ' \
... 'FROM "cpu" GROUP BY time(1m)'
>> client.create_continuous_query(
... 'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m'
... )
>> client.get_list_continuous_queries()
[
{
'db_name': [
{
'name': 'cpu_mean',
'query': 'CREATE CONTINUOUS QUERY "cpu_mean" '
'ON "db_name" '
'RESAMPLE EVERY 10s FOR 2m '
'BEGIN SELECT mean("value") '
'INTO "cpu_mean" FROM "cpu" '
'GROUP BY time(1m) END'
}
]
}
]
"""
query_string = (
"CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END"
).format(quote_ident(name), quote_ident(database or self._database),
' RESAMPLE ' + resample_opts if resample_opts else '', select)
self.query(query_string) | python | def create_continuous_query(self, name, select, database=None,
resample_opts=None):
r"""Create a continuous query for a database.
:param name: the name of continuous query to create
:type name: str
:param select: select statement for the continuous query
:type select: str
:param database: the database for which the continuous query is
created. Defaults to current client's database
:type database: str
:param resample_opts: resample options
:type resample_opts: str
:Example:
::
>> select_clause = 'SELECT mean("value") INTO "cpu_mean" ' \
... 'FROM "cpu" GROUP BY time(1m)'
>> client.create_continuous_query(
... 'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m'
... )
>> client.get_list_continuous_queries()
[
{
'db_name': [
{
'name': 'cpu_mean',
'query': 'CREATE CONTINUOUS QUERY "cpu_mean" '
'ON "db_name" '
'RESAMPLE EVERY 10s FOR 2m '
'BEGIN SELECT mean("value") '
'INTO "cpu_mean" FROM "cpu" '
'GROUP BY time(1m) END'
}
]
}
]
"""
query_string = (
"CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END"
).format(quote_ident(name), quote_ident(database or self._database),
' RESAMPLE ' + resample_opts if resample_opts else '', select)
self.query(query_string) | [
"def",
"create_continuous_query",
"(",
"self",
",",
"name",
",",
"select",
",",
"database",
"=",
"None",
",",
"resample_opts",
"=",
"None",
")",
":",
"query_string",
"=",
"(",
"\"CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END\"",
")",
".",
"format",
"(",
"quo... | r"""Create a continuous query for a database.
:param name: the name of continuous query to create
:type name: str
:param select: select statement for the continuous query
:type select: str
:param database: the database for which the continuous query is
created. Defaults to current client's database
:type database: str
:param resample_opts: resample options
:type resample_opts: str
:Example:
::
>> select_clause = 'SELECT mean("value") INTO "cpu_mean" ' \
... 'FROM "cpu" GROUP BY time(1m)'
>> client.create_continuous_query(
... 'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m'
... )
>> client.get_list_continuous_queries()
[
{
'db_name': [
{
'name': 'cpu_mean',
'query': 'CREATE CONTINUOUS QUERY "cpu_mean" '
'ON "db_name" '
'RESAMPLE EVERY 10s FOR 2m '
'BEGIN SELECT mean("value") '
'INTO "cpu_mean" FROM "cpu" '
'GROUP BY time(1m) END'
}
]
}
] | [
"r",
"Create",
"a",
"continuous",
"query",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L976-L1020 |
234,020 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.drop_continuous_query | def drop_continuous_query(self, name, database=None):
"""Drop an existing continuous query for a database.
:param name: the name of continuous query to drop
:type name: str
:param database: the database for which the continuous query is
dropped. Defaults to current client's database
:type database: str
"""
query_string = (
"DROP CONTINUOUS QUERY {0} ON {1}"
).format(quote_ident(name), quote_ident(database or self._database))
self.query(query_string) | python | def drop_continuous_query(self, name, database=None):
query_string = (
"DROP CONTINUOUS QUERY {0} ON {1}"
).format(quote_ident(name), quote_ident(database or self._database))
self.query(query_string) | [
"def",
"drop_continuous_query",
"(",
"self",
",",
"name",
",",
"database",
"=",
"None",
")",
":",
"query_string",
"=",
"(",
"\"DROP CONTINUOUS QUERY {0} ON {1}\"",
")",
".",
"format",
"(",
"quote_ident",
"(",
"name",
")",
",",
"quote_ident",
"(",
"database",
"... | Drop an existing continuous query for a database.
:param name: the name of continuous query to drop
:type name: str
:param database: the database for which the continuous query is
dropped. Defaults to current client's database
:type database: str | [
"Drop",
"an",
"existing",
"continuous",
"query",
"for",
"a",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L1022-L1034 |
234,021 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.send_packet | def send_packet(self, packet, protocol='json', time_precision=None):
"""Send an UDP packet.
:param packet: the packet to be sent
:type packet: (if protocol is 'json') dict
(if protocol is 'line') list of line protocol strings
:param protocol: protocol of input data, either 'json' or 'line'
:type protocol: str
:param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None
:type time_precision: str
"""
if protocol == 'json':
data = make_lines(packet, time_precision).encode('utf-8')
elif protocol == 'line':
data = ('\n'.join(packet) + '\n').encode('utf-8')
self.udp_socket.sendto(data, (self._host, self._udp_port)) | python | def send_packet(self, packet, protocol='json', time_precision=None):
if protocol == 'json':
data = make_lines(packet, time_precision).encode('utf-8')
elif protocol == 'line':
data = ('\n'.join(packet) + '\n').encode('utf-8')
self.udp_socket.sendto(data, (self._host, self._udp_port)) | [
"def",
"send_packet",
"(",
"self",
",",
"packet",
",",
"protocol",
"=",
"'json'",
",",
"time_precision",
"=",
"None",
")",
":",
"if",
"protocol",
"==",
"'json'",
":",
"data",
"=",
"make_lines",
"(",
"packet",
",",
"time_precision",
")",
".",
"encode",
"(... | Send an UDP packet.
:param packet: the packet to be sent
:type packet: (if protocol is 'json') dict
(if protocol is 'line') list of line protocol strings
:param protocol: protocol of input data, either 'json' or 'line'
:type protocol: str
:param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None
:type time_precision: str | [
"Send",
"an",
"UDP",
"packet",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L1036-L1051 |
234,022 | influxdata/influxdb-python | influxdb/client.py | InfluxDBClient.close | def close(self):
"""Close http session."""
if isinstance(self._session, requests.Session):
self._session.close() | python | def close(self):
if isinstance(self._session, requests.Session):
self._session.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_session",
",",
"requests",
".",
"Session",
")",
":",
"self",
".",
"_session",
".",
"close",
"(",
")"
] | Close http session. | [
"Close",
"http",
"session",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L1053-L1056 |
234,023 | influxdata/influxdb-python | influxdb/chunked_json.py | loads | def loads(s):
"""Generate a sequence of JSON values from a string."""
_decoder = json.JSONDecoder()
while s:
s = s.strip()
obj, pos = _decoder.raw_decode(s)
if not pos:
raise ValueError('no JSON object found at %i' % pos)
yield obj
s = s[pos:] | python | def loads(s):
_decoder = json.JSONDecoder()
while s:
s = s.strip()
obj, pos = _decoder.raw_decode(s)
if not pos:
raise ValueError('no JSON object found at %i' % pos)
yield obj
s = s[pos:] | [
"def",
"loads",
"(",
"s",
")",
":",
"_decoder",
"=",
"json",
".",
"JSONDecoder",
"(",
")",
"while",
"s",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"obj",
",",
"pos",
"=",
"_decoder",
".",
"raw_decode",
"(",
"s",
")",
"if",
"not",
"pos",
":",
... | Generate a sequence of JSON values from a string. | [
"Generate",
"a",
"sequence",
"of",
"JSON",
"values",
"from",
"a",
"string",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/chunked_json.py#L17-L27 |
234,024 | influxdata/influxdb-python | influxdb/influxdb08/helper.py | SeriesHelper.commit | def commit(cls, client=None):
"""Commit everything from datapoints via the client.
:param client: InfluxDBClient instance for writing points to InfluxDB.
:attention: any provided client will supersede the class client.
:return: result of client.write_points.
"""
if not client:
client = cls._client
rtn = client.write_points(cls._json_body_())
cls._reset_()
return rtn | python | def commit(cls, client=None):
if not client:
client = cls._client
rtn = client.write_points(cls._json_body_())
cls._reset_()
return rtn | [
"def",
"commit",
"(",
"cls",
",",
"client",
"=",
"None",
")",
":",
"if",
"not",
"client",
":",
"client",
"=",
"cls",
".",
"_client",
"rtn",
"=",
"client",
".",
"write_points",
"(",
"cls",
".",
"_json_body_",
"(",
")",
")",
"cls",
".",
"_reset_",
"(... | Commit everything from datapoints via the client.
:param client: InfluxDBClient instance for writing points to InfluxDB.
:attention: any provided client will supersede the class client.
:return: result of client.write_points. | [
"Commit",
"everything",
"from",
"datapoints",
"via",
"the",
"client",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/helper.py#L122-L133 |
234,025 | influxdata/influxdb-python | influxdb/influxdb08/helper.py | SeriesHelper._json_body_ | def _json_body_(cls):
"""Return JSON body of the datapoints.
:return: JSON body of the datapoints.
"""
json = []
for series_name, data in six.iteritems(cls._datapoints):
json.append({'name': series_name,
'columns': cls._fields,
'points': [[getattr(point, k) for k in cls._fields]
for point in data]
})
return json | python | def _json_body_(cls):
json = []
for series_name, data in six.iteritems(cls._datapoints):
json.append({'name': series_name,
'columns': cls._fields,
'points': [[getattr(point, k) for k in cls._fields]
for point in data]
})
return json | [
"def",
"_json_body_",
"(",
"cls",
")",
":",
"json",
"=",
"[",
"]",
"for",
"series_name",
",",
"data",
"in",
"six",
".",
"iteritems",
"(",
"cls",
".",
"_datapoints",
")",
":",
"json",
".",
"append",
"(",
"{",
"'name'",
":",
"series_name",
",",
"'colum... | Return JSON body of the datapoints.
:return: JSON body of the datapoints. | [
"Return",
"JSON",
"body",
"of",
"the",
"datapoints",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/helper.py#L136-L148 |
234,026 | influxdata/influxdb-python | influxdb/_dataframe_client.py | DataFrameClient.query | def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
raise_errors=True,
chunked=False,
chunk_size=0,
method="GET",
dropna=True):
"""
Query data into a DataFrame.
.. danger::
In order to avoid injection vulnerabilities (similar to `SQL
injection <https://www.owasp.org/index.php/SQL_Injection>`_
vulnerabilities), do not directly include untrusted data into the
``query`` parameter, use ``bind_params`` instead.
:param query: the actual query string
:param params: additional parameters for the request, defaults to {}
:param bind_params: bind parameters for the query:
any variable in the query written as ``'$var_name'`` will be
replaced with ``bind_params['var_name']``. Only works in the
``WHERE`` clause and takes precedence over ``params['params']``
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
:param expected_response_code: the expected status code of response,
defaults to 200
:param database: database to query, defaults to None
:param raise_errors: Whether or not to raise exceptions when InfluxDB
returns errors, defaults to True
:param chunked: Enable to use chunked responses from InfluxDB.
With ``chunked`` enabled, one ResultSet is returned per chunk
containing all results within that chunk
:param chunk_size: Size of each chunk to tell InfluxDB to use.
:param dropna: drop columns where all values are missing
:returns: the queried data
:rtype: :class:`~.ResultSet`
"""
query_args = dict(params=params,
bind_params=bind_params,
epoch=epoch,
expected_response_code=expected_response_code,
raise_errors=raise_errors,
chunked=chunked,
database=database,
method=method,
chunk_size=chunk_size)
results = super(DataFrameClient, self).query(query, **query_args)
if query.strip().upper().startswith("SELECT"):
if len(results) > 0:
return self._to_dataframe(results, dropna)
else:
return {}
else:
return results | python | def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
raise_errors=True,
chunked=False,
chunk_size=0,
method="GET",
dropna=True):
query_args = dict(params=params,
bind_params=bind_params,
epoch=epoch,
expected_response_code=expected_response_code,
raise_errors=raise_errors,
chunked=chunked,
database=database,
method=method,
chunk_size=chunk_size)
results = super(DataFrameClient, self).query(query, **query_args)
if query.strip().upper().startswith("SELECT"):
if len(results) > 0:
return self._to_dataframe(results, dropna)
else:
return {}
else:
return results | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"params",
"=",
"None",
",",
"bind_params",
"=",
"None",
",",
"epoch",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"database",
"=",
"None",
",",
"raise_errors",
"=",
"True",
",",
"chunked",
... | Query data into a DataFrame.
.. danger::
In order to avoid injection vulnerabilities (similar to `SQL
injection <https://www.owasp.org/index.php/SQL_Injection>`_
vulnerabilities), do not directly include untrusted data into the
``query`` parameter, use ``bind_params`` instead.
:param query: the actual query string
:param params: additional parameters for the request, defaults to {}
:param bind_params: bind parameters for the query:
any variable in the query written as ``'$var_name'`` will be
replaced with ``bind_params['var_name']``. Only works in the
``WHERE`` clause and takes precedence over ``params['params']``
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
:param expected_response_code: the expected status code of response,
defaults to 200
:param database: database to query, defaults to None
:param raise_errors: Whether or not to raise exceptions when InfluxDB
returns errors, defaults to True
:param chunked: Enable to use chunked responses from InfluxDB.
With ``chunked`` enabled, one ResultSet is returned per chunk
containing all results within that chunk
:param chunk_size: Size of each chunk to tell InfluxDB to use.
:param dropna: drop columns where all values are missing
:returns: the queried data
:rtype: :class:`~.ResultSet` | [
"Query",
"data",
"into",
"a",
"DataFrame",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/_dataframe_client.py#L142-L201 |
234,027 | influxdata/influxdb-python | examples/tutorial.py | main | def main(host='localhost', port=8086):
"""Instantiate a connection to the InfluxDB."""
user = 'root'
password = 'root'
dbname = 'example'
dbuser = 'smly'
dbuser_password = 'my_secret_password'
query = 'select Float_value from cpu_load_short;'
query_where = 'select Int_value from cpu_load_short where host=$host;'
bind_params = {'host': 'server01'}
json_body = [
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z",
"fields": {
"Float_value": 0.64,
"Int_value": 3,
"String_value": "Text",
"Bool_value": True
}
}
]
client = InfluxDBClient(host, port, user, password, dbname)
print("Create database: " + dbname)
client.create_database(dbname)
print("Create a retention policy")
client.create_retention_policy('awesome_policy', '3d', 3, default=True)
print("Switch user: " + dbuser)
client.switch_user(dbuser, dbuser_password)
print("Write points: {0}".format(json_body))
client.write_points(json_body)
print("Querying data: " + query)
result = client.query(query)
print("Result: {0}".format(result))
print("Querying data: " + query_where)
result = client.query(query_where, bind_params=bind_params)
print("Result: {0}".format(result))
print("Switch user: " + user)
client.switch_user(user, password)
print("Drop database: " + dbname)
client.drop_database(dbname) | python | def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'example'
dbuser = 'smly'
dbuser_password = 'my_secret_password'
query = 'select Float_value from cpu_load_short;'
query_where = 'select Int_value from cpu_load_short where host=$host;'
bind_params = {'host': 'server01'}
json_body = [
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z",
"fields": {
"Float_value": 0.64,
"Int_value": 3,
"String_value": "Text",
"Bool_value": True
}
}
]
client = InfluxDBClient(host, port, user, password, dbname)
print("Create database: " + dbname)
client.create_database(dbname)
print("Create a retention policy")
client.create_retention_policy('awesome_policy', '3d', 3, default=True)
print("Switch user: " + dbuser)
client.switch_user(dbuser, dbuser_password)
print("Write points: {0}".format(json_body))
client.write_points(json_body)
print("Querying data: " + query)
result = client.query(query)
print("Result: {0}".format(result))
print("Querying data: " + query_where)
result = client.query(query_where, bind_params=bind_params)
print("Result: {0}".format(result))
print("Switch user: " + user)
client.switch_user(user, password)
print("Drop database: " + dbname)
client.drop_database(dbname) | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
")",
":",
"user",
"=",
"'root'",
"password",
"=",
"'root'",
"dbname",
"=",
"'example'",
"dbuser",
"=",
"'smly'",
"dbuser_password",
"=",
"'my_secret_password'",
"query",
"=",
"'select ... | Instantiate a connection to the InfluxDB. | [
"Instantiate",
"a",
"connection",
"to",
"the",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/examples/tutorial.py#L9-L64 |
234,028 | influxdata/influxdb-python | examples/tutorial_udp.py | main | def main(uport):
"""Instantiate connection to the InfluxDB."""
# NOTE: structure of the UDP packet is different than that of information
# sent via HTTP
json_body = {
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z",
"points": [{
"measurement": "cpu_load_short",
"fields": {
"value": 0.64
}
},
{
"measurement": "cpu_load_short",
"fields": {
"value": 0.67
}
}]
}
# make `use_udp` True and add `udp_port` number from `influxdb.conf` file
# no need to mention the database name since it is already configured
client = InfluxDBClient(use_udp=True, udp_port=uport)
# Instead of `write_points` use `send_packet`
client.send_packet(json_body) | python | def main(uport):
# NOTE: structure of the UDP packet is different than that of information
# sent via HTTP
json_body = {
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z",
"points": [{
"measurement": "cpu_load_short",
"fields": {
"value": 0.64
}
},
{
"measurement": "cpu_load_short",
"fields": {
"value": 0.67
}
}]
}
# make `use_udp` True and add `udp_port` number from `influxdb.conf` file
# no need to mention the database name since it is already configured
client = InfluxDBClient(use_udp=True, udp_port=uport)
# Instead of `write_points` use `send_packet`
client.send_packet(json_body) | [
"def",
"main",
"(",
"uport",
")",
":",
"# NOTE: structure of the UDP packet is different than that of information",
"# sent via HTTP",
"json_body",
"=",
"{",
"\"tags\"",
":",
"{",
"\"host\"",
":",
"\"server01\"",
",",
"\"region\"",
":",
"\"us-west\"",
"}",
",",
"\... | Instantiate connection to the InfluxDB. | [
"Instantiate",
"connection",
"to",
"the",
"InfluxDB",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/examples/tutorial_udp.py#L23-L52 |
234,029 | influxdata/influxdb-python | influxdb/helper.py | SeriesHelper._json_body_ | def _json_body_(cls):
"""Return the JSON body of given datapoints.
:return: JSON body of these datapoints.
"""
json = []
for series_name, data in six.iteritems(cls._datapoints):
for point in data:
json_point = {
"measurement": series_name,
"fields": {},
"tags": {},
"time": getattr(point, "time")
}
for field in cls._fields:
value = getattr(point, field)
if value is not None:
json_point['fields'][field] = value
for tag in cls._tags:
json_point['tags'][tag] = getattr(point, tag)
json.append(json_point)
return json | python | def _json_body_(cls):
json = []
for series_name, data in six.iteritems(cls._datapoints):
for point in data:
json_point = {
"measurement": series_name,
"fields": {},
"tags": {},
"time": getattr(point, "time")
}
for field in cls._fields:
value = getattr(point, field)
if value is not None:
json_point['fields'][field] = value
for tag in cls._tags:
json_point['tags'][tag] = getattr(point, tag)
json.append(json_point)
return json | [
"def",
"_json_body_",
"(",
"cls",
")",
":",
"json",
"=",
"[",
"]",
"for",
"series_name",
",",
"data",
"in",
"six",
".",
"iteritems",
"(",
"cls",
".",
"_datapoints",
")",
":",
"for",
"point",
"in",
"data",
":",
"json_point",
"=",
"{",
"\"measurement\"",... | Return the JSON body of given datapoints.
:return: JSON body of these datapoints. | [
"Return",
"the",
"JSON",
"body",
"of",
"given",
"datapoints",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/helper.py#L151-L175 |
234,030 | influxdata/influxdb-python | examples/tutorial_server_data.py | main | def main(host='localhost', port=8086, nb_day=15):
"""Instantiate a connection to the backend."""
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an event every x minutes
total_minutes = 1440 * nb_day
total_records = int(total_minutes / timeinterval_min)
now = datetime.datetime.today()
metric = "server_data.cpu_idle"
series = []
for i in range(0, total_records):
past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
value = random.randint(0, 200)
hostName = "server-%d" % random.randint(1, 5)
# pointValues = [int(past_date.strftime('%s')), value, hostName]
pointValues = {
"time": int(past_date.strftime('%s')),
"measurement": metric,
"fields": {
"value": value,
},
"tags": {
"hostName": hostName,
},
}
series.append(pointValues)
print(series)
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)
print("Create database: " + DBNAME)
try:
client.create_database(DBNAME)
except InfluxDBClientError:
# Drop and create
client.drop_database(DBNAME)
client.create_database(DBNAME)
print("Create a retention policy")
retention_policy = 'server_data'
client.create_retention_policy(retention_policy, '3d', 3, default=True)
print("Write points #: {0}".format(total_records))
client.write_points(series, retention_policy=retention_policy)
time.sleep(2)
query = "SELECT MEAN(value) FROM {} WHERE \
time > now() - 10d GROUP BY time(500m)".format(metric)
result = client.query(query, database=DBNAME)
print(result)
print("Result: {0}".format(result))
print("Drop database: {}".format(DBNAME))
client.drop_database(DBNAME) | python | def main(host='localhost', port=8086, nb_day=15):
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an event every x minutes
total_minutes = 1440 * nb_day
total_records = int(total_minutes / timeinterval_min)
now = datetime.datetime.today()
metric = "server_data.cpu_idle"
series = []
for i in range(0, total_records):
past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
value = random.randint(0, 200)
hostName = "server-%d" % random.randint(1, 5)
# pointValues = [int(past_date.strftime('%s')), value, hostName]
pointValues = {
"time": int(past_date.strftime('%s')),
"measurement": metric,
"fields": {
"value": value,
},
"tags": {
"hostName": hostName,
},
}
series.append(pointValues)
print(series)
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)
print("Create database: " + DBNAME)
try:
client.create_database(DBNAME)
except InfluxDBClientError:
# Drop and create
client.drop_database(DBNAME)
client.create_database(DBNAME)
print("Create a retention policy")
retention_policy = 'server_data'
client.create_retention_policy(retention_policy, '3d', 3, default=True)
print("Write points #: {0}".format(total_records))
client.write_points(series, retention_policy=retention_policy)
time.sleep(2)
query = "SELECT MEAN(value) FROM {} WHERE \
time > now() - 10d GROUP BY time(500m)".format(metric)
result = client.query(query, database=DBNAME)
print(result)
print("Result: {0}".format(result))
print("Drop database: {}".format(DBNAME))
client.drop_database(DBNAME) | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
",",
"nb_day",
"=",
"15",
")",
":",
"nb_day",
"=",
"15",
"# number of day to generate time series",
"timeinterval_min",
"=",
"5",
"# create an event every x minutes",
"total_minutes",
"=",
"... | Instantiate a connection to the backend. | [
"Instantiate",
"a",
"connection",
"to",
"the",
"backend",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/examples/tutorial_server_data.py#L19-L74 |
234,031 | influxdata/influxdb-python | examples/tutorial_sine_wave.py | main | def main(host='localhost', port=8086):
"""Define function to generate the sin wave."""
now = datetime.datetime.today()
points = []
for angle in range(0, 360):
y = 10 + math.sin(math.radians(angle)) * 10
point = {
"measurement": 'foobar',
"time": int(now.strftime('%s')) + angle,
"fields": {
"value": y
}
}
points.append(point)
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)
print("Create database: " + DBNAME)
client.create_database(DBNAME)
client.switch_database(DBNAME)
# Write points
client.write_points(points)
time.sleep(3)
query = 'SELECT * FROM foobar'
print("Querying data: " + query)
result = client.query(query, database=DBNAME)
print("Result: {0}".format(result))
"""
You might want to comment the delete and plot the result on InfluxDB
Interface. Connect on InfluxDB Interface at http://127.0.0.1:8083/
Select the database tutorial -> Explore Data
Then run the following query:
SELECT * from foobar
"""
print("Delete database: " + DBNAME)
client.drop_database(DBNAME) | python | def main(host='localhost', port=8086):
now = datetime.datetime.today()
points = []
for angle in range(0, 360):
y = 10 + math.sin(math.radians(angle)) * 10
point = {
"measurement": 'foobar',
"time": int(now.strftime('%s')) + angle,
"fields": {
"value": y
}
}
points.append(point)
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)
print("Create database: " + DBNAME)
client.create_database(DBNAME)
client.switch_database(DBNAME)
# Write points
client.write_points(points)
time.sleep(3)
query = 'SELECT * FROM foobar'
print("Querying data: " + query)
result = client.query(query, database=DBNAME)
print("Result: {0}".format(result))
"""
You might want to comment the delete and plot the result on InfluxDB
Interface. Connect on InfluxDB Interface at http://127.0.0.1:8083/
Select the database tutorial -> Explore Data
Then run the following query:
SELECT * from foobar
"""
print("Delete database: " + DBNAME)
client.drop_database(DBNAME) | [
"def",
"main",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8086",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"points",
"=",
"[",
"]",
"for",
"angle",
"in",
"range",
"(",
"0",
",",
"360",
")",
":",
"y",
"=... | Define function to generate the sin wave. | [
"Define",
"function",
"to",
"generate",
"the",
"sin",
"wave",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/examples/tutorial_sine_wave.py#L17-L61 |
234,032 | influxdata/influxdb-python | influxdb/resultset.py | ResultSet.get_points | def get_points(self, measurement=None, tags=None):
"""Return a generator for all the points that match the given filters.
:param measurement: The measurement name
:type measurement: str
:param tags: Tags to look for
:type tags: dict
:return: Points generator
"""
# Raise error if measurement is not str or bytes
if not isinstance(measurement,
(bytes, type(b''.decode()), type(None))):
raise TypeError('measurement must be an str or None')
for series in self._get_series():
series_name = series.get('measurement',
series.get('name', 'results'))
if series_name is None:
# this is a "system" query or a query which
# doesn't return a name attribute.
# like 'show retention policies' ..
if tags is None:
for item in self._get_points_for_series(series):
yield item
elif measurement in (None, series_name):
# by default if no tags was provided then
# we will matches every returned series
series_tags = series.get('tags', {})
for item in self._get_points_for_series(series):
if tags is None or \
self._tag_matches(item, tags) or \
self._tag_matches(series_tags, tags):
yield item | python | def get_points(self, measurement=None, tags=None):
# Raise error if measurement is not str or bytes
if not isinstance(measurement,
(bytes, type(b''.decode()), type(None))):
raise TypeError('measurement must be an str or None')
for series in self._get_series():
series_name = series.get('measurement',
series.get('name', 'results'))
if series_name is None:
# this is a "system" query or a query which
# doesn't return a name attribute.
# like 'show retention policies' ..
if tags is None:
for item in self._get_points_for_series(series):
yield item
elif measurement in (None, series_name):
# by default if no tags was provided then
# we will matches every returned series
series_tags = series.get('tags', {})
for item in self._get_points_for_series(series):
if tags is None or \
self._tag_matches(item, tags) or \
self._tag_matches(series_tags, tags):
yield item | [
"def",
"get_points",
"(",
"self",
",",
"measurement",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# Raise error if measurement is not str or bytes",
"if",
"not",
"isinstance",
"(",
"measurement",
",",
"(",
"bytes",
",",
"type",
"(",
"b''",
".",
"decode",... | Return a generator for all the points that match the given filters.
:param measurement: The measurement name
:type measurement: str
:param tags: Tags to look for
:type tags: dict
:return: Points generator | [
"Return",
"a",
"generator",
"for",
"all",
"the",
"points",
"that",
"match",
"the",
"given",
"filters",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/resultset.py#L80-L115 |
234,033 | influxdata/influxdb-python | influxdb/resultset.py | ResultSet.keys | def keys(self):
"""Return the list of keys in the ResultSet.
:return: List of keys. Keys are tuples (series_name, tags)
"""
keys = []
for series in self._get_series():
keys.append(
(series.get('measurement',
series.get('name', 'results')),
series.get('tags', None))
)
return keys | python | def keys(self):
keys = []
for series in self._get_series():
keys.append(
(series.get('measurement',
series.get('name', 'results')),
series.get('tags', None))
)
return keys | [
"def",
"keys",
"(",
"self",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"series",
"in",
"self",
".",
"_get_series",
"(",
")",
":",
"keys",
".",
"append",
"(",
"(",
"series",
".",
"get",
"(",
"'measurement'",
",",
"series",
".",
"get",
"(",
"'name'",
... | Return the list of keys in the ResultSet.
:return: List of keys. Keys are tuples (series_name, tags) | [
"Return",
"the",
"list",
"of",
"keys",
"in",
"the",
"ResultSet",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/resultset.py#L153-L165 |
234,034 | influxdata/influxdb-python | influxdb/resultset.py | ResultSet.items | def items(self):
"""Return the set of items from the ResultSet.
:return: List of tuples, (key, generator)
"""
items = []
for series in self._get_series():
series_key = (series.get('measurement',
series.get('name', 'results')),
series.get('tags', None))
items.append(
(series_key, self._get_points_for_series(series))
)
return items | python | def items(self):
items = []
for series in self._get_series():
series_key = (series.get('measurement',
series.get('name', 'results')),
series.get('tags', None))
items.append(
(series_key, self._get_points_for_series(series))
)
return items | [
"def",
"items",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"series",
"in",
"self",
".",
"_get_series",
"(",
")",
":",
"series_key",
"=",
"(",
"series",
".",
"get",
"(",
"'measurement'",
",",
"series",
".",
"get",
"(",
"'name'",
",",
"'re... | Return the set of items from the ResultSet.
:return: List of tuples, (key, generator) | [
"Return",
"the",
"set",
"of",
"items",
"from",
"the",
"ResultSet",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/resultset.py#L167-L180 |
234,035 | influxdata/influxdb-python | influxdb/resultset.py | ResultSet._get_points_for_series | def _get_points_for_series(self, series):
"""Return generator of dict from columns and values of a series.
:param series: One series
:return: Generator of dicts
"""
for point in series.get('values', []):
yield self.point_from_cols_vals(
series['columns'],
point
) | python | def _get_points_for_series(self, series):
for point in series.get('values', []):
yield self.point_from_cols_vals(
series['columns'],
point
) | [
"def",
"_get_points_for_series",
"(",
"self",
",",
"series",
")",
":",
"for",
"point",
"in",
"series",
".",
"get",
"(",
"'values'",
",",
"[",
"]",
")",
":",
"yield",
"self",
".",
"point_from_cols_vals",
"(",
"series",
"[",
"'columns'",
"]",
",",
"point",... | Return generator of dict from columns and values of a series.
:param series: One series
:return: Generator of dicts | [
"Return",
"generator",
"of",
"dict",
"from",
"columns",
"and",
"values",
"of",
"a",
"series",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/resultset.py#L182-L192 |
234,036 | influxdata/influxdb-python | influxdb/resultset.py | ResultSet.point_from_cols_vals | def point_from_cols_vals(cols, vals):
"""Create a dict from columns and values lists.
:param cols: List of columns
:param vals: List of values
:return: Dict where keys are columns.
"""
point = {}
for col_index, col_name in enumerate(cols):
point[col_name] = vals[col_index]
return point | python | def point_from_cols_vals(cols, vals):
point = {}
for col_index, col_name in enumerate(cols):
point[col_name] = vals[col_index]
return point | [
"def",
"point_from_cols_vals",
"(",
"cols",
",",
"vals",
")",
":",
"point",
"=",
"{",
"}",
"for",
"col_index",
",",
"col_name",
"in",
"enumerate",
"(",
"cols",
")",
":",
"point",
"[",
"col_name",
"]",
"=",
"vals",
"[",
"col_index",
"]",
"return",
"poin... | Create a dict from columns and values lists.
:param cols: List of columns
:param vals: List of values
:return: Dict where keys are columns. | [
"Create",
"a",
"dict",
"from",
"columns",
"and",
"values",
"lists",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/resultset.py#L195-L206 |
234,037 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.from_dsn | def from_dsn(dsn, **kwargs):
r"""Return an instaance of InfluxDBClient from given data source name.
Returns an instance of InfluxDBClient from the provided data source
name. Supported schemes are "influxdb", "https+influxdb",
"udp+influxdb". Parameters for the InfluxDBClient constructor may be
also be passed to this function.
Examples:
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
... localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
... localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
:param dsn: data source name
:type dsn: string
:param **kwargs: additional parameters for InfluxDBClient.
:type **kwargs: dict
:note: parameters provided in **kwargs may override dsn parameters.
:note: when using "udp+influxdb" the specified port (if any) will be
used for the TCP connection; specify the udp port with the additional
udp_port parameter (cf. examples).
:raise ValueError: if the provided DSN has any unexpected value.
"""
init_args = {}
conn_params = urlparse(dsn)
scheme_info = conn_params.scheme.split('+')
if len(scheme_info) == 1:
scheme = scheme_info[0]
modifier = None
else:
modifier, scheme = scheme_info
if scheme != 'influxdb':
raise ValueError('Unknown scheme "{0}".'.format(scheme))
if modifier:
if modifier == 'udp':
init_args['use_udp'] = True
elif modifier == 'https':
init_args['ssl'] = True
else:
raise ValueError('Unknown modifier "{0}".'.format(modifier))
if conn_params.hostname:
init_args['host'] = conn_params.hostname
if conn_params.port:
init_args['port'] = conn_params.port
if conn_params.username:
init_args['username'] = conn_params.username
if conn_params.password:
init_args['password'] = conn_params.password
if conn_params.path and len(conn_params.path) > 1:
init_args['database'] = conn_params.path[1:]
init_args.update(kwargs)
return InfluxDBClient(**init_args) | python | def from_dsn(dsn, **kwargs):
r"""Return an instaance of InfluxDBClient from given data source name.
Returns an instance of InfluxDBClient from the provided data source
name. Supported schemes are "influxdb", "https+influxdb",
"udp+influxdb". Parameters for the InfluxDBClient constructor may be
also be passed to this function.
Examples:
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
... localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
... localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
:param dsn: data source name
:type dsn: string
:param **kwargs: additional parameters for InfluxDBClient.
:type **kwargs: dict
:note: parameters provided in **kwargs may override dsn parameters.
:note: when using "udp+influxdb" the specified port (if any) will be
used for the TCP connection; specify the udp port with the additional
udp_port parameter (cf. examples).
:raise ValueError: if the provided DSN has any unexpected value.
"""
init_args = {}
conn_params = urlparse(dsn)
scheme_info = conn_params.scheme.split('+')
if len(scheme_info) == 1:
scheme = scheme_info[0]
modifier = None
else:
modifier, scheme = scheme_info
if scheme != 'influxdb':
raise ValueError('Unknown scheme "{0}".'.format(scheme))
if modifier:
if modifier == 'udp':
init_args['use_udp'] = True
elif modifier == 'https':
init_args['ssl'] = True
else:
raise ValueError('Unknown modifier "{0}".'.format(modifier))
if conn_params.hostname:
init_args['host'] = conn_params.hostname
if conn_params.port:
init_args['port'] = conn_params.port
if conn_params.username:
init_args['username'] = conn_params.username
if conn_params.password:
init_args['password'] = conn_params.password
if conn_params.path and len(conn_params.path) > 1:
init_args['database'] = conn_params.path[1:]
init_args.update(kwargs)
return InfluxDBClient(**init_args) | [
"def",
"from_dsn",
"(",
"dsn",
",",
"*",
"*",
"kwargs",
")",
":",
"init_args",
"=",
"{",
"}",
"conn_params",
"=",
"urlparse",
"(",
"dsn",
")",
"scheme_info",
"=",
"conn_params",
".",
"scheme",
".",
"split",
"(",
"'+'",
")",
"if",
"len",
"(",
"scheme_... | r"""Return an instaance of InfluxDBClient from given data source name.
Returns an instance of InfluxDBClient from the provided data source
name. Supported schemes are "influxdb", "https+influxdb",
"udp+influxdb". Parameters for the InfluxDBClient constructor may be
also be passed to this function.
Examples:
>> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
... localhost:8086/databasename', timeout=5)
>> type(cli)
<class 'influxdb.client.InfluxDBClient'>
>> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
... localhost:8086/databasename', timeout=5, udp_port=159)
>> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
http://localhost:8086 - True 159
:param dsn: data source name
:type dsn: string
:param **kwargs: additional parameters for InfluxDBClient.
:type **kwargs: dict
:note: parameters provided in **kwargs may override dsn parameters.
:note: when using "udp+influxdb" the specified port (if any) will be
used for the TCP connection; specify the udp port with the additional
udp_port parameter (cf. examples).
:raise ValueError: if the provided DSN has any unexpected value. | [
"r",
"Return",
"an",
"instaance",
"of",
"InfluxDBClient",
"from",
"given",
"data",
"source",
"name",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L106-L169 |
234,038 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.request | def request(self, url, method='GET', params=None, data=None,
expected_response_code=200):
"""Make a http request to API."""
url = "{0}/{1}".format(self._baseurl, url)
if params is None:
params = {}
auth = {
'u': self._username,
'p': self._password
}
params.update(auth)
if data is not None and not isinstance(data, str):
data = json.dumps(data)
retry = True
_try = 0
# Try to send the request more than once by default (see #103)
while retry:
try:
response = session.request(
method=method,
url=url,
params=params,
data=data,
headers=self._headers,
verify=self._verify_ssl,
timeout=self._timeout
)
break
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout):
_try += 1
if self._retries != 0:
retry = _try < self._retries
else:
raise requests.exceptions.ConnectionError
if response.status_code == expected_response_code:
return response
else:
raise InfluxDBClientError(response.content, response.status_code) | python | def request(self, url, method='GET', params=None, data=None,
expected_response_code=200):
url = "{0}/{1}".format(self._baseurl, url)
if params is None:
params = {}
auth = {
'u': self._username,
'p': self._password
}
params.update(auth)
if data is not None and not isinstance(data, str):
data = json.dumps(data)
retry = True
_try = 0
# Try to send the request more than once by default (see #103)
while retry:
try:
response = session.request(
method=method,
url=url,
params=params,
data=data,
headers=self._headers,
verify=self._verify_ssl,
timeout=self._timeout
)
break
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout):
_try += 1
if self._retries != 0:
retry = _try < self._retries
else:
raise requests.exceptions.ConnectionError
if response.status_code == expected_response_code:
return response
else:
raise InfluxDBClientError(response.content, response.status_code) | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
")",
":",
"url",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"_baseurl",
... | Make a http request to API. | [
"Make",
"a",
"http",
"request",
"to",
"API",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L204-L248 |
234,039 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.write | def write(self, data):
"""Provide as convenience for influxdb v0.9.0, this may change."""
self.request(
url="write",
method='POST',
params=None,
data=data,
expected_response_code=200
)
return True | python | def write(self, data):
self.request(
url="write",
method='POST',
params=None,
data=data,
expected_response_code=200
)
return True | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"request",
"(",
"url",
"=",
"\"write\"",
",",
"method",
"=",
"'POST'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"data",
",",
"expected_response_code",
"=",
"200",
")",
"return",
"T... | Provide as convenience for influxdb v0.9.0, this may change. | [
"Provide",
"as",
"convenience",
"for",
"influxdb",
"v0",
".",
"9",
".",
"0",
"this",
"may",
"change",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L250-L259 |
234,040 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.delete_points | def delete_points(self, name):
"""Delete an entire series."""
url = "db/{0}/series/{1}".format(self._database, name)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | python | def delete_points(self, name):
url = "db/{0}/series/{1}".format(self._database, name)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | [
"def",
"delete_points",
"(",
"self",
",",
"name",
")",
":",
"url",
"=",
"\"db/{0}/series/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"name",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
",",
"expec... | Delete an entire series. | [
"Delete",
"an",
"entire",
"series",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L364-L374 |
234,041 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.query | def query(self, query, time_precision='s', chunked=False):
"""Query data from the influxdb v0.8 database.
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param chunked: [Optional, default=False] True if the data shall be
retrieved in chunks, False otherwise.
"""
return self._query(query, time_precision=time_precision,
chunked=chunked) | python | def query(self, query, time_precision='s', chunked=False):
return self._query(query, time_precision=time_precision,
chunked=chunked) | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"time_precision",
"=",
"'s'",
",",
"chunked",
"=",
"False",
")",
":",
"return",
"self",
".",
"_query",
"(",
"query",
",",
"time_precision",
"=",
"time_precision",
",",
"chunked",
"=",
"chunked",
")"
] | Query data from the influxdb v0.8 database.
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param chunked: [Optional, default=False] True if the data shall be
retrieved in chunks, False otherwise. | [
"Query",
"data",
"from",
"the",
"influxdb",
"v0",
".",
"8",
"database",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L414-L423 |
234,042 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.create_database | def create_database(self, database):
"""Create a database on the InfluxDB server.
:param database: the name of the database to create
:type database: string
:rtype: boolean
"""
url = "db"
data = {'name': database}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=201
)
return True | python | def create_database(self, database):
url = "db"
data = {'name': database}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=201
)
return True | [
"def",
"create_database",
"(",
"self",
",",
"database",
")",
":",
"url",
"=",
"\"db\"",
"data",
"=",
"{",
"'name'",
":",
"database",
"}",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"data",
",",
"... | Create a database on the InfluxDB server.
:param database: the name of the database to create
:type database: string
:rtype: boolean | [
"Create",
"a",
"database",
"on",
"the",
"InfluxDB",
"server",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L472-L490 |
234,043 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.delete_database | def delete_database(self, database):
"""Drop a database on the InfluxDB server.
:param database: the name of the database to delete
:type database: string
:rtype: boolean
"""
url = "db/{0}".format(database)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | python | def delete_database(self, database):
url = "db/{0}".format(database)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | [
"def",
"delete_database",
"(",
"self",
",",
"database",
")",
":",
"url",
"=",
"\"db/{0}\"",
".",
"format",
"(",
"database",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
",",
"expected_response_code",
"=",
"204",
")... | Drop a database on the InfluxDB server.
:param database: the name of the database to delete
:type database: string
:rtype: boolean | [
"Drop",
"a",
"database",
"on",
"the",
"InfluxDB",
"server",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L492-L507 |
234,044 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.get_list_database | def get_list_database(self):
"""Get the list of databases."""
url = "db"
response = self.request(
url=url,
method='GET',
expected_response_code=200
)
return response.json() | python | def get_list_database(self):
url = "db"
response = self.request(
url=url,
method='GET',
expected_response_code=200
)
return response.json() | [
"def",
"get_list_database",
"(",
"self",
")",
":",
"url",
"=",
"\"db\"",
"response",
"=",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'GET'",
",",
"expected_response_code",
"=",
"200",
")",
"return",
"response",
".",
"json",
"(",... | Get the list of databases. | [
"Get",
"the",
"list",
"of",
"databases",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L512-L522 |
234,045 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.delete_series | def delete_series(self, series):
"""Drop a series on the InfluxDB server.
:param series: the name of the series to delete
:type series: string
:rtype: boolean
"""
url = "db/{0}/series/{1}".format(
self._database,
series
)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | python | def delete_series(self, series):
url = "db/{0}/series/{1}".format(
self._database,
series
)
self.request(
url=url,
method='DELETE',
expected_response_code=204
)
return True | [
"def",
"delete_series",
"(",
"self",
",",
"series",
")",
":",
"url",
"=",
"\"db/{0}/series/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"series",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
",",
"e... | Drop a series on the InfluxDB server.
:param series: the name of the series to delete
:type series: string
:rtype: boolean | [
"Drop",
"a",
"series",
"on",
"the",
"InfluxDB",
"server",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L536-L554 |
234,046 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.get_list_cluster_admins | def get_list_cluster_admins(self):
"""Get list of cluster admins."""
response = self.request(
url="cluster_admins",
method='GET',
expected_response_code=200
)
return response.json() | python | def get_list_cluster_admins(self):
response = self.request(
url="cluster_admins",
method='GET',
expected_response_code=200
)
return response.json() | [
"def",
"get_list_cluster_admins",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"url",
"=",
"\"cluster_admins\"",
",",
"method",
"=",
"'GET'",
",",
"expected_response_code",
"=",
"200",
")",
"return",
"response",
".",
"json",
"(",
")"
... | Get list of cluster admins. | [
"Get",
"list",
"of",
"cluster",
"admins",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L597-L605 |
234,047 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.add_cluster_admin | def add_cluster_admin(self, new_username, new_password):
"""Add cluster admin."""
data = {
'name': new_username,
'password': new_password
}
self.request(
url="cluster_admins",
method='POST',
data=data,
expected_response_code=200
)
return True | python | def add_cluster_admin(self, new_username, new_password):
data = {
'name': new_username,
'password': new_password
}
self.request(
url="cluster_admins",
method='POST',
data=data,
expected_response_code=200
)
return True | [
"def",
"add_cluster_admin",
"(",
"self",
",",
"new_username",
",",
"new_password",
")",
":",
"data",
"=",
"{",
"'name'",
":",
"new_username",
",",
"'password'",
":",
"new_password",
"}",
"self",
".",
"request",
"(",
"url",
"=",
"\"cluster_admins\"",
",",
"me... | Add cluster admin. | [
"Add",
"cluster",
"admin",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L607-L621 |
234,048 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.update_cluster_admin_password | def update_cluster_admin_password(self, username, new_password):
"""Update cluster admin password."""
url = "cluster_admins/{0}".format(username)
data = {
'password': new_password
}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | python | def update_cluster_admin_password(self, username, new_password):
url = "cluster_admins/{0}".format(username)
data = {
'password': new_password
}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | [
"def",
"update_cluster_admin_password",
"(",
"self",
",",
"username",
",",
"new_password",
")",
":",
"url",
"=",
"\"cluster_admins/{0}\"",
".",
"format",
"(",
"username",
")",
"data",
"=",
"{",
"'password'",
":",
"new_password",
"}",
"self",
".",
"request",
"(... | Update cluster admin password. | [
"Update",
"cluster",
"admin",
"password",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L623-L638 |
234,049 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.delete_cluster_admin | def delete_cluster_admin(self, username):
"""Delete cluster admin."""
url = "cluster_admins/{0}".format(username)
self.request(
url=url,
method='DELETE',
expected_response_code=200
)
return True | python | def delete_cluster_admin(self, username):
url = "cluster_admins/{0}".format(username)
self.request(
url=url,
method='DELETE',
expected_response_code=200
)
return True | [
"def",
"delete_cluster_admin",
"(",
"self",
",",
"username",
")",
":",
"url",
"=",
"\"cluster_admins/{0}\"",
".",
"format",
"(",
"username",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
",",
"expected_response_code",
"... | Delete cluster admin. | [
"Delete",
"cluster",
"admin",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L640-L650 |
234,050 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.alter_database_admin | def alter_database_admin(self, username, is_admin):
"""Alter the database admin."""
url = "db/{0}/users/{1}".format(self._database, username)
data = {'admin': is_admin}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | python | def alter_database_admin(self, username, is_admin):
url = "db/{0}/users/{1}".format(self._database, username)
data = {'admin': is_admin}
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | [
"def",
"alter_database_admin",
"(",
"self",
",",
"username",
",",
"is_admin",
")",
":",
"url",
"=",
"\"db/{0}/users/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"username",
")",
"data",
"=",
"{",
"'admin'",
":",
"is_admin",
"}",
"self",
".",
... | Alter the database admin. | [
"Alter",
"the",
"database",
"admin",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L660-L673 |
234,051 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.get_database_users | def get_database_users(self):
"""Get list of database users."""
url = "db/{0}/users".format(self._database)
response = self.request(
url=url,
method='GET',
expected_response_code=200
)
return response.json() | python | def get_database_users(self):
url = "db/{0}/users".format(self._database)
response = self.request(
url=url,
method='GET',
expected_response_code=200
)
return response.json() | [
"def",
"get_database_users",
"(",
"self",
")",
":",
"url",
"=",
"\"db/{0}/users\"",
".",
"format",
"(",
"self",
".",
"_database",
")",
"response",
"=",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'GET'",
",",
"expected_response_cod... | Get list of database users. | [
"Get",
"list",
"of",
"database",
"users",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L733-L743 |
234,052 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.add_database_user | def add_database_user(self, new_username, new_password, permissions=None):
"""Add database user.
:param permissions: A ``(readFrom, writeTo)`` tuple
"""
url = "db/{0}/users".format(self._database)
data = {
'name': new_username,
'password': new_password
}
if permissions:
try:
data['readFrom'], data['writeTo'] = permissions
except (ValueError, TypeError):
raise TypeError(
"'permissions' must be (readFrom, writeTo) tuple"
)
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | python | def add_database_user(self, new_username, new_password, permissions=None):
url = "db/{0}/users".format(self._database)
data = {
'name': new_username,
'password': new_password
}
if permissions:
try:
data['readFrom'], data['writeTo'] = permissions
except (ValueError, TypeError):
raise TypeError(
"'permissions' must be (readFrom, writeTo) tuple"
)
self.request(
url=url,
method='POST',
data=data,
expected_response_code=200
)
return True | [
"def",
"add_database_user",
"(",
"self",
",",
"new_username",
",",
"new_password",
",",
"permissions",
"=",
"None",
")",
":",
"url",
"=",
"\"db/{0}/users\"",
".",
"format",
"(",
"self",
".",
"_database",
")",
"data",
"=",
"{",
"'name'",
":",
"new_username",
... | Add database user.
:param permissions: A ``(readFrom, writeTo)`` tuple | [
"Add",
"database",
"user",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L745-L772 |
234,053 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.delete_database_user | def delete_database_user(self, username):
"""Delete database user."""
url = "db/{0}/users/{1}".format(self._database, username)
self.request(
url=url,
method='DELETE',
expected_response_code=200
)
return True | python | def delete_database_user(self, username):
url = "db/{0}/users/{1}".format(self._database, username)
self.request(
url=url,
method='DELETE',
expected_response_code=200
)
return True | [
"def",
"delete_database_user",
"(",
"self",
",",
"username",
")",
":",
"url",
"=",
"\"db/{0}/users/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"username",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
... | Delete database user. | [
"Delete",
"database",
"user",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L815-L825 |
234,054 | influxdata/influxdb-python | influxdb/influxdb08/client.py | InfluxDBClient.send_packet | def send_packet(self, packet):
"""Send a UDP packet along the wire."""
data = json.dumps(packet)
byte = data.encode('utf-8')
self.udp_socket.sendto(byte, (self._host, self._udp_port)) | python | def send_packet(self, packet):
data = json.dumps(packet)
byte = data.encode('utf-8')
self.udp_socket.sendto(byte, (self._host, self._udp_port)) | [
"def",
"send_packet",
"(",
"self",
",",
"packet",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"packet",
")",
"byte",
"=",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"udp_socket",
".",
"sendto",
"(",
"byte",
",",
"(",
"self",
"."... | Send a UDP packet along the wire. | [
"Send",
"a",
"UDP",
"packet",
"along",
"the",
"wire",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L839-L843 |
234,055 | influxdata/influxdb-python | influxdb/influxdb08/dataframe_client.py | DataFrameClient.query | def query(self, query, time_precision='s', chunked=False):
"""Query data into DataFrames.
Returns a DataFrame for a single time series and a map for multiple
time series with the time series as value and its name as key.
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param chunked: [Optional, default=False] True if the data shall be
retrieved in chunks, False otherwise.
"""
result = InfluxDBClient.query(self, query=query,
time_precision=time_precision,
chunked=chunked)
if len(result) == 0:
return result
elif len(result) == 1:
return self._to_dataframe(result[0], time_precision)
else:
ret = {}
for time_series in result:
ret[time_series['name']] = self._to_dataframe(time_series,
time_precision)
return ret | python | def query(self, query, time_precision='s', chunked=False):
result = InfluxDBClient.query(self, query=query,
time_precision=time_precision,
chunked=chunked)
if len(result) == 0:
return result
elif len(result) == 1:
return self._to_dataframe(result[0], time_precision)
else:
ret = {}
for time_series in result:
ret[time_series['name']] = self._to_dataframe(time_series,
time_precision)
return ret | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"time_precision",
"=",
"'s'",
",",
"chunked",
"=",
"False",
")",
":",
"result",
"=",
"InfluxDBClient",
".",
"query",
"(",
"self",
",",
"query",
"=",
"query",
",",
"time_precision",
"=",
"time_precision",
",... | Query data into DataFrames.
Returns a DataFrame for a single time series and a map for multiple
time series with the time series as value and its name as key.
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param chunked: [Optional, default=False] True if the data shall be
retrieved in chunks, False otherwise. | [
"Query",
"data",
"into",
"DataFrames",
"."
] | d5d12499f3755199d5eedd8b363450f1cf4073bd | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/dataframe_client.py#L85-L108 |
234,056 | groveco/django-sql-explorer | explorer/forms.py | SqlField.validate | def validate(self, value):
"""
Ensure that the SQL passes the blacklist.
:param value: The SQL for this Query model.
"""
query = Query(sql=value)
passes_blacklist, failing_words = query.passes_blacklist()
error = MSG_FAILED_BLACKLIST % ', '.join(failing_words) if not passes_blacklist else None
if error:
raise ValidationError(
error,
code="InvalidSql"
) | python | def validate(self, value):
query = Query(sql=value)
passes_blacklist, failing_words = query.passes_blacklist()
error = MSG_FAILED_BLACKLIST % ', '.join(failing_words) if not passes_blacklist else None
if error:
raise ValidationError(
error,
code="InvalidSql"
) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"query",
"=",
"Query",
"(",
"sql",
"=",
"value",
")",
"passes_blacklist",
",",
"failing_words",
"=",
"query",
".",
"passes_blacklist",
"(",
")",
"error",
"=",
"MSG_FAILED_BLACKLIST",
"%",
"', '",
".",... | Ensure that the SQL passes the blacklist.
:param value: The SQL for this Query model. | [
"Ensure",
"that",
"the",
"SQL",
"passes",
"the",
"blacklist",
"."
] | 622b96354e1d7ae7f7105ae90b8da3247e028623 | https://github.com/groveco/django-sql-explorer/blob/622b96354e1d7ae7f7105ae90b8da3247e028623/explorer/forms.py#L11-L28 |
234,057 | groveco/django-sql-explorer | explorer/schema.py | build_schema_info | def build_schema_info(connection_alias):
"""
Construct schema information via engine-specific queries of the tables in the DB.
:return: Schema information of the following form, sorted by db_table_name.
[
("db_table_name",
[
("db_column_name", "DbFieldType"),
(...),
]
)
]
"""
connection = get_valid_connection(connection_alias)
ret = []
with connection.cursor() as cursor:
tables_to_introspect = connection.introspection.table_names(cursor, include_views=_include_views())
for table_name in tables_to_introspect:
if not _include_table(table_name):
continue
td = []
table_description = connection.introspection.get_table_description(cursor, table_name)
for row in table_description:
column_name = row[0]
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError as e:
field_type = 'Unknown'
td.append((column_name, field_type))
ret.append((table_name, td))
return ret | python | def build_schema_info(connection_alias):
connection = get_valid_connection(connection_alias)
ret = []
with connection.cursor() as cursor:
tables_to_introspect = connection.introspection.table_names(cursor, include_views=_include_views())
for table_name in tables_to_introspect:
if not _include_table(table_name):
continue
td = []
table_description = connection.introspection.get_table_description(cursor, table_name)
for row in table_description:
column_name = row[0]
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError as e:
field_type = 'Unknown'
td.append((column_name, field_type))
ret.append((table_name, td))
return ret | [
"def",
"build_schema_info",
"(",
"connection_alias",
")",
":",
"connection",
"=",
"get_valid_connection",
"(",
"connection_alias",
")",
"ret",
"=",
"[",
"]",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"tables_to_introspect",
"=",
"connec... | Construct schema information via engine-specific queries of the tables in the DB.
:return: Schema information of the following form, sorted by db_table_name.
[
("db_table_name",
[
("db_column_name", "DbFieldType"),
(...),
]
)
] | [
"Construct",
"schema",
"information",
"via",
"engine",
"-",
"specific",
"queries",
"of",
"the",
"tables",
"in",
"the",
"DB",
"."
] | 622b96354e1d7ae7f7105ae90b8da3247e028623 | https://github.com/groveco/django-sql-explorer/blob/622b96354e1d7ae7f7105ae90b8da3247e028623/explorer/schema.py#L52-L85 |
234,058 | CodeReclaimers/neat-python | neat/graphs.py | creates_cycle | def creates_cycle(connections, test):
"""
Returns true if the addition of the 'test' connection would create a cycle,
assuming that no cycle already exists in the graph represented by 'connections'.
"""
i, o = test
if i == o:
return True
visited = {o}
while True:
num_added = 0
for a, b in connections:
if a in visited and b not in visited:
if b == i:
return True
visited.add(b)
num_added += 1
if num_added == 0:
return False | python | def creates_cycle(connections, test):
i, o = test
if i == o:
return True
visited = {o}
while True:
num_added = 0
for a, b in connections:
if a in visited and b not in visited:
if b == i:
return True
visited.add(b)
num_added += 1
if num_added == 0:
return False | [
"def",
"creates_cycle",
"(",
"connections",
",",
"test",
")",
":",
"i",
",",
"o",
"=",
"test",
"if",
"i",
"==",
"o",
":",
"return",
"True",
"visited",
"=",
"{",
"o",
"}",
"while",
"True",
":",
"num_added",
"=",
"0",
"for",
"a",
",",
"b",
"in",
... | Returns true if the addition of the 'test' connection would create a cycle,
assuming that no cycle already exists in the graph represented by 'connections'. | [
"Returns",
"true",
"if",
"the",
"addition",
"of",
"the",
"test",
"connection",
"would",
"create",
"a",
"cycle",
"assuming",
"that",
"no",
"cycle",
"already",
"exists",
"in",
"the",
"graph",
"represented",
"by",
"connections",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/graphs.py#L3-L24 |
234,059 | CodeReclaimers/neat-python | examples/xor/evolve-feedforward-threaded.py | run | def run(config_file):
"""load the config, create a population, evolve and show the result"""
# Load configuration.
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config_file)
# Create the population, which is the top-level object for a NEAT run.
p = neat.Population(config)
# Add a stdout reporter to show progress in the terminal.
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
# Run for up to 300 generations.
pe = neat.ThreadedEvaluator(4, eval_genome)
winner = p.run(pe.evaluate, 300)
pe.stop()
# Display the winning genome.
print('\nBest genome:\n{!s}'.format(winner))
# Show output of the most fit genome against training data.
print('\nOutput:')
winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
for xi, xo in zip(xor_inputs, xor_outputs):
output = winner_net.activate(xi)
print(
"input {!r}, expected output {!r}, got {!r}".format(xi, xo, output)
)
if visualize is not None:
node_names = {-1: 'A', -2: 'B', 0: 'A XOR B'}
visualize.draw_net(config, winner, True, node_names=node_names)
visualize.plot_stats(stats, ylog=False, view=True)
visualize.plot_species(stats, view=True) | python | def run(config_file):
# Load configuration.
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config_file)
# Create the population, which is the top-level object for a NEAT run.
p = neat.Population(config)
# Add a stdout reporter to show progress in the terminal.
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
# Run for up to 300 generations.
pe = neat.ThreadedEvaluator(4, eval_genome)
winner = p.run(pe.evaluate, 300)
pe.stop()
# Display the winning genome.
print('\nBest genome:\n{!s}'.format(winner))
# Show output of the most fit genome against training data.
print('\nOutput:')
winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
for xi, xo in zip(xor_inputs, xor_outputs):
output = winner_net.activate(xi)
print(
"input {!r}, expected output {!r}, got {!r}".format(xi, xo, output)
)
if visualize is not None:
node_names = {-1: 'A', -2: 'B', 0: 'A XOR B'}
visualize.draw_net(config, winner, True, node_names=node_names)
visualize.plot_stats(stats, ylog=False, view=True)
visualize.plot_species(stats, view=True) | [
"def",
"run",
"(",
"config_file",
")",
":",
"# Load configuration.",
"config",
"=",
"neat",
".",
"Config",
"(",
"neat",
".",
"DefaultGenome",
",",
"neat",
".",
"DefaultReproduction",
",",
"neat",
".",
"DefaultSpeciesSet",
",",
"neat",
".",
"DefaultStagnation",
... | load the config, create a population, evolve and show the result | [
"load",
"the",
"config",
"create",
"a",
"population",
"evolve",
"and",
"show",
"the",
"result"
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/xor/evolve-feedforward-threaded.py#L49-L85 |
234,060 | CodeReclaimers/neat-python | examples/memory-variable/visualize.py | plot_stats | def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
""" Plots the population's average and best fitness. """
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
generation = range(len(statistics.most_fit_genomes))
best_fitness = [c.fitness for c in statistics.most_fit_genomes]
avg_fitness = np.array(statistics.get_fitness_mean())
stdev_fitness = np.array(statistics.get_fitness_stdev())
plt.plot(generation, avg_fitness, 'b-', label="average")
plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
plt.plot(generation, best_fitness, 'r-', label="best")
plt.title("Population's average and best fitness")
plt.xlabel("Generations")
plt.ylabel("Fitness")
plt.grid()
plt.legend(loc="best")
if ylog:
plt.gca().set_yscale('symlog')
plt.savefig(filename)
if view:
plt.show()
plt.close() | python | def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
generation = range(len(statistics.most_fit_genomes))
best_fitness = [c.fitness for c in statistics.most_fit_genomes]
avg_fitness = np.array(statistics.get_fitness_mean())
stdev_fitness = np.array(statistics.get_fitness_stdev())
plt.plot(generation, avg_fitness, 'b-', label="average")
plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
plt.plot(generation, best_fitness, 'r-', label="best")
plt.title("Population's average and best fitness")
plt.xlabel("Generations")
plt.ylabel("Fitness")
plt.grid()
plt.legend(loc="best")
if ylog:
plt.gca().set_yscale('symlog')
plt.savefig(filename)
if view:
plt.show()
plt.close() | [
"def",
"plot_stats",
"(",
"statistics",
",",
"ylog",
"=",
"False",
",",
"view",
"=",
"False",
",",
"filename",
"=",
"'avg_fitness.svg'",
")",
":",
"if",
"plt",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"This display is not available due to a missing opt... | Plots the population's average and best fitness. | [
"Plots",
"the",
"population",
"s",
"average",
"and",
"best",
"fitness",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/memory-variable/visualize.py#L12-L40 |
234,061 | CodeReclaimers/neat-python | examples/memory-variable/visualize.py | plot_species | def plot_species(statistics, view=False, filename='speciation.svg'):
""" Visualizes speciation throughout evolution. """
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
species_sizes = statistics.get_species_sizes()
num_generations = len(species_sizes)
curves = np.array(species_sizes).T
fig, ax = plt.subplots()
ax.stackplot(range(num_generations), *curves)
plt.title("Speciation")
plt.ylabel("Size per Species")
plt.xlabel("Generations")
plt.savefig(filename)
if view:
plt.show()
plt.close() | python | def plot_species(statistics, view=False, filename='speciation.svg'):
if plt is None:
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
return
species_sizes = statistics.get_species_sizes()
num_generations = len(species_sizes)
curves = np.array(species_sizes).T
fig, ax = plt.subplots()
ax.stackplot(range(num_generations), *curves)
plt.title("Speciation")
plt.ylabel("Size per Species")
plt.xlabel("Generations")
plt.savefig(filename)
if view:
plt.show()
plt.close() | [
"def",
"plot_species",
"(",
"statistics",
",",
"view",
"=",
"False",
",",
"filename",
"=",
"'speciation.svg'",
")",
":",
"if",
"plt",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"This display is not available due to a missing optional dependency (matplotlib)\"",
... | Visualizes speciation throughout evolution. | [
"Visualizes",
"speciation",
"throughout",
"evolution",
"."
] | e3dbe77c0d776eae41d598e6439e6ac02ab90b18 | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/memory-variable/visualize.py#L89-L111 |
234,062 | 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):
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 |
234,063 | 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):
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 |
234,064 | 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
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 |
234,065 | 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):
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 |
234,066 | 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):
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 |
234,067 | 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):
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 |
234,068 | 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):
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 |
234,069 | 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):
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 |
234,070 | 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):
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 |
234,071 | 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):
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 |
234,072 | 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):
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 |
234,073 | 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):
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 |
234,074 | 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):
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 |
234,075 | 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):
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 |
234,076 | 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):
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 |
234,077 | 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):
# 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 |
234,078 | 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):
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 |
234,079 | 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):
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 |
234,080 | 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):
# 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 |
234,081 | 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):
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 |
234,082 | 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):
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 |
234,083 | 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):
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 |
234,084 | 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):
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 |
234,085 | 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):
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 |
234,086 | 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):
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 |
234,087 | 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):
# 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 |
234,088 | 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):
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 |
234,089 | 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):
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 |
234,090 | 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 |
234,091 | 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):
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 |
234,092 | 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
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 |
234,093 | 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):
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 |
234,094 | 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):
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 |
234,095 | 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):
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 |
234,096 | 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'):
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 |
234,097 | 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'):
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 |
234,098 | 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):
# 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 |
234,099 | 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):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.