Plone/Dexterity schema.Choice not allowing Spanish characters - character-encoding

In Plone 4.1.2 I created a myContentType with Dexterity. It has 3 zope.schema.Choice fields. Two of them take their values from a hardcoded vocabulary and the other one from a dynamic vocabulary. In both cases, if I choose a value that has Spanish accents, when I save the add form the selection is gone and doesn't show up in the view form (without showing any error message). But if I choose a non accented value everything works fine.
Any advise on how to solve this problem?
(David; I hope this is what you asked me for)
# -*- coding: utf-8 -*-
from five import grok
from zope import schema
from plone.directives import form, dexterity
from zope.component import getMultiAdapter
from plone.namedfile.interfaces import IImageScaleTraversable
from plone.namedfile.field import NamedBlobFile, NamedBlobImage
from plone.formwidget.contenttree import ObjPathSourceBinder
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.schema.interfaces import IVocabularyFactory
from z3c.formwidget.query.interfaces import IQuerySource
from zope.component import queryUtility
from plone.formwidget.masterselect import (
_,
MasterSelectField,
MasterSelectBoolField,
)
from plone.app.textfield.interfaces import ITransformer
from plone.indexer import indexer
from oaxaca.newcontent import ContentMessageFactory as _
from oaxaca.newcontent.config import OAXACA
from types import UnicodeType
_default_encoding = 'utf-8'
def _encode(s, encoding=_default_encoding):
try:
return s.encode(encoding)
except (TypeError, UnicodeDecodeError, ValueError):
return s
def _decode(s, encoding=_default_encoding):
try:
return unicode(s, encoding)
except (TypeError, UnicodeDecodeError, ValueError):
return s
view = view.encode('utf-8')
def getSlaveVocab(master):
results = []
if master in OAXACA:
results = sorted(OAXACA[master])
return SimpleVocabulary.fromValues(results)
class IFicha(form.Schema, IImageScaleTraversable):
"""Describes a ficha
"""
tipoMenu = schema.Choice(
title=_(u"Tipo de evento"),
description=_(u"Marque la opción que aplique o "
"seleccione otro si ninguna aplica"),
values=(
u'Manifestación en lugar público',
u'Toma de instalaciones municipales',
u'Toma de instalaciones estatales',
u'Toma de instalaciones federales',
u'Bloqueo de carretera municipal',
u'Bloqueo de carretera estatal',
u'Bloqueo de carretera federal',
u'Secuestro de funcionario',
u'Otro',),
required=False,
)
tipoAdicional = schema.TextLine(
title=_(u"Registre un nuevo tipo de evento"),
description=_(u"Use este campo solo si marcó otro en el menú de arriba"),
required=False
)
fecha = schema.Date(
title=_(u"Fecha"),
description=_(u"Seleccione el día en que ocurrió el evento"),
required=False
)
municipio = MasterSelectField(
title=_(u"Municipio"),
description=_(u"Seleccione el municipio donde ocurrió el evento"),
required=False,
vocabulary="oaxaca.newcontent.municipios",
slave_fields=(
{'name': 'localidad',
'action': 'vocabulary',
'vocab_method': getSlaveVocab,
'control_param': 'master',
},
)
)
localidad = schema.Choice(
title=_(u"Localidad"),
description=_(u"Seleccione la localidad donde ocurrió el evento."),
values=[u'',],
required=False,
)
actores = schema.Text(
title=_(u"Actores"),
description=_(u"Liste las agrupaciones y los individuos que participaron en el evento"),
required=False,
)
demandas = schema.Text(
title=_(u"Demandas"),
description=_(u"Liste las demandas o exigencias de los participantes"),
required=False
)
depResponsable = schema.Text(
title=_(u"Dependencias"),
description=_(u"Liste las dependencias gubernamentales responsables de atender las demandas"),
required=False
)
seguimiento = schema.Text(
title=_(u"Acciones de seguimiento"),
description=_(u"Anote cualquier accion de seguimiento que se haya realizado"),
required=False
)
modulo = schema.Choice(
title=_(u"Informa"),
description=_(u"Seleccione el módulo que llena esta ficha"),
values=(
u'M1',
u'M2',
u'M3',
u'M4',
u'M5',
u'M6',
u'M7',
u'M8',
u'M9',
u'M10',
u'M11',
u'M12',
u'M13',
u'M14',
u'M15',
u'M16',
u'M17',
u'M18',
u'M19',
u'M20',
u'M21',
u'M22',
u'M23',
u'M24',
u'M25',
u'M26',
u'M27',
u'M28',
u'M29',
u'M30',),
required=False
)
imagen1 = NamedBlobImage(
title=_(u"Imagen 1"),
description=_(u"Subir imagen 1"),
required=False
)
imagen2 = NamedBlobImage(
title=_(u"Imagen 2"),
description=_(u"Subir imagen 2"),
required=False
)
anexo1 = NamedBlobFile(
title=_(u"Anexo 1"),
description=_(u"Subir archivo 1"),
required=False
)
anexo2 = NamedBlobFile(
title=_(u"Anexo 2"),
description=_(u"Subir archivo 2"),
required=False
)
#indexer(IFicha)
def textIndexer(obj):
"""SearchableText contains fechaFicha, actores, demandas, municipio and localidad as plain text.
"""
transformer = ITransformer(obj)
text = transformer(obj.text, 'text/plain')
return '%s %s %s %s %s' % (obj.fecha,
obj.actores,
obj.demandas,
obj.municipio,
obj.localidad)
grok.global_adapter(textIndexer, name='SearchableText')
class View(grok.View):
"""Default view (called "##view"") for a ficha.
The associated template is found in ficha_templates/view.pt.
"""
grok.context(IFicha)
grok.require('zope2.View')
grok.name('view')

