Python pylibmc syntax / how can I use mc.set in a loop - python-3.x

I want to set keys in a for loop, and read them back in another script also using a loop.
To test memcache is working I made these simple scripts:
a.py
import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
behaviors={"tcp_nodelay": True,
"ketama": True})
mc["key_1"] = "Value 1"
mc["key_2"] = "Value 2"
mc["key_3"] = "Value 3"
mc["key_4"] = "Value 4"
b.py:
import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
behaviors={"tcp_nodelay": True,
"ketama": True})
print("%s" % (mc["key_1"]))
print("%s" % (mc["key_2"]))
print("%s" % (mc["key_3"]))
print("%s" % (mc["key_4"]))
This working fine. But I have no clue how to rewrite memcache line to be used in a for loop.
I tried several things, but nothing I tried did work.
What I want is something like this:
for index in range (0,4):
mc["key_(index)"] = "Value (index)"

you can use f-strings:
for index in range (0,4):
key = f"key_{index}"
mc[key] = f"{mc[key]} {index}" # or "Value {index}"

Related

Can't get the text from LineEdit to pass to a function

Context:
I click on a button -> a WindowDialogue appears -> there are 2 LineEdit Nodes and a button
Supposed procedure:
I fill these LineEdits, press the button, and the function tied to the button receives the texts from the LineEdits (and creates a dictionary key-value pair).
Problem:
The texts from the LineEdits do not pass down to the function (through connect()).
I tried passing the text directly with LineEdit.text. I tried writing it in a different variable and passing the variable. The debug shows the function is getting executed (no problem with that), but the strings passed from the LineEdits are always empty. Somehow, it worked for some time when I explicitly pressed ENTER after filling the LineEdits. But after I tried to fix the aforementioned problem, it stopped working altogether.
P.S. Everything I mentioned is created dynamically through the code, if that matters.
Code:
#Declaring the variables
var temp_text_key = ""
var temp_text_value = ""
#Function to show up a dialogue window with LineEdits and Confirm button
func _on_add_new_property(dict: Dictionary):
temporal_window_dialogue = WindowDialog.new()
temporal_window_dialogue.rect_min_size = Vector2(410,90)
temporal_window_dialogue.resizable = true
temporal_window_dialogue.popup_exclusive = true
temporal_window_dialogue.window_title = "Adding new property to %s" % get_dict_name_by_id(professions, dict["id"])
var le_key = LineEdit.new()
le_key.placeholder_text = "Name of the property"
le_key.hint_tooltip = "Name of the property"
le_key.connect("text_changed", self, "_on_add_new_prop_text_entered", ["key"])
var le_value = LineEdit.new()
le_value.expand_to_text_length = true
le_value.placeholder_text = "Value of the property"
le_value.set("custom_constants/minimum_spaces", 36)
le_value.hint_tooltip = "Value of the property"
le_value.connect("text_changed", self, "_on_add_new_prop_text_entered", ["value"])
var lab = Label.new()
lab.text = "Should the Value become a Dictionary?"
var check_bt = CheckBox.new()
var vbox = VBoxContainer.new()
var grid_container = GridContainer.new()
grid_container.columns = 2
var accept_bt = Button.new()
accept_bt.text = "Confirm"
temporal_window_dialogue.add_child(vbox)
vbox.add_child(grid_container)
grid_container.add_child(le_key)
grid_container.add_child(le_value)
grid_container.add_child(lab)
grid_container.add_child(check_bt)
vbox.add_child(accept_bt)
grid_container.set("custom_constants/vseparation", 5)
grid_container.set("custom_constants/hseparation", 5)
check_bt.connect("pressed", self, "_on_check_dict_pressed")
popup_window.add_child(temporal_window_dialogue)
temporal_window_dialogue.connect("popup_hide", self, "_on_close_specific_codegenerated_popup", [temporal_window_dialogue])
temporal_window_dialogue.popup_centered()
accept_bt.connect("pressed", self, "_on_add_new_property_confirmation", [dict, temp_text_key, temp_text_value])
#Function to create a new key/value pair in a dictionary
func _on_add_new_property_confirmation(dict: Dictionary, prop_name: String, prop_value: String):
if prop_name == "" or prop_value == "":
send_message_to_console("Neither of the two can be empty", 3)
return
if add_dictionary_flag:
dict[prop_name] = {
prop_value: {
"id": get_free_local_id_for_dict(dict)
}
}
elif !add_dictionary_flag:
if keywords_for_dictionaries.has(prop_name):
send_message_to_console("Only Dictionary items can become %s" % prop_name)
dict[prop_name] = prop_value
temp_text_key = ""
temp_text_value = ""
#Optional function to write the text from LineEdits to the variables
func _on_add_new_prop_text_entered(new_text, key_or_value):
if key_or_value == "key":
temp_text_key = new_text
elif key_or_value == "value":
temp_text_value = new_text
You mentioned using 'LineEdit.text', but have you tried the following?
var text = LineEdit.get_text()
If this doesn't help, please update your original post to include code examples.

