id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
231,100 | ultrabug/py3status | py3status/module.py | Module.add_udev_trigger | def add_udev_trigger(self, trigger_action, subsystem):
"""
Subscribe to the requested udev subsystem and apply the given action.
"""
if self._py3_wrapper.udev_monitor.subscribe(self, trigger_action, subsystem):
if trigger_action == "refresh_and_freeze":
# FIXME: we may want to disable refresh instead of using cache_timeout
self.module_class.cache_timeout = PY3_CACHE_FOREVER | python | def add_udev_trigger(self, trigger_action, subsystem):
if self._py3_wrapper.udev_monitor.subscribe(self, trigger_action, subsystem):
if trigger_action == "refresh_and_freeze":
# FIXME: we may want to disable refresh instead of using cache_timeout
self.module_class.cache_timeout = PY3_CACHE_FOREVER | [
"def",
"add_udev_trigger",
"(",
"self",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"self",
".",
"_py3_wrapper",
".",
"udev_monitor",
".",
"subscribe",
"(",
"self",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"trigger_action",
"==",
... | Subscribe to the requested udev subsystem and apply the given action. | [
"Subscribe",
"to",
"the",
"requested",
"udev",
"subsystem",
"and",
"apply",
"the",
"given",
"action",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L1058-L1065 |
231,101 | ultrabug/py3status | py3status/modules/google_calendar.py | Py3status._get_events | def _get_events(self):
"""
Fetches events from the calendar into a list.
Returns: The list of events.
"""
self.last_update = datetime.datetime.now()
time_min = datetime.datetime.utcnow()
time_max = time_min + datetime.timedelta(hours=self.events_within_hours)
events = []
try:
eventsResult = (
self.service.events()
.list(
calendarId="primary",
timeMax=time_max.isoformat() + "Z", # 'Z' indicates UTC time
timeMin=time_min.isoformat() + "Z", # 'Z' indicates UTC time
singleEvents=True,
orderBy="startTime",
)
.execute(num_retries=5)
)
except Exception:
return self.events or events
else:
for event in eventsResult.get("items", []):
# filter out events that we did not accept (default)
# unless we organized them with no attendees
i_organized = event.get("organizer", {}).get("self", False)
has_attendees = event.get("attendees", [])
for attendee in event.get("attendees", []):
if attendee.get("self") is True:
if attendee["responseStatus"] in self.response:
break
else:
# we did not organize the event or we did not accept it
if not i_organized or has_attendees:
continue
# strip and lower case output if needed
for key in ["description", "location", "summary"]:
event[key] = event.get(key, "").strip()
if self.force_lowercase is True:
event[key] = event[key].lower()
# ignore all day events if configured
if event["start"].get("date") is not None:
if self.ignore_all_day_events:
continue
# filter out blacklisted event names
if event["summary"] is not None:
if event["summary"].lower() in map(
lambda e: e.lower(), self.blacklist_events
):
continue
events.append(event)
return events[: self.num_events] | python | def _get_events(self):
self.last_update = datetime.datetime.now()
time_min = datetime.datetime.utcnow()
time_max = time_min + datetime.timedelta(hours=self.events_within_hours)
events = []
try:
eventsResult = (
self.service.events()
.list(
calendarId="primary",
timeMax=time_max.isoformat() + "Z", # 'Z' indicates UTC time
timeMin=time_min.isoformat() + "Z", # 'Z' indicates UTC time
singleEvents=True,
orderBy="startTime",
)
.execute(num_retries=5)
)
except Exception:
return self.events or events
else:
for event in eventsResult.get("items", []):
# filter out events that we did not accept (default)
# unless we organized them with no attendees
i_organized = event.get("organizer", {}).get("self", False)
has_attendees = event.get("attendees", [])
for attendee in event.get("attendees", []):
if attendee.get("self") is True:
if attendee["responseStatus"] in self.response:
break
else:
# we did not organize the event or we did not accept it
if not i_organized or has_attendees:
continue
# strip and lower case output if needed
for key in ["description", "location", "summary"]:
event[key] = event.get(key, "").strip()
if self.force_lowercase is True:
event[key] = event[key].lower()
# ignore all day events if configured
if event["start"].get("date") is not None:
if self.ignore_all_day_events:
continue
# filter out blacklisted event names
if event["summary"] is not None:
if event["summary"].lower() in map(
lambda e: e.lower(), self.blacklist_events
):
continue
events.append(event)
return events[: self.num_events] | [
"def",
"_get_events",
"(",
"self",
")",
":",
"self",
".",
"last_update",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"time_min",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"time_max",
"=",
"time_min",
"+",
"datetime",
".",
"... | Fetches events from the calendar into a list.
Returns: The list of events. | [
"Fetches",
"events",
"from",
"the",
"calendar",
"into",
"a",
"list",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L256-L316 |
231,102 | ultrabug/py3status | py3status/modules/google_calendar.py | Py3status._check_warn_threshold | def _check_warn_threshold(self, time_to, event_dict):
"""
Checks if the time until an event starts is less than or equal to the
warn_threshold. If True, issue a warning with self.py3.notify_user.
"""
if time_to["total_minutes"] <= self.warn_threshold:
warn_message = self.py3.safe_format(self.format_notification, event_dict)
self.py3.notify_user(warn_message, "warning", self.warn_timeout) | python | def _check_warn_threshold(self, time_to, event_dict):
if time_to["total_minutes"] <= self.warn_threshold:
warn_message = self.py3.safe_format(self.format_notification, event_dict)
self.py3.notify_user(warn_message, "warning", self.warn_timeout) | [
"def",
"_check_warn_threshold",
"(",
"self",
",",
"time_to",
",",
"event_dict",
")",
":",
"if",
"time_to",
"[",
"\"total_minutes\"",
"]",
"<=",
"self",
".",
"warn_threshold",
":",
"warn_message",
"=",
"self",
".",
"py3",
".",
"safe_format",
"(",
"self",
".",... | Checks if the time until an event starts is less than or equal to the
warn_threshold. If True, issue a warning with self.py3.notify_user. | [
"Checks",
"if",
"the",
"time",
"until",
"an",
"event",
"starts",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"warn_threshold",
".",
"If",
"True",
"issue",
"a",
"warning",
"with",
"self",
".",
"py3",
".",
"notify_user",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L318-L325 |
231,103 | ultrabug/py3status | py3status/modules/google_calendar.py | Py3status._build_response | def _build_response(self):
"""
Builds the composite reponse to be output by the module by looping
through all events and formatting the necessary strings.
Returns: A composite containing the individual response for each event.
"""
responses = []
self.event_urls = []
for index, event in enumerate(self.events):
self.py3.threshold_get_color(index + 1, "event")
self.py3.threshold_get_color(index + 1, "time")
event_dict = {}
event_dict["summary"] = event.get("summary")
event_dict["location"] = event.get("location")
event_dict["description"] = event.get("description")
self.event_urls.append(event["htmlLink"])
if event["start"].get("date") is not None:
start_dt = self._gstr_to_date(event["start"].get("date"))
end_dt = self._gstr_to_date(event["end"].get("date"))
else:
start_dt = self._gstr_to_datetime(event["start"].get("dateTime"))
end_dt = self._gstr_to_datetime(event["end"].get("dateTime"))
if end_dt < datetime.datetime.now(tzlocal()):
continue
event_dict["start_time"] = self._datetime_to_str(start_dt, self.format_time)
event_dict["end_time"] = self._datetime_to_str(end_dt, self.format_time)
event_dict["start_date"] = self._datetime_to_str(start_dt, self.format_date)
event_dict["end_date"] = self._datetime_to_str(end_dt, self.format_date)
time_delta = self._delta_time(start_dt)
if time_delta["days"] < 0:
time_delta = self._delta_time(end_dt)
is_current = True
else:
is_current = False
event_dict["format_timer"] = self._format_timedelta(
index, time_delta, is_current
)
if self.warn_threshold > 0:
self._check_warn_threshold(time_delta, event_dict)
event_formatted = self.py3.safe_format(
self.format_event,
{
"is_toggled": self.button_states[index],
"summary": event_dict["summary"],
"location": event_dict["location"],
"description": event_dict["description"],
"start_time": event_dict["start_time"],
"end_time": event_dict["end_time"],
"start_date": event_dict["start_date"],
"end_date": event_dict["end_date"],
"format_timer": event_dict["format_timer"],
},
)
self.py3.composite_update(event_formatted, {"index": index})
responses.append(event_formatted)
self.no_update = False
format_separator = self.py3.safe_format(self.format_separator)
self.py3.composite_update(format_separator, {"index": "sep"})
responses = self.py3.composite_join(format_separator, responses)
return {"events": responses} | python | def _build_response(self):
responses = []
self.event_urls = []
for index, event in enumerate(self.events):
self.py3.threshold_get_color(index + 1, "event")
self.py3.threshold_get_color(index + 1, "time")
event_dict = {}
event_dict["summary"] = event.get("summary")
event_dict["location"] = event.get("location")
event_dict["description"] = event.get("description")
self.event_urls.append(event["htmlLink"])
if event["start"].get("date") is not None:
start_dt = self._gstr_to_date(event["start"].get("date"))
end_dt = self._gstr_to_date(event["end"].get("date"))
else:
start_dt = self._gstr_to_datetime(event["start"].get("dateTime"))
end_dt = self._gstr_to_datetime(event["end"].get("dateTime"))
if end_dt < datetime.datetime.now(tzlocal()):
continue
event_dict["start_time"] = self._datetime_to_str(start_dt, self.format_time)
event_dict["end_time"] = self._datetime_to_str(end_dt, self.format_time)
event_dict["start_date"] = self._datetime_to_str(start_dt, self.format_date)
event_dict["end_date"] = self._datetime_to_str(end_dt, self.format_date)
time_delta = self._delta_time(start_dt)
if time_delta["days"] < 0:
time_delta = self._delta_time(end_dt)
is_current = True
else:
is_current = False
event_dict["format_timer"] = self._format_timedelta(
index, time_delta, is_current
)
if self.warn_threshold > 0:
self._check_warn_threshold(time_delta, event_dict)
event_formatted = self.py3.safe_format(
self.format_event,
{
"is_toggled": self.button_states[index],
"summary": event_dict["summary"],
"location": event_dict["location"],
"description": event_dict["description"],
"start_time": event_dict["start_time"],
"end_time": event_dict["end_time"],
"start_date": event_dict["start_date"],
"end_date": event_dict["end_date"],
"format_timer": event_dict["format_timer"],
},
)
self.py3.composite_update(event_formatted, {"index": index})
responses.append(event_formatted)
self.no_update = False
format_separator = self.py3.safe_format(self.format_separator)
self.py3.composite_update(format_separator, {"index": "sep"})
responses = self.py3.composite_join(format_separator, responses)
return {"events": responses} | [
"def",
"_build_response",
"(",
"self",
")",
":",
"responses",
"=",
"[",
"]",
"self",
".",
"event_urls",
"=",
"[",
"]",
"for",
"index",
",",
"event",
"in",
"enumerate",
"(",
"self",
".",
"events",
")",
":",
"self",
".",
"py3",
".",
"threshold_get_color"... | Builds the composite reponse to be output by the module by looping
through all events and formatting the necessary strings.
Returns: A composite containing the individual response for each event. | [
"Builds",
"the",
"composite",
"reponse",
"to",
"be",
"output",
"by",
"the",
"module",
"by",
"looping",
"through",
"all",
"events",
"and",
"formatting",
"the",
"necessary",
"strings",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L381-L456 |
231,104 | ultrabug/py3status | py3status/modules/google_calendar.py | Py3status.google_calendar | def google_calendar(self):
"""
The method that outputs the response.
First, we check credential authorization. If no authorization, we
display an error message, and try authorizing again in 5 seconds.
Otherwise, we fetch the events, build the response, and output
the resulting composite.
"""
composite = {}
if not self.is_authorized:
cached_until = 0
self.is_authorized = self._authorize_credentials()
else:
if not self.no_update:
self.events = self._get_events()
composite = self._build_response()
cached_until = self.cache_timeout
return {
"cached_until": self.py3.time_in(cached_until),
"composite": self.py3.safe_format(self.format, composite),
} | python | def google_calendar(self):
composite = {}
if not self.is_authorized:
cached_until = 0
self.is_authorized = self._authorize_credentials()
else:
if not self.no_update:
self.events = self._get_events()
composite = self._build_response()
cached_until = self.cache_timeout
return {
"cached_until": self.py3.time_in(cached_until),
"composite": self.py3.safe_format(self.format, composite),
} | [
"def",
"google_calendar",
"(",
"self",
")",
":",
"composite",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"is_authorized",
":",
"cached_until",
"=",
"0",
"self",
".",
"is_authorized",
"=",
"self",
".",
"_authorize_credentials",
"(",
")",
"else",
":",
"if",
... | The method that outputs the response.
First, we check credential authorization. If no authorization, we
display an error message, and try authorizing again in 5 seconds.
Otherwise, we fetch the events, build the response, and output
the resulting composite. | [
"The",
"method",
"that",
"outputs",
"the",
"response",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L458-L483 |
231,105 | ultrabug/py3status | py3status/command.py | parse_list_or_docstring | def parse_list_or_docstring(options, sps):
"""
Handle py3-cmd list and docstring options.
"""
import py3status.docstrings as docstrings
# HARDCODE: make include path to search for user modules
home_path = os.path.expanduser("~")
xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
options.include_paths = [
"{}/py3status/modules".format(xdg_home_path),
"{}/i3status/py3status".format(xdg_home_path),
"{}/i3/py3status".format(xdg_home_path),
"{}/.i3/py3status".format(home_path),
]
include_paths = []
for path in options.include_paths:
path = os.path.abspath(path)
if os.path.isdir(path) and os.listdir(path):
include_paths.append(path)
options.include_paths = include_paths
# init
config = vars(options)
modules = [x.rsplit(".py", 1)[0] for x in config["module"]]
# list module names and details
if config["command"] == "list":
tests = [not config[x] for x in ["all", "user", "core"]]
if all([not modules] + tests):
msg = "missing positional or optional arguments"
sps["list"].error(msg)
docstrings.show_modules(config, modules)
# docstring formatting and checking
elif config["command"] == "docstring":
if config["check"]:
docstrings.check_docstrings(False, config, modules)
elif config["diff"]:
docstrings.check_docstrings(True, config, None)
elif config["update"]:
if not modules:
msg = "missing positional arguments or `modules`"
sps["docstring"].error(msg)
if "modules" in modules:
docstrings.update_docstrings()
else:
docstrings.update_readme_for_modules(modules)
else:
msg = "missing positional or optional arguments"
sps["docstring"].error(msg) | python | def parse_list_or_docstring(options, sps):
import py3status.docstrings as docstrings
# HARDCODE: make include path to search for user modules
home_path = os.path.expanduser("~")
xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
options.include_paths = [
"{}/py3status/modules".format(xdg_home_path),
"{}/i3status/py3status".format(xdg_home_path),
"{}/i3/py3status".format(xdg_home_path),
"{}/.i3/py3status".format(home_path),
]
include_paths = []
for path in options.include_paths:
path = os.path.abspath(path)
if os.path.isdir(path) and os.listdir(path):
include_paths.append(path)
options.include_paths = include_paths
# init
config = vars(options)
modules = [x.rsplit(".py", 1)[0] for x in config["module"]]
# list module names and details
if config["command"] == "list":
tests = [not config[x] for x in ["all", "user", "core"]]
if all([not modules] + tests):
msg = "missing positional or optional arguments"
sps["list"].error(msg)
docstrings.show_modules(config, modules)
# docstring formatting and checking
elif config["command"] == "docstring":
if config["check"]:
docstrings.check_docstrings(False, config, modules)
elif config["diff"]:
docstrings.check_docstrings(True, config, None)
elif config["update"]:
if not modules:
msg = "missing positional arguments or `modules`"
sps["docstring"].error(msg)
if "modules" in modules:
docstrings.update_docstrings()
else:
docstrings.update_readme_for_modules(modules)
else:
msg = "missing positional or optional arguments"
sps["docstring"].error(msg) | [
"def",
"parse_list_or_docstring",
"(",
"options",
",",
"sps",
")",
":",
"import",
"py3status",
".",
"docstrings",
"as",
"docstrings",
"# HARDCODE: make include path to search for user modules",
"home_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",... | Handle py3-cmd list and docstring options. | [
"Handle",
"py3",
"-",
"cmd",
"list",
"and",
"docstring",
"options",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L458-L508 |
231,106 | ultrabug/py3status | py3status/command.py | send_command | def send_command():
"""
Run a remote command. This is called via py3-cmd utility.
We look for any uds sockets with the correct name prefix and send our
command to all that we find. This allows us to communicate with multiple
py3status instances.
"""
def verbose(msg):
"""
print output if verbose is set.
"""
if options.verbose:
print(msg)
options = command_parser()
msg = json.dumps(vars(options)).encode("utf-8")
if len(msg) > MAX_SIZE:
verbose("Message length too long, max length (%s)" % MAX_SIZE)
# find all likely socket addresses
uds_list = glob.glob("{}.[0-9]*".format(SERVER_ADDRESS))
verbose('message "%s"' % msg)
for uds in uds_list:
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
verbose("connecting to %s" % uds)
try:
sock.connect(uds)
except socket.error:
# this is a stale socket so delete it
verbose("stale socket deleting")
try:
os.unlink(uds)
except OSError:
pass
continue
try:
# Send data
verbose("sending")
sock.sendall(msg)
finally:
verbose("closing socket")
sock.close() | python | def send_command():
def verbose(msg):
"""
print output if verbose is set.
"""
if options.verbose:
print(msg)
options = command_parser()
msg = json.dumps(vars(options)).encode("utf-8")
if len(msg) > MAX_SIZE:
verbose("Message length too long, max length (%s)" % MAX_SIZE)
# find all likely socket addresses
uds_list = glob.glob("{}.[0-9]*".format(SERVER_ADDRESS))
verbose('message "%s"' % msg)
for uds in uds_list:
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
verbose("connecting to %s" % uds)
try:
sock.connect(uds)
except socket.error:
# this is a stale socket so delete it
verbose("stale socket deleting")
try:
os.unlink(uds)
except OSError:
pass
continue
try:
# Send data
verbose("sending")
sock.sendall(msg)
finally:
verbose("closing socket")
sock.close() | [
"def",
"send_command",
"(",
")",
":",
"def",
"verbose",
"(",
"msg",
")",
":",
"\"\"\"\n print output if verbose is set.\n \"\"\"",
"if",
"options",
".",
"verbose",
":",
"print",
"(",
"msg",
")",
"options",
"=",
"command_parser",
"(",
")",
"msg",
"=... | Run a remote command. This is called via py3-cmd utility.
We look for any uds sockets with the correct name prefix and send our
command to all that we find. This allows us to communicate with multiple
py3status instances. | [
"Run",
"a",
"remote",
"command",
".",
"This",
"is",
"called",
"via",
"py3",
"-",
"cmd",
"utility",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L511-L558 |
231,107 | ultrabug/py3status | py3status/command.py | CommandRunner.run_command | def run_command(self, data):
"""
check the given command and send to the correct dispatcher
"""
command = data.get("command")
if self.debug:
self.py3_wrapper.log("Running remote command %s" % command)
if command == "refresh":
self.refresh(data)
elif command == "refresh_all":
self.py3_wrapper.refresh_modules()
elif command == "click":
self.click(data) | python | def run_command(self, data):
command = data.get("command")
if self.debug:
self.py3_wrapper.log("Running remote command %s" % command)
if command == "refresh":
self.refresh(data)
elif command == "refresh_all":
self.py3_wrapper.refresh_modules()
elif command == "click":
self.click(data) | [
"def",
"run_command",
"(",
"self",
",",
"data",
")",
":",
"command",
"=",
"data",
".",
"get",
"(",
"\"command\"",
")",
"if",
"self",
".",
"debug",
":",
"self",
".",
"py3_wrapper",
".",
"log",
"(",
"\"Running remote command %s\"",
"%",
"command",
")",
"if... | check the given command and send to the correct dispatcher | [
"check",
"the",
"given",
"command",
"and",
"send",
"to",
"the",
"correct",
"dispatcher"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L205-L217 |
231,108 | ultrabug/py3status | py3status/command.py | CommandServer.kill | def kill(self):
"""
Remove the socket as it is no longer needed.
"""
try:
os.unlink(self.server_address)
except OSError:
if os.path.exists(self.server_address):
raise | python | def kill(self):
try:
os.unlink(self.server_address)
except OSError:
if os.path.exists(self.server_address):
raise | [
"def",
"kill",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"server_address",
")",
"except",
"OSError",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"server_address",
")",
":",
"raise"
] | Remove the socket as it is no longer needed. | [
"Remove",
"the",
"socket",
"as",
"it",
"is",
"no",
"longer",
"needed",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L254-L262 |
231,109 | ultrabug/py3status | py3status/command.py | CommandServer.run | def run(self):
"""
Main thread listen to socket and send any commands to the
CommandRunner.
"""
while True:
try:
data = None
# Wait for a connection
if self.debug:
self.py3_wrapper.log("waiting for a connection")
connection, client_address = self.sock.accept()
try:
if self.debug:
self.py3_wrapper.log("connection from")
data = connection.recv(MAX_SIZE)
if data:
data = json.loads(data.decode("utf-8"))
if self.debug:
self.py3_wrapper.log(u"received %s" % data)
self.command_runner.run_command(data)
finally:
# Clean up the connection
connection.close()
except Exception:
if data:
self.py3_wrapper.log("Command error")
self.py3_wrapper.log(data)
self.py3_wrapper.report_exception("command failed") | python | def run(self):
while True:
try:
data = None
# Wait for a connection
if self.debug:
self.py3_wrapper.log("waiting for a connection")
connection, client_address = self.sock.accept()
try:
if self.debug:
self.py3_wrapper.log("connection from")
data = connection.recv(MAX_SIZE)
if data:
data = json.loads(data.decode("utf-8"))
if self.debug:
self.py3_wrapper.log(u"received %s" % data)
self.command_runner.run_command(data)
finally:
# Clean up the connection
connection.close()
except Exception:
if data:
self.py3_wrapper.log("Command error")
self.py3_wrapper.log(data)
self.py3_wrapper.report_exception("command failed") | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"data",
"=",
"None",
"# Wait for a connection",
"if",
"self",
".",
"debug",
":",
"self",
".",
"py3_wrapper",
".",
"log",
"(",
"\"waiting for a connection\"",
")",
"connection",
",",
"cl... | Main thread listen to socket and send any commands to the
CommandRunner. | [
"Main",
"thread",
"listen",
"to",
"socket",
"and",
"send",
"any",
"commands",
"to",
"the",
"CommandRunner",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L264-L294 |
231,110 | ultrabug/py3status | py3status/modules/player_control.py | Py3status._change_volume | def _change_volume(self, increase):
"""Change volume using amixer
"""
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | python | def _change_volume(self, increase):
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | [
"def",
"_change_volume",
"(",
"self",
",",
"increase",
")",
":",
"sign",
"=",
"\"+\"",
"if",
"increase",
"else",
"\"-\"",
"delta",
"=",
"\"%d%%%s\"",
"%",
"(",
"self",
".",
"volume_tick",
",",
"sign",
")",
"self",
".",
"_run",
"(",
"[",
"\"amixer\"",
"... | Change volume using amixer | [
"Change",
"volume",
"using",
"amixer"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/player_control.py#L137-L142 |
231,111 | ultrabug/py3status | py3status/modules/player_control.py | Py3status._detect_running_player | def _detect_running_player(self):
"""Detect running player process, if any
"""
supported_players = self.supported_players.split(",")
running_players = []
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
fn = os.path.join("/proc", pid, "comm")
try:
with open(fn, "rb") as f:
player_name = f.read().decode().rstrip()
except: # noqa e722
# (IOError, FileNotFoundError): # (assumed py2, assumed py3)
continue
if player_name in supported_players:
running_players.append(player_name)
# Pick which player to use based on the order in self.supported_players
for player_name in supported_players:
if player_name in running_players:
if self.debug:
self.py3.log("found player: %s" % player_name)
# those players need the dbus module
if player_name in ("vlc") and not dbus_available:
self.py3.log("%s requires the dbus python module" % player_name)
return None
return player_name
return None | python | def _detect_running_player(self):
supported_players = self.supported_players.split(",")
running_players = []
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
fn = os.path.join("/proc", pid, "comm")
try:
with open(fn, "rb") as f:
player_name = f.read().decode().rstrip()
except: # noqa e722
# (IOError, FileNotFoundError): # (assumed py2, assumed py3)
continue
if player_name in supported_players:
running_players.append(player_name)
# Pick which player to use based on the order in self.supported_players
for player_name in supported_players:
if player_name in running_players:
if self.debug:
self.py3.log("found player: %s" % player_name)
# those players need the dbus module
if player_name in ("vlc") and not dbus_available:
self.py3.log("%s requires the dbus python module" % player_name)
return None
return player_name
return None | [
"def",
"_detect_running_player",
"(",
"self",
")",
":",
"supported_players",
"=",
"self",
".",
"supported_players",
".",
"split",
"(",
"\",\"",
")",
"running_players",
"=",
"[",
"]",
"for",
"pid",
"in",
"os",
".",
"listdir",
"(",
"\"/proc\"",
")",
":",
"if... | Detect running player process, if any | [
"Detect",
"running",
"player",
"process",
"if",
"any"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/player_control.py#L144-L177 |
231,112 | ultrabug/py3status | py3status/modules/rainbow.py | Py3status._set_cycle_time | def _set_cycle_time(self):
"""
Set next cycle update time synced to nearest second or 0.1 of second.
"""
now = time()
try:
cycle_time = now - self._cycle_time
if cycle_time < 0:
cycle_time = 0
except AttributeError:
cycle_time = 0
cycle_time += self.cycle_time
if cycle_time == int(cycle_time):
self._cycle_time = math.ceil(now + cycle_time)
else:
self._cycle_time = math.ceil((now + cycle_time) * 10) / 10
self._cycle_time = now + self.cycle_time | python | def _set_cycle_time(self):
now = time()
try:
cycle_time = now - self._cycle_time
if cycle_time < 0:
cycle_time = 0
except AttributeError:
cycle_time = 0
cycle_time += self.cycle_time
if cycle_time == int(cycle_time):
self._cycle_time = math.ceil(now + cycle_time)
else:
self._cycle_time = math.ceil((now + cycle_time) * 10) / 10
self._cycle_time = now + self.cycle_time | [
"def",
"_set_cycle_time",
"(",
"self",
")",
":",
"now",
"=",
"time",
"(",
")",
"try",
":",
"cycle_time",
"=",
"now",
"-",
"self",
".",
"_cycle_time",
"if",
"cycle_time",
"<",
"0",
":",
"cycle_time",
"=",
"0",
"except",
"AttributeError",
":",
"cycle_time"... | Set next cycle update time synced to nearest second or 0.1 of second. | [
"Set",
"next",
"cycle",
"update",
"time",
"synced",
"to",
"nearest",
"second",
"or",
"0",
".",
"1",
"of",
"second",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/rainbow.py#L156-L172 |
231,113 | ultrabug/py3status | py3status/modules/rainbow.py | Py3status._get_current_output | def _get_current_output(self):
"""
Get child modules output.
"""
output = []
for item in self.items:
out = self.py3.get_output(item)
if out and "separator" not in out[-1]:
out[-1]["separator"] = True
output += out
return output | python | def _get_current_output(self):
output = []
for item in self.items:
out = self.py3.get_output(item)
if out and "separator" not in out[-1]:
out[-1]["separator"] = True
output += out
return output | [
"def",
"_get_current_output",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"items",
":",
"out",
"=",
"self",
".",
"py3",
".",
"get_output",
"(",
"item",
")",
"if",
"out",
"and",
"\"separator\"",
"not",
"in",
"out"... | Get child modules output. | [
"Get",
"child",
"modules",
"output",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/rainbow.py#L174-L184 |
231,114 | ultrabug/py3status | py3status/modules/rainbow.py | Py3status.rainbow | def rainbow(self):
"""
Make a rainbow!
"""
if not self.items:
return {"full_text": "", "cached_until": self.py3.CACHE_FOREVER}
if time() >= self._cycle_time - (self.cycle_time / 10):
self.active_color = (self.active_color + 1) % len(self.colors)
self._set_cycle_time()
color = self.colors[self.active_color]
content = self._get_current_output()
output = []
if content:
step = len(self.colors) // len(content)
for index, item in enumerate(content):
if self.multi_color:
offset = (self.active_color + (index * step)) % len(self.colors)
color = self.colors[offset]
obj = item.copy()
if self.force or not obj.get("color"):
obj["color"] = color
output.append(obj)
composites = {"output": self.py3.composite_create(output)}
rainbow = self.py3.safe_format(self.format, composites)
return {"cached_until": self._cycle_time, "full_text": rainbow} | python | def rainbow(self):
if not self.items:
return {"full_text": "", "cached_until": self.py3.CACHE_FOREVER}
if time() >= self._cycle_time - (self.cycle_time / 10):
self.active_color = (self.active_color + 1) % len(self.colors)
self._set_cycle_time()
color = self.colors[self.active_color]
content = self._get_current_output()
output = []
if content:
step = len(self.colors) // len(content)
for index, item in enumerate(content):
if self.multi_color:
offset = (self.active_color + (index * step)) % len(self.colors)
color = self.colors[offset]
obj = item.copy()
if self.force or not obj.get("color"):
obj["color"] = color
output.append(obj)
composites = {"output": self.py3.composite_create(output)}
rainbow = self.py3.safe_format(self.format, composites)
return {"cached_until": self._cycle_time, "full_text": rainbow} | [
"def",
"rainbow",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"items",
":",
"return",
"{",
"\"full_text\"",
":",
"\"\"",
",",
"\"cached_until\"",
":",
"self",
".",
"py3",
".",
"CACHE_FOREVER",
"}",
"if",
"time",
"(",
")",
">=",
"self",
".",
"_cy... | Make a rainbow! | [
"Make",
"a",
"rainbow!"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/rainbow.py#L186-L215 |
231,115 | ultrabug/py3status | py3status/screenshots.py | get_color_for_name | def get_color_for_name(module_name):
"""
Create a custom color for a given string.
This allows the screenshots to each have a unique color but also for that
color to be consistent.
"""
# all screenshots of the same module should be a uniform color
module_name = module_name.split("-")[0]
saturation = 0.5
value = 243.2
try:
# we must be bytes to allow the md5 hash to be calculated
module_name = module_name.encode("utf-8")
except AttributeError:
pass
hue = int(md5(module_name).hexdigest(), 16) / 16 ** 32
hue *= 6
hue += 3.708
r, g, b = (
(
value,
value - value * saturation * abs(1 - hue % 2),
value - value * saturation,
)
* 3
)[5 ** int(hue) // 3 % 3 :: int(hue) % 2 + 1][:3]
return "#" + "%02x" * 3 % (int(r), int(g), int(b)) | python | def get_color_for_name(module_name):
# all screenshots of the same module should be a uniform color
module_name = module_name.split("-")[0]
saturation = 0.5
value = 243.2
try:
# we must be bytes to allow the md5 hash to be calculated
module_name = module_name.encode("utf-8")
except AttributeError:
pass
hue = int(md5(module_name).hexdigest(), 16) / 16 ** 32
hue *= 6
hue += 3.708
r, g, b = (
(
value,
value - value * saturation * abs(1 - hue % 2),
value - value * saturation,
)
* 3
)[5 ** int(hue) // 3 % 3 :: int(hue) % 2 + 1][:3]
return "#" + "%02x" * 3 % (int(r), int(g), int(b)) | [
"def",
"get_color_for_name",
"(",
"module_name",
")",
":",
"# all screenshots of the same module should be a uniform color",
"module_name",
"=",
"module_name",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"saturation",
"=",
"0.5",
"value",
"=",
"243.2",
"try",
":... | Create a custom color for a given string.
This allows the screenshots to each have a unique color but also for that
color to be consistent. | [
"Create",
"a",
"custom",
"color",
"for",
"a",
"given",
"string",
".",
"This",
"allows",
"the",
"screenshots",
"to",
"each",
"have",
"a",
"unique",
"color",
"but",
"also",
"for",
"that",
"color",
"to",
"be",
"consistent",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/screenshots.py#L63-L90 |
231,116 | ultrabug/py3status | py3status/screenshots.py | contains_bad_glyph | def contains_bad_glyph(glyph_data, data):
"""
Pillow only looks for glyphs in the font used so we need to make sure our
font has the glygh. Although we could substitute a glyph from another font
eg symbola but this adds more complexity and is of limited value.
"""
def check_glyph(char):
for cmap in glyph_data["cmap"].tables:
if cmap.isUnicode():
if char in cmap.cmap:
return True
return False
for part in data:
text = part.get("full_text", "")
try:
# for python 2
text = text.decode("utf8")
except AttributeError:
pass
for char in text:
if not check_glyph(ord(char)):
# we have not found a character in the font
print(u"%s (%s) missing" % (char, ord(char)))
return True
return False | python | def contains_bad_glyph(glyph_data, data):
def check_glyph(char):
for cmap in glyph_data["cmap"].tables:
if cmap.isUnicode():
if char in cmap.cmap:
return True
return False
for part in data:
text = part.get("full_text", "")
try:
# for python 2
text = text.decode("utf8")
except AttributeError:
pass
for char in text:
if not check_glyph(ord(char)):
# we have not found a character in the font
print(u"%s (%s) missing" % (char, ord(char)))
return True
return False | [
"def",
"contains_bad_glyph",
"(",
"glyph_data",
",",
"data",
")",
":",
"def",
"check_glyph",
"(",
"char",
")",
":",
"for",
"cmap",
"in",
"glyph_data",
"[",
"\"cmap\"",
"]",
".",
"tables",
":",
"if",
"cmap",
".",
"isUnicode",
"(",
")",
":",
"if",
"char"... | Pillow only looks for glyphs in the font used so we need to make sure our
font has the glygh. Although we could substitute a glyph from another font
eg symbola but this adds more complexity and is of limited value. | [
"Pillow",
"only",
"looks",
"for",
"glyphs",
"in",
"the",
"font",
"used",
"so",
"we",
"need",
"to",
"make",
"sure",
"our",
"font",
"has",
"the",
"glygh",
".",
"Although",
"we",
"could",
"substitute",
"a",
"glyph",
"from",
"another",
"font",
"eg",
"symbola... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/screenshots.py#L93-L120 |
231,117 | ultrabug/py3status | py3status/screenshots.py | create_screenshot | def create_screenshot(name, data, path, font, is_module):
"""
Create screenshot of py3status output and save to path
"""
desktop_color = get_color_for_name(name)
# if this screenshot is for a module then add modules name etc
if is_module:
data.append(
{"full_text": name.split("-")[0], "color": desktop_color, "separator": True}
)
data.append(
{"full_text": "py3status", "color": COLOR_PY3STATUS, "separator": True}
)
img = Image.new("RGB", (WIDTH, HEIGHT), COLOR_BG)
d = ImageDraw.Draw(img)
# top bar
d.rectangle((0, 0, WIDTH, TOP_BAR_HEIGHT), fill=desktop_color)
x = X_OFFSET
# add text and separators
for part in reversed(data):
text = part.get("full_text")
color = part.get("color", COLOR)
background = part.get("background")
separator = part.get("separator")
urgent = part.get("urgent")
# urgent background
if urgent:
color = COLOR_URGENT
background = COLOR_URGENT_BG
size = font.getsize(text)
if background:
d.rectangle(
(
WIDTH - x - (size[0] // SCALE),
TOP_BAR_HEIGHT + PADDING,
WIDTH - x - 1,
HEIGHT - PADDING,
),
fill=background,
)
x += size[0] // SCALE
txt = Image.new("RGB", size, background or COLOR_BG)
d_text = ImageDraw.Draw(txt)
d_text.text((0, 0), text, font=font, fill=color)
# resize to actual size wanted and add to image
txt = txt.resize((size[0] // SCALE, size[1] // SCALE), Image.ANTIALIAS)
img.paste(txt, (WIDTH - x, TOP_BAR_HEIGHT + PADDING))
if separator:
x += SEP_PADDING_RIGHT
d.line(
(
(WIDTH - x, TOP_BAR_HEIGHT + PADDING),
(WIDTH - x, TOP_BAR_HEIGHT + 1 + PADDING + FONT_SIZE),
),
fill=COLOR_SEP,
width=1,
)
x += SEP_PADDING_LEFT
img.save(os.path.join(path, "%s.png" % name))
print(" %s.png" % name) | python | def create_screenshot(name, data, path, font, is_module):
desktop_color = get_color_for_name(name)
# if this screenshot is for a module then add modules name etc
if is_module:
data.append(
{"full_text": name.split("-")[0], "color": desktop_color, "separator": True}
)
data.append(
{"full_text": "py3status", "color": COLOR_PY3STATUS, "separator": True}
)
img = Image.new("RGB", (WIDTH, HEIGHT), COLOR_BG)
d = ImageDraw.Draw(img)
# top bar
d.rectangle((0, 0, WIDTH, TOP_BAR_HEIGHT), fill=desktop_color)
x = X_OFFSET
# add text and separators
for part in reversed(data):
text = part.get("full_text")
color = part.get("color", COLOR)
background = part.get("background")
separator = part.get("separator")
urgent = part.get("urgent")
# urgent background
if urgent:
color = COLOR_URGENT
background = COLOR_URGENT_BG
size = font.getsize(text)
if background:
d.rectangle(
(
WIDTH - x - (size[0] // SCALE),
TOP_BAR_HEIGHT + PADDING,
WIDTH - x - 1,
HEIGHT - PADDING,
),
fill=background,
)
x += size[0] // SCALE
txt = Image.new("RGB", size, background or COLOR_BG)
d_text = ImageDraw.Draw(txt)
d_text.text((0, 0), text, font=font, fill=color)
# resize to actual size wanted and add to image
txt = txt.resize((size[0] // SCALE, size[1] // SCALE), Image.ANTIALIAS)
img.paste(txt, (WIDTH - x, TOP_BAR_HEIGHT + PADDING))
if separator:
x += SEP_PADDING_RIGHT
d.line(
(
(WIDTH - x, TOP_BAR_HEIGHT + PADDING),
(WIDTH - x, TOP_BAR_HEIGHT + 1 + PADDING + FONT_SIZE),
),
fill=COLOR_SEP,
width=1,
)
x += SEP_PADDING_LEFT
img.save(os.path.join(path, "%s.png" % name))
print(" %s.png" % name) | [
"def",
"create_screenshot",
"(",
"name",
",",
"data",
",",
"path",
",",
"font",
",",
"is_module",
")",
":",
"desktop_color",
"=",
"get_color_for_name",
"(",
"name",
")",
"# if this screenshot is for a module then add modules name etc",
"if",
"is_module",
":",
"data",
... | Create screenshot of py3status output and save to path | [
"Create",
"screenshot",
"of",
"py3status",
"output",
"and",
"save",
"to",
"path"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/screenshots.py#L123-L193 |
231,118 | ultrabug/py3status | py3status/screenshots.py | create_screenshots | def create_screenshots(quiet=False):
"""
create screenshots for all core modules.
The screenshots directory will have all .png files deleted before new shots
are created.
"""
if os.environ.get("READTHEDOCS") == "True":
path = "../doc/screenshots"
else:
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"doc/screenshots",
)
print("Creating screenshots...")
samples = get_samples()
for name, data in sorted(samples.items()):
process(name, path, data) | python | def create_screenshots(quiet=False):
if os.environ.get("READTHEDOCS") == "True":
path = "../doc/screenshots"
else:
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"doc/screenshots",
)
print("Creating screenshots...")
samples = get_samples()
for name, data in sorted(samples.items()):
process(name, path, data) | [
"def",
"create_screenshots",
"(",
"quiet",
"=",
"False",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"READTHEDOCS\"",
")",
"==",
"\"True\"",
":",
"path",
"=",
"\"../doc/screenshots\"",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join"... | create screenshots for all core modules.
The screenshots directory will have all .png files deleted before new shots
are created. | [
"create",
"screenshots",
"for",
"all",
"core",
"modules",
".",
"The",
"screenshots",
"directory",
"will",
"have",
"all",
".",
"png",
"files",
"deleted",
"before",
"new",
"shots",
"are",
"created",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/screenshots.py#L267-L284 |
231,119 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.check_child_friendly | def check_child_friendly(self, name):
"""
Check if a module is a container and so can have children
"""
name = name.split()[0]
if name in self.container_modules:
return
root = os.path.dirname(os.path.realpath(__file__))
module_path = os.path.join(root, "modules")
try:
info = imp.find_module(name, [module_path])
except ImportError:
return
if not info:
return
(file, pathname, description) = info
try:
py_mod = imp.load_module(name, file, pathname, description)
except Exception:
# We cannot load the module! We could error out here but then the
# user gets informed that the problem is with their config. This
# is not correct. Better to say that all is well and then the
# config can get parsed and py3status loads. The error about the
# failing module load is better handled at that point, and will be.
return
try:
container = py_mod.Py3status.Meta.container
except AttributeError:
container = False
# delete the module
del py_mod
if container:
self.container_modules.append(name)
else:
self.error("Module `{}` cannot contain others".format(name)) | python | def check_child_friendly(self, name):
name = name.split()[0]
if name in self.container_modules:
return
root = os.path.dirname(os.path.realpath(__file__))
module_path = os.path.join(root, "modules")
try:
info = imp.find_module(name, [module_path])
except ImportError:
return
if not info:
return
(file, pathname, description) = info
try:
py_mod = imp.load_module(name, file, pathname, description)
except Exception:
# We cannot load the module! We could error out here but then the
# user gets informed that the problem is with their config. This
# is not correct. Better to say that all is well and then the
# config can get parsed and py3status loads. The error about the
# failing module load is better handled at that point, and will be.
return
try:
container = py_mod.Py3status.Meta.container
except AttributeError:
container = False
# delete the module
del py_mod
if container:
self.container_modules.append(name)
else:
self.error("Module `{}` cannot contain others".format(name)) | [
"def",
"check_child_friendly",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"split",
"(",
")",
"[",
"0",
"]",
"if",
"name",
"in",
"self",
".",
"container_modules",
":",
"return",
"root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
... | Check if a module is a container and so can have children | [
"Check",
"if",
"a",
"module",
"is",
"a",
"container",
"and",
"so",
"can",
"have",
"children"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L180-L214 |
231,120 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.check_module_name | def check_module_name(self, name, offset=0):
"""
Checks a module name eg. some i3status modules cannot have an instance
name.
"""
if name in ["general"]:
return
split_name = name.split()
if len(split_name) > 1 and split_name[0] in I3S_SINGLE_NAMES:
self.current_token -= len(split_name) - 1 - offset
self.error("Invalid name cannot have 2 tokens")
if len(split_name) > 2:
self.current_token -= len(split_name) - 2 - offset
self.error("Invalid name cannot have more than 2 tokens") | python | def check_module_name(self, name, offset=0):
if name in ["general"]:
return
split_name = name.split()
if len(split_name) > 1 and split_name[0] in I3S_SINGLE_NAMES:
self.current_token -= len(split_name) - 1 - offset
self.error("Invalid name cannot have 2 tokens")
if len(split_name) > 2:
self.current_token -= len(split_name) - 2 - offset
self.error("Invalid name cannot have more than 2 tokens") | [
"def",
"check_module_name",
"(",
"self",
",",
"name",
",",
"offset",
"=",
"0",
")",
":",
"if",
"name",
"in",
"[",
"\"general\"",
"]",
":",
"return",
"split_name",
"=",
"name",
".",
"split",
"(",
")",
"if",
"len",
"(",
"split_name",
")",
">",
"1",
"... | Checks a module name eg. some i3status modules cannot have an instance
name. | [
"Checks",
"a",
"module",
"name",
"eg",
".",
"some",
"i3status",
"modules",
"cannot",
"have",
"an",
"instance",
"name",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L216-L229 |
231,121 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.error | def error(self, msg, previous=False):
"""
Raise a ParseException.
We provide information to help locate the error in the config to allow
easy config debugging for users. previous indicates that the error
actually occurred at the end of the previous line.
"""
token = self.tokens[self.current_token - 1]
line_no = self.line
if previous:
line_no -= 1
line = self.raw[line_no]
position = token["start"] - self.line_start
if previous:
position = len(line) + 2
raise ParseException(msg, line, line_no + 1, position, token["value"]) | python | def error(self, msg, previous=False):
token = self.tokens[self.current_token - 1]
line_no = self.line
if previous:
line_no -= 1
line = self.raw[line_no]
position = token["start"] - self.line_start
if previous:
position = len(line) + 2
raise ParseException(msg, line, line_no + 1, position, token["value"]) | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"previous",
"=",
"False",
")",
":",
"token",
"=",
"self",
".",
"tokens",
"[",
"self",
".",
"current_token",
"-",
"1",
"]",
"line_no",
"=",
"self",
".",
"line",
"if",
"previous",
":",
"line_no",
"-=",
"1... | Raise a ParseException.
We provide information to help locate the error in the config to allow
easy config debugging for users. previous indicates that the error
actually occurred at the end of the previous line. | [
"Raise",
"a",
"ParseException",
".",
"We",
"provide",
"information",
"to",
"help",
"locate",
"the",
"error",
"in",
"the",
"config",
"to",
"allow",
"easy",
"config",
"debugging",
"for",
"users",
".",
"previous",
"indicates",
"that",
"the",
"error",
"actually",
... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L231-L246 |
231,122 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.tokenize | def tokenize(self, config):
"""
Break the config into a series of tokens
"""
tokens = []
reg_ex = re.compile(self.TOKENS[0], re.M | re.I)
for token in re.finditer(reg_ex, config):
value = token.group(0)
if token.group("operator"):
t_type = "operator"
elif token.group("literal"):
t_type = "literal"
elif token.group("newline"):
t_type = "newline"
elif token.group("function"):
t_type = "function"
elif token.group("unknown"):
t_type = "unknown"
else:
continue
tokens.append(
{"type": t_type, "value": value, "match": token, "start": token.start()}
)
self.tokens = tokens | python | def tokenize(self, config):
tokens = []
reg_ex = re.compile(self.TOKENS[0], re.M | re.I)
for token in re.finditer(reg_ex, config):
value = token.group(0)
if token.group("operator"):
t_type = "operator"
elif token.group("literal"):
t_type = "literal"
elif token.group("newline"):
t_type = "newline"
elif token.group("function"):
t_type = "function"
elif token.group("unknown"):
t_type = "unknown"
else:
continue
tokens.append(
{"type": t_type, "value": value, "match": token, "start": token.start()}
)
self.tokens = tokens | [
"def",
"tokenize",
"(",
"self",
",",
"config",
")",
":",
"tokens",
"=",
"[",
"]",
"reg_ex",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"TOKENS",
"[",
"0",
"]",
",",
"re",
".",
"M",
"|",
"re",
".",
"I",
")",
"for",
"token",
"in",
"re",
".",
... | Break the config into a series of tokens | [
"Break",
"the",
"config",
"into",
"a",
"series",
"of",
"tokens"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L248-L272 |
231,123 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.next | def next(self):
"""
Return the next token. Keep track of our current position in the
config for nice errors.
"""
if self.current_token == len(self.tokens):
return None
token = self.tokens[self.current_token]
if token["type"] == "newline":
self.line += 1
self.line_start = token["start"]
self.current_token += 1
if token["type"] == "unknown":
self.error("Unknown token")
return token | python | def next(self):
if self.current_token == len(self.tokens):
return None
token = self.tokens[self.current_token]
if token["type"] == "newline":
self.line += 1
self.line_start = token["start"]
self.current_token += 1
if token["type"] == "unknown":
self.error("Unknown token")
return token | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_token",
"==",
"len",
"(",
"self",
".",
"tokens",
")",
":",
"return",
"None",
"token",
"=",
"self",
".",
"tokens",
"[",
"self",
".",
"current_token",
"]",
"if",
"token",
"[",
"\"type\""... | Return the next token. Keep track of our current position in the
config for nice errors. | [
"Return",
"the",
"next",
"token",
".",
"Keep",
"track",
"of",
"our",
"current",
"position",
"in",
"the",
"config",
"for",
"nice",
"errors",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L274-L288 |
231,124 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.remove_quotes | def remove_quotes(self, value):
"""
Remove any surrounding quotes from a value and unescape any contained
quotes of that type.
"""
# beware the empty string
if not value:
return value
if value[0] == value[-1] == '"':
return value[1:-1].replace('\\"', '"')
if value[0] == value[-1] == "'":
return value[1:-1].replace("\\'", "'")
return value | python | def remove_quotes(self, value):
# beware the empty string
if not value:
return value
if value[0] == value[-1] == '"':
return value[1:-1].replace('\\"', '"')
if value[0] == value[-1] == "'":
return value[1:-1].replace("\\'", "'")
return value | [
"def",
"remove_quotes",
"(",
"self",
",",
"value",
")",
":",
"# beware the empty string",
"if",
"not",
"value",
":",
"return",
"value",
"if",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"return",
"value",
"[",
"1",
"... | Remove any surrounding quotes from a value and unescape any contained
quotes of that type. | [
"Remove",
"any",
"surrounding",
"quotes",
"from",
"a",
"value",
"and",
"unescape",
"any",
"contained",
"quotes",
"of",
"that",
"type",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L290-L303 |
231,125 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_value | def make_value(self, value):
"""
Converts to actual value, or remains as string.
"""
# ensure any escape sequences are converted to unicode
value = self.unicode_escape_sequence_fix(value)
if value and value[0] in ['"', "'"]:
return self.remove_quotes(value)
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
if value.lower() == "true":
return True
if value.lower() == "false":
return False
if value.lower() == "none":
return None
return value | python | def make_value(self, value):
# ensure any escape sequences are converted to unicode
value = self.unicode_escape_sequence_fix(value)
if value and value[0] in ['"', "'"]:
return self.remove_quotes(value)
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
if value.lower() == "true":
return True
if value.lower() == "false":
return False
if value.lower() == "none":
return None
return value | [
"def",
"make_value",
"(",
"self",
",",
"value",
")",
":",
"# ensure any escape sequences are converted to unicode",
"value",
"=",
"self",
".",
"unicode_escape_sequence_fix",
"(",
"value",
")",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"in",
"[",
"'\"'",
",",... | Converts to actual value, or remains as string. | [
"Converts",
"to",
"actual",
"value",
"or",
"remains",
"as",
"string",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L321-L345 |
231,126 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.config_function | def config_function(self, token):
"""
Process a config function from a token
"""
match = token["match"]
function = match.group(2).lower()
param = match.group(3) or ""
value_type = match.group(6) or "auto"
# fix any escaped closing parenthesis
param = param.replace(r"\)", ")")
CONFIG_FUNCTIONS = {
"base64": self.make_function_value_private,
"env": self.make_value_from_env,
"hide": self.make_function_value_private,
"shell": self.make_value_from_shell,
}
return CONFIG_FUNCTIONS[function](param, value_type, function) | python | def config_function(self, token):
match = token["match"]
function = match.group(2).lower()
param = match.group(3) or ""
value_type = match.group(6) or "auto"
# fix any escaped closing parenthesis
param = param.replace(r"\)", ")")
CONFIG_FUNCTIONS = {
"base64": self.make_function_value_private,
"env": self.make_value_from_env,
"hide": self.make_function_value_private,
"shell": self.make_value_from_shell,
}
return CONFIG_FUNCTIONS[function](param, value_type, function) | [
"def",
"config_function",
"(",
"self",
",",
"token",
")",
":",
"match",
"=",
"token",
"[",
"\"match\"",
"]",
"function",
"=",
"match",
".",
"group",
"(",
"2",
")",
".",
"lower",
"(",
")",
"param",
"=",
"match",
".",
"group",
"(",
"3",
")",
"or",
... | Process a config function from a token | [
"Process",
"a",
"config",
"function",
"from",
"a",
"token"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L347-L366 |
231,127 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.value_convert | def value_convert(self, value, value_type):
"""
convert string into type used by `config functions`
"""
CONVERSION_OPTIONS = {
"str": str,
"int": int,
"float": float,
# Treat booleans specially
"bool": (lambda val: val.lower() in ("true", "1")),
# Auto-guess the type
"auto": self.make_value,
}
try:
return CONVERSION_OPTIONS[value_type](value)
except (TypeError, ValueError):
self.notify_user("Bad type conversion")
return None | python | def value_convert(self, value, value_type):
CONVERSION_OPTIONS = {
"str": str,
"int": int,
"float": float,
# Treat booleans specially
"bool": (lambda val: val.lower() in ("true", "1")),
# Auto-guess the type
"auto": self.make_value,
}
try:
return CONVERSION_OPTIONS[value_type](value)
except (TypeError, ValueError):
self.notify_user("Bad type conversion")
return None | [
"def",
"value_convert",
"(",
"self",
",",
"value",
",",
"value_type",
")",
":",
"CONVERSION_OPTIONS",
"=",
"{",
"\"str\"",
":",
"str",
",",
"\"int\"",
":",
"int",
",",
"\"float\"",
":",
"float",
",",
"# Treat booleans specially",
"\"bool\"",
":",
"(",
"lambd... | convert string into type used by `config functions` | [
"convert",
"string",
"into",
"type",
"used",
"by",
"config",
"functions"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L368-L386 |
231,128 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_value_from_env | def make_value_from_env(self, param, value_type, function):
"""
get environment variable
"""
value = os.getenv(param)
if value is None:
self.notify_user("Environment variable `%s` undefined" % param)
return self.value_convert(value, value_type) | python | def make_value_from_env(self, param, value_type, function):
value = os.getenv(param)
if value is None:
self.notify_user("Environment variable `%s` undefined" % param)
return self.value_convert(value, value_type) | [
"def",
"make_value_from_env",
"(",
"self",
",",
"param",
",",
"value_type",
",",
"function",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"param",
")",
"if",
"value",
"is",
"None",
":",
"self",
".",
"notify_user",
"(",
"\"Environment variable `%s` undef... | get environment variable | [
"get",
"environment",
"variable"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L388-L395 |
231,129 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_value_from_shell | def make_value_from_shell(self, param, value_type, function):
"""
run command in the shell
"""
try:
value = check_output(param, shell=True).rstrip()
except CalledProcessError:
# for value_type of 'bool' we return False on error code
if value_type == "bool":
value = False
else:
if self.py3_wrapper:
self.py3_wrapper.report_exception(
msg="shell: called with command `%s`" % param
)
self.notify_user("shell script exited with an error")
value = None
else:
# if the value_type is 'bool' then we return True for success
if value_type == "bool":
value = True
else:
# convert bytes to unicode
value = value.decode("utf-8")
value = self.value_convert(value, value_type)
return value | python | def make_value_from_shell(self, param, value_type, function):
try:
value = check_output(param, shell=True).rstrip()
except CalledProcessError:
# for value_type of 'bool' we return False on error code
if value_type == "bool":
value = False
else:
if self.py3_wrapper:
self.py3_wrapper.report_exception(
msg="shell: called with command `%s`" % param
)
self.notify_user("shell script exited with an error")
value = None
else:
# if the value_type is 'bool' then we return True for success
if value_type == "bool":
value = True
else:
# convert bytes to unicode
value = value.decode("utf-8")
value = self.value_convert(value, value_type)
return value | [
"def",
"make_value_from_shell",
"(",
"self",
",",
"param",
",",
"value_type",
",",
"function",
")",
":",
"try",
":",
"value",
"=",
"check_output",
"(",
"param",
",",
"shell",
"=",
"True",
")",
".",
"rstrip",
"(",
")",
"except",
"CalledProcessError",
":",
... | run command in the shell | [
"run",
"command",
"in",
"the",
"shell"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L397-L422 |
231,130 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_function_value_private | def make_function_value_private(self, value, value_type, function):
"""
Wraps converted value so that it is hidden in logs etc.
Note this is not secure just reduces leaking info
Allows base 64 encode stuff using base64() or plain hide() in the
config
"""
# remove quotes
value = self.remove_quotes(value)
if function == "base64":
try:
import base64
value = base64.b64decode(value).decode("utf-8")
except TypeError as e:
self.notify_user("base64(..) error %s" % str(e))
# check we are in a module definition etc
if not self.current_module:
self.notify_user("%s(..) used outside of module or section" % function)
return None
module = self.current_module[-1].split()[0]
if module in CONFIG_FILE_SPECIAL_SECTIONS + I3S_MODULE_NAMES:
self.notify_user(
"%s(..) cannot be used outside of py3status module "
"configuration" % function
)
return None
value = self.value_convert(value, value_type)
module_name = self.current_module[-1]
return PrivateHide(value, module_name) | python | def make_function_value_private(self, value, value_type, function):
# remove quotes
value = self.remove_quotes(value)
if function == "base64":
try:
import base64
value = base64.b64decode(value).decode("utf-8")
except TypeError as e:
self.notify_user("base64(..) error %s" % str(e))
# check we are in a module definition etc
if not self.current_module:
self.notify_user("%s(..) used outside of module or section" % function)
return None
module = self.current_module[-1].split()[0]
if module in CONFIG_FILE_SPECIAL_SECTIONS + I3S_MODULE_NAMES:
self.notify_user(
"%s(..) cannot be used outside of py3status module "
"configuration" % function
)
return None
value = self.value_convert(value, value_type)
module_name = self.current_module[-1]
return PrivateHide(value, module_name) | [
"def",
"make_function_value_private",
"(",
"self",
",",
"value",
",",
"value_type",
",",
"function",
")",
":",
"# remove quotes",
"value",
"=",
"self",
".",
"remove_quotes",
"(",
"value",
")",
"if",
"function",
"==",
"\"base64\"",
":",
"try",
":",
"import",
... | Wraps converted value so that it is hidden in logs etc.
Note this is not secure just reduces leaking info
Allows base 64 encode stuff using base64() or plain hide() in the
config | [
"Wraps",
"converted",
"value",
"so",
"that",
"it",
"is",
"hidden",
"in",
"logs",
"etc",
".",
"Note",
"this",
"is",
"not",
"secure",
"just",
"reduces",
"leaking",
"info"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L424-L458 |
231,131 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.separator | def separator(self, separator=",", end_token=None):
"""
Read through tokens till the required separator is found. We ignore
newlines. If an end token is supplied raise a ParseEnd exception if it
is found.
"""
while True:
token = self.next()
t_value = token["value"]
if end_token and t_value == end_token:
raise self.ParseEnd()
if t_value == separator:
return
if t_value == "\n":
continue
self.error("Unexpected character") | python | def separator(self, separator=",", end_token=None):
while True:
token = self.next()
t_value = token["value"]
if end_token and t_value == end_token:
raise self.ParseEnd()
if t_value == separator:
return
if t_value == "\n":
continue
self.error("Unexpected character") | [
"def",
"separator",
"(",
"self",
",",
"separator",
"=",
"\",\"",
",",
"end_token",
"=",
"None",
")",
":",
"while",
"True",
":",
"token",
"=",
"self",
".",
"next",
"(",
")",
"t_value",
"=",
"token",
"[",
"\"value\"",
"]",
"if",
"end_token",
"and",
"t_... | Read through tokens till the required separator is found. We ignore
newlines. If an end token is supplied raise a ParseEnd exception if it
is found. | [
"Read",
"through",
"tokens",
"till",
"the",
"required",
"separator",
"is",
"found",
".",
"We",
"ignore",
"newlines",
".",
"If",
"an",
"end",
"token",
"is",
"supplied",
"raise",
"a",
"ParseEnd",
"exception",
"if",
"it",
"is",
"found",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L460-L475 |
231,132 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_list | def make_list(self, end_token="]"):
"""
We are in a list so get values until the end token. This can also
used to get tuples.
"""
out = []
while True:
try:
value = self.value_assign(end_token=end_token)
out.append(value)
self.separator(end_token=end_token)
except self.ParseEnd:
return out | python | def make_list(self, end_token="]"):
out = []
while True:
try:
value = self.value_assign(end_token=end_token)
out.append(value)
self.separator(end_token=end_token)
except self.ParseEnd:
return out | [
"def",
"make_list",
"(",
"self",
",",
"end_token",
"=",
"\"]\"",
")",
":",
"out",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"value",
"=",
"self",
".",
"value_assign",
"(",
"end_token",
"=",
"end_token",
")",
"out",
".",
"append",
"(",
"value",... | We are in a list so get values until the end token. This can also
used to get tuples. | [
"We",
"are",
"in",
"a",
"list",
"so",
"get",
"values",
"until",
"the",
"end",
"token",
".",
"This",
"can",
"also",
"used",
"to",
"get",
"tuples",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L477-L489 |
231,133 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.dict_key | def dict_key(self):
"""
Find the next key in a dict. We skip any newlines and check for if the
dict has ended.
"""
while True:
token = self.next()
t_value = token["value"]
if t_value == "\n":
continue
if t_value == "}":
raise self.ParseEnd()
if token["type"] == "literal":
return self.make_value(t_value)
self.error("Invalid Key") | python | def dict_key(self):
while True:
token = self.next()
t_value = token["value"]
if t_value == "\n":
continue
if t_value == "}":
raise self.ParseEnd()
if token["type"] == "literal":
return self.make_value(t_value)
self.error("Invalid Key") | [
"def",
"dict_key",
"(",
"self",
")",
":",
"while",
"True",
":",
"token",
"=",
"self",
".",
"next",
"(",
")",
"t_value",
"=",
"token",
"[",
"\"value\"",
"]",
"if",
"t_value",
"==",
"\"\\n\"",
":",
"continue",
"if",
"t_value",
"==",
"\"}\"",
":",
"rais... | Find the next key in a dict. We skip any newlines and check for if the
dict has ended. | [
"Find",
"the",
"next",
"key",
"in",
"a",
"dict",
".",
"We",
"skip",
"any",
"newlines",
"and",
"check",
"for",
"if",
"the",
"dict",
"has",
"ended",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L491-L505 |
231,134 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.make_dict | def make_dict(self):
"""
We are in a dict so get key value pairs until the end token.
"""
out = {}
while True:
try:
key = self.dict_key()
self.separator(separator=":")
value = self.value_assign(end_token="]")
out[key] = value
self.separator(end_token="}")
except self.ParseEnd:
return out | python | def make_dict(self):
out = {}
while True:
try:
key = self.dict_key()
self.separator(separator=":")
value = self.value_assign(end_token="]")
out[key] = value
self.separator(end_token="}")
except self.ParseEnd:
return out | [
"def",
"make_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"while",
"True",
":",
"try",
":",
"key",
"=",
"self",
".",
"dict_key",
"(",
")",
"self",
".",
"separator",
"(",
"separator",
"=",
"\":\"",
")",
"value",
"=",
"self",
".",
"value_assig... | We are in a dict so get key value pairs until the end token. | [
"We",
"are",
"in",
"a",
"dict",
"so",
"get",
"key",
"value",
"pairs",
"until",
"the",
"end",
"token",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L507-L520 |
231,135 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.module_def | def module_def(self):
"""
This is a module definition so parse content till end.
"""
if self.module_level == MAX_NESTING_LEVELS:
self.error("Module nested too deep")
self.module_level += 1
module = ModuleDefinition()
self.parse(module, end_token="}")
self.module_level -= 1
self.current_module.pop()
return module | python | def module_def(self):
if self.module_level == MAX_NESTING_LEVELS:
self.error("Module nested too deep")
self.module_level += 1
module = ModuleDefinition()
self.parse(module, end_token="}")
self.module_level -= 1
self.current_module.pop()
return module | [
"def",
"module_def",
"(",
"self",
")",
":",
"if",
"self",
".",
"module_level",
"==",
"MAX_NESTING_LEVELS",
":",
"self",
".",
"error",
"(",
"\"Module nested too deep\"",
")",
"self",
".",
"module_level",
"+=",
"1",
"module",
"=",
"ModuleDefinition",
"(",
")",
... | This is a module definition so parse content till end. | [
"This",
"is",
"a",
"module",
"definition",
"so",
"parse",
"content",
"till",
"end",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L549-L560 |
231,136 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.process_value | def process_value(self, name, value, module_name):
"""
This method allow any encodings to be dealt with.
Currently only base64 is supported.
Note: If other encodings are added then this should be split so that
there is a method for each encoding.
"""
# if we have a colon in the name of a setting then it
# indicates that it has been encoded.
if ":" in name:
if module_name.split(" ")[0] in I3S_MODULE_NAMES + ["general"]:
self.error("Only py3status modules can use obfuscated")
if type(value).__name__ not in ["str", "unicode"]:
self.error("Only strings can be obfuscated")
(name, scheme) = name.split(":")
if scheme == "base64":
value = PrivateBase64(value, module_name)
elif scheme == "hide":
value = PrivateHide(value, module_name)
else:
self.error("Unknown scheme {} for data".format(scheme))
return name, value | python | def process_value(self, name, value, module_name):
# if we have a colon in the name of a setting then it
# indicates that it has been encoded.
if ":" in name:
if module_name.split(" ")[0] in I3S_MODULE_NAMES + ["general"]:
self.error("Only py3status modules can use obfuscated")
if type(value).__name__ not in ["str", "unicode"]:
self.error("Only strings can be obfuscated")
(name, scheme) = name.split(":")
if scheme == "base64":
value = PrivateBase64(value, module_name)
elif scheme == "hide":
value = PrivateHide(value, module_name)
else:
self.error("Unknown scheme {} for data".format(scheme))
return name, value | [
"def",
"process_value",
"(",
"self",
",",
"name",
",",
"value",
",",
"module_name",
")",
":",
"# if we have a colon in the name of a setting then it",
"# indicates that it has been encoded.",
"if",
"\":\"",
"in",
"name",
":",
"if",
"module_name",
".",
"split",
"(",
"\... | This method allow any encodings to be dealt with.
Currently only base64 is supported.
Note: If other encodings are added then this should be split so that
there is a method for each encoding. | [
"This",
"method",
"allow",
"any",
"encodings",
"to",
"be",
"dealt",
"with",
".",
"Currently",
"only",
"base64",
"is",
"supported",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L573-L599 |
231,137 | ultrabug/py3status | py3status/parse_config.py | ConfigParser.parse | def parse(self, dictionary=None, end_token=None):
"""
Parse through the tokens. Finding names and values.
This is called at the start of parsing the config but is
also called to parse module definitions.
"""
self.level += 1
name = []
if dictionary is None:
dictionary = self.config
while True:
token = self.next()
if token is None:
# we have got to the end of the config
break
t_type = token["type"]
t_value = token["value"]
if t_type == "newline":
continue
elif t_value == end_token:
self.level -= 1
return
elif t_type == "literal":
value = self.remove_quotes(t_value)
if not name and not re.match("[a-zA-Z_]", value):
self.error("Invalid name")
name.append(value)
elif t_type == "function":
self.error("Name expected")
elif t_type == "operator":
name = " ".join(name)
if not name:
self.error("Name expected")
elif t_value == "+=" and name not in dictionary:
# deal with encoded names
if name.split(":")[0] not in dictionary:
# order is treated specially
if not (self.level == 1 and name == "order"):
self.error("{} does not exist".format(name))
if t_value in ["{"]:
if self.current_module:
self.check_child_friendly(self.current_module[-1])
self.check_module_name(name)
self.current_module.append(name)
value = self.assignment(token)
# order is treated specially to create a list
if self.level == 1 and name == "order":
if not value:
self.error("Invalid module")
self.check_module_name(value, offset=1)
dictionary.setdefault(name, []).append(value)
# assignment of module definition
elif t_value == "{":
# If this is an py3status module and in a container and has
# no instance name then give it an anon one. This allows
# us to have multiple non-instance named modules defined
# without them clashing.
if (
self.level > 1
and " " not in name
and name not in I3S_MODULE_NAMES
):
name = "{} _anon_module_{}".format(name, self.anon_count)
self.anon_count += 1
dictionary[name] = value
# assignment of value
elif t_value == "=":
try:
name, value = self.process_value(
name, value, self.current_module[-1]
)
except IndexError:
self.error("Missing {", previous=True)
dictionary[name] = value
# appending to existing values
elif t_value == "+=":
dictionary[name] += value
else:
self.error("Unexpected character")
name = [] | python | def parse(self, dictionary=None, end_token=None):
self.level += 1
name = []
if dictionary is None:
dictionary = self.config
while True:
token = self.next()
if token is None:
# we have got to the end of the config
break
t_type = token["type"]
t_value = token["value"]
if t_type == "newline":
continue
elif t_value == end_token:
self.level -= 1
return
elif t_type == "literal":
value = self.remove_quotes(t_value)
if not name and not re.match("[a-zA-Z_]", value):
self.error("Invalid name")
name.append(value)
elif t_type == "function":
self.error("Name expected")
elif t_type == "operator":
name = " ".join(name)
if not name:
self.error("Name expected")
elif t_value == "+=" and name not in dictionary:
# deal with encoded names
if name.split(":")[0] not in dictionary:
# order is treated specially
if not (self.level == 1 and name == "order"):
self.error("{} does not exist".format(name))
if t_value in ["{"]:
if self.current_module:
self.check_child_friendly(self.current_module[-1])
self.check_module_name(name)
self.current_module.append(name)
value = self.assignment(token)
# order is treated specially to create a list
if self.level == 1 and name == "order":
if not value:
self.error("Invalid module")
self.check_module_name(value, offset=1)
dictionary.setdefault(name, []).append(value)
# assignment of module definition
elif t_value == "{":
# If this is an py3status module and in a container and has
# no instance name then give it an anon one. This allows
# us to have multiple non-instance named modules defined
# without them clashing.
if (
self.level > 1
and " " not in name
and name not in I3S_MODULE_NAMES
):
name = "{} _anon_module_{}".format(name, self.anon_count)
self.anon_count += 1
dictionary[name] = value
# assignment of value
elif t_value == "=":
try:
name, value = self.process_value(
name, value, self.current_module[-1]
)
except IndexError:
self.error("Missing {", previous=True)
dictionary[name] = value
# appending to existing values
elif t_value == "+=":
dictionary[name] += value
else:
self.error("Unexpected character")
name = [] | [
"def",
"parse",
"(",
"self",
",",
"dictionary",
"=",
"None",
",",
"end_token",
"=",
"None",
")",
":",
"self",
".",
"level",
"+=",
"1",
"name",
"=",
"[",
"]",
"if",
"dictionary",
"is",
"None",
":",
"dictionary",
"=",
"self",
".",
"config",
"while",
... | Parse through the tokens. Finding names and values.
This is called at the start of parsing the config but is
also called to parse module definitions. | [
"Parse",
"through",
"the",
"tokens",
".",
"Finding",
"names",
"and",
"values",
".",
"This",
"is",
"called",
"at",
"the",
"start",
"of",
"parsing",
"the",
"config",
"but",
"is",
"also",
"called",
"to",
"parse",
"module",
"definitions",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L601-L680 |
231,138 | ultrabug/py3status | py3status/modules/moc.py | Py3status.on_click | def on_click(self, event):
"""
Control moc with mouse clicks.
"""
button = event["button"]
if button == self.button_pause:
if self.state == "STOP":
self.py3.command_run("mocp --play")
else:
self.py3.command_run("mocp --toggle-pause")
elif button == self.button_stop:
self.py3.command_run("mocp --stop")
elif button == self.button_next:
self.py3.command_run("mocp --next")
elif button == self.button_previous:
self.py3.command_run("mocp --prev")
else:
self.py3.prevent_refresh() | python | def on_click(self, event):
button = event["button"]
if button == self.button_pause:
if self.state == "STOP":
self.py3.command_run("mocp --play")
else:
self.py3.command_run("mocp --toggle-pause")
elif button == self.button_stop:
self.py3.command_run("mocp --stop")
elif button == self.button_next:
self.py3.command_run("mocp --next")
elif button == self.button_previous:
self.py3.command_run("mocp --prev")
else:
self.py3.prevent_refresh() | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"button",
"=",
"event",
"[",
"\"button\"",
"]",
"if",
"button",
"==",
"self",
".",
"button_pause",
":",
"if",
"self",
".",
"state",
"==",
"\"STOP\"",
":",
"self",
".",
"py3",
".",
"command_run",
... | Control moc with mouse clicks. | [
"Control",
"moc",
"with",
"mouse",
"clicks",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/moc.py#L156-L173 |
231,139 | ultrabug/py3status | py3status/py3.py | Py3._thresholds_init | def _thresholds_init(self):
"""
Initiate and check any thresholds set
"""
thresholds = getattr(self._py3status_module, "thresholds", [])
self._thresholds = {}
if isinstance(thresholds, list):
try:
thresholds.sort()
except TypeError:
pass
self._thresholds[None] = [(x[0], self._get_color(x[1])) for x in thresholds]
return
elif isinstance(thresholds, dict):
for key, value in thresholds.items():
if isinstance(value, list):
try:
value.sort()
except TypeError:
pass
self._thresholds[key] = [
(x[0], self._get_color(x[1])) for x in value
] | python | def _thresholds_init(self):
thresholds = getattr(self._py3status_module, "thresholds", [])
self._thresholds = {}
if isinstance(thresholds, list):
try:
thresholds.sort()
except TypeError:
pass
self._thresholds[None] = [(x[0], self._get_color(x[1])) for x in thresholds]
return
elif isinstance(thresholds, dict):
for key, value in thresholds.items():
if isinstance(value, list):
try:
value.sort()
except TypeError:
pass
self._thresholds[key] = [
(x[0], self._get_color(x[1])) for x in value
] | [
"def",
"_thresholds_init",
"(",
"self",
")",
":",
"thresholds",
"=",
"getattr",
"(",
"self",
".",
"_py3status_module",
",",
"\"thresholds\"",
",",
"[",
"]",
")",
"self",
".",
"_thresholds",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"thresholds",
",",
"list",... | Initiate and check any thresholds set | [
"Initiate",
"and",
"check",
"any",
"thresholds",
"set"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L192-L214 |
231,140 | ultrabug/py3status | py3status/py3.py | Py3._report_exception | def _report_exception(self, msg, frame_skip=2):
"""
THIS IS PRIVATE AND UNSUPPORTED.
logs an exception that occurs inside of a Py3 method. We only log the
exception once to prevent spamming the logs and we do not notify the
user.
frame_skip is used to change the place in the code that the error is
reported as coming from. We want to show it as coming from the
py3status module where the Py3 method was called.
"""
# We use a hash to see if the message is being repeated.
msg_hash = hash(msg)
if msg_hash in self._report_exception_cache:
return
self._report_exception_cache.add(msg_hash)
# If we just report the error the traceback will end in the try
# except block that we are calling from.
# We want to show the traceback originating from the module that
# called the Py3 method so get the correct error frame and pass this
# along.
error_frame = sys._getframe(0)
while frame_skip:
error_frame = error_frame.f_back
frame_skip -= 1
self._py3_wrapper.report_exception(
msg, notify_user=False, error_frame=error_frame
) | python | def _report_exception(self, msg, frame_skip=2):
# We use a hash to see if the message is being repeated.
msg_hash = hash(msg)
if msg_hash in self._report_exception_cache:
return
self._report_exception_cache.add(msg_hash)
# If we just report the error the traceback will end in the try
# except block that we are calling from.
# We want to show the traceback originating from the module that
# called the Py3 method so get the correct error frame and pass this
# along.
error_frame = sys._getframe(0)
while frame_skip:
error_frame = error_frame.f_back
frame_skip -= 1
self._py3_wrapper.report_exception(
msg, notify_user=False, error_frame=error_frame
) | [
"def",
"_report_exception",
"(",
"self",
",",
"msg",
",",
"frame_skip",
"=",
"2",
")",
":",
"# We use a hash to see if the message is being repeated.",
"msg_hash",
"=",
"hash",
"(",
"msg",
")",
"if",
"msg_hash",
"in",
"self",
".",
"_report_exception_cache",
":",
"... | THIS IS PRIVATE AND UNSUPPORTED.
logs an exception that occurs inside of a Py3 method. We only log the
exception once to prevent spamming the logs and we do not notify the
user.
frame_skip is used to change the place in the code that the error is
reported as coming from. We want to show it as coming from the
py3status module where the Py3 method was called. | [
"THIS",
"IS",
"PRIVATE",
"AND",
"UNSUPPORTED",
".",
"logs",
"an",
"exception",
"that",
"occurs",
"inside",
"of",
"a",
"Py3",
"method",
".",
"We",
"only",
"log",
"the",
"exception",
"once",
"to",
"prevent",
"spamming",
"the",
"logs",
"and",
"we",
"do",
"n... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L227-L255 |
231,141 | ultrabug/py3status | py3status/py3.py | Py3.flatten_dict | def flatten_dict(self, d, delimiter="-", intermediates=False, parent_key=None):
"""
Flatten a dictionary.
Values that are dictionaries are flattened using delimiter in between
(eg. parent-child)
Values that are lists are flattened using delimiter
followed by the index (eg. parent-0)
example:
.. code-block:: python
{
'fish_facts': {
'sharks': 'Most will drown if they stop moving',
'skates': 'More than 200 species',
},
'fruits': ['apple', 'peach', 'watermelon'],
'number': 52
}
# becomes
{
'fish_facts-sharks': 'Most will drown if they stop moving',
'fish_facts-skates': 'More than 200 species',
'fruits-0': 'apple',
'fruits-1': 'peach',
'fruits-2': 'watermelon',
'number': 52
}
# if intermediates is True then we also get unflattened elements
# as well as the flattened ones.
{
'fish_facts': {
'sharks': 'Most will drown if they stop moving',
'skates': 'More than 200 species',
},
'fish_facts-sharks': 'Most will drown if they stop moving',
'fish_facts-skates': 'More than 200 species',
'fruits': ['apple', 'peach', 'watermelon'],
'fruits-0': 'apple',
'fruits-1': 'peach',
'fruits-2': 'watermelon',
'number': 52
}
"""
items = []
if isinstance(d, list):
d = dict(enumerate(d))
for k, v in d.items():
if parent_key:
k = u"{}{}{}".format(parent_key, delimiter, k)
if intermediates:
items.append((k, v))
if isinstance(v, list):
v = dict(enumerate(v))
if isinstance(v, collections.Mapping):
items.extend(
self.flatten_dict(v, delimiter, intermediates, str(k)).items()
)
else:
items.append((str(k), v))
return dict(items) | python | def flatten_dict(self, d, delimiter="-", intermediates=False, parent_key=None):
items = []
if isinstance(d, list):
d = dict(enumerate(d))
for k, v in d.items():
if parent_key:
k = u"{}{}{}".format(parent_key, delimiter, k)
if intermediates:
items.append((k, v))
if isinstance(v, list):
v = dict(enumerate(v))
if isinstance(v, collections.Mapping):
items.extend(
self.flatten_dict(v, delimiter, intermediates, str(k)).items()
)
else:
items.append((str(k), v))
return dict(items) | [
"def",
"flatten_dict",
"(",
"self",
",",
"d",
",",
"delimiter",
"=",
"\"-\"",
",",
"intermediates",
"=",
"False",
",",
"parent_key",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"d",
"=",
"dict... | Flatten a dictionary.
Values that are dictionaries are flattened using delimiter in between
(eg. parent-child)
Values that are lists are flattened using delimiter
followed by the index (eg. parent-0)
example:
.. code-block:: python
{
'fish_facts': {
'sharks': 'Most will drown if they stop moving',
'skates': 'More than 200 species',
},
'fruits': ['apple', 'peach', 'watermelon'],
'number': 52
}
# becomes
{
'fish_facts-sharks': 'Most will drown if they stop moving',
'fish_facts-skates': 'More than 200 species',
'fruits-0': 'apple',
'fruits-1': 'peach',
'fruits-2': 'watermelon',
'number': 52
}
# if intermediates is True then we also get unflattened elements
# as well as the flattened ones.
{
'fish_facts': {
'sharks': 'Most will drown if they stop moving',
'skates': 'More than 200 species',
},
'fish_facts-sharks': 'Most will drown if they stop moving',
'fish_facts-skates': 'More than 200 species',
'fruits': ['apple', 'peach', 'watermelon'],
'fruits-0': 'apple',
'fruits-1': 'peach',
'fruits-2': 'watermelon',
'number': 52
} | [
"Flatten",
"a",
"dictionary",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L268-L335 |
231,142 | ultrabug/py3status | py3status/py3.py | Py3.is_my_event | def is_my_event(self, event):
"""
Checks if an event triggered belongs to the module receiving it. This
is mainly for containers who will also receive events from any children
they have.
Returns True if the event name and instance match that of the module
checking.
"""
return (
event.get("name") == self._module.module_name
and event.get("instance") == self._module.module_inst
) | python | def is_my_event(self, event):
return (
event.get("name") == self._module.module_name
and event.get("instance") == self._module.module_inst
) | [
"def",
"is_my_event",
"(",
"self",
",",
"event",
")",
":",
"return",
"(",
"event",
".",
"get",
"(",
"\"name\"",
")",
"==",
"self",
".",
"_module",
".",
"module_name",
"and",
"event",
".",
"get",
"(",
"\"instance\"",
")",
"==",
"self",
".",
"_module",
... | Checks if an event triggered belongs to the module receiving it. This
is mainly for containers who will also receive events from any children
they have.
Returns True if the event name and instance match that of the module
checking. | [
"Checks",
"if",
"an",
"event",
"triggered",
"belongs",
"to",
"the",
"module",
"receiving",
"it",
".",
"This",
"is",
"mainly",
"for",
"containers",
"who",
"will",
"also",
"receive",
"events",
"from",
"any",
"children",
"they",
"have",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L460-L473 |
231,143 | ultrabug/py3status | py3status/py3.py | Py3.log | def log(self, message, level=LOG_INFO):
"""
Log the message.
The level must be one of LOG_ERROR, LOG_INFO or LOG_WARNING
"""
assert level in [
self.LOG_ERROR,
self.LOG_INFO,
self.LOG_WARNING,
], "level must be LOG_ERROR, LOG_INFO or LOG_WARNING"
# nicely format logs if we can using pretty print
if isinstance(message, (dict, list, set, tuple)):
message = pformat(message)
# start on new line if multi-line output
try:
if "\n" in message:
message = "\n" + message
except: # noqa e722
pass
message = "Module `{}`: {}".format(self._module.module_full_name, message)
self._py3_wrapper.log(message, level) | python | def log(self, message, level=LOG_INFO):
assert level in [
self.LOG_ERROR,
self.LOG_INFO,
self.LOG_WARNING,
], "level must be LOG_ERROR, LOG_INFO or LOG_WARNING"
# nicely format logs if we can using pretty print
if isinstance(message, (dict, list, set, tuple)):
message = pformat(message)
# start on new line if multi-line output
try:
if "\n" in message:
message = "\n" + message
except: # noqa e722
pass
message = "Module `{}`: {}".format(self._module.module_full_name, message)
self._py3_wrapper.log(message, level) | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"level",
"=",
"LOG_INFO",
")",
":",
"assert",
"level",
"in",
"[",
"self",
".",
"LOG_ERROR",
",",
"self",
".",
"LOG_INFO",
",",
"self",
".",
"LOG_WARNING",
",",
"]",
",",
"\"level must be LOG_ERROR, LOG_INFO o... | Log the message.
The level must be one of LOG_ERROR, LOG_INFO or LOG_WARNING | [
"Log",
"the",
"message",
".",
"The",
"level",
"must",
"be",
"one",
"of",
"LOG_ERROR",
"LOG_INFO",
"or",
"LOG_WARNING"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L475-L496 |
231,144 | ultrabug/py3status | py3status/py3.py | Py3.update | def update(self, module_name=None):
"""
Update a module. If module_name is supplied the module of that
name is updated. Otherwise the module calling is updated.
"""
if not module_name:
return self._module.force_update()
else:
module_info = self._get_module_info(module_name)
if module_info:
module_info["module"].force_update() | python | def update(self, module_name=None):
if not module_name:
return self._module.force_update()
else:
module_info = self._get_module_info(module_name)
if module_info:
module_info["module"].force_update() | [
"def",
"update",
"(",
"self",
",",
"module_name",
"=",
"None",
")",
":",
"if",
"not",
"module_name",
":",
"return",
"self",
".",
"_module",
".",
"force_update",
"(",
")",
"else",
":",
"module_info",
"=",
"self",
".",
"_get_module_info",
"(",
"module_name",... | Update a module. If module_name is supplied the module of that
name is updated. Otherwise the module calling is updated. | [
"Update",
"a",
"module",
".",
"If",
"module_name",
"is",
"supplied",
"the",
"module",
"of",
"that",
"name",
"is",
"updated",
".",
"Otherwise",
"the",
"module",
"calling",
"is",
"updated",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L498-L508 |
231,145 | ultrabug/py3status | py3status/py3.py | Py3.get_output | def get_output(self, module_name):
"""
Return the output of the named module. This will be a list.
"""
output = []
module_info = self._get_module_info(module_name)
if module_info:
output = module_info["module"].get_latest()
# we do a deep copy so that any user does not change the actual output
# of the module.
return deepcopy(output) | python | def get_output(self, module_name):
output = []
module_info = self._get_module_info(module_name)
if module_info:
output = module_info["module"].get_latest()
# we do a deep copy so that any user does not change the actual output
# of the module.
return deepcopy(output) | [
"def",
"get_output",
"(",
"self",
",",
"module_name",
")",
":",
"output",
"=",
"[",
"]",
"module_info",
"=",
"self",
".",
"_get_module_info",
"(",
"module_name",
")",
"if",
"module_info",
":",
"output",
"=",
"module_info",
"[",
"\"module\"",
"]",
".",
"get... | Return the output of the named module. This will be a list. | [
"Return",
"the",
"output",
"of",
"the",
"named",
"module",
".",
"This",
"will",
"be",
"a",
"list",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L519-L529 |
231,146 | ultrabug/py3status | py3status/py3.py | Py3.trigger_event | def trigger_event(self, module_name, event):
"""
Trigger an event on a named module.
"""
if module_name:
self._py3_wrapper.events_thread.process_event(module_name, event) | python | def trigger_event(self, module_name, event):
if module_name:
self._py3_wrapper.events_thread.process_event(module_name, event) | [
"def",
"trigger_event",
"(",
"self",
",",
"module_name",
",",
"event",
")",
":",
"if",
"module_name",
":",
"self",
".",
"_py3_wrapper",
".",
"events_thread",
".",
"process_event",
"(",
"module_name",
",",
"event",
")"
] | Trigger an event on a named module. | [
"Trigger",
"an",
"event",
"on",
"a",
"named",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L531-L536 |
231,147 | ultrabug/py3status | py3status/py3.py | Py3.notify_user | def notify_user(self, msg, level="info", rate_limit=5, title=None, icon=None):
"""
Send a notification to the user.
level must be 'info', 'error' or 'warning'.
rate_limit is the time period in seconds during which this message
should not be repeated.
icon must be an icon path or icon name.
"""
module_name = self._module.module_full_name
if isinstance(msg, Composite):
msg = msg.text()
if title is None:
title = "py3status: {}".format(module_name)
elif isinstance(title, Composite):
title = title.text()
# force unicode for python2 str
if self._is_python_2:
if isinstance(msg, str):
msg = msg.decode("utf-8")
if isinstance(title, str):
title = title.decode("utf-8")
if msg:
self._py3_wrapper.notify_user(
msg=msg,
level=level,
rate_limit=rate_limit,
module_name=module_name,
title=title,
icon=icon,
) | python | def notify_user(self, msg, level="info", rate_limit=5, title=None, icon=None):
module_name = self._module.module_full_name
if isinstance(msg, Composite):
msg = msg.text()
if title is None:
title = "py3status: {}".format(module_name)
elif isinstance(title, Composite):
title = title.text()
# force unicode for python2 str
if self._is_python_2:
if isinstance(msg, str):
msg = msg.decode("utf-8")
if isinstance(title, str):
title = title.decode("utf-8")
if msg:
self._py3_wrapper.notify_user(
msg=msg,
level=level,
rate_limit=rate_limit,
module_name=module_name,
title=title,
icon=icon,
) | [
"def",
"notify_user",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"\"info\"",
",",
"rate_limit",
"=",
"5",
",",
"title",
"=",
"None",
",",
"icon",
"=",
"None",
")",
":",
"module_name",
"=",
"self",
".",
"_module",
".",
"module_full_name",
"if",
"isinst... | Send a notification to the user.
level must be 'info', 'error' or 'warning'.
rate_limit is the time period in seconds during which this message
should not be repeated.
icon must be an icon path or icon name. | [
"Send",
"a",
"notification",
"to",
"the",
"user",
".",
"level",
"must",
"be",
"info",
"error",
"or",
"warning",
".",
"rate_limit",
"is",
"the",
"time",
"period",
"in",
"seconds",
"during",
"which",
"this",
"message",
"should",
"not",
"be",
"repeated",
".",... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L546-L575 |
231,148 | ultrabug/py3status | py3status/py3.py | Py3.register_function | def register_function(self, function_name, function):
"""
Register a function for the module.
The following functions can be registered
.. py:function:: content_function()
Called to discover what modules a container is displaying. This is
used to determine when updates need passing on to the container and
also when modules can be put to sleep.
the function must return a set of module names that are being
displayed.
.. note::
This function should only be used by containers.
.. py:function:: urgent_function(module_names)
This function will be called when one of the contents of a container
has changed from a non-urgent to an urgent state. It is used by the
group module to switch to displaying the urgent module.
``module_names`` is a list of modules that have become urgent
.. note::
This function should only be used by containers.
"""
my_info = self._get_module_info(self._module.module_full_name)
my_info[function_name] = function | python | def register_function(self, function_name, function):
my_info = self._get_module_info(self._module.module_full_name)
my_info[function_name] = function | [
"def",
"register_function",
"(",
"self",
",",
"function_name",
",",
"function",
")",
":",
"my_info",
"=",
"self",
".",
"_get_module_info",
"(",
"self",
".",
"_module",
".",
"module_full_name",
")",
"my_info",
"[",
"function_name",
"]",
"=",
"function"
] | Register a function for the module.
The following functions can be registered
.. py:function:: content_function()
Called to discover what modules a container is displaying. This is
used to determine when updates need passing on to the container and
also when modules can be put to sleep.
the function must return a set of module names that are being
displayed.
.. note::
This function should only be used by containers.
.. py:function:: urgent_function(module_names)
This function will be called when one of the contents of a container
has changed from a non-urgent to an urgent state. It is used by the
group module to switch to displaying the urgent module.
``module_names`` is a list of modules that have become urgent
.. note::
This function should only be used by containers. | [
"Register",
"a",
"function",
"for",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L577-L610 |
231,149 | ultrabug/py3status | py3status/py3.py | Py3.time_in | def time_in(self, seconds=None, sync_to=None, offset=0):
"""
Returns the time a given number of seconds into the future. Helpful
for creating the ``cached_until`` value for the module output.
.. note::
from version 3.1 modules no longer need to explicitly set a
``cached_until`` in their response unless they wish to directly control
it.
:param seconds: specifies the number of seconds that should occur before the
update is required. Passing a value of ``CACHE_FOREVER`` returns
``CACHE_FOREVER`` which can be useful for some modules.
:param sync_to: causes the update to be synchronized to a time period. 1 would
cause the update on the second, 60 to the nearest minute. By default we
synchronize to the nearest second. 0 will disable this feature.
:param offset: is used to alter the base time used. A timer that started at a
certain time could set that as the offset and any synchronization would
then be relative to that time.
"""
# if called with CACHE_FOREVER we just return this
if seconds is self.CACHE_FOREVER:
return self.CACHE_FOREVER
if seconds is None:
# If we have a sync_to then seconds can be 0
if sync_to and sync_to > 0:
seconds = 0
else:
try:
# use py3status modules cache_timeout
seconds = self._py3status_module.cache_timeout
except AttributeError:
# use default cache_timeout
seconds = self._module.config["cache_timeout"]
# Unless explicitly set we sync to the nearest second
# Unless the requested update is in less than a second
if sync_to is None:
if seconds and seconds < 1:
if 1 % seconds == 0:
sync_to = seconds
else:
sync_to = 0
else:
sync_to = 1
if seconds:
seconds -= 0.1
requested = time() + seconds - offset
# if sync_to then we find the sync time for the requested time
if sync_to:
requested = (requested + sync_to) - (requested % sync_to)
return requested + offset | python | def time_in(self, seconds=None, sync_to=None, offset=0):
# if called with CACHE_FOREVER we just return this
if seconds is self.CACHE_FOREVER:
return self.CACHE_FOREVER
if seconds is None:
# If we have a sync_to then seconds can be 0
if sync_to and sync_to > 0:
seconds = 0
else:
try:
# use py3status modules cache_timeout
seconds = self._py3status_module.cache_timeout
except AttributeError:
# use default cache_timeout
seconds = self._module.config["cache_timeout"]
# Unless explicitly set we sync to the nearest second
# Unless the requested update is in less than a second
if sync_to is None:
if seconds and seconds < 1:
if 1 % seconds == 0:
sync_to = seconds
else:
sync_to = 0
else:
sync_to = 1
if seconds:
seconds -= 0.1
requested = time() + seconds - offset
# if sync_to then we find the sync time for the requested time
if sync_to:
requested = (requested + sync_to) - (requested % sync_to)
return requested + offset | [
"def",
"time_in",
"(",
"self",
",",
"seconds",
"=",
"None",
",",
"sync_to",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"# if called with CACHE_FOREVER we just return this",
"if",
"seconds",
"is",
"self",
".",
"CACHE_FOREVER",
":",
"return",
"self",
".",
... | Returns the time a given number of seconds into the future. Helpful
for creating the ``cached_until`` value for the module output.
.. note::
from version 3.1 modules no longer need to explicitly set a
``cached_until`` in their response unless they wish to directly control
it.
:param seconds: specifies the number of seconds that should occur before the
update is required. Passing a value of ``CACHE_FOREVER`` returns
``CACHE_FOREVER`` which can be useful for some modules.
:param sync_to: causes the update to be synchronized to a time period. 1 would
cause the update on the second, 60 to the nearest minute. By default we
synchronize to the nearest second. 0 will disable this feature.
:param offset: is used to alter the base time used. A timer that started at a
certain time could set that as the offset and any synchronization would
then be relative to that time. | [
"Returns",
"the",
"time",
"a",
"given",
"number",
"of",
"seconds",
"into",
"the",
"future",
".",
"Helpful",
"for",
"creating",
"the",
"cached_until",
"value",
"for",
"the",
"module",
"output",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L612-L671 |
231,150 | ultrabug/py3status | py3status/py3.py | Py3.format_contains | def format_contains(self, format_string, names):
"""
Determines if ``format_string`` contains a placeholder string ``names``
or a list of placeholders ``names``.
``names`` is tested against placeholders using fnmatch so the following
patterns can be used:
.. code-block:: none
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
This is useful because a simple test like
``'{placeholder}' in format_string``
will fail if the format string contains placeholder formatting
eg ``'{placeholder:.2f}'``
"""
# We cache things to prevent parsing the format_string more than needed
if isinstance(names, list):
key = str(names)
else:
key = names
names = [names]
try:
return self._format_placeholders_cache[format_string][key]
except KeyError:
pass
if format_string not in self._format_placeholders:
placeholders = self._formatter.get_placeholders(format_string)
self._format_placeholders[format_string] = placeholders
else:
placeholders = self._format_placeholders[format_string]
if format_string not in self._format_placeholders_cache:
self._format_placeholders_cache[format_string] = {}
for name in names:
for placeholder in placeholders:
if fnmatch(placeholder, name):
self._format_placeholders_cache[format_string][key] = True
return True
self._format_placeholders_cache[format_string][key] = False
return False | python | def format_contains(self, format_string, names):
# We cache things to prevent parsing the format_string more than needed
if isinstance(names, list):
key = str(names)
else:
key = names
names = [names]
try:
return self._format_placeholders_cache[format_string][key]
except KeyError:
pass
if format_string not in self._format_placeholders:
placeholders = self._formatter.get_placeholders(format_string)
self._format_placeholders[format_string] = placeholders
else:
placeholders = self._format_placeholders[format_string]
if format_string not in self._format_placeholders_cache:
self._format_placeholders_cache[format_string] = {}
for name in names:
for placeholder in placeholders:
if fnmatch(placeholder, name):
self._format_placeholders_cache[format_string][key] = True
return True
self._format_placeholders_cache[format_string][key] = False
return False | [
"def",
"format_contains",
"(",
"self",
",",
"format_string",
",",
"names",
")",
":",
"# We cache things to prevent parsing the format_string more than needed",
"if",
"isinstance",
"(",
"names",
",",
"list",
")",
":",
"key",
"=",
"str",
"(",
"names",
")",
"else",
"... | Determines if ``format_string`` contains a placeholder string ``names``
or a list of placeholders ``names``.
``names`` is tested against placeholders using fnmatch so the following
patterns can be used:
.. code-block:: none
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
This is useful because a simple test like
``'{placeholder}' in format_string``
will fail if the format string contains placeholder formatting
eg ``'{placeholder:.2f}'`` | [
"Determines",
"if",
"format_string",
"contains",
"a",
"placeholder",
"string",
"names",
"or",
"a",
"list",
"of",
"placeholders",
"names",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L673-L719 |
231,151 | ultrabug/py3status | py3status/py3.py | Py3.get_color_names_list | def get_color_names_list(self, format_strings):
"""
Returns a list of color names in ``format_string``.
:param format_strings: Accepts a format string or a list of format strings.
"""
if not format_strings:
return []
if not getattr(self._py3status_module, "thresholds", None):
return []
if isinstance(format_strings, basestring):
format_strings = [format_strings]
names = set()
for string in format_strings:
names.update(self._formatter.get_color_names(string))
return list(names) | python | def get_color_names_list(self, format_strings):
if not format_strings:
return []
if not getattr(self._py3status_module, "thresholds", None):
return []
if isinstance(format_strings, basestring):
format_strings = [format_strings]
names = set()
for string in format_strings:
names.update(self._formatter.get_color_names(string))
return list(names) | [
"def",
"get_color_names_list",
"(",
"self",
",",
"format_strings",
")",
":",
"if",
"not",
"format_strings",
":",
"return",
"[",
"]",
"if",
"not",
"getattr",
"(",
"self",
".",
"_py3status_module",
",",
"\"thresholds\"",
",",
"None",
")",
":",
"return",
"[",
... | Returns a list of color names in ``format_string``.
:param format_strings: Accepts a format string or a list of format strings. | [
"Returns",
"a",
"list",
"of",
"color",
"names",
"in",
"format_string",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L721-L736 |
231,152 | ultrabug/py3status | py3status/py3.py | Py3.get_placeholders_list | def get_placeholders_list(self, format_string, matches=None):
"""
Returns a list of placeholders in ``format_string``.
If ``matches`` is provided then it is used to filter the result
using fnmatch so the following patterns can be used:
.. code-block:: none
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
This is useful because we just get simple placeholder without any
formatting that may be applied to them
eg ``'{placeholder:.2f}'`` will give ``['{placeholder}']``
"""
if format_string not in self._format_placeholders:
placeholders = self._formatter.get_placeholders(format_string)
self._format_placeholders[format_string] = placeholders
else:
placeholders = self._format_placeholders[format_string]
if not matches:
return list(placeholders)
elif isinstance(matches, basestring):
matches = [matches]
# filter matches
found = set()
for match in matches:
for placeholder in placeholders:
if fnmatch(placeholder, match):
found.add(placeholder)
return list(found) | python | def get_placeholders_list(self, format_string, matches=None):
if format_string not in self._format_placeholders:
placeholders = self._formatter.get_placeholders(format_string)
self._format_placeholders[format_string] = placeholders
else:
placeholders = self._format_placeholders[format_string]
if not matches:
return list(placeholders)
elif isinstance(matches, basestring):
matches = [matches]
# filter matches
found = set()
for match in matches:
for placeholder in placeholders:
if fnmatch(placeholder, match):
found.add(placeholder)
return list(found) | [
"def",
"get_placeholders_list",
"(",
"self",
",",
"format_string",
",",
"matches",
"=",
"None",
")",
":",
"if",
"format_string",
"not",
"in",
"self",
".",
"_format_placeholders",
":",
"placeholders",
"=",
"self",
".",
"_formatter",
".",
"get_placeholders",
"(",
... | Returns a list of placeholders in ``format_string``.
If ``matches`` is provided then it is used to filter the result
using fnmatch so the following patterns can be used:
.. code-block:: none
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
This is useful because we just get simple placeholder without any
formatting that may be applied to them
eg ``'{placeholder:.2f}'`` will give ``['{placeholder}']`` | [
"Returns",
"a",
"list",
"of",
"placeholders",
"in",
"format_string",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L738-L773 |
231,153 | ultrabug/py3status | py3status/py3.py | Py3.safe_format | def safe_format(
self, format_string, param_dict=None, force_composite=False, attr_getter=None
):
r"""
Parser for advanced formatting.
Unknown placeholders will be shown in the output eg ``{foo}``.
Square brackets ``[]`` can be used. The content of them will be removed
from the output if there is no valid placeholder contained within.
They can also be nested.
A pipe (vertical bar) ``|`` can be used to divide sections the first
valid section only will be shown in the output.
A backslash ``\`` can be used to escape a character eg ``\[`` will show ``[``
in the output.
``\?`` is special and is used to provide extra commands to the format
string, example ``\?color=#FF00FF``. Multiple commands can be given
using an ampersand ``&`` as a separator, example ``\?color=#FF00FF&show``.
``\?if=<placeholder>`` can be used to check if a placeholder exists. An
exclamation mark ``!`` after the equals sign ``=`` can be used to negate
the condition.
``\?if=<placeholder>=<value>`` can be used to determine if {<placeholder>}
would be replaced with <value>. ``[]`` in <value> don't need to be escaped.
``{<placeholder>}`` will be converted, or removed if it is None or empty.
Formatting can also be applied to the placeholder Eg
``{number:03.2f}``.
example format_string:
``"[[{artist} - ]{title}]|{file}"``
This will show ``artist - title`` if artist is present,
``title`` if title but no artist,
and ``file`` if file is present but not artist or title.
param_dict is a dictionary of placeholders that will be substituted.
If a placeholder is not in the dictionary then if the py3status module
has an attribute with the same name then it will be used.
.. note::
Added in version 3.3
Composites can be included in the param_dict.
The result returned from this function can either be a string in the
case of simple parsing or a Composite if more complex.
If force_composite parameter is True a composite will always be
returned.
attr_getter is a function that will when called with an attribute name
as a parameter will return a value.
"""
try:
return self._formatter.format(
format_string,
self._py3status_module,
param_dict,
force_composite=force_composite,
attr_getter=attr_getter,
)
except Exception:
self._report_exception(u"Invalid format `{}`".format(format_string))
return "invalid format" | python | def safe_format(
self, format_string, param_dict=None, force_composite=False, attr_getter=None
):
r"""
Parser for advanced formatting.
Unknown placeholders will be shown in the output eg ``{foo}``.
Square brackets ``[]`` can be used. The content of them will be removed
from the output if there is no valid placeholder contained within.
They can also be nested.
A pipe (vertical bar) ``|`` can be used to divide sections the first
valid section only will be shown in the output.
A backslash ``\`` can be used to escape a character eg ``\[`` will show ``[``
in the output.
``\?`` is special and is used to provide extra commands to the format
string, example ``\?color=#FF00FF``. Multiple commands can be given
using an ampersand ``&`` as a separator, example ``\?color=#FF00FF&show``.
``\?if=<placeholder>`` can be used to check if a placeholder exists. An
exclamation mark ``!`` after the equals sign ``=`` can be used to negate
the condition.
``\?if=<placeholder>=<value>`` can be used to determine if {<placeholder>}
would be replaced with <value>. ``[]`` in <value> don't need to be escaped.
``{<placeholder>}`` will be converted, or removed if it is None or empty.
Formatting can also be applied to the placeholder Eg
``{number:03.2f}``.
example format_string:
``"[[{artist} - ]{title}]|{file}"``
This will show ``artist - title`` if artist is present,
``title`` if title but no artist,
and ``file`` if file is present but not artist or title.
param_dict is a dictionary of placeholders that will be substituted.
If a placeholder is not in the dictionary then if the py3status module
has an attribute with the same name then it will be used.
.. note::
Added in version 3.3
Composites can be included in the param_dict.
The result returned from this function can either be a string in the
case of simple parsing or a Composite if more complex.
If force_composite parameter is True a composite will always be
returned.
attr_getter is a function that will when called with an attribute name
as a parameter will return a value.
"""
try:
return self._formatter.format(
format_string,
self._py3status_module,
param_dict,
force_composite=force_composite,
attr_getter=attr_getter,
)
except Exception:
self._report_exception(u"Invalid format `{}`".format(format_string))
return "invalid format" | [
"def",
"safe_format",
"(",
"self",
",",
"format_string",
",",
"param_dict",
"=",
"None",
",",
"force_composite",
"=",
"False",
",",
"attr_getter",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_formatter",
".",
"format",
"(",
"format_string",
... | r"""
Parser for advanced formatting.
Unknown placeholders will be shown in the output eg ``{foo}``.
Square brackets ``[]`` can be used. The content of them will be removed
from the output if there is no valid placeholder contained within.
They can also be nested.
A pipe (vertical bar) ``|`` can be used to divide sections the first
valid section only will be shown in the output.
A backslash ``\`` can be used to escape a character eg ``\[`` will show ``[``
in the output.
``\?`` is special and is used to provide extra commands to the format
string, example ``\?color=#FF00FF``. Multiple commands can be given
using an ampersand ``&`` as a separator, example ``\?color=#FF00FF&show``.
``\?if=<placeholder>`` can be used to check if a placeholder exists. An
exclamation mark ``!`` after the equals sign ``=`` can be used to negate
the condition.
``\?if=<placeholder>=<value>`` can be used to determine if {<placeholder>}
would be replaced with <value>. ``[]`` in <value> don't need to be escaped.
``{<placeholder>}`` will be converted, or removed if it is None or empty.
Formatting can also be applied to the placeholder Eg
``{number:03.2f}``.
example format_string:
``"[[{artist} - ]{title}]|{file}"``
This will show ``artist - title`` if artist is present,
``title`` if title but no artist,
and ``file`` if file is present but not artist or title.
param_dict is a dictionary of placeholders that will be substituted.
If a placeholder is not in the dictionary then if the py3status module
has an attribute with the same name then it will be used.
.. note::
Added in version 3.3
Composites can be included in the param_dict.
The result returned from this function can either be a string in the
case of simple parsing or a Composite if more complex.
If force_composite parameter is True a composite will always be
returned.
attr_getter is a function that will when called with an attribute name
as a parameter will return a value. | [
"r",
"Parser",
"for",
"advanced",
"formatting",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L793-L862 |
231,154 | ultrabug/py3status | py3status/py3.py | Py3.check_commands | def check_commands(self, cmd_list):
"""
Checks to see if commands in list are available using ``which``.
returns the first available command.
If a string is passed then that command will be checked for.
"""
# if a string is passed then convert it to a list. This prevents an
# easy mistake that could be made
if isinstance(cmd_list, basestring):
cmd_list = [cmd_list]
for cmd in cmd_list:
if self.command_run("which {}".format(cmd)) == 0:
return cmd | python | def check_commands(self, cmd_list):
# if a string is passed then convert it to a list. This prevents an
# easy mistake that could be made
if isinstance(cmd_list, basestring):
cmd_list = [cmd_list]
for cmd in cmd_list:
if self.command_run("which {}".format(cmd)) == 0:
return cmd | [
"def",
"check_commands",
"(",
"self",
",",
"cmd_list",
")",
":",
"# if a string is passed then convert it to a list. This prevents an",
"# easy mistake that could be made",
"if",
"isinstance",
"(",
"cmd_list",
",",
"basestring",
")",
":",
"cmd_list",
"=",
"[",
"cmd_list",
... | Checks to see if commands in list are available using ``which``.
returns the first available command.
If a string is passed then that command will be checked for. | [
"Checks",
"to",
"see",
"if",
"commands",
"in",
"list",
"are",
"available",
"using",
"which",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L942-L957 |
231,155 | ultrabug/py3status | py3status/py3.py | Py3.command_run | def command_run(self, command):
"""
Runs a command and returns the exit code.
The command can either be supplied as a sequence or string.
An Exception is raised if an error occurs
"""
# convert the command to sequence if a string
if isinstance(command, basestring):
command = shlex.split(command)
try:
return Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True).wait()
except Exception as e:
# make a pretty command for error loggings and...
if isinstance(command, basestring):
pretty_cmd = command
else:
pretty_cmd = " ".join(command)
msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e.errno)
raise exceptions.CommandError(msg, error_code=e.errno) | python | def command_run(self, command):
# convert the command to sequence if a string
if isinstance(command, basestring):
command = shlex.split(command)
try:
return Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True).wait()
except Exception as e:
# make a pretty command for error loggings and...
if isinstance(command, basestring):
pretty_cmd = command
else:
pretty_cmd = " ".join(command)
msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e.errno)
raise exceptions.CommandError(msg, error_code=e.errno) | [
"def",
"command_run",
"(",
"self",
",",
"command",
")",
":",
"# convert the command to sequence if a string",
"if",
"isinstance",
"(",
"command",
",",
"basestring",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"try",
":",
"return",
"Po... | Runs a command and returns the exit code.
The command can either be supplied as a sequence or string.
An Exception is raised if an error occurs | [
"Runs",
"a",
"command",
"and",
"returns",
"the",
"exit",
"code",
".",
"The",
"command",
"can",
"either",
"be",
"supplied",
"as",
"a",
"sequence",
"or",
"string",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L959-L978 |
231,156 | ultrabug/py3status | py3status/py3.py | Py3.command_output | def command_output(
self, command, shell=False, capture_stderr=False, localized=False
):
"""
Run a command and return its output as unicode.
The command can either be supplied as a sequence or string.
:param command: command to run can be a str or list
:param shell: if `True` then command is run through the shell
:param capture_stderr: if `True` then STDERR is piped to STDOUT
:param localized: if `False` then command is forced to use its default (English) locale
A CommandError is raised if an error occurs
"""
# make a pretty command for error loggings and...
if isinstance(command, basestring):
pretty_cmd = command
else:
pretty_cmd = " ".join(command)
# convert the non-shell command to sequence if it is a string
if not shell and isinstance(command, basestring):
command = shlex.split(command)
stderr = STDOUT if capture_stderr else PIPE
env = self._english_env if not localized else None
try:
process = Popen(
command,
stdout=PIPE,
stderr=stderr,
close_fds=True,
universal_newlines=True,
shell=shell,
env=env,
)
except Exception as e:
msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e)
raise exceptions.CommandError(msg, error_code=e.errno)
output, error = process.communicate()
if self._is_python_2 and isinstance(output, str):
output = output.decode("utf-8")
error = error.decode("utf-8")
retcode = process.poll()
if retcode:
# under certain conditions a successfully run command may get a
# return code of -15 even though correct output was returned see
# #664. This issue seems to be related to arch linux but the
# reason is not entirely clear.
if retcode == -15:
msg = "Command `{cmd}` returned SIGTERM (ignoring)"
self.log(msg.format(cmd=pretty_cmd))
else:
msg = "Command `{cmd}` returned non-zero exit status {error}"
output_oneline = output.replace("\n", " ")
if output_oneline:
msg += " ({output})"
msg = msg.format(cmd=pretty_cmd, error=retcode, output=output_oneline)
raise exceptions.CommandError(
msg, error_code=retcode, error=error, output=output
)
return output | python | def command_output(
self, command, shell=False, capture_stderr=False, localized=False
):
# make a pretty command for error loggings and...
if isinstance(command, basestring):
pretty_cmd = command
else:
pretty_cmd = " ".join(command)
# convert the non-shell command to sequence if it is a string
if not shell and isinstance(command, basestring):
command = shlex.split(command)
stderr = STDOUT if capture_stderr else PIPE
env = self._english_env if not localized else None
try:
process = Popen(
command,
stdout=PIPE,
stderr=stderr,
close_fds=True,
universal_newlines=True,
shell=shell,
env=env,
)
except Exception as e:
msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e)
raise exceptions.CommandError(msg, error_code=e.errno)
output, error = process.communicate()
if self._is_python_2 and isinstance(output, str):
output = output.decode("utf-8")
error = error.decode("utf-8")
retcode = process.poll()
if retcode:
# under certain conditions a successfully run command may get a
# return code of -15 even though correct output was returned see
# #664. This issue seems to be related to arch linux but the
# reason is not entirely clear.
if retcode == -15:
msg = "Command `{cmd}` returned SIGTERM (ignoring)"
self.log(msg.format(cmd=pretty_cmd))
else:
msg = "Command `{cmd}` returned non-zero exit status {error}"
output_oneline = output.replace("\n", " ")
if output_oneline:
msg += " ({output})"
msg = msg.format(cmd=pretty_cmd, error=retcode, output=output_oneline)
raise exceptions.CommandError(
msg, error_code=retcode, error=error, output=output
)
return output | [
"def",
"command_output",
"(",
"self",
",",
"command",
",",
"shell",
"=",
"False",
",",
"capture_stderr",
"=",
"False",
",",
"localized",
"=",
"False",
")",
":",
"# make a pretty command for error loggings and...",
"if",
"isinstance",
"(",
"command",
",",
"basestri... | Run a command and return its output as unicode.
The command can either be supplied as a sequence or string.
:param command: command to run can be a str or list
:param shell: if `True` then command is run through the shell
:param capture_stderr: if `True` then STDERR is piped to STDOUT
:param localized: if `False` then command is forced to use its default (English) locale
A CommandError is raised if an error occurs | [
"Run",
"a",
"command",
"and",
"return",
"its",
"output",
"as",
"unicode",
".",
"The",
"command",
"can",
"either",
"be",
"supplied",
"as",
"a",
"sequence",
"or",
"string",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L980-L1042 |
231,157 | ultrabug/py3status | py3status/py3.py | Py3._storage_init | def _storage_init(self):
"""
Ensure that storage is initialized.
"""
if not self._storage.initialized:
self._storage.init(self._module._py3_wrapper, self._is_python_2) | python | def _storage_init(self):
if not self._storage.initialized:
self._storage.init(self._module._py3_wrapper, self._is_python_2) | [
"def",
"_storage_init",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_storage",
".",
"initialized",
":",
"self",
".",
"_storage",
".",
"init",
"(",
"self",
".",
"_module",
".",
"_py3_wrapper",
",",
"self",
".",
"_is_python_2",
")"
] | Ensure that storage is initialized. | [
"Ensure",
"that",
"storage",
"is",
"initialized",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1044-L1049 |
231,158 | ultrabug/py3status | py3status/py3.py | Py3.storage_set | def storage_set(self, key, value):
"""
Store a value for the module.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_set(module_name, key, value) | python | def storage_set(self, key, value):
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_set(module_name, key, value) | [
"def",
"storage_set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_module",
":",
"return",
"self",
".",
"_storage_init",
"(",
")",
"module_name",
"=",
"self",
".",
"_module",
".",
"module_full_name",
"return",
"self",
".",... | Store a value for the module. | [
"Store",
"a",
"value",
"for",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1051-L1059 |
231,159 | ultrabug/py3status | py3status/py3.py | Py3.storage_get | def storage_get(self, key):
"""
Retrieve a value for the module.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_get(module_name, key) | python | def storage_get(self, key):
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_get(module_name, key) | [
"def",
"storage_get",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"_module",
":",
"return",
"self",
".",
"_storage_init",
"(",
")",
"module_name",
"=",
"self",
".",
"_module",
".",
"module_full_name",
"return",
"self",
".",
"_storage",
"... | Retrieve a value for the module. | [
"Retrieve",
"a",
"value",
"for",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1061-L1069 |
231,160 | ultrabug/py3status | py3status/py3.py | Py3.storage_del | def storage_del(self, key=None):
"""
Remove the value stored with the key from storage.
If key is not supplied then all values for the module are removed.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_del(module_name, key=key) | python | def storage_del(self, key=None):
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_del(module_name, key=key) | [
"def",
"storage_del",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_module",
":",
"return",
"self",
".",
"_storage_init",
"(",
")",
"module_name",
"=",
"self",
".",
"_module",
".",
"module_full_name",
"return",
"self",
".",
... | Remove the value stored with the key from storage.
If key is not supplied then all values for the module are removed. | [
"Remove",
"the",
"value",
"stored",
"with",
"the",
"key",
"from",
"storage",
".",
"If",
"key",
"is",
"not",
"supplied",
"then",
"all",
"values",
"for",
"the",
"module",
"are",
"removed",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1071-L1080 |
231,161 | ultrabug/py3status | py3status/py3.py | Py3.storage_keys | def storage_keys(self):
"""
Return a list of the keys for values stored for the module.
Keys will contain the following metadata entries:
- '_ctime': storage creation timestamp
- '_mtime': storage last modification timestamp
"""
if not self._module:
return []
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_keys(module_name) | python | def storage_keys(self):
if not self._module:
return []
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_keys(module_name) | [
"def",
"storage_keys",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_module",
":",
"return",
"[",
"]",
"self",
".",
"_storage_init",
"(",
")",
"module_name",
"=",
"self",
".",
"_module",
".",
"module_full_name",
"return",
"self",
".",
"_storage",
".... | Return a list of the keys for values stored for the module.
Keys will contain the following metadata entries:
- '_ctime': storage creation timestamp
- '_mtime': storage last modification timestamp | [
"Return",
"a",
"list",
"of",
"the",
"keys",
"for",
"values",
"stored",
"for",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1082-L1094 |
231,162 | ultrabug/py3status | py3status/py3.py | Py3.storage_items | def storage_items(self):
"""
Return key, value pairs of the stored data for the module.
Keys will contain the following metadata entries:
- '_ctime': storage creation timestamp
- '_mtime': storage last modification timestamp
"""
if not self._module:
return {}.items()
self._storage_init()
items = []
module_name = self._module.module_full_name
for key in self._storage.storage_keys(module_name):
value = self._storage.storage_get(module_name, key)
items.add((key, value))
return items | python | def storage_items(self):
if not self._module:
return {}.items()
self._storage_init()
items = []
module_name = self._module.module_full_name
for key in self._storage.storage_keys(module_name):
value = self._storage.storage_get(module_name, key)
items.add((key, value))
return items | [
"def",
"storage_items",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_module",
":",
"return",
"{",
"}",
".",
"items",
"(",
")",
"self",
".",
"_storage_init",
"(",
")",
"items",
"=",
"[",
"]",
"module_name",
"=",
"self",
".",
"_module",
".",
"m... | Return key, value pairs of the stored data for the module.
Keys will contain the following metadata entries:
- '_ctime': storage creation timestamp
- '_mtime': storage last modification timestamp | [
"Return",
"key",
"value",
"pairs",
"of",
"the",
"stored",
"data",
"for",
"the",
"module",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1096-L1112 |
231,163 | ultrabug/py3status | py3status/py3.py | Py3.play_sound | def play_sound(self, sound_file):
"""
Plays sound_file if possible.
"""
self.stop_sound()
if sound_file:
cmd = self.check_commands(["ffplay", "paplay", "play"])
if cmd:
if cmd == "ffplay":
cmd = "ffplay -autoexit -nodisp -loglevel 0"
sound_file = os.path.expanduser(sound_file)
c = shlex.split("{} {}".format(cmd, sound_file))
self._audio = Popen(c) | python | def play_sound(self, sound_file):
self.stop_sound()
if sound_file:
cmd = self.check_commands(["ffplay", "paplay", "play"])
if cmd:
if cmd == "ffplay":
cmd = "ffplay -autoexit -nodisp -loglevel 0"
sound_file = os.path.expanduser(sound_file)
c = shlex.split("{} {}".format(cmd, sound_file))
self._audio = Popen(c) | [
"def",
"play_sound",
"(",
"self",
",",
"sound_file",
")",
":",
"self",
".",
"stop_sound",
"(",
")",
"if",
"sound_file",
":",
"cmd",
"=",
"self",
".",
"check_commands",
"(",
"[",
"\"ffplay\"",
",",
"\"paplay\"",
",",
"\"play\"",
"]",
")",
"if",
"cmd",
"... | Plays sound_file if possible. | [
"Plays",
"sound_file",
"if",
"possible",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1114-L1126 |
231,164 | ultrabug/py3status | py3status/py3.py | Py3.threshold_get_color | def threshold_get_color(self, value, name=None):
"""
Obtain color for a value using thresholds.
The value will be checked against any defined thresholds. These should
have been set in the i3status configuration. If more than one
threshold is needed for a module then the name can also be supplied.
If the user has not supplied a named threshold but has defined a
general one that will be used.
If the gradients config parameter is True then rather than sharp
thresholds we will use a gradient between the color values.
:param value: numerical value to be graded
:param name: accepts a string, otherwise 'threshold'
accepts 3-tuples to allow name with different
values eg ('name', 'key', 'thresholds')
"""
# If first run then process the threshold data.
if self._thresholds is None:
self._thresholds_init()
# allow name with different values
if isinstance(name, tuple):
name_used = "{}/{}".format(name[0], name[1])
if name[2]:
self._thresholds[name_used] = [
(x[0], self._get_color(x[1])) for x in name[2]
]
name = name[0]
else:
# if name not in thresholds info then use defaults
name_used = name
if name_used not in self._thresholds:
name_used = None
# convert value to int/float
thresholds = self._thresholds.get(name_used)
color = None
try:
value = float(value)
except (TypeError, ValueError):
pass
# skip on empty thresholds/values
if not thresholds or value in [None, ""]:
pass
elif isinstance(value, basestring):
# string
for threshold in thresholds:
if value == threshold[0]:
color = threshold[1]
break
else:
# int/float
try:
if self._get_config_setting("gradients"):
try:
colors, minimum, maximum = self._threshold_gradients[name_used]
except KeyError:
colors = self._gradients.make_threshold_gradient(
self, thresholds
)
minimum = min(thresholds)[0]
maximum = max(thresholds)[0]
self._threshold_gradients[name_used] = (
colors,
minimum,
maximum,
)
if value < minimum:
color = colors[0]
elif value > maximum:
color = colors[-1]
else:
value -= minimum
col_index = int(
((len(colors) - 1) / (maximum - minimum)) * value
)
color = colors[col_index]
else:
color = thresholds[0][1]
for threshold in thresholds:
if value >= threshold[0]:
color = threshold[1]
else:
break
except TypeError:
color = None
# save color so it can be accessed via safe_format()
if name:
color_name = "color_threshold_%s" % name
else:
color_name = "color_threshold"
setattr(self._py3status_module, color_name, color)
return color | python | def threshold_get_color(self, value, name=None):
# If first run then process the threshold data.
if self._thresholds is None:
self._thresholds_init()
# allow name with different values
if isinstance(name, tuple):
name_used = "{}/{}".format(name[0], name[1])
if name[2]:
self._thresholds[name_used] = [
(x[0], self._get_color(x[1])) for x in name[2]
]
name = name[0]
else:
# if name not in thresholds info then use defaults
name_used = name
if name_used not in self._thresholds:
name_used = None
# convert value to int/float
thresholds = self._thresholds.get(name_used)
color = None
try:
value = float(value)
except (TypeError, ValueError):
pass
# skip on empty thresholds/values
if not thresholds or value in [None, ""]:
pass
elif isinstance(value, basestring):
# string
for threshold in thresholds:
if value == threshold[0]:
color = threshold[1]
break
else:
# int/float
try:
if self._get_config_setting("gradients"):
try:
colors, minimum, maximum = self._threshold_gradients[name_used]
except KeyError:
colors = self._gradients.make_threshold_gradient(
self, thresholds
)
minimum = min(thresholds)[0]
maximum = max(thresholds)[0]
self._threshold_gradients[name_used] = (
colors,
minimum,
maximum,
)
if value < minimum:
color = colors[0]
elif value > maximum:
color = colors[-1]
else:
value -= minimum
col_index = int(
((len(colors) - 1) / (maximum - minimum)) * value
)
color = colors[col_index]
else:
color = thresholds[0][1]
for threshold in thresholds:
if value >= threshold[0]:
color = threshold[1]
else:
break
except TypeError:
color = None
# save color so it can be accessed via safe_format()
if name:
color_name = "color_threshold_%s" % name
else:
color_name = "color_threshold"
setattr(self._py3status_module, color_name, color)
return color | [
"def",
"threshold_get_color",
"(",
"self",
",",
"value",
",",
"name",
"=",
"None",
")",
":",
"# If first run then process the threshold data.",
"if",
"self",
".",
"_thresholds",
"is",
"None",
":",
"self",
".",
"_thresholds_init",
"(",
")",
"# allow name with differe... | Obtain color for a value using thresholds.
The value will be checked against any defined thresholds. These should
have been set in the i3status configuration. If more than one
threshold is needed for a module then the name can also be supplied.
If the user has not supplied a named threshold but has defined a
general one that will be used.
If the gradients config parameter is True then rather than sharp
thresholds we will use a gradient between the color values.
:param value: numerical value to be graded
:param name: accepts a string, otherwise 'threshold'
accepts 3-tuples to allow name with different
values eg ('name', 'key', 'thresholds') | [
"Obtain",
"color",
"for",
"a",
"value",
"using",
"thresholds",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1136-L1234 |
231,165 | ultrabug/py3status | py3status/py3.py | Py3.request | def request(
self,
url,
params=None,
data=None,
headers=None,
timeout=None,
auth=None,
cookiejar=None,
):
"""
Make a request to a url and retrieve the results.
If the headers parameter does not provide an 'User-Agent' key, one will
be added automatically following the convention:
py3status/<version> <per session random uuid>
:param url: url to request eg `http://example.com`
:param params: extra query string parameters as a dict
:param data: POST data as a dict. If this is not supplied the GET method will be used
:param headers: http headers to be added to the request as a dict
:param timeout: timeout for the request in seconds
:param auth: authentication info as tuple `(username, password)`
:param cookiejar: an object of a CookieJar subclass
:returns: HttpResponse
"""
# The aim of this function is to be a limited lightweight replacement
# for the requests library but using only pythons standard libs.
# IMPORTANT NOTICE
# This function is excluded from private variable hiding as it is
# likely to need api keys etc which people may have obfuscated.
# Therefore it is important that no logging is done in this function
# that might reveal this information.
if headers is None:
headers = {}
if timeout is None:
timeout = getattr(self._py3status_module, "request_timeout", 10)
if "User-Agent" not in headers:
headers["User-Agent"] = "py3status/{} {}".format(version, self._uid)
return HttpResponse(
url,
params=params,
data=data,
headers=headers,
timeout=timeout,
auth=auth,
cookiejar=cookiejar,
) | python | def request(
self,
url,
params=None,
data=None,
headers=None,
timeout=None,
auth=None,
cookiejar=None,
):
# The aim of this function is to be a limited lightweight replacement
# for the requests library but using only pythons standard libs.
# IMPORTANT NOTICE
# This function is excluded from private variable hiding as it is
# likely to need api keys etc which people may have obfuscated.
# Therefore it is important that no logging is done in this function
# that might reveal this information.
if headers is None:
headers = {}
if timeout is None:
timeout = getattr(self._py3status_module, "request_timeout", 10)
if "User-Agent" not in headers:
headers["User-Agent"] = "py3status/{} {}".format(version, self._uid)
return HttpResponse(
url,
params=params,
data=data,
headers=headers,
timeout=timeout,
auth=auth,
cookiejar=cookiejar,
) | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"cookiejar",
"=",
"None",
",",
")",
":",
"# The aim of this func... | Make a request to a url and retrieve the results.
If the headers parameter does not provide an 'User-Agent' key, one will
be added automatically following the convention:
py3status/<version> <per session random uuid>
:param url: url to request eg `http://example.com`
:param params: extra query string parameters as a dict
:param data: POST data as a dict. If this is not supplied the GET method will be used
:param headers: http headers to be added to the request as a dict
:param timeout: timeout for the request in seconds
:param auth: authentication info as tuple `(username, password)`
:param cookiejar: an object of a CookieJar subclass
:returns: HttpResponse | [
"Make",
"a",
"request",
"to",
"a",
"url",
"and",
"retrieve",
"the",
"results",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L1236-L1291 |
231,166 | ultrabug/py3status | py3status/modules/wwan_status.py | Py3status._get_ip | def _get_ip(self, interface):
"""
Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string
"""
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]["addr"]
return "" | python | def _get_ip(self, interface):
if interface in ni.interfaces():
addresses = ni.ifaddresses(interface)
if ni.AF_INET in addresses:
return addresses[ni.AF_INET][0]["addr"]
return "" | [
"def",
"_get_ip",
"(",
"self",
",",
"interface",
")",
":",
"if",
"interface",
"in",
"ni",
".",
"interfaces",
"(",
")",
":",
"addresses",
"=",
"ni",
".",
"ifaddresses",
"(",
"interface",
")",
"if",
"ni",
".",
"AF_INET",
"in",
"addresses",
":",
"return",... | Returns the interface's IPv4 address if device exists and has a valid
ip address. Otherwise, returns an empty string | [
"Returns",
"the",
"interface",
"s",
"IPv4",
"address",
"if",
"device",
"exists",
"and",
"has",
"a",
"valid",
"ip",
"address",
".",
"Otherwise",
"returns",
"an",
"empty",
"string"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/wwan_status.py#L168-L177 |
231,167 | ultrabug/py3status | py3status/modules/battery_level.py | Py3status.on_click | def on_click(self, event):
"""
Display a notification following the specified format
"""
if not self.notification:
return
if self.charging:
format = self.format_notify_charging
else:
format = self.format_notify_discharging
message = self.py3.safe_format(
format,
dict(
ascii_bar=self.ascii_bar,
icon=self.icon,
percent=self.percent_charged,
time_remaining=self.time_remaining,
),
)
if message:
self.py3.notify_user(message, "info") | python | def on_click(self, event):
if not self.notification:
return
if self.charging:
format = self.format_notify_charging
else:
format = self.format_notify_discharging
message = self.py3.safe_format(
format,
dict(
ascii_bar=self.ascii_bar,
icon=self.icon,
percent=self.percent_charged,
time_remaining=self.time_remaining,
),
)
if message:
self.py3.notify_user(message, "info") | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"notification",
":",
"return",
"if",
"self",
".",
"charging",
":",
"format",
"=",
"self",
".",
"format_notify_charging",
"else",
":",
"format",
"=",
"self",
".",
"format_no... | Display a notification following the specified format | [
"Display",
"a",
"notification",
"following",
"the",
"specified",
"format"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/battery_level.py#L190-L213 |
231,168 | ultrabug/py3status | py3status/modules/battery_level.py | Py3status._extract_battery_info_from_acpi | def _extract_battery_info_from_acpi(self):
"""
Get the battery info from acpi
# Example acpi -bi raw output (Discharging):
Battery 0: Discharging, 94%, 09:23:28 remaining
Battery 0: design capacity 5703 mAh, last full capacity 5283 mAh = 92%
Battery 1: Unknown, 98%
Battery 1: design capacity 1880 mAh, last full capacity 1370 mAh = 72%
# Example Charging
Battery 0: Charging, 96%, 00:20:40 until charged
Battery 0: design capacity 5566 mAh, last full capacity 5156 mAh = 92%
Battery 1: Unknown, 98%
Battery 1: design capacity 1879 mAh, last full capacity 1370 mAh = 72%
"""
def _parse_battery_info(acpi_battery_lines):
battery = {}
battery["percent_charged"] = int(
findall("(?<= )(\d+)(?=%)", acpi_battery_lines[0])[0]
)
battery["charging"] = "Charging" in acpi_battery_lines[0]
battery["capacity"] = int(
findall("(?<= )(\d+)(?= mAh)", acpi_battery_lines[1])[1]
)
# ACPI only shows time remaining if battery is discharging or
# charging
try:
battery["time_remaining"] = "".join(
findall(
"(?<=, )(\d+:\d+:\d+)(?= remaining)|"
"(?<=, )(\d+:\d+:\d+)(?= until)",
acpi_battery_lines[0],
)[0]
)
except IndexError:
battery["time_remaining"] = FULLY_CHARGED
return battery
acpi_list = self.py3.command_output(["acpi", "-b", "-i"]).splitlines()
# Separate the output because each pair of lines corresponds to a
# single battery. Now the list index will correspond to the index of
# the battery we want to look at
acpi_list = [acpi_list[i : i + 2] for i in range(0, len(acpi_list) - 1, 2)]
return [_parse_battery_info(battery) for battery in acpi_list] | python | def _extract_battery_info_from_acpi(self):
def _parse_battery_info(acpi_battery_lines):
battery = {}
battery["percent_charged"] = int(
findall("(?<= )(\d+)(?=%)", acpi_battery_lines[0])[0]
)
battery["charging"] = "Charging" in acpi_battery_lines[0]
battery["capacity"] = int(
findall("(?<= )(\d+)(?= mAh)", acpi_battery_lines[1])[1]
)
# ACPI only shows time remaining if battery is discharging or
# charging
try:
battery["time_remaining"] = "".join(
findall(
"(?<=, )(\d+:\d+:\d+)(?= remaining)|"
"(?<=, )(\d+:\d+:\d+)(?= until)",
acpi_battery_lines[0],
)[0]
)
except IndexError:
battery["time_remaining"] = FULLY_CHARGED
return battery
acpi_list = self.py3.command_output(["acpi", "-b", "-i"]).splitlines()
# Separate the output because each pair of lines corresponds to a
# single battery. Now the list index will correspond to the index of
# the battery we want to look at
acpi_list = [acpi_list[i : i + 2] for i in range(0, len(acpi_list) - 1, 2)]
return [_parse_battery_info(battery) for battery in acpi_list] | [
"def",
"_extract_battery_info_from_acpi",
"(",
"self",
")",
":",
"def",
"_parse_battery_info",
"(",
"acpi_battery_lines",
")",
":",
"battery",
"=",
"{",
"}",
"battery",
"[",
"\"percent_charged\"",
"]",
"=",
"int",
"(",
"findall",
"(",
"\"(?<= )(\\d+)(?=%)\"",
",",... | Get the battery info from acpi
# Example acpi -bi raw output (Discharging):
Battery 0: Discharging, 94%, 09:23:28 remaining
Battery 0: design capacity 5703 mAh, last full capacity 5283 mAh = 92%
Battery 1: Unknown, 98%
Battery 1: design capacity 1880 mAh, last full capacity 1370 mAh = 72%
# Example Charging
Battery 0: Charging, 96%, 00:20:40 until charged
Battery 0: design capacity 5566 mAh, last full capacity 5156 mAh = 92%
Battery 1: Unknown, 98%
Battery 1: design capacity 1879 mAh, last full capacity 1370 mAh = 72% | [
"Get",
"the",
"battery",
"info",
"from",
"acpi"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/battery_level.py#L215-L264 |
231,169 | ultrabug/py3status | doc/example_module.py | Py3status.example_method | def example_method(self, i3s_output_list, i3s_config):
"""
This method will return an empty text message
so it will NOT be displayed on your i3bar.
If you want something displayed you should write something
in the 'full_text' key of your response.
See the i3bar protocol spec for more information:
http://i3wm.org/docs/i3bar-protocol.html
"""
# create out output text replacing the placeholder
full_text = self.format.format(output='example')
response = {
'cached_until': time() + self.cache_timeout,
'full_text': full_text
}
return response | python | def example_method(self, i3s_output_list, i3s_config):
# create out output text replacing the placeholder
full_text = self.format.format(output='example')
response = {
'cached_until': time() + self.cache_timeout,
'full_text': full_text
}
return response | [
"def",
"example_method",
"(",
"self",
",",
"i3s_output_list",
",",
"i3s_config",
")",
":",
"# create out output text replacing the placeholder",
"full_text",
"=",
"self",
".",
"format",
".",
"format",
"(",
"output",
"=",
"'example'",
")",
"response",
"=",
"{",
"'c... | This method will return an empty text message
so it will NOT be displayed on your i3bar.
If you want something displayed you should write something
in the 'full_text' key of your response.
See the i3bar protocol spec for more information:
http://i3wm.org/docs/i3bar-protocol.html | [
"This",
"method",
"will",
"return",
"an",
"empty",
"text",
"message",
"so",
"it",
"will",
"NOT",
"be",
"displayed",
"on",
"your",
"i3bar",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/doc/example_module.py#L104-L121 |
231,170 | ultrabug/py3status | py3status/modules/whatismyip.py | Py3status.on_click | def on_click(self, event):
"""
Toggle between display modes 'ip' and 'status'
"""
button = event["button"]
if button == self.button_toggle:
self.toggled = True
if self.mode == "ip":
self.mode = "status"
else:
self.mode = "ip"
elif button == self.button_refresh:
self.idle_time = 0
else:
self.py3.prevent_refresh() | python | def on_click(self, event):
button = event["button"]
if button == self.button_toggle:
self.toggled = True
if self.mode == "ip":
self.mode = "status"
else:
self.mode = "ip"
elif button == self.button_refresh:
self.idle_time = 0
else:
self.py3.prevent_refresh() | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"button",
"=",
"event",
"[",
"\"button\"",
"]",
"if",
"button",
"==",
"self",
".",
"button_toggle",
":",
"self",
".",
"toggled",
"=",
"True",
"if",
"self",
".",
"mode",
"==",
"\"ip\"",
":",
"sel... | Toggle between display modes 'ip' and 'status' | [
"Toggle",
"between",
"display",
"modes",
"ip",
"and",
"status"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/whatismyip.py#L162-L176 |
231,171 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._get_layout | def _get_layout(self):
"""
Get the outputs layout from xrandr and try to detect the
currently active layout as best as we can on start.
"""
connected = list()
active_layout = list()
disconnected = list()
layout = OrderedDict(
{"connected": OrderedDict(), "disconnected": OrderedDict()}
)
current = self.py3.command_output("xrandr")
for line in current.splitlines():
try:
s = line.split(" ")
infos = line[line.find("(") :]
if s[1] == "connected":
output, state, mode = s[0], s[1], None
for index, x in enumerate(s[2:], 2):
if "x" in x and "+" in x:
mode = x
active_layout.append(output)
infos = line[line.find(s[index + 1]) :]
break
elif "(" in x:
break
connected.append(output)
elif s[1] == "disconnected":
output, state, mode = s[0], s[1], None
disconnected.append(output)
else:
continue
except Exception as err:
self.py3.log('xrandr error="{}"'.format(err))
else:
layout[state][output] = {"infos": infos, "mode": mode, "state": state}
# initialize the active layout
if self.active_layout is None:
self.active_comb = tuple(active_layout)
self.active_layout = self._get_string_and_set_width(
tuple(active_layout), self.active_mode
)
return layout | python | def _get_layout(self):
connected = list()
active_layout = list()
disconnected = list()
layout = OrderedDict(
{"connected": OrderedDict(), "disconnected": OrderedDict()}
)
current = self.py3.command_output("xrandr")
for line in current.splitlines():
try:
s = line.split(" ")
infos = line[line.find("(") :]
if s[1] == "connected":
output, state, mode = s[0], s[1], None
for index, x in enumerate(s[2:], 2):
if "x" in x and "+" in x:
mode = x
active_layout.append(output)
infos = line[line.find(s[index + 1]) :]
break
elif "(" in x:
break
connected.append(output)
elif s[1] == "disconnected":
output, state, mode = s[0], s[1], None
disconnected.append(output)
else:
continue
except Exception as err:
self.py3.log('xrandr error="{}"'.format(err))
else:
layout[state][output] = {"infos": infos, "mode": mode, "state": state}
# initialize the active layout
if self.active_layout is None:
self.active_comb = tuple(active_layout)
self.active_layout = self._get_string_and_set_width(
tuple(active_layout), self.active_mode
)
return layout | [
"def",
"_get_layout",
"(",
"self",
")",
":",
"connected",
"=",
"list",
"(",
")",
"active_layout",
"=",
"list",
"(",
")",
"disconnected",
"=",
"list",
"(",
")",
"layout",
"=",
"OrderedDict",
"(",
"{",
"\"connected\"",
":",
"OrderedDict",
"(",
")",
",",
... | Get the outputs layout from xrandr and try to detect the
currently active layout as best as we can on start. | [
"Get",
"the",
"outputs",
"layout",
"from",
"xrandr",
"and",
"try",
"to",
"detect",
"the",
"currently",
"active",
"layout",
"as",
"best",
"as",
"we",
"can",
"on",
"start",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L193-L238 |
231,172 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._set_available_combinations | def _set_available_combinations(self):
"""
Generate all connected outputs combinations and
set the max display width while iterating.
"""
available = set()
combinations_map = {}
whitelist = None
if self.output_combinations:
whitelist = self.output_combinations.split("|")
self.max_width = 0
for output in range(len(self.layout["connected"])):
for comb in combinations(self.layout["connected"], output + 1):
for mode in ["clone", "extend"]:
string = self._get_string_and_set_width(comb, mode)
if whitelist and string not in whitelist:
continue
if len(comb) == 1:
combinations_map[string] = (comb, None)
else:
combinations_map[string] = (comb, mode)
available.add(string)
# Preserve the order in which user defined the output combinations
if whitelist:
available = reversed([comb for comb in whitelist if comb in available])
self.available_combinations = deque(available)
self.combinations_map = combinations_map | python | def _set_available_combinations(self):
available = set()
combinations_map = {}
whitelist = None
if self.output_combinations:
whitelist = self.output_combinations.split("|")
self.max_width = 0
for output in range(len(self.layout["connected"])):
for comb in combinations(self.layout["connected"], output + 1):
for mode in ["clone", "extend"]:
string = self._get_string_and_set_width(comb, mode)
if whitelist and string not in whitelist:
continue
if len(comb) == 1:
combinations_map[string] = (comb, None)
else:
combinations_map[string] = (comb, mode)
available.add(string)
# Preserve the order in which user defined the output combinations
if whitelist:
available = reversed([comb for comb in whitelist if comb in available])
self.available_combinations = deque(available)
self.combinations_map = combinations_map | [
"def",
"_set_available_combinations",
"(",
"self",
")",
":",
"available",
"=",
"set",
"(",
")",
"combinations_map",
"=",
"{",
"}",
"whitelist",
"=",
"None",
"if",
"self",
".",
"output_combinations",
":",
"whitelist",
"=",
"self",
".",
"output_combinations",
".... | Generate all connected outputs combinations and
set the max display width while iterating. | [
"Generate",
"all",
"connected",
"outputs",
"combinations",
"and",
"set",
"the",
"max",
"display",
"width",
"while",
"iterating",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L240-L270 |
231,173 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._get_string_and_set_width | def _get_string_and_set_width(self, combination, mode):
"""
Construct the string to be displayed and record the max width.
"""
show = "{}".format(self._separator(mode)).join(combination)
show = show.rstrip("{}".format(self._separator(mode)))
self.max_width = max([self.max_width, len(show)])
return show | python | def _get_string_and_set_width(self, combination, mode):
show = "{}".format(self._separator(mode)).join(combination)
show = show.rstrip("{}".format(self._separator(mode)))
self.max_width = max([self.max_width, len(show)])
return show | [
"def",
"_get_string_and_set_width",
"(",
"self",
",",
"combination",
",",
"mode",
")",
":",
"show",
"=",
"\"{}\"",
".",
"format",
"(",
"self",
".",
"_separator",
"(",
"mode",
")",
")",
".",
"join",
"(",
"combination",
")",
"show",
"=",
"show",
".",
"rs... | Construct the string to be displayed and record the max width. | [
"Construct",
"the",
"string",
"to",
"be",
"displayed",
"and",
"record",
"the",
"max",
"width",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L272-L279 |
231,174 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._choose_what_to_display | def _choose_what_to_display(self, force_refresh=False):
"""
Choose what combination to display on the bar.
By default we try to display the active layout on the first run, else
we display the last selected combination.
"""
for _ in range(len(self.available_combinations)):
if (
self.displayed is None
and self.available_combinations[0] == self.active_layout
):
self.displayed = self.available_combinations[0]
break
else:
if self.displayed == self.available_combinations[0]:
break
else:
self.available_combinations.rotate(1)
else:
if force_refresh:
self.displayed = self.available_combinations[0]
else:
self.py3.log('xrandr error="displayed combination is not available"') | python | def _choose_what_to_display(self, force_refresh=False):
for _ in range(len(self.available_combinations)):
if (
self.displayed is None
and self.available_combinations[0] == self.active_layout
):
self.displayed = self.available_combinations[0]
break
else:
if self.displayed == self.available_combinations[0]:
break
else:
self.available_combinations.rotate(1)
else:
if force_refresh:
self.displayed = self.available_combinations[0]
else:
self.py3.log('xrandr error="displayed combination is not available"') | [
"def",
"_choose_what_to_display",
"(",
"self",
",",
"force_refresh",
"=",
"False",
")",
":",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"available_combinations",
")",
")",
":",
"if",
"(",
"self",
".",
"displayed",
"is",
"None",
"and",
"self... | Choose what combination to display on the bar.
By default we try to display the active layout on the first run, else
we display the last selected combination. | [
"Choose",
"what",
"combination",
"to",
"display",
"on",
"the",
"bar",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L281-L304 |
231,175 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._apply_workspaces | def _apply_workspaces(self, combination, mode):
"""
Allows user to force move a comma separated list of workspaces to the
given output when it's activated.
Example:
- DP1_workspaces = "1,2,3"
"""
if len(combination) > 1 and mode == "extend":
sleep(3)
for output in combination:
workspaces = getattr(self, "{}_workspaces".format(output), "").split(
","
)
for workspace in workspaces:
if not workspace:
continue
# switch to workspace
cmd = '{} workspace "{}"'.format(self.py3.get_wm_msg(), workspace)
self.py3.command_run(cmd)
# move it to output
cmd = '{} move workspace to output "{}"'.format(
self.py3.get_wm_msg(), output
)
self.py3.command_run(cmd)
# log this
self.py3.log(
"moved workspace {} to output {}".format(workspace, output)
) | python | def _apply_workspaces(self, combination, mode):
if len(combination) > 1 and mode == "extend":
sleep(3)
for output in combination:
workspaces = getattr(self, "{}_workspaces".format(output), "").split(
","
)
for workspace in workspaces:
if not workspace:
continue
# switch to workspace
cmd = '{} workspace "{}"'.format(self.py3.get_wm_msg(), workspace)
self.py3.command_run(cmd)
# move it to output
cmd = '{} move workspace to output "{}"'.format(
self.py3.get_wm_msg(), output
)
self.py3.command_run(cmd)
# log this
self.py3.log(
"moved workspace {} to output {}".format(workspace, output)
) | [
"def",
"_apply_workspaces",
"(",
"self",
",",
"combination",
",",
"mode",
")",
":",
"if",
"len",
"(",
"combination",
")",
">",
"1",
"and",
"mode",
"==",
"\"extend\"",
":",
"sleep",
"(",
"3",
")",
"for",
"output",
"in",
"combination",
":",
"workspaces",
... | Allows user to force move a comma separated list of workspaces to the
given output when it's activated.
Example:
- DP1_workspaces = "1,2,3" | [
"Allows",
"user",
"to",
"force",
"move",
"a",
"comma",
"separated",
"list",
"of",
"workspaces",
"to",
"the",
"given",
"output",
"when",
"it",
"s",
"activated",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L378-L406 |
231,176 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._fallback_to_available_output | def _fallback_to_available_output(self):
"""
Fallback to the first available output when the active layout
was composed of only one output.
This allows us to avoid cases where you get stuck with a black sreen
on your laptop by switching back to the integrated screen
automatically !
"""
if len(self.active_comb) == 1:
self._choose_what_to_display(force_refresh=True)
self._apply()
self.py3.update() | python | def _fallback_to_available_output(self):
if len(self.active_comb) == 1:
self._choose_what_to_display(force_refresh=True)
self._apply()
self.py3.update() | [
"def",
"_fallback_to_available_output",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"active_comb",
")",
"==",
"1",
":",
"self",
".",
"_choose_what_to_display",
"(",
"force_refresh",
"=",
"True",
")",
"self",
".",
"_apply",
"(",
")",
"self",
".",
... | Fallback to the first available output when the active layout
was composed of only one output.
This allows us to avoid cases where you get stuck with a black sreen
on your laptop by switching back to the integrated screen
automatically ! | [
"Fallback",
"to",
"the",
"first",
"available",
"output",
"when",
"the",
"active",
"layout",
"was",
"composed",
"of",
"only",
"one",
"output",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L408-L420 |
231,177 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._force_force_on_start | def _force_force_on_start(self):
"""
Force the user configured mode on start.
"""
if self.force_on_start in self.available_combinations:
self.displayed = self.force_on_start
self._choose_what_to_display(force_refresh=True)
self._apply(force=True)
self.py3.update()
self.force_on_start = None | python | def _force_force_on_start(self):
if self.force_on_start in self.available_combinations:
self.displayed = self.force_on_start
self._choose_what_to_display(force_refresh=True)
self._apply(force=True)
self.py3.update()
self.force_on_start = None | [
"def",
"_force_force_on_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"force_on_start",
"in",
"self",
".",
"available_combinations",
":",
"self",
".",
"displayed",
"=",
"self",
".",
"force_on_start",
"self",
".",
"_choose_what_to_display",
"(",
"force_refresh"... | Force the user configured mode on start. | [
"Force",
"the",
"user",
"configured",
"mode",
"on",
"start",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L422-L431 |
231,178 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status._force_on_change | def _force_on_change(self):
"""
Handle force_on_change feature.
"""
for layout in self.force_on_change:
if layout in self.available_combinations:
if self.active_layout != layout:
self.displayed = layout
self._apply(force=True)
self.py3.update()
break
else:
break | python | def _force_on_change(self):
for layout in self.force_on_change:
if layout in self.available_combinations:
if self.active_layout != layout:
self.displayed = layout
self._apply(force=True)
self.py3.update()
break
else:
break | [
"def",
"_force_on_change",
"(",
"self",
")",
":",
"for",
"layout",
"in",
"self",
".",
"force_on_change",
":",
"if",
"layout",
"in",
"self",
".",
"available_combinations",
":",
"if",
"self",
".",
"active_layout",
"!=",
"layout",
":",
"self",
".",
"displayed",... | Handle force_on_change feature. | [
"Handle",
"force_on_change",
"feature",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L446-L458 |
231,179 | ultrabug/py3status | py3status/modules/xrandr.py | Py3status.xrandr | def xrandr(self):
"""
This is the main py3status method, it will orchestrate what's being
displayed on the bar.
"""
self.layout = self._get_layout()
self._set_available_combinations()
self._choose_what_to_display()
if len(self.available_combinations) < 2 and self.hide_if_single_combination:
full_text = self.py3.safe_format(self.format, {"output": ""})
else:
if self.fixed_width is True:
output = self._center(self.displayed)
else:
output = self.displayed
full_text = self.py3.safe_format(self.format, {"output": output})
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": full_text,
}
# coloration
if self.displayed == self.active_layout:
response["color"] = self.py3.COLOR_GOOD
elif self.displayed not in self.available_combinations:
response["color"] = self.py3.COLOR_BAD
# force default layout setup at module startup
if self.force_on_start is not None:
sleep(1)
self._force_force_on_start()
# follow on change
if not self._no_force_on_change and self.force_on_change:
self._force_on_change()
# this was a click event triggered update
if self._no_force_on_change:
self._no_force_on_change = False
# fallback detection
if self.active_layout not in self.available_combinations:
response["color"] = self.py3.COLOR_DEGRADED
if self.fallback is True:
self._fallback_to_available_output()
return response | python | def xrandr(self):
self.layout = self._get_layout()
self._set_available_combinations()
self._choose_what_to_display()
if len(self.available_combinations) < 2 and self.hide_if_single_combination:
full_text = self.py3.safe_format(self.format, {"output": ""})
else:
if self.fixed_width is True:
output = self._center(self.displayed)
else:
output = self.displayed
full_text = self.py3.safe_format(self.format, {"output": output})
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": full_text,
}
# coloration
if self.displayed == self.active_layout:
response["color"] = self.py3.COLOR_GOOD
elif self.displayed not in self.available_combinations:
response["color"] = self.py3.COLOR_BAD
# force default layout setup at module startup
if self.force_on_start is not None:
sleep(1)
self._force_force_on_start()
# follow on change
if not self._no_force_on_change and self.force_on_change:
self._force_on_change()
# this was a click event triggered update
if self._no_force_on_change:
self._no_force_on_change = False
# fallback detection
if self.active_layout not in self.available_combinations:
response["color"] = self.py3.COLOR_DEGRADED
if self.fallback is True:
self._fallback_to_available_output()
return response | [
"def",
"xrandr",
"(",
"self",
")",
":",
"self",
".",
"layout",
"=",
"self",
".",
"_get_layout",
"(",
")",
"self",
".",
"_set_available_combinations",
"(",
")",
"self",
".",
"_choose_what_to_display",
"(",
")",
"if",
"len",
"(",
"self",
".",
"available_comb... | This is the main py3status method, it will orchestrate what's being
displayed on the bar. | [
"This",
"is",
"the",
"main",
"py3status",
"method",
"it",
"will",
"orchestrate",
"what",
"s",
"being",
"displayed",
"on",
"the",
"bar",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L478-L526 |
231,180 | ultrabug/py3status | py3status/modules/velib_metropole.py | Py3status._set_optimal_area | def _set_optimal_area(self, data):
"""
Reduce the zone to reduce the size of fetched data on refresh
"""
lats = [station["latitude"] for station in data.values()]
longs = [station["longitude"] for station in data.values()]
self.gps.update(
{
"gpsTopLatitude": max(lats),
"gpsTopLongitude": max(longs),
"gpsBotLatitude": min(lats),
"gpsBotLongitude": min(longs),
}
) | python | def _set_optimal_area(self, data):
lats = [station["latitude"] for station in data.values()]
longs = [station["longitude"] for station in data.values()]
self.gps.update(
{
"gpsTopLatitude": max(lats),
"gpsTopLongitude": max(longs),
"gpsBotLatitude": min(lats),
"gpsBotLongitude": min(longs),
}
) | [
"def",
"_set_optimal_area",
"(",
"self",
",",
"data",
")",
":",
"lats",
"=",
"[",
"station",
"[",
"\"latitude\"",
"]",
"for",
"station",
"in",
"data",
".",
"values",
"(",
")",
"]",
"longs",
"=",
"[",
"station",
"[",
"\"longitude\"",
"]",
"for",
"statio... | Reduce the zone to reduce the size of fetched data on refresh | [
"Reduce",
"the",
"zone",
"to",
"reduce",
"the",
"size",
"of",
"fetched",
"data",
"on",
"refresh"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/velib_metropole.py#L161-L174 |
231,181 | ultrabug/py3status | py3status/modules/mpris.py | Py3status._get_text | def _get_text(self):
"""
Get the current metadata
"""
if self._data.get("state") == PLAYING:
color = self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD
state_symbol = self.state_play
elif self._data.get("state") == PAUSED:
color = self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED
state_symbol = self.state_pause
else:
color = self.py3.COLOR_STOPPED or self.py3.COLOR_BAD
state_symbol = self.state_stop
if self._data.get("error_occurred"):
color = self.py3.COLOR_BAD
try:
ptime_ms = self._player.Position
ptime = _get_time_str(ptime_ms)
except Exception:
ptime = None
if (
self.py3.format_contains(self.format, "time")
and self._data.get("state") == PLAYING
):
# Don't get trapped in aliasing errors!
update = time() + 0.5
else:
update = self.py3.CACHE_FOREVER
placeholders = {
"player": self._data.get("player"),
"state": state_symbol,
"album": self._data.get("album"),
"artist": self._data.get("artist"),
"length": self._data.get("length"),
"time": ptime,
"title": self._data.get("title") or "No Track",
"full_name": self._player_details.get("full_name"), # for debugging ;p
}
return (placeholders, color, update) | python | def _get_text(self):
if self._data.get("state") == PLAYING:
color = self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD
state_symbol = self.state_play
elif self._data.get("state") == PAUSED:
color = self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED
state_symbol = self.state_pause
else:
color = self.py3.COLOR_STOPPED or self.py3.COLOR_BAD
state_symbol = self.state_stop
if self._data.get("error_occurred"):
color = self.py3.COLOR_BAD
try:
ptime_ms = self._player.Position
ptime = _get_time_str(ptime_ms)
except Exception:
ptime = None
if (
self.py3.format_contains(self.format, "time")
and self._data.get("state") == PLAYING
):
# Don't get trapped in aliasing errors!
update = time() + 0.5
else:
update = self.py3.CACHE_FOREVER
placeholders = {
"player": self._data.get("player"),
"state": state_symbol,
"album": self._data.get("album"),
"artist": self._data.get("artist"),
"length": self._data.get("length"),
"time": ptime,
"title": self._data.get("title") or "No Track",
"full_name": self._player_details.get("full_name"), # for debugging ;p
}
return (placeholders, color, update) | [
"def",
"_get_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
".",
"get",
"(",
"\"state\"",
")",
"==",
"PLAYING",
":",
"color",
"=",
"self",
".",
"py3",
".",
"COLOR_PLAYING",
"or",
"self",
".",
"py3",
".",
"COLOR_GOOD",
"state_symbol",
"=",
... | Get the current metadata | [
"Get",
"the",
"current",
"metadata"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L240-L283 |
231,182 | ultrabug/py3status | py3status/modules/mpris.py | Py3status._set_player | def _set_player(self):
"""
Sort the current players into priority order and set self._player
Players are ordered by working state then prefernce supplied by user
and finally by instance if a player has more than one running.
"""
players = []
for name, p in self._mpris_players.items():
# we set the priority here as we need to establish the player name
# which might not be immediately available.
if "_priority" not in p:
if self.player_priority:
try:
priority = self.player_priority.index(p["name"])
except ValueError:
try:
priority = self.player_priority.index("*")
except ValueError:
priority = None
else:
priority = 0
if priority is not None:
p["_priority"] = priority
if p.get("_priority") is not None:
players.append((p["_state_priority"], p["_priority"], p["index"], name))
if players:
top_player = self._mpris_players.get(sorted(players)[0][3])
else:
top_player = {}
self._player = top_player.get("_dbus_player")
self._player_details = top_player
self.py3.update() | python | def _set_player(self):
players = []
for name, p in self._mpris_players.items():
# we set the priority here as we need to establish the player name
# which might not be immediately available.
if "_priority" not in p:
if self.player_priority:
try:
priority = self.player_priority.index(p["name"])
except ValueError:
try:
priority = self.player_priority.index("*")
except ValueError:
priority = None
else:
priority = 0
if priority is not None:
p["_priority"] = priority
if p.get("_priority") is not None:
players.append((p["_state_priority"], p["_priority"], p["index"], name))
if players:
top_player = self._mpris_players.get(sorted(players)[0][3])
else:
top_player = {}
self._player = top_player.get("_dbus_player")
self._player_details = top_player
self.py3.update() | [
"def",
"_set_player",
"(",
"self",
")",
":",
"players",
"=",
"[",
"]",
"for",
"name",
",",
"p",
"in",
"self",
".",
"_mpris_players",
".",
"items",
"(",
")",
":",
"# we set the priority here as we need to establish the player name",
"# which might not be immediately av... | Sort the current players into priority order and set self._player
Players are ordered by working state then prefernce supplied by user
and finally by instance if a player has more than one running. | [
"Sort",
"the",
"current",
"players",
"into",
"priority",
"order",
"and",
"set",
"self",
".",
"_player",
"Players",
"are",
"ordered",
"by",
"working",
"state",
"then",
"prefernce",
"supplied",
"by",
"user",
"and",
"finally",
"by",
"instance",
"if",
"a",
"play... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L328-L361 |
231,183 | ultrabug/py3status | py3status/modules/mpris.py | Py3status._add_player | def _add_player(self, player_id):
"""
Add player to mpris_players
"""
if not player_id.startswith(SERVICE_BUS):
return False
player = self._dbus.get(player_id, SERVICE_BUS_URL)
if player.Identity not in self._mpris_names:
self._mpris_names[player.Identity] = player_id.split(".")[-1]
for p in self._mpris_players.values():
if not p["name"] and p["identity"] in self._mpris_names:
p["name"] = self._mpris_names[p["identity"]]
p["full_name"] = u"{} {}".format(p["name"], p["index"])
identity = player.Identity
name = self._mpris_names.get(identity)
if (
self.player_priority != []
and name not in self.player_priority
and "*" not in self.player_priority
):
return False
if identity not in self._mpris_name_index:
self._mpris_name_index[identity] = 0
status = player.PlaybackStatus
state_priority = WORKING_STATES.index(status)
index = self._mpris_name_index[identity]
self._mpris_name_index[identity] += 1
try:
subscription = player.PropertiesChanged.connect(
self._player_monitor(player_id)
)
except AttributeError:
subscription = {}
self._mpris_players[player_id] = {
"_dbus_player": player,
"_id": player_id,
"_state_priority": state_priority,
"index": index,
"identity": identity,
"name": name,
"full_name": u"{} {}".format(name, index),
"status": status,
"subscription": subscription,
}
return True | python | def _add_player(self, player_id):
if not player_id.startswith(SERVICE_BUS):
return False
player = self._dbus.get(player_id, SERVICE_BUS_URL)
if player.Identity not in self._mpris_names:
self._mpris_names[player.Identity] = player_id.split(".")[-1]
for p in self._mpris_players.values():
if not p["name"] and p["identity"] in self._mpris_names:
p["name"] = self._mpris_names[p["identity"]]
p["full_name"] = u"{} {}".format(p["name"], p["index"])
identity = player.Identity
name = self._mpris_names.get(identity)
if (
self.player_priority != []
and name not in self.player_priority
and "*" not in self.player_priority
):
return False
if identity not in self._mpris_name_index:
self._mpris_name_index[identity] = 0
status = player.PlaybackStatus
state_priority = WORKING_STATES.index(status)
index = self._mpris_name_index[identity]
self._mpris_name_index[identity] += 1
try:
subscription = player.PropertiesChanged.connect(
self._player_monitor(player_id)
)
except AttributeError:
subscription = {}
self._mpris_players[player_id] = {
"_dbus_player": player,
"_id": player_id,
"_state_priority": state_priority,
"index": index,
"identity": identity,
"name": name,
"full_name": u"{} {}".format(name, index),
"status": status,
"subscription": subscription,
}
return True | [
"def",
"_add_player",
"(",
"self",
",",
"player_id",
")",
":",
"if",
"not",
"player_id",
".",
"startswith",
"(",
"SERVICE_BUS",
")",
":",
"return",
"False",
"player",
"=",
"self",
".",
"_dbus",
".",
"get",
"(",
"player_id",
",",
"SERVICE_BUS_URL",
")",
"... | Add player to mpris_players | [
"Add",
"player",
"to",
"mpris_players"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L390-L441 |
231,184 | ultrabug/py3status | py3status/modules/mpris.py | Py3status._remove_player | def _remove_player(self, player_id):
"""
Remove player from mpris_players
"""
player = self._mpris_players.get(player_id)
if player:
if player.get("subscription"):
player["subscription"].disconnect()
del self._mpris_players[player_id] | python | def _remove_player(self, player_id):
player = self._mpris_players.get(player_id)
if player:
if player.get("subscription"):
player["subscription"].disconnect()
del self._mpris_players[player_id] | [
"def",
"_remove_player",
"(",
"self",
",",
"player_id",
")",
":",
"player",
"=",
"self",
".",
"_mpris_players",
".",
"get",
"(",
"player_id",
")",
"if",
"player",
":",
"if",
"player",
".",
"get",
"(",
"\"subscription\"",
")",
":",
"player",
"[",
"\"subsc... | Remove player from mpris_players | [
"Remove",
"player",
"from",
"mpris_players"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L443-L451 |
231,185 | ultrabug/py3status | py3status/modules/mpris.py | Py3status.mpris | def mpris(self):
"""
Get the current output format and return it.
"""
if self._kill:
raise KeyboardInterrupt
current_player_id = self._player_details.get("id")
cached_until = self.py3.CACHE_FOREVER
if self._player is None:
text = self.format_none
color = self.py3.COLOR_BAD
composite = [{"full_text": text, "color": color}]
self._data = {}
else:
self._init_data()
(text, color, cached_until) = self._get_text()
self._control_states = self._get_control_states()
buttons = self._get_response_buttons()
composite = self.py3.safe_format(self.format, dict(text, **buttons))
if self._data.get(
"error_occurred"
) or current_player_id != self._player_details.get("id"):
# Something went wrong or the player changed during our processing
# This is usually due to something like a player being killed
# whilst we are checking its details
# Retry but limit the number of attempts
self._tries += 1
if self._tries < 3:
return self.mpris()
# Max retries hit we need to output something
composite = [
{"full_text": "Something went wrong", "color": self.py3.COLOR_BAD}
]
cached_until = self.py3.time_in(1)
response = {
"cached_until": cached_until,
"color": color,
"composite": composite,
}
# we are outputing so reset tries
self._tries = 0
return response | python | def mpris(self):
if self._kill:
raise KeyboardInterrupt
current_player_id = self._player_details.get("id")
cached_until = self.py3.CACHE_FOREVER
if self._player is None:
text = self.format_none
color = self.py3.COLOR_BAD
composite = [{"full_text": text, "color": color}]
self._data = {}
else:
self._init_data()
(text, color, cached_until) = self._get_text()
self._control_states = self._get_control_states()
buttons = self._get_response_buttons()
composite = self.py3.safe_format(self.format, dict(text, **buttons))
if self._data.get(
"error_occurred"
) or current_player_id != self._player_details.get("id"):
# Something went wrong or the player changed during our processing
# This is usually due to something like a player being killed
# whilst we are checking its details
# Retry but limit the number of attempts
self._tries += 1
if self._tries < 3:
return self.mpris()
# Max retries hit we need to output something
composite = [
{"full_text": "Something went wrong", "color": self.py3.COLOR_BAD}
]
cached_until = self.py3.time_in(1)
response = {
"cached_until": cached_until,
"color": color,
"composite": composite,
}
# we are outputing so reset tries
self._tries = 0
return response | [
"def",
"mpris",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kill",
":",
"raise",
"KeyboardInterrupt",
"current_player_id",
"=",
"self",
".",
"_player_details",
".",
"get",
"(",
"\"id\"",
")",
"cached_until",
"=",
"self",
".",
"py3",
".",
"CACHE_FOREVER",
"... | Get the current output format and return it. | [
"Get",
"the",
"current",
"output",
"format",
"and",
"return",
"it",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L513-L558 |
231,186 | ultrabug/py3status | py3status/modules/mpris.py | Py3status.on_click | def on_click(self, event):
"""
Handles click events
"""
index = event["index"]
button = event["button"]
if index not in self._control_states.keys():
if button == self.button_toggle:
index = "toggle"
elif button == self.button_stop:
index = "stop"
elif button == self.button_next:
index = "next"
elif button == self.button_previous:
index = "previous"
else:
return
elif button != 1:
return
try:
control_state = self._control_states.get(index)
if self._player and self._get_button_state(control_state):
getattr(self._player, self._control_states[index]["action"])()
except GError as err:
self.py3.log(str(err).split(":", 1)[-1]) | python | def on_click(self, event):
index = event["index"]
button = event["button"]
if index not in self._control_states.keys():
if button == self.button_toggle:
index = "toggle"
elif button == self.button_stop:
index = "stop"
elif button == self.button_next:
index = "next"
elif button == self.button_previous:
index = "previous"
else:
return
elif button != 1:
return
try:
control_state = self._control_states.get(index)
if self._player and self._get_button_state(control_state):
getattr(self._player, self._control_states[index]["action"])()
except GError as err:
self.py3.log(str(err).split(":", 1)[-1]) | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"index",
"=",
"event",
"[",
"\"index\"",
"]",
"button",
"=",
"event",
"[",
"\"button\"",
"]",
"if",
"index",
"not",
"in",
"self",
".",
"_control_states",
".",
"keys",
"(",
")",
":",
"if",
"butto... | Handles click events | [
"Handles",
"click",
"events"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/mpris.py#L560-L586 |
231,187 | ultrabug/py3status | py3status/modules/clock.py | Py3status._get_timezone | def _get_timezone(self, tz):
"""
Find and return the time zone if possible
"""
# special Local timezone
if tz == "Local":
try:
return tzlocal.get_localzone()
except pytz.UnknownTimeZoneError:
return "?"
# we can use a country code to get tz
# FIXME this is broken for multi-timezone countries eg US
# for now we just grab the first one
if len(tz) == 2:
try:
zones = pytz.country_timezones(tz)
except KeyError:
return "?"
tz = zones[0]
# get the timezone
try:
zone = pytz.timezone(tz)
except pytz.UnknownTimeZoneError:
return "?"
return zone | python | def _get_timezone(self, tz):
# special Local timezone
if tz == "Local":
try:
return tzlocal.get_localzone()
except pytz.UnknownTimeZoneError:
return "?"
# we can use a country code to get tz
# FIXME this is broken for multi-timezone countries eg US
# for now we just grab the first one
if len(tz) == 2:
try:
zones = pytz.country_timezones(tz)
except KeyError:
return "?"
tz = zones[0]
# get the timezone
try:
zone = pytz.timezone(tz)
except pytz.UnknownTimeZoneError:
return "?"
return zone | [
"def",
"_get_timezone",
"(",
"self",
",",
"tz",
")",
":",
"# special Local timezone",
"if",
"tz",
"==",
"\"Local\"",
":",
"try",
":",
"return",
"tzlocal",
".",
"get_localzone",
"(",
")",
"except",
"pytz",
".",
"UnknownTimeZoneError",
":",
"return",
"\"?\"",
... | Find and return the time zone if possible | [
"Find",
"and",
"return",
"the",
"time",
"zone",
"if",
"possible"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/clock.py#L206-L232 |
231,188 | ultrabug/py3status | doc/conf.py | setup | def setup(sphinx):
"""
This will be called by sphinx.
"""
create_auto_documentation()
# add the py3status lexer (for code blocks)
from sphinx.highlighting import lexers
lexers['py3status'] = Py3statusLexer()
# enable screenshot directive for dynamic screenshots
sphinx.add_directive('screenshot', ScreenshotDirective) | python | def setup(sphinx):
create_auto_documentation()
# add the py3status lexer (for code blocks)
from sphinx.highlighting import lexers
lexers['py3status'] = Py3statusLexer()
# enable screenshot directive for dynamic screenshots
sphinx.add_directive('screenshot', ScreenshotDirective) | [
"def",
"setup",
"(",
"sphinx",
")",
":",
"create_auto_documentation",
"(",
")",
"# add the py3status lexer (for code blocks)",
"from",
"sphinx",
".",
"highlighting",
"import",
"lexers",
"lexers",
"[",
"'py3status'",
"]",
"=",
"Py3statusLexer",
"(",
")",
"# enable scre... | This will be called by sphinx. | [
"This",
"will",
"be",
"called",
"by",
"sphinx",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/doc/conf.py#L174-L185 |
231,189 | ultrabug/py3status | py3status/modules/spotify.py | Py3status._compile_re | def _compile_re(self, expression):
"""
Compile given regular expression for current sanitize words
"""
meta_words = "|".join(self.sanitize_words)
expression = expression.replace("META_WORDS_HERE", meta_words)
return re.compile(expression, re.IGNORECASE) | python | def _compile_re(self, expression):
meta_words = "|".join(self.sanitize_words)
expression = expression.replace("META_WORDS_HERE", meta_words)
return re.compile(expression, re.IGNORECASE) | [
"def",
"_compile_re",
"(",
"self",
",",
"expression",
")",
":",
"meta_words",
"=",
"\"|\"",
".",
"join",
"(",
"self",
".",
"sanitize_words",
")",
"expression",
"=",
"expression",
".",
"replace",
"(",
"\"META_WORDS_HERE\"",
",",
"meta_words",
")",
"return",
"... | Compile given regular expression for current sanitize words | [
"Compile",
"given",
"regular",
"expression",
"for",
"current",
"sanitize",
"words"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/spotify.py#L118-L124 |
231,190 | ultrabug/py3status | py3status/modules/spotify.py | Py3status._sanitize_title | def _sanitize_title(self, title):
"""
Remove redunant meta data from title and return it
"""
title = re.sub(self.inside_brackets, "", title)
title = re.sub(self.after_delimiter, "", title)
return title.strip() | python | def _sanitize_title(self, title):
title = re.sub(self.inside_brackets, "", title)
title = re.sub(self.after_delimiter, "", title)
return title.strip() | [
"def",
"_sanitize_title",
"(",
"self",
",",
"title",
")",
":",
"title",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"inside_brackets",
",",
"\"\"",
",",
"title",
")",
"title",
"=",
"re",
".",
"sub",
"(",
"self",
".",
"after_delimiter",
",",
"\"\"",
",",... | Remove redunant meta data from title and return it | [
"Remove",
"redunant",
"meta",
"data",
"from",
"title",
"and",
"return",
"it"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/spotify.py#L171-L177 |
231,191 | ultrabug/py3status | py3status/modules/spotify.py | Py3status.spotify | def spotify(self):
"""
Get the current "artist - title" and return it.
"""
(text, color) = self._get_text()
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"color": color,
"full_text": text,
}
return response | python | def spotify(self):
(text, color) = self._get_text()
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"color": color,
"full_text": text,
}
return response | [
"def",
"spotify",
"(",
"self",
")",
":",
"(",
"text",
",",
"color",
")",
"=",
"self",
".",
"_get_text",
"(",
")",
"response",
"=",
"{",
"\"cached_until\"",
":",
"self",
".",
"py3",
".",
"time_in",
"(",
"self",
".",
"cache_timeout",
")",
",",
"\"color... | Get the current "artist - title" and return it. | [
"Get",
"the",
"current",
"artist",
"-",
"title",
"and",
"return",
"it",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/spotify.py#L179-L189 |
231,192 | ultrabug/py3status | py3status/storage.py | Storage.get_legacy_storage_path | def get_legacy_storage_path(self):
"""
Detect and return existing legacy storage path.
"""
config_dir = os.path.dirname(
self.py3_wrapper.config.get("i3status_config_path", "/tmp")
)
storage_path = os.path.join(config_dir, "py3status.data")
if os.path.exists(storage_path):
return storage_path
else:
return None | python | def get_legacy_storage_path(self):
config_dir = os.path.dirname(
self.py3_wrapper.config.get("i3status_config_path", "/tmp")
)
storage_path = os.path.join(config_dir, "py3status.data")
if os.path.exists(storage_path):
return storage_path
else:
return None | [
"def",
"get_legacy_storage_path",
"(",
"self",
")",
":",
"config_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"py3_wrapper",
".",
"config",
".",
"get",
"(",
"\"i3status_config_path\"",
",",
"\"/tmp\"",
")",
")",
"storage_path",
"=",
"os",
... | Detect and return existing legacy storage path. | [
"Detect",
"and",
"return",
"existing",
"legacy",
"storage",
"path",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/storage.py#L66-L77 |
231,193 | ultrabug/py3status | py3status/storage.py | Storage.save | def save(self):
"""
Save our data to disk. We want to always have a valid file.
"""
with NamedTemporaryFile(
dir=os.path.dirname(self.storage_path), delete=False
) as f:
# we use protocol=2 for python 2/3 compatibility
dump(self.data, f, protocol=2)
f.flush()
os.fsync(f.fileno())
tmppath = f.name
os.rename(tmppath, self.storage_path) | python | def save(self):
with NamedTemporaryFile(
dir=os.path.dirname(self.storage_path), delete=False
) as f:
# we use protocol=2 for python 2/3 compatibility
dump(self.data, f, protocol=2)
f.flush()
os.fsync(f.fileno())
tmppath = f.name
os.rename(tmppath, self.storage_path) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"storage_path",
")",
",",
"delete",
"=",
"False",
")",
"as",
"f",
":",
"# we use protocol=2 for python 2/3 compatibility... | Save our data to disk. We want to always have a valid file. | [
"Save",
"our",
"data",
"to",
"disk",
".",
"We",
"want",
"to",
"always",
"have",
"a",
"valid",
"file",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/storage.py#L79-L91 |
231,194 | ultrabug/py3status | py3status/modules/rate_counter.py | Py3status.secs_to_dhms | def secs_to_dhms(time_in_secs):
"""Convert seconds to days, hours, minutes, seconds.
Using days as the largest unit of time. Blindly using the days in
`time.gmtime()` will fail if it's more than one month (days > 31).
"""
days = int(time_in_secs / SECS_IN_DAY)
remaining_secs = time_in_secs % SECS_IN_DAY
hours = int(remaining_secs / SECS_IN_HOUR)
remaining_secs = remaining_secs % SECS_IN_HOUR
mins = int(remaining_secs / SECS_IN_MIN)
secs = int(remaining_secs % SECS_IN_MIN)
return days, hours, mins, secs | python | def secs_to_dhms(time_in_secs):
days = int(time_in_secs / SECS_IN_DAY)
remaining_secs = time_in_secs % SECS_IN_DAY
hours = int(remaining_secs / SECS_IN_HOUR)
remaining_secs = remaining_secs % SECS_IN_HOUR
mins = int(remaining_secs / SECS_IN_MIN)
secs = int(remaining_secs % SECS_IN_MIN)
return days, hours, mins, secs | [
"def",
"secs_to_dhms",
"(",
"time_in_secs",
")",
":",
"days",
"=",
"int",
"(",
"time_in_secs",
"/",
"SECS_IN_DAY",
")",
"remaining_secs",
"=",
"time_in_secs",
"%",
"SECS_IN_DAY",
"hours",
"=",
"int",
"(",
"remaining_secs",
"/",
"SECS_IN_HOUR",
")",
"remaining_se... | Convert seconds to days, hours, minutes, seconds.
Using days as the largest unit of time. Blindly using the days in
`time.gmtime()` will fail if it's more than one month (days > 31). | [
"Convert",
"seconds",
"to",
"days",
"hours",
"minutes",
"seconds",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/rate_counter.py#L85-L97 |
231,195 | ultrabug/py3status | py3status/modules/pomodoro.py | Py3status._setup_bar | def _setup_bar(self):
"""
Setup the process bar.
"""
bar = u""
items_cnt = len(PROGRESS_BAR_ITEMS)
bar_val = float(self._time_left) / self._section_time * self.num_progress_bars
while bar_val > 0:
selector = int(bar_val * items_cnt)
selector = min(selector, items_cnt - 1)
bar += PROGRESS_BAR_ITEMS[selector]
bar_val -= 1
bar = bar.ljust(self.num_progress_bars)
return bar | python | def _setup_bar(self):
bar = u""
items_cnt = len(PROGRESS_BAR_ITEMS)
bar_val = float(self._time_left) / self._section_time * self.num_progress_bars
while bar_val > 0:
selector = int(bar_val * items_cnt)
selector = min(selector, items_cnt - 1)
bar += PROGRESS_BAR_ITEMS[selector]
bar_val -= 1
bar = bar.ljust(self.num_progress_bars)
return bar | [
"def",
"_setup_bar",
"(",
"self",
")",
":",
"bar",
"=",
"u\"\"",
"items_cnt",
"=",
"len",
"(",
"PROGRESS_BAR_ITEMS",
")",
"bar_val",
"=",
"float",
"(",
"self",
".",
"_time_left",
")",
"/",
"self",
".",
"_section_time",
"*",
"self",
".",
"num_progress_bars"... | Setup the process bar. | [
"Setup",
"the",
"process",
"bar",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/pomodoro.py#L189-L203 |
231,196 | ultrabug/py3status | py3status/modules/pomodoro.py | Py3status.pomodoro | def pomodoro(self):
"""
Pomodoro response handling and countdown
"""
if not self._initialized:
self._init()
cached_until = self.py3.time_in(0)
if self._running:
self._time_left = ceil(self._end_time - time())
time_left = ceil(self._time_left)
else:
time_left = ceil(self._time_left)
vals = {"ss": int(time_left), "mm": int(ceil(time_left / 60))}
if self.py3.format_contains(self.format, "mmss"):
hours, rest = divmod(time_left, 3600)
mins, seconds = divmod(rest, 60)
if hours:
vals["mmss"] = u"%d%s%02d%s%02d" % (
hours,
self.format_separator,
mins,
self.format_separator,
seconds,
)
else:
vals["mmss"] = u"%d%s%02d" % (mins, self.format_separator, seconds)
if self.py3.format_contains(self.format, "bar"):
vals["bar"] = self._setup_bar()
formatted = self.format.format(**vals)
if self._running:
if self._active:
format = self.format_active
else:
format = self.format_break
else:
if self._active:
format = self.format_stopped
else:
format = self.format_break_stopped
cached_until = self.py3.CACHE_FOREVER
response = {
"full_text": format.format(
breakno=self._break_number, format=formatted, **vals
),
"cached_until": cached_until,
}
if self._alert:
response["urgent"] = True
self._alert = False
if not self._running:
response["color"] = self.py3.COLOR_BAD
else:
if self._active:
response["color"] = self.py3.COLOR_GOOD
else:
response["color"] = self.py3.COLOR_DEGRADED
return response | python | def pomodoro(self):
if not self._initialized:
self._init()
cached_until = self.py3.time_in(0)
if self._running:
self._time_left = ceil(self._end_time - time())
time_left = ceil(self._time_left)
else:
time_left = ceil(self._time_left)
vals = {"ss": int(time_left), "mm": int(ceil(time_left / 60))}
if self.py3.format_contains(self.format, "mmss"):
hours, rest = divmod(time_left, 3600)
mins, seconds = divmod(rest, 60)
if hours:
vals["mmss"] = u"%d%s%02d%s%02d" % (
hours,
self.format_separator,
mins,
self.format_separator,
seconds,
)
else:
vals["mmss"] = u"%d%s%02d" % (mins, self.format_separator, seconds)
if self.py3.format_contains(self.format, "bar"):
vals["bar"] = self._setup_bar()
formatted = self.format.format(**vals)
if self._running:
if self._active:
format = self.format_active
else:
format = self.format_break
else:
if self._active:
format = self.format_stopped
else:
format = self.format_break_stopped
cached_until = self.py3.CACHE_FOREVER
response = {
"full_text": format.format(
breakno=self._break_number, format=formatted, **vals
),
"cached_until": cached_until,
}
if self._alert:
response["urgent"] = True
self._alert = False
if not self._running:
response["color"] = self.py3.COLOR_BAD
else:
if self._active:
response["color"] = self.py3.COLOR_GOOD
else:
response["color"] = self.py3.COLOR_DEGRADED
return response | [
"def",
"pomodoro",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_init",
"(",
")",
"cached_until",
"=",
"self",
".",
"py3",
".",
"time_in",
"(",
"0",
")",
"if",
"self",
".",
"_running",
":",
"self",
".",
"_time... | Pomodoro response handling and countdown | [
"Pomodoro",
"response",
"handling",
"and",
"countdown"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/pomodoro.py#L205-L272 |
231,197 | ultrabug/py3status | py3status/udev_monitor.py | UdevMonitor._setup_pyudev_monitoring | def _setup_pyudev_monitoring(self):
"""
Setup the udev monitor.
"""
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event)
self.udev_observer.start()
self.py3_wrapper.log("udev monitoring enabled") | python | def _setup_pyudev_monitoring(self):
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event)
self.udev_observer.start()
self.py3_wrapper.log("udev monitoring enabled") | [
"def",
"_setup_pyudev_monitoring",
"(",
"self",
")",
":",
"context",
"=",
"pyudev",
".",
"Context",
"(",
")",
"monitor",
"=",
"pyudev",
".",
"Monitor",
".",
"from_netlink",
"(",
"context",
")",
"self",
".",
"udev_observer",
"=",
"pyudev",
".",
"MonitorObserv... | Setup the udev monitor. | [
"Setup",
"the",
"udev",
"monitor",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/udev_monitor.py#L25-L33 |
231,198 | ultrabug/py3status | py3status/udev_monitor.py | UdevMonitor.subscribe | def subscribe(self, py3_module, trigger_action, subsystem):
"""
Subscribe the given module to the given udev subsystem.
Here we will lazy load the monitor if necessary and return success or
failure based on the availability of pyudev.
"""
if self.pyudev_available:
# lazy load the udev monitor
if self.udev_observer is None:
self._setup_pyudev_monitoring()
if trigger_action not in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"module %s: invalid action %s on udev events subscription"
% (py3_module.module_full_name, trigger_action)
)
return False
self.udev_consumers[subsystem].append((py3_module, trigger_action))
self.py3_wrapper.log(
"module %s subscribed to udev events on %s"
% (py3_module.module_full_name, subsystem)
)
return True
else:
self.py3_wrapper.log(
"pyudev module not installed: module %s not subscribed to events on %s"
% (py3_module.module_full_name, subsystem)
)
return False | python | def subscribe(self, py3_module, trigger_action, subsystem):
if self.pyudev_available:
# lazy load the udev monitor
if self.udev_observer is None:
self._setup_pyudev_monitoring()
if trigger_action not in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"module %s: invalid action %s on udev events subscription"
% (py3_module.module_full_name, trigger_action)
)
return False
self.udev_consumers[subsystem].append((py3_module, trigger_action))
self.py3_wrapper.log(
"module %s subscribed to udev events on %s"
% (py3_module.module_full_name, subsystem)
)
return True
else:
self.py3_wrapper.log(
"pyudev module not installed: module %s not subscribed to events on %s"
% (py3_module.module_full_name, subsystem)
)
return False | [
"def",
"subscribe",
"(",
"self",
",",
"py3_module",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"self",
".",
"pyudev_available",
":",
"# lazy load the udev monitor",
"if",
"self",
".",
"udev_observer",
"is",
"None",
":",
"self",
".",
"_setup_pyudev_... | Subscribe the given module to the given udev subsystem.
Here we will lazy load the monitor if necessary and return success or
failure based on the availability of pyudev. | [
"Subscribe",
"the",
"given",
"module",
"to",
"the",
"given",
"udev",
"subsystem",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/udev_monitor.py#L44-L72 |
231,199 | ultrabug/py3status | py3status/udev_monitor.py | UdevMonitor.trigger_actions | def trigger_actions(self, subsystem):
"""
Refresh all modules which subscribed to the given subsystem.
"""
for py3_module, trigger_action in self.udev_consumers[subsystem]:
if trigger_action in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"%s udev event, refresh consumer %s"
% (subsystem, py3_module.module_full_name)
)
py3_module.force_update() | python | def trigger_actions(self, subsystem):
for py3_module, trigger_action in self.udev_consumers[subsystem]:
if trigger_action in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"%s udev event, refresh consumer %s"
% (subsystem, py3_module.module_full_name)
)
py3_module.force_update() | [
"def",
"trigger_actions",
"(",
"self",
",",
"subsystem",
")",
":",
"for",
"py3_module",
",",
"trigger_action",
"in",
"self",
".",
"udev_consumers",
"[",
"subsystem",
"]",
":",
"if",
"trigger_action",
"in",
"ON_TRIGGER_ACTIONS",
":",
"self",
".",
"py3_wrapper",
... | Refresh all modules which subscribed to the given subsystem. | [
"Refresh",
"all",
"modules",
"which",
"subscribed",
"to",
"the",
"given",
"subsystem",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/udev_monitor.py#L74-L84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.