_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q35000
Py3statusWrapper.log
train
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
{ "resource": "" }
q35001
Py3statusWrapper.create_output_modules
train
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
{ "resource": "" }
q35002
Py3statusWrapper.create_mappings
train
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
{ "resource": "" }
q35003
Py3statusWrapper.process_module_output
train
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
{ "resource": "" }
q35004
Py3statusWrapper.run
train
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
{ "resource": "" }
q35005
Gradients.hex_2_rgb
train
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
{ "resource": "" }
q35006
Gradients.rgb_2_hex
train
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
{ "resource": "" }
q35007
Gradients.hsv_2_hex
train
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
{ "resource": "" }
q35008
Gradients.make_threshold_gradient
train
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
{ "resource": "" }
q35009
Events.get_module_text
train
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
{ "resource": "" }
q35010
Events.wm_msg
train
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
{ "resource": "" }
q35011
Events.dispatch_event
train
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
{ "resource": "" }
q35012
Events.run
train
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
{ "resource": "" }
q35013
Py3status._start_handler_thread
train
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
{ "resource": "" }
q35014
Py3status._start_loop
train
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
{ "resource": "" }
q35015
Py3status._vpn_signal_handler
train
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
{ "resource": "" }
q35016
Py3status._get_vpn_status
train
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
{ "resource": "" }
q35017
Py3status.vpn_status
train
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
{ "resource": "" }
q35018
Composite.append
train
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
{ "resource": "" }
q35019
Composite.simplify
train
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
{ "resource": "" }
q35020
Composite.composite_join
train
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
{ "resource": "" }
q35021
Py3status._init_dbus
train
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
{ "resource": "" }
q35022
Py3status._get_device_id
train
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
{ "resource": "" }
q35023
Py3status._get_device
train
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
{ "resource": "" }
q35024
Py3status._get_battery
train
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
{ "resource": "" }
q35025
Py3status._get_battery_status
train
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
{ "resource": "" }
q35026
Py3status._get_notifications_status
train
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
{ "resource": "" }
q35027
Py3status._get_text
train
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
{ "resource": "" }
q35028
Py3status.kdeconnector
train
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
{ "resource": "" }
q35029
Py3status.dpms
train
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
{ "resource": "" }
q35030
Py3status.on_click
train
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
{ "resource": "" }
q35031
Py3status._get_progress
train
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
{ "resource": "" }
q35032
Py3status._idle
train
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
{ "resource": "" }
q35033
Py3status._get_cputemp_with_lmsensors
train
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
{ "resource": "" }
q35034
Formatter.tokens
train
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
{ "resource": "" }
q35035
Formatter.get_color_names
train
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
{ "resource": "" }
q35036
Formatter.get_placeholders
train
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
{ "resource": "" }
q35037
Formatter.update_placeholders
train
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
{ "resource": "" }
q35038
Formatter.update_placeholder_formats
train
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
{ "resource": "" }
q35039
Formatter.build_block
train
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
{ "resource": "" }
q35040
Formatter.format
train
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
{ "resource": "" }
q35041
Placeholder.get
train
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
{ "resource": "" }
q35042
Condition._check_valid_condition
train
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
{ "resource": "" }
q35043
Condition._check_valid_basic
train
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
{ "resource": "" }
q35044
BlockConfig.update_commands
train
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
{ "resource": "" }
q35045
BlockConfig._set_int
train
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
{ "resource": "" }
q35046
Block.new_block
train
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
{ "resource": "" }
q35047
Block.switch
train
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
{ "resource": "" }
q35048
Block.check_valid
train
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
{ "resource": "" }
q35049
Py3status._content_function
train
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
{ "resource": "" }
q35050
Py3status._urgent_function
train
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
{ "resource": "" }
q35051
get_backends
train
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
{ "resource": "" }
q35052
ClickTimer.trigger
train
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
{ "resource": "" }
q35053
ClickTimer.event
train
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
{ "resource": "" }
q35054
Py3status._get_stat
train
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
{ "resource": "" }
q35055
Py3status._format_value
train
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
{ "resource": "" }
q35056
Py3status._persist
train
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
{ "resource": "" }
q35057
markdown_2_rst
train
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
{ "resource": "" }
q35058
file_sort
train
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
{ "resource": "" }
q35059
screenshots
train
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
{ "resource": "" }
q35060
create_module_docs
train
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
{ "resource": "" }
q35061
get_variable_docstrings
train
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
{ "resource": "" }
q35062
get_py3_info
train
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
{ "resource": "" }
q35063
auto_undent
train
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
{ "resource": "" }
q35064
create_py3_docs
train
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
{ "resource": "" }
q35065
Py3status._time_up
train
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
{ "resource": "" }
q35066
HttpResponse.status_code
train
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
{ "resource": "" }
q35067
HttpResponse.text
train
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
{ "resource": "" }
q35068
HttpResponse.json
train
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
{ "resource": "" }
q35069
HttpResponse.headers
train
def headers(self): """ Get the headers from the response. """ try: return self._headers except AttributeError: self._headers = self._response.headers return self._headers
python
{ "resource": "" }
q35070
modules_directory
train
def modules_directory(): """ Get the core modules directory. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules")
python
{ "resource": "" }
q35071
create_readme
train
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
{ "resource": "" }
q35072
_reformat_docstring
train
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
{ "resource": "" }
q35073
_to_docstring
train
def _to_docstring(doc): """ format from Markdown to docstring """ def format_fn(line, status): """ format function """ # swap &lt; &gt; 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
{ "resource": "" }
q35074
_from_docstring_md
train
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 "&lt;" if found == ">": return "&gt;" if found == "&": return "&amp;" 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
{ "resource": "" }
q35075
_from_docstring_rst
train
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
{ "resource": "" }
q35076
check_docstrings
train
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
{ "resource": "" }
q35077
update_readme_for_modules
train
def update_readme_for_modules(modules): """ Update README.md updating the sections for the module names listed. """ readme = parse_readme() module_docstrings = core_module_docstrings() if modules == ["__all__"]: modules = core_module_docstrings().keys() for module in modules: if module in module_docstrings: print_stderr("Updating README.md for module {}".format(module)) readme[module] = module_docstrings[module] else: print_stderr("Module {} not in core modules".format(module)) # write the file readme_file = os.path.join(modules_directory(), "README.md") with open(readme_file, "w") as f: f.write(create_readme(readme))
python
{ "resource": "" }
q35078
show_modules
train
def show_modules(config, modules_list): """ List modules available optionally with details. """ details = config["full"] core_mods = not config["user"] user_mods = not config["core"] modules = core_module_docstrings( include_core=core_mods, include_user=user_mods, config=config ) new_modules = [] if modules_list: from fnmatch import fnmatch for _filter in modules_list: for name in modules.keys(): if fnmatch(name, _filter): if name not in new_modules: new_modules.append(name) else: new_modules = modules.keys() for name in sorted(new_modules): module = _to_docstring(modules[name]) desc = module[0][:-1] if details: dash_len = len(name) + 4 print("#" * dash_len) print("# {} #".format(name)) print("#" * dash_len) for description in module: print(description[:-1]) else: print("%-22s %s" % (name, desc))
python
{ "resource": "" }
q35079
InjectionContextFactory.new
train
def new(self, injection_site_fn): """Creates a _InjectionContext. Args: injection_site_fn: the initial function being injected into Returns: a new empty _InjectionContext in the default scope """ return _InjectionContext( injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED, is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn)
python
{ "resource": "" }
q35080
_InjectionContext.get_child
train
def get_child(self, injection_site_fn, binding): """Creates a child injection context. A "child" injection context is a context for a binding used to inject something into the current binding's provided value. Args: injection_site_fn: the child function being injected into binding: a Binding Returns: a new _InjectionContext """ child_scope_id = binding.scope_id new_binding_stack = self._binding_stack + [binding] if binding in self._binding_stack: raise errors.CyclicInjectionError(new_binding_stack) if not self._is_scope_usable_from_scope_fn( child_scope_id, self._scope_id): raise errors.BadDependencyScopeError( self.get_injection_site_desc(), self._scope_id, child_scope_id, binding.binding_key) return _InjectionContext( injection_site_fn, new_binding_stack, child_scope_id, self._is_scope_usable_from_scope_fn)
python
{ "resource": "" }
q35081
ObjectGraph.provide
train
def provide(self, cls): """Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable """ support.verify_class_type(cls, 'cls') if not self._is_injectable_fn(cls): provide_loc = locations.get_back_frame_loc() raise errors.NonExplicitlyBoundClassError(provide_loc, cls) try: return self._obj_provider.provide_class( cls, self._injection_context_factory.new(cls.__init__), direct_init_pargs=[], direct_init_kwargs={}) except errors.Error as e: if self._use_short_stack_traces: raise e else: raise
python
{ "resource": "" }
q35082
_get_type_name
train
def _get_type_name(target_thing): """ Functions, bound methods and unbound methods change significantly in Python 3. For instance: class SomeObject(object): def method(): pass In Python 2: - Unbound method inspect.ismethod(SomeObject.method) returns True - Unbound inspect.isfunction(SomeObject.method) returns False - Unbound hasattr(SomeObject.method, 'im_class') returns True - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns True In Python 3: - Unbound method inspect.ismethod(SomeObject.method) returns False - Unbound inspect.isfunction(SomeObject.method) returns True - Unbound hasattr(SomeObject.method, 'im_class') returns False - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns False This method tries to consolidate the approach for retrieving the enclosing type of a bound/unbound method and functions. """ thing = target_thing if hasattr(thing, 'im_class'): # only works in Python 2 return thing.im_class.__name__ if inspect.ismethod(thing): for cls in inspect.getmro(thing.__self__.__class__): if cls.__dict__.get(thing.__name__) is thing: return cls.__name__ thing = thing.__func__ if inspect.isfunction(thing) and hasattr(thing, '__qualname__'): qualifier = thing.__qualname__ if LOCALS_TOKEN in qualifier: return _get_local_type_name(thing) return _get_external_type_name(thing) return inspect.getmodule(target_thing).__name__
python
{ "resource": "" }
q35083
get_unbound_arg_names
train
def get_unbound_arg_names(arg_names, arg_binding_keys): """Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of arg names that is a (possibly empty, possibly non-proper) subset of arg_names """ bound_arg_names = [abk._arg_name for abk in arg_binding_keys] return [arg_name for arg_name in arg_names if arg_name not in bound_arg_names]
python
{ "resource": "" }
q35084
new
train
def new(arg_name, annotated_with=None): """Creates an ArgBindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated arg binding key Returns: a new ArgBindingKey """ if arg_name.startswith(_PROVIDE_PREFIX): binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:] provider_indirection = provider_indirections.INDIRECTION else: binding_key_name = arg_name provider_indirection = provider_indirections.NO_INDIRECTION binding_key = binding_keys.new(binding_key_name, annotated_with) return ArgBindingKey(arg_name, binding_key, provider_indirection)
python
{ "resource": "" }
q35085
get_overall_binding_key_to_binding_maps
train
def get_overall_binding_key_to_binding_maps(bindings_lists): """bindings_lists from lowest to highest priority. Last item in bindings_lists is assumed explicit. """ binding_key_to_binding = {} collided_binding_key_to_bindings = {} for index, bindings in enumerate(bindings_lists): is_final_index = (index == (len(bindings_lists) - 1)) handle_binding_collision_fn = { True: _handle_explicit_binding_collision, False: _handle_implicit_binding_collision}[is_final_index] this_binding_key_to_binding, this_collided_binding_key_to_bindings = ( _get_binding_key_to_binding_maps( bindings, handle_binding_collision_fn)) for good_binding_key in this_binding_key_to_binding: collided_binding_key_to_bindings.pop(good_binding_key, None) binding_key_to_binding.update(this_binding_key_to_binding) collided_binding_key_to_bindings.update( this_collided_binding_key_to_bindings) return binding_key_to_binding, collided_binding_key_to_bindings
python
{ "resource": "" }
q35086
default_get_arg_names_from_class_name
train
def default_get_arg_names_from_class_name(class_name): """Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding arg names, e.g., ["foo_bar"] """ parts = [] rest = class_name if rest.startswith('_'): rest = rest[1:] while True: m = re.match(r'([A-Z][a-z]+)(.*)', rest) if m is None: break parts.append(m.group(1)) rest = m.group(2) if not parts: return [] return ['_'.join(part.lower() for part in parts)]
python
{ "resource": "" }
q35087
annotate_arg
train
def annotate_arg(arg_name, with_annotation): """Adds an annotation to an injected arg. arg_name must be one of the named args of the decorated function, i.e., @annotate_arg('foo', with_annotation='something') def a_function(foo): # ... is OK, but @annotate_arg('foo', with_annotation='something') def a_function(bar, **kwargs): # ... is not. The same arg (on the same function) may not be annotated twice. Args: arg_name: the name of the arg to annotate on the decorated function with_annotation: an annotation object Returns: a function that will decorate functions passed to it """ arg_binding_key = arg_binding_keys.new(arg_name, with_annotation) return _get_pinject_wrapper(locations.get_back_frame_loc(), arg_binding_key=arg_binding_key)
python
{ "resource": "" }
q35088
inject
train
def inject(arg_names=None, all_except=None): """Marks an initializer explicitly as injectable. An initializer marked with @inject will be usable even when setting only_use_explicit_bindings=True when calling new_object_graph(). This decorator can be used on an initializer or provider method to separate the injectable args from the args that will be passed directly. If arg_names is specified, then it must be a sequence, and only those args are injected (and the rest must be passed directly). If all_except is specified, then it must be a sequence, and only those args are passed directly (and the rest must be specified). If neither arg_names nor all_except are specified, then all args are injected (and none may be passed directly). arg_names or all_except, when specified, must not be empty and must contain a (possibly empty, possibly non-proper) subset of the named args of the decorated function. all_except may not be all args of the decorated function (because then why call that provider method or initialzer via Pinject?). At most one of arg_names and all_except may be specified. A function may be decorated by @inject at most once. """ back_frame_loc = locations.get_back_frame_loc() if arg_names is not None and all_except is not None: raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc) for arg, arg_value in [('arg_names', arg_names), ('all_except', all_except)]: if arg_value is not None: if not arg_value: raise errors.EmptySequenceArgError(back_frame_loc, arg) if (not support.is_sequence(arg_value) or support.is_string(arg_value)): raise errors.WrongArgTypeError( arg, 'sequence (of arg names)', type(arg_value).__name__) if arg_names is None and all_except is None: all_except = [] return _get_pinject_wrapper( back_frame_loc, inject_arg_names=arg_names, inject_all_except_arg_names=all_except)
python
{ "resource": "" }
q35089
provides
train
def provides(arg_name=None, annotated_with=None, in_scope=None): """Modifies the binding of a provider method. If arg_name is specified, then the created binding is for that arg name instead of the one gotten from the provider method name (e.g., 'foo' from 'provide_foo'). If annotated_with is specified, then the created binding includes that annotation object. If in_scope is specified, then the created binding is in the scope with that scope ID. At least one of the args must be specified. A provider method may not be decorated with @provides() twice. Args: arg_name: the name of the arg to annotate on the decorated function annotated_with: an annotation object in_scope: a scope ID Returns: a function that will decorate functions passed to it """ if arg_name is None and annotated_with is None and in_scope is None: raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc()) return _get_pinject_wrapper(locations.get_back_frame_loc(), provider_arg_name=arg_name, provider_annotated_with=annotated_with, provider_in_scope_id=in_scope)
python
{ "resource": "" }
q35090
get_provider_fn_decorations
train
def get_provider_fn_decorations(provider_fn, default_arg_names): """Retrieves the provider method-relevant info set by decorators. If any info wasn't set by decorators, then defaults are returned. Args: provider_fn: a (possibly decorated) provider function default_arg_names: the (possibly empty) arg names to use if none were specified via @provides() Returns: a sequence of ProviderDecoration """ if hasattr(provider_fn, _IS_WRAPPER_ATTR): provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR) if provider_decorations: expanded_provider_decorations = [] for provider_decoration in provider_decorations: # TODO(kurts): seems like default scope should be done at # ProviderDecoration instantiation time. if provider_decoration.in_scope_id is None: provider_decoration.in_scope_id = scoping.DEFAULT_SCOPE if provider_decoration.arg_name is not None: expanded_provider_decorations.append(provider_decoration) else: expanded_provider_decorations.extend( [ProviderDecoration(default_arg_name, provider_decoration.annotated_with, provider_decoration.in_scope_id) for default_arg_name in default_arg_names]) return expanded_provider_decorations return [ProviderDecoration(default_arg_name, annotated_with=None, in_scope_id=scoping.DEFAULT_SCOPE) for default_arg_name in default_arg_names]
python
{ "resource": "" }
q35091
new
train
def new(arg_name, annotated_with=None): """Creates a BindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated binding key Returns: a new BindingKey """ if annotated_with is not None: annotation = annotations.Annotation(annotated_with) else: annotation = annotations.NO_ANNOTATION return BindingKey(arg_name, annotation)
python
{ "resource": "" }
q35092
__setkey
train
def __setkey(key): """ Set up the key schedule from the encryption key. """ global C, D, KS, E shifts = (1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1) # First, generate C and D by permuting the key. The lower order bit of each # 8-bit char is not used, so C and D are only 28 bits apiece. for i in range(28): C[i] = key[PC1_C[i] - 1] D[i] = key[PC1_D[i] - 1] for i in range(16): # rotate for k in range(shifts[i]): temp = C[0] for j in range(27): C[j] = C[j + 1] C[27] = temp temp = D[0] for j in range(27): D[j] = D[j + 1] D[27] = temp # get Ki. Note C and D are concatenated for j in range(24): KS[i][j] = C[PC2_C[j] - 1] KS[i][j + 24] = D[PC2_D[j] - 28 - 1] # load E with the initial E bit selections for i in range(48): E[i] = e2[i]
python
{ "resource": "" }
q35093
Cursor.nextset
train
def nextset(self): """ Skip to the next available result set, discarding any remaining rows from the current result set. If there are no more result sets, this method returns False. Otherwise, it returns a True and subsequent calls to the fetch*() methods will return rows from the next result set. """ # skip any data for this set if exists self.flush_to_end_of_result() if self._message is None: return False elif isinstance(self._message, END_OF_RESULT_RESPONSES): # there might be another set, read next message to find out self._message = self.connection.read_message() if isinstance(self._message, messages.RowDescription): self.description = [Column(fd, self.unicode_error) for fd in self._message.fields] self._message = self.connection.read_message() return True elif isinstance(self._message, messages.BindComplete): self._message = self.connection.read_message() return True elif isinstance(self._message, messages.ReadyForQuery): return False elif isinstance(self._message, END_OF_RESULT_RESPONSES): # result of a DDL/transaction return True elif isinstance(self._message, messages.ErrorResponse): raise errors.QueryError.from_error_response(self._message, self.operation) else: raise errors.MessageError( 'Unexpected nextset() state after END_OF_RESULT_RESPONSES: {0}'.format(self._message)) elif isinstance(self._message, messages.ReadyForQuery): # no more sets left to be read return False else: raise errors.MessageError('Unexpected nextset() state: {0}'.format(self._message))
python
{ "resource": "" }
q35094
Cursor._prepare
train
def _prepare(self, query): """ Send the query to be prepared to the server. The server will parse the query and return some metadata. """ self._logger.info(u'Prepare a statement: [{}]'.format(query)) # Send Parse message to server # We don't need to tell the server the parameter types yet self.connection.write(messages.Parse(self.prepared_name, query, param_types=())) # Send Describe message to server self.connection.write(messages.Describe('prepared_statement', self.prepared_name)) self.connection.write(messages.Flush()) # Read expected message: ParseComplete self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler) # Read expected message: ParameterDescription self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler) self._param_metadata = self._message.parameters # Read expected message: RowDescription or NoData self._message = self.connection.read_expected_message( (messages.RowDescription, messages.NoData), self._error_handler) if isinstance(self._message, messages.NoData): self.description = None # response was NoData for a DDL/transaction PreparedStatement else: self.description = [Column(fd, self.unicode_error) for fd in self._message.fields] # Read expected message: CommandDescription self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler) if len(self._message.command_tag) == 0: msg = 'The statement being prepared is empty' self._logger.error(msg) self.connection.write(messages.Sync()) raise errors.EmptyQueryError(msg) self._logger.info('Finish preparing the statement')
python
{ "resource": "" }
q35095
Cursor._execute_prepared_statement
train
def _execute_prepared_statement(self, list_of_parameter_values): """ Send multiple statement parameter sets to the server using the extended query protocol. The server would bind and execute each set of parameter values. This function should not be called without first calling _prepare() to prepare a statement. """ portal_name = "" parameter_type_oids = [metadata['data_type_oid'] for metadata in self._param_metadata] parameter_count = len(self._param_metadata) try: if len(list_of_parameter_values) == 0: raise ValueError("Empty list/tuple, nothing to execute") for parameter_values in list_of_parameter_values: if parameter_values is None: parameter_values = () self._logger.info(u'Bind parameters: {}'.format(parameter_values)) if len(parameter_values) != parameter_count: msg = ("Invalid number of parameters for {}: {} given, {} expected" .format(parameter_values, len(parameter_values), parameter_count)) raise ValueError(msg) self.connection.write(messages.Bind(portal_name, self.prepared_name, parameter_values, parameter_type_oids)) self.connection.write(messages.Execute(portal_name, 0)) self.connection.write(messages.Sync()) except Exception as e: self._logger.error(str(e)) # the server will not send anything until we issue a sync self.connection.write(messages.Sync()) self._message = self.connection.read_message() raise self.connection.write(messages.Flush()) # Read expected message: BindComplete self.connection.read_expected_message(messages.BindComplete) self._message = self.connection.read_message() if isinstance(self._message, messages.ErrorResponse): raise errors.QueryError.from_error_response(self._message, self.prepared_sql)
python
{ "resource": "" }
q35096
Cursor._close_prepared_statement
train
def _close_prepared_statement(self): """ Close the prepared statement on the server. """ self.prepared_sql = None self.flush_to_query_ready() self.connection.write(messages.Close('prepared_statement', self.prepared_name)) self.connection.write(messages.Flush()) self._message = self.connection.read_expected_message(messages.CloseComplete) self.connection.write(messages.Sync())
python
{ "resource": "" }
q35097
VerticaLogging.ensure_dir_exists
train
def ensure_dir_exists(cls, filepath): """Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. """ directory = os.path.dirname(filepath) if directory != '' and not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
python
{ "resource": "" }
q35098
getTypeName
train
def getTypeName(data_type_oid, type_modifier): """Returns the base type name according to data_type_oid and type_modifier""" if data_type_oid == VerticaType.BOOL: return "Boolean" elif data_type_oid == VerticaType.INT8: return "Integer" elif data_type_oid == VerticaType.FLOAT8: return "Float" elif data_type_oid == VerticaType.CHAR: return "Char" elif data_type_oid in (VerticaType.VARCHAR, VerticaType.UNKNOWN): return "Varchar" elif data_type_oid == VerticaType.LONGVARCHAR: return "Long Varchar" elif data_type_oid == VerticaType.DATE: return "Date" elif data_type_oid == VerticaType.TIME: return "Time" elif data_type_oid == VerticaType.TIMETZ: return "TimeTz" elif data_type_oid == VerticaType.TIMESTAMP: return "Timestamp" elif data_type_oid == VerticaType.TIMESTAMPTZ: return "TimestampTz" elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM): return "Interval " + getIntervalRange(data_type_oid, type_modifier) elif data_type_oid == VerticaType.BINARY: return "Binary" elif data_type_oid == VerticaType.VARBINARY: return "Varbinary" elif data_type_oid == VerticaType.LONGVARBINARY: return "Long Varbinary" elif data_type_oid == VerticaType.NUMERIC: return "Numeric" elif data_type_oid == VerticaType.UUID: return "Uuid" else: return "Unknown"
python
{ "resource": "" }
q35099
getIntervalRange
train
def getIntervalRange(data_type_oid, type_modifier): """Extracts an interval's range from the bits set in its type_modifier""" if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM): raise ValueError("Invalid data type OID: {}".format(data_type_oid)) if type_modifier == -1: # assume the default if data_type_oid == VerticaType.INTERVALYM: return "Year to Month" elif data_type_oid == VerticaType.INTERVAL: return "Day to Second" if data_type_oid == VerticaType.INTERVALYM: # Year/Month intervals if (type_modifier & INTERVAL_MASK_YEAR2MONTH) == INTERVAL_MASK_YEAR2MONTH: return "Year to Month" elif (type_modifier & INTERVAL_MASK_YEAR) == INTERVAL_MASK_YEAR: return "Year" elif (type_modifier & INTERVAL_MASK_MONTH) == INTERVAL_MASK_MONTH: return "Month" else: return "Year to Month" if data_type_oid == VerticaType.INTERVAL: # Day/Time intervals if (type_modifier & INTERVAL_MASK_DAY2SEC) == INTERVAL_MASK_DAY2SEC: return "Day to Second" elif (type_modifier & INTERVAL_MASK_DAY2MIN) == INTERVAL_MASK_DAY2MIN: return "Day to Minute" elif (type_modifier & INTERVAL_MASK_DAY2HOUR) == INTERVAL_MASK_DAY2HOUR: return "Day to Hour" elif (type_modifier & INTERVAL_MASK_DAY) == INTERVAL_MASK_DAY: return "Day" elif (type_modifier & INTERVAL_MASK_HOUR2SEC) == INTERVAL_MASK_HOUR2SEC: return "Hour to Second" elif (type_modifier & INTERVAL_MASK_HOUR2MIN) == INTERVAL_MASK_HOUR2MIN: return "Hour to Minute" elif (type_modifier & INTERVAL_MASK_HOUR) == INTERVAL_MASK_HOUR: return "Hour" elif (type_modifier & INTERVAL_MASK_MIN2SEC) == INTERVAL_MASK_MIN2SEC: return "Minute to Second" elif (type_modifier & INTERVAL_MASK_MINUTE) == INTERVAL_MASK_MINUTE: return "Minute" elif (type_modifier & INTERVAL_MASK_SECOND) == INTERVAL_MASK_SECOND: return "Second" else: return "Day to Second"
python
{ "resource": "" }