I have a big problem and I need your help.
I have to encrypt my data with the xtea algorithm. I'm a completely beginner in python so I don't know any further.
I put my two hashed passwords and some data together. Because the my xtea algorithm don't want to have any strings in it I encoded it. (Encode 'utf-8' doesnt work here)
datas = macpassword_hashed_versch + tea_password + txt_neu
data_endi = str.encode(datas)
normales_password = normales_password.encode('utf-8')
data_en = xtea_algo(data_endi, normales_password)
Here is my xtea:
def xtea_algo(message, p):
key = p
text = message * 8
x = new(key, mode=MODE_CFB, IV="12345678")
c = x.encrypt(text)
return c
After this it is giving me this error:
Traceback (most recent call last):
Steganographie.py", line 77, in
data_en = xtea_algo(data_endi, normales_password)
Steganographie.py", line 23, in xtea_algo
c = x.encrypt(text)
lib\site-packages\pep272_encryption__init__.py", line 188, in
encrypt
encrypted_iv = self.encrypt_block(self.key, self._status)
lib\site-packages\xtea__init__.py", line 230, in encrypt_block
struct.unpack(self.endian + "2L", block),
TypeError: a bytes-like object is required, not 'str'
I controlled the types in my giving parameters and every object type is "bytes"
:( Do you guys have any ideas?
Related
Hello I used encryption algorithm called fernet to encrypt values in the database. I want to retrieve those values decrypted. The array which is being returned is a byte array, but I would like to decode it. It doesn't seem to be working. I am getting this error:
Traceback (most recent call last):
File "C:\Users\d\OneDrive\Bureaublad\Assignment8\CDMS.py", line 51, in <module>
get_clients()
File "C:\Users\d\OneDrive\Bureaublad\Assignment8\CDMS.py", line 41, in get_clients
print(arr[i].decode())
TypeError: list indices must be integers or slices, not bytes
This is the array which im trying to decode:
[(b'gAAAAABg5EBDnm6LZdHNzzjnDlFcA80SeS1s-wXhKx_opwOm0vSNsfcxheZC4abQ-qvifmxxbCT8gGy2O1dz-76gx3_ALVmeZQ==', b'gAAAAABg5EBD1k2kpmYaAI0PNfjHondg5mB9RwxoIxVqAkfZcAeYrK-H4oqyYjV9WcHFN0CF7Xf0dN2rAXKrkAq-myyfNUplSg==', b'gAAAAABg5EBDJrUQazdiAdf4yejxIwzZHSln-hAcYLkh27-7HO5gE8XjHZjUz3Y2-lHo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TEX-kGwfw-JJmBOh_7RJnTa-23HWJQtfChSWWuXzsxULJ5vI289c0BVIqrw==', 'gAAAAABg5EVhy8aowZUiuX6M2IPW35XFZNBueXDd_JFal39ViFmg6avpbkvs0mhVzpqVvXjNcMmr3QbNeXf3daLCDa7_KdCmmg==')]
This is the code where im trying to decode it:
def get_clients():
arr = []
retrieved_vals = ""
c.execute("SELECT * FROM client")
arr = c.fetchall()
i = 0
for i in arr[i]:
print(arr[i].decode())
What can i do?
Arr is a tuple within a list with encoded strings.
so your for needs to look like this: for i in arr[0]: print(i.decode())
I'm using QGIS 3.6 with the built in Python text editor. I have found a snippet of code that I'm trying to make work, and I've modified it to the best of my abilities to fit my specific needs. I have a point layer called "Regulators" and it contains a field called "Town". The idea of the code is that when I select a single feature on the "Regulators" layer, the code will look at the "Town" field, and select all other features that match that field's value. I select a feature, run this code:
layer = iface.activeLayer()
field_name = 'Town'
values = []
for feat in layer.selectedFeatures():
tmp_value = feat[field_name]
if tmp_value not in values:
values.append(str(tmp_value))
strings = []
for val in values:
if val != values[-1]:
string = field_name + ' = ' + val + ' or '
strings.append(string)
else:
last_string = field_name + ' = ' + val
strings.append(last_string)
query = ''.join(strings)
request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
request.setSubsetOfAttributes([]).setFilterExpression(query)
selection = layer.getFeatures(request)
layer.setSelectedFeatures([k.id() for k in selection])
and I get this error:
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.6\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 24, in <module>
AttributeError: 'QgsVectorLayer' object has no attribute 'setSelectedFeatures'
I'm very much new to python, and see nothing wrong with line 1 or 5. I have found some other codes that do what I'm attempting here, but they also return errors, so I'm wondering if there is some method or function that has changed since this code was posted. The integrated compiler with QGIS is also much different than I am used to.
EDIT: I've updated the code and the error message based on feedback I've received on the post so far. I assume that QgsVectorLayer is the generic term for a vector layer being referenced, in this case the "Regulators" layer. but I don't understand why it's trying to use the setSelectedFeatures method as an attribute.
I am getting more and more confused in python.
when i try on one row, it works, but when i work on the whole rows of one column, it shows error.
i want to use the function convert_hex_to_int for each row in the column,
but it shows me the error
Traceback (most recent call last):
File
"C:/Users/ranic/.PyCharmCE2018.3/config/scratches/scratch_2.py", line
59, in
result_print = (convert_hex_to_int(hex_int, 4))
File "C:/Users/r/.PyCharmCE2018.3/config/scratches/scratch_2.py", line 32,
in conver
t_hex_to_int
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)] TypeError: 'str' object cannot be
interpreted as an integer
here is my code:
cnxn = pyodbc.connect(conn_str)
cnxn.add_output_converter(pyodbc.SQL_VARBINARY, hexToString)
cursor = cnxn.cursor()
def convert_hex_to_int(n:int, interval:int):
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
return [int(hex(unpack('<H', pack('>H', int(i, 16)))[0]), 16) for i in splitted]
try:
cursor.execute(query)
row=cursor.fetchval()
row_list=[]
while row is not None:
row=cursor.fetchval()
hex_int = int(row, 16)
result_print = (convert_hex_to_int(hex_int, 4))
result_float = [float("{0:.2f}".format((i) * 10 ** -2)) for i in result_print]
row_list.append(result_float)
print(row_list)
Please leave any comment if I miss something, thanks in advance.
When I debugged it, it shows something like this:
Debugged screen
*sorry I had to attach the image as it is the debugged screen and i cant copy the code, and it had to be in link because i am a new user
**edit: i think it has to do with the use of .fetchval twice, but im not too sure
If the line
[hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
Results in
TypeError: 'str' object cannot be interpreted as an integer
Then n must not be an integer.
Observe, if n is '0x94069206':
>>> hex('0x94069206')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
As the code is taking slices of n it looks as if n needs to be a string, so the line should be:
splitted = [n[2:][i:i + interval] for i in range(0, len(n[2:]), interval)]
It follows that the function signature should be
def convert_hex_to_int(n:str, interval:int)
On the other hand, if n is an int then the next line needs to be reworked.
so i was coding some problems in python in this page
https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/train/python
the code work fine on my computer but when i update it, i came across this bug.
note that its python 3.4.3
def flap_display(lines, rotors):
baseString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ?!##&()|<>.:=-+*/0123456789"
res = []
baseLen = len(baseString)
lineLen = len(lines)
sLen = len(rotors)
carrier = 0
for item in range(0 , sLen):
if (item < lineLen):
carrier =carrier + rotors[item]
tmp = baseString.index(lines[item])
tmp = tmp + carrier
tmp = tmp % baseLen
res.append( baseString[tmp] )
resS = ''.join(res)
return resS
print (flap_display("CAT", [1,13,27]))
all the website gave me is this:
Traceback:
in
in flap_display
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Now i want to know if my code is incorrect or its just the site being buggy.
Problem is solved! Thank to mr.kuro
sum requires an iterable: a sequence of items, such as a list. You gave it a single integer. If you want to add up all the integers in rotors, you can do that outside of a loop, with
carrier = sum(rotors)
More to your code, just add up the items you wanted:
carrier = sum(rotors[:lineLen])
This adds the first lineLen elements of rotors, allowing you to get rid of that pesky if statement.
Can you adapt the rest of the loop logic to take proper advantage of that?
Thr traceback should be like below:
Traceback (most recent call last):
File "test1.py", line 17, in
print (flap_display("CAT", [1,13,27]))
File "test1.py", line 10, in flap_display
carrier =carrier + sum(rotors[item])
TypeError: 'int' object is not iterable
And, as the traceback says, in line
carrier =carrier + sum(rotors[item])
rotors[item] will apparently be an int, so you can't call sum on it, hence the Error.
Replace the above line with:
carrier = carrier + rotors[item]
Or, just skip the loop, and do:
carrier = sum(rotors)
It should be okay now.
I am trying to replicate a section of code from the graph-tool cookbook to find the marginal probablity of the number of groups in a graph when using hierarchical partitioning. I however get an error telling me that 'NestedBlockState' object has no attribute 'get_nonempty_B' so presumably I have made a mistake somewhere. Does anybody know where I went wrong?
import graph_tool.all as gt
import cPickle as pickle
g = gt.load_graph('graph_no_multi_reac_type.gt')
gt.remove_parallel_edges(g)
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
state = state.copy(sampling=True)
with open('state_mcmc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
print 'equilibrating Markov chain'
gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
h = np.zeros(g.num_vertices() + 1)
def collect_num_groups(s):
B = s.get_nonempty_B()
h[B] += 1
print 'colleting marginals'
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
callback=collect_num_groups)
with open('state_ncnc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
with open('hist.pkl','wb') as h_pkl:
pickle.dump(h,h_pkl,-1)
The error I get looks as follows:
Traceback (most recent call last):
File "num_groups_marg_prob.py", line 42, in <module>
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
File "/usr/lib/python2.7/dist-packages/graph_tool/inference/mcmc.py", line 172, in mcmc_equilibrate
extra = callback(state)
File "num_groups_marg_prob.py", line 35, in collect_num_groups
def collect_num_groups(s):
AttributeError: 'NestedBlockState' object has no attribute 'get_nonempty_B'
Quoting from an answer from the graph-tool mailing list:
"The error message is clear. This attribute belongs to BlockState, not
NestedBlockState. What you wish to do is:
s.levels[0].get_nonempty_B()
"
http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/self-state-couple-state-state-state-entropy-args-Python-argument-types-did-not-match-C-signature-td4026975.html