I found the same problem some months ago on early development of collective.nitf.
The tokens on a vocabulary must be normalized; this is how I solved it:
# -*- coding: utf-8 -*-
import unicodedata
…
class SectionsVocabulary(object):
"""Creates a vocabulary with the sections stored in the registry; the
vocabulary is normalized to allow the use of non-ascii characters.
"""
grok.implements(IVocabularyFactory)
def __call__(self, context):
registry = getUtility(IRegistry)
settings = registry.forInterface(INITFSettings)
items = []
for section in settings.sections:
token = unicodedata.normalize('NFKD', section).encode('ascii', 'ignore').lower()
items.append(SimpleVocabulary.createTerm(section, token, section))
return SimpleVocabulary(items)
grok.global_utility(SectionsVocabulary, name=u'collective.nitf.Sections')

Plone uses gettext for internationalization. The bulletproof approach would be to implement your custom functionality in English and use locales for your specific language. Look at the relevant parts of the community manual on how this is done. Since you already setup a MessageFactory you could even use a tool like e.g. zettwerk.i18nduder for quick extraction of message strings.

I found a partial explanation/solution here. I can get the Spanish characters in the view form if i do:
-- coding: utf-8 --
from plone.directives import form
from five import grok
from zope import schema
from plone.directives import form, dexterity
from zope.schema.vocabulary import SimpleVocabulary
myVocabulary = SimpleVocabulary.fromItems((
(u"Foo", "id_foó"),
(u"Baroo", "id_baroó")))
class IPrueba(form.Schema):
tipoMenu = schema.Choice(
title=_(u"Tipo de evento"),
description=_(u"Marque la opción que aplique o "
"seleccione otro si ninguna aplica"),
vocabulary=myVocabulary,
required=False,
)

Related

How to find a string from a specific word to other word using rails

