repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mrjoes/sockjs-tornado | sockjs/tornado/sessioncontainer.py | SessionContainer.remove | def remove(self, session_id):
"""Remove session object from the container
`session_id`
Session identifier
"""
session = self._items.get(session_id, None)
if session is not None:
session.promoted = -1
session.on_delete(True)
del self._items[session_id]
return True
return False | python | def remove(self, session_id):
"""Remove session object from the container
`session_id`
Session identifier
"""
session = self._items.get(session_id, None)
if session is not None:
session.promoted = -1
session.on_delete(True)
del self._items[session_id]
return True
return False | [
"def",
"remove",
"(",
"self",
",",
"session_id",
")",
":",
"session",
"=",
"self",
".",
"_items",
".",
"get",
"(",
"session_id",
",",
"None",
")",
"if",
"session",
"is",
"not",
"None",
":",
"session",
".",
"promoted",
"=",
"-",
"1",
"session",
".",
... | Remove session object from the container
`session_id`
Session identifier | [
"Remove",
"session",
"object",
"from",
"the",
"container"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/sessioncontainer.py#L101-L115 | train | 35,000 |
mrjoes/sockjs-tornado | sockjs/tornado/transports/streamingbase.py | StreamingTransportBase.send_complete | def send_complete(self):
"""
Verify if connection should be closed based on amount of data that was sent.
"""
self.active = True
if self.should_finish():
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
else:
if self.session:
self.session.flush() | python | def send_complete(self):
"""
Verify if connection should be closed based on amount of data that was sent.
"""
self.active = True
if self.should_finish():
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
else:
if self.session:
self.session.flush() | [
"def",
"send_complete",
"(",
"self",
")",
":",
"self",
".",
"active",
"=",
"True",
"if",
"self",
".",
"should_finish",
"(",
")",
":",
"self",
".",
"_detach",
"(",
")",
"# Avoid race condition when waiting for write callback and session getting closed in between",
"if"... | Verify if connection should be closed based on amount of data that was sent. | [
"Verify",
"if",
"connection",
"should",
"be",
"closed",
"based",
"on",
"amount",
"of",
"data",
"that",
"was",
"sent",
"."
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/transports/streamingbase.py#L33-L47 | train | 35,001 |
mrjoes/sockjs-tornado | sockjs/tornado/conn.py | SockJSConnection.send | def send(self, message, binary=False):
"""Send message to the client.
`message`
Message to send.
"""
if not self.is_closed:
self.session.send_message(message, binary=binary) | python | def send(self, message, binary=False):
"""Send message to the client.
`message`
Message to send.
"""
if not self.is_closed:
self.session.send_message(message, binary=binary) | [
"def",
"send",
"(",
"self",
",",
"message",
",",
"binary",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_closed",
":",
"self",
".",
"session",
".",
"send_message",
"(",
"message",
",",
"binary",
"=",
"binary",
")"
] | Send message to the client.
`message`
Message to send. | [
"Send",
"message",
"to",
"the",
"client",
"."
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/conn.py#L42-L49 | train | 35,002 |
mrjoes/sockjs-tornado | sockjs/tornado/stats.py | StatsCollector.dump | def dump(self):
"""Return dictionary with current statistical information"""
data = dict(
# Sessions
sessions_active=self.sess_active,
# Connections
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
# Packets
packets_sent_ps=self.pack_sent_ps.last_average,
packets_recv_ps=self.pack_recv_ps.last_average
)
for k, v in self.sess_transports.items():
data['transp_' + k] = v
return data | python | def dump(self):
"""Return dictionary with current statistical information"""
data = dict(
# Sessions
sessions_active=self.sess_active,
# Connections
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
# Packets
packets_sent_ps=self.pack_sent_ps.last_average,
packets_recv_ps=self.pack_recv_ps.last_average
)
for k, v in self.sess_transports.items():
data['transp_' + k] = v
return data | [
"def",
"dump",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
"# Sessions",
"sessions_active",
"=",
"self",
".",
"sess_active",
",",
"# Connections",
"connections_active",
"=",
"self",
".",
"conn_active",
",",
"connections_ps",
"=",
"self",
".",
"conn_ps",
... | Return dictionary with current statistical information | [
"Return",
"dictionary",
"with",
"current",
"statistical",
"information"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/stats.py#L79-L97 | train | 35,003 |
mrjoes/sockjs-tornado | sockjs/tornado/basehandler.py | BaseHandler.finish | def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk) | python | def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk) | [
"def",
"finish",
"(",
"self",
",",
"chunk",
"=",
"None",
")",
":",
"self",
".",
"_log_disconnect",
"(",
")",
"super",
"(",
"BaseHandler",
",",
"self",
")",
".",
"finish",
"(",
"chunk",
")"
] | Tornado `finish` handler | [
"Tornado",
"finish",
"handler"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/basehandler.py#L42-L46 | train | 35,004 |
mrjoes/sockjs-tornado | sockjs/tornado/basehandler.py | BaseHandler.handle_session_cookie | def handle_session_cookie(self):
"""Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings, ignore cookie logic
if not self.server.settings['jsessionid']:
return
cookie = self.cookies.get('JSESSIONID')
if not cookie:
cv = 'dummy'
else:
cv = cookie.value
self.set_cookie('JSESSIONID', cv) | python | def handle_session_cookie(self):
"""Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings, ignore cookie logic
if not self.server.settings['jsessionid']:
return
cookie = self.cookies.get('JSESSIONID')
if not cookie:
cv = 'dummy'
else:
cv = cookie.value
self.set_cookie('JSESSIONID', cv) | [
"def",
"handle_session_cookie",
"(",
"self",
")",
":",
"# If JSESSIONID support is disabled in the settings, ignore cookie logic",
"if",
"not",
"self",
".",
"server",
".",
"settings",
"[",
"'jsessionid'",
"]",
":",
"return",
"cookie",
"=",
"self",
".",
"cookies",
".",... | Handle JSESSIONID cookie logic | [
"Handle",
"JSESSIONID",
"cookie",
"logic"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/basehandler.py#L66-L79 | train | 35,005 |
mrjoes/sockjs-tornado | sockjs/tornado/basehandler.py | PreflightHandler.options | def options(self, *args, **kwargs):
"""XHR cross-domain OPTIONS handler"""
self.enable_cache()
self.handle_session_cookie()
self.preflight()
if self.verify_origin():
allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST')
self.set_header('Access-Control-Allow-Methods', allowed_methods)
self.set_header('Allow', allowed_methods)
self.set_status(204)
else:
# Set forbidden
self.set_status(403)
self.finish() | python | def options(self, *args, **kwargs):
"""XHR cross-domain OPTIONS handler"""
self.enable_cache()
self.handle_session_cookie()
self.preflight()
if self.verify_origin():
allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST')
self.set_header('Access-Control-Allow-Methods', allowed_methods)
self.set_header('Allow', allowed_methods)
self.set_status(204)
else:
# Set forbidden
self.set_status(403)
self.finish() | [
"def",
"options",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"enable_cache",
"(",
")",
"self",
".",
"handle_session_cookie",
"(",
")",
"self",
".",
"preflight",
"(",
")",
"if",
"self",
".",
"verify_origin",
"(",
")... | XHR cross-domain OPTIONS handler | [
"XHR",
"cross",
"-",
"domain",
"OPTIONS",
"handler"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/basehandler.py#L98-L114 | train | 35,006 |
mrjoes/sockjs-tornado | sockjs/tornado/basehandler.py | PreflightHandler.preflight | def preflight(self):
"""Handles request authentication"""
origin = self.request.headers.get('Origin', '*')
self.set_header('Access-Control-Allow-Origin', origin)
headers = self.request.headers.get('Access-Control-Request-Headers')
if headers:
self.set_header('Access-Control-Allow-Headers', headers)
self.set_header('Access-Control-Allow-Credentials', 'true') | python | def preflight(self):
"""Handles request authentication"""
origin = self.request.headers.get('Origin', '*')
self.set_header('Access-Control-Allow-Origin', origin)
headers = self.request.headers.get('Access-Control-Request-Headers')
if headers:
self.set_header('Access-Control-Allow-Headers', headers)
self.set_header('Access-Control-Allow-Credentials', 'true') | [
"def",
"preflight",
"(",
"self",
")",
":",
"origin",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Origin'",
",",
"'*'",
")",
"self",
".",
"set_header",
"(",
"'Access-Control-Allow-Origin'",
",",
"origin",
")",
"headers",
"=",
"self",
"... | Handles request authentication | [
"Handles",
"request",
"authentication"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/basehandler.py#L116-L125 | train | 35,007 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | ConnectionInfo.get_argument | def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0]
return None | python | def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0]
return None | [
"def",
"get_argument",
"(",
"self",
",",
"name",
")",
":",
"val",
"=",
"self",
".",
"arguments",
".",
"get",
"(",
"name",
")",
"if",
"val",
":",
"return",
"val",
"[",
"0",
"]",
"return",
"None"
] | Return single argument by name | [
"Return",
"single",
"argument",
"by",
"name"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L43-L48 | train | 35,008 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | BaseSession.verify_state | def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
self.state = OPEN
self.conn.on_open(self.conn_info) | python | def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
self.state = OPEN
self.conn.on_open(self.conn_info) | [
"def",
"verify_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"CONNECTING",
":",
"self",
".",
"state",
"=",
"OPEN",
"self",
".",
"conn",
".",
"on_open",
"(",
"self",
".",
"conn_info",
")"
] | Verify if session was not yet opened. If it is, open it and call connections `on_open` | [
"Verify",
"if",
"session",
"was",
"not",
"yet",
"opened",
".",
"If",
"it",
"is",
"open",
"it",
"and",
"call",
"connections",
"on_open"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L107-L112 | train | 35,009 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | BaseSession.delayed_close | def delayed_close(self):
"""Delayed close - won't close immediately, but on next ioloop tick."""
self.state = CLOSING
self.server.io_loop.add_callback(self.close) | python | def delayed_close(self):
"""Delayed close - won't close immediately, but on next ioloop tick."""
self.state = CLOSING
self.server.io_loop.add_callback(self.close) | [
"def",
"delayed_close",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"CLOSING",
"self",
".",
"server",
".",
"io_loop",
".",
"add_callback",
"(",
"self",
".",
"close",
")"
] | Delayed close - won't close immediately, but on next ioloop tick. | [
"Delayed",
"close",
"-",
"won",
"t",
"close",
"immediately",
"but",
"on",
"next",
"ioloop",
"tick",
"."
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L151-L154 | train | 35,010 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | Session.on_delete | def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
if not forced and self.handler is not None and not self.is_closed:
self.promote()
else:
self.close() | python | def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
if not forced and self.handler is not None and not self.is_closed:
self.promote()
else:
self.close() | [
"def",
"on_delete",
"(",
"self",
",",
"forced",
")",
":",
"# Do not remove connection if it was not forced and there's running connection",
"if",
"not",
"forced",
"and",
"self",
".",
"handler",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"is_closed",
":",
"self"... | Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False. | [
"Session",
"expiration",
"callback"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L241-L252 | train | 35,011 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | Session.remove_handler | def remove_handler(self, handler):
"""Detach active handler from the session
`handler`
Handler to remove
"""
super(Session, self).remove_handler(handler)
self.promote()
self.stop_heartbeat() | python | def remove_handler(self, handler):
"""Detach active handler from the session
`handler`
Handler to remove
"""
super(Session, self).remove_handler(handler)
self.promote()
self.stop_heartbeat() | [
"def",
"remove_handler",
"(",
"self",
",",
"handler",
")",
":",
"super",
"(",
"Session",
",",
"self",
")",
".",
"remove_handler",
"(",
"handler",
")",
"self",
".",
"promote",
"(",
")",
"self",
".",
"stop_heartbeat",
"(",
")"
] | Detach active handler from the session
`handler`
Handler to remove | [
"Detach",
"active",
"handler",
"from",
"the",
"session"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L303-L312 | train | 35,012 |
mrjoes/sockjs-tornado | sockjs/tornado/migrate.py | WebsocketHandler.on_open | def on_open(self, info):
"""sockjs-tornado on_open handler"""
# Store some properties
self.ip = info.ip
# Create fake request object
self.request = info
# Call open
self.open() | python | def on_open(self, info):
"""sockjs-tornado on_open handler"""
# Store some properties
self.ip = info.ip
# Create fake request object
self.request = info
# Call open
self.open() | [
"def",
"on_open",
"(",
"self",
",",
"info",
")",
":",
"# Store some properties",
"self",
".",
"ip",
"=",
"info",
".",
"ip",
"# Create fake request object",
"self",
".",
"request",
"=",
"info",
"# Call open",
"self",
".",
"open",
"(",
")"
] | sockjs-tornado on_open handler | [
"sockjs",
"-",
"tornado",
"on_open",
"handler"
] | bd3a99b407f1181f054b3b1730f438dde375ca1c | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/migrate.py#L22-L31 | train | 35,013 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager._notebook_model_from_path | def _notebook_model_from_path(self, path, content=False, format=None):
"""
Build a notebook model from database record.
"""
model = base_model(path)
model["type"] = "notebook"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTIME"]
else:
model["last_modified"] = model["created"] = DUMMY_CREATED_DATE
if content:
if not self.fs.isfile(path):
self.no_such_entity(path)
file_content = self.fs.read(path)
nb_content = reads(file_content, as_version=NBFORMAT_VERSION)
self.mark_trusted_cells(nb_content, path)
model["format"] = "json"
model["content"] = nb_content
self.validate_notebook_model(model)
return model | python | def _notebook_model_from_path(self, path, content=False, format=None):
"""
Build a notebook model from database record.
"""
model = base_model(path)
model["type"] = "notebook"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTIME"]
else:
model["last_modified"] = model["created"] = DUMMY_CREATED_DATE
if content:
if not self.fs.isfile(path):
self.no_such_entity(path)
file_content = self.fs.read(path)
nb_content = reads(file_content, as_version=NBFORMAT_VERSION)
self.mark_trusted_cells(nb_content, path)
model["format"] = "json"
model["content"] = nb_content
self.validate_notebook_model(model)
return model | [
"def",
"_notebook_model_from_path",
"(",
"self",
",",
"path",
",",
"content",
"=",
"False",
",",
"format",
"=",
"None",
")",
":",
"model",
"=",
"base_model",
"(",
"path",
")",
"model",
"[",
"\"type\"",
"]",
"=",
"\"notebook\"",
"if",
"self",
".",
"fs",
... | Build a notebook model from database record. | [
"Build",
"a",
"notebook",
"model",
"from",
"database",
"record",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L111-L130 | train | 35,014 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager._file_model_from_path | def _file_model_from_path(self, path, content=False, format=None):
"""
Build a file model from database record.
"""
model = base_model(path)
model["type"] = "file"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTIME"]
else:
model["last_modified"] = model["created"] = DUMMY_CREATED_DATE
if content:
try:
content = self.fs.read(path)
except NoSuchFile as e:
self.no_such_entity(e.path)
except GenericFSError as e:
self.do_error(str(e), 500)
model["format"] = format or "text"
model["content"] = content
model["mimetype"] = mimetypes.guess_type(path)[0] or "text/plain"
if format == "base64":
model["format"] = format or "base64"
from base64 import b64decode
model["content"] = b64decode(content)
return model | python | def _file_model_from_path(self, path, content=False, format=None):
"""
Build a file model from database record.
"""
model = base_model(path)
model["type"] = "file"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTIME"]
else:
model["last_modified"] = model["created"] = DUMMY_CREATED_DATE
if content:
try:
content = self.fs.read(path)
except NoSuchFile as e:
self.no_such_entity(e.path)
except GenericFSError as e:
self.do_error(str(e), 500)
model["format"] = format or "text"
model["content"] = content
model["mimetype"] = mimetypes.guess_type(path)[0] or "text/plain"
if format == "base64":
model["format"] = format or "base64"
from base64 import b64decode
model["content"] = b64decode(content)
return model | [
"def",
"_file_model_from_path",
"(",
"self",
",",
"path",
",",
"content",
"=",
"False",
",",
"format",
"=",
"None",
")",
":",
"model",
"=",
"base_model",
"(",
"path",
")",
"model",
"[",
"\"type\"",
"]",
"=",
"\"file\"",
"if",
"self",
".",
"fs",
".",
... | Build a file model from database record. | [
"Build",
"a",
"file",
"model",
"from",
"database",
"record",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L132-L156 | train | 35,015 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager._convert_file_records | def _convert_file_records(self, paths):
"""
Applies _notebook_model_from_s3_path or _file_model_from_s3_path to each entry of `paths`,
depending on the result of `guess_type`.
"""
ret = []
for path in paths:
# path = self.fs.remove_prefix(path, self.prefix) # Remove bucket prefix from paths
if os.path.basename(path) == self.fs.dir_keep_file:
continue
type_ = self.guess_type(path, allow_directory=True)
if type_ == "notebook":
ret.append(self._notebook_model_from_path(path, False))
elif type_ == "file":
ret.append(self._file_model_from_path(path, False, None))
elif type_ == "directory":
ret.append(self._directory_model_from_path(path, False))
else:
self.do_error("Unknown file type %s for file '%s'" % (type_, path), 500)
return ret | python | def _convert_file_records(self, paths):
"""
Applies _notebook_model_from_s3_path or _file_model_from_s3_path to each entry of `paths`,
depending on the result of `guess_type`.
"""
ret = []
for path in paths:
# path = self.fs.remove_prefix(path, self.prefix) # Remove bucket prefix from paths
if os.path.basename(path) == self.fs.dir_keep_file:
continue
type_ = self.guess_type(path, allow_directory=True)
if type_ == "notebook":
ret.append(self._notebook_model_from_path(path, False))
elif type_ == "file":
ret.append(self._file_model_from_path(path, False, None))
elif type_ == "directory":
ret.append(self._directory_model_from_path(path, False))
else:
self.do_error("Unknown file type %s for file '%s'" % (type_, path), 500)
return ret | [
"def",
"_convert_file_records",
"(",
"self",
",",
"paths",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"# path = self.fs.remove_prefix(path, self.prefix) # Remove bucket prefix from paths",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"path... | Applies _notebook_model_from_s3_path or _file_model_from_s3_path to each entry of `paths`,
depending on the result of `guess_type`. | [
"Applies",
"_notebook_model_from_s3_path",
"or",
"_file_model_from_s3_path",
"to",
"each",
"entry",
"of",
"paths",
"depending",
"on",
"the",
"result",
"of",
"guess_type",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L158-L177 | train | 35,016 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager.save | def save(self, model, path):
"""Save a file or directory model to path.
"""
self.log.debug("S3contents.GenericManager: save %s: '%s'", model, path)
if "type" not in model:
self.do_error("No model type provided", 400)
if "content" not in model and model["type"] != "directory":
self.do_error("No file content provided", 400)
if model["type"] not in ("file", "directory", "notebook"):
self.do_error("Unhandled contents type: %s" % model["type"], 400)
try:
if model["type"] == "notebook":
validation_message = self._save_notebook(model, path)
elif model["type"] == "file":
validation_message = self._save_file(model, path)
else:
validation_message = self._save_directory(path)
except Exception as e:
self.log.error("Error while saving file: %s %s", path, e, exc_info=True)
self.do_error("Unexpected error while saving file: %s %s" % (path, e), 500)
model = self.get(path, type=model["type"], content=False)
if validation_message is not None:
model["message"] = validation_message
return model | python | def save(self, model, path):
"""Save a file or directory model to path.
"""
self.log.debug("S3contents.GenericManager: save %s: '%s'", model, path)
if "type" not in model:
self.do_error("No model type provided", 400)
if "content" not in model and model["type"] != "directory":
self.do_error("No file content provided", 400)
if model["type"] not in ("file", "directory", "notebook"):
self.do_error("Unhandled contents type: %s" % model["type"], 400)
try:
if model["type"] == "notebook":
validation_message = self._save_notebook(model, path)
elif model["type"] == "file":
validation_message = self._save_file(model, path)
else:
validation_message = self._save_directory(path)
except Exception as e:
self.log.error("Error while saving file: %s %s", path, e, exc_info=True)
self.do_error("Unexpected error while saving file: %s %s" % (path, e), 500)
model = self.get(path, type=model["type"], content=False)
if validation_message is not None:
model["message"] = validation_message
return model | [
"def",
"save",
"(",
"self",
",",
"model",
",",
"path",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"S3contents.GenericManager: save %s: '%s'\"",
",",
"model",
",",
"path",
")",
"if",
"\"type\"",
"not",
"in",
"model",
":",
"self",
".",
"do_error",
... | Save a file or directory model to path. | [
"Save",
"a",
"file",
"or",
"directory",
"model",
"to",
"path",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L179-L205 | train | 35,017 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager.rename_file | def rename_file(self, old_path, new_path):
"""Rename a file or directory.
NOTE: This method is unfortunately named on the base class. It
actually moves a file or a directory.
"""
self.log.debug("S3contents.GenericManager: Init rename of '%s' to '%s'", old_path, new_path)
if self.file_exists(new_path) or self.dir_exists(new_path):
self.already_exists(new_path)
elif self.file_exists(old_path) or self.dir_exists(old_path):
self.log.debug("S3contents.GenericManager: Actually renaming '%s' to '%s'", old_path,
new_path)
self.fs.mv(old_path, new_path)
else:
self.no_such_entity(old_path) | python | def rename_file(self, old_path, new_path):
"""Rename a file or directory.
NOTE: This method is unfortunately named on the base class. It
actually moves a file or a directory.
"""
self.log.debug("S3contents.GenericManager: Init rename of '%s' to '%s'", old_path, new_path)
if self.file_exists(new_path) or self.dir_exists(new_path):
self.already_exists(new_path)
elif self.file_exists(old_path) or self.dir_exists(old_path):
self.log.debug("S3contents.GenericManager: Actually renaming '%s' to '%s'", old_path,
new_path)
self.fs.mv(old_path, new_path)
else:
self.no_such_entity(old_path) | [
"def",
"rename_file",
"(",
"self",
",",
"old_path",
",",
"new_path",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"S3contents.GenericManager: Init rename of '%s' to '%s'\"",
",",
"old_path",
",",
"new_path",
")",
"if",
"self",
".",
"file_exists",
"(",
"new... | Rename a file or directory.
NOTE: This method is unfortunately named on the base class. It
actually moves a file or a directory. | [
"Rename",
"a",
"file",
"or",
"directory",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L223-L237 | train | 35,018 |
danielfrg/s3contents | s3contents/genericmanager.py | GenericContentsManager.delete_file | def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
if self.file_exists(path) or self.dir_exists(path):
self.fs.rm(path)
else:
self.no_such_entity(path) | python | def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
if self.file_exists(path) or self.dir_exists(path):
self.fs.rm(path)
else:
self.no_such_entity(path) | [
"def",
"delete_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"S3contents.GenericManager: delete_file '%s'\"",
",",
"path",
")",
"if",
"self",
".",
"file_exists",
"(",
"path",
")",
"or",
"self",
".",
"dir_exists",
"(",
... | Delete the file or directory at path. | [
"Delete",
"the",
"file",
"or",
"directory",
"at",
"path",
"."
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L239-L246 | train | 35,019 |
danielfrg/s3contents | s3contents/gcs_fs.py | GCSFS.path | def path(self, *path):
"""Utility to join paths including the bucket and prefix"""
path = list(filter(None, path))
path = self.unprefix(path)
items = [self.prefix_] + path
return self.join(*items) | python | def path(self, *path):
"""Utility to join paths including the bucket and prefix"""
path = list(filter(None, path))
path = self.unprefix(path)
items = [self.prefix_] + path
return self.join(*items) | [
"def",
"path",
"(",
"self",
",",
"*",
"path",
")",
":",
"path",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"path",
")",
")",
"path",
"=",
"self",
".",
"unprefix",
"(",
"path",
")",
"items",
"=",
"[",
"self",
".",
"prefix_",
"]",
"+",
"path",... | Utility to join paths including the bucket and prefix | [
"Utility",
"to",
"join",
"paths",
"including",
"the",
"bucket",
"and",
"prefix"
] | d7e398c7da8836ac7579fa475bded06838e053ea | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/gcs_fs.py#L167-L172 | train | 35,020 |
MagicTheGathering/mtg-sdk-python | mtgsdk/restclient.py | RestClient.get | def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):
request_url = "{}?{}".format(url, urlencode(params))
try:
req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'})
response = json.loads(urlopen(req).read().decode("utf-8"))
return response
except HTTPError as err:
raise MtgException(err.read()) | python | def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):
request_url = "{}?{}".format(url, urlencode(params))
try:
req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'})
response = json.loads(urlopen(req).read().decode("utf-8"))
return response
except HTTPError as err:
raise MtgException(err.read()) | [
"def",
"get",
"(",
"url",
",",
"params",
"=",
"{",
"}",
")",
":",
"request_url",
"=",
"url",
"if",
"len",
"(",
"params",
")",
":",
"request_url",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"url",
",",
"urlencode",
"(",
"params",
")",
")",
"try",
":",
... | Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary | [
"Invoke",
"an",
"HTTP",
"GET",
"request",
"on",
"a",
"url"
] | 3d28fe209d72356a559321355d3f7e53ca78a9cc | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/restclient.py#L20-L40 | train | 35,021 |
MagicTheGathering/mtg-sdk-python | mtgsdk/querybuilder.py | QueryBuilder.find | def find(self, id):
"""Get a resource by its id
Args:
id (string): Resource id
Returns:
object: Instance of the resource type
"""
url = "{}/{}/{}".format(__endpoint__, self.type.RESOURCE, id)
response = RestClient.get(url)[self.type.RESOURCE[:-1]]
return self.type(response) | python | def find(self, id):
"""Get a resource by its id
Args:
id (string): Resource id
Returns:
object: Instance of the resource type
"""
url = "{}/{}/{}".format(__endpoint__, self.type.RESOURCE, id)
response = RestClient.get(url)[self.type.RESOURCE[:-1]]
return self.type(response) | [
"def",
"find",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"\"{}/{}/{}\"",
".",
"format",
"(",
"__endpoint__",
",",
"self",
".",
"type",
".",
"RESOURCE",
",",
"id",
")",
"response",
"=",
"RestClient",
".",
"get",
"(",
"url",
")",
"[",
"self",
"."... | Get a resource by its id
Args:
id (string): Resource id
Returns:
object: Instance of the resource type | [
"Get",
"a",
"resource",
"by",
"its",
"id"
] | 3d28fe209d72356a559321355d3f7e53ca78a9cc | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/querybuilder.py#L19-L29 | train | 35,022 |
MagicTheGathering/mtg-sdk-python | mtgsdk/querybuilder.py | QueryBuilder.find_many | def find_many(self, url, type, resource):
"""Get a list of resources
Args:
url (string): URL to invoke
type (class): Class type
resource (string): The REST Resource
Returns:
list of object: List of resource instances
"""
return [type(item) for item in RestClient.get(url)[resource]] | python | def find_many(self, url, type, resource):
"""Get a list of resources
Args:
url (string): URL to invoke
type (class): Class type
resource (string): The REST Resource
Returns:
list of object: List of resource instances
"""
return [type(item) for item in RestClient.get(url)[resource]] | [
"def",
"find_many",
"(",
"self",
",",
"url",
",",
"type",
",",
"resource",
")",
":",
"return",
"[",
"type",
"(",
"item",
")",
"for",
"item",
"in",
"RestClient",
".",
"get",
"(",
"url",
")",
"[",
"resource",
"]",
"]"
] | Get a list of resources
Args:
url (string): URL to invoke
type (class): Class type
resource (string): The REST Resource
Returns:
list of object: List of resource instances | [
"Get",
"a",
"list",
"of",
"resources"
] | 3d28fe209d72356a559321355d3f7e53ca78a9cc | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/querybuilder.py#L31-L41 | train | 35,023 |
MagicTheGathering/mtg-sdk-python | mtgsdk/querybuilder.py | QueryBuilder.iter | def iter(self):
"""Gets all resources, automating paging through data
Returns:
iterable of object: Iterable of resource objects
"""
page = 1
fetch_all = True
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
if 'page' in self.params:
page = self.params['page']
fetch_all = False
response = RestClient.get(url, self.params)[self.type.RESOURCE]
while len(response):
for item in response:
yield self.type(item)
if not fetch_all:
break
else:
page += 1
self.where(page=page)
response = RestClient.get(url, self.params)[self.type.RESOURCE] | python | def iter(self):
"""Gets all resources, automating paging through data
Returns:
iterable of object: Iterable of resource objects
"""
page = 1
fetch_all = True
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
if 'page' in self.params:
page = self.params['page']
fetch_all = False
response = RestClient.get(url, self.params)[self.type.RESOURCE]
while len(response):
for item in response:
yield self.type(item)
if not fetch_all:
break
else:
page += 1
self.where(page=page)
response = RestClient.get(url, self.params)[self.type.RESOURCE] | [
"def",
"iter",
"(",
"self",
")",
":",
"page",
"=",
"1",
"fetch_all",
"=",
"True",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"__endpoint__",
",",
"self",
".",
"type",
".",
"RESOURCE",
")",
"if",
"'page'",
"in",
"self",
".",
"params",
":",
"page",
... | Gets all resources, automating paging through data
Returns:
iterable of object: Iterable of resource objects | [
"Gets",
"all",
"resources",
"automating",
"paging",
"through",
"data"
] | 3d28fe209d72356a559321355d3f7e53ca78a9cc | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/querybuilder.py#L64-L89 | train | 35,024 |
MagicTheGathering/mtg-sdk-python | mtgsdk/querybuilder.py | QueryBuilder.array | def array(self):
"""Get all resources and return the result as an array
Returns:
array of str: Array of resources
"""
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
return RestClient.get(url, self.params)[self.type.RESOURCE] | python | def array(self):
"""Get all resources and return the result as an array
Returns:
array of str: Array of resources
"""
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
return RestClient.get(url, self.params)[self.type.RESOURCE] | [
"def",
"array",
"(",
"self",
")",
":",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"__endpoint__",
",",
"self",
".",
"type",
".",
"RESOURCE",
")",
"return",
"RestClient",
".",
"get",
"(",
"url",
",",
"self",
".",
"params",
")",
"[",
"self",
".",
"... | Get all resources and return the result as an array
Returns:
array of str: Array of resources | [
"Get",
"all",
"resources",
"and",
"return",
"the",
"result",
"as",
"an",
"array"
] | 3d28fe209d72356a559321355d3f7e53ca78a9cc | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/querybuilder.py#L93-L100 | train | 35,025 |
dranjan/python-plyfile | plyfile.py | make2d | def make2d(array, cols=None, dtype=None):
'''
Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty.
'''
if not len(array):
if cols is None or dtype is None:
raise RuntimeError(
"cols and dtype must be specified for empty array"
)
return _np.empty((0, cols), dtype=dtype)
return _np.vstack(array) | python | def make2d(array, cols=None, dtype=None):
'''
Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty.
'''
if not len(array):
if cols is None or dtype is None:
raise RuntimeError(
"cols and dtype must be specified for empty array"
)
return _np.empty((0, cols), dtype=dtype)
return _np.vstack(array) | [
"def",
"make2d",
"(",
"array",
",",
"cols",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"array",
")",
":",
"if",
"cols",
"is",
"None",
"or",
"dtype",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"cols and dtype mu... | Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty. | [
"Make",
"a",
"2D",
"array",
"from",
"an",
"array",
"of",
"arrays",
".",
"The",
"cols",
"and",
"dtype",
"arguments",
"can",
"be",
"omitted",
"if",
"the",
"array",
"is",
"not",
"empty",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L91-L103 | train | 35,026 |
dranjan/python-plyfile | plyfile.py | PlyData._parse_header | def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
) | python | def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
) | [
"def",
"_parse_header",
"(",
"stream",
")",
":",
"parser",
"=",
"_PlyHeaderParser",
"(",
")",
"while",
"parser",
".",
"consume",
"(",
"stream",
".",
"readline",
"(",
")",
")",
":",
"pass",
"return",
"PlyData",
"(",
"[",
"PlyElement",
"(",
"*",
"e",
")"... | Parse a PLY header from a readable file-like stream. | [
"Parse",
"a",
"PLY",
"header",
"from",
"a",
"readable",
"file",
"-",
"like",
"stream",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L367-L382 | train | 35,027 |
dranjan/python-plyfile | plyfile.py | PlyData.read | def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data | python | def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data | [
"def",
"read",
"(",
"stream",
")",
":",
"(",
"must_close",
",",
"stream",
")",
"=",
"_open_stream",
"(",
"stream",
",",
"'read'",
")",
"try",
":",
"data",
"=",
"PlyData",
".",
"_parse_header",
"(",
"stream",
")",
"for",
"elt",
"in",
"data",
":",
"elt... | Read PLY data from a readable file-like object or filename. | [
"Read",
"PLY",
"data",
"from",
"a",
"readable",
"file",
"-",
"like",
"object",
"or",
"filename",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L385-L399 | train | 35,028 |
dranjan/python-plyfile | plyfile.py | PlyData.write | def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close() | python | def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close() | [
"def",
"write",
"(",
"self",
",",
"stream",
")",
":",
"(",
"must_close",
",",
"stream",
")",
"=",
"_open_stream",
"(",
"stream",
",",
"'write'",
")",
"try",
":",
"stream",
".",
"write",
"(",
"self",
".",
"header",
".",
"encode",
"(",
"'ascii'",
")",
... | Write PLY data to a writeable file-like object or filename. | [
"Write",
"PLY",
"data",
"to",
"a",
"writeable",
"file",
"-",
"like",
"object",
"or",
"filename",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L401-L414 | train | 35,029 |
dranjan/python-plyfile | plyfile.py | PlyData.header | def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines) | python | def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines) | [
"def",
"header",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"'ply'",
"]",
"if",
"self",
".",
"text",
":",
"lines",
".",
"append",
"(",
"'format ascii 1.0'",
")",
"else",
":",
"lines",
".",
"append",
"(",
"'format '",
"+",
"_byte_order_reverse",
"[",
"se... | Provide PLY-formatted metadata for the instance. | [
"Provide",
"PLY",
"-",
"formatted",
"metadata",
"for",
"the",
"instance",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L417-L441 | train | 35,030 |
dranjan/python-plyfile | plyfile.py | PlyElement.describe | def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt | python | def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt | [
"def",
"describe",
"(",
"data",
",",
"name",
",",
"len_types",
"=",
"{",
"}",
",",
"val_types",
"=",
"{",
"}",
",",
"comments",
"=",
"[",
"]",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"_np",
".",
"ndarray",
")",
":",
"raise",
"TypeE... | Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer). | [
"Construct",
"a",
"PlyElement",
"from",
"an",
"array",
"s",
"metadata",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L572-L630 | train | 35,031 |
dranjan/python-plyfile | plyfile.py | PlyElement._read | def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity() | python | def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity() | [
"def",
"_read",
"(",
"self",
",",
"stream",
",",
"text",
",",
"byte_order",
")",
":",
"dtype",
"=",
"self",
".",
"dtype",
"(",
"byte_order",
")",
"if",
"text",
":",
"self",
".",
"_read_txt",
"(",
"stream",
")",
"elif",
"_can_mmap",
"(",
"stream",
")"... | Read the actual data from a PLY file. | [
"Read",
"the",
"actual",
"data",
"from",
"a",
"PLY",
"file",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L632-L658 | train | 35,032 |
dranjan/python-plyfile | plyfile.py | PlyElement._write | def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data) | python | def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data) | [
"def",
"_write",
"(",
"self",
",",
"stream",
",",
"text",
",",
"byte_order",
")",
":",
"if",
"text",
":",
"self",
".",
"_write_txt",
"(",
"stream",
")",
"else",
":",
"if",
"self",
".",
"_have_list",
":",
"# There are list properties, so serialization is",
"#... | Write the data to a PLY file. | [
"Write",
"the",
"data",
"to",
"a",
"PLY",
"file",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L660-L676 | train | 35,033 |
dranjan/python-plyfile | plyfile.py | PlyElement._read_txt | def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k) | python | def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k) | [
"def",
"_read_txt",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"_data",
"=",
"_np",
".",
"empty",
"(",
"self",
".",
"count",
",",
"dtype",
"=",
"self",
".",
"dtype",
"(",
")",
")",
"k",
"=",
"0",
"for",
"line",
"in",
"_islice",
"(",
"it... | Load a PLY element from an ASCII-format PLY file. The element
may contain list properties. | [
"Load",
"a",
"PLY",
"element",
"from",
"an",
"ASCII",
"-",
"format",
"PLY",
"file",
".",
"The",
"element",
"may",
"contain",
"list",
"properties",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L678-L709 | train | 35,034 |
dranjan/python-plyfile | plyfile.py | PlyElement._write_txt | def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n') | python | def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n') | [
"def",
"_write_txt",
"(",
"self",
",",
"stream",
")",
":",
"for",
"rec",
"in",
"self",
".",
"data",
":",
"fields",
"=",
"[",
"]",
"for",
"prop",
"in",
"self",
".",
"properties",
":",
"fields",
".",
"extend",
"(",
"prop",
".",
"_to_fields",
"(",
"re... | Save a PLY element to an ASCII-format PLY file. The element may
contain list properties. | [
"Save",
"a",
"PLY",
"element",
"to",
"an",
"ASCII",
"-",
"format",
"PLY",
"file",
".",
"The",
"element",
"may",
"contain",
"list",
"properties",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L711-L722 | train | 35,035 |
dranjan/python-plyfile | plyfile.py | PlyElement._read_bin | def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop) | python | def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop) | [
"def",
"_read_bin",
"(",
"self",
",",
"stream",
",",
"byte_order",
")",
":",
"self",
".",
"_data",
"=",
"_np",
".",
"empty",
"(",
"self",
".",
"count",
",",
"dtype",
"=",
"self",
".",
"dtype",
"(",
"byte_order",
")",
")",
"for",
"k",
"in",
"_range"... | Load a PLY element from a binary PLY file. The element may
contain list properties. | [
"Load",
"a",
"PLY",
"element",
"from",
"a",
"binary",
"PLY",
"file",
".",
"The",
"element",
"may",
"contain",
"list",
"properties",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L724-L739 | train | 35,036 |
dranjan/python-plyfile | plyfile.py | PlyElement._write_bin | def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order) | python | def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order) | [
"def",
"_write_bin",
"(",
"self",
",",
"stream",
",",
"byte_order",
")",
":",
"for",
"rec",
"in",
"self",
".",
"data",
":",
"for",
"prop",
"in",
"self",
".",
"properties",
":",
"prop",
".",
"_write_bin",
"(",
"rec",
"[",
"prop",
".",
"name",
"]",
"... | Save a PLY element to a binary PLY file. The element may
contain list properties. | [
"Save",
"a",
"PLY",
"element",
"to",
"a",
"binary",
"PLY",
"file",
".",
"The",
"element",
"may",
"contain",
"list",
"properties",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L741-L749 | train | 35,037 |
dranjan/python-plyfile | plyfile.py | PlyElement.header | def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines) | python | def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines) | [
"def",
"header",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"'element %s %d'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"count",
")",
"]",
"# Some information is lost here, since all comments are placed",
"# between the 'element' line and the first property definit... | Format this element's metadata as it would appear in a PLY
header. | [
"Format",
"this",
"element",
"s",
"metadata",
"as",
"it",
"would",
"appear",
"in",
"a",
"PLY",
"header",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L752-L767 | train | 35,038 |
dranjan/python-plyfile | plyfile.py | PlyProperty._from_fields | def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields)) | python | def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields)) | [
"def",
"_from_fields",
"(",
"self",
",",
"fields",
")",
":",
"return",
"_np",
".",
"dtype",
"(",
"self",
".",
"dtype",
"(",
")",
")",
".",
"type",
"(",
"next",
"(",
"fields",
")",
")"
] | Parse from generator. Raise StopIteration if the property could
not be read. | [
"Parse",
"from",
"generator",
".",
"Raise",
"StopIteration",
"if",
"the",
"property",
"could",
"not",
"be",
"read",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L826-L832 | train | 35,039 |
dranjan/python-plyfile | plyfile.py | PlyProperty._read_bin | def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration | python | def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration | [
"def",
"_read_bin",
"(",
"self",
",",
"stream",
",",
"byte_order",
")",
":",
"try",
":",
"return",
"_read_array",
"(",
"stream",
",",
"self",
".",
"dtype",
"(",
"byte_order",
")",
",",
"1",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"S... | Read data from a binary stream. Raise StopIteration if the
property could not be read. | [
"Read",
"data",
"from",
"a",
"binary",
"stream",
".",
"Raise",
"StopIteration",
"if",
"the",
"property",
"could",
"not",
"be",
"read",
"."
] | 9f8e8708d3a071229cf292caae7d13264e11c88b | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L841-L850 | train | 35,040 |
99designs/colorific | colorific/palette.py | color_stream_st | def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs):
"""
Read filenames from the input stream and detect their palette.
"""
for line in istream:
filename = line.strip()
try:
palette = extract_colors(filename, **kwargs)
except Exception as e:
print(filename, e, file=sys.stderr)
continue
print_colors(filename, palette)
if save_palette:
save_palette_as_image(filename, palette) | python | def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs):
"""
Read filenames from the input stream and detect their palette.
"""
for line in istream:
filename = line.strip()
try:
palette = extract_colors(filename, **kwargs)
except Exception as e:
print(filename, e, file=sys.stderr)
continue
print_colors(filename, palette)
if save_palette:
save_palette_as_image(filename, palette) | [
"def",
"color_stream_st",
"(",
"istream",
"=",
"sys",
".",
"stdin",
",",
"save_palette",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"line",
"in",
"istream",
":",
"filename",
"=",
"line",
".",
"strip",
"(",
")",
"try",
":",
"palette",
"="... | Read filenames from the input stream and detect their palette. | [
"Read",
"filenames",
"from",
"the",
"input",
"stream",
"and",
"detect",
"their",
"palette",
"."
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L37-L52 | train | 35,041 |
99designs/colorific | colorific/palette.py | color_stream_mt | def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs):
"""
Read filenames from the input stream and detect their palette using
multiple processes.
"""
queue = multiprocessing.Queue(1000)
lock = multiprocessing.Lock()
pool = [multiprocessing.Process(target=color_process, args=(queue, lock),
kwargs=kwargs) for i in range(n)]
for p in pool:
p.start()
block = []
for line in istream:
block.append(line.strip())
if len(block) == config.BLOCK_SIZE:
queue.put(block)
block = []
if block:
queue.put(block)
for i in range(n):
queue.put(config.SENTINEL)
for p in pool:
p.join() | python | def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs):
"""
Read filenames from the input stream and detect their palette using
multiple processes.
"""
queue = multiprocessing.Queue(1000)
lock = multiprocessing.Lock()
pool = [multiprocessing.Process(target=color_process, args=(queue, lock),
kwargs=kwargs) for i in range(n)]
for p in pool:
p.start()
block = []
for line in istream:
block.append(line.strip())
if len(block) == config.BLOCK_SIZE:
queue.put(block)
block = []
if block:
queue.put(block)
for i in range(n):
queue.put(config.SENTINEL)
for p in pool:
p.join() | [
"def",
"color_stream_mt",
"(",
"istream",
"=",
"sys",
".",
"stdin",
",",
"n",
"=",
"config",
".",
"N_PROCESSES",
",",
"*",
"*",
"kwargs",
")",
":",
"queue",
"=",
"multiprocessing",
".",
"Queue",
"(",
"1000",
")",
"lock",
"=",
"multiprocessing",
".",
"L... | Read filenames from the input stream and detect their palette using
multiple processes. | [
"Read",
"filenames",
"from",
"the",
"input",
"stream",
"and",
"detect",
"their",
"palette",
"using",
"multiple",
"processes",
"."
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L55-L81 | train | 35,042 |
99designs/colorific | colorific/palette.py | color_process | def color_process(queue, lock):
"Receive filenames and get the colors from their images."
while True:
block = queue.get()
if block == config.SENTINEL:
break
for filename in block:
try:
palette = extract_colors(filename)
except: # TODO: it's too broad exception.
continue
lock.acquire()
try:
print_colors(filename, palette)
finally:
lock.release() | python | def color_process(queue, lock):
"Receive filenames and get the colors from their images."
while True:
block = queue.get()
if block == config.SENTINEL:
break
for filename in block:
try:
palette = extract_colors(filename)
except: # TODO: it's too broad exception.
continue
lock.acquire()
try:
print_colors(filename, palette)
finally:
lock.release() | [
"def",
"color_process",
"(",
"queue",
",",
"lock",
")",
":",
"while",
"True",
":",
"block",
"=",
"queue",
".",
"get",
"(",
")",
"if",
"block",
"==",
"config",
".",
"SENTINEL",
":",
"break",
"for",
"filename",
"in",
"block",
":",
"try",
":",
"palette"... | Receive filenames and get the colors from their images. | [
"Receive",
"filenames",
"and",
"get",
"the",
"colors",
"from",
"their",
"images",
"."
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L84-L100 | train | 35,043 |
99designs/colorific | colorific/palette.py | extract_colors | def extract_colors(
filename_or_img, min_saturation=config.MIN_SATURATION,
min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS,
min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED):
"""
Determine what the major colors are in the given image.
"""
if Image.isImageType(filename_or_img):
im = filename_or_img
else:
im = Image.open(filename_or_img)
# get point color count
if im.mode != 'RGB':
im = im.convert('RGB')
im = autocrop(im, config.WHITE) # assume white box
im = im.convert(
'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB')
dist = Counter({color: count for count, color
in im.getcolors(n_quantized)})
n_pixels = mul(*im.size)
# aggregate colors
to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK}
aggregated = Counter({config.WHITE: 0, config.BLACK: 0})
sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True)
for c, n in sorted_cols:
if c in aggregated:
# exact match!
aggregated[c] += n
else:
d, nearest = min((distance(c, alt), alt) for alt in aggregated)
if d < min_distance:
# nearby match
aggregated[nearest] += n
to_canonical[c] = nearest
else:
# no nearby match
aggregated[c] = n
to_canonical[c] = c
# order by prominence
colors = sorted(
[Color(c, n / float(n_pixels)) for c, n in aggregated.items()],
key=attrgetter('prominence'), reverse=True)
colors, bg_color = detect_background(im, colors, to_canonical)
# keep any color which meets the minimum saturation
sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)]
if bg_color and not meets_min_saturation(bg_color, min_saturation):
bg_color = None
if sat_colors:
colors = sat_colors
else:
# keep at least one color
colors = colors[:1]
# keep any color within 10% of the majority color
color_list = []
color_count = 0
for color in colors:
if color.prominence >= colors[0].prominence * min_prominence:
color_list.append(color)
color_count += 1
if color_count >= max_colors:
break
return Palette(color_list, bg_color) | python | def extract_colors(
filename_or_img, min_saturation=config.MIN_SATURATION,
min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS,
min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED):
"""
Determine what the major colors are in the given image.
"""
if Image.isImageType(filename_or_img):
im = filename_or_img
else:
im = Image.open(filename_or_img)
# get point color count
if im.mode != 'RGB':
im = im.convert('RGB')
im = autocrop(im, config.WHITE) # assume white box
im = im.convert(
'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB')
dist = Counter({color: count for count, color
in im.getcolors(n_quantized)})
n_pixels = mul(*im.size)
# aggregate colors
to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK}
aggregated = Counter({config.WHITE: 0, config.BLACK: 0})
sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True)
for c, n in sorted_cols:
if c in aggregated:
# exact match!
aggregated[c] += n
else:
d, nearest = min((distance(c, alt), alt) for alt in aggregated)
if d < min_distance:
# nearby match
aggregated[nearest] += n
to_canonical[c] = nearest
else:
# no nearby match
aggregated[c] = n
to_canonical[c] = c
# order by prominence
colors = sorted(
[Color(c, n / float(n_pixels)) for c, n in aggregated.items()],
key=attrgetter('prominence'), reverse=True)
colors, bg_color = detect_background(im, colors, to_canonical)
# keep any color which meets the minimum saturation
sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)]
if bg_color and not meets_min_saturation(bg_color, min_saturation):
bg_color = None
if sat_colors:
colors = sat_colors
else:
# keep at least one color
colors = colors[:1]
# keep any color within 10% of the majority color
color_list = []
color_count = 0
for color in colors:
if color.prominence >= colors[0].prominence * min_prominence:
color_list.append(color)
color_count += 1
if color_count >= max_colors:
break
return Palette(color_list, bg_color) | [
"def",
"extract_colors",
"(",
"filename_or_img",
",",
"min_saturation",
"=",
"config",
".",
"MIN_SATURATION",
",",
"min_distance",
"=",
"config",
".",
"MIN_DISTANCE",
",",
"max_colors",
"=",
"config",
".",
"MAX_COLORS",
",",
"min_prominence",
"=",
"config",
".",
... | Determine what the major colors are in the given image. | [
"Determine",
"what",
"the",
"major",
"colors",
"are",
"in",
"the",
"given",
"image",
"."
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L124-L194 | train | 35,044 |
99designs/colorific | colorific/palette.py | save_palette_as_image | def save_palette_as_image(filename, palette):
"Save palette as a PNG with labeled, colored blocks"
output_filename = '%s_palette.png' % filename[:filename.rfind('.')]
size = (80 * len(palette.colors), 80)
im = Image.new('RGB', size)
draw = ImageDraw.Draw(im)
for i, c in enumerate(palette.colors):
v = colorsys.rgb_to_hsv(*norm_color(c.value))[2]
(x1, y1) = (i * 80, 0)
(x2, y2) = ((i + 1) * 80 - 1, 79)
draw.rectangle([(x1, y1), (x2, y2)], fill=c.value)
if v < 0.6:
# white with shadow
draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (90, 90, 90))
draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value))
else:
# dark with bright "shadow"
draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (230, 230, 230))
draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value), (0, 0, 0))
im.save(output_filename, "PNG") | python | def save_palette_as_image(filename, palette):
"Save palette as a PNG with labeled, colored blocks"
output_filename = '%s_palette.png' % filename[:filename.rfind('.')]
size = (80 * len(palette.colors), 80)
im = Image.new('RGB', size)
draw = ImageDraw.Draw(im)
for i, c in enumerate(palette.colors):
v = colorsys.rgb_to_hsv(*norm_color(c.value))[2]
(x1, y1) = (i * 80, 0)
(x2, y2) = ((i + 1) * 80 - 1, 79)
draw.rectangle([(x1, y1), (x2, y2)], fill=c.value)
if v < 0.6:
# white with shadow
draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (90, 90, 90))
draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value))
else:
# dark with bright "shadow"
draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (230, 230, 230))
draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value), (0, 0, 0))
im.save(output_filename, "PNG") | [
"def",
"save_palette_as_image",
"(",
"filename",
",",
"palette",
")",
":",
"output_filename",
"=",
"'%s_palette.png'",
"%",
"filename",
"[",
":",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"]",
"size",
"=",
"(",
"80",
"*",
"len",
"(",
"palette",
".",
"co... | Save palette as a PNG with labeled, colored blocks | [
"Save",
"palette",
"as",
"a",
"PNG",
"with",
"labeled",
"colored",
"blocks"
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L235-L255 | train | 35,045 |
99designs/colorific | colorific/palette.py | autocrop | def autocrop(im, bgcolor):
"Crop away a border of the given background color."
if im.mode != "RGB":
im = im.convert("RGB")
bg = Image.new("RGB", im.size, bgcolor)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
return im | python | def autocrop(im, bgcolor):
"Crop away a border of the given background color."
if im.mode != "RGB":
im = im.convert("RGB")
bg = Image.new("RGB", im.size, bgcolor)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
return im | [
"def",
"autocrop",
"(",
"im",
",",
"bgcolor",
")",
":",
"if",
"im",
".",
"mode",
"!=",
"\"RGB\"",
":",
"im",
"=",
"im",
".",
"convert",
"(",
"\"RGB\"",
")",
"bg",
"=",
"Image",
".",
"new",
"(",
"\"RGB\"",
",",
"im",
".",
"size",
",",
"bgcolor",
... | Crop away a border of the given background color. | [
"Crop",
"away",
"a",
"border",
"of",
"the",
"given",
"background",
"color",
"."
] | f83e59f61295500f5527dee5894207f2f033cf35 | https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L262-L272 | train | 35,046 |
ttu/ruuvitag-sensor | examples/post_to_influxdb.py | convert_to_influx | def convert_to_influx(mac, payload):
'''
Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB
'''
dataFormat = payload["data_format"] if ('data_format' in payload) else None
fields = {}
fields["temperature"] = payload["temperature"] if ('temperature' in payload) else None
fields["humidity"] = payload["humidity"] if ('humidity' in payload) else None
fields["pressure"] = payload["pressure"] if ('pressure' in payload) else None
fields["accelerationX"] = payload["acceleration_x"] if ('acceleration_x' in payload) else None
fields["accelerationY"] = payload["acceleration_y"] if ('acceleration_y' in payload) else None
fields["accelerationZ"] = payload["acceleration_z"] if ('acceleration_z' in payload) else None
fields["batteryVoltage"] = payload["battery"]/1000.0 if ('battery' in payload) else None
fields["txPower"] = payload["tx_power"] if ('tx_power' in payload) else None
fields["movementCounter"] = payload["movement_counter"] if ('movement_counter' in payload) else None
fields["measurementSequenceNumber"] = payload["measurement_sequence_number"] if ('measurement_sequence_number' in payload) else None
fields["tagID"] = payload["tagID"] if ('tagID' in payload) else None
fields["rssi"] = payload["rssi"] if ('rssi' in payload) else None
return {
"measurement": "ruuvi_measurements",
"tags": {
"mac": mac,
"dataFormat": dataFormat
},
"fields": fields
} | python | def convert_to_influx(mac, payload):
'''
Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB
'''
dataFormat = payload["data_format"] if ('data_format' in payload) else None
fields = {}
fields["temperature"] = payload["temperature"] if ('temperature' in payload) else None
fields["humidity"] = payload["humidity"] if ('humidity' in payload) else None
fields["pressure"] = payload["pressure"] if ('pressure' in payload) else None
fields["accelerationX"] = payload["acceleration_x"] if ('acceleration_x' in payload) else None
fields["accelerationY"] = payload["acceleration_y"] if ('acceleration_y' in payload) else None
fields["accelerationZ"] = payload["acceleration_z"] if ('acceleration_z' in payload) else None
fields["batteryVoltage"] = payload["battery"]/1000.0 if ('battery' in payload) else None
fields["txPower"] = payload["tx_power"] if ('tx_power' in payload) else None
fields["movementCounter"] = payload["movement_counter"] if ('movement_counter' in payload) else None
fields["measurementSequenceNumber"] = payload["measurement_sequence_number"] if ('measurement_sequence_number' in payload) else None
fields["tagID"] = payload["tagID"] if ('tagID' in payload) else None
fields["rssi"] = payload["rssi"] if ('rssi' in payload) else None
return {
"measurement": "ruuvi_measurements",
"tags": {
"mac": mac,
"dataFormat": dataFormat
},
"fields": fields
} | [
"def",
"convert_to_influx",
"(",
"mac",
",",
"payload",
")",
":",
"dataFormat",
"=",
"payload",
"[",
"\"data_format\"",
"]",
"if",
"(",
"'data_format'",
"in",
"payload",
")",
"else",
"None",
"fields",
"=",
"{",
"}",
"fields",
"[",
"\"temperature\"",
"]",
"... | Convert data into RuuviCollector naming schme and scale
returns:
Object to be written to InfluxDB | [
"Convert",
"data",
"into",
"RuuviCollector",
"naming",
"schme",
"and",
"scale"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/post_to_influxdb.py#L35-L63 | train | 35,047 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi_rx.py | _run_get_data_background | def _run_get_data_background(macs, queue, shared_data, bt_device):
"""
Background process function for RuuviTag Sensors
"""
run_flag = RunFlag()
def add_data(data):
if not shared_data['run_flag']:
run_flag.running = False
data[1]['time'] = datetime.utcnow().isoformat()
queue.put(data)
RuuviTagSensor.get_datas(add_data, macs, run_flag, bt_device) | python | def _run_get_data_background(macs, queue, shared_data, bt_device):
"""
Background process function for RuuviTag Sensors
"""
run_flag = RunFlag()
def add_data(data):
if not shared_data['run_flag']:
run_flag.running = False
data[1]['time'] = datetime.utcnow().isoformat()
queue.put(data)
RuuviTagSensor.get_datas(add_data, macs, run_flag, bt_device) | [
"def",
"_run_get_data_background",
"(",
"macs",
",",
"queue",
",",
"shared_data",
",",
"bt_device",
")",
":",
"run_flag",
"=",
"RunFlag",
"(",
")",
"def",
"add_data",
"(",
"data",
")",
":",
"if",
"not",
"shared_data",
"[",
"'run_flag'",
"]",
":",
"run_flag... | Background process function for RuuviTag Sensors | [
"Background",
"process",
"function",
"for",
"RuuviTag",
"Sensors"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi_rx.py#L11-L25 | train | 35,048 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi_rx.py | RuuviTagReactive._data_update | def _data_update(subjects, queue, run_flag):
"""
Get data from backgound process and notify all subscribed observers with the new data
"""
while run_flag.running:
while not queue.empty():
data = queue.get()
for subject in [s for s in subjects if not s.is_disposed]:
subject.on_next(data)
time.sleep(0.1) | python | def _data_update(subjects, queue, run_flag):
"""
Get data from backgound process and notify all subscribed observers with the new data
"""
while run_flag.running:
while not queue.empty():
data = queue.get()
for subject in [s for s in subjects if not s.is_disposed]:
subject.on_next(data)
time.sleep(0.1) | [
"def",
"_data_update",
"(",
"subjects",
",",
"queue",
",",
"run_flag",
")",
":",
"while",
"run_flag",
".",
"running",
":",
"while",
"not",
"queue",
".",
"empty",
"(",
")",
":",
"data",
"=",
"queue",
".",
"get",
"(",
")",
"for",
"subject",
"in",
"[",
... | Get data from backgound process and notify all subscribed observers with the new data | [
"Get",
"data",
"from",
"backgound",
"process",
"and",
"notify",
"all",
"subscribed",
"observers",
"with",
"the",
"new",
"data"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi_rx.py#L34-L43 | train | 35,049 |
ttu/ruuvitag-sensor | examples/http_server_asyncio.py | data_update | async def data_update(queue):
"""
Update data sent by the background process to global allData variable
"""
global allData
while True:
while not queue.empty():
data = queue.get()
allData[data[0]] = data[1]
for key, value in tags.items():
if key in allData:
allData[key]['name'] = value
await asyncio.sleep(0.5) | python | async def data_update(queue):
"""
Update data sent by the background process to global allData variable
"""
global allData
while True:
while not queue.empty():
data = queue.get()
allData[data[0]] = data[1]
for key, value in tags.items():
if key in allData:
allData[key]['name'] = value
await asyncio.sleep(0.5) | [
"async",
"def",
"data_update",
"(",
"queue",
")",
":",
"global",
"allData",
"while",
"True",
":",
"while",
"not",
"queue",
".",
"empty",
"(",
")",
":",
"data",
"=",
"queue",
".",
"get",
"(",
")",
"allData",
"[",
"data",
"[",
"0",
"]",
"]",
"=",
"... | Update data sent by the background process to global allData variable | [
"Update",
"data",
"sent",
"by",
"the",
"background",
"process",
"to",
"global",
"allData",
"variable"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/http_server_asyncio.py#L36-L48 | train | 35,050 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi.py | RuuviTagSensor.convert_data | def convert_data(raw):
"""
Validate that data is from RuuviTag and get correct data part.
Returns:
tuple (int, string): Data Format type and Sensor data
"""
# TODO: Check from raw data correct data format
# Now this returns 2 also for Data Format 4
data = RuuviTagSensor._get_data_format_2and4(raw)
if data is not None:
return (2, data)
data = RuuviTagSensor._get_data_format_3(raw)
if data is not None:
return (3, data)
data = RuuviTagSensor._get_data_format_5(raw)
if data is not None:
return (5, data)
return (None, None) | python | def convert_data(raw):
"""
Validate that data is from RuuviTag and get correct data part.
Returns:
tuple (int, string): Data Format type and Sensor data
"""
# TODO: Check from raw data correct data format
# Now this returns 2 also for Data Format 4
data = RuuviTagSensor._get_data_format_2and4(raw)
if data is not None:
return (2, data)
data = RuuviTagSensor._get_data_format_3(raw)
if data is not None:
return (3, data)
data = RuuviTagSensor._get_data_format_5(raw)
if data is not None:
return (5, data)
return (None, None) | [
"def",
"convert_data",
"(",
"raw",
")",
":",
"# TODO: Check from raw data correct data format",
"# Now this returns 2 also for Data Format 4",
"data",
"=",
"RuuviTagSensor",
".",
"_get_data_format_2and4",
"(",
"raw",
")",
"if",
"data",
"is",
"not",
"None",
":",
"return",
... | Validate that data is from RuuviTag and get correct data part.
Returns:
tuple (int, string): Data Format type and Sensor data | [
"Validate",
"that",
"data",
"is",
"from",
"RuuviTag",
"and",
"get",
"correct",
"data",
"part",
"."
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L42-L66 | train | 35,051 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi.py | RuuviTagSensor.find_ruuvitags | def find_ruuvitags(bt_device=''):
"""
Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors
"""
log.info('Finding RuuviTags. Stop with Ctrl+C.')
datas = dict()
for new_data in RuuviTagSensor._get_ruuvitag_datas(bt_device=bt_device):
if new_data[0] in datas:
continue
datas[new_data[0]] = new_data[1]
log.info(new_data[0])
log.info(new_data[1])
return datas | python | def find_ruuvitags(bt_device=''):
"""
Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors
"""
log.info('Finding RuuviTags. Stop with Ctrl+C.')
datas = dict()
for new_data in RuuviTagSensor._get_ruuvitag_datas(bt_device=bt_device):
if new_data[0] in datas:
continue
datas[new_data[0]] = new_data[1]
log.info(new_data[0])
log.info(new_data[1])
return datas | [
"def",
"find_ruuvitags",
"(",
"bt_device",
"=",
"''",
")",
":",
"log",
".",
"info",
"(",
"'Finding RuuviTags. Stop with Ctrl+C.'",
")",
"datas",
"=",
"dict",
"(",
")",
"for",
"new_data",
"in",
"RuuviTagSensor",
".",
"_get_ruuvitag_datas",
"(",
"bt_device",
"=",
... | Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors | [
"Find",
"all",
"RuuviTags",
".",
"Function",
"will",
"print",
"the",
"mac",
"and",
"the",
"state",
"of",
"the",
"sensors",
"when",
"found",
".",
"Function",
"will",
"execute",
"as",
"long",
"as",
"it",
"is",
"stopped",
".",
"Stop",
"ecexution",
"with",
"... | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L69-L88 | train | 35,052 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi.py | RuuviTagSensor.get_data_for_sensors | def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):
"""
Get lates data for sensors in the MAC's list.
Args:
macs (array): MAC addresses
search_duratio_sec (int): Search duration in seconds. Default 5
bt_device (string): Bluetooth device id
Returns:
dict: MAC and state of found sensors
"""
log.info('Get latest data for sensors. Stop with Ctrl+C.')
log.info('Stops automatically in %ss', search_duratio_sec)
log.info('MACs: %s', macs)
datas = dict()
for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):
datas[new_data[0]] = new_data[1]
return datas | python | def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):
"""
Get lates data for sensors in the MAC's list.
Args:
macs (array): MAC addresses
search_duratio_sec (int): Search duration in seconds. Default 5
bt_device (string): Bluetooth device id
Returns:
dict: MAC and state of found sensors
"""
log.info('Get latest data for sensors. Stop with Ctrl+C.')
log.info('Stops automatically in %ss', search_duratio_sec)
log.info('MACs: %s', macs)
datas = dict()
for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):
datas[new_data[0]] = new_data[1]
return datas | [
"def",
"get_data_for_sensors",
"(",
"macs",
"=",
"[",
"]",
",",
"search_duratio_sec",
"=",
"5",
",",
"bt_device",
"=",
"''",
")",
":",
"log",
".",
"info",
"(",
"'Get latest data for sensors. Stop with Ctrl+C.'",
")",
"log",
".",
"info",
"(",
"'Stops automaticall... | Get lates data for sensors in the MAC's list.
Args:
macs (array): MAC addresses
search_duratio_sec (int): Search duration in seconds. Default 5
bt_device (string): Bluetooth device id
Returns:
dict: MAC and state of found sensors | [
"Get",
"lates",
"data",
"for",
"sensors",
"in",
"the",
"MAC",
"s",
"list",
"."
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L91-L112 | train | 35,053 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi.py | RuuviTagSensor.get_datas | def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''):
"""
Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. Function executes while run_flag.running
bt_device (string): Bluetooth device id
"""
log.info('Get latest data for sensors. Stop with Ctrl+C.')
log.info('MACs: %s', macs)
for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device):
callback(new_data) | python | def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''):
"""
Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. Function executes while run_flag.running
bt_device (string): Bluetooth device id
"""
log.info('Get latest data for sensors. Stop with Ctrl+C.')
log.info('MACs: %s', macs)
for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device):
callback(new_data) | [
"def",
"get_datas",
"(",
"callback",
",",
"macs",
"=",
"[",
"]",
",",
"run_flag",
"=",
"RunFlag",
"(",
")",
",",
"bt_device",
"=",
"''",
")",
":",
"log",
".",
"info",
"(",
"'Get latest data for sensors. Stop with Ctrl+C.'",
")",
"log",
".",
"info",
"(",
... | Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. Function executes while run_flag.running
bt_device (string): Bluetooth device id | [
"Get",
"data",
"for",
"all",
"ruuvitag",
"sensors",
"or",
"sensors",
"in",
"the",
"MAC",
"s",
"list",
"."
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L115-L130 | train | 35,054 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvi.py | RuuviTagSensor._get_ruuvitag_datas | def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):
"""
Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag
bt_device (string): Bluetooth device id
Yields:
tuple: MAC and State of RuuviTag sensor data
"""
mac_blacklist = []
start_time = time.time()
data_iter = ble.get_datas(mac_blacklist, bt_device)
for ble_data in data_iter:
# Check duration
if search_duratio_sec and time.time() - start_time > search_duratio_sec:
data_iter.send(StopIteration)
break
# Check running flag
if not run_flag.running:
data_iter.send(StopIteration)
break
# Check MAC whitelist
if macs and not ble_data[0] in macs:
continue
(data_format, data) = RuuviTagSensor.convert_data(ble_data[1])
# Check that encoded data is valid RuuviTag data and it is sensor data
# If data is not valid RuuviTag data add MAC to blacklist
if data is not None:
state = get_decoder(data_format).decode_data(data)
if state is not None:
yield (ble_data[0], state)
else:
mac_blacklist.append(ble_data[0]) | python | def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):
"""
Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag
bt_device (string): Bluetooth device id
Yields:
tuple: MAC and State of RuuviTag sensor data
"""
mac_blacklist = []
start_time = time.time()
data_iter = ble.get_datas(mac_blacklist, bt_device)
for ble_data in data_iter:
# Check duration
if search_duratio_sec and time.time() - start_time > search_duratio_sec:
data_iter.send(StopIteration)
break
# Check running flag
if not run_flag.running:
data_iter.send(StopIteration)
break
# Check MAC whitelist
if macs and not ble_data[0] in macs:
continue
(data_format, data) = RuuviTagSensor.convert_data(ble_data[1])
# Check that encoded data is valid RuuviTag data and it is sensor data
# If data is not valid RuuviTag data add MAC to blacklist
if data is not None:
state = get_decoder(data_format).decode_data(data)
if state is not None:
yield (ble_data[0], state)
else:
mac_blacklist.append(ble_data[0]) | [
"def",
"_get_ruuvitag_datas",
"(",
"macs",
"=",
"[",
"]",
",",
"search_duratio_sec",
"=",
"None",
",",
"run_flag",
"=",
"RunFlag",
"(",
")",
",",
"bt_device",
"=",
"''",
")",
":",
"mac_blacklist",
"=",
"[",
"]",
"start_time",
"=",
"time",
".",
"time",
... | Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag
bt_device (string): Bluetooth device id
Yields:
tuple: MAC and State of RuuviTag sensor data | [
"Get",
"data",
"from",
"BluetoothCommunication",
"and",
"handle",
"data",
"encoding",
"."
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L133-L170 | train | 35,055 |
ttu/ruuvitag-sensor | ruuvitag_sensor/ruuvitag.py | RuuviTag.update | def update(self):
"""
Get lates data from the sensor and update own state.
Returns:
dict: Latest state
"""
(data_format, data) = RuuviTagSensor.get_data(self._mac, self._bt_device)
if data == self._data:
return self._state
self._data = data
if self._data is None:
self._state = {}
else:
self._state = get_decoder(data_format).decode_data(self._data)
return self._state | python | def update(self):
"""
Get lates data from the sensor and update own state.
Returns:
dict: Latest state
"""
(data_format, data) = RuuviTagSensor.get_data(self._mac, self._bt_device)
if data == self._data:
return self._state
self._data = data
if self._data is None:
self._state = {}
else:
self._state = get_decoder(data_format).decode_data(self._data)
return self._state | [
"def",
"update",
"(",
"self",
")",
":",
"(",
"data_format",
",",
"data",
")",
"=",
"RuuviTagSensor",
".",
"get_data",
"(",
"self",
".",
"_mac",
",",
"self",
".",
"_bt_device",
")",
"if",
"data",
"==",
"self",
".",
"_data",
":",
"return",
"self",
".",... | Get lates data from the sensor and update own state.
Returns:
dict: Latest state | [
"Get",
"lates",
"data",
"from",
"the",
"sensor",
"and",
"update",
"own",
"state",
"."
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvitag.py#L32-L52 | train | 35,056 |
ttu/ruuvitag-sensor | examples/post_to_influxdb_rx.py | write_to_influxdb | def write_to_influxdb(received_data):
'''
Convert data into RuuviCollecor naming schme and scale
'''
dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None
fields = {}
fields["temperature"] = received_data[1]["temperature"] if ('temperature' in received_data[1]) else None
fields["humidity"] = received_data[1]["humidity"] if ('humidity' in received_data[1]) else None
fields["pressure"] = received_data[1]["pressure"] if ('pressure' in received_data[1]) else None
fields["accelerationX"] = received_data[1]["acceleration_x"] if ('acceleration_x' in received_data[1]) else None
fields["accelerationY"] = received_data[1]["acceleration_y"] if ('acceleration_y' in received_data[1]) else None
fields["accelerationZ"] = received_data[1]["acceleration_z"] if ('acceleration_z' in received_data[1]) else None
fields["batteryVoltage"] = received_data[1]["battery"]/1000.0 if ('battery' in received_data[1]) else None
fields["txPower"] = received_data[1]["tx_power"] if ('tx_power' in received_data[1]) else None
fields["movementCounter"] = received_data[1]["movement_counter"] if ('movement_counter' in received_data[1]) else None
fields["measurementSequenceNumber"] = received_data[1]["measurement_sequence_number"] if ('measurement_sequence_number' in received_data[1]) else None
fields["tagID"] = received_data[1]["tagID"] if ('tagID' in received_data[1]) else None
fields["rssi"] = received_data[1]["rssi"] if ('rssi' in received_data[1]) else None
json_body = [
{
"measurement": "ruuvi_measurements",
"tags": {
"mac": received_data[0],
"dataFormat": dataFormat
},
"fields": fields
}
]
client.write_points(json_body) | python | def write_to_influxdb(received_data):
'''
Convert data into RuuviCollecor naming schme and scale
'''
dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None
fields = {}
fields["temperature"] = received_data[1]["temperature"] if ('temperature' in received_data[1]) else None
fields["humidity"] = received_data[1]["humidity"] if ('humidity' in received_data[1]) else None
fields["pressure"] = received_data[1]["pressure"] if ('pressure' in received_data[1]) else None
fields["accelerationX"] = received_data[1]["acceleration_x"] if ('acceleration_x' in received_data[1]) else None
fields["accelerationY"] = received_data[1]["acceleration_y"] if ('acceleration_y' in received_data[1]) else None
fields["accelerationZ"] = received_data[1]["acceleration_z"] if ('acceleration_z' in received_data[1]) else None
fields["batteryVoltage"] = received_data[1]["battery"]/1000.0 if ('battery' in received_data[1]) else None
fields["txPower"] = received_data[1]["tx_power"] if ('tx_power' in received_data[1]) else None
fields["movementCounter"] = received_data[1]["movement_counter"] if ('movement_counter' in received_data[1]) else None
fields["measurementSequenceNumber"] = received_data[1]["measurement_sequence_number"] if ('measurement_sequence_number' in received_data[1]) else None
fields["tagID"] = received_data[1]["tagID"] if ('tagID' in received_data[1]) else None
fields["rssi"] = received_data[1]["rssi"] if ('rssi' in received_data[1]) else None
json_body = [
{
"measurement": "ruuvi_measurements",
"tags": {
"mac": received_data[0],
"dataFormat": dataFormat
},
"fields": fields
}
]
client.write_points(json_body) | [
"def",
"write_to_influxdb",
"(",
"received_data",
")",
":",
"dataFormat",
"=",
"received_data",
"[",
"1",
"]",
"[",
"\"data_format\"",
"]",
"if",
"(",
"'data_format'",
"in",
"received_data",
"[",
"1",
"]",
")",
"else",
"None",
"fields",
"=",
"{",
"}",
"fie... | Convert data into RuuviCollecor naming schme and scale | [
"Convert",
"data",
"into",
"RuuviCollecor",
"naming",
"schme",
"and",
"scale"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/post_to_influxdb_rx.py#L12-L40 | train | 35,057 |
ttu/ruuvitag-sensor | examples/http_server.py | update_data | def update_data():
"""
Update data sent by background process to global allData
"""
global allData
while not q.empty():
allData = q.get()
for key, value in tags.items():
if key in allData:
allData[key]['name'] = value | python | def update_data():
"""
Update data sent by background process to global allData
"""
global allData
while not q.empty():
allData = q.get()
for key, value in tags.items():
if key in allData:
allData[key]['name'] = value | [
"def",
"update_data",
"(",
")",
":",
"global",
"allData",
"while",
"not",
"q",
".",
"empty",
"(",
")",
":",
"allData",
"=",
"q",
".",
"get",
"(",
")",
"for",
"key",
",",
"value",
"in",
"tags",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"al... | Update data sent by background process to global allData | [
"Update",
"data",
"sent",
"by",
"background",
"process",
"to",
"global",
"allData"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/http_server.py#L44-L53 | train | 35,058 |
ttu/ruuvitag-sensor | ruuvitag_sensor/decoder.py | Df5Decoder._get_acceleration | def _get_acceleration(self, data):
'''Return acceleration mG'''
if (data[7:8] == 0x7FFF or
data[9:10] == 0x7FFF or
data[11:12] == 0x7FFF):
return (None, None, None)
acc_x = twos_complement((data[7] << 8) + data[8], 16)
acc_y = twos_complement((data[9] << 8) + data[10], 16)
acc_z = twos_complement((data[11] << 8) + data[12], 16)
return (acc_x, acc_y, acc_z) | python | def _get_acceleration(self, data):
'''Return acceleration mG'''
if (data[7:8] == 0x7FFF or
data[9:10] == 0x7FFF or
data[11:12] == 0x7FFF):
return (None, None, None)
acc_x = twos_complement((data[7] << 8) + data[8], 16)
acc_y = twos_complement((data[9] << 8) + data[10], 16)
acc_z = twos_complement((data[11] << 8) + data[12], 16)
return (acc_x, acc_y, acc_z) | [
"def",
"_get_acceleration",
"(",
"self",
",",
"data",
")",
":",
"if",
"(",
"data",
"[",
"7",
":",
"8",
"]",
"==",
"0x7FFF",
"or",
"data",
"[",
"9",
":",
"10",
"]",
"==",
"0x7FFF",
"or",
"data",
"[",
"11",
":",
"12",
"]",
"==",
"0x7FFF",
")",
... | Return acceleration mG | [
"Return",
"acceleration",
"mG"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L195-L205 | train | 35,059 |
ttu/ruuvitag-sensor | ruuvitag_sensor/decoder.py | Df5Decoder._get_powerinfo | def _get_powerinfo(self, data):
'''Return battery voltage and tx power '''
power_info = (data[13] & 0xFF) << 8 | (data[14] & 0xFF)
battery_voltage = rshift(power_info, 5) + 1600
tx_power = (power_info & 0b11111) * 2 - 40
if rshift(power_info, 5) == 0b11111111111:
battery_voltage = None
if (power_info & 0b11111) == 0b11111:
tx_power = None
return (round(battery_voltage, 3), tx_power) | python | def _get_powerinfo(self, data):
'''Return battery voltage and tx power '''
power_info = (data[13] & 0xFF) << 8 | (data[14] & 0xFF)
battery_voltage = rshift(power_info, 5) + 1600
tx_power = (power_info & 0b11111) * 2 - 40
if rshift(power_info, 5) == 0b11111111111:
battery_voltage = None
if (power_info & 0b11111) == 0b11111:
tx_power = None
return (round(battery_voltage, 3), tx_power) | [
"def",
"_get_powerinfo",
"(",
"self",
",",
"data",
")",
":",
"power_info",
"=",
"(",
"data",
"[",
"13",
"]",
"&",
"0xFF",
")",
"<<",
"8",
"|",
"(",
"data",
"[",
"14",
"]",
"&",
"0xFF",
")",
"battery_voltage",
"=",
"rshift",
"(",
"power_info",
",",
... | Return battery voltage and tx power | [
"Return",
"battery",
"voltage",
"and",
"tx",
"power"
] | b5d1367c26844ae5875b2964c68e7b2f4e1cb082 | https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L207-L218 | train | 35,060 |
carlosescri/DottedDict | dotted/collection.py | split_key | def split_key(key, max_keys=0):
"""Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', '']
Args:
key (basestring): The key to be splitted.
max_keys (int): The maximum number of keys to be extracted. 0 means no
limits.
Returns:
A list of keys
"""
parts = [x for x in re.split(SPLIT_REGEX, key) if x != "."]
result = []
while len(parts) > 0:
if max_keys > 0 and len(result) == max_keys:
break
result.append(parts.pop(0))
if len(parts) > 0:
result.append(".".join(parts))
return result | python | def split_key(key, max_keys=0):
"""Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', '']
Args:
key (basestring): The key to be splitted.
max_keys (int): The maximum number of keys to be extracted. 0 means no
limits.
Returns:
A list of keys
"""
parts = [x for x in re.split(SPLIT_REGEX, key) if x != "."]
result = []
while len(parts) > 0:
if max_keys > 0 and len(result) == max_keys:
break
result.append(parts.pop(0))
if len(parts) > 0:
result.append(".".join(parts))
return result | [
"def",
"split_key",
"(",
"key",
",",
"max_keys",
"=",
"0",
")",
":",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"re",
".",
"split",
"(",
"SPLIT_REGEX",
",",
"key",
")",
"if",
"x",
"!=",
"\".\"",
"]",
"result",
"=",
"[",
"]",
"while",
"len",
"(",... | Splits a key but allows dots in the key name if they're scaped properly.
Splitting this complex key:
complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme."
split_key(complex_key)
results in:
['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', '']
Args:
key (basestring): The key to be splitted.
max_keys (int): The maximum number of keys to be extracted. 0 means no
limits.
Returns:
A list of keys | [
"Splits",
"a",
"key",
"but",
"allows",
"dots",
"in",
"the",
"key",
"name",
"if",
"they",
"re",
"scaped",
"properly",
"."
] | fa1cba43f414871d0f6978487d61b8760fda4a68 | https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L20-L50 | train | 35,061 |
carlosescri/DottedDict | dotted/collection.py | DottedList.to_python | def to_python(self):
"""Returns a plain python list and converts to plain python objects all
this object's descendants.
"""
result = list(self)
for index, value in enumerate(result):
if isinstance(value, DottedCollection):
result[index] = value.to_python()
return result | python | def to_python(self):
"""Returns a plain python list and converts to plain python objects all
this object's descendants.
"""
result = list(self)
for index, value in enumerate(result):
if isinstance(value, DottedCollection):
result[index] = value.to_python()
return result | [
"def",
"to_python",
"(",
"self",
")",
":",
"result",
"=",
"list",
"(",
"self",
")",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"DottedCollection",
")",
":",
"result",
"[",
"index",
... | Returns a plain python list and converts to plain python objects all
this object's descendants. | [
"Returns",
"a",
"plain",
"python",
"list",
"and",
"converts",
"to",
"plain",
"python",
"objects",
"all",
"this",
"object",
"s",
"descendants",
"."
] | fa1cba43f414871d0f6978487d61b8760fda4a68 | https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L238-L248 | train | 35,062 |
carlosescri/DottedDict | dotted/collection.py | DottedDict.to_python | def to_python(self):
"""Returns a plain python dict and converts to plain python objects all
this object's descendants.
"""
result = dict(self)
for key, value in iteritems(result):
if isinstance(value, DottedCollection):
result[key] = value.to_python()
return result | python | def to_python(self):
"""Returns a plain python dict and converts to plain python objects all
this object's descendants.
"""
result = dict(self)
for key, value in iteritems(result):
if isinstance(value, DottedCollection):
result[key] = value.to_python()
return result | [
"def",
"to_python",
"(",
"self",
")",
":",
"result",
"=",
"dict",
"(",
"self",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"result",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"DottedCollection",
")",
":",
"result",
"[",
"key",
"]"... | Returns a plain python dict and converts to plain python objects all
this object's descendants. | [
"Returns",
"a",
"plain",
"python",
"dict",
"and",
"converts",
"to",
"plain",
"python",
"objects",
"all",
"this",
"object",
"s",
"descendants",
"."
] | fa1cba43f414871d0f6978487d61b8760fda4a68 | https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L315-L325 | train | 35,063 |
jaraco/irc | irc/server.py | IRCClient.handle_nick | def handle_nick(self, params):
"""
Handle the initial setting of the user's nickname and nick changes.
"""
nick = params
# Valid nickname?
if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick):
raise IRCError.from_name('erroneusnickname', ':%s' % nick)
if self.server.clients.get(nick, None) == self:
# Already registered to user
return
if nick in self.server.clients:
# Someone else is using the nick
raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick))
if not self.nick:
# New connection and nick is available; register and send welcome
# and MOTD.
self.nick = nick
self.server.clients[nick] = self
response = ':%s %s %s :%s' % (
self.server.servername,
events.codes['welcome'], self.nick, SRV_WELCOME)
self.send_queue.append(response)
response = ':%s 376 %s :End of MOTD command.' % (
self.server.servername, self.nick)
self.send_queue.append(response)
return
# Nick is available. Change the nick.
message = ':%s NICK :%s' % (self.client_ident(), nick)
self.server.clients.pop(self.nick)
self.nick = nick
self.server.clients[self.nick] = self
# Send a notification of the nick change to all the clients in the
# channels the client is in.
for channel in self.channels.values():
self._send_to_others(message, channel)
# Send a notification of the nick change to the client itself
return message | python | def handle_nick(self, params):
"""
Handle the initial setting of the user's nickname and nick changes.
"""
nick = params
# Valid nickname?
if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick):
raise IRCError.from_name('erroneusnickname', ':%s' % nick)
if self.server.clients.get(nick, None) == self:
# Already registered to user
return
if nick in self.server.clients:
# Someone else is using the nick
raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick))
if not self.nick:
# New connection and nick is available; register and send welcome
# and MOTD.
self.nick = nick
self.server.clients[nick] = self
response = ':%s %s %s :%s' % (
self.server.servername,
events.codes['welcome'], self.nick, SRV_WELCOME)
self.send_queue.append(response)
response = ':%s 376 %s :End of MOTD command.' % (
self.server.servername, self.nick)
self.send_queue.append(response)
return
# Nick is available. Change the nick.
message = ':%s NICK :%s' % (self.client_ident(), nick)
self.server.clients.pop(self.nick)
self.nick = nick
self.server.clients[self.nick] = self
# Send a notification of the nick change to all the clients in the
# channels the client is in.
for channel in self.channels.values():
self._send_to_others(message, channel)
# Send a notification of the nick change to the client itself
return message | [
"def",
"handle_nick",
"(",
"self",
",",
"params",
")",
":",
"nick",
"=",
"params",
"# Valid nickname?",
"if",
"re",
".",
"search",
"(",
"r'[^a-zA-Z0-9\\-\\[\\]\\'`^{}_]'",
",",
"nick",
")",
":",
"raise",
"IRCError",
".",
"from_name",
"(",
"'erroneusnickname'",
... | Handle the initial setting of the user's nickname and nick changes. | [
"Handle",
"the",
"initial",
"setting",
"of",
"the",
"user",
"s",
"nickname",
"and",
"nick",
"changes",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L194-L239 | train | 35,064 |
jaraco/irc | irc/server.py | IRCClient.handle_user | def handle_user(self, params):
"""
Handle the USER command which identifies the user to the server.
"""
params = params.split(' ', 3)
if len(params) != 4:
raise IRCError.from_name(
'needmoreparams',
'USER :Not enough parameters')
user, mode, unused, realname = params
self.user = user
self.mode = mode
self.realname = realname
return '' | python | def handle_user(self, params):
"""
Handle the USER command which identifies the user to the server.
"""
params = params.split(' ', 3)
if len(params) != 4:
raise IRCError.from_name(
'needmoreparams',
'USER :Not enough parameters')
user, mode, unused, realname = params
self.user = user
self.mode = mode
self.realname = realname
return '' | [
"def",
"handle_user",
"(",
"self",
",",
"params",
")",
":",
"params",
"=",
"params",
".",
"split",
"(",
"' '",
",",
"3",
")",
"if",
"len",
"(",
"params",
")",
"!=",
"4",
":",
"raise",
"IRCError",
".",
"from_name",
"(",
"'needmoreparams'",
",",
"'USER... | Handle the USER command which identifies the user to the server. | [
"Handle",
"the",
"USER",
"command",
"which",
"identifies",
"the",
"user",
"to",
"the",
"server",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L241-L256 | train | 35,065 |
jaraco/irc | irc/server.py | IRCClient.handle_privmsg | def handle_privmsg(self, params):
"""
Handle sending a private message to a user or channel.
"""
target, sep, msg = params.partition(' ')
if not msg:
raise IRCError.from_name(
'needmoreparams',
'PRIVMSG :Not enough parameters')
message = ':%s PRIVMSG %s %s' % (self.client_ident(), target, msg)
if target.startswith('#') or target.startswith('$'):
# Message to channel. Check if the channel exists.
channel = self.server.channels.get(target)
if not channel:
raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target)
if channel.name not in self.channels:
# The user isn't in the channel.
raise IRCError.from_name(
'cannotsendtochan',
'%s :Cannot send to channel' % channel.name)
self._send_to_others(message, channel)
else:
# Message to user
client = self.server.clients.get(target, None)
if not client:
raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target)
client.send_queue.append(message) | python | def handle_privmsg(self, params):
"""
Handle sending a private message to a user or channel.
"""
target, sep, msg = params.partition(' ')
if not msg:
raise IRCError.from_name(
'needmoreparams',
'PRIVMSG :Not enough parameters')
message = ':%s PRIVMSG %s %s' % (self.client_ident(), target, msg)
if target.startswith('#') or target.startswith('$'):
# Message to channel. Check if the channel exists.
channel = self.server.channels.get(target)
if not channel:
raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target)
if channel.name not in self.channels:
# The user isn't in the channel.
raise IRCError.from_name(
'cannotsendtochan',
'%s :Cannot send to channel' % channel.name)
self._send_to_others(message, channel)
else:
# Message to user
client = self.server.clients.get(target, None)
if not client:
raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target)
client.send_queue.append(message) | [
"def",
"handle_privmsg",
"(",
"self",
",",
"params",
")",
":",
"target",
",",
"sep",
",",
"msg",
"=",
"params",
".",
"partition",
"(",
"' '",
")",
"if",
"not",
"msg",
":",
"raise",
"IRCError",
".",
"from_name",
"(",
"'needmoreparams'",
",",
"'PRIVMSG :No... | Handle sending a private message to a user or channel. | [
"Handle",
"sending",
"a",
"private",
"message",
"to",
"a",
"user",
"or",
"channel",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L314-L344 | train | 35,066 |
jaraco/irc | irc/server.py | IRCClient._send_to_others | def _send_to_others(self, message, channel):
"""
Send the message to all clients in the specified channel except for
self.
"""
other_clients = [
client for client in channel.clients
if not client == self]
for client in other_clients:
client.send_queue.append(message) | python | def _send_to_others(self, message, channel):
"""
Send the message to all clients in the specified channel except for
self.
"""
other_clients = [
client for client in channel.clients
if not client == self]
for client in other_clients:
client.send_queue.append(message) | [
"def",
"_send_to_others",
"(",
"self",
",",
"message",
",",
"channel",
")",
":",
"other_clients",
"=",
"[",
"client",
"for",
"client",
"in",
"channel",
".",
"clients",
"if",
"not",
"client",
"==",
"self",
"]",
"for",
"client",
"in",
"other_clients",
":",
... | Send the message to all clients in the specified channel except for
self. | [
"Send",
"the",
"message",
"to",
"all",
"clients",
"in",
"the",
"specified",
"channel",
"except",
"for",
"self",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L346-L355 | train | 35,067 |
jaraco/irc | irc/server.py | IRCClient.handle_topic | def handle_topic(self, params):
"""
Handle a topic command.
"""
channel_name, sep, topic = params.partition(' ')
channel = self.server.channels.get(channel_name)
if not channel:
raise IRCError.from_name(
'nosuchnick', 'PRIVMSG :%s' % channel_name)
if channel.name not in self.channels:
# The user isn't in the channel.
raise IRCError.from_name(
'cannotsendtochan',
'%s :Cannot send to channel' % channel.name)
if topic:
channel.topic = topic.lstrip(':')
channel.topic_by = self.nick
message = ':%s TOPIC %s :%s' % (
self.client_ident(), channel_name,
channel.topic)
return message | python | def handle_topic(self, params):
"""
Handle a topic command.
"""
channel_name, sep, topic = params.partition(' ')
channel = self.server.channels.get(channel_name)
if not channel:
raise IRCError.from_name(
'nosuchnick', 'PRIVMSG :%s' % channel_name)
if channel.name not in self.channels:
# The user isn't in the channel.
raise IRCError.from_name(
'cannotsendtochan',
'%s :Cannot send to channel' % channel.name)
if topic:
channel.topic = topic.lstrip(':')
channel.topic_by = self.nick
message = ':%s TOPIC %s :%s' % (
self.client_ident(), channel_name,
channel.topic)
return message | [
"def",
"handle_topic",
"(",
"self",
",",
"params",
")",
":",
"channel_name",
",",
"sep",
",",
"topic",
"=",
"params",
".",
"partition",
"(",
"' '",
")",
"channel",
"=",
"self",
".",
"server",
".",
"channels",
".",
"get",
"(",
"channel_name",
")",
"if",... | Handle a topic command. | [
"Handle",
"a",
"topic",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L357-L379 | train | 35,068 |
jaraco/irc | irc/server.py | IRCClient.handle_quit | def handle_quit(self, params):
"""
Handle the client breaking off the connection with a QUIT command.
"""
response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':'))
# Send quit message to all clients in all channels user is in, and
# remove the user from the channels.
for channel in self.channels.values():
for client in channel.clients:
client.send_queue.append(response)
channel.clients.remove(self) | python | def handle_quit(self, params):
"""
Handle the client breaking off the connection with a QUIT command.
"""
response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':'))
# Send quit message to all clients in all channels user is in, and
# remove the user from the channels.
for channel in self.channels.values():
for client in channel.clients:
client.send_queue.append(response)
channel.clients.remove(self) | [
"def",
"handle_quit",
"(",
"self",
",",
"params",
")",
":",
"response",
"=",
"':%s QUIT :%s'",
"%",
"(",
"self",
".",
"client_ident",
"(",
")",
",",
"params",
".",
"lstrip",
"(",
"':'",
")",
")",
"# Send quit message to all clients in all channels user is in, and"... | Handle the client breaking off the connection with a QUIT command. | [
"Handle",
"the",
"client",
"breaking",
"off",
"the",
"connection",
"with",
"a",
"QUIT",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L401-L411 | train | 35,069 |
jaraco/irc | irc/server.py | IRCClient.handle_dump | def handle_dump(self, params):
"""
Dump internal server information for debugging purposes.
"""
print("Clients:", self.server.clients)
for client in self.server.clients.values():
print(" ", client)
for channel in client.channels.values():
print(" ", channel.name)
print("Channels:", self.server.channels)
for channel in self.server.channels.values():
print(" ", channel.name, channel)
for client in channel.clients:
print(" ", client.nick, client) | python | def handle_dump(self, params):
"""
Dump internal server information for debugging purposes.
"""
print("Clients:", self.server.clients)
for client in self.server.clients.values():
print(" ", client)
for channel in client.channels.values():
print(" ", channel.name)
print("Channels:", self.server.channels)
for channel in self.server.channels.values():
print(" ", channel.name, channel)
for client in channel.clients:
print(" ", client.nick, client) | [
"def",
"handle_dump",
"(",
"self",
",",
"params",
")",
":",
"print",
"(",
"\"Clients:\"",
",",
"self",
".",
"server",
".",
"clients",
")",
"for",
"client",
"in",
"self",
".",
"server",
".",
"clients",
".",
"values",
"(",
")",
":",
"print",
"(",
"\" \... | Dump internal server information for debugging purposes. | [
"Dump",
"internal",
"server",
"information",
"for",
"debugging",
"purposes",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L413-L426 | train | 35,070 |
jaraco/irc | irc/server.py | IRCClient.client_ident | def client_ident(self):
"""
Return the client identifier as included in many command replies.
"""
return irc.client.NickMask.from_params(
self.nick, self.user,
self.server.servername) | python | def client_ident(self):
"""
Return the client identifier as included in many command replies.
"""
return irc.client.NickMask.from_params(
self.nick, self.user,
self.server.servername) | [
"def",
"client_ident",
"(",
"self",
")",
":",
"return",
"irc",
".",
"client",
".",
"NickMask",
".",
"from_params",
"(",
"self",
".",
"nick",
",",
"self",
".",
"user",
",",
"self",
".",
"server",
".",
"servername",
")"
] | Return the client identifier as included in many command replies. | [
"Return",
"the",
"client",
"identifier",
"as",
"included",
"in",
"many",
"command",
"replies",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L442-L448 | train | 35,071 |
jaraco/irc | irc/server.py | IRCClient.finish | def finish(self):
"""
The client conection is finished. Do some cleanup to ensure that the
client doesn't linger around in any channel or the client list, in case
the client didn't properly close the connection with PART and QUIT.
"""
log.info('Client disconnected: %s', self.client_ident())
response = ':%s QUIT :EOF from client' % self.client_ident()
for channel in self.channels.values():
if self in channel.clients:
# Client is gone without properly QUITing or PARTing this
# channel.
for client in channel.clients:
client.send_queue.append(response)
channel.clients.remove(self)
if self.nick:
self.server.clients.pop(self.nick)
log.info('Connection finished: %s', self.client_ident()) | python | def finish(self):
"""
The client conection is finished. Do some cleanup to ensure that the
client doesn't linger around in any channel or the client list, in case
the client didn't properly close the connection with PART and QUIT.
"""
log.info('Client disconnected: %s', self.client_ident())
response = ':%s QUIT :EOF from client' % self.client_ident()
for channel in self.channels.values():
if self in channel.clients:
# Client is gone without properly QUITing or PARTing this
# channel.
for client in channel.clients:
client.send_queue.append(response)
channel.clients.remove(self)
if self.nick:
self.server.clients.pop(self.nick)
log.info('Connection finished: %s', self.client_ident()) | [
"def",
"finish",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Client disconnected: %s'",
",",
"self",
".",
"client_ident",
"(",
")",
")",
"response",
"=",
"':%s QUIT :EOF from client'",
"%",
"self",
".",
"client_ident",
"(",
")",
"for",
"channel",
"in",... | The client conection is finished. Do some cleanup to ensure that the
client doesn't linger around in any channel or the client list, in case
the client didn't properly close the connection with PART and QUIT. | [
"The",
"client",
"conection",
"is",
"finished",
".",
"Do",
"some",
"cleanup",
"to",
"ensure",
"that",
"the",
"client",
"doesn",
"t",
"linger",
"around",
"in",
"any",
"channel",
"or",
"the",
"client",
"list",
"in",
"case",
"the",
"client",
"didn",
"t",
"p... | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L450-L467 | train | 35,072 |
jaraco/irc | irc/client_aio.py | AioConnection.send_raw | def send_raw(self, string):
"""Send raw string to the server, via the asyncio transport.
The string will be padded with appropriate CR LF.
"""
log.debug('RAW: {}'.format(string))
if self.transport is None:
raise ServerNotConnectedError("Not connected.")
self.transport.write(self._prep_message(string)) | python | def send_raw(self, string):
"""Send raw string to the server, via the asyncio transport.
The string will be padded with appropriate CR LF.
"""
log.debug('RAW: {}'.format(string))
if self.transport is None:
raise ServerNotConnectedError("Not connected.")
self.transport.write(self._prep_message(string)) | [
"def",
"send_raw",
"(",
"self",
",",
"string",
")",
":",
"log",
".",
"debug",
"(",
"'RAW: {}'",
".",
"format",
"(",
"string",
")",
")",
"if",
"self",
".",
"transport",
"is",
"None",
":",
"raise",
"ServerNotConnectedError",
"(",
"\"Not connected.\"",
")",
... | Send raw string to the server, via the asyncio transport.
The string will be padded with appropriate CR LF. | [
"Send",
"raw",
"string",
"to",
"the",
"server",
"via",
"the",
"asyncio",
"transport",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client_aio.py#L175-L184 | train | 35,073 |
jaraco/irc | irc/modes.py | _parse_modes | def _parse_modes(mode_string, unary_modes=""):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _parse_modes('+a foo bar baz')
[['+', 'a', None]]
Return none for unary args when not provided
>>> _parse_modes('+abc foo', unary_modes='abc')
[['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]]
This function never throws an error:
>>> import random
>>> def random_text(min_len = 3, max_len = 80):
... len = random.randint(min_len, max_len)
... chars_to_choose = [chr(x) for x in range(0,1024)]
... chars = (random.choice(chars_to_choose) for x in range(len))
... return ''.join(chars)
>>> def random_texts(min_len = 3, max_len = 80):
... while True:
... yield random_text(min_len, max_len)
>>> import itertools
>>> texts = itertools.islice(random_texts(), 1000)
>>> set(type(_parse_modes(text)) for text in texts) == {list}
True
"""
# mode_string must be non-empty and begin with a sign
if not mode_string or not mode_string[0] in '+-':
return []
modes = []
parts = mode_string.split()
mode_part, args = parts[0], parts[1:]
for ch in mode_part:
if ch in "+-":
sign = ch
continue
arg = args.pop(0) if ch in unary_modes and args else None
modes.append([sign, ch, arg])
return modes | python | def _parse_modes(mode_string, unary_modes=""):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _parse_modes('+a foo bar baz')
[['+', 'a', None]]
Return none for unary args when not provided
>>> _parse_modes('+abc foo', unary_modes='abc')
[['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]]
This function never throws an error:
>>> import random
>>> def random_text(min_len = 3, max_len = 80):
... len = random.randint(min_len, max_len)
... chars_to_choose = [chr(x) for x in range(0,1024)]
... chars = (random.choice(chars_to_choose) for x in range(len))
... return ''.join(chars)
>>> def random_texts(min_len = 3, max_len = 80):
... while True:
... yield random_text(min_len, max_len)
>>> import itertools
>>> texts = itertools.islice(random_texts(), 1000)
>>> set(type(_parse_modes(text)) for text in texts) == {list}
True
"""
# mode_string must be non-empty and begin with a sign
if not mode_string or not mode_string[0] in '+-':
return []
modes = []
parts = mode_string.split()
mode_part, args = parts[0], parts[1:]
for ch in mode_part:
if ch in "+-":
sign = ch
continue
arg = args.pop(0) if ch in unary_modes and args else None
modes.append([sign, ch, arg])
return modes | [
"def",
"_parse_modes",
"(",
"mode_string",
",",
"unary_modes",
"=",
"\"\"",
")",
":",
"# mode_string must be non-empty and begin with a sign",
"if",
"not",
"mode_string",
"or",
"not",
"mode_string",
"[",
"0",
"]",
"in",
"'+-'",
":",
"return",
"[",
"]",
"modes",
... | Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _parse_modes('+a foo bar baz')
[['+', 'a', None]]
Return none for unary args when not provided
>>> _parse_modes('+abc foo', unary_modes='abc')
[['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]]
This function never throws an error:
>>> import random
>>> def random_text(min_len = 3, max_len = 80):
... len = random.randint(min_len, max_len)
... chars_to_choose = [chr(x) for x in range(0,1024)]
... chars = (random.choice(chars_to_choose) for x in range(len))
... return ''.join(chars)
>>> def random_texts(min_len = 3, max_len = 80):
... while True:
... yield random_text(min_len, max_len)
>>> import itertools
>>> texts = itertools.islice(random_texts(), 1000)
>>> set(type(_parse_modes(text)) for text in texts) == {list}
True | [
"Parse",
"the",
"mode_string",
"and",
"return",
"a",
"list",
"of",
"triples",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/modes.py#L32-L89 | train | 35,074 |
jaraco/irc | irc/message.py | Tag.from_group | def from_group(cls, group):
"""
Construct tags from the regex group
"""
if not group:
return
tag_items = group.split(";")
return list(map(cls.parse, tag_items)) | python | def from_group(cls, group):
"""
Construct tags from the regex group
"""
if not group:
return
tag_items = group.split(";")
return list(map(cls.parse, tag_items)) | [
"def",
"from_group",
"(",
"cls",
",",
"group",
")",
":",
"if",
"not",
"group",
":",
"return",
"tag_items",
"=",
"group",
".",
"split",
"(",
"\";\"",
")",
"return",
"list",
"(",
"map",
"(",
"cls",
".",
"parse",
",",
"tag_items",
")",
")"
] | Construct tags from the regex group | [
"Construct",
"tags",
"from",
"the",
"regex",
"group"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/message.py#L39-L46 | train | 35,075 |
jaraco/irc | irc/message.py | Arguments.from_group | def from_group(group):
"""
Construct arguments from the regex group
>>> Arguments.from_group('foo')
['foo']
>>> Arguments.from_group(None)
[]
>>> Arguments.from_group('')
[]
>>> Arguments.from_group('foo bar')
['foo', 'bar']
>>> Arguments.from_group('foo bar :baz')
['foo', 'bar', 'baz']
>>> Arguments.from_group('foo bar :baz bing')
['foo', 'bar', 'baz bing']
"""
if not group:
return []
main, sep, ext = group.partition(" :")
arguments = main.split()
if sep:
arguments.append(ext)
return arguments | python | def from_group(group):
"""
Construct arguments from the regex group
>>> Arguments.from_group('foo')
['foo']
>>> Arguments.from_group(None)
[]
>>> Arguments.from_group('')
[]
>>> Arguments.from_group('foo bar')
['foo', 'bar']
>>> Arguments.from_group('foo bar :baz')
['foo', 'bar', 'baz']
>>> Arguments.from_group('foo bar :baz bing')
['foo', 'bar', 'baz bing']
"""
if not group:
return []
main, sep, ext = group.partition(" :")
arguments = main.split()
if sep:
arguments.append(ext)
return arguments | [
"def",
"from_group",
"(",
"group",
")",
":",
"if",
"not",
"group",
":",
"return",
"[",
"]",
"main",
",",
"sep",
",",
"ext",
"=",
"group",
".",
"partition",
"(",
"\" :\"",
")",
"arguments",
"=",
"main",
".",
"split",
"(",
")",
"if",
"sep",
":",
"a... | Construct arguments from the regex group
>>> Arguments.from_group('foo')
['foo']
>>> Arguments.from_group(None)
[]
>>> Arguments.from_group('')
[]
>>> Arguments.from_group('foo bar')
['foo', 'bar']
>>> Arguments.from_group('foo bar :baz')
['foo', 'bar', 'baz']
>>> Arguments.from_group('foo bar :baz bing')
['foo', 'bar', 'baz bing'] | [
"Construct",
"arguments",
"from",
"the",
"regex",
"group"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/message.py#L51-L81 | train | 35,076 |
jaraco/irc | irc/features.py | FeatureSet.set | def set(self, name, value=True):
"set a feature value"
setattr(self, name.lower(), value) | python | def set(self, name, value=True):
"set a feature value"
setattr(self, name.lower(), value) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
"=",
"True",
")",
":",
"setattr",
"(",
"self",
",",
"name",
".",
"lower",
"(",
")",
",",
"value",
")"
] | set a feature value | [
"set",
"a",
"feature",
"value"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L36-L38 | train | 35,077 |
jaraco/irc | irc/features.py | FeatureSet.load | def load(self, arguments):
"Load the values from the a ServerConnection arguments"
features = arguments[1:-1]
list(map(self.load_feature, features)) | python | def load(self, arguments):
"Load the values from the a ServerConnection arguments"
features = arguments[1:-1]
list(map(self.load_feature, features)) | [
"def",
"load",
"(",
"self",
",",
"arguments",
")",
":",
"features",
"=",
"arguments",
"[",
"1",
":",
"-",
"1",
"]",
"list",
"(",
"map",
"(",
"self",
".",
"load_feature",
",",
"features",
")",
")"
] | Load the values from the a ServerConnection arguments | [
"Load",
"the",
"values",
"from",
"the",
"a",
"ServerConnection",
"arguments"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L44-L47 | train | 35,078 |
jaraco/irc | irc/features.py | FeatureSet._parse_PREFIX | def _parse_PREFIX(value):
"channel user prefixes"
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
return collections.OrderedDict(zip(channel_chars, channel_modes)) | python | def _parse_PREFIX(value):
"channel user prefixes"
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
return collections.OrderedDict(zip(channel_chars, channel_modes)) | [
"def",
"_parse_PREFIX",
"(",
"value",
")",
":",
"channel_modes",
",",
"channel_chars",
"=",
"value",
".",
"split",
"(",
"')'",
")",
"channel_modes",
"=",
"channel_modes",
"[",
"1",
":",
"]",
"return",
"collections",
".",
"OrderedDict",
"(",
"zip",
"(",
"ch... | channel user prefixes | [
"channel",
"user",
"prefixes"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L68-L72 | train | 35,079 |
jaraco/irc | irc/bot.py | SingleServerIRCBot._connect | def _connect(self):
"""
Establish a connection to the server at the front of the server_list.
"""
server = self.servers.peek()
try:
self.connect(
server.host, server.port, self._nickname,
server.password, ircname=self._realname,
**self.__connect_params)
except irc.client.ServerConnectionError:
pass | python | def _connect(self):
"""
Establish a connection to the server at the front of the server_list.
"""
server = self.servers.peek()
try:
self.connect(
server.host, server.port, self._nickname,
server.password, ircname=self._realname,
**self.__connect_params)
except irc.client.ServerConnectionError:
pass | [
"def",
"_connect",
"(",
"self",
")",
":",
"server",
"=",
"self",
".",
"servers",
".",
"peek",
"(",
")",
"try",
":",
"self",
".",
"connect",
"(",
"server",
".",
"host",
",",
"server",
".",
"port",
",",
"self",
".",
"_nickname",
",",
"server",
".",
... | Establish a connection to the server at the front of the server_list. | [
"Establish",
"a",
"connection",
"to",
"the",
"server",
"at",
"the",
"front",
"of",
"the",
"server_list",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L173-L184 | train | 35,080 |
jaraco/irc | irc/bot.py | SingleServerIRCBot.jump_server | def jump_server(self, msg="Changing servers"):
"""Connect to a new server, possibly disconnecting from the current.
The bot will skip to next server in the server_list each time
jump_server is called.
"""
if self.connection.is_connected():
self.connection.disconnect(msg)
next(self.servers)
self._connect() | python | def jump_server(self, msg="Changing servers"):
"""Connect to a new server, possibly disconnecting from the current.
The bot will skip to next server in the server_list each time
jump_server is called.
"""
if self.connection.is_connected():
self.connection.disconnect(msg)
next(self.servers)
self._connect() | [
"def",
"jump_server",
"(",
"self",
",",
"msg",
"=",
"\"Changing servers\"",
")",
":",
"if",
"self",
".",
"connection",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"connection",
".",
"disconnect",
"(",
"msg",
")",
"next",
"(",
"self",
".",
"servers",... | Connect to a new server, possibly disconnecting from the current.
The bot will skip to next server in the server_list each time
jump_server is called. | [
"Connect",
"to",
"a",
"new",
"server",
"possibly",
"disconnecting",
"from",
"the",
"current",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L298-L308 | train | 35,081 |
jaraco/irc | irc/bot.py | SingleServerIRCBot.on_ctcp | def on_ctcp(self, connection, event):
"""Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method.
"""
nick = event.source.nick
if event.arguments[0] == "VERSION":
connection.ctcp_reply(nick, "VERSION " + self.get_version())
elif event.arguments[0] == "PING":
if len(event.arguments) > 1:
connection.ctcp_reply(nick, "PING " + event.arguments[1])
elif (
event.arguments[0] == "DCC"
and event.arguments[1].split(" ", 1)[0] == "CHAT"):
self.on_dccchat(connection, event) | python | def on_ctcp(self, connection, event):
"""Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method.
"""
nick = event.source.nick
if event.arguments[0] == "VERSION":
connection.ctcp_reply(nick, "VERSION " + self.get_version())
elif event.arguments[0] == "PING":
if len(event.arguments) > 1:
connection.ctcp_reply(nick, "PING " + event.arguments[1])
elif (
event.arguments[0] == "DCC"
and event.arguments[1].split(" ", 1)[0] == "CHAT"):
self.on_dccchat(connection, event) | [
"def",
"on_ctcp",
"(",
"self",
",",
"connection",
",",
"event",
")",
":",
"nick",
"=",
"event",
".",
"source",
".",
"nick",
"if",
"event",
".",
"arguments",
"[",
"0",
"]",
"==",
"\"VERSION\"",
":",
"connection",
".",
"ctcp_reply",
"(",
"nick",
",",
"... | Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method. | [
"Default",
"handler",
"for",
"ctcp",
"events",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L310-L325 | train | 35,082 |
jaraco/irc | irc/bot.py | Channel.set_mode | def set_mode(self, mode, value=None):
"""Set mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
if mode in self.user_modes:
self.mode_users[mode][value] = 1
else:
self.modes[mode] = value | python | def set_mode(self, mode, value=None):
"""Set mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
if mode in self.user_modes:
self.mode_users[mode][value] = 1
else:
self.modes[mode] = value | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
",",
"value",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"self",
".",
"user_modes",
":",
"self",
".",
"mode_users",
"[",
"mode",
"]",
"[",
"value",
"]",
"=",
"1",
"else",
":",
"self",
".",
"modes",
"["... | Set mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value | [
"Set",
"mode",
"on",
"the",
"channel",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L424-L436 | train | 35,083 |
jaraco/irc | irc/bot.py | Channel.clear_mode | def clear_mode(self, mode, value=None):
"""Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
try:
if mode in self.user_modes:
del self.mode_users[mode][value]
else:
del self.modes[mode]
except KeyError:
pass | python | def clear_mode(self, mode, value=None):
"""Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value
"""
try:
if mode in self.user_modes:
del self.mode_users[mode][value]
else:
del self.modes[mode]
except KeyError:
pass | [
"def",
"clear_mode",
"(",
"self",
",",
"mode",
",",
"value",
"=",
"None",
")",
":",
"try",
":",
"if",
"mode",
"in",
"self",
".",
"user_modes",
":",
"del",
"self",
".",
"mode_users",
"[",
"mode",
"]",
"[",
"value",
"]",
"else",
":",
"del",
"self",
... | Clear mode on the channel.
Arguments:
mode -- The mode (a single-character string).
value -- Value | [
"Clear",
"mode",
"on",
"the",
"channel",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L438-L453 | train | 35,084 |
jaraco/irc | irc/client.py | ip_numstr_to_quad | def ip_numstr_to_quad(num):
"""
Convert an IP number as an integer given in ASCII
representation to an IP address string.
>>> ip_numstr_to_quad('3232235521')
'192.168.0.1'
>>> ip_numstr_to_quad(3232235521)
'192.168.0.1'
"""
packed = struct.pack('>L', int(num))
bytes = struct.unpack('BBBB', packed)
return ".".join(map(str, bytes)) | python | def ip_numstr_to_quad(num):
"""
Convert an IP number as an integer given in ASCII
representation to an IP address string.
>>> ip_numstr_to_quad('3232235521')
'192.168.0.1'
>>> ip_numstr_to_quad(3232235521)
'192.168.0.1'
"""
packed = struct.pack('>L', int(num))
bytes = struct.unpack('BBBB', packed)
return ".".join(map(str, bytes)) | [
"def",
"ip_numstr_to_quad",
"(",
"num",
")",
":",
"packed",
"=",
"struct",
".",
"pack",
"(",
"'>L'",
",",
"int",
"(",
"num",
")",
")",
"bytes",
"=",
"struct",
".",
"unpack",
"(",
"'BBBB'",
",",
"packed",
")",
"return",
"\".\"",
".",
"join",
"(",
"m... | Convert an IP number as an integer given in ASCII
representation to an IP address string.
>>> ip_numstr_to_quad('3232235521')
'192.168.0.1'
>>> ip_numstr_to_quad(3232235521)
'192.168.0.1' | [
"Convert",
"an",
"IP",
"number",
"as",
"an",
"integer",
"given",
"in",
"ASCII",
"representation",
"to",
"an",
"IP",
"address",
"string",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1249-L1261 | train | 35,085 |
jaraco/irc | irc/client.py | ServerConnection.as_nick | def as_nick(self, name):
"""
Set the nick for the duration of the context.
"""
orig = self.get_nickname()
self.nick(name)
try:
yield orig
finally:
self.nick(orig) | python | def as_nick(self, name):
"""
Set the nick for the duration of the context.
"""
orig = self.get_nickname()
self.nick(name)
try:
yield orig
finally:
self.nick(orig) | [
"def",
"as_nick",
"(",
"self",
",",
"name",
")",
":",
"orig",
"=",
"self",
".",
"get_nickname",
"(",
")",
"self",
".",
"nick",
"(",
"name",
")",
"try",
":",
"yield",
"orig",
"finally",
":",
"self",
".",
"nick",
"(",
"orig",
")"
] | Set the nick for the duration of the context. | [
"Set",
"the",
"nick",
"for",
"the",
"duration",
"of",
"the",
"context",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L238-L247 | train | 35,086 |
jaraco/irc | irc/client.py | ServerConnection.process_data | def process_data(self):
"read and process input from self.socket"
try:
reader = getattr(self.socket, 'read', self.socket.recv)
new_data = reader(2 ** 14)
except socket.error:
# The server hung up.
self.disconnect("Connection reset by peer")
return
if not new_data:
# Read nothing: connection must be down.
self.disconnect("Connection reset by peer")
return
self.buffer.feed(new_data)
# process each non-empty line after logging all lines
for line in self.buffer:
log.debug("FROM SERVER: %s", line)
if not line:
continue
self._process_line(line) | python | def process_data(self):
"read and process input from self.socket"
try:
reader = getattr(self.socket, 'read', self.socket.recv)
new_data = reader(2 ** 14)
except socket.error:
# The server hung up.
self.disconnect("Connection reset by peer")
return
if not new_data:
# Read nothing: connection must be down.
self.disconnect("Connection reset by peer")
return
self.buffer.feed(new_data)
# process each non-empty line after logging all lines
for line in self.buffer:
log.debug("FROM SERVER: %s", line)
if not line:
continue
self._process_line(line) | [
"def",
"process_data",
"(",
"self",
")",
":",
"try",
":",
"reader",
"=",
"getattr",
"(",
"self",
".",
"socket",
",",
"'read'",
",",
"self",
".",
"socket",
".",
"recv",
")",
"new_data",
"=",
"reader",
"(",
"2",
"**",
"14",
")",
"except",
"socket",
"... | read and process input from self.socket | [
"read",
"and",
"process",
"input",
"from",
"self",
".",
"socket"
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L249-L271 | train | 35,087 |
jaraco/irc | irc/client.py | ServerConnection.ctcp | def ctcp(self, ctcptype, target, parameter=""):
"""Send a CTCP command."""
ctcptype = ctcptype.upper()
tmpl = (
"\001{ctcptype} {parameter}\001" if parameter else
"\001{ctcptype}\001"
)
self.privmsg(target, tmpl.format(**vars())) | python | def ctcp(self, ctcptype, target, parameter=""):
"""Send a CTCP command."""
ctcptype = ctcptype.upper()
tmpl = (
"\001{ctcptype} {parameter}\001" if parameter else
"\001{ctcptype}\001"
)
self.privmsg(target, tmpl.format(**vars())) | [
"def",
"ctcp",
"(",
"self",
",",
"ctcptype",
",",
"target",
",",
"parameter",
"=",
"\"\"",
")",
":",
"ctcptype",
"=",
"ctcptype",
".",
"upper",
"(",
")",
"tmpl",
"=",
"(",
"\"\\001{ctcptype} {parameter}\\001\"",
"if",
"parameter",
"else",
"\"\\001{ctcptype}\\0... | Send a CTCP command. | [
"Send",
"a",
"CTCP",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L441-L448 | train | 35,088 |
jaraco/irc | irc/client.py | ServerConnection.kick | def kick(self, channel, nick, comment=""):
"""Send a KICK command."""
self.send_items('KICK', channel, nick, comment and ':' + comment) | python | def kick(self, channel, nick, comment=""):
"""Send a KICK command."""
self.send_items('KICK', channel, nick, comment and ':' + comment) | [
"def",
"kick",
"(",
"self",
",",
"channel",
",",
"nick",
",",
"comment",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'KICK'",
",",
"channel",
",",
"nick",
",",
"comment",
"and",
"':'",
"+",
"comment",
")"
] | Send a KICK command. | [
"Send",
"a",
"KICK",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L501-L503 | train | 35,089 |
jaraco/irc | irc/client.py | ServerConnection.list | def list(self, channels=None, server=""):
"""Send a LIST command."""
self.send_items('LIST', ','.join(always_iterable(channels)), server) | python | def list(self, channels=None, server=""):
"""Send a LIST command."""
self.send_items('LIST', ','.join(always_iterable(channels)), server) | [
"def",
"list",
"(",
"self",
",",
"channels",
"=",
"None",
",",
"server",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'LIST'",
",",
"','",
".",
"join",
"(",
"always_iterable",
"(",
"channels",
")",
")",
",",
"server",
")"
] | Send a LIST command. | [
"Send",
"a",
"LIST",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L509-L511 | train | 35,090 |
jaraco/irc | irc/client.py | ServerConnection.part | def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | python | def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | [
"def",
"part",
"(",
"self",
",",
"channels",
",",
"message",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'PART'",
",",
"','",
".",
"join",
"(",
"always_iterable",
"(",
"channels",
")",
")",
",",
"message",
")"
] | Send a PART command. | [
"Send",
"a",
"PART",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L542-L544 | train | 35,091 |
jaraco/irc | irc/client.py | ServerConnection.privmsg_many | def privmsg_many(self, targets, text):
"""Send a PRIVMSG command to multiple targets."""
target = ','.join(targets)
return self.privmsg(target, text) | python | def privmsg_many(self, targets, text):
"""Send a PRIVMSG command to multiple targets."""
target = ','.join(targets)
return self.privmsg(target, text) | [
"def",
"privmsg_many",
"(",
"self",
",",
"targets",
",",
"text",
")",
":",
"target",
"=",
"','",
".",
"join",
"(",
"targets",
")",
"return",
"self",
".",
"privmsg",
"(",
"target",
",",
"text",
")"
] | Send a PRIVMSG command to multiple targets. | [
"Send",
"a",
"PRIVMSG",
"command",
"to",
"multiple",
"targets",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L562-L565 | train | 35,092 |
jaraco/irc | irc/client.py | ServerConnection.user | def user(self, username, realname):
"""Send a USER command."""
cmd = 'USER {username} 0 * :{realname}'.format(**locals())
self.send_raw(cmd) | python | def user(self, username, realname):
"""Send a USER command."""
cmd = 'USER {username} 0 * :{realname}'.format(**locals())
self.send_raw(cmd) | [
"def",
"user",
"(",
"self",
",",
"username",
",",
"realname",
")",
":",
"cmd",
"=",
"'USER {username} 0 * :{realname}'",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"self",
".",
"send_raw",
"(",
"cmd",
")"
] | Send a USER command. | [
"Send",
"a",
"USER",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L628-L631 | train | 35,093 |
jaraco/irc | irc/client.py | ServerConnection.whowas | def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
self.send_items('WHOWAS', nick, max, server) | python | def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
self.send_items('WHOWAS', nick, max, server) | [
"def",
"whowas",
"(",
"self",
",",
"nick",
",",
"max",
"=",
"\"\"",
",",
"server",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'WHOWAS'",
",",
"nick",
",",
"max",
",",
"server",
")"
] | Send a WHOWAS command. | [
"Send",
"a",
"WHOWAS",
"command",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L657-L659 | train | 35,094 |
jaraco/irc | irc/client.py | ServerConnection.set_keepalive | def set_keepalive(self, interval):
"""
Set a keepalive to occur every ``interval`` on this connection.
"""
pinger = functools.partial(self.ping, 'keep-alive')
self.reactor.scheduler.execute_every(period=interval, func=pinger) | python | def set_keepalive(self, interval):
"""
Set a keepalive to occur every ``interval`` on this connection.
"""
pinger = functools.partial(self.ping, 'keep-alive')
self.reactor.scheduler.execute_every(period=interval, func=pinger) | [
"def",
"set_keepalive",
"(",
"self",
",",
"interval",
")",
":",
"pinger",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"ping",
",",
"'keep-alive'",
")",
"self",
".",
"reactor",
".",
"scheduler",
".",
"execute_every",
"(",
"period",
"=",
"interval",
... | Set a keepalive to occur every ``interval`` on this connection. | [
"Set",
"a",
"keepalive",
"to",
"occur",
"every",
"interval",
"on",
"this",
"connection",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L668-L673 | train | 35,095 |
jaraco/irc | irc/client.py | Reactor.server | def server(self):
"""Creates and returns a ServerConnection object."""
conn = self.connection_class(self)
with self.mutex:
self.connections.append(conn)
return conn | python | def server(self):
"""Creates and returns a ServerConnection object."""
conn = self.connection_class(self)
with self.mutex:
self.connections.append(conn)
return conn | [
"def",
"server",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"connection_class",
"(",
"self",
")",
"with",
"self",
".",
"mutex",
":",
"self",
".",
"connections",
".",
"append",
"(",
"conn",
")",
"return",
"conn"
] | Creates and returns a ServerConnection object. | [
"Creates",
"and",
"returns",
"a",
"ServerConnection",
"object",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L766-L772 | train | 35,096 |
jaraco/irc | irc/client.py | Reactor.process_data | def process_data(self, sockets):
"""Called when there is more data to read on connection sockets.
Arguments:
sockets -- A list of socket objects.
See documentation for Reactor.__init__.
"""
with self.mutex:
log.log(logging.DEBUG - 2, "process_data()")
for sock, conn in itertools.product(sockets, self.connections):
if sock == conn.socket:
conn.process_data() | python | def process_data(self, sockets):
"""Called when there is more data to read on connection sockets.
Arguments:
sockets -- A list of socket objects.
See documentation for Reactor.__init__.
"""
with self.mutex:
log.log(logging.DEBUG - 2, "process_data()")
for sock, conn in itertools.product(sockets, self.connections):
if sock == conn.socket:
conn.process_data() | [
"def",
"process_data",
"(",
"self",
",",
"sockets",
")",
":",
"with",
"self",
".",
"mutex",
":",
"log",
".",
"log",
"(",
"logging",
".",
"DEBUG",
"-",
"2",
",",
"\"process_data()\"",
")",
"for",
"sock",
",",
"conn",
"in",
"itertools",
".",
"product",
... | Called when there is more data to read on connection sockets.
Arguments:
sockets -- A list of socket objects.
See documentation for Reactor.__init__. | [
"Called",
"when",
"there",
"is",
"more",
"data",
"to",
"read",
"on",
"connection",
"sockets",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L774-L787 | train | 35,097 |
jaraco/irc | irc/client.py | Reactor.process_once | def process_once(self, timeout=0):
"""Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
incoming data, if there are any. If that seems boring, look
at the process_forever method.
"""
log.log(logging.DEBUG - 2, "process_once()")
sockets = self.sockets
if sockets:
in_, out, err = select.select(sockets, [], [], timeout)
self.process_data(in_)
else:
time.sleep(timeout)
self.process_timeout() | python | def process_once(self, timeout=0):
"""Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
incoming data, if there are any. If that seems boring, look
at the process_forever method.
"""
log.log(logging.DEBUG - 2, "process_once()")
sockets = self.sockets
if sockets:
in_, out, err = select.select(sockets, [], [], timeout)
self.process_data(in_)
else:
time.sleep(timeout)
self.process_timeout() | [
"def",
"process_once",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"log",
".",
"log",
"(",
"logging",
".",
"DEBUG",
"-",
"2",
",",
"\"process_once()\"",
")",
"sockets",
"=",
"self",
".",
"sockets",
"if",
"sockets",
":",
"in_",
",",
"out",
",",
... | Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
incoming data, if there are any. If that seems boring, look
at the process_forever method. | [
"Process",
"data",
"from",
"connections",
"once",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L807-L826 | train | 35,098 |
jaraco/irc | irc/client.py | Reactor.disconnect_all | def disconnect_all(self, message=""):
"""Disconnects all connections."""
with self.mutex:
for conn in self.connections:
conn.disconnect(message) | python | def disconnect_all(self, message=""):
"""Disconnects all connections."""
with self.mutex:
for conn in self.connections:
conn.disconnect(message) | [
"def",
"disconnect_all",
"(",
"self",
",",
"message",
"=",
"\"\"",
")",
":",
"with",
"self",
".",
"mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"conn",
".",
"disconnect",
"(",
"message",
")"
] | Disconnects all connections. | [
"Disconnects",
"all",
"connections",
"."
] | 571c1f448d5d5bb92bbe2605c33148bf6e698413 | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L844-L848 | train | 35,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.