Prevent loss of data in recursive function

I have a recursive function to which i pass certain args. The function is as below:
def insert_category(a, b, c, d, content_to_write):
response_content = []
if content_to_write:
response_content.extend(content_to_write)
for x in b:
write_back_content = {}
write_back_content = {"category_path": "a", "name": "b" ,"status" : "Successful" ,"err_desc" : "-" }
form_category = {"pid": "0", "name": "Library" }
category_exists = db.collection.find_one({"_id":a})
if some_cond:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Duplicate Category"
response_content.append(write_back_content)
continue
elif some_other_cond:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Invalid pid i.e category path"
response_content.append(write_back_content)
continue
insert_status = db.collections.insert(form_category)
if not insert_status:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Unable to create category"
response_content.append(write_back_content)
continue
else:
c[map_some_id] = insert_status
response_content.append(write_back_content)
insert_category(a, b, c, d ,content_to_write=response_content)
logger.info("RESPONSE CONTENT {}".format(response_content))
return response_content
The current problem I am facing here is that the log line "RESPONSE CONTENT" somehow loses the last attached info, ex: if there are 4 insertions in response_content, when i call this function, the return response has only 3 insertions. The last one goes missing. Also, weirdly, the log prints 4 times instead of just once since it is outside the for loop.Any idea where I am going wrong?
Okay so after quite a long time of debugging, i realised the mistake was quite silly. The function returns some data. So i was not storing the return content. So the solution that worked was response_content = insert_category(args).

Jupyter Notebook HOw can i assign a default value to datepicker and sort the time within the selected date?

I can try to set condition some data that is within the time picker in the datepicker. I got two problem
MY code was
def show_filter_date(start ,end):
print(start_dater.value)
print(end_dater.value)
time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start))&(id_one['_source.timestampstring']<pd.to_datetime(end))])
#print(time_df.head(20))
# time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start_dater.value))&(id_one['_source.timestampstring']<pd.to_datetime(end_dater.value))])
time_df.head(20)
layout = widgets.Layout(width='auto', height='40px')
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False)
end_dater = widgets.DatePicker(description='Pick an End Date',disabled=False )
#display(widgets.HBox((start_dater, end_dater)))
#display(start_dater)
#display(end_dater)
#id_one.head()
#combine_date = widgets.HBox((start = start_dater, end = end_dater))
#country_selector = widgets.Dropdown(
interact(show_filter_date,start = start_dater , end = end_dater)
everytime i run the code it show Error
"Invalid comparison between dtype=datetime64[ns] and NoneType"
I have tried to assign default value like
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False, year = 2020 ,month = 12, day = 1)
but it won't change to 2020/12/01
So, how can I get a value other than null?
I fail in interact for the datepicker in which
A) print(time_df.head(20))
B)
time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start_dater.value))&(id_one['_source.timestampstring']<pd.to_datetime(end_dater.value))])
time_df.head(20)
Only (A) can be "interact" or "refresh" when I pick a day but not (B)
And for Question 2, when I put time_df.head(20) in the NEXT CELL it does work tho.......
But what i want is to show the result like in time_df
I would appreciate if any help
the id_one is something like
Index _source.hdrrId _source.hdrfId _source.hdrType \
199 1300 1234 1
_source.timestampstring
199 2020-11-06 09:36:04.800
Thanks!
Jeff
I replicated your first error with
id_one = pd.DataFrame(pd.date_range('20200101','20200202'), columns = ['_source.timestampstring'])
This is because you did not set a default value for the DatePicker. The value is None by default hence the error. Here is the fix (value argument is the default value):
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False, value = datetime.date(2020,1,1))
end_dater = widgets.DatePicker(description='Pick an End Date',disabled=False, value = datetime.date(2020,2,1))
I cannot replicate your second error. My guess is you put print before the time_df = statement. You need to put the print after the line that calculates time_df