I have the following string and I'm trying to display the information from specific start word to specific end word:
Protocolo de medición
\r\n\r\nEnsayador disruptivo
\r\nDPA 75C Versión: 1.07
\r\nNúmero de serie: 1101908010
\r\n11/02/2022 02:15\r\n_____________________________
\r\n\r\nInformación sobre el ensayo
\r\n\r\nNombre de protocolo: .......................
\r\nNúmero de muestra: 0569.1
\r\nMedición según norma: ASTM D1816:2004 2mm
\r\nForma de electrodos: Forma de seta
\r\nDistancia entre electrodos: 2 mm
\r\nFrec. del ensayo: 60 Hz\r\n\r\n_____________________________
\r\n\r\nConfig. según norma
\r\n\r\nDiámetro de los electrodos: 36 mm\r\n\r\n_____________________________
\r\n\r\nValores de medición
\r\n\r\nTemperatura: 20 °C
\r\n\r\nMedición 1: 60.6 kV
\r\nMedición 2: 72.7 kV\r\nMedición 3: >75.0 kV
\r\nMedición 4: 54.7 kV\r\nMedición 5: 66.4 kV
\r\n\r\nValor medio: 65.9 kV
\r\nDesviación estándar: 8.4 kV
\r\nDesviación estándar/val. medio: 12.8 %
\r\n\r\n\r\nEnsayo correctamente realiz.
\r\n\r\n\r\nEnsayo ejecutado por: .......................
The code should find the string line
\r\nNúmero de muestra: 0569.1 \r\
Final result should be
0569.1
I tried this code only display the word searched
#article.description.match(/Número de muestra:\b/)
I tried this code and works but i need to count the number from and to
<%= #article.description.slice(249..260) %>
What i want is write the FROM WORD - TO WORD string without typing the index word.
If the string you are looking to capture always has a line end character after it at some point you can do:
data = #article.description.match(/Número de muestra:*(.*)$/)
returns a Match object like:
#<MatchData "Número de muestra: 0569.1" 1:"0569.1">
you can then access the match with
data[1]
# => "0569.1"
The Match object stores the matching string in data[0] and the first capture is in data[1]. In the regexp we are using the .* matches the spaces after the string Número de muestra:. The (.*) matches any characters after the spaces. The $ matches the end of line character. Anything that matches what is between the parens () gets stored as matches in the Match object.

Streaming with Tweepy: converting unicode characters to letters

The tweets I capture when streaming with Tweepy come in Unicode special characters and I need them to be letters. I have found many solutions on the site but none of them seemed to work or even to apply to my case, since I’m collecting tweets in real time. Can anyone help?
Here’s my code:
from urllib3.exceptions import ProtocolError
from tweepy import Stream
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener
import time
ckey = 'your code here'
csecret = 'your code here'
atoken = 'your code here'
asecret = 'your code here'
class listener(StreamListener):
def on_data(self, data):
while True:
try:
#print (data)
tweet = data.split(',"text":"')[1].split('","')[0]
tweet2 = data.split(',"screen_name":"')[1].split('","location')[0]
print (tweet2,tweet)
saveFile = open ('test.csv','a')
saveFile.write('#')
saveFile.write(tweet2)
saveFile.write(';')
saveFile.write(tweet)
saveFile.write('\n')
saveFile.close()
return True
except ProtocolError:
continue
except BaseException as e:
print ('Failed on data', str(e))
break
def on_error(self, status):
print (status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=['keyword'])
Here's my output for the keyword "fluminense":
adrianabpadilha Impressionante como mesmo com poucas op\u00e7\u00f5es para o banco o Burro s\u00f3 me sobe o Wisney e o Higor! Pq n\u00e3o levar o Pato\u2026 https:\/\/t.co\/lO4CJJsaaP
Miguel_Aalmeida RT #pulligffc: O Fluminense em dia de jogo olha pra mim e faz isso
TRANQUILINHO3 Time fdpt \ud83d\ude20
LeleoCasttroo #jrmenini #FFvinho Palmeiras e Fluminense ainda tiveram a base como fonte de renda, atl\u00e9tico n\u00e3o revela um jogador\u2026 https:\/\/t.co\/ZF8awS6pDt
SouzaArthur6 #CezarSabia #andreisilvasoar #ndrzej87 #futebol_info C\u00e9zar, existe um tempo certo de testagem, q se d\u00e1 no 5\u00b0 da doe\u2026 https:\/\/t.co\/zmBlBzafdo
Thomasrodrigue_ #renatojr_07 \u00c9 o mesmo exemplo da final da ta\u00e7a rio, a \u00fanica coisa que muda \u00e9 que na final n\u00e3o tinha jogador contam\u2026 https:\/\/t.co\/3Q2nCBw9XS
As you can see, some characters like "ç" and "õ" are shown as "/u00e7" and "\u00f5" respectively.
Thank you!
This occurs because of the encoding character problem You can decode the string using unicode_escape encoding
for example
s = r'\u00e7'
print s
\u00e7 #output
print s.decode('unicode-escape')
ç #output

