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,200 | ultrabug/py3status | py3status/i3status.py | I3statusModule.run | def run(self):
"""
updates the modules output.
Currently only time and tztime need to do this
"""
if self.update_time_value():
self.i3status.py3_wrapper.notify_update(self.module_name)
due_time = self.py3.time_in(sync_to=self.time_delta)
self.i3status.py3_wrapper.timeout_queue_add(self, due_time) | python | def run(self):
if self.update_time_value():
self.i3status.py3_wrapper.notify_update(self.module_name)
due_time = self.py3.time_in(sync_to=self.time_delta)
self.i3status.py3_wrapper.timeout_queue_add(self, due_time) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"update_time_value",
"(",
")",
":",
"self",
".",
"i3status",
".",
"py3_wrapper",
".",
"notify_update",
"(",
"self",
".",
"module_name",
")",
"due_time",
"=",
"self",
".",
"py3",
".",
"time_in",
"(... | updates the modules output.
Currently only time and tztime need to do this | [
"updates",
"the",
"modules",
"output",
".",
"Currently",
"only",
"time",
"and",
"tztime",
"need",
"to",
"do",
"this"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L131-L140 |
231,201 | ultrabug/py3status | py3status/i3status.py | I3statusModule.update_from_item | def update_from_item(self, item):
"""
Update from i3status output. returns if item has changed.
"""
if not self.is_time_module:
# correct the output
# Restore the name/instance.
item["name"] = self.name
item["instance"] = self.instance
# change color good/bad is set specifically for module
if "color" in item and item["color"] in self.color_map:
item["color"] = self.color_map[item["color"]]
# have we updated?
is_updated = self.item != item
self.item = item
else:
# If no timezone or a minute has passed update timezone
t = time()
if self.time_zone_check_due < t:
# If we are late for our timezone update then schedule the next
# update to happen when we next get new data from i3status
interval = self.i3status.update_interval
if not self.set_time_zone(item):
# we had an issue with an invalid time zone probably due to
# suspending. re check the time zone when we next can.
self.time_zone_check_due = 0
elif self.time_zone_check_due and (
t - self.time_zone_check_due > 5 + interval
):
self.time_zone_check_due = 0
else:
# Check again in 30 mins. We do this in case the timezone
# used has switched to/from summer time
self.time_zone_check_due = ((int(t) // 1800) * 1800) + 1800
if not self.time_started:
self.time_started = True
self.i3status.py3_wrapper.timeout_queue_add(self)
is_updated = False
# update time to be shown
return is_updated | python | def update_from_item(self, item):
if not self.is_time_module:
# correct the output
# Restore the name/instance.
item["name"] = self.name
item["instance"] = self.instance
# change color good/bad is set specifically for module
if "color" in item and item["color"] in self.color_map:
item["color"] = self.color_map[item["color"]]
# have we updated?
is_updated = self.item != item
self.item = item
else:
# If no timezone or a minute has passed update timezone
t = time()
if self.time_zone_check_due < t:
# If we are late for our timezone update then schedule the next
# update to happen when we next get new data from i3status
interval = self.i3status.update_interval
if not self.set_time_zone(item):
# we had an issue with an invalid time zone probably due to
# suspending. re check the time zone when we next can.
self.time_zone_check_due = 0
elif self.time_zone_check_due and (
t - self.time_zone_check_due > 5 + interval
):
self.time_zone_check_due = 0
else:
# Check again in 30 mins. We do this in case the timezone
# used has switched to/from summer time
self.time_zone_check_due = ((int(t) // 1800) * 1800) + 1800
if not self.time_started:
self.time_started = True
self.i3status.py3_wrapper.timeout_queue_add(self)
is_updated = False
# update time to be shown
return is_updated | [
"def",
"update_from_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"self",
".",
"is_time_module",
":",
"# correct the output",
"# Restore the name/instance.",
"item",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"name",
"item",
"[",
"\"instance\"",
"]",
"=... | Update from i3status output. returns if item has changed. | [
"Update",
"from",
"i3status",
"output",
".",
"returns",
"if",
"item",
"has",
"changed",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L142-L183 |
231,202 | ultrabug/py3status | py3status/i3status.py | I3statusModule.set_time_zone | def set_time_zone(self, item):
"""
Work out the time zone and create a shim tzinfo.
We return True if all is good or False if there was an issue and we
need to re check the time zone. see issue #1375
"""
# parse i3status date
i3s_time = item["full_text"].encode("UTF-8", "replace")
try:
# python3 compatibility code
i3s_time = i3s_time.decode()
except: # noqa e722
pass
# get datetime and time zone info
parts = i3s_time.split()
i3s_datetime = " ".join(parts[:2])
# occassionally we do not get the timezone name
if len(parts) < 3:
return True
else:
i3s_time_tz = parts[2]
date = datetime.strptime(i3s_datetime, TIME_FORMAT)
# calculate the time delta
utcnow = datetime.utcnow()
delta = datetime(
date.year, date.month, date.day, date.hour, date.minute
) - datetime(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute)
# create our custom timezone
try:
self.tz = Tz(i3s_time_tz, delta)
except ValueError:
return False
return True | python | def set_time_zone(self, item):
# parse i3status date
i3s_time = item["full_text"].encode("UTF-8", "replace")
try:
# python3 compatibility code
i3s_time = i3s_time.decode()
except: # noqa e722
pass
# get datetime and time zone info
parts = i3s_time.split()
i3s_datetime = " ".join(parts[:2])
# occassionally we do not get the timezone name
if len(parts) < 3:
return True
else:
i3s_time_tz = parts[2]
date = datetime.strptime(i3s_datetime, TIME_FORMAT)
# calculate the time delta
utcnow = datetime.utcnow()
delta = datetime(
date.year, date.month, date.day, date.hour, date.minute
) - datetime(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute)
# create our custom timezone
try:
self.tz = Tz(i3s_time_tz, delta)
except ValueError:
return False
return True | [
"def",
"set_time_zone",
"(",
"self",
",",
"item",
")",
":",
"# parse i3status date",
"i3s_time",
"=",
"item",
"[",
"\"full_text\"",
"]",
".",
"encode",
"(",
"\"UTF-8\"",
",",
"\"replace\"",
")",
"try",
":",
"# python3 compatibility code",
"i3s_time",
"=",
"i3s_t... | Work out the time zone and create a shim tzinfo.
We return True if all is good or False if there was an issue and we
need to re check the time zone. see issue #1375 | [
"Work",
"out",
"the",
"time",
"zone",
"and",
"create",
"a",
"shim",
"tzinfo",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L208-L243 |
231,203 | ultrabug/py3status | py3status/i3status.py | I3status.setup | def setup(self):
"""
Do any setup work needed to run i3status modules
"""
for conf_name in self.py3_config["i3s_modules"]:
module = I3statusModule(conf_name, self)
self.i3modules[conf_name] = module
if module.is_time_module:
self.time_modules.append(module) | python | def setup(self):
for conf_name in self.py3_config["i3s_modules"]:
module = I3statusModule(conf_name, self)
self.i3modules[conf_name] = module
if module.is_time_module:
self.time_modules.append(module) | [
"def",
"setup",
"(",
"self",
")",
":",
"for",
"conf_name",
"in",
"self",
".",
"py3_config",
"[",
"\"i3s_modules\"",
"]",
":",
"module",
"=",
"I3statusModule",
"(",
"conf_name",
",",
"self",
")",
"self",
".",
"i3modules",
"[",
"conf_name",
"]",
"=",
"modu... | Do any setup work needed to run i3status modules | [
"Do",
"any",
"setup",
"work",
"needed",
"to",
"run",
"i3status",
"modules"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L297-L305 |
231,204 | ultrabug/py3status | py3status/i3status.py | I3status.valid_config_param | def valid_config_param(self, param_name, cleanup=False):
"""
Check if a given section name is a valid parameter for i3status.
"""
if cleanup:
valid_config_params = [
_
for _ in self.i3status_module_names
if _ not in ["cpu_usage", "ddate", "ipv6", "load", "time"]
]
else:
valid_config_params = self.i3status_module_names + ["general", "order"]
return param_name.split(" ")[0] in valid_config_params | python | def valid_config_param(self, param_name, cleanup=False):
if cleanup:
valid_config_params = [
_
for _ in self.i3status_module_names
if _ not in ["cpu_usage", "ddate", "ipv6", "load", "time"]
]
else:
valid_config_params = self.i3status_module_names + ["general", "order"]
return param_name.split(" ")[0] in valid_config_params | [
"def",
"valid_config_param",
"(",
"self",
",",
"param_name",
",",
"cleanup",
"=",
"False",
")",
":",
"if",
"cleanup",
":",
"valid_config_params",
"=",
"[",
"_",
"for",
"_",
"in",
"self",
".",
"i3status_module_names",
"if",
"_",
"not",
"in",
"[",
"\"cpu_usa... | Check if a given section name is a valid parameter for i3status. | [
"Check",
"if",
"a",
"given",
"section",
"name",
"is",
"a",
"valid",
"parameter",
"for",
"i3status",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L307-L319 |
231,205 | ultrabug/py3status | py3status/i3status.py | I3status.set_responses | def set_responses(self, json_list):
"""
Set the given i3status responses on their respective configuration.
"""
self.update_json_list()
updates = []
for index, item in enumerate(self.json_list):
conf_name = self.py3_config["i3s_modules"][index]
module = self.i3modules[conf_name]
if module.update_from_item(item):
updates.append(conf_name)
if updates:
self.py3_wrapper.notify_update(updates) | python | def set_responses(self, json_list):
self.update_json_list()
updates = []
for index, item in enumerate(self.json_list):
conf_name = self.py3_config["i3s_modules"][index]
module = self.i3modules[conf_name]
if module.update_from_item(item):
updates.append(conf_name)
if updates:
self.py3_wrapper.notify_update(updates) | [
"def",
"set_responses",
"(",
"self",
",",
"json_list",
")",
":",
"self",
".",
"update_json_list",
"(",
")",
"updates",
"=",
"[",
"]",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"json_list",
")",
":",
"conf_name",
"=",
"self",
"."... | Set the given i3status responses on their respective configuration. | [
"Set",
"the",
"given",
"i3status",
"responses",
"on",
"their",
"respective",
"configuration",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L321-L334 |
231,206 | ultrabug/py3status | py3status/i3status.py | I3status.write_in_tmpfile | def write_in_tmpfile(text, tmpfile):
"""
Write the given text in the given tmpfile in python2 and python3.
"""
try:
tmpfile.write(text)
except TypeError:
tmpfile.write(str.encode(text))
except UnicodeEncodeError:
tmpfile.write(text.encode("utf-8")) | python | def write_in_tmpfile(text, tmpfile):
try:
tmpfile.write(text)
except TypeError:
tmpfile.write(str.encode(text))
except UnicodeEncodeError:
tmpfile.write(text.encode("utf-8")) | [
"def",
"write_in_tmpfile",
"(",
"text",
",",
"tmpfile",
")",
":",
"try",
":",
"tmpfile",
".",
"write",
"(",
"text",
")",
"except",
"TypeError",
":",
"tmpfile",
".",
"write",
"(",
"str",
".",
"encode",
"(",
"text",
")",
")",
"except",
"UnicodeEncodeError"... | Write the given text in the given tmpfile in python2 and python3. | [
"Write",
"the",
"given",
"text",
"in",
"the",
"given",
"tmpfile",
"in",
"python2",
"and",
"python3",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L346-L355 |
231,207 | ultrabug/py3status | py3status/i3status.py | I3status.write_tmp_i3status_config | def write_tmp_i3status_config(self, tmpfile):
"""
Given a temporary file descriptor, write a valid i3status config file
based on the parsed one from 'i3status_config_path'.
"""
# order += ...
for module in self.py3_config["i3s_modules"]:
self.write_in_tmpfile('order += "%s"\n' % module, tmpfile)
self.write_in_tmpfile("\n", tmpfile)
# config params for general section and each module
for section_name in ["general"] + self.py3_config["i3s_modules"]:
section = self.py3_config[section_name]
self.write_in_tmpfile("%s {\n" % section_name, tmpfile)
for key, value in section.items():
# don't include color values except in the general section
if key.startswith("color"):
if (
section_name.split(" ")[0] not in I3S_COLOR_MODULES
or key not in I3S_ALLOWED_COLORS
):
continue
# Set known fixed format for time and tztime so we can work
# out the timezone
if section_name.split()[0] in TIME_MODULES:
if key == "format":
value = TZTIME_FORMAT
if key == "format_time":
continue
if isinstance(value, bool):
value = "{}".format(value).lower()
self.write_in_tmpfile(' %s = "%s"\n' % (key, value), tmpfile)
self.write_in_tmpfile("}\n\n", tmpfile)
tmpfile.flush() | python | def write_tmp_i3status_config(self, tmpfile):
# order += ...
for module in self.py3_config["i3s_modules"]:
self.write_in_tmpfile('order += "%s"\n' % module, tmpfile)
self.write_in_tmpfile("\n", tmpfile)
# config params for general section and each module
for section_name in ["general"] + self.py3_config["i3s_modules"]:
section = self.py3_config[section_name]
self.write_in_tmpfile("%s {\n" % section_name, tmpfile)
for key, value in section.items():
# don't include color values except in the general section
if key.startswith("color"):
if (
section_name.split(" ")[0] not in I3S_COLOR_MODULES
or key not in I3S_ALLOWED_COLORS
):
continue
# Set known fixed format for time and tztime so we can work
# out the timezone
if section_name.split()[0] in TIME_MODULES:
if key == "format":
value = TZTIME_FORMAT
if key == "format_time":
continue
if isinstance(value, bool):
value = "{}".format(value).lower()
self.write_in_tmpfile(' %s = "%s"\n' % (key, value), tmpfile)
self.write_in_tmpfile("}\n\n", tmpfile)
tmpfile.flush() | [
"def",
"write_tmp_i3status_config",
"(",
"self",
",",
"tmpfile",
")",
":",
"# order += ...",
"for",
"module",
"in",
"self",
".",
"py3_config",
"[",
"\"i3s_modules\"",
"]",
":",
"self",
".",
"write_in_tmpfile",
"(",
"'order += \"%s\"\\n'",
"%",
"module",
",",
"tm... | Given a temporary file descriptor, write a valid i3status config file
based on the parsed one from 'i3status_config_path'. | [
"Given",
"a",
"temporary",
"file",
"descriptor",
"write",
"a",
"valid",
"i3status",
"config",
"file",
"based",
"on",
"the",
"parsed",
"one",
"from",
"i3status_config_path",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L357-L389 |
231,208 | ultrabug/py3status | py3status/i3status.py | I3status.spawn_i3status | def spawn_i3status(self):
"""
Spawn i3status using a self generated config file and poll its output.
"""
try:
with NamedTemporaryFile(prefix="py3status_") as tmpfile:
self.write_tmp_i3status_config(tmpfile)
i3status_pipe = Popen(
[self.i3status_path, "-c", tmpfile.name],
stdout=PIPE,
stderr=PIPE,
# Ignore the SIGTSTP signal for this subprocess
preexec_fn=lambda: signal(SIGTSTP, SIG_IGN),
)
self.py3_wrapper.log(
"i3status spawned using config file {}".format(tmpfile.name)
)
self.poller_inp = IOPoller(i3status_pipe.stdout)
self.poller_err = IOPoller(i3status_pipe.stderr)
self.tmpfile_path = tmpfile.name
# Store the pipe so we can signal it
self.i3status_pipe = i3status_pipe
try:
# loop on i3status output
while self.py3_wrapper.running:
line = self.poller_inp.readline()
if line:
# remove leading comma if present
if line[0] == ",":
line = line[1:]
if line.startswith("[{"):
json_list = loads(line)
self.last_output = json_list
self.set_responses(json_list)
self.ready = True
else:
err = self.poller_err.readline()
code = i3status_pipe.poll()
if code is not None:
msg = "i3status died"
if err:
msg += " and said: {}".format(err)
else:
msg += " with code {}".format(code)
raise IOError(msg)
except IOError:
err = sys.exc_info()[1]
self.error = err
self.py3_wrapper.log(err, "error")
except OSError:
self.error = "Problem starting i3status maybe it is not installed"
except Exception:
self.py3_wrapper.report_exception("", notify_user=True)
self.i3status_pipe = None | python | def spawn_i3status(self):
try:
with NamedTemporaryFile(prefix="py3status_") as tmpfile:
self.write_tmp_i3status_config(tmpfile)
i3status_pipe = Popen(
[self.i3status_path, "-c", tmpfile.name],
stdout=PIPE,
stderr=PIPE,
# Ignore the SIGTSTP signal for this subprocess
preexec_fn=lambda: signal(SIGTSTP, SIG_IGN),
)
self.py3_wrapper.log(
"i3status spawned using config file {}".format(tmpfile.name)
)
self.poller_inp = IOPoller(i3status_pipe.stdout)
self.poller_err = IOPoller(i3status_pipe.stderr)
self.tmpfile_path = tmpfile.name
# Store the pipe so we can signal it
self.i3status_pipe = i3status_pipe
try:
# loop on i3status output
while self.py3_wrapper.running:
line = self.poller_inp.readline()
if line:
# remove leading comma if present
if line[0] == ",":
line = line[1:]
if line.startswith("[{"):
json_list = loads(line)
self.last_output = json_list
self.set_responses(json_list)
self.ready = True
else:
err = self.poller_err.readline()
code = i3status_pipe.poll()
if code is not None:
msg = "i3status died"
if err:
msg += " and said: {}".format(err)
else:
msg += " with code {}".format(code)
raise IOError(msg)
except IOError:
err = sys.exc_info()[1]
self.error = err
self.py3_wrapper.log(err, "error")
except OSError:
self.error = "Problem starting i3status maybe it is not installed"
except Exception:
self.py3_wrapper.report_exception("", notify_user=True)
self.i3status_pipe = None | [
"def",
"spawn_i3status",
"(",
"self",
")",
":",
"try",
":",
"with",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"\"py3status_\"",
")",
"as",
"tmpfile",
":",
"self",
".",
"write_tmp_i3status_config",
"(",
"tmpfile",
")",
"i3status_pipe",
"=",
"Popen",
"(",
"[",
... | Spawn i3status using a self generated config file and poll its output. | [
"Spawn",
"i3status",
"using",
"a",
"self",
"generated",
"config",
"file",
"and",
"poll",
"its",
"output",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/i3status.py#L419-L477 |
231,209 | ultrabug/py3status | py3status/private.py | catch_factory | def catch_factory(attr):
"""
Factory returning a catch function
"""
def _catch(s, *args, **kw):
"""
This is used to catch and process all calls.
"""
def process(value):
"""
return the actual value after processing
"""
if attr.startswith("__"):
# __repr__, __str__ etc
return getattr(value, attr)(*args, **kw)
else:
# upper, lower etc
return getattr(u"".__class__, attr)(value, *args, **kw)
stack = inspect.stack()
mod = inspect.getmodule(stack[1][0])
# We are called from the owning module so allow
if mod.__name__.split(".")[-1] == s._module_name:
return process(s._value)
# very shallow calling no stack
if len(stack) < 3:
return process(s._private)
# Check if this is an internal or external module. We need to allow
# calls to modules like requests etc
remote = not inspect.getmodule(stack[2][0]).__name__.startswith("py3status")
valid = False
# go through the stack to see how we came through the code
for frame in stack[2:]:
mod = inspect.getmodule(frame[0])
if remote and mod.__name__.split(".")[-1] == s._module_name:
# the call to an external module started in the correct module
# so allow this usage
valid = True
break
if mod.__name__ == "py3status.py3" and frame[3] == "request":
# Py3.request has special needs due so it is allowed to access
# private variables.
valid = True
break
if mod.__name__.startswith("py3status"):
# We were somewhere else in py3status than the module, maybe we
# are doing some logging. Prevent usage
return process(s._private)
if valid:
return process(s._value)
return process(s._private)
return _catch | python | def catch_factory(attr):
def _catch(s, *args, **kw):
"""
This is used to catch and process all calls.
"""
def process(value):
"""
return the actual value after processing
"""
if attr.startswith("__"):
# __repr__, __str__ etc
return getattr(value, attr)(*args, **kw)
else:
# upper, lower etc
return getattr(u"".__class__, attr)(value, *args, **kw)
stack = inspect.stack()
mod = inspect.getmodule(stack[1][0])
# We are called from the owning module so allow
if mod.__name__.split(".")[-1] == s._module_name:
return process(s._value)
# very shallow calling no stack
if len(stack) < 3:
return process(s._private)
# Check if this is an internal or external module. We need to allow
# calls to modules like requests etc
remote = not inspect.getmodule(stack[2][0]).__name__.startswith("py3status")
valid = False
# go through the stack to see how we came through the code
for frame in stack[2:]:
mod = inspect.getmodule(frame[0])
if remote and mod.__name__.split(".")[-1] == s._module_name:
# the call to an external module started in the correct module
# so allow this usage
valid = True
break
if mod.__name__ == "py3status.py3" and frame[3] == "request":
# Py3.request has special needs due so it is allowed to access
# private variables.
valid = True
break
if mod.__name__.startswith("py3status"):
# We were somewhere else in py3status than the module, maybe we
# are doing some logging. Prevent usage
return process(s._private)
if valid:
return process(s._value)
return process(s._private)
return _catch | [
"def",
"catch_factory",
"(",
"attr",
")",
":",
"def",
"_catch",
"(",
"s",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"\n This is used to catch and process all calls.\n \"\"\"",
"def",
"process",
"(",
"value",
")",
":",
"\"\"\"\n ... | Factory returning a catch function | [
"Factory",
"returning",
"a",
"catch",
"function"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/private.py#L65-L119 |
231,210 | ultrabug/py3status | py3status/modules/github.py | Py3status._github_count | def _github_count(self, url):
"""
Get counts for requests that return 'total_count' in the json response.
"""
url = self.url_api + url + "&per_page=1"
# if we have authentication details use them as we get better
# rate-limiting.
if self.username and self.auth_token:
auth = (self.username, self.auth_token)
else:
auth = None
try:
info = self.py3.request(url, auth=auth)
except (self.py3.RequestException):
return
if info and info.status_code == 200:
return int(info.json()["total_count"])
if info.status_code == 422:
if not self.repo_warning:
self.py3.notify_user("Github repo cannot be found.")
self.repo_warning = True
return "?" | python | def _github_count(self, url):
url = self.url_api + url + "&per_page=1"
# if we have authentication details use them as we get better
# rate-limiting.
if self.username and self.auth_token:
auth = (self.username, self.auth_token)
else:
auth = None
try:
info = self.py3.request(url, auth=auth)
except (self.py3.RequestException):
return
if info and info.status_code == 200:
return int(info.json()["total_count"])
if info.status_code == 422:
if not self.repo_warning:
self.py3.notify_user("Github repo cannot be found.")
self.repo_warning = True
return "?" | [
"def",
"_github_count",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"url_api",
"+",
"url",
"+",
"\"&per_page=1\"",
"# if we have authentication details use them as we get better",
"# rate-limiting.",
"if",
"self",
".",
"username",
"and",
"self",
".",... | Get counts for requests that return 'total_count' in the json response. | [
"Get",
"counts",
"for",
"requests",
"that",
"return",
"total_count",
"in",
"the",
"json",
"response",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/github.py#L127-L148 |
231,211 | ultrabug/py3status | py3status/modules/github.py | Py3status._notifications | def _notifications(self):
"""
Get the number of unread notifications.
"""
if not self.username or not self.auth_token:
if not self.notification_warning:
self.py3.notify_user(
"Github module needs username and "
"auth_token to check notifications."
)
self.notification_warning = True
return "?"
if self.notifications == "all" or not self.repo:
url = self.url_api + "/notifications"
else:
url = self.url_api + "/repos/" + self.repo + "/notifications"
url += "?per_page=100"
try:
info = self.py3.request(url, auth=(self.username, self.auth_token))
except (self.py3.RequestException):
return
if info.status_code == 200:
links = info.headers.get("Link")
if not links:
return len(info.json())
last_page = 1
for link in links.split(","):
if 'rel="last"' in link:
last_url = link[link.find("<") + 1 : link.find(">")]
parsed = urlparse.urlparse(last_url)
last_page = int(urlparse.parse_qs(parsed.query)["page"][0])
if last_page == 1:
return len(info.json())
try:
last_page_info = self.py3.request(
last_url, auth=(self.username, self.auth_token)
)
except self.py3.RequestException:
return
return len(info.json()) * (last_page - 1) + len(last_page_info.json())
if info.status_code == 404:
if not self.repo_warning:
self.py3.notify_user("Github repo cannot be found.")
self.repo_warning = True | python | def _notifications(self):
if not self.username or not self.auth_token:
if not self.notification_warning:
self.py3.notify_user(
"Github module needs username and "
"auth_token to check notifications."
)
self.notification_warning = True
return "?"
if self.notifications == "all" or not self.repo:
url = self.url_api + "/notifications"
else:
url = self.url_api + "/repos/" + self.repo + "/notifications"
url += "?per_page=100"
try:
info = self.py3.request(url, auth=(self.username, self.auth_token))
except (self.py3.RequestException):
return
if info.status_code == 200:
links = info.headers.get("Link")
if not links:
return len(info.json())
last_page = 1
for link in links.split(","):
if 'rel="last"' in link:
last_url = link[link.find("<") + 1 : link.find(">")]
parsed = urlparse.urlparse(last_url)
last_page = int(urlparse.parse_qs(parsed.query)["page"][0])
if last_page == 1:
return len(info.json())
try:
last_page_info = self.py3.request(
last_url, auth=(self.username, self.auth_token)
)
except self.py3.RequestException:
return
return len(info.json()) * (last_page - 1) + len(last_page_info.json())
if info.status_code == 404:
if not self.repo_warning:
self.py3.notify_user("Github repo cannot be found.")
self.repo_warning = True | [
"def",
"_notifications",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"auth_token",
":",
"if",
"not",
"self",
".",
"notification_warning",
":",
"self",
".",
"py3",
".",
"notify_user",
"(",
"\"Github module needs user... | Get the number of unread notifications. | [
"Get",
"the",
"number",
"of",
"unread",
"notifications",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/github.py#L150-L198 |
231,212 | ultrabug/py3status | py3status/core.py | Common.get_config_attribute | def get_config_attribute(self, name, attribute):
"""
Look for the attribute in the config. Start with the named module and
then walk up through any containing group and then try the general
section of the config.
"""
# A user can set a param to None in the config to prevent a param
# being used. This is important when modules do something like
#
# color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD
config = self.config["py3_config"]
param = config[name].get(attribute, self.none_setting)
if hasattr(param, "none_setting") and name in config[".module_groups"]:
for module in config[".module_groups"][name]:
if attribute in config.get(module, {}):
param = config[module].get(attribute)
break
if hasattr(param, "none_setting"):
# check py3status config section
param = config["py3status"].get(attribute, self.none_setting)
if hasattr(param, "none_setting"):
# check py3status general section
param = config["general"].get(attribute, self.none_setting)
if param and (attribute == "color" or attribute.startswith("color_")):
if param[0] != "#":
# named color
param = COLOR_NAMES.get(param.lower(), self.none_setting)
elif len(param) == 4:
# This is a color like #123 convert it to #112233
param = (
"#"
+ param[1]
+ param[1]
+ param[2]
+ param[2]
+ param[3]
+ param[3]
)
return param | python | def get_config_attribute(self, name, attribute):
# A user can set a param to None in the config to prevent a param
# being used. This is important when modules do something like
#
# color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD
config = self.config["py3_config"]
param = config[name].get(attribute, self.none_setting)
if hasattr(param, "none_setting") and name in config[".module_groups"]:
for module in config[".module_groups"][name]:
if attribute in config.get(module, {}):
param = config[module].get(attribute)
break
if hasattr(param, "none_setting"):
# check py3status config section
param = config["py3status"].get(attribute, self.none_setting)
if hasattr(param, "none_setting"):
# check py3status general section
param = config["general"].get(attribute, self.none_setting)
if param and (attribute == "color" or attribute.startswith("color_")):
if param[0] != "#":
# named color
param = COLOR_NAMES.get(param.lower(), self.none_setting)
elif len(param) == 4:
# This is a color like #123 convert it to #112233
param = (
"#"
+ param[1]
+ param[1]
+ param[2]
+ param[2]
+ param[3]
+ param[3]
)
return param | [
"def",
"get_config_attribute",
"(",
"self",
",",
"name",
",",
"attribute",
")",
":",
"# A user can set a param to None in the config to prevent a param",
"# being used. This is important when modules do something like",
"#",
"# color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD",
"confi... | Look for the attribute in the config. Start with the named module and
then walk up through any containing group and then try the general
section of the config. | [
"Look",
"for",
"the",
"attribute",
"in",
"the",
"config",
".",
"Start",
"with",
"the",
"named",
"module",
"and",
"then",
"walk",
"up",
"through",
"any",
"containing",
"group",
"and",
"then",
"try",
"the",
"general",
"section",
"of",
"the",
"config",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L138-L177 |
231,213 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.timeout_queue_add | def timeout_queue_add(self, item, cache_time=0):
"""
Add a item to be run at a future time.
This must be a Module, I3statusModule or a Task
"""
# add the info to the add queue. We do this so that actually adding
# the module is done in the core thread.
self.timeout_add_queue.append((item, cache_time))
# if the timeout_add_queue is not due to be processed until after this
# update request is due then trigger an update now.
if self.timeout_due is None or cache_time < self.timeout_due:
self.update_request.set() | python | def timeout_queue_add(self, item, cache_time=0):
# add the info to the add queue. We do this so that actually adding
# the module is done in the core thread.
self.timeout_add_queue.append((item, cache_time))
# if the timeout_add_queue is not due to be processed until after this
# update request is due then trigger an update now.
if self.timeout_due is None or cache_time < self.timeout_due:
self.update_request.set() | [
"def",
"timeout_queue_add",
"(",
"self",
",",
"item",
",",
"cache_time",
"=",
"0",
")",
":",
"# add the info to the add queue. We do this so that actually adding",
"# the module is done in the core thread.",
"self",
".",
"timeout_add_queue",
".",
"append",
"(",
"(",
"item"... | Add a item to be run at a future time.
This must be a Module, I3statusModule or a Task | [
"Add",
"a",
"item",
"to",
"be",
"run",
"at",
"a",
"future",
"time",
".",
"This",
"must",
"be",
"a",
"Module",
"I3statusModule",
"or",
"a",
"Task"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L292-L303 |
231,214 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.timeout_process_add_queue | def timeout_process_add_queue(self, module, cache_time):
"""
Add a module to the timeout_queue if it is scheduled in the future or
if it is due for an update immediately just trigger that.
the timeout_queue is a dict with the scheduled time as the key and the
value is a list of module instance names due to be updated at that
point. An ordered list of keys is kept to allow easy checking of when
updates are due. A list is also kept of which modules are in the
update_queue to save having to search for modules in it unless needed.
"""
# If already set to update do nothing
if module in self.timeout_update_due:
return
# remove if already in the queue
key = self.timeout_queue_lookup.get(module)
if key:
queue_item = self.timeout_queue[key]
queue_item.remove(module)
if not queue_item:
del self.timeout_queue[key]
self.timeout_keys.remove(key)
if cache_time == 0:
# if cache_time is 0 we can just trigger the module update
self.timeout_update_due.append(module)
self.timeout_queue_lookup[module] = None
else:
# add the module to the timeout queue
if cache_time not in self.timeout_keys:
self.timeout_queue[cache_time] = set([module])
self.timeout_keys.append(cache_time)
# sort keys so earliest is first
self.timeout_keys.sort()
# when is next timeout due?
try:
self.timeout_due = self.timeout_keys[0]
except IndexError:
self.timeout_due = None
else:
self.timeout_queue[cache_time].add(module)
# note that the module is in the timeout_queue
self.timeout_queue_lookup[module] = cache_time | python | def timeout_process_add_queue(self, module, cache_time):
# If already set to update do nothing
if module in self.timeout_update_due:
return
# remove if already in the queue
key = self.timeout_queue_lookup.get(module)
if key:
queue_item = self.timeout_queue[key]
queue_item.remove(module)
if not queue_item:
del self.timeout_queue[key]
self.timeout_keys.remove(key)
if cache_time == 0:
# if cache_time is 0 we can just trigger the module update
self.timeout_update_due.append(module)
self.timeout_queue_lookup[module] = None
else:
# add the module to the timeout queue
if cache_time not in self.timeout_keys:
self.timeout_queue[cache_time] = set([module])
self.timeout_keys.append(cache_time)
# sort keys so earliest is first
self.timeout_keys.sort()
# when is next timeout due?
try:
self.timeout_due = self.timeout_keys[0]
except IndexError:
self.timeout_due = None
else:
self.timeout_queue[cache_time].add(module)
# note that the module is in the timeout_queue
self.timeout_queue_lookup[module] = cache_time | [
"def",
"timeout_process_add_queue",
"(",
"self",
",",
"module",
",",
"cache_time",
")",
":",
"# If already set to update do nothing",
"if",
"module",
"in",
"self",
".",
"timeout_update_due",
":",
"return",
"# remove if already in the queue",
"key",
"=",
"self",
".",
"... | Add a module to the timeout_queue if it is scheduled in the future or
if it is due for an update immediately just trigger that.
the timeout_queue is a dict with the scheduled time as the key and the
value is a list of module instance names due to be updated at that
point. An ordered list of keys is kept to allow easy checking of when
updates are due. A list is also kept of which modules are in the
update_queue to save having to search for modules in it unless needed. | [
"Add",
"a",
"module",
"to",
"the",
"timeout_queue",
"if",
"it",
"is",
"scheduled",
"in",
"the",
"future",
"or",
"if",
"it",
"is",
"due",
"for",
"an",
"update",
"immediately",
"just",
"trigger",
"that",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L305-L349 |
231,215 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.timeout_queue_process | def timeout_queue_process(self):
"""
Check the timeout_queue and set any due modules to update.
"""
# process any items that need adding to the queue
while self.timeout_add_queue:
self.timeout_process_add_queue(*self.timeout_add_queue.popleft())
now = time.time()
due_timeouts = []
# find any due timeouts
for timeout in self.timeout_keys:
if timeout > now:
break
due_timeouts.append(timeout)
if due_timeouts:
# process them
for timeout in due_timeouts:
modules = self.timeout_queue[timeout]
# remove from the queue
del self.timeout_queue[timeout]
self.timeout_keys.remove(timeout)
for module in modules:
# module no longer in queue
del self.timeout_queue_lookup[module]
# tell module to update
self.timeout_update_due.append(module)
# when is next timeout due?
try:
self.timeout_due = self.timeout_keys[0]
except IndexError:
self.timeout_due = None
# process any finished modules.
# Now that the module has finished running it may have been marked to
# be triggered again. This is most likely to happen when events are
# being processed and the events are arriving much faster than the
# module can handle them. It is important as a module may handle
# events but not trigger the module update. If during the event the
# module is due to update the update is not actioned but it needs to be
# once the events have finished or else the module will no longer
# continue to update.
while self.timeout_finished:
module_name = self.timeout_finished.popleft()
self.timeout_running.discard(module_name)
if module_name in self.timeout_missed:
module = self.timeout_missed.pop(module_name)
self.timeout_update_due.append(module)
# run any modules that are due
while self.timeout_update_due:
module = self.timeout_update_due.popleft()
module_name = getattr(module, "module_full_name", None)
# if the module is running then we do not want to trigger it but
# instead wait till it has finished running and then trigger
if module_name and module_name in self.timeout_running:
self.timeout_missed[module_name] = module
else:
self.timeout_running.add(module_name)
Runner(module, self, module_name)
# we return how long till we next need to process the timeout_queue
if self.timeout_due is not None:
return self.timeout_due - time.time() | python | def timeout_queue_process(self):
# process any items that need adding to the queue
while self.timeout_add_queue:
self.timeout_process_add_queue(*self.timeout_add_queue.popleft())
now = time.time()
due_timeouts = []
# find any due timeouts
for timeout in self.timeout_keys:
if timeout > now:
break
due_timeouts.append(timeout)
if due_timeouts:
# process them
for timeout in due_timeouts:
modules = self.timeout_queue[timeout]
# remove from the queue
del self.timeout_queue[timeout]
self.timeout_keys.remove(timeout)
for module in modules:
# module no longer in queue
del self.timeout_queue_lookup[module]
# tell module to update
self.timeout_update_due.append(module)
# when is next timeout due?
try:
self.timeout_due = self.timeout_keys[0]
except IndexError:
self.timeout_due = None
# process any finished modules.
# Now that the module has finished running it may have been marked to
# be triggered again. This is most likely to happen when events are
# being processed and the events are arriving much faster than the
# module can handle them. It is important as a module may handle
# events but not trigger the module update. If during the event the
# module is due to update the update is not actioned but it needs to be
# once the events have finished or else the module will no longer
# continue to update.
while self.timeout_finished:
module_name = self.timeout_finished.popleft()
self.timeout_running.discard(module_name)
if module_name in self.timeout_missed:
module = self.timeout_missed.pop(module_name)
self.timeout_update_due.append(module)
# run any modules that are due
while self.timeout_update_due:
module = self.timeout_update_due.popleft()
module_name = getattr(module, "module_full_name", None)
# if the module is running then we do not want to trigger it but
# instead wait till it has finished running and then trigger
if module_name and module_name in self.timeout_running:
self.timeout_missed[module_name] = module
else:
self.timeout_running.add(module_name)
Runner(module, self, module_name)
# we return how long till we next need to process the timeout_queue
if self.timeout_due is not None:
return self.timeout_due - time.time() | [
"def",
"timeout_queue_process",
"(",
"self",
")",
":",
"# process any items that need adding to the queue",
"while",
"self",
".",
"timeout_add_queue",
":",
"self",
".",
"timeout_process_add_queue",
"(",
"*",
"self",
".",
"timeout_add_queue",
".",
"popleft",
"(",
")",
... | Check the timeout_queue and set any due modules to update. | [
"Check",
"the",
"timeout_queue",
"and",
"set",
"any",
"due",
"modules",
"to",
"update",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L351-L416 |
231,216 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.gevent_monkey_patch_report | def gevent_monkey_patch_report(self):
"""
Report effective gevent monkey patching on the logs.
"""
try:
import gevent.socket
import socket
if gevent.socket.socket is socket.socket:
self.log("gevent monkey patching is active")
return True
else:
self.notify_user("gevent monkey patching failed.")
except ImportError:
self.notify_user("gevent is not installed, monkey patching failed.")
return False | python | def gevent_monkey_patch_report(self):
try:
import gevent.socket
import socket
if gevent.socket.socket is socket.socket:
self.log("gevent monkey patching is active")
return True
else:
self.notify_user("gevent monkey patching failed.")
except ImportError:
self.notify_user("gevent is not installed, monkey patching failed.")
return False | [
"def",
"gevent_monkey_patch_report",
"(",
"self",
")",
":",
"try",
":",
"import",
"gevent",
".",
"socket",
"import",
"socket",
"if",
"gevent",
".",
"socket",
".",
"socket",
"is",
"socket",
".",
"socket",
":",
"self",
".",
"log",
"(",
"\"gevent monkey patchin... | Report effective gevent monkey patching on the logs. | [
"Report",
"effective",
"gevent",
"monkey",
"patching",
"on",
"the",
"logs",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L418-L433 |
231,217 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.get_user_modules | def get_user_modules(self):
"""
Search configured include directories for user provided modules.
user_modules: {
'weather_yahoo': ('~/i3/py3status/', 'weather_yahoo.py')
}
"""
user_modules = {}
for include_path in self.config["include_paths"]:
for f_name in sorted(os.listdir(include_path)):
if not f_name.endswith(".py"):
continue
module_name = f_name[:-3]
# do not overwrite modules if already found
if module_name in user_modules:
pass
user_modules[module_name] = (include_path, f_name)
return user_modules | python | def get_user_modules(self):
user_modules = {}
for include_path in self.config["include_paths"]:
for f_name in sorted(os.listdir(include_path)):
if not f_name.endswith(".py"):
continue
module_name = f_name[:-3]
# do not overwrite modules if already found
if module_name in user_modules:
pass
user_modules[module_name] = (include_path, f_name)
return user_modules | [
"def",
"get_user_modules",
"(",
"self",
")",
":",
"user_modules",
"=",
"{",
"}",
"for",
"include_path",
"in",
"self",
".",
"config",
"[",
"\"include_paths\"",
"]",
":",
"for",
"f_name",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"include_path",
")",
... | Search configured include directories for user provided modules.
user_modules: {
'weather_yahoo': ('~/i3/py3status/', 'weather_yahoo.py')
} | [
"Search",
"configured",
"include",
"directories",
"for",
"user",
"provided",
"modules",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L435-L453 |
231,218 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.get_user_configured_modules | def get_user_configured_modules(self):
"""
Get a dict of all available and configured py3status modules
in the user's i3status.conf.
"""
user_modules = {}
if not self.py3_modules:
return user_modules
for module_name, module_info in self.get_user_modules().items():
for module in self.py3_modules:
if module_name == module.split(" ")[0]:
include_path, f_name = module_info
user_modules[module_name] = (include_path, f_name)
return user_modules | python | def get_user_configured_modules(self):
user_modules = {}
if not self.py3_modules:
return user_modules
for module_name, module_info in self.get_user_modules().items():
for module in self.py3_modules:
if module_name == module.split(" ")[0]:
include_path, f_name = module_info
user_modules[module_name] = (include_path, f_name)
return user_modules | [
"def",
"get_user_configured_modules",
"(",
"self",
")",
":",
"user_modules",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"py3_modules",
":",
"return",
"user_modules",
"for",
"module_name",
",",
"module_info",
"in",
"self",
".",
"get_user_modules",
"(",
")",
".",
... | Get a dict of all available and configured py3status modules
in the user's i3status.conf. | [
"Get",
"a",
"dict",
"of",
"all",
"available",
"and",
"configured",
"py3status",
"modules",
"in",
"the",
"user",
"s",
"i3status",
".",
"conf",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L455-L468 |
231,219 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.notify_user | def notify_user(
self,
msg,
level="error",
rate_limit=None,
module_name="",
icon=None,
title="py3status",
):
"""
Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency.
"""
dbus = self.config.get("dbus_notify")
if dbus:
# force msg, icon, title to be a string
title = u"{}".format(title)
msg = u"{}".format(msg)
if icon:
icon = u"{}".format(icon)
else:
msg = u"py3status: {}".format(msg)
if level != "info" and module_name == "":
fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)"
msg = fix_msg.format(msg)
# Rate limiting. If rate limiting then we need to calculate the time
# period for which the message should not be repeated. We just use
# A simple chunked time model where a message cannot be repeated in a
# given time period. Messages can be repeated more frequently but must
# be in different time periods.
limit_key = ""
if rate_limit:
try:
limit_key = time.time() // rate_limit
except TypeError:
pass
# We use a hash to see if the message is being repeated. This is crude
# and imperfect but should work for our needs.
msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title))
if msg_hash in self.notified_messages:
return
elif module_name:
log_msg = 'Module `%s` sent a notification. "%s: %s"' % (
module_name,
title,
msg,
)
self.log(log_msg, level)
else:
self.log(msg, level)
self.notified_messages.add(msg_hash)
try:
if dbus:
# fix any html entities
msg = msg.replace("&", "&")
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
cmd = ["notify-send"]
if icon:
cmd += ["-i", icon]
cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"]
cmd += [title, msg]
else:
py3_config = self.config.get("py3_config", {})
nagbar_font = py3_config.get("py3status", {}).get("nagbar_font")
wm_nag = self.config["wm"]["nag"]
cmd = [wm_nag, "-m", msg, "-t", level]
if nagbar_font:
cmd += ["-f", nagbar_font]
Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
except Exception as err:
self.log("notify_user error: %s" % err) | python | def notify_user(
self,
msg,
level="error",
rate_limit=None,
module_name="",
icon=None,
title="py3status",
):
dbus = self.config.get("dbus_notify")
if dbus:
# force msg, icon, title to be a string
title = u"{}".format(title)
msg = u"{}".format(msg)
if icon:
icon = u"{}".format(icon)
else:
msg = u"py3status: {}".format(msg)
if level != "info" and module_name == "":
fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)"
msg = fix_msg.format(msg)
# Rate limiting. If rate limiting then we need to calculate the time
# period for which the message should not be repeated. We just use
# A simple chunked time model where a message cannot be repeated in a
# given time period. Messages can be repeated more frequently but must
# be in different time periods.
limit_key = ""
if rate_limit:
try:
limit_key = time.time() // rate_limit
except TypeError:
pass
# We use a hash to see if the message is being repeated. This is crude
# and imperfect but should work for our needs.
msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title))
if msg_hash in self.notified_messages:
return
elif module_name:
log_msg = 'Module `%s` sent a notification. "%s: %s"' % (
module_name,
title,
msg,
)
self.log(log_msg, level)
else:
self.log(msg, level)
self.notified_messages.add(msg_hash)
try:
if dbus:
# fix any html entities
msg = msg.replace("&", "&")
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
cmd = ["notify-send"]
if icon:
cmd += ["-i", icon]
cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"]
cmd += [title, msg]
else:
py3_config = self.config.get("py3_config", {})
nagbar_font = py3_config.get("py3status", {}).get("nagbar_font")
wm_nag = self.config["wm"]["nag"]
cmd = [wm_nag, "-m", msg, "-t", level]
if nagbar_font:
cmd += ["-f", nagbar_font]
Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
except Exception as err:
self.log("notify_user error: %s" % err) | [
"def",
"notify_user",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"\"error\"",
",",
"rate_limit",
"=",
"None",
",",
"module_name",
"=",
"\"\"",
",",
"icon",
"=",
"None",
",",
"title",
"=",
"\"py3status\"",
",",
")",
":",
"dbus",
"=",
"self",
".",
"co... | Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency. | [
"Display",
"notification",
"to",
"user",
"via",
"i3",
"-",
"nagbar",
"or",
"send",
"-",
"notify",
"We",
"also",
"make",
"sure",
"to",
"log",
"anything",
"to",
"keep",
"trace",
"of",
"it",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L619-L694 |
231,220 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.stop | def stop(self):
"""
Set the Event lock, this will break all threads' loops.
"""
self.running = False
# stop the command server
try:
self.commands_thread.kill()
except: # noqa e722
pass
try:
self.lock.set()
if self.config["debug"]:
self.log("lock set, exiting")
# run kill() method on all py3status modules
for module in self.modules.values():
module.kill()
except: # noqa e722
pass | python | def stop(self):
self.running = False
# stop the command server
try:
self.commands_thread.kill()
except: # noqa e722
pass
try:
self.lock.set()
if self.config["debug"]:
self.log("lock set, exiting")
# run kill() method on all py3status modules
for module in self.modules.values():
module.kill()
except: # noqa e722
pass | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"# stop the command server",
"try",
":",
"self",
".",
"commands_thread",
".",
"kill",
"(",
")",
"except",
":",
"# noqa e722",
"pass",
"try",
":",
"self",
".",
"lock",
".",
"set",... | Set the Event lock, this will break all threads' loops. | [
"Set",
"the",
"Event",
"lock",
"this",
"will",
"break",
"all",
"threads",
"loops",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L696-L715 |
231,221 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.refresh_modules | def refresh_modules(self, module_string=None, exact=True):
"""
Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a module is an i3status one then we refresh i3status.
To prevent abuse, we rate limit this function to 100ms for full
refreshes.
"""
if not module_string:
if time.time() > (self.last_refresh_ts + 0.1):
self.last_refresh_ts = time.time()
else:
# rate limiting
return
update_i3status = False
for name, module in self.output_modules.items():
if (
module_string is None
or (exact and name == module_string)
or (not exact and name.startswith(module_string))
):
if module["type"] == "py3status":
if self.config["debug"]:
self.log("refresh py3status module {}".format(name))
module["module"].force_update()
else:
if self.config["debug"]:
self.log("refresh i3status module {}".format(name))
update_i3status = True
if update_i3status:
self.i3status_thread.refresh_i3status() | python | def refresh_modules(self, module_string=None, exact=True):
if not module_string:
if time.time() > (self.last_refresh_ts + 0.1):
self.last_refresh_ts = time.time()
else:
# rate limiting
return
update_i3status = False
for name, module in self.output_modules.items():
if (
module_string is None
or (exact and name == module_string)
or (not exact and name.startswith(module_string))
):
if module["type"] == "py3status":
if self.config["debug"]:
self.log("refresh py3status module {}".format(name))
module["module"].force_update()
else:
if self.config["debug"]:
self.log("refresh i3status module {}".format(name))
update_i3status = True
if update_i3status:
self.i3status_thread.refresh_i3status() | [
"def",
"refresh_modules",
"(",
"self",
",",
"module_string",
"=",
"None",
",",
"exact",
"=",
"True",
")",
":",
"if",
"not",
"module_string",
":",
"if",
"time",
".",
"time",
"(",
")",
">",
"(",
"self",
".",
"last_refresh_ts",
"+",
"0.1",
")",
":",
"se... | Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a module is an i3status one then we refresh i3status.
To prevent abuse, we rate limit this function to 100ms for full
refreshes. | [
"Update",
"modules",
".",
"if",
"module_string",
"is",
"None",
"all",
"modules",
"are",
"refreshed",
"if",
"module_string",
"then",
"modules",
"with",
"the",
"exact",
"name",
"or",
"those",
"starting",
"with",
"the",
"given",
"string",
"depending",
"on",
"exac... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L717-L749 |
231,222 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.notify_update | def notify_update(self, update, urgent=False):
"""
Name or list of names of modules that have updated.
"""
if not isinstance(update, list):
update = [update]
self.update_queue.extend(update)
# find containers that use the modules that updated
containers = self.config["py3_config"][".module_groups"]
containers_to_update = set()
for item in update:
if item in containers:
containers_to_update.update(set(containers[item]))
# force containers to update
for container in containers_to_update:
container_module = self.output_modules.get(container)
if container_module:
# If the container registered a urgent_function then call it
# if this update is urgent.
if urgent and container_module.get("urgent_function"):
container_module["urgent_function"](update)
# If a container has registered a content_function we use that
# to see if the container needs to be updated.
# We only need to update containers if their active content has
# changed.
if container_module.get("content_function"):
if set(update) & container_module["content_function"]():
container_module["module"].force_update()
else:
# we don't know so just update.
container_module["module"].force_update()
# we need to update the output
if self.update_queue:
self.update_request.set() | python | def notify_update(self, update, urgent=False):
if not isinstance(update, list):
update = [update]
self.update_queue.extend(update)
# find containers that use the modules that updated
containers = self.config["py3_config"][".module_groups"]
containers_to_update = set()
for item in update:
if item in containers:
containers_to_update.update(set(containers[item]))
# force containers to update
for container in containers_to_update:
container_module = self.output_modules.get(container)
if container_module:
# If the container registered a urgent_function then call it
# if this update is urgent.
if urgent and container_module.get("urgent_function"):
container_module["urgent_function"](update)
# If a container has registered a content_function we use that
# to see if the container needs to be updated.
# We only need to update containers if their active content has
# changed.
if container_module.get("content_function"):
if set(update) & container_module["content_function"]():
container_module["module"].force_update()
else:
# we don't know so just update.
container_module["module"].force_update()
# we need to update the output
if self.update_queue:
self.update_request.set() | [
"def",
"notify_update",
"(",
"self",
",",
"update",
",",
"urgent",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"update",
",",
"list",
")",
":",
"update",
"=",
"[",
"update",
"]",
"self",
".",
"update_queue",
".",
"extend",
"(",
"update",
... | Name or list of names of modules that have updated. | [
"Name",
"or",
"list",
"of",
"names",
"of",
"modules",
"that",
"have",
"updated",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L780-L815 |
231,223 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.log | def log(self, msg, level="info"):
"""
log this information to syslog or user provided logfile.
"""
if not self.config.get("log_file"):
# If level was given as a str then convert to actual level
level = LOG_LEVELS.get(level, level)
syslog(level, u"{}".format(msg))
else:
# Binary mode so fs encoding setting is not an issue
with open(self.config["log_file"], "ab") as f:
log_time = time.strftime("%Y-%m-%d %H:%M:%S")
# nice formating of data structures using pretty print
if isinstance(msg, (dict, list, set, tuple)):
msg = pformat(msg)
# if multiline then start the data output on a fresh line
# to aid readability.
if "\n" in msg:
msg = u"\n" + msg
out = u"{} {} {}\n".format(log_time, level.upper(), msg)
try:
# Encode unicode strings to bytes
f.write(out.encode("utf-8"))
except (AttributeError, UnicodeDecodeError):
# Write any byte strings straight to log
f.write(out) | python | def log(self, msg, level="info"):
if not self.config.get("log_file"):
# If level was given as a str then convert to actual level
level = LOG_LEVELS.get(level, level)
syslog(level, u"{}".format(msg))
else:
# Binary mode so fs encoding setting is not an issue
with open(self.config["log_file"], "ab") as f:
log_time = time.strftime("%Y-%m-%d %H:%M:%S")
# nice formating of data structures using pretty print
if isinstance(msg, (dict, list, set, tuple)):
msg = pformat(msg)
# if multiline then start the data output on a fresh line
# to aid readability.
if "\n" in msg:
msg = u"\n" + msg
out = u"{} {} {}\n".format(log_time, level.upper(), msg)
try:
# Encode unicode strings to bytes
f.write(out.encode("utf-8"))
except (AttributeError, UnicodeDecodeError):
# Write any byte strings straight to log
f.write(out) | [
"def",
"log",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"\"info\"",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"get",
"(",
"\"log_file\"",
")",
":",
"# If level was given as a str then convert to actual level",
"level",
"=",
"LOG_LEVELS",
".",
"get",... | log this information to syslog or user provided logfile. | [
"log",
"this",
"information",
"to",
"syslog",
"or",
"user",
"provided",
"logfile",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L817-L842 |
231,224 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.create_output_modules | def create_output_modules(self):
"""
Setup our output modules to allow easy updating of py3modules and
i3status modules allows the same module to be used multiple times.
"""
py3_config = self.config["py3_config"]
i3modules = self.i3status_thread.i3modules
output_modules = self.output_modules
# position in the bar of the modules
positions = {}
for index, name in enumerate(py3_config["order"]):
if name not in positions:
positions[name] = []
positions[name].append(index)
# py3status modules
for name in self.modules:
if name not in output_modules:
output_modules[name] = {}
output_modules[name]["position"] = positions.get(name, [])
output_modules[name]["module"] = self.modules[name]
output_modules[name]["type"] = "py3status"
output_modules[name]["color"] = self.mappings_color.get(name)
# i3status modules
for name in i3modules:
if name not in output_modules:
output_modules[name] = {}
output_modules[name]["position"] = positions.get(name, [])
output_modules[name]["module"] = i3modules[name]
output_modules[name]["type"] = "i3status"
output_modules[name]["color"] = self.mappings_color.get(name)
self.output_modules = output_modules | python | def create_output_modules(self):
py3_config = self.config["py3_config"]
i3modules = self.i3status_thread.i3modules
output_modules = self.output_modules
# position in the bar of the modules
positions = {}
for index, name in enumerate(py3_config["order"]):
if name not in positions:
positions[name] = []
positions[name].append(index)
# py3status modules
for name in self.modules:
if name not in output_modules:
output_modules[name] = {}
output_modules[name]["position"] = positions.get(name, [])
output_modules[name]["module"] = self.modules[name]
output_modules[name]["type"] = "py3status"
output_modules[name]["color"] = self.mappings_color.get(name)
# i3status modules
for name in i3modules:
if name not in output_modules:
output_modules[name] = {}
output_modules[name]["position"] = positions.get(name, [])
output_modules[name]["module"] = i3modules[name]
output_modules[name]["type"] = "i3status"
output_modules[name]["color"] = self.mappings_color.get(name)
self.output_modules = output_modules | [
"def",
"create_output_modules",
"(",
"self",
")",
":",
"py3_config",
"=",
"self",
".",
"config",
"[",
"\"py3_config\"",
"]",
"i3modules",
"=",
"self",
".",
"i3status_thread",
".",
"i3modules",
"output_modules",
"=",
"self",
".",
"output_modules",
"# position in th... | Setup our output modules to allow easy updating of py3modules and
i3status modules allows the same module to be used multiple times. | [
"Setup",
"our",
"output",
"modules",
"to",
"allow",
"easy",
"updating",
"of",
"py3modules",
"and",
"i3status",
"modules",
"allows",
"the",
"same",
"module",
"to",
"be",
"used",
"multiple",
"times",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L844-L876 |
231,225 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.create_mappings | def create_mappings(self, config):
"""
Create any mappings needed for global substitutions eg. colors
"""
mappings = {}
for name, cfg in config.items():
# Ignore special config sections.
if name in CONFIG_SPECIAL_SECTIONS:
continue
color = self.get_config_attribute(name, "color")
if hasattr(color, "none_setting"):
color = None
mappings[name] = color
# Store mappings for later use.
self.mappings_color = mappings | python | def create_mappings(self, config):
mappings = {}
for name, cfg in config.items():
# Ignore special config sections.
if name in CONFIG_SPECIAL_SECTIONS:
continue
color = self.get_config_attribute(name, "color")
if hasattr(color, "none_setting"):
color = None
mappings[name] = color
# Store mappings for later use.
self.mappings_color = mappings | [
"def",
"create_mappings",
"(",
"self",
",",
"config",
")",
":",
"mappings",
"=",
"{",
"}",
"for",
"name",
",",
"cfg",
"in",
"config",
".",
"items",
"(",
")",
":",
"# Ignore special config sections.",
"if",
"name",
"in",
"CONFIG_SPECIAL_SECTIONS",
":",
"conti... | Create any mappings needed for global substitutions eg. colors | [
"Create",
"any",
"mappings",
"needed",
"for",
"global",
"substitutions",
"eg",
".",
"colors"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L878-L892 |
231,226 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.process_module_output | def process_module_output(self, module):
"""
Process the output for a module and return a json string representing it.
Color processing occurs here.
"""
outputs = module["module"].get_latest()
color = module["color"]
if color:
for output in outputs:
# Color: substitute the config defined color
if "color" not in output:
output["color"] = color
# Create the json string output.
return ",".join([dumps(x) for x in outputs]) | python | def process_module_output(self, module):
outputs = module["module"].get_latest()
color = module["color"]
if color:
for output in outputs:
# Color: substitute the config defined color
if "color" not in output:
output["color"] = color
# Create the json string output.
return ",".join([dumps(x) for x in outputs]) | [
"def",
"process_module_output",
"(",
"self",
",",
"module",
")",
":",
"outputs",
"=",
"module",
"[",
"\"module\"",
"]",
".",
"get_latest",
"(",
")",
"color",
"=",
"module",
"[",
"\"color\"",
"]",
"if",
"color",
":",
"for",
"output",
"in",
"outputs",
":",... | Process the output for a module and return a json string representing it.
Color processing occurs here. | [
"Process",
"the",
"output",
"for",
"a",
"module",
"and",
"return",
"a",
"json",
"string",
"representing",
"it",
".",
"Color",
"processing",
"occurs",
"here",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L894-L907 |
231,227 | ultrabug/py3status | py3status/core.py | Py3statusWrapper.run | def run(self):
"""
Main py3status loop, continuously read from i3status and modules
and output it to i3bar for displaying.
"""
# SIGUSR1 forces a refresh of the bar both for py3status and i3status,
# this mimics the USR1 signal handling of i3status (see man i3status)
signal(SIGUSR1, self.sig_handler)
signal(SIGTERM, self.terminate)
# initialize usage variables
py3_config = self.config["py3_config"]
# prepare the color mappings
self.create_mappings(py3_config)
# self.output_modules needs to have been created before modules are
# started. This is so that modules can do things like register their
# content_function.
self.create_output_modules()
# start up all our modules
for module in self.modules.values():
task = ModuleRunner(module)
self.timeout_queue_add(task)
# this will be our output set to the correct length for the number of
# items in the bar
output = [None] * len(py3_config["order"])
write = sys.__stdout__.write
flush = sys.__stdout__.flush
# start our output
header = {
"version": 1,
"click_events": self.config["click_events"],
"stop_signal": SIGTSTP,
}
write(dumps(header))
write("\n[[]\n")
update_due = None
# main loop
while True:
# process the timeout_queue and get interval till next update due
update_due = self.timeout_queue_process()
# wait until an update is requested
if self.update_request.wait(timeout=update_due):
# event was set so clear it
self.update_request.clear()
while not self.i3bar_running:
time.sleep(0.1)
# check if an update is needed
if self.update_queue:
while len(self.update_queue):
module_name = self.update_queue.popleft()
module = self.output_modules[module_name]
out = self.process_module_output(module)
for index in module["position"]:
# store the output as json
output[index] = out
# build output string
out = ",".join([x for x in output if x])
# dump the line to stdout
write(",[{}]\n".format(out))
flush() | python | def run(self):
# SIGUSR1 forces a refresh of the bar both for py3status and i3status,
# this mimics the USR1 signal handling of i3status (see man i3status)
signal(SIGUSR1, self.sig_handler)
signal(SIGTERM, self.terminate)
# initialize usage variables
py3_config = self.config["py3_config"]
# prepare the color mappings
self.create_mappings(py3_config)
# self.output_modules needs to have been created before modules are
# started. This is so that modules can do things like register their
# content_function.
self.create_output_modules()
# start up all our modules
for module in self.modules.values():
task = ModuleRunner(module)
self.timeout_queue_add(task)
# this will be our output set to the correct length for the number of
# items in the bar
output = [None] * len(py3_config["order"])
write = sys.__stdout__.write
flush = sys.__stdout__.flush
# start our output
header = {
"version": 1,
"click_events": self.config["click_events"],
"stop_signal": SIGTSTP,
}
write(dumps(header))
write("\n[[]\n")
update_due = None
# main loop
while True:
# process the timeout_queue and get interval till next update due
update_due = self.timeout_queue_process()
# wait until an update is requested
if self.update_request.wait(timeout=update_due):
# event was set so clear it
self.update_request.clear()
while not self.i3bar_running:
time.sleep(0.1)
# check if an update is needed
if self.update_queue:
while len(self.update_queue):
module_name = self.update_queue.popleft()
module = self.output_modules[module_name]
out = self.process_module_output(module)
for index in module["position"]:
# store the output as json
output[index] = out
# build output string
out = ",".join([x for x in output if x])
# dump the line to stdout
write(",[{}]\n".format(out))
flush() | [
"def",
"run",
"(",
"self",
")",
":",
"# SIGUSR1 forces a refresh of the bar both for py3status and i3status,",
"# this mimics the USR1 signal handling of i3status (see man i3status)",
"signal",
"(",
"SIGUSR1",
",",
"self",
".",
"sig_handler",
")",
"signal",
"(",
"SIGTERM",
",",... | Main py3status loop, continuously read from i3status and modules
and output it to i3bar for displaying. | [
"Main",
"py3status",
"loop",
"continuously",
"read",
"from",
"i3status",
"and",
"modules",
"and",
"output",
"it",
"to",
"i3bar",
"for",
"displaying",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L934-L1005 |
231,228 | ultrabug/py3status | py3status/util.py | Gradients.hex_2_rgb | def hex_2_rgb(self, color):
"""
convert a hex color to rgb
"""
if not self.RE_HEX.match(color):
color = "#FFF"
if len(color) == 7:
return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5])
return (int(c, 16) / 15 for c in color) | python | def hex_2_rgb(self, color):
if not self.RE_HEX.match(color):
color = "#FFF"
if len(color) == 7:
return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5])
return (int(c, 16) / 15 for c in color) | [
"def",
"hex_2_rgb",
"(",
"self",
",",
"color",
")",
":",
"if",
"not",
"self",
".",
"RE_HEX",
".",
"match",
"(",
"color",
")",
":",
"color",
"=",
"\"#FFF\"",
"if",
"len",
"(",
"color",
")",
"==",
"7",
":",
"return",
"(",
"int",
"(",
"color",
"[",
... | convert a hex color to rgb | [
"convert",
"a",
"hex",
"color",
"to",
"rgb"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L18-L26 |
231,229 | ultrabug/py3status | py3status/util.py | Gradients.rgb_2_hex | def rgb_2_hex(self, r, g, b):
"""
convert a rgb color to hex
"""
return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255)) | python | def rgb_2_hex(self, r, g, b):
return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255)) | [
"def",
"rgb_2_hex",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"return",
"\"#{:02X}{:02X}{:02X}\"",
".",
"format",
"(",
"int",
"(",
"r",
"*",
"255",
")",
",",
"int",
"(",
"g",
"*",
"255",
")",
",",
"int",
"(",
"b",
"*",
"255",
")",
... | convert a rgb color to hex | [
"convert",
"a",
"rgb",
"color",
"to",
"hex"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L28-L32 |
231,230 | ultrabug/py3status | py3status/util.py | Gradients.hsv_2_hex | def hsv_2_hex(self, h, s, v):
"""
convert a hsv color to hex
"""
return self.rgb_2_hex(*hsv_to_rgb(h, s, v)) | python | def hsv_2_hex(self, h, s, v):
return self.rgb_2_hex(*hsv_to_rgb(h, s, v)) | [
"def",
"hsv_2_hex",
"(",
"self",
",",
"h",
",",
"s",
",",
"v",
")",
":",
"return",
"self",
".",
"rgb_2_hex",
"(",
"*",
"hsv_to_rgb",
"(",
"h",
",",
"s",
",",
"v",
")",
")"
] | convert a hsv color to hex | [
"convert",
"a",
"hsv",
"color",
"to",
"hex"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L40-L44 |
231,231 | ultrabug/py3status | py3status/util.py | Gradients.make_threshold_gradient | def make_threshold_gradient(self, py3, thresholds, size=100):
"""
Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in the
gradient cannot be guaranteed.
"""
thresholds = sorted(thresholds)
key = "{}|{}".format(thresholds, size)
try:
return self._gradients_cache[key]
except KeyError:
pass
minimum = min(thresholds)[0]
maximum = max(thresholds)[0]
if maximum - minimum > size:
steps_size = size / (maximum - minimum)
else:
steps_size = 1
colors = []
for index in range(len(thresholds) - 1):
color_list = [thresholds[index][1], thresholds[index + 1][1]]
num_colors = int(
(thresholds[index + 1][0] - thresholds[index][0]) * steps_size
)
colors.extend(self.generate_gradient(color_list, num_colors))
# cache gradient
self._gradients_cache[key] = colors
return colors | python | def make_threshold_gradient(self, py3, thresholds, size=100):
thresholds = sorted(thresholds)
key = "{}|{}".format(thresholds, size)
try:
return self._gradients_cache[key]
except KeyError:
pass
minimum = min(thresholds)[0]
maximum = max(thresholds)[0]
if maximum - minimum > size:
steps_size = size / (maximum - minimum)
else:
steps_size = 1
colors = []
for index in range(len(thresholds) - 1):
color_list = [thresholds[index][1], thresholds[index + 1][1]]
num_colors = int(
(thresholds[index + 1][0] - thresholds[index][0]) * steps_size
)
colors.extend(self.generate_gradient(color_list, num_colors))
# cache gradient
self._gradients_cache[key] = colors
return colors | [
"def",
"make_threshold_gradient",
"(",
"self",
",",
"py3",
",",
"thresholds",
",",
"size",
"=",
"100",
")",
":",
"thresholds",
"=",
"sorted",
"(",
"thresholds",
")",
"key",
"=",
"\"{}|{}\"",
".",
"format",
"(",
"thresholds",
",",
"size",
")",
"try",
":",... | Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in the
gradient cannot be guaranteed. | [
"Given",
"a",
"thresholds",
"list",
"creates",
"a",
"gradient",
"list",
"that",
"covers",
"the",
"range",
"of",
"the",
"thresholds",
".",
"The",
"number",
"of",
"colors",
"in",
"the",
"gradient",
"is",
"limited",
"by",
"size",
".",
"Because",
"of",
"how",
... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L109-L139 |
231,232 | ultrabug/py3status | py3status/events.py | Events.get_module_text | def get_module_text(self, module_name, event):
"""
Get the full text for the module as well as the partial text if the
module is a composite. Partial text is the text for just the single
section of a composite.
"""
index = event.get("index")
module_info = self.py3_wrapper.output_modules.get(module_name)
output = module_info["module"].get_latest()
full_text = u"".join([out["full_text"] for out in output])
partial = None
if index is not None:
if isinstance(index, int):
partial = output[index]
else:
for item in output:
if item.get("index") == index:
partial = item
break
if partial:
partial_text = partial["full_text"]
else:
partial_text = full_text
return full_text, partial_text | python | def get_module_text(self, module_name, event):
index = event.get("index")
module_info = self.py3_wrapper.output_modules.get(module_name)
output = module_info["module"].get_latest()
full_text = u"".join([out["full_text"] for out in output])
partial = None
if index is not None:
if isinstance(index, int):
partial = output[index]
else:
for item in output:
if item.get("index") == index:
partial = item
break
if partial:
partial_text = partial["full_text"]
else:
partial_text = full_text
return full_text, partial_text | [
"def",
"get_module_text",
"(",
"self",
",",
"module_name",
",",
"event",
")",
":",
"index",
"=",
"event",
".",
"get",
"(",
"\"index\"",
")",
"module_info",
"=",
"self",
".",
"py3_wrapper",
".",
"output_modules",
".",
"get",
"(",
"module_name",
")",
"output... | Get the full text for the module as well as the partial text if the
module is a composite. Partial text is the text for just the single
section of a composite. | [
"Get",
"the",
"full",
"text",
"for",
"the",
"module",
"as",
"well",
"as",
"the",
"partial",
"text",
"if",
"the",
"module",
"is",
"a",
"composite",
".",
"Partial",
"text",
"is",
"the",
"text",
"for",
"just",
"the",
"single",
"section",
"of",
"a",
"compo... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/events.py#L106-L130 |
231,233 | ultrabug/py3status | py3status/events.py | Events.wm_msg | def wm_msg(self, module_name, command):
"""
Execute the message with i3-msg or swaymsg and log its output.
"""
wm_msg = self.config["wm"]["msg"]
pipe = Popen([wm_msg, command], stdout=PIPE)
self.py3_wrapper.log(
'{} module="{}" command="{}" stdout={}'.format(
wm_msg, module_name, command, pipe.stdout.read()
)
) | python | def wm_msg(self, module_name, command):
wm_msg = self.config["wm"]["msg"]
pipe = Popen([wm_msg, command], stdout=PIPE)
self.py3_wrapper.log(
'{} module="{}" command="{}" stdout={}'.format(
wm_msg, module_name, command, pipe.stdout.read()
)
) | [
"def",
"wm_msg",
"(",
"self",
",",
"module_name",
",",
"command",
")",
":",
"wm_msg",
"=",
"self",
".",
"config",
"[",
"\"wm\"",
"]",
"[",
"\"msg\"",
"]",
"pipe",
"=",
"Popen",
"(",
"[",
"wm_msg",
",",
"command",
"]",
",",
"stdout",
"=",
"PIPE",
")... | Execute the message with i3-msg or swaymsg and log its output. | [
"Execute",
"the",
"message",
"with",
"i3",
"-",
"msg",
"or",
"swaymsg",
"and",
"log",
"its",
"output",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/events.py#L158-L168 |
231,234 | ultrabug/py3status | py3status/events.py | Events.dispatch_event | def dispatch_event(self, event):
"""
Takes an event dict. Logs the event if needed and cleans up the dict
such as setting the index needed for composits.
"""
if self.config["debug"]:
self.py3_wrapper.log("received event {}".format(event))
# usage variables
event["index"] = event.get("index", "")
instance = event.get("instance", "")
name = event.get("name", "")
# composites have an index which is passed to i3bar with
# the instance. We need to separate this out here and
# clean up the event. If index
# is an integer type then cast it as such.
if " " in instance:
instance, index = instance.split(" ", 1)
try:
index = int(index)
except ValueError:
pass
event["index"] = index
event["instance"] = instance
if self.config["debug"]:
self.py3_wrapper.log(
'trying to dispatch event to module "{}"'.format(
"{} {}".format(name, instance).strip()
)
)
# guess the module config name
module_name = "{} {}".format(name, instance).strip()
default_event = False
module_info = self.output_modules.get(module_name)
module = module_info["module"]
# execute any configured i3-msg command
# we do not do this for containers
# modules that have failed do not execute their config on_click
if module.allow_config_clicks:
button = event.get("button", 0)
on_click = self.on_click.get(module_name, {}).get(str(button))
if on_click:
task = EventClickTask(module_name, event, self, on_click)
self.py3_wrapper.timeout_queue_add(task)
# otherwise setup default action on button 2 press
elif button == 2:
default_event = True
# do the work
task = EventTask(module_name, event, default_event, self)
self.py3_wrapper.timeout_queue_add(task) | python | def dispatch_event(self, event):
if self.config["debug"]:
self.py3_wrapper.log("received event {}".format(event))
# usage variables
event["index"] = event.get("index", "")
instance = event.get("instance", "")
name = event.get("name", "")
# composites have an index which is passed to i3bar with
# the instance. We need to separate this out here and
# clean up the event. If index
# is an integer type then cast it as such.
if " " in instance:
instance, index = instance.split(" ", 1)
try:
index = int(index)
except ValueError:
pass
event["index"] = index
event["instance"] = instance
if self.config["debug"]:
self.py3_wrapper.log(
'trying to dispatch event to module "{}"'.format(
"{} {}".format(name, instance).strip()
)
)
# guess the module config name
module_name = "{} {}".format(name, instance).strip()
default_event = False
module_info = self.output_modules.get(module_name)
module = module_info["module"]
# execute any configured i3-msg command
# we do not do this for containers
# modules that have failed do not execute their config on_click
if module.allow_config_clicks:
button = event.get("button", 0)
on_click = self.on_click.get(module_name, {}).get(str(button))
if on_click:
task = EventClickTask(module_name, event, self, on_click)
self.py3_wrapper.timeout_queue_add(task)
# otherwise setup default action on button 2 press
elif button == 2:
default_event = True
# do the work
task = EventTask(module_name, event, default_event, self)
self.py3_wrapper.timeout_queue_add(task) | [
"def",
"dispatch_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"config",
"[",
"\"debug\"",
"]",
":",
"self",
".",
"py3_wrapper",
".",
"log",
"(",
"\"received event {}\"",
".",
"format",
"(",
"event",
")",
")",
"# usage variables",
"event"... | Takes an event dict. Logs the event if needed and cleans up the dict
such as setting the index needed for composits. | [
"Takes",
"an",
"event",
"dict",
".",
"Logs",
"the",
"event",
"if",
"needed",
"and",
"cleans",
"up",
"the",
"dict",
"such",
"as",
"setting",
"the",
"index",
"needed",
"for",
"composits",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/events.py#L205-L259 |
231,235 | ultrabug/py3status | py3status/events.py | Events.run | def run(self):
"""
Wait for an i3bar JSON event, then find the right module to dispatch
the message to based on the 'name' and 'instance' of the event.
In case the module does NOT support click_events, the default
implementation is to clear the module's cache
when the MIDDLE button (2) is pressed on it.
Example event:
{'y': 13, 'x': 1737, 'button': 1, 'name': 'empty', 'instance': 'first'}
"""
try:
while self.py3_wrapper.running:
event_str = self.poller_inp.readline()
if not event_str:
continue
try:
# remove leading comma if present
if event_str[0] == ",":
event_str = event_str[1:]
event = loads(event_str)
self.dispatch_event(event)
except Exception:
self.py3_wrapper.report_exception("Event failed")
except: # noqa e722
err = "Events thread died, click events are disabled."
self.py3_wrapper.report_exception(err, notify_user=False)
self.py3_wrapper.notify_user(err, level="warning") | python | def run(self):
try:
while self.py3_wrapper.running:
event_str = self.poller_inp.readline()
if not event_str:
continue
try:
# remove leading comma if present
if event_str[0] == ",":
event_str = event_str[1:]
event = loads(event_str)
self.dispatch_event(event)
except Exception:
self.py3_wrapper.report_exception("Event failed")
except: # noqa e722
err = "Events thread died, click events are disabled."
self.py3_wrapper.report_exception(err, notify_user=False)
self.py3_wrapper.notify_user(err, level="warning") | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"while",
"self",
".",
"py3_wrapper",
".",
"running",
":",
"event_str",
"=",
"self",
".",
"poller_inp",
".",
"readline",
"(",
")",
"if",
"not",
"event_str",
":",
"continue",
"try",
":",
"# remove leading co... | Wait for an i3bar JSON event, then find the right module to dispatch
the message to based on the 'name' and 'instance' of the event.
In case the module does NOT support click_events, the default
implementation is to clear the module's cache
when the MIDDLE button (2) is pressed on it.
Example event:
{'y': 13, 'x': 1737, 'button': 1, 'name': 'empty', 'instance': 'first'} | [
"Wait",
"for",
"an",
"i3bar",
"JSON",
"event",
"then",
"find",
"the",
"right",
"module",
"to",
"dispatch",
"the",
"message",
"to",
"based",
"on",
"the",
"name",
"and",
"instance",
"of",
"the",
"event",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/events.py#L262-L290 |
231,236 | ultrabug/py3status | py3status/modules/vpn_status.py | Py3status._start_handler_thread | def _start_handler_thread(self):
"""Called once to start the event handler thread."""
# Create handler thread
t = Thread(target=self._start_loop)
t.daemon = True
# Start handler thread
t.start()
self.thread_started = True | python | def _start_handler_thread(self):
# Create handler thread
t = Thread(target=self._start_loop)
t.daemon = True
# Start handler thread
t.start()
self.thread_started = True | [
"def",
"_start_handler_thread",
"(",
"self",
")",
":",
"# Create handler thread",
"t",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_start_loop",
")",
"t",
".",
"daemon",
"=",
"True",
"# Start handler thread",
"t",
".",
"start",
"(",
")",
"self",
".",
... | Called once to start the event handler thread. | [
"Called",
"once",
"to",
"start",
"the",
"event",
"handler",
"thread",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/vpn_status.py#L58-L66 |
231,237 | ultrabug/py3status | py3status/modules/vpn_status.py | Py3status._start_loop | def _start_loop(self):
"""Starts main event handler loop, run in handler thread t."""
# Create our main loop, get our bus, and add the signal handler
loop = GObject.MainLoop()
bus = SystemBus()
manager = bus.get(".NetworkManager")
manager.onPropertiesChanged = self._vpn_signal_handler
# Loop forever
loop.run() | python | def _start_loop(self):
# Create our main loop, get our bus, and add the signal handler
loop = GObject.MainLoop()
bus = SystemBus()
manager = bus.get(".NetworkManager")
manager.onPropertiesChanged = self._vpn_signal_handler
# Loop forever
loop.run() | [
"def",
"_start_loop",
"(",
"self",
")",
":",
"# Create our main loop, get our bus, and add the signal handler",
"loop",
"=",
"GObject",
".",
"MainLoop",
"(",
")",
"bus",
"=",
"SystemBus",
"(",
")",
"manager",
"=",
"bus",
".",
"get",
"(",
"\".NetworkManager\"",
")"... | Starts main event handler loop, run in handler thread t. | [
"Starts",
"main",
"event",
"handler",
"loop",
"run",
"in",
"handler",
"thread",
"t",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/vpn_status.py#L68-L77 |
231,238 | ultrabug/py3status | py3status/modules/vpn_status.py | Py3status._vpn_signal_handler | def _vpn_signal_handler(self, args):
"""Called on NetworkManager PropertiesChanged signal"""
# Args is a dictionary of changed properties
# We only care about changes in ActiveConnections
active = "ActiveConnections"
# Compare current ActiveConnections to last seen ActiveConnections
if active in args.keys() and sorted(self.active) != sorted(args[active]):
self.active = args[active]
self.py3.update() | python | def _vpn_signal_handler(self, args):
# Args is a dictionary of changed properties
# We only care about changes in ActiveConnections
active = "ActiveConnections"
# Compare current ActiveConnections to last seen ActiveConnections
if active in args.keys() and sorted(self.active) != sorted(args[active]):
self.active = args[active]
self.py3.update() | [
"def",
"_vpn_signal_handler",
"(",
"self",
",",
"args",
")",
":",
"# Args is a dictionary of changed properties",
"# We only care about changes in ActiveConnections",
"active",
"=",
"\"ActiveConnections\"",
"# Compare current ActiveConnections to last seen ActiveConnections",
"if",
"ac... | Called on NetworkManager PropertiesChanged signal | [
"Called",
"on",
"NetworkManager",
"PropertiesChanged",
"signal"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/vpn_status.py#L79-L87 |
231,239 | ultrabug/py3status | py3status/modules/vpn_status.py | Py3status._get_vpn_status | def _get_vpn_status(self):
"""Returns None if no VPN active, Id if active."""
# Sleep for a bit to let any changes in state finish
sleep(0.3)
# Check if any active connections are a VPN
bus = SystemBus()
ids = []
for name in self.active:
conn = bus.get(".NetworkManager", name)
if conn.Vpn:
ids.append(conn.Id)
# No active VPN
return ids | python | def _get_vpn_status(self):
# Sleep for a bit to let any changes in state finish
sleep(0.3)
# Check if any active connections are a VPN
bus = SystemBus()
ids = []
for name in self.active:
conn = bus.get(".NetworkManager", name)
if conn.Vpn:
ids.append(conn.Id)
# No active VPN
return ids | [
"def",
"_get_vpn_status",
"(",
"self",
")",
":",
"# Sleep for a bit to let any changes in state finish",
"sleep",
"(",
"0.3",
")",
"# Check if any active connections are a VPN",
"bus",
"=",
"SystemBus",
"(",
")",
"ids",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".... | Returns None if no VPN active, Id if active. | [
"Returns",
"None",
"if",
"no",
"VPN",
"active",
"Id",
"if",
"active",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/vpn_status.py#L89-L101 |
231,240 | ultrabug/py3status | py3status/modules/vpn_status.py | Py3status.vpn_status | def vpn_status(self):
"""Returns response dict"""
# Start signal handler thread if it should be running
if not self.check_pid and not self.thread_started:
self._start_handler_thread()
# Set color_bad as default output. Replaced if VPN active.
name = None
color = self.py3.COLOR_BAD
# If we are acting like the default i3status module
if self.check_pid:
if self._check_pid():
name = "yes"
color = self.py3.COLOR_GOOD
# Otherwise, find the VPN name, if it is active
else:
vpn = self._get_vpn_status()
if vpn:
name = ", ".join(vpn)
color = self.py3.COLOR_GOOD
# Format and create the response dict
full_text = self.py3.safe_format(self.format, {"name": name})
response = {
"full_text": full_text,
"color": color,
"cached_until": self.py3.CACHE_FOREVER,
}
# Cache forever unless in check_pid mode
if self.check_pid:
response["cached_until"] = self.py3.time_in(self.cache_timeout)
return response | python | def vpn_status(self):
# Start signal handler thread if it should be running
if not self.check_pid and not self.thread_started:
self._start_handler_thread()
# Set color_bad as default output. Replaced if VPN active.
name = None
color = self.py3.COLOR_BAD
# If we are acting like the default i3status module
if self.check_pid:
if self._check_pid():
name = "yes"
color = self.py3.COLOR_GOOD
# Otherwise, find the VPN name, if it is active
else:
vpn = self._get_vpn_status()
if vpn:
name = ", ".join(vpn)
color = self.py3.COLOR_GOOD
# Format and create the response dict
full_text = self.py3.safe_format(self.format, {"name": name})
response = {
"full_text": full_text,
"color": color,
"cached_until": self.py3.CACHE_FOREVER,
}
# Cache forever unless in check_pid mode
if self.check_pid:
response["cached_until"] = self.py3.time_in(self.cache_timeout)
return response | [
"def",
"vpn_status",
"(",
"self",
")",
":",
"# Start signal handler thread if it should be running",
"if",
"not",
"self",
".",
"check_pid",
"and",
"not",
"self",
".",
"thread_started",
":",
"self",
".",
"_start_handler_thread",
"(",
")",
"# Set color_bad as default outp... | Returns response dict | [
"Returns",
"response",
"dict"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/vpn_status.py#L108-L143 |
231,241 | ultrabug/py3status | py3status/composite.py | Composite.append | def append(self, item):
"""
Add an item to the Composite. Item can be a Composite, list etc
"""
if isinstance(item, Composite):
self._content += item.get_content()
elif isinstance(item, list):
self._content += item
elif isinstance(item, dict):
self._content.append(item)
elif isinstance(item, basestring):
self._content.append({"full_text": item})
else:
msg = "{!r} not suitable to append to Composite"
raise Exception(msg.format(item)) | python | def append(self, item):
if isinstance(item, Composite):
self._content += item.get_content()
elif isinstance(item, list):
self._content += item
elif isinstance(item, dict):
self._content.append(item)
elif isinstance(item, basestring):
self._content.append({"full_text": item})
else:
msg = "{!r} not suitable to append to Composite"
raise Exception(msg.format(item)) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"Composite",
")",
":",
"self",
".",
"_content",
"+=",
"item",
".",
"get_content",
"(",
")",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"self",
... | Add an item to the Composite. Item can be a Composite, list etc | [
"Add",
"an",
"item",
"to",
"the",
"Composite",
".",
"Item",
"can",
"be",
"a",
"Composite",
"list",
"etc"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/composite.py#L58-L72 |
231,242 | ultrabug/py3status | py3status/composite.py | Composite.simplify | def simplify(self):
"""
Simplify the content of a Composite merging any parts that can be
and returning the new Composite as well as updating itself internally
"""
final_output = []
diff_last = None
item_last = None
for item in self._content:
# remove any undefined colors
if hasattr(item.get("color"), "none_setting"):
del item["color"]
# ignore empty items
if not item.get("full_text") and not item.get("separator"):
continue
# merge items if we can
diff = item.copy()
del diff["full_text"]
if diff == diff_last or (item["full_text"].strip() == "" and item_last):
item_last["full_text"] += item["full_text"]
else:
diff_last = diff
item_last = item.copy() # copy item as we may change it
final_output.append(item_last)
self._content = final_output
return self | python | def simplify(self):
final_output = []
diff_last = None
item_last = None
for item in self._content:
# remove any undefined colors
if hasattr(item.get("color"), "none_setting"):
del item["color"]
# ignore empty items
if not item.get("full_text") and not item.get("separator"):
continue
# merge items if we can
diff = item.copy()
del diff["full_text"]
if diff == diff_last or (item["full_text"].strip() == "" and item_last):
item_last["full_text"] += item["full_text"]
else:
diff_last = diff
item_last = item.copy() # copy item as we may change it
final_output.append(item_last)
self._content = final_output
return self | [
"def",
"simplify",
"(",
"self",
")",
":",
"final_output",
"=",
"[",
"]",
"diff_last",
"=",
"None",
"item_last",
"=",
"None",
"for",
"item",
"in",
"self",
".",
"_content",
":",
"# remove any undefined colors",
"if",
"hasattr",
"(",
"item",
".",
"get",
"(",
... | Simplify the content of a Composite merging any parts that can be
and returning the new Composite as well as updating itself internally | [
"Simplify",
"the",
"content",
"of",
"a",
"Composite",
"merging",
"any",
"parts",
"that",
"can",
"be",
"and",
"returning",
"the",
"new",
"Composite",
"as",
"well",
"as",
"updating",
"itself",
"internally"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/composite.py#L86-L112 |
231,243 | ultrabug/py3status | py3status/composite.py | Composite.composite_join | def composite_join(separator, items):
"""
Join a list of items with a separator.
This is used in joining strings, responses and Composites.
The output will be a Composite.
"""
output = Composite()
first_item = True
for item in items:
# skip empty items
if not item:
continue
# skip separator on first item
if first_item:
first_item = False
else:
output.append(separator)
output.append(item)
return output | python | def composite_join(separator, items):
output = Composite()
first_item = True
for item in items:
# skip empty items
if not item:
continue
# skip separator on first item
if first_item:
first_item = False
else:
output.append(separator)
output.append(item)
return output | [
"def",
"composite_join",
"(",
"separator",
",",
"items",
")",
":",
"output",
"=",
"Composite",
"(",
")",
"first_item",
"=",
"True",
"for",
"item",
"in",
"items",
":",
"# skip empty items",
"if",
"not",
"item",
":",
"continue",
"# skip separator on first item",
... | Join a list of items with a separator.
This is used in joining strings, responses and Composites.
The output will be a Composite. | [
"Join",
"a",
"list",
"of",
"items",
"with",
"a",
"separator",
".",
"This",
"is",
"used",
"in",
"joining",
"strings",
"responses",
"and",
"Composites",
".",
"The",
"output",
"will",
"be",
"a",
"Composite",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/composite.py#L115-L133 |
231,244 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._init_dbus | def _init_dbus(self):
"""
Get the device id
"""
_bus = SessionBus()
if self.device_id is None:
self.device_id = self._get_device_id(_bus)
if self.device_id is None:
return False
try:
self._dev = _bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % self.device_id)
except Exception:
return False
return True | python | def _init_dbus(self):
_bus = SessionBus()
if self.device_id is None:
self.device_id = self._get_device_id(_bus)
if self.device_id is None:
return False
try:
self._dev = _bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % self.device_id)
except Exception:
return False
return True | [
"def",
"_init_dbus",
"(",
"self",
")",
":",
"_bus",
"=",
"SessionBus",
"(",
")",
"if",
"self",
".",
"device_id",
"is",
"None",
":",
"self",
".",
"device_id",
"=",
"self",
".",
"_get_device_id",
"(",
"_bus",
")",
"if",
"self",
".",
"device_id",
"is",
... | Get the device id | [
"Get",
"the",
"device",
"id"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L105-L121 |
231,245 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_device_id | def _get_device_id(self, bus):
"""
Find the device id
"""
_dbus = bus.get(SERVICE_BUS, PATH)
devices = _dbus.devices()
if self.device is None and self.device_id is None and len(devices) == 1:
return devices[0]
for id in devices:
self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % id)
if self.device == self._dev.name:
return id
return None | python | def _get_device_id(self, bus):
_dbus = bus.get(SERVICE_BUS, PATH)
devices = _dbus.devices()
if self.device is None and self.device_id is None and len(devices) == 1:
return devices[0]
for id in devices:
self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % id)
if self.device == self._dev.name:
return id
return None | [
"def",
"_get_device_id",
"(",
"self",
",",
"bus",
")",
":",
"_dbus",
"=",
"bus",
".",
"get",
"(",
"SERVICE_BUS",
",",
"PATH",
")",
"devices",
"=",
"_dbus",
".",
"devices",
"(",
")",
"if",
"self",
".",
"device",
"is",
"None",
"and",
"self",
".",
"de... | Find the device id | [
"Find",
"the",
"device",
"id"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L123-L138 |
231,246 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_device | def _get_device(self):
"""
Get the device
"""
try:
device = {
"name": self._dev.name,
"isReachable": self._dev.isReachable,
"isTrusted": self._get_isTrusted(),
}
except Exception:
return None
return device | python | def _get_device(self):
try:
device = {
"name": self._dev.name,
"isReachable": self._dev.isReachable,
"isTrusted": self._get_isTrusted(),
}
except Exception:
return None
return device | [
"def",
"_get_device",
"(",
"self",
")",
":",
"try",
":",
"device",
"=",
"{",
"\"name\"",
":",
"self",
".",
"_dev",
".",
"name",
",",
"\"isReachable\"",
":",
"self",
".",
"_dev",
".",
"isReachable",
",",
"\"isTrusted\"",
":",
"self",
".",
"_get_isTrusted"... | Get the device | [
"Get",
"the",
"device"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L154-L167 |
231,247 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_battery | def _get_battery(self):
"""
Get the battery
"""
try:
battery = {
"charge": self._dev.charge(),
"isCharging": self._dev.isCharging() == 1,
}
except Exception:
return None
return battery | python | def _get_battery(self):
try:
battery = {
"charge": self._dev.charge(),
"isCharging": self._dev.isCharging() == 1,
}
except Exception:
return None
return battery | [
"def",
"_get_battery",
"(",
"self",
")",
":",
"try",
":",
"battery",
"=",
"{",
"\"charge\"",
":",
"self",
".",
"_dev",
".",
"charge",
"(",
")",
",",
"\"isCharging\"",
":",
"self",
".",
"_dev",
".",
"isCharging",
"(",
")",
"==",
"1",
",",
"}",
"exce... | Get the battery | [
"Get",
"the",
"battery"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L169-L181 |
231,248 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_battery_status | def _get_battery_status(self, battery):
"""
Get the battery status
"""
if battery["charge"] == -1:
return (UNKNOWN_SYMBOL, UNKNOWN, "#FFFFFF")
if battery["isCharging"]:
status = self.status_chr
color = self.py3.COLOR_GOOD
else:
status = self.status_bat
color = self.py3.COLOR_DEGRADED
if not battery["isCharging"] and battery["charge"] <= self.low_threshold:
color = self.py3.COLOR_BAD
if battery["charge"] > 99:
status = self.status_full
return (battery["charge"], status, color) | python | def _get_battery_status(self, battery):
if battery["charge"] == -1:
return (UNKNOWN_SYMBOL, UNKNOWN, "#FFFFFF")
if battery["isCharging"]:
status = self.status_chr
color = self.py3.COLOR_GOOD
else:
status = self.status_bat
color = self.py3.COLOR_DEGRADED
if not battery["isCharging"] and battery["charge"] <= self.low_threshold:
color = self.py3.COLOR_BAD
if battery["charge"] > 99:
status = self.status_full
return (battery["charge"], status, color) | [
"def",
"_get_battery_status",
"(",
"self",
",",
"battery",
")",
":",
"if",
"battery",
"[",
"\"charge\"",
"]",
"==",
"-",
"1",
":",
"return",
"(",
"UNKNOWN_SYMBOL",
",",
"UNKNOWN",
",",
"\"#FFFFFF\"",
")",
"if",
"battery",
"[",
"\"isCharging\"",
"]",
":",
... | Get the battery status | [
"Get",
"the",
"battery",
"status"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L194-L214 |
231,249 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_notifications_status | def _get_notifications_status(self, notifications):
"""
Get the notifications status
"""
if notifications:
size = len(notifications["activeNotifications"])
else:
size = 0
status = self.status_notif if size > 0 else self.status_no_notif
return (size, status) | python | def _get_notifications_status(self, notifications):
if notifications:
size = len(notifications["activeNotifications"])
else:
size = 0
status = self.status_notif if size > 0 else self.status_no_notif
return (size, status) | [
"def",
"_get_notifications_status",
"(",
"self",
",",
"notifications",
")",
":",
"if",
"notifications",
":",
"size",
"=",
"len",
"(",
"notifications",
"[",
"\"activeNotifications\"",
"]",
")",
"else",
":",
"size",
"=",
"0",
"status",
"=",
"self",
".",
"statu... | Get the notifications status | [
"Get",
"the",
"notifications",
"status"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L216-L226 |
231,250 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status._get_text | def _get_text(self):
"""
Get the current metadatas
"""
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD)
if not device["isReachable"] or not device["isTrusted"]:
return (
self.py3.safe_format(
self.format_disconnected, {"name": device["name"]}
),
self.py3.COLOR_BAD,
)
battery = self._get_battery()
(charge, bat_status, color) = self._get_battery_status(battery)
notif = self._get_notifications()
(notif_size, notif_status) = self._get_notifications_status(notif)
return (
self.py3.safe_format(
self.format,
dict(
name=device["name"],
charge=charge,
bat_status=bat_status,
notif_size=notif_size,
notif_status=notif_status,
),
),
color,
) | python | def _get_text(self):
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD)
if not device["isReachable"] or not device["isTrusted"]:
return (
self.py3.safe_format(
self.format_disconnected, {"name": device["name"]}
),
self.py3.COLOR_BAD,
)
battery = self._get_battery()
(charge, bat_status, color) = self._get_battery_status(battery)
notif = self._get_notifications()
(notif_size, notif_status) = self._get_notifications_status(notif)
return (
self.py3.safe_format(
self.format,
dict(
name=device["name"],
charge=charge,
bat_status=bat_status,
notif_size=notif_size,
notif_status=notif_status,
),
),
color,
) | [
"def",
"_get_text",
"(",
"self",
")",
":",
"device",
"=",
"self",
".",
"_get_device",
"(",
")",
"if",
"device",
"is",
"None",
":",
"return",
"(",
"UNKNOWN_DEVICE",
",",
"self",
".",
"py3",
".",
"COLOR_BAD",
")",
"if",
"not",
"device",
"[",
"\"isReachab... | Get the current metadatas | [
"Get",
"the",
"current",
"metadatas"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L228-L262 |
231,251 | ultrabug/py3status | py3status/modules/kdeconnector.py | Py3status.kdeconnector | def kdeconnector(self):
"""
Get the current state and return it.
"""
if self._init_dbus():
(text, color) = self._get_text()
else:
text = UNKNOWN_DEVICE
color = self.py3.COLOR_BAD
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": text,
"color": color,
}
return response | python | def kdeconnector(self):
if self._init_dbus():
(text, color) = self._get_text()
else:
text = UNKNOWN_DEVICE
color = self.py3.COLOR_BAD
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": text,
"color": color,
}
return response | [
"def",
"kdeconnector",
"(",
"self",
")",
":",
"if",
"self",
".",
"_init_dbus",
"(",
")",
":",
"(",
"text",
",",
"color",
")",
"=",
"self",
".",
"_get_text",
"(",
")",
"else",
":",
"text",
"=",
"UNKNOWN_DEVICE",
"color",
"=",
"self",
".",
"py3",
"."... | Get the current state and return it. | [
"Get",
"the",
"current",
"state",
"and",
"return",
"it",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/kdeconnector.py#L264-L279 |
231,252 | ultrabug/py3status | py3status/modules/dpms.py | Py3status.dpms | def dpms(self):
"""
Display a colorful state of DPMS.
"""
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
_format = self.icon_on
color = self.color_on
else:
_format = self.icon_off
color = self.color_off
icon = self.py3.safe_format(_format)
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(self.format, {"icon": icon}),
"color": color,
} | python | def dpms(self):
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
_format = self.icon_on
color = self.color_on
else:
_format = self.icon_off
color = self.color_off
icon = self.py3.safe_format(_format)
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(self.format, {"icon": icon}),
"color": color,
} | [
"def",
"dpms",
"(",
"self",
")",
":",
"if",
"\"DPMS is Enabled\"",
"in",
"self",
".",
"py3",
".",
"command_output",
"(",
"\"xset -q\"",
")",
":",
"_format",
"=",
"self",
".",
"icon_on",
"color",
"=",
"self",
".",
"color_on",
"else",
":",
"_format",
"=",
... | Display a colorful state of DPMS. | [
"Display",
"a",
"colorful",
"state",
"of",
"DPMS",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/dpms.py#L62-L79 |
231,253 | ultrabug/py3status | py3status/modules/dpms.py | Py3status.on_click | def on_click(self, event):
"""
Control DPMS with mouse clicks.
"""
if event["button"] == self.button_toggle:
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
self.py3.command_run("xset -dpms s off")
else:
self.py3.command_run("xset +dpms s on")
if event["button"] == self.button_off:
self.py3.command_run("xset dpms force off") | python | def on_click(self, event):
if event["button"] == self.button_toggle:
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
self.py3.command_run("xset -dpms s off")
else:
self.py3.command_run("xset +dpms s on")
if event["button"] == self.button_off:
self.py3.command_run("xset dpms force off") | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
"[",
"\"button\"",
"]",
"==",
"self",
".",
"button_toggle",
":",
"if",
"\"DPMS is Enabled\"",
"in",
"self",
".",
"py3",
".",
"command_output",
"(",
"\"xset -q\"",
")",
":",
"self",
".... | Control DPMS with mouse clicks. | [
"Control",
"DPMS",
"with",
"mouse",
"clicks",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/dpms.py#L81-L92 |
231,254 | ultrabug/py3status | py3status/modules/emerge_status.py | Py3status._get_progress | def _get_progress(self):
"""
Get current progress of emerge.
Returns a dict containing current and total value.
"""
input_data = []
ret = {}
# traverse emerge.log from bottom up to get latest information
last_lines = self.py3.command_output(["tail", "-50", self.emerge_log_file])
input_data = last_lines.split("\n")
input_data.reverse()
for line in input_data:
if "*** terminating." in line:
# copy content of ret_default, not only the references
ret = copy.deepcopy(self.ret_default)
break
else:
status_re = re.compile(
"\((?P<cu>[\d]+) of (?P<t>[\d]+)\) "
"(?P<a>[a-zA-Z\/]+( [a-zA-Z]+)?) "
"\((?P<ca>[\w\-]+)\/(?P<p>[\w\.]+)"
)
res = status_re.search(line)
if res is not None:
ret["action"] = res.group("a").lower()
ret["category"] = res.group("ca")
ret["current"] = res.group("cu")
ret["pkg"] = res.group("p")
ret["total"] = res.group("t")
break
return ret | python | def _get_progress(self):
input_data = []
ret = {}
# traverse emerge.log from bottom up to get latest information
last_lines = self.py3.command_output(["tail", "-50", self.emerge_log_file])
input_data = last_lines.split("\n")
input_data.reverse()
for line in input_data:
if "*** terminating." in line:
# copy content of ret_default, not only the references
ret = copy.deepcopy(self.ret_default)
break
else:
status_re = re.compile(
"\((?P<cu>[\d]+) of (?P<t>[\d]+)\) "
"(?P<a>[a-zA-Z\/]+( [a-zA-Z]+)?) "
"\((?P<ca>[\w\-]+)\/(?P<p>[\w\.]+)"
)
res = status_re.search(line)
if res is not None:
ret["action"] = res.group("a").lower()
ret["category"] = res.group("ca")
ret["current"] = res.group("cu")
ret["pkg"] = res.group("p")
ret["total"] = res.group("t")
break
return ret | [
"def",
"_get_progress",
"(",
"self",
")",
":",
"input_data",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"# traverse emerge.log from bottom up to get latest information",
"last_lines",
"=",
"self",
".",
"py3",
".",
"command_output",
"(",
"[",
"\"tail\"",
",",
"\"-50\"",
... | Get current progress of emerge.
Returns a dict containing current and total value. | [
"Get",
"current",
"progress",
"of",
"emerge",
".",
"Returns",
"a",
"dict",
"containing",
"current",
"and",
"total",
"value",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/emerge_status.py#L93-L125 |
231,255 | ultrabug/py3status | py3status/modules/imap.py | Py3status._idle | def _idle(self):
"""
since imaplib doesn't support IMAP4r1 IDLE, we'll do it by hand
"""
socket = None
try:
# build a new command tag (Xnnn) as bytes:
self.command_tag = (self.command_tag + 1) % 1000
command_tag = b"X" + bytes(str(self.command_tag).zfill(3), "ascii")
# make sure we have selected anything before idling:
directories = self.mailbox.split(",")
self.connection.select(directories[0])
socket = self.connection.socket()
# send IDLE command and check response:
socket.write(command_tag + b" IDLE\r\n")
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'IDLE' in time")
if not response.lower().startswith("+ idling"):
raise imaplib.IMAP4.abort("While initializing IDLE: " + str(response))
# wait for changes (EXISTS, EXPUNGE, etc.):
socket.settimeout(self.cache_timeout)
while True:
try:
response = socket.read(4096).decode("ascii")
if response.upper().startswith("* OK"):
continue # ignore '* OK Still here'
else:
break
except socket_error: # IDLE timed out
break
finally: # terminate IDLE command gracefully
if socket is None:
return
socket.settimeout(self.read_timeout)
socket.write(b"DONE\r\n") # important! Can't query IMAP again otherwise
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'DONE' in time")
# sometimes, more messages come in between reading and DONEing; so read them again:
if response.startswith("* "):
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort(
"Server sent more continuations, but no 'DONE' ack"
)
expected_response = (command_tag + b" OK").decode("ascii")
if not response.lower().startswith(expected_response.lower()):
raise imaplib.IMAP4.abort("While terminating IDLE: " + response) | python | def _idle(self):
socket = None
try:
# build a new command tag (Xnnn) as bytes:
self.command_tag = (self.command_tag + 1) % 1000
command_tag = b"X" + bytes(str(self.command_tag).zfill(3), "ascii")
# make sure we have selected anything before idling:
directories = self.mailbox.split(",")
self.connection.select(directories[0])
socket = self.connection.socket()
# send IDLE command and check response:
socket.write(command_tag + b" IDLE\r\n")
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'IDLE' in time")
if not response.lower().startswith("+ idling"):
raise imaplib.IMAP4.abort("While initializing IDLE: " + str(response))
# wait for changes (EXISTS, EXPUNGE, etc.):
socket.settimeout(self.cache_timeout)
while True:
try:
response = socket.read(4096).decode("ascii")
if response.upper().startswith("* OK"):
continue # ignore '* OK Still here'
else:
break
except socket_error: # IDLE timed out
break
finally: # terminate IDLE command gracefully
if socket is None:
return
socket.settimeout(self.read_timeout)
socket.write(b"DONE\r\n") # important! Can't query IMAP again otherwise
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'DONE' in time")
# sometimes, more messages come in between reading and DONEing; so read them again:
if response.startswith("* "):
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort(
"Server sent more continuations, but no 'DONE' ack"
)
expected_response = (command_tag + b" OK").decode("ascii")
if not response.lower().startswith(expected_response.lower()):
raise imaplib.IMAP4.abort("While terminating IDLE: " + response) | [
"def",
"_idle",
"(",
"self",
")",
":",
"socket",
"=",
"None",
"try",
":",
"# build a new command tag (Xnnn) as bytes:",
"self",
".",
"command_tag",
"=",
"(",
"self",
".",
"command_tag",
"+",
"1",
")",
"%",
"1000",
"command_tag",
"=",
"b\"X\"",
"+",
"bytes",
... | since imaplib doesn't support IMAP4r1 IDLE, we'll do it by hand | [
"since",
"imaplib",
"doesn",
"t",
"support",
"IMAP4r1",
"IDLE",
"we",
"ll",
"do",
"it",
"by",
"hand"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/imap.py#L171-L231 |
231,256 | ultrabug/py3status | py3status/modules/sysdata.py | Py3status._get_cputemp_with_lmsensors | def _get_cputemp_with_lmsensors(self, zone=None):
"""
Tries to determine CPU temperature using the 'sensors' command.
Searches for the CPU temperature by looking for a value prefixed
by either "CPU Temp" or "Core 0" - does not look for or average
out temperatures of all codes if more than one.
"""
sensors = None
command = ["sensors"]
if zone:
try:
sensors = self.py3.command_output(command + [zone])
except self.py3.CommandError:
pass
if not sensors:
sensors = self.py3.command_output(command)
m = re.search("(Core 0|CPU Temp).+\+(.+).+\(.+", sensors)
if m:
cpu_temp = float(m.groups()[1].strip()[:-2])
else:
cpu_temp = "?"
return cpu_temp | python | def _get_cputemp_with_lmsensors(self, zone=None):
sensors = None
command = ["sensors"]
if zone:
try:
sensors = self.py3.command_output(command + [zone])
except self.py3.CommandError:
pass
if not sensors:
sensors = self.py3.command_output(command)
m = re.search("(Core 0|CPU Temp).+\+(.+).+\(.+", sensors)
if m:
cpu_temp = float(m.groups()[1].strip()[:-2])
else:
cpu_temp = "?"
return cpu_temp | [
"def",
"_get_cputemp_with_lmsensors",
"(",
"self",
",",
"zone",
"=",
"None",
")",
":",
"sensors",
"=",
"None",
"command",
"=",
"[",
"\"sensors\"",
"]",
"if",
"zone",
":",
"try",
":",
"sensors",
"=",
"self",
".",
"py3",
".",
"command_output",
"(",
"comman... | Tries to determine CPU temperature using the 'sensors' command.
Searches for the CPU temperature by looking for a value prefixed
by either "CPU Temp" or "Core 0" - does not look for or average
out temperatures of all codes if more than one. | [
"Tries",
"to",
"determine",
"CPU",
"temperature",
"using",
"the",
"sensors",
"command",
".",
"Searches",
"for",
"the",
"CPU",
"temperature",
"by",
"looking",
"for",
"a",
"value",
"prefixed",
"by",
"either",
"CPU",
"Temp",
"or",
"Core",
"0",
"-",
"does",
"n... | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/sysdata.py#L269-L292 |
231,257 | ultrabug/py3status | py3status/formatter.py | Formatter.tokens | def tokens(self, format_string):
"""
Get the tokenized format_string.
Tokenizing is resource intensive so we only do it once and cache it
"""
if format_string not in self.format_string_cache:
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
tokens = list(re.finditer(self.reg_ex, format_string))
self.format_string_cache[format_string] = tokens
return self.format_string_cache[format_string] | python | def tokens(self, format_string):
if format_string not in self.format_string_cache:
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
tokens = list(re.finditer(self.reg_ex, format_string))
self.format_string_cache[format_string] = tokens
return self.format_string_cache[format_string] | [
"def",
"tokens",
"(",
"self",
",",
"format_string",
")",
":",
"if",
"format_string",
"not",
"in",
"self",
".",
"format_string_cache",
":",
"if",
"python2",
"and",
"isinstance",
"(",
"format_string",
",",
"str",
")",
":",
"format_string",
"=",
"format_string",
... | Get the tokenized format_string.
Tokenizing is resource intensive so we only do it once and cache it | [
"Get",
"the",
"tokenized",
"format_string",
".",
"Tokenizing",
"is",
"resource",
"intensive",
"so",
"we",
"only",
"do",
"it",
"once",
"and",
"cache",
"it"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L44-L54 |
231,258 | ultrabug/py3status | py3status/formatter.py | Formatter.get_color_names | def get_color_names(self, format_string):
"""
Parses the format_string and returns a set of color names.
"""
names = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("command"):
name = dict(parse_qsl(token.group("command"))).get("color")
if (
not name
or name in COLOR_NAMES_EXCLUDED
or name in COLOR_NAMES
or name[0] == "#"
):
continue
names.add(name)
return names | python | def get_color_names(self, format_string):
names = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("command"):
name = dict(parse_qsl(token.group("command"))).get("color")
if (
not name
or name in COLOR_NAMES_EXCLUDED
or name in COLOR_NAMES
or name[0] == "#"
):
continue
names.add(name)
return names | [
"def",
"get_color_names",
"(",
"self",
",",
"format_string",
")",
":",
"names",
"=",
"set",
"(",
")",
"# Tokenize the format string and process them",
"for",
"token",
"in",
"self",
".",
"tokens",
"(",
"format_string",
")",
":",
"if",
"token",
".",
"group",
"("... | Parses the format_string and returns a set of color names. | [
"Parses",
"the",
"format_string",
"and",
"returns",
"a",
"set",
"of",
"color",
"names",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L56-L73 |
231,259 | ultrabug/py3status | py3status/formatter.py | Formatter.get_placeholders | def get_placeholders(self, format_string):
"""
Parses the format_string and returns a set of placeholders.
"""
placeholders = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("placeholder"):
placeholders.add(token.group("key"))
elif token.group("command"):
# get any placeholders used in commands
commands = dict(parse_qsl(token.group("command")))
# placeholders only used in `if`
if_ = commands.get("if")
if if_:
placeholders.add(Condition(if_).variable)
return placeholders | python | def get_placeholders(self, format_string):
placeholders = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("placeholder"):
placeholders.add(token.group("key"))
elif token.group("command"):
# get any placeholders used in commands
commands = dict(parse_qsl(token.group("command")))
# placeholders only used in `if`
if_ = commands.get("if")
if if_:
placeholders.add(Condition(if_).variable)
return placeholders | [
"def",
"get_placeholders",
"(",
"self",
",",
"format_string",
")",
":",
"placeholders",
"=",
"set",
"(",
")",
"# Tokenize the format string and process them",
"for",
"token",
"in",
"self",
".",
"tokens",
"(",
"format_string",
")",
":",
"if",
"token",
".",
"group... | Parses the format_string and returns a set of placeholders. | [
"Parses",
"the",
"format_string",
"and",
"returns",
"a",
"set",
"of",
"placeholders",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L75-L91 |
231,260 | ultrabug/py3status | py3status/formatter.py | Formatter.update_placeholders | def update_placeholders(self, format_string, placeholders):
"""
Update a format string renaming placeholders.
"""
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if token.group("key") in placeholders:
output.append(
"{%s%s}" % (placeholders[token.group("key")], token.group("format"))
)
continue
elif token.group("command"):
# update any placeholders used in commands
commands = parse_qsl(token.group("command"), keep_blank_values=True)
# placeholders only used in `if`
if "if" in [x[0] for x in commands]:
items = []
for key, value in commands:
if key == "if":
# we have to rebuild from the parts we have
condition = Condition(value)
variable = condition.variable
if variable in placeholders:
variable = placeholders[variable]
# negation via `!`
not_ = "!" if not condition.default else ""
condition_ = condition.condition or ""
# if there is no condition then there is no
# value
if condition_:
value_ = condition.value
else:
value_ = ""
value = "{}{}{}{}".format(
not_, variable, condition_, value_
)
if value:
items.append("{}={}".format(key, value))
else:
items.append(key)
# we cannot use urlencode because it will escape things
# like `!`
output.append(r"\?{} ".format("&".join(items)))
continue
value = token.group(0)
output.append(value)
return u"".join(output) | python | def update_placeholders(self, format_string, placeholders):
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if token.group("key") in placeholders:
output.append(
"{%s%s}" % (placeholders[token.group("key")], token.group("format"))
)
continue
elif token.group("command"):
# update any placeholders used in commands
commands = parse_qsl(token.group("command"), keep_blank_values=True)
# placeholders only used in `if`
if "if" in [x[0] for x in commands]:
items = []
for key, value in commands:
if key == "if":
# we have to rebuild from the parts we have
condition = Condition(value)
variable = condition.variable
if variable in placeholders:
variable = placeholders[variable]
# negation via `!`
not_ = "!" if not condition.default else ""
condition_ = condition.condition or ""
# if there is no condition then there is no
# value
if condition_:
value_ = condition.value
else:
value_ = ""
value = "{}{}{}{}".format(
not_, variable, condition_, value_
)
if value:
items.append("{}={}".format(key, value))
else:
items.append(key)
# we cannot use urlencode because it will escape things
# like `!`
output.append(r"\?{} ".format("&".join(items)))
continue
value = token.group(0)
output.append(value)
return u"".join(output) | [
"def",
"update_placeholders",
"(",
"self",
",",
"format_string",
",",
"placeholders",
")",
":",
"# Tokenize the format string and process them",
"output",
"=",
"[",
"]",
"for",
"token",
"in",
"self",
".",
"tokens",
"(",
"format_string",
")",
":",
"if",
"token",
... | Update a format string renaming placeholders. | [
"Update",
"a",
"format",
"string",
"renaming",
"placeholders",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L105-L153 |
231,261 | ultrabug/py3status | py3status/formatter.py | Formatter.update_placeholder_formats | def update_placeholder_formats(self, format_string, placeholder_formats):
"""
Update a format string adding formats if they are not already present.
"""
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if (
token.group("placeholder")
and (not token.group("format"))
and token.group("key") in placeholder_formats
):
output.append(
"{%s%s}"
% (token.group("key"), placeholder_formats[token.group("key")])
)
continue
value = token.group(0)
output.append(value)
return u"".join(output) | python | def update_placeholder_formats(self, format_string, placeholder_formats):
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if (
token.group("placeholder")
and (not token.group("format"))
and token.group("key") in placeholder_formats
):
output.append(
"{%s%s}"
% (token.group("key"), placeholder_formats[token.group("key")])
)
continue
value = token.group(0)
output.append(value)
return u"".join(output) | [
"def",
"update_placeholder_formats",
"(",
"self",
",",
"format_string",
",",
"placeholder_formats",
")",
":",
"# Tokenize the format string and process them",
"output",
"=",
"[",
"]",
"for",
"token",
"in",
"self",
".",
"tokens",
"(",
"format_string",
")",
":",
"if",... | Update a format string adding formats if they are not already present. | [
"Update",
"a",
"format",
"string",
"adding",
"formats",
"if",
"they",
"are",
"not",
"already",
"present",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L155-L174 |
231,262 | ultrabug/py3status | py3status/formatter.py | Formatter.build_block | def build_block(self, format_string):
"""
Parse the format string into blocks containing Literals, Placeholders
etc that we can cache and reuse.
"""
first_block = Block(None, py3_wrapper=self.py3_wrapper)
block = first_block
# Tokenize the format string and process them
for token in self.tokens(format_string):
value = token.group(0)
if token.group("block_start"):
# Create new block
block = block.new_block()
elif token.group("block_end"):
# Close block setting any valid state as needed
# and return to parent block to continue
if not block.parent:
raise Exception("Too many `]`")
block = block.parent
elif token.group("switch"):
# a new option has been created
block = block.switch()
elif token.group("placeholder"):
# Found a {placeholder}
key = token.group("key")
format = token.group("format")
block.add(Placeholder(key, format))
elif token.group("literal"):
block.add(Literal(value))
elif token.group("lost_brace"):
# due to how parsing happens we can get a lonesome }
# eg in format_string '{{something}' this fixes that issue
block.add(Literal(value))
elif token.group("command"):
# a block command has been found
block.set_commands(token.group("command"))
elif token.group("escaped"):
# escaped characters add unescaped values
if value[0] in ["\\", "{", "}"]:
value = value[1:]
block.add(Literal(value))
if block.parent:
raise Exception("Block not closed")
# add to the cache
self.block_cache[format_string] = first_block | python | def build_block(self, format_string):
first_block = Block(None, py3_wrapper=self.py3_wrapper)
block = first_block
# Tokenize the format string and process them
for token in self.tokens(format_string):
value = token.group(0)
if token.group("block_start"):
# Create new block
block = block.new_block()
elif token.group("block_end"):
# Close block setting any valid state as needed
# and return to parent block to continue
if not block.parent:
raise Exception("Too many `]`")
block = block.parent
elif token.group("switch"):
# a new option has been created
block = block.switch()
elif token.group("placeholder"):
# Found a {placeholder}
key = token.group("key")
format = token.group("format")
block.add(Placeholder(key, format))
elif token.group("literal"):
block.add(Literal(value))
elif token.group("lost_brace"):
# due to how parsing happens we can get a lonesome }
# eg in format_string '{{something}' this fixes that issue
block.add(Literal(value))
elif token.group("command"):
# a block command has been found
block.set_commands(token.group("command"))
elif token.group("escaped"):
# escaped characters add unescaped values
if value[0] in ["\\", "{", "}"]:
value = value[1:]
block.add(Literal(value))
if block.parent:
raise Exception("Block not closed")
# add to the cache
self.block_cache[format_string] = first_block | [
"def",
"build_block",
"(",
"self",
",",
"format_string",
")",
":",
"first_block",
"=",
"Block",
"(",
"None",
",",
"py3_wrapper",
"=",
"self",
".",
"py3_wrapper",
")",
"block",
"=",
"first_block",
"# Tokenize the format string and process them",
"for",
"token",
"in... | Parse the format string into blocks containing Literals, Placeholders
etc that we can cache and reuse. | [
"Parse",
"the",
"format",
"string",
"into",
"blocks",
"containing",
"Literals",
"Placeholders",
"etc",
"that",
"we",
"can",
"cache",
"and",
"reuse",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L176-L222 |
231,263 | ultrabug/py3status | py3status/formatter.py | Formatter.format | def format(
self,
format_string,
module=None,
param_dict=None,
force_composite=False,
attr_getter=None,
):
"""
Format a string, substituting place holders which can be found in
param_dict, attributes of the supplied module, or provided via calls to
the attr_getter function.
"""
# fix python 2 unicode issues
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
if param_dict is None:
param_dict = {}
# if the processed format string is not in the cache then create it.
if format_string not in self.block_cache:
self.build_block(format_string)
first_block = self.block_cache[format_string]
def get_parameter(key):
"""
function that finds and returns the value for a placeholder.
"""
if key in param_dict:
# was a supplied parameter
param = param_dict.get(key)
elif module and hasattr(module, key):
param = getattr(module, key)
if hasattr(param, "__call__"):
# we don't allow module methods
raise Exception()
elif attr_getter:
# get value from attr_getter function
try:
param = attr_getter(key)
except: # noqa e722
raise Exception()
else:
raise Exception()
if isinstance(param, Composite):
if param.text():
param = param.copy()
else:
param = u""
elif python2 and isinstance(param, str):
param = param.decode("utf-8")
return param
# render our processed format
valid, output = first_block.render(get_parameter, module)
# clean things up a little
if isinstance(output, list):
output = Composite(output)
if not output:
if force_composite:
output = Composite()
else:
output = ""
return output | python | def format(
self,
format_string,
module=None,
param_dict=None,
force_composite=False,
attr_getter=None,
):
# fix python 2 unicode issues
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
if param_dict is None:
param_dict = {}
# if the processed format string is not in the cache then create it.
if format_string not in self.block_cache:
self.build_block(format_string)
first_block = self.block_cache[format_string]
def get_parameter(key):
"""
function that finds and returns the value for a placeholder.
"""
if key in param_dict:
# was a supplied parameter
param = param_dict.get(key)
elif module and hasattr(module, key):
param = getattr(module, key)
if hasattr(param, "__call__"):
# we don't allow module methods
raise Exception()
elif attr_getter:
# get value from attr_getter function
try:
param = attr_getter(key)
except: # noqa e722
raise Exception()
else:
raise Exception()
if isinstance(param, Composite):
if param.text():
param = param.copy()
else:
param = u""
elif python2 and isinstance(param, str):
param = param.decode("utf-8")
return param
# render our processed format
valid, output = first_block.render(get_parameter, module)
# clean things up a little
if isinstance(output, list):
output = Composite(output)
if not output:
if force_composite:
output = Composite()
else:
output = ""
return output | [
"def",
"format",
"(",
"self",
",",
"format_string",
",",
"module",
"=",
"None",
",",
"param_dict",
"=",
"None",
",",
"force_composite",
"=",
"False",
",",
"attr_getter",
"=",
"None",
",",
")",
":",
"# fix python 2 unicode issues",
"if",
"python2",
"and",
"is... | Format a string, substituting place holders which can be found in
param_dict, attributes of the supplied module, or provided via calls to
the attr_getter function. | [
"Format",
"a",
"string",
"substituting",
"place",
"holders",
"which",
"can",
"be",
"found",
"in",
"param_dict",
"attributes",
"of",
"the",
"supplied",
"module",
"or",
"provided",
"via",
"calls",
"to",
"the",
"attr_getter",
"function",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L224-L291 |
231,264 | ultrabug/py3status | py3status/formatter.py | Placeholder.get | def get(self, get_params, block):
"""
return the correct value for the placeholder
"""
value = "{%s}" % self.key
try:
value = value_ = get_params(self.key)
if self.format.startswith(":"):
# if a parameter has been set to be formatted as a numeric
# type then we see if we can coerce it to be. This allows
# the user to format types that normally would not be
# allowed eg '123' it also allows {:d} to be used as a
# shorthand for {:.0f}. Use {:g} to remove insignificant
# trailing zeroes and the decimal point too if there are
# no remaining digits following it. If the parameter cannot
# be successfully converted then the format will be removed.
try:
if "ceil" in self.format:
value = int(ceil(float(value)))
if "f" in self.format:
value = float(value)
if "g" in self.format:
value = float(value)
if "d" in self.format:
value = int(float(value))
output = u"{[%s]%s}" % (self.key, self.format)
value = output.format({self.key: value})
value_ = float(value)
except ValueError:
pass
elif self.format.startswith("!"):
output = u"{%s%s}" % (self.key, self.format)
value = value_ = output.format(**{self.key: value})
if block.commands.not_zero:
valid = value_ not in ["", None, False, "0", "0.0", 0, 0.0]
else:
# '', None, and False are ignored
# numbers like 0 and 0.0 are not.
valid = not (value_ in ["", None] or value_ is False)
enough = False
except: # noqa e722
# Exception raised when we don't have the param
enough = True
valid = False
return valid, value, enough | python | def get(self, get_params, block):
value = "{%s}" % self.key
try:
value = value_ = get_params(self.key)
if self.format.startswith(":"):
# if a parameter has been set to be formatted as a numeric
# type then we see if we can coerce it to be. This allows
# the user to format types that normally would not be
# allowed eg '123' it also allows {:d} to be used as a
# shorthand for {:.0f}. Use {:g} to remove insignificant
# trailing zeroes and the decimal point too if there are
# no remaining digits following it. If the parameter cannot
# be successfully converted then the format will be removed.
try:
if "ceil" in self.format:
value = int(ceil(float(value)))
if "f" in self.format:
value = float(value)
if "g" in self.format:
value = float(value)
if "d" in self.format:
value = int(float(value))
output = u"{[%s]%s}" % (self.key, self.format)
value = output.format({self.key: value})
value_ = float(value)
except ValueError:
pass
elif self.format.startswith("!"):
output = u"{%s%s}" % (self.key, self.format)
value = value_ = output.format(**{self.key: value})
if block.commands.not_zero:
valid = value_ not in ["", None, False, "0", "0.0", 0, 0.0]
else:
# '', None, and False are ignored
# numbers like 0 and 0.0 are not.
valid = not (value_ in ["", None] or value_ is False)
enough = False
except: # noqa e722
# Exception raised when we don't have the param
enough = True
valid = False
return valid, value, enough | [
"def",
"get",
"(",
"self",
",",
"get_params",
",",
"block",
")",
":",
"value",
"=",
"\"{%s}\"",
"%",
"self",
".",
"key",
"try",
":",
"value",
"=",
"value_",
"=",
"get_params",
"(",
"self",
".",
"key",
")",
"if",
"self",
".",
"format",
".",
"startsw... | return the correct value for the placeholder | [
"return",
"the",
"correct",
"value",
"for",
"the",
"placeholder"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L303-L349 |
231,265 | ultrabug/py3status | py3status/formatter.py | Condition._check_valid_condition | def _check_valid_condition(self, get_params):
"""
Check if the condition has been met.
We need to make sure that we are of the correct type.
"""
try:
variable = get_params(self.variable)
except: # noqa e722
variable = None
value = self.value
# if None, return oppositely
if variable is None:
return not self.default
# convert the value to a correct type
if isinstance(variable, bool):
value = bool(self.value)
elif isinstance(variable, Number):
try:
value = int(self.value)
except: # noqa e722
try:
value = float(self.value)
except: # noqa e722
# could not parse
return not self.default
# compare and return the result
if self.condition == "=":
return (variable == value) == self.default
elif self.condition == ">":
return (variable > value) == self.default
elif self.condition == "<":
return (variable < value) == self.default | python | def _check_valid_condition(self, get_params):
try:
variable = get_params(self.variable)
except: # noqa e722
variable = None
value = self.value
# if None, return oppositely
if variable is None:
return not self.default
# convert the value to a correct type
if isinstance(variable, bool):
value = bool(self.value)
elif isinstance(variable, Number):
try:
value = int(self.value)
except: # noqa e722
try:
value = float(self.value)
except: # noqa e722
# could not parse
return not self.default
# compare and return the result
if self.condition == "=":
return (variable == value) == self.default
elif self.condition == ">":
return (variable > value) == self.default
elif self.condition == "<":
return (variable < value) == self.default | [
"def",
"_check_valid_condition",
"(",
"self",
",",
"get_params",
")",
":",
"try",
":",
"variable",
"=",
"get_params",
"(",
"self",
".",
"variable",
")",
"except",
":",
"# noqa e722",
"variable",
"=",
"None",
"value",
"=",
"self",
".",
"value",
"# if None, re... | Check if the condition has been met.
We need to make sure that we are of the correct type. | [
"Check",
"if",
"the",
"condition",
"has",
"been",
"met",
".",
"We",
"need",
"to",
"make",
"sure",
"that",
"we",
"are",
"of",
"the",
"correct",
"type",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L410-L444 |
231,266 | ultrabug/py3status | py3status/formatter.py | Condition._check_valid_basic | def _check_valid_basic(self, get_params):
"""
Simple check that the variable is set
"""
try:
if get_params(self.variable):
return self.default
except: # noqa e722
pass
return not self.default | python | def _check_valid_basic(self, get_params):
try:
if get_params(self.variable):
return self.default
except: # noqa e722
pass
return not self.default | [
"def",
"_check_valid_basic",
"(",
"self",
",",
"get_params",
")",
":",
"try",
":",
"if",
"get_params",
"(",
"self",
".",
"variable",
")",
":",
"return",
"self",
".",
"default",
"except",
":",
"# noqa e722",
"pass",
"return",
"not",
"self",
".",
"default"
] | Simple check that the variable is set | [
"Simple",
"check",
"that",
"the",
"variable",
"is",
"set"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L446-L455 |
231,267 | ultrabug/py3status | py3status/formatter.py | BlockConfig.update_commands | def update_commands(self, commands_str):
"""
update with commands from the block
"""
commands = dict(parse_qsl(commands_str, keep_blank_values=True))
_if = commands.get("if", self._if)
if _if:
self._if = Condition(_if)
self._set_int(commands, "max_length")
self._set_int(commands, "min_length")
self.color = self._check_color(commands.get("color"))
self.not_zero = "not_zero" in commands or self.not_zero
self.show = "show" in commands or self.show
self.soft = "soft" in commands or self.soft | python | def update_commands(self, commands_str):
commands = dict(parse_qsl(commands_str, keep_blank_values=True))
_if = commands.get("if", self._if)
if _if:
self._if = Condition(_if)
self._set_int(commands, "max_length")
self._set_int(commands, "min_length")
self.color = self._check_color(commands.get("color"))
self.not_zero = "not_zero" in commands or self.not_zero
self.show = "show" in commands or self.show
self.soft = "soft" in commands or self.soft | [
"def",
"update_commands",
"(",
"self",
",",
"commands_str",
")",
":",
"commands",
"=",
"dict",
"(",
"parse_qsl",
"(",
"commands_str",
",",
"keep_blank_values",
"=",
"True",
")",
")",
"_if",
"=",
"commands",
".",
"get",
"(",
"\"if\"",
",",
"self",
".",
"_... | update with commands from the block | [
"update",
"with",
"commands",
"from",
"the",
"block"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L483-L497 |
231,268 | ultrabug/py3status | py3status/formatter.py | BlockConfig._set_int | def _set_int(self, commands, name):
"""
set integer value from commands
"""
if name in commands:
try:
value = int(commands[name])
setattr(self, name, value)
except ValueError:
pass | python | def _set_int(self, commands, name):
if name in commands:
try:
value = int(commands[name])
setattr(self, name, value)
except ValueError:
pass | [
"def",
"_set_int",
"(",
"self",
",",
"commands",
",",
"name",
")",
":",
"if",
"name",
"in",
"commands",
":",
"try",
":",
"value",
"=",
"int",
"(",
"commands",
"[",
"name",
"]",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
"except",
... | set integer value from commands | [
"set",
"integer",
"value",
"from",
"commands"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L499-L508 |
231,269 | ultrabug/py3status | py3status/formatter.py | Block.new_block | def new_block(self):
"""
create a new sub block to the current block and return it.
the sub block is added to the current block.
"""
child = Block(self, py3_wrapper=self.py3_wrapper)
self.add(child)
return child | python | def new_block(self):
child = Block(self, py3_wrapper=self.py3_wrapper)
self.add(child)
return child | [
"def",
"new_block",
"(",
"self",
")",
":",
"child",
"=",
"Block",
"(",
"self",
",",
"py3_wrapper",
"=",
"self",
".",
"py3_wrapper",
")",
"self",
".",
"add",
"(",
"child",
")",
"return",
"child"
] | create a new sub block to the current block and return it.
the sub block is added to the current block. | [
"create",
"a",
"new",
"sub",
"block",
"to",
"the",
"current",
"block",
"and",
"return",
"it",
".",
"the",
"sub",
"block",
"is",
"added",
"to",
"the",
"current",
"block",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L555-L562 |
231,270 | ultrabug/py3status | py3status/formatter.py | Block.switch | def switch(self):
"""
block has been split via | so we need to start a new block for that
option and return it to the user.
"""
base_block = self.base_block or self
self.next_block = Block(
self.parent, base_block=base_block, py3_wrapper=self.py3_wrapper
)
return self.next_block | python | def switch(self):
base_block = self.base_block or self
self.next_block = Block(
self.parent, base_block=base_block, py3_wrapper=self.py3_wrapper
)
return self.next_block | [
"def",
"switch",
"(",
"self",
")",
":",
"base_block",
"=",
"self",
".",
"base_block",
"or",
"self",
"self",
".",
"next_block",
"=",
"Block",
"(",
"self",
".",
"parent",
",",
"base_block",
"=",
"base_block",
",",
"py3_wrapper",
"=",
"self",
".",
"py3_wrap... | block has been split via | so we need to start a new block for that
option and return it to the user. | [
"block",
"has",
"been",
"split",
"via",
"|",
"so",
"we",
"need",
"to",
"start",
"a",
"new",
"block",
"for",
"that",
"option",
"and",
"return",
"it",
"to",
"the",
"user",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L564-L573 |
231,271 | ultrabug/py3status | py3status/formatter.py | Block.check_valid | def check_valid(self, get_params):
"""
see if the if condition for a block is valid
"""
if self.commands._if:
return self.commands._if.check_valid(get_params) | python | def check_valid(self, get_params):
if self.commands._if:
return self.commands._if.check_valid(get_params) | [
"def",
"check_valid",
"(",
"self",
",",
"get_params",
")",
":",
"if",
"self",
".",
"commands",
".",
"_if",
":",
"return",
"self",
".",
"commands",
".",
"_if",
".",
"check_valid",
"(",
"get_params",
")"
] | see if the if condition for a block is valid | [
"see",
"if",
"the",
"if",
"condition",
"for",
"a",
"block",
"is",
"valid"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L584-L589 |
231,272 | ultrabug/py3status | py3status/modules/group.py | Py3status._content_function | def _content_function(self):
"""
This returns a set containing the actively shown module.
This is so we only get update events triggered for these modules.
"""
# ensure that active is valid
self.active = self.active % len(self.items)
return set([self.items[self.active]]) | python | def _content_function(self):
# ensure that active is valid
self.active = self.active % len(self.items)
return set([self.items[self.active]]) | [
"def",
"_content_function",
"(",
"self",
")",
":",
"# ensure that active is valid",
"self",
".",
"active",
"=",
"self",
".",
"active",
"%",
"len",
"(",
"self",
".",
"items",
")",
"return",
"set",
"(",
"[",
"self",
".",
"items",
"[",
"self",
".",
"active"... | This returns a set containing the actively shown module.
This is so we only get update events triggered for these modules. | [
"This",
"returns",
"a",
"set",
"containing",
"the",
"actively",
"shown",
"module",
".",
"This",
"is",
"so",
"we",
"only",
"get",
"update",
"events",
"triggered",
"for",
"these",
"modules",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/group.py#L142-L150 |
231,273 | ultrabug/py3status | py3status/modules/group.py | Py3status._urgent_function | def _urgent_function(self, module_list):
"""
A contained module has become urgent.
We want to display it to the user.
"""
for module in module_list:
if module in self.items:
self.active = self.items.index(module)
self.urgent = True | python | def _urgent_function(self, module_list):
for module in module_list:
if module in self.items:
self.active = self.items.index(module)
self.urgent = True | [
"def",
"_urgent_function",
"(",
"self",
",",
"module_list",
")",
":",
"for",
"module",
"in",
"module_list",
":",
"if",
"module",
"in",
"self",
".",
"items",
":",
"self",
".",
"active",
"=",
"self",
".",
"items",
".",
"index",
"(",
"module",
")",
"self"... | A contained module has become urgent.
We want to display it to the user. | [
"A",
"contained",
"module",
"has",
"become",
"urgent",
".",
"We",
"want",
"to",
"display",
"it",
"to",
"the",
"user",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/group.py#L152-L160 |
231,274 | ultrabug/py3status | py3status/modules/i3pystatus.py | get_backends | def get_backends():
"""
Get backends info so that we can find the correct one.
We just look in the directory structure to find modules.
"""
IGNORE_DIRS = ["core", "tools", "utils"]
global backends
if backends is None:
backends = {}
i3pystatus_dir = os.path.dirname(i3pystatus.__file__)
subdirs = [
x
for x in next(os.walk(i3pystatus_dir))[1]
if not x.startswith("_") and x not in IGNORE_DIRS
]
for subdir in subdirs:
dirs = next(os.walk(os.path.join(i3pystatus_dir, subdir)))[2]
backends.update(
{
x[:-3]: "i3pystatus.%s.%s" % (subdir, x[:-3])
for x in dirs
if not x.startswith("_") and x.endswith(".py")
}
)
return backends | python | def get_backends():
IGNORE_DIRS = ["core", "tools", "utils"]
global backends
if backends is None:
backends = {}
i3pystatus_dir = os.path.dirname(i3pystatus.__file__)
subdirs = [
x
for x in next(os.walk(i3pystatus_dir))[1]
if not x.startswith("_") and x not in IGNORE_DIRS
]
for subdir in subdirs:
dirs = next(os.walk(os.path.join(i3pystatus_dir, subdir)))[2]
backends.update(
{
x[:-3]: "i3pystatus.%s.%s" % (subdir, x[:-3])
for x in dirs
if not x.startswith("_") and x.endswith(".py")
}
)
return backends | [
"def",
"get_backends",
"(",
")",
":",
"IGNORE_DIRS",
"=",
"[",
"\"core\"",
",",
"\"tools\"",
",",
"\"utils\"",
"]",
"global",
"backends",
"if",
"backends",
"is",
"None",
":",
"backends",
"=",
"{",
"}",
"i3pystatus_dir",
"=",
"os",
".",
"path",
".",
"dirn... | Get backends info so that we can find the correct one.
We just look in the directory structure to find modules. | [
"Get",
"backends",
"info",
"so",
"that",
"we",
"can",
"find",
"the",
"correct",
"one",
".",
"We",
"just",
"look",
"in",
"the",
"directory",
"structure",
"to",
"find",
"modules",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/i3pystatus.py#L87-L112 |
231,275 | ultrabug/py3status | py3status/modules/i3pystatus.py | ClickTimer.trigger | def trigger(self):
"""
Actually trigger the event
"""
if self.last_button:
button_index = min(self.last_button, len(self.callbacks)) - 1
click_style = 0 if self.clicks == 1 else 1
callback = self.callbacks[button_index][click_style]
if callback:
# we can do test for str as only python > 3 is supported
if isinstance(callback, str):
# no parameters
callback_name = callback
callback_args = []
else:
# has parameters
callback_name = callback[0]
callback_args = callback[1:]
callback_function = getattr(self.parent.module, callback_name)
callback_function(*callback_args)
# We want to ensure that the module has the latest output. The
# best way is to call the run method of the module
self.parent.module.run()
else:
self.parent.py3.prevent_refresh()
self.last_button = None
self.clicks = 0 | python | def trigger(self):
if self.last_button:
button_index = min(self.last_button, len(self.callbacks)) - 1
click_style = 0 if self.clicks == 1 else 1
callback = self.callbacks[button_index][click_style]
if callback:
# we can do test for str as only python > 3 is supported
if isinstance(callback, str):
# no parameters
callback_name = callback
callback_args = []
else:
# has parameters
callback_name = callback[0]
callback_args = callback[1:]
callback_function = getattr(self.parent.module, callback_name)
callback_function(*callback_args)
# We want to ensure that the module has the latest output. The
# best way is to call the run method of the module
self.parent.module.run()
else:
self.parent.py3.prevent_refresh()
self.last_button = None
self.clicks = 0 | [
"def",
"trigger",
"(",
"self",
")",
":",
"if",
"self",
".",
"last_button",
":",
"button_index",
"=",
"min",
"(",
"self",
".",
"last_button",
",",
"len",
"(",
"self",
".",
"callbacks",
")",
")",
"-",
"1",
"click_style",
"=",
"0",
"if",
"self",
".",
... | Actually trigger the event | [
"Actually",
"trigger",
"the",
"event"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/i3pystatus.py#L139-L165 |
231,276 | ultrabug/py3status | py3status/modules/i3pystatus.py | ClickTimer.event | def event(self, button):
"""
button has been clicked
"""
# cancel any pending timer
if self.timer:
self.timer.cancel()
if self.last_button != button:
if self.last_button:
# new button clicked process the one before.
self.trigger()
self.clicks = 1
else:
self.clicks += 1
# do we accept double clicks on this button?
# if not then just process the click
button_index = min(button, len(self.callbacks)) - 1
if not self.callbacks[button_index][1]:
# set things up correctly for the trigger
self.clicks = 1
self.last_button = button
self.trigger()
else:
# set a timeout to trigger the click
# this will be cancelled if we click again before it runs
self.last_button = button
self.timer = Timer(self.click_time, self.trigger)
self.timer.start() | python | def event(self, button):
# cancel any pending timer
if self.timer:
self.timer.cancel()
if self.last_button != button:
if self.last_button:
# new button clicked process the one before.
self.trigger()
self.clicks = 1
else:
self.clicks += 1
# do we accept double clicks on this button?
# if not then just process the click
button_index = min(button, len(self.callbacks)) - 1
if not self.callbacks[button_index][1]:
# set things up correctly for the trigger
self.clicks = 1
self.last_button = button
self.trigger()
else:
# set a timeout to trigger the click
# this will be cancelled if we click again before it runs
self.last_button = button
self.timer = Timer(self.click_time, self.trigger)
self.timer.start() | [
"def",
"event",
"(",
"self",
",",
"button",
")",
":",
"# cancel any pending timer",
"if",
"self",
".",
"timer",
":",
"self",
".",
"timer",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"last_button",
"!=",
"button",
":",
"if",
"self",
".",
"last_button",
... | button has been clicked | [
"button",
"has",
"been",
"clicked"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/i3pystatus.py#L167-L194 |
231,277 | ultrabug/py3status | py3status/modules/net_rate.py | Py3status._get_stat | def _get_stat(self):
"""
Get statistics from devfile in list of lists of words
"""
def dev_filter(x):
# get first word and remove trailing interface number
x = x.strip().split(" ")[0][:-1]
if x in self.interfaces_blacklist:
return False
if self.all_interfaces:
return True
if x in self.interfaces:
return True
return False
# read devfile, skip two header files
x = filter(dev_filter, open(self.devfile).readlines()[2:])
try:
# split info into words, filter empty ones
return [list(filter(lambda x: x, _x.split(" "))) for _x in x]
except StopIteration:
return None | python | def _get_stat(self):
def dev_filter(x):
# get first word and remove trailing interface number
x = x.strip().split(" ")[0][:-1]
if x in self.interfaces_blacklist:
return False
if self.all_interfaces:
return True
if x in self.interfaces:
return True
return False
# read devfile, skip two header files
x = filter(dev_filter, open(self.devfile).readlines()[2:])
try:
# split info into words, filter empty ones
return [list(filter(lambda x: x, _x.split(" "))) for _x in x]
except StopIteration:
return None | [
"def",
"_get_stat",
"(",
"self",
")",
":",
"def",
"dev_filter",
"(",
"x",
")",
":",
"# get first word and remove trailing interface number",
"x",
"=",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
"[",
":",
"-",
"1",
"]",... | Get statistics from devfile in list of lists of words | [
"Get",
"statistics",
"from",
"devfile",
"in",
"list",
"of",
"lists",
"of",
"words"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/net_rate.py#L191-L219 |
231,278 | ultrabug/py3status | py3status/modules/net_rate.py | Py3status._format_value | def _format_value(self, value):
"""
Return formatted string
"""
value, unit = self.py3.format_units(value, unit=self.unit, si=self.si_units)
return self.py3.safe_format(self.format_value, {"value": value, "unit": unit}) | python | def _format_value(self, value):
value, unit = self.py3.format_units(value, unit=self.unit, si=self.si_units)
return self.py3.safe_format(self.format_value, {"value": value, "unit": unit}) | [
"def",
"_format_value",
"(",
"self",
",",
"value",
")",
":",
"value",
",",
"unit",
"=",
"self",
".",
"py3",
".",
"format_units",
"(",
"value",
",",
"unit",
"=",
"self",
".",
"unit",
",",
"si",
"=",
"self",
".",
"si_units",
")",
"return",
"self",
".... | Return formatted string | [
"Return",
"formatted",
"string"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/net_rate.py#L221-L226 |
231,279 | ultrabug/py3status | py3status/modules/i3block.py | Py3status._persist | def _persist(self):
"""
Run the command inside a thread so that we can catch output for each
line as it comes in and display it.
"""
# run the block/command
for command in self.commands:
try:
process = Popen(
[command],
stdout=PIPE,
stderr=PIPE,
universal_newlines=True,
env=self.env,
shell=True,
)
except Exception as e:
retcode = process.poll()
msg = "Command '{cmd}' {error} retcode {retcode}"
self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))
# persistent blocklet output can be of two forms. Either each row
# of the output is on a new line this is much easier to deal with)
# or else the output can be continuous and just flushed when ready.
# The second form is more tricky, if we find newlines then we
# switch to easy parsing of the output.
# When we have output we store in self.persistent_output and then
# trigger the module to update.
fd = process.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
has_newlines = False
while True:
line = process.stdout.read(1)
# switch to a non-blocking read as we do not know the output
# length
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
line += process.stdout.read(1024)
# switch back to blocking so we can wait for the next output
fcntl.fcntl(fd, fcntl.F_SETFL, fl)
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
if line[-1] == "\n":
has_newlines = True
break
if line == "":
break
if has_newlines:
msg = "Switch to newline persist method {cmd}"
self.py3.log(msg.format(cmd=command))
# just read the output in a sane manner
for line in iter(process.stdout.readline, b""):
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
self.py3.log("command exited {cmd}".format(cmd=command))
self.persistent_output = "Error\nError\n{}".format(
self.py3.COLOR_ERROR or self.py3.COLOR_BAD
)
self.py3.update() | python | def _persist(self):
# run the block/command
for command in self.commands:
try:
process = Popen(
[command],
stdout=PIPE,
stderr=PIPE,
universal_newlines=True,
env=self.env,
shell=True,
)
except Exception as e:
retcode = process.poll()
msg = "Command '{cmd}' {error} retcode {retcode}"
self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))
# persistent blocklet output can be of two forms. Either each row
# of the output is on a new line this is much easier to deal with)
# or else the output can be continuous and just flushed when ready.
# The second form is more tricky, if we find newlines then we
# switch to easy parsing of the output.
# When we have output we store in self.persistent_output and then
# trigger the module to update.
fd = process.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
has_newlines = False
while True:
line = process.stdout.read(1)
# switch to a non-blocking read as we do not know the output
# length
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
line += process.stdout.read(1024)
# switch back to blocking so we can wait for the next output
fcntl.fcntl(fd, fcntl.F_SETFL, fl)
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
if line[-1] == "\n":
has_newlines = True
break
if line == "":
break
if has_newlines:
msg = "Switch to newline persist method {cmd}"
self.py3.log(msg.format(cmd=command))
# just read the output in a sane manner
for line in iter(process.stdout.readline, b""):
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
self.py3.log("command exited {cmd}".format(cmd=command))
self.persistent_output = "Error\nError\n{}".format(
self.py3.COLOR_ERROR or self.py3.COLOR_BAD
)
self.py3.update() | [
"def",
"_persist",
"(",
"self",
")",
":",
"# run the block/command",
"for",
"command",
"in",
"self",
".",
"commands",
":",
"try",
":",
"process",
"=",
"Popen",
"(",
"[",
"command",
"]",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"univ... | Run the command inside a thread so that we can catch output for each
line as it comes in and display it. | [
"Run",
"the",
"command",
"inside",
"a",
"thread",
"so",
"that",
"we",
"can",
"catch",
"output",
"for",
"each",
"line",
"as",
"it",
"comes",
"in",
"and",
"display",
"it",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/i3block.py#L158-L225 |
231,280 | ultrabug/py3status | py3status/autodoc.py | markdown_2_rst | def markdown_2_rst(lines):
"""
Convert markdown to restructured text
"""
out = []
code = False
for line in lines:
# code blocks
if line.strip() == "```":
code = not code
space = " " * (len(line.rstrip()) - 3)
if code:
out.append("\n\n%s.. code-block:: none\n\n" % space)
else:
out.append("\n")
else:
if code and line.strip():
line = " " + line
else:
# escape any backslashes
line = line.replace("\\", "\\\\")
out.append(line)
return out | python | def markdown_2_rst(lines):
out = []
code = False
for line in lines:
# code blocks
if line.strip() == "```":
code = not code
space = " " * (len(line.rstrip()) - 3)
if code:
out.append("\n\n%s.. code-block:: none\n\n" % space)
else:
out.append("\n")
else:
if code and line.strip():
line = " " + line
else:
# escape any backslashes
line = line.replace("\\", "\\\\")
out.append(line)
return out | [
"def",
"markdown_2_rst",
"(",
"lines",
")",
":",
"out",
"=",
"[",
"]",
"code",
"=",
"False",
"for",
"line",
"in",
"lines",
":",
"# code blocks",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"\"```\"",
":",
"code",
"=",
"not",
"code",
"space",
"=",
"... | Convert markdown to restructured text | [
"Convert",
"markdown",
"to",
"restructured",
"text"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L93-L115 |
231,281 | ultrabug/py3status | py3status/autodoc.py | file_sort | def file_sort(my_list):
"""
Sort a list of files in a nice way.
eg item-10 will be after item-9
"""
def alphanum_key(key):
"""
Split the key into str/int parts
"""
return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)]
my_list.sort(key=alphanum_key)
return my_list | python | def file_sort(my_list):
def alphanum_key(key):
"""
Split the key into str/int parts
"""
return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)]
my_list.sort(key=alphanum_key)
return my_list | [
"def",
"file_sort",
"(",
"my_list",
")",
":",
"def",
"alphanum_key",
"(",
"key",
")",
":",
"\"\"\"\n Split the key into str/int parts\n \"\"\"",
"return",
"[",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
"for",
"s",
... | Sort a list of files in a nice way.
eg item-10 will be after item-9 | [
"Sort",
"a",
"list",
"of",
"files",
"in",
"a",
"nice",
"way",
".",
"eg",
"item",
"-",
"10",
"will",
"be",
"after",
"item",
"-",
"9"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L118-L131 |
231,282 | ultrabug/py3status | py3status/autodoc.py | screenshots | def screenshots(screenshots_data, module_name):
"""
Create .rst output for any screenshots a module may have.
"""
shots = screenshots_data.get(module_name)
if not shots:
return ""
out = []
for shot in file_sort(shots):
if not os.path.exists("../doc/screenshots/%s.png" % shot):
continue
out.append(u"\n.. image:: screenshots/{}.png\n\n".format(shot))
return u"".join(out) | python | def screenshots(screenshots_data, module_name):
shots = screenshots_data.get(module_name)
if not shots:
return ""
out = []
for shot in file_sort(shots):
if not os.path.exists("../doc/screenshots/%s.png" % shot):
continue
out.append(u"\n.. image:: screenshots/{}.png\n\n".format(shot))
return u"".join(out) | [
"def",
"screenshots",
"(",
"screenshots_data",
",",
"module_name",
")",
":",
"shots",
"=",
"screenshots_data",
".",
"get",
"(",
"module_name",
")",
"if",
"not",
"shots",
":",
"return",
"\"\"",
"out",
"=",
"[",
"]",
"for",
"shot",
"in",
"file_sort",
"(",
... | Create .rst output for any screenshots a module may have. | [
"Create",
".",
"rst",
"output",
"for",
"any",
"screenshots",
"a",
"module",
"may",
"have",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L134-L147 |
231,283 | ultrabug/py3status | py3status/autodoc.py | create_module_docs | def create_module_docs():
"""
Create documentation for modules.
"""
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_data:
screenshots_data[module] = []
screenshots_data[module].append(sample)
out = []
# details
for module in sorted(data.keys()):
out.append("\n.. _module_%s:\n" % module) # reference for linking
out.append(
"\n{name}\n{underline}\n\n{screenshots}{details}\n".format(
name=module,
screenshots=screenshots(screenshots_data, module),
underline="-" * len(module),
details="".join(markdown_2_rst(data[module])).strip(),
)
)
# write include file
with open("../doc/modules-info.inc", "w") as f:
f.write("".join(out)) | python | def create_module_docs():
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_data:
screenshots_data[module] = []
screenshots_data[module].append(sample)
out = []
# details
for module in sorted(data.keys()):
out.append("\n.. _module_%s:\n" % module) # reference for linking
out.append(
"\n{name}\n{underline}\n\n{screenshots}{details}\n".format(
name=module,
screenshots=screenshots(screenshots_data, module),
underline="-" * len(module),
details="".join(markdown_2_rst(data[module])).strip(),
)
)
# write include file
with open("../doc/modules-info.inc", "w") as f:
f.write("".join(out)) | [
"def",
"create_module_docs",
"(",
")",
":",
"data",
"=",
"core_module_docstrings",
"(",
"format",
"=",
"\"rst\"",
")",
"# get screenshot data",
"screenshots_data",
"=",
"{",
"}",
"samples",
"=",
"get_samples",
"(",
")",
"for",
"sample",
"in",
"samples",
".",
"... | Create documentation for modules. | [
"Create",
"documentation",
"for",
"modules",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L150-L178 |
231,284 | ultrabug/py3status | py3status/autodoc.py | get_variable_docstrings | def get_variable_docstrings(filename):
"""
Go through the file and find all documented variables.
That is ones that have a literal expression following them.
Also get a dict of assigned values so that we can substitute constants.
"""
def walk_node(parent, values=None, prefix=""):
"""
walk the ast searching for docstrings/values
"""
docstrings = {}
if values is None:
values = {}
key = None
for node in ast.iter_child_nodes(parent):
if isinstance(node, ast.ClassDef):
# We are in a class so walk the class
docs = walk_node(node, values, prefix + node.name + ".")[0]
docstrings[node.name] = docs
elif isinstance(node, ast.Assign):
key = node.targets[0].id
if isinstance(node.value, ast.Num):
values[key] = node.value.n
if isinstance(node.value, ast.Str):
values[key] = node.value.s
if isinstance(node.value, ast.Name):
if node.value.id in values:
values[prefix + key] = values[node.value.id]
elif isinstance(node, ast.Expr) and key:
docstrings[key] = node.value.s
else:
key = None
return docstrings, values
with open(filename, "r") as f:
source = f.read()
return walk_node(ast.parse(source)) | python | def get_variable_docstrings(filename):
def walk_node(parent, values=None, prefix=""):
"""
walk the ast searching for docstrings/values
"""
docstrings = {}
if values is None:
values = {}
key = None
for node in ast.iter_child_nodes(parent):
if isinstance(node, ast.ClassDef):
# We are in a class so walk the class
docs = walk_node(node, values, prefix + node.name + ".")[0]
docstrings[node.name] = docs
elif isinstance(node, ast.Assign):
key = node.targets[0].id
if isinstance(node.value, ast.Num):
values[key] = node.value.n
if isinstance(node.value, ast.Str):
values[key] = node.value.s
if isinstance(node.value, ast.Name):
if node.value.id in values:
values[prefix + key] = values[node.value.id]
elif isinstance(node, ast.Expr) and key:
docstrings[key] = node.value.s
else:
key = None
return docstrings, values
with open(filename, "r") as f:
source = f.read()
return walk_node(ast.parse(source)) | [
"def",
"get_variable_docstrings",
"(",
"filename",
")",
":",
"def",
"walk_node",
"(",
"parent",
",",
"values",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
")",
":",
"\"\"\"\n walk the ast searching for docstrings/values\n \"\"\"",
"docstrings",
"=",
"{",
"}... | Go through the file and find all documented variables.
That is ones that have a literal expression following them.
Also get a dict of assigned values so that we can substitute constants. | [
"Go",
"through",
"the",
"file",
"and",
"find",
"all",
"documented",
"variables",
".",
"That",
"is",
"ones",
"that",
"have",
"a",
"literal",
"expression",
"following",
"them",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L181-L219 |
231,285 | ultrabug/py3status | py3status/autodoc.py | get_py3_info | def get_py3_info():
"""
Inspect Py3 class and get constants, exceptions, methods
along with their docstrings.
"""
# get all documented constants and their values
constants, values = get_variable_docstrings("../py3status/py3.py")
# we only care about ones defined in Py3
constants = constants["Py3"]
# sort them alphabetically
constants = [(k, v) for k, v in sorted(constants.items())]
# filter values as we only care about values defined in Py3
values = dict([(v, k[4:]) for k, v in values.items() if k.startswith("Py3.")])
def make_value(attr, arg, default):
"""
If the methods parameter is defined as a constant then do a
replacement. Otherwise return the values representation.
"""
if (attr, arg) in CONSTANT_PARAMS and default in values:
return values[default]
return repr(default)
# inspect Py3 to find it's methods etc
py3 = Py3()
# no private ones
attrs = [x for x in dir(py3) if not x.startswith("_")]
exceptions = []
methods = []
for attr in attrs:
item = getattr(py3, attr)
if "method" in str(item):
# a method so we need to get the call parameters
args, vargs, kw, defaults = inspect.getargspec(item)
args = args[1:]
len_defaults = len(defaults) if defaults else 0
len_args = len(args)
sig = []
for index, arg in enumerate(args):
# default values set?
if len_args - index <= len_defaults:
default = defaults[len_defaults - len_args + index]
sig.append("%s=%s" % (arg, make_value(attr, arg, default)))
else:
sig.append(arg)
definition = "%s(%s)" % (attr, ", ".join(sig))
methods.append((definition, item.__doc__))
continue
try:
# find any exceptions
if isinstance(item(), Exception):
exceptions.append((attr, item.__doc__))
continue
except: # noqa e722
pass
return {"methods": methods, "exceptions": exceptions, "constants": constants} | python | def get_py3_info():
# get all documented constants and their values
constants, values = get_variable_docstrings("../py3status/py3.py")
# we only care about ones defined in Py3
constants = constants["Py3"]
# sort them alphabetically
constants = [(k, v) for k, v in sorted(constants.items())]
# filter values as we only care about values defined in Py3
values = dict([(v, k[4:]) for k, v in values.items() if k.startswith("Py3.")])
def make_value(attr, arg, default):
"""
If the methods parameter is defined as a constant then do a
replacement. Otherwise return the values representation.
"""
if (attr, arg) in CONSTANT_PARAMS and default in values:
return values[default]
return repr(default)
# inspect Py3 to find it's methods etc
py3 = Py3()
# no private ones
attrs = [x for x in dir(py3) if not x.startswith("_")]
exceptions = []
methods = []
for attr in attrs:
item = getattr(py3, attr)
if "method" in str(item):
# a method so we need to get the call parameters
args, vargs, kw, defaults = inspect.getargspec(item)
args = args[1:]
len_defaults = len(defaults) if defaults else 0
len_args = len(args)
sig = []
for index, arg in enumerate(args):
# default values set?
if len_args - index <= len_defaults:
default = defaults[len_defaults - len_args + index]
sig.append("%s=%s" % (arg, make_value(attr, arg, default)))
else:
sig.append(arg)
definition = "%s(%s)" % (attr, ", ".join(sig))
methods.append((definition, item.__doc__))
continue
try:
# find any exceptions
if isinstance(item(), Exception):
exceptions.append((attr, item.__doc__))
continue
except: # noqa e722
pass
return {"methods": methods, "exceptions": exceptions, "constants": constants} | [
"def",
"get_py3_info",
"(",
")",
":",
"# get all documented constants and their values",
"constants",
",",
"values",
"=",
"get_variable_docstrings",
"(",
"\"../py3status/py3.py\"",
")",
"# we only care about ones defined in Py3",
"constants",
"=",
"constants",
"[",
"\"Py3\"",
... | Inspect Py3 class and get constants, exceptions, methods
along with their docstrings. | [
"Inspect",
"Py3",
"class",
"and",
"get",
"constants",
"exceptions",
"methods",
"along",
"with",
"their",
"docstrings",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L222-L280 |
231,286 | ultrabug/py3status | py3status/autodoc.py | auto_undent | def auto_undent(string):
"""
Unindent a docstring.
"""
lines = string.splitlines()
while lines[0].strip() == "":
lines = lines[1:]
if not lines:
return []
spaces = len(lines[0]) - len(lines[0].lstrip(" "))
out = []
for line in lines:
num_spaces = len(line) - len(line.lstrip(" "))
out.append(line[min(spaces, num_spaces) :])
return out | python | def auto_undent(string):
lines = string.splitlines()
while lines[0].strip() == "":
lines = lines[1:]
if not lines:
return []
spaces = len(lines[0]) - len(lines[0].lstrip(" "))
out = []
for line in lines:
num_spaces = len(line) - len(line.lstrip(" "))
out.append(line[min(spaces, num_spaces) :])
return out | [
"def",
"auto_undent",
"(",
"string",
")",
":",
"lines",
"=",
"string",
".",
"splitlines",
"(",
")",
"while",
"lines",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"lines",
"=",
"lines",
"[",
"1",
":",
"]",
"if",
"not",
"lines",
":",
... | Unindent a docstring. | [
"Unindent",
"a",
"docstring",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L283-L297 |
231,287 | ultrabug/py3status | py3status/autodoc.py | create_py3_docs | def create_py3_docs():
"""
Create the include files for py3 documentation.
"""
# we want the correct .rst 'type' for our data
trans = {"methods": "function", "exceptions": "exception", "constants": "attribute"}
data = get_py3_info()
for k, v in data.items():
output = []
for name, desc in v:
output.append("")
output.append(".. _%s:" % name) # reference for linking
output.append("")
output.append(".. py:%s:: %s" % (trans[k], name))
output.append("")
output.extend(auto_undent(desc))
with open("../doc/py3-%s-info.inc" % k, "w") as f:
f.write("\n".join(output)) | python | def create_py3_docs():
# we want the correct .rst 'type' for our data
trans = {"methods": "function", "exceptions": "exception", "constants": "attribute"}
data = get_py3_info()
for k, v in data.items():
output = []
for name, desc in v:
output.append("")
output.append(".. _%s:" % name) # reference for linking
output.append("")
output.append(".. py:%s:: %s" % (trans[k], name))
output.append("")
output.extend(auto_undent(desc))
with open("../doc/py3-%s-info.inc" % k, "w") as f:
f.write("\n".join(output)) | [
"def",
"create_py3_docs",
"(",
")",
":",
"# we want the correct .rst 'type' for our data",
"trans",
"=",
"{",
"\"methods\"",
":",
"\"function\"",
",",
"\"exceptions\"",
":",
"\"exception\"",
",",
"\"constants\"",
":",
"\"attribute\"",
"}",
"data",
"=",
"get_py3_info",
... | Create the include files for py3 documentation. | [
"Create",
"the",
"include",
"files",
"for",
"py3",
"documentation",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L300-L317 |
231,288 | ultrabug/py3status | py3status/modules/timer.py | Py3status._time_up | def _time_up(self):
"""
Called when the timer expires
"""
self.running = False
self.color = self.py3.COLOR_BAD
self.time_left = 0
self.done = True
if self.sound:
self.py3.play_sound(self.sound)
self.alarm = True
self.timer() | python | def _time_up(self):
self.running = False
self.color = self.py3.COLOR_BAD
self.time_left = 0
self.done = True
if self.sound:
self.py3.play_sound(self.sound)
self.alarm = True
self.timer() | [
"def",
"_time_up",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"self",
".",
"color",
"=",
"self",
".",
"py3",
".",
"COLOR_BAD",
"self",
".",
"time_left",
"=",
"0",
"self",
".",
"done",
"=",
"True",
"if",
"self",
".",
"sound",
":",
... | Called when the timer expires | [
"Called",
"when",
"the",
"timer",
"expires"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/timer.py#L70-L81 |
231,289 | ultrabug/py3status | py3status/request.py | HttpResponse.status_code | def status_code(self):
"""
Get the http status code for the response
"""
try:
return self._status_code
except AttributeError:
self._status_code = self._response.getcode()
return self._status_code | python | def status_code(self):
try:
return self._status_code
except AttributeError:
self._status_code = self._response.getcode()
return self._status_code | [
"def",
"status_code",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_status_code",
"except",
"AttributeError",
":",
"self",
".",
"_status_code",
"=",
"self",
".",
"_response",
".",
"getcode",
"(",
")",
"return",
"self",
".",
"_status_code"
] | Get the http status code for the response | [
"Get",
"the",
"http",
"status",
"code",
"for",
"the",
"response"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/request.py#L93-L101 |
231,290 | ultrabug/py3status | py3status/request.py | HttpResponse.text | def text(self):
"""
Get the raw text for the response
"""
try:
return self._text
except AttributeError:
if IS_PYTHON_3:
encoding = self._response.headers.get_content_charset("utf-8")
else:
encoding = self._response.headers.getparam("charset")
self._text = self._response.read().decode(encoding or "utf-8")
return self._text | python | def text(self):
try:
return self._text
except AttributeError:
if IS_PYTHON_3:
encoding = self._response.headers.get_content_charset("utf-8")
else:
encoding = self._response.headers.getparam("charset")
self._text = self._response.read().decode(encoding or "utf-8")
return self._text | [
"def",
"text",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_text",
"except",
"AttributeError",
":",
"if",
"IS_PYTHON_3",
":",
"encoding",
"=",
"self",
".",
"_response",
".",
"headers",
".",
"get_content_charset",
"(",
"\"utf-8\"",
")",
"else... | Get the raw text for the response | [
"Get",
"the",
"raw",
"text",
"for",
"the",
"response"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/request.py#L104-L116 |
231,291 | ultrabug/py3status | py3status/request.py | HttpResponse.json | def json(self):
"""
Return an object representing the return json for the request
"""
try:
return self._json
except AttributeError:
try:
self._json = json.loads(self.text)
return self._json
except: # noqa e722
raise RequestInvalidJSON("Invalid JSON received") | python | def json(self):
try:
return self._json
except AttributeError:
try:
self._json = json.loads(self.text)
return self._json
except: # noqa e722
raise RequestInvalidJSON("Invalid JSON received") | [
"def",
"json",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_json",
"except",
"AttributeError",
":",
"try",
":",
"self",
".",
"_json",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"text",
")",
"return",
"self",
".",
"_json",
"except",
... | Return an object representing the return json for the request | [
"Return",
"an",
"object",
"representing",
"the",
"return",
"json",
"for",
"the",
"request"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/request.py#L118-L129 |
231,292 | ultrabug/py3status | py3status/request.py | HttpResponse.headers | def headers(self):
"""
Get the headers from the response.
"""
try:
return self._headers
except AttributeError:
self._headers = self._response.headers
return self._headers | python | def headers(self):
try:
return self._headers
except AttributeError:
self._headers = self._response.headers
return self._headers | [
"def",
"headers",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_headers",
"except",
"AttributeError",
":",
"self",
".",
"_headers",
"=",
"self",
".",
"_response",
".",
"headers",
"return",
"self",
".",
"_headers"
] | Get the headers from the response. | [
"Get",
"the",
"headers",
"from",
"the",
"response",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/request.py#L132-L140 |
231,293 | ultrabug/py3status | py3status/docstrings.py | modules_directory | def modules_directory():
"""
Get the core modules directory.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") | python | def modules_directory():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") | [
"def",
"modules_directory",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\"modules\"",
")"
] | Get the core modules directory. | [
"Get",
"the",
"core",
"modules",
"directory",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L10-L14 |
231,294 | ultrabug/py3status | py3status/docstrings.py | create_readme | def create_readme(data):
"""
Create README.md text for the given module data.
"""
out = ['<a name="top"></a>Modules\n========\n\n']
# Links
for module in sorted(data.keys()):
desc = "".join(data[module]).strip().split("\n")[0]
format_str = "\n**[{name}](#{name})** — {desc}\n"
out.append(format_str.format(name=module, desc=desc))
# details
for module in sorted(data.keys()):
out.append(
'\n---\n\n### <a name="{name}"></a>{name}\n\n{details}\n'.format(
name=module, details="".join(data[module]).strip()
)
)
return "".join(out) | python | def create_readme(data):
out = ['<a name="top"></a>Modules\n========\n\n']
# Links
for module in sorted(data.keys()):
desc = "".join(data[module]).strip().split("\n")[0]
format_str = "\n**[{name}](#{name})** — {desc}\n"
out.append(format_str.format(name=module, desc=desc))
# details
for module in sorted(data.keys()):
out.append(
'\n---\n\n### <a name="{name}"></a>{name}\n\n{details}\n'.format(
name=module, details="".join(data[module]).strip()
)
)
return "".join(out) | [
"def",
"create_readme",
"(",
"data",
")",
":",
"out",
"=",
"[",
"'<a name=\"top\"></a>Modules\\n========\\n\\n'",
"]",
"# Links",
"for",
"module",
"in",
"sorted",
"(",
"data",
".",
"keys",
"(",
")",
")",
":",
"desc",
"=",
"\"\"",
".",
"join",
"(",
"data",
... | Create README.md text for the given module data. | [
"Create",
"README",
".",
"md",
"text",
"for",
"the",
"given",
"module",
"data",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L98-L115 |
231,295 | ultrabug/py3status | py3status/docstrings.py | _reformat_docstring | def _reformat_docstring(doc, format_fn, code_newline=""):
"""
Go through lines of file and reformat using format_fn
"""
out = []
status = {"listing": False, "add_line": False, "eat_line": False}
code = False
for line in doc:
if status["add_line"]:
out.append("\n")
status["add_line"] = False
if status["eat_line"]:
status["eat_line"] = False
if line.strip() == "":
continue
# check for start/end of code block
if line.strip() == "```":
code = not code
out.append(line + code_newline)
continue
if not code:
# if we are in a block listing a blank line ends it
if line.rstrip() == "":
status["listing"] = False
# format the line
line = format_fn(line, status)
# see if block start
if re_listing.match(line):
status["listing"] = True
out.append(line.rstrip() + "\n")
return out | python | def _reformat_docstring(doc, format_fn, code_newline=""):
out = []
status = {"listing": False, "add_line": False, "eat_line": False}
code = False
for line in doc:
if status["add_line"]:
out.append("\n")
status["add_line"] = False
if status["eat_line"]:
status["eat_line"] = False
if line.strip() == "":
continue
# check for start/end of code block
if line.strip() == "```":
code = not code
out.append(line + code_newline)
continue
if not code:
# if we are in a block listing a blank line ends it
if line.rstrip() == "":
status["listing"] = False
# format the line
line = format_fn(line, status)
# see if block start
if re_listing.match(line):
status["listing"] = True
out.append(line.rstrip() + "\n")
return out | [
"def",
"_reformat_docstring",
"(",
"doc",
",",
"format_fn",
",",
"code_newline",
"=",
"\"\"",
")",
":",
"out",
"=",
"[",
"]",
"status",
"=",
"{",
"\"listing\"",
":",
"False",
",",
"\"add_line\"",
":",
"False",
",",
"\"eat_line\"",
":",
"False",
"}",
"cod... | Go through lines of file and reformat using format_fn | [
"Go",
"through",
"lines",
"of",
"file",
"and",
"reformat",
"using",
"format_fn"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L140-L170 |
231,296 | ultrabug/py3status | py3status/docstrings.py | _to_docstring | def _to_docstring(doc):
"""
format from Markdown to docstring
"""
def format_fn(line, status):
""" format function """
# swap < > to < >
line = re_to_tag.sub(r"<\1>", line)
if re_to_data.match(line):
line = re_to_data.sub(r"@\1 ", line)
status["eat_line"] = True
line = re_to_defaults.sub(r"\1", line)
if status["listing"]:
# parameters
if re_to_param.match(line):
line = re_to_param.sub(r" \1: ", line)
# status items
elif re_to_status.match(line):
line = re_to_status.sub(r" \1 ", line)
# bullets
elif re_to_item.match(line):
line = re_to_item.sub(r" -", line)
# is continuation line
else:
line = " " * 8 + line.lstrip()
return line
return _reformat_docstring(doc, format_fn) | python | def _to_docstring(doc):
def format_fn(line, status):
""" format function """
# swap < > to < >
line = re_to_tag.sub(r"<\1>", line)
if re_to_data.match(line):
line = re_to_data.sub(r"@\1 ", line)
status["eat_line"] = True
line = re_to_defaults.sub(r"\1", line)
if status["listing"]:
# parameters
if re_to_param.match(line):
line = re_to_param.sub(r" \1: ", line)
# status items
elif re_to_status.match(line):
line = re_to_status.sub(r" \1 ", line)
# bullets
elif re_to_item.match(line):
line = re_to_item.sub(r" -", line)
# is continuation line
else:
line = " " * 8 + line.lstrip()
return line
return _reformat_docstring(doc, format_fn) | [
"def",
"_to_docstring",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"# swap < > to < >",
"line",
"=",
"re_to_tag",
".",
"sub",
"(",
"r\"<\\1>\"",
",",
"line",
")",
"if",
"re_to_data",
"... | format from Markdown to docstring | [
"format",
"from",
"Markdown",
"to",
"docstring"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L173-L201 |
231,297 | ultrabug/py3status | py3status/docstrings.py | _from_docstring_md | def _from_docstring_md(doc):
"""
format from docstring to Markdown
"""
def format_fn(line, status):
""" format function """
def fix_tags(line):
# In markdown we need to escape < > and & for display
# but we don't want to do this is the value is quoted
# by backticks ``
def fn(match):
# swap matched chars
found = match.group(1)
if found == "<":
return "<"
if found == ">":
return ">"
if found == "&":
return "&"
return match.group(0)
return re_from_tag.sub(fn, line)
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", fix_tags(line))
# is continuation line
else:
line = fix_tags(line)
line = " " * 4 + line.lstrip()
else:
line = fix_tags(line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\n") | python | def _from_docstring_md(doc):
def format_fn(line, status):
""" format function """
def fix_tags(line):
# In markdown we need to escape < > and & for display
# but we don't want to do this is the value is quoted
# by backticks ``
def fn(match):
# swap matched chars
found = match.group(1)
if found == "<":
return "<"
if found == ">":
return ">"
if found == "&":
return "&"
return match.group(0)
return re_from_tag.sub(fn, line)
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", fix_tags(line))
# is continuation line
else:
line = fix_tags(line)
line = " " * 4 + line.lstrip()
else:
line = fix_tags(line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\n") | [
"def",
"_from_docstring_md",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"def",
"fix_tags",
"(",
"line",
")",
":",
"# In markdown we need to escape < > and & for display",
"# but we don't want to do this... | format from docstring to Markdown | [
"format",
"from",
"docstring",
"to",
"Markdown"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L204-L254 |
231,298 | ultrabug/py3status | py3status/docstrings.py | _from_docstring_rst | def _from_docstring_rst(doc):
"""
format from docstring to ReStructured Text
"""
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", line)
# is continuation line
else:
line = " " * 4 + line.lstrip()
# in .rst format code samples use double backticks vs single ones for
# .md This converts them.
line = re_lone_backtick.sub("``", line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\n") | python | def _from_docstring_rst(doc):
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", line)
# is continuation line
else:
line = " " * 4 + line.lstrip()
# in .rst format code samples use double backticks vs single ones for
# .md This converts them.
line = re_lone_backtick.sub("``", line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\n") | [
"def",
"_from_docstring_rst",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"if",
"re_from_data",
".",
"match",
"(",
"line",
")",
":",
"line",
"=",
"re_from_data",
".",
"sub",
"(",
"r\"**\\1*... | format from docstring to ReStructured Text | [
"format",
"from",
"docstring",
"to",
"ReStructured",
"Text"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L257-L289 |
231,299 | ultrabug/py3status | py3status/docstrings.py | check_docstrings | def check_docstrings(show_diff=False, config=None, mods=None):
"""
Check docstrings in module match the README.md
"""
readme = parse_readme()
modules_readme = core_module_docstrings(config=config)
warned = False
if create_readme(readme) != create_readme(modules_readme):
for module in sorted(readme):
if mods and module not in mods:
continue
err = None
if module not in modules_readme:
err = "Module {} in README but not in /modules".format(module)
elif (
"".join(readme[module]).strip()
!= "".join(modules_readme[module]).strip()
):
err = "Module {} docstring does not match README".format(module)
if err:
if not warned:
print_stderr("Documentation does not match!\n")
warned = True
print_stderr(err)
for module in modules_readme:
if mods and module not in mods:
continue
if module not in readme:
print_stderr("Module {} in /modules but not in README".format(module))
if show_diff:
print_stderr(
"\n".join(
difflib.unified_diff(
create_readme(readme).split("\n"),
create_readme(modules_readme).split("\n"),
)
)
)
else:
if warned:
print_stderr("\nUse `py3-cmd docstring --diff` to view diff.") | python | def check_docstrings(show_diff=False, config=None, mods=None):
readme = parse_readme()
modules_readme = core_module_docstrings(config=config)
warned = False
if create_readme(readme) != create_readme(modules_readme):
for module in sorted(readme):
if mods and module not in mods:
continue
err = None
if module not in modules_readme:
err = "Module {} in README but not in /modules".format(module)
elif (
"".join(readme[module]).strip()
!= "".join(modules_readme[module]).strip()
):
err = "Module {} docstring does not match README".format(module)
if err:
if not warned:
print_stderr("Documentation does not match!\n")
warned = True
print_stderr(err)
for module in modules_readme:
if mods and module not in mods:
continue
if module not in readme:
print_stderr("Module {} in /modules but not in README".format(module))
if show_diff:
print_stderr(
"\n".join(
difflib.unified_diff(
create_readme(readme).split("\n"),
create_readme(modules_readme).split("\n"),
)
)
)
else:
if warned:
print_stderr("\nUse `py3-cmd docstring --diff` to view diff.") | [
"def",
"check_docstrings",
"(",
"show_diff",
"=",
"False",
",",
"config",
"=",
"None",
",",
"mods",
"=",
"None",
")",
":",
"readme",
"=",
"parse_readme",
"(",
")",
"modules_readme",
"=",
"core_module_docstrings",
"(",
"config",
"=",
"config",
")",
"warned",
... | Check docstrings in module match the README.md | [
"Check",
"docstrings",
"in",
"module",
"match",
"the",
"README",
".",
"md"
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L338-L380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.