Answer the question
In order to leave comments, you need to log in
MODx How to add an option/setting to the whole site?
How to add an option/setting that will be visible on the entire site from all templates?
For example, in the admin panel, somewhere in the settings, there will be a select with a list of options
. When you change it, the class will change, for example, body
Answer the question
In order to leave comments, you need to log in
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complex.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practically it beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one and preferably only one obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea let's do more of those!
I did something like this, only here this "text" is read from a file, and the decrypted text is written to another file.
def read_file():
f = open("Cipher", "r")
cesar_cipher = f.read()
f.close()
return cesar_cipher
def create_new_string(message):
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
key = 1
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
if num < 0:
else:
translated = translated + symbol
return translated
def create_strings(string):
array_of_strings = string.split()
array_of_words = []
string = ""
for word in array_of_strings:
if not '/' in word:
string += word + " "
else:
string += word
array_of_words.append(string)
string = ""
return array_of_words
#This function will shuffle the sequence of symbols to the beginning of a word
def cesar_cipher_decode(array_of_words):
decoded_strings = []
shift = -3
for item in array_of_words:
decoded_strings.append(decode_string(item, shift))
shift -= 1
return decoded_strings
def decode_string(string, shift):
separated_string = string.split()
string = ""
decoded_string = ""
for word in separated_string:
string = word[(len(word) + shift) % len(word):] + word[:(len(word) + shift) % len(word)]
decoded_string += string + " "
string = ""
return decoded_string
def write_information_to_the_file():
f = open("Cipher_decode", "w")
f.write(convert_to_string(cesar_cipher_decode(create_strings(create_new_string((read_file()))))))
f.close()
return 0
def convert_to_string(arr):
s = ""
for item in arr:
s += item + '\n'
return s
if __name__ == "__main__":
write_information_to_the_file()
Somehow like this. It's a two-step cipher. First, the Caesar cipher is applied, and then the shift within the word, which increases with each sentence.
LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def get_encrypted_word(message, key):
translated_step_1 = ''
translated_step_2 = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
translated_step_1 += LETTERS[num-key]
else:
translated_step_1 += symbol
replace_index = 3
for word in translated_step_1.split(' '):
new_word = ''
for index in range(len(word)):
new_word += (word[index - replace_index % len(word)])
if new_word.endswith('/'):
replace_index += 1
translated_step_2 += new_word + ' '
translated_step_2 = translated_step_2.replace('/', '\n')
return translated_step_2
crypted_string = 'тут ваш зашифрованный текст'
print(get_encrypted_word(crypted_string, 1))
Good day!
preamble ...
In the cart I am in the Python smoking room group. From time to time I help growing pythons deal with their problems. Nothing but entertainment and brain food. Then one guy threw a problem and asked for help to solve it.
Problem 10. Truth
What to do
You have received a ciphertext, which means a big truth for many Python programmers. Write a program that implements an algorithm for decrypting this text. Decipher the text with your program, and then search for it on the Internet.
I don’t cite the text here, it is below in the source code below.
Moreover, after 10 minutes the guy said - thank you, my colleague helped me solve it and flashed a screenshot with the source code. I saw a nesting doll of three cycles nested in each other and decided to assert itself. To do this, I sat down to write something compact and without "matryoshkas". It was then that interesting things began ...
I did not begin to rewrite the implementation of the Caesar encryption algorithm, but the second encryption algorithm by shifting letters seemed interesting to me and the "matryoshka" was in it.
Guys, this is not an easy task. It didn’t work out on her knee .. Take a closer look.
I even recorded a video here with reasoning about the solution and demonstrating the pitfalls.
I would be glad to hear your opinion, criticism and suggestions.
I have questions about the assignment as a whole:
1. How, looking at the source text, could it be understood that the Caesar algorithm should be applied to it?
2. In order to select the displacement step in Caesar, it was necessary to have an introductory type:
# Max Chubin 2022-04-16
# алгоритм цезаря
def encrypt(message, key):
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
translated = translated + LETTERS[num - key]
else:
translated = translated + symbol
return translated
# исходный текст
txt = '''
vujgvmCfb tj ufscfu ouib z/vhm jdjuFyqm jt fscfuu uibo jdju/jnqm fTjnqm tj scfuuf ibou fy/dpnqm yDpnqmf jt cfuufs boui dbufe/dpnqmj uGmb tj fuufsc ouib oftufe/ bstfTq jt uufscf uibo otf/ef uzSfbebcjmj vout/dp djbmTqf dbtft (ubsfo djbmtqf hifopv up csfbl ifu t/svmf ipvhiBmu zqsbdujdbmju fbutc uz/qvsj Fsspst tipvme wfsof qbtt foumz/tjm omfttV mjdjumzfyq odfe/tjmf Jo fui dfgb pg hvjuz-bncj gvtfsf fui ubujpoufnq up ftt/hv Uifsf vmetip fc pof.. boe sbcmzqsfgf zpom pof pvt..pcwj xbz pu pe ju/ Bmuipvhi uibu bzx bzn puo cf wjpvtpc bu jstug ttvomf sfzpv( i/Evud xOp tj scfuuf ibou /ofwfs uipvhiBm fsofw jt fopgu cfuufs boui iu++sjh x/op gJ ifu nfoubujpojnqmf tj eibs pu mbjo-fyq tju( b bec /jefb Jg fui foubujpojnqmfn jt fbtz up bjo-fyqm ju znb cf b hppe jefb/ bnftqbdftO bsf pof ipoljoh sfbuh efbj .. fu(tm pe psfn gp tf"uip/
'''
# используемый в шифровании набор символов
LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# удаление дублей в списке
def clean_doubles(param):
clean_list = []
counter = 0
for item in param:
if item in clean_list:
counter += 1
continue
else:
clean_list.append(item)
return clean_list
# дешифровка слов методом сдвига букв по принципу стэка
def shift(text, iterations = 35):
txt = text.split(' ') # разбиваем исходный текст по словам
# ищем слова со слэшами. по условию строка имеет вид "Beautiful is better than ugly/"
# т.е. слэш должен стоять в конце последнего слова. добавляем перевод строки.
txt = ' '.join(map(lambda x: x+'\n' if '/' in x else x, txt))
txt = txt.split('\n') # снова разбиваем текст уже по переводам строк
result = ''
for line in txt: # перебираем строки
words = line.split() # разбиваем строки на слова
new_line = ''
key = 1 # величина сдвига букв в слове
if len(words) == 0:
continue
results_list = []
while key < iterations:
words_new = list(map(lambda x: x[-key%len(x):] + x[:-key%len(x)], words)) # сдвиг букв на шаг key
# print(' '.join(words_new), key, end='')
# if ' ' in input(':'):
# key += 1
# continue
# если в первом слове первая буква заглавная и в последнем слове в конце символ '/'
if words_new[0][0].isupper() and words_new[-1].endswith('/'):
results_list.append(' '.join(words_new)) # добавляем этот вариант строки в список вариантов
key += 1
clean_list = clean_doubles(results_list) # чистим дубли в списке
select = 0
if len(clean_list) != 1:
print('Выберите строку, которая не содержит ошибок:')
for num, item in enumerate(clean_list):
print(num, ':', item)
while True: # добиваемся от пользователя выбора доступного варианта из списка предложенных
select = input(':')
if select.isnumeric():
select = int(select)
if 0 <= select < len(clean_list):
break
result += clean_list[select] + '\n' # собираем новый дешифрованный текст
return result
if __name__ == "__main__":
# дешифровка цезарем
text = encrypt(txt, 1)
print(text)
# дешифровка сдвигом
result = shift(text)
print(result)
Well, there are two ways.
The first way is standard. Add a parameter to the standard settings prntscr.com/cld6u0
Then output it to a template or chunk
Or a more convenient option through the ConfigClient
component
There is a convenient interface.
We output the template in the same way
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question