Google Sheet merged cells create space

I got a sheet with merged cells and in those merged cells, a script write its results.
When I copy this result in the merged cells, it gave me multiple spaces at the end.
Like : Result #1________ (« _ » represent invisible space)
When I put the same result in a normal cell (not merged), it doesn’t put any space at the end.
Result #1
I tried multiple cell format (Center aligned, left aligned, etc.) but nothing changed.
Do you have any idea why ?
Thanks !
EDIT : add script
Script
function Devise() {
const sheetName = "Missions";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var Devise = "";
var NombreMission = "";
var NomOperateurs = "";
if(sheet.getRange("H2").getValue()=="") { // Si la mission 7 est vide
NombreMission = 6; // On compte seulement 6 missions
} else {
NombreMission = 7; // Sinon on compte 7 missions
}
for (i = 1; i < NombreMission+1; i++) { // Boucle FOR pour NombreMission missions
if(sheet.getRange(2,i+1).getValue()=="") { continue; } // Si la mission est vide, on la passe
Devise = Devise + i + "/";
l = 0; // Variable pour indiquer "Rien" si personne à placer dans la mission
NomOperateurs = ""; // Reset les noms pour la mission d'après
for (j = 1; j < 27+1; j++) { // Boucle FOR pour tous les opérateurs
if(sheet.getRange(j+2,i+1).getFontWeight() == 'bold') { // Vérifie si la case est en gras
/*if(i!=NombreMission) { // Tant qu'il ne s'agit pas de la dernière mission ...
Devise = Devise + sheet.getRange(j+2,1).getValue() + " "; // ... on affiche les opérateurs
}*/
NomOperateurs = NomOperateurs + sheet.getRange(j+2,1).getValue() + " ";
l = l + 1; // On compte les opérateurs
}
} // Fin Boucle FOR opérateurs
if (l==24) { // S'il y a tous les operateurs sur une mission...
Devise = Devise + "ALL OPs! " // ... On affiche "All Op!"
} else if (i==NombreMission && l!=0) { // Sinon s'il s'agit de la dernière mission et qu'il reste des opérateurs à placer...
Devise = Devise + "Autres + Epic "; // ... On indique qu'il s'agit du reste et des épiques
} else if (l==0) { // Sinon s'il n'y a aucun opérateurs à placer...
Devise = Devise + "RIEN " // ... On indique "RIEN"
} else { // Sinon ...
Devise = Devise + NomOperateurs; // ... On affiche les opérateurs
}
} // FIN BOUCLE FOR NombreMission
if(NombreMission==6 && Devise!="") { Devise = Devise + "7/!NOTHING!";}
sheet.getRange("K13").setValue(Devise);
}
Your problem is related to the data you copied and the way that you copied it as pasting text in merged cells doesn't create any new lines.
Also, an important thing to keep in mind is that CTRL+ENTER creates the mentioned space also known as a line break.
So, for example, if this cell contains the text Text + line break:
And the text from the above cell is copied and pasted into a merged cell it will look like this - which is the same outcome as the one that you have mentioned:
But if you paste the same text to a simple cell, it will look like this:
This is essentially because the line break will signify the start of a new cell.
For example, this cell contains this text with line breaks:
After the text is copied and pasted into a different cell, this is how it will actually be pasted as:
In order to solve your issue, I suggest you to copy only the text needed and if possible to avoid using any line breaks.
Reference
Edit and Format a Spreadsheet.
Encountering the same issue.
I have a merged cell with text. If I select the cell and paste it into notepad, It includes quite a lot of white space.
I've checked and if the merged cell spans two rows, the white space includes a line break.
If the merged cell spans one row but two columns, the white space does not include a line break.
If I have a single cell and have it take its value from the mered cell "=A1", the text does not include the white space.
So the addition of the whitespace is definitely the result of having a merged cell.

BLE write characteristic ios