XGetWindowProperty and ctypes

Question
I'm trying to find NET_WM_NAME property for each of the window/client that X11 reports. Problem is that there's nothing returned - number of items is 0 and returned data results in empty string. I've looked at multiple code examples through out github and examples written in C and C++ , specifically Why is XGetWindowProperty returning null? as well as Xlib XGetWindowProperty Zero items returned , however I cannot find where is the problem with my code. Seemingly everything is fine, order of parameters passed to XGetWindowProperty function is in accordance with documentation, and the function returns success status, but results are empty. Where is the problem with my code ?
Code
Below is the code I am working with. The issue is xgetwindowproperty function. The other parts below it work fine, and are provided only for completeness.
#! /usr/bin/env python3
import sys
from ctypes import *
def xgetwindowproperty(display,w):
actual_type_return = c_ulong()
actual_format_return = c_int()
nitems_return = c_ulong()
bytes_after_return = c_ulong()
prop_return = POINTER(c_ubyte)()
wm_name = Xlib.XInternAtom(display,'_NET_WM_NAME',False)
utf8atom = Xlib.XInternAtom(display,'UTF8_STRING',False)
print('_NET_WM_NAME',wm_name, 'UTF8_STRING',utf8atom)
# AnyPropertyType = c_long(0)
status = Xlib.XGetWindowProperty(
display,
w,
wm_name,
0,
65536,
False,
utf8atom,
byref(actual_type_return),
byref(actual_format_return),
byref(nitems_return),
byref(bytes_after_return),
byref(prop_return)
)
print(nitems_return.value) # returns 0
# empty string as result
print( 'Prop', ''.join([ chr(c) for c in prop_return[:bytes_after_return.value] ]) )
Xlib.XFree(prop_return)
print('#'*10)
# -------
Xlib = CDLL("libX11.so.6")
display = Xlib.XOpenDisplay(None)
if display == 0:
sys.exit(2)
w = Xlib.XRootWindow(display, c_int(0))
root = c_ulong()
children = POINTER(c_ulong)()
parent = c_ulong()
nchildren = c_uint()
Xlib.XQueryTree(display, w, byref(root), byref(parent), byref(children), byref(nchildren))
for i in range(nchildren.value):
print("Child:",children[i])
xgetwindowproperty(display,children[i])

PyTest: fix repeating code and remove dependencies

I am writing tests for an API with pytest.
The tests are structured like that:
KEEP_BOX_IDS = ["123abc"]
#pytest.fixture(scope="module")
def s():
UID = os.environ.get("MYAPI_UID")
if UID is None:
raise KeyError("UID not set in environment variable")
PWD = os.environ.get("MYAPI_PWD")
if PWD is None:
raise KeyError("PWD not set in environment variable")
return myapi.Session(UID, PWD)
#pytest.mark.parametrize("name,description,count", [
("Normal Box", "Normal Box Description", 1),
("ÄäÖöÜüß!§", "ÄäÖöÜüß!§", 2),
("___--_?'*#", "\n\n1738\n\n", 3),
])
def test_create_boxes(s, name, description, count):
box_info_create = s.create_box(name, description)
assert box_info_create["name"] == name
assert box_info_create["desc"] == description
box_info = s.get_box_info(box_info_create["id"])
assert box_info["name"] == name
assert box_info["desc"] == description
assert len(s.get_box_list()) == count + len(KEEP_BOX_IDS)
def test_update_boxes(s):
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
new_name = b["name"] + "_updated"
new_desc = b["desc"] + "_updated"
s.update_box(b_id, new_name, new_desc)
box_info = s.get_box_info(b_id)
assert box_info["name"] == new_name
assert get_box_info["desc"] == new_desc
I use a fixture to set up the session (this will keep me connected to the API).
As you can see I am creating 3 boxes at the beginning.
All test that are following do some sort of operations on this 3 boxes. (Boxes are just spaces for folders and files)
For example: update_boxes, create_folders, rename_folders, upload_files, change_file names, etc..
I know it's not good, since all the tests are dependent from each other, but if I execute them in the right order the test is valid and thats enough.
The second issue, which borders me the most, is that all the following tests start with the same lines:
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
box_info = s.get_box_info(b_id)
I always need to call this for loop to get each boxs id and info.
I've tried to put it in a second fixture, but the problem is that then there will be two fixtures.
Is there a better way of doing this?
Thanks

Resources