It's me again
I got connection between a mini thermal printer and a iOS device, everything is fine except for the number of letters that it prints.
If a want to print a long string it just print a few of them.And the worst is this.
For example if i want to print this "aaaaa1aaaa1" and this "bbbbb2bbbb2"
the result is
"aaaaa1" "aaaa1b" "bbbb2b" "bbbb2" (each block is separated)
this is the code for the print button
#IBAction func btnImprimironClick(_ sender: Any) {
let mensaje = "-----Guillermo Celi (CREO-SUMA) dijo que el primer mandatario está dentro del plazo para remitir un alcance al veto parcial, y pueda “objetar la creación de los cuerpos de seguridad para la custodia de burócratas”. Explicó que su bancada está en contra de ese capítulo del proyecto porque es inconstitucional, y que esa tarea le corresponde a las Fuerzas Armadas y la Policía Nacional. La comisión de Soberanía y Asuntos Internacionales, presidida por Doris Soliz (AP), se allanó al veto parcial del Ejecutivo. Ella señaló que lo único que cabe es acoger el informe pese al pedido de la oposición."
var datos = mensaje.data(using: .utf8)!
self.printer.writeValue(datos , for: characteristic1, type: CBCharacteristicWriteType.withoutResponse)
Please help me with this, could be something wrong whit the code or the utf8
Thanks.
For some reason it's about the coding format, first I use the utf8 because its a standard but I change to macOSRoman and work perfectly.
static func printText(text: String)
{
let text = "Some long paragraph in spanish version."
let byteArray = text.data(using:String.Encoding.macOSRoman)
self.printer.writeValue(byteArray! , for: characteristic1, type: CBCharacteristicWriteType.withoutResponse)
}

Python splitting text returns a str and a list of str

I wonder whether someone can help me with the syntax to split my text file into key, value pairs.
Abbasso: termine con cui si indicano gli ambienti situati sotto il ponte di coperta.
Abbattuta: manovra che consiste nel puggiare sino a fare prendere il vento alle vele sulle mure opposte.
Abbisciare: (fr.: prendre la biture; ingl.: to coil) stendere un cavo o una catena come fosse una biscia in modo da evitare che si imbrogli successivamente, quando sarà posto in opera.
Abbordo: (fr.: abordage; ingl.: collision) collisione in mare. Sinonimo, poco usato, di accosto e di abbordaggio.
Abbrivo: (fr.: erre; ingl.: way-on) inerzia dell'imbarcazione a continuare nel suo movimento anche quando è cessata la spinta propulsiva, sia essa a vela che a motore.
Abbuono: (fr.: bonification, rating; ingl.: rating) compenso: (o vantaggio) dato ad una imbarcazione per permetterle di gareggiare più equamente: (ad esempio abbuono per anzianità di costruzione dello scafo).
My function at the minute gives me a key str, but a value type(list). Instead I want the value also to be a str. I get what my problem is that what should a be the value is splitting on every colon instead of only on the leftmost colon.
def create_dict():
eng_fr_it_dict={}
f_name = "dizionario_della_vela.txt"
handle = open(f_name, encoding = 'utf8')
for line in handle:
#print(line)
if line.startswith(" ") : continue
line.lstrip()
terms = line.split(": ")
#print(terms[1:])
term = terms[0].lstrip()
expan = terms[1:]
print(type(term), type(expan))
eng_fr_it_dict[term] = eng_fr_it_dict.get(term, expan)
with open("eng_fr_it_dict.txt", "wb") as infile:
pickle.dump(eng_fr_it_dict,infile)
print(eng_fr_it_dict)
Can you suggest a cleverer way to do this or will I have to work out how to covert the list of str to a single str? I thought that there was a split in-built function, but obviously not
file = open("dizionario_della_vela.txt", "r")
data = file.read()
file.close()
data = data.split("\n") # getting every line as seperate list
myDict = {}
for line in data:
line = line.split(":")
key = line[0] # getting first element as key
value = ":".join(line[1:]) # joins elements (starting with second) with
# ":". We need this because previous line
# was splitted by ":" to get your key. This
# is where "string" value is produced.
myDict[key] = value
for key in myDict.keys():
print(myDict[key])

Resources