Capture d’écran 2019-06-18 à 18.26.40.png - spyder

With the code shown hereunder, spyder 3.3.4 return the following error message :
AttributeError : module 'random' has no attribute 'randit'
The code is as follows:
import random, math
SV = 0 #somme des valeurs du temps d'attente
SC = 0 # somme des carrés du temps d'attente
nb_simul = 5000 #nb simulations
for k in range(nb_simul):
arr1 = random.randit(0 , 60) #arrivée 1
arr2 = random.randit(0 , 60) #arrivée 2
c = abs(arr1 - arr2)#tps d'attente
SV = SV + c
SC = SC + c*c
MV = SV / nb_simul#moyenne des temps d'attente
MC = SC / nb_simul#moyenne des carrés des temps d'attente
e = sqrt((MC - MV*MV)/nb_simul) #écart-type des moyennes des temps
d'attente
print("Estimation ponctuelle :", MV)
print("Intervalle de confiance à 95% [", MV - 1.96*e, ";", MV +
1.96*e,"]" )

Related

How to create and send a table by grouping rows by email addresses - GoogleSheets

I need help to create a table, from column [B] to column [I] if the emails from the managers of column [J] are the same:
Example_01
The yellow lines have the same manager in column [J]: "rafalmfei#gmail.com", so I need to set up a single email with a table, for the manager (Column [J2] and [J3]) with a copy for o Partner E-mail "rafaalmeida_feitoa#yahoo.com.br" (column k 2 and k 3) with lines 2 and 3.
Example_02
And an email with another separate table for the manager "rafaalmeida_feitoa#yahoo.com.br", (column [4] and column [5]) with a copy for Partner E-mail "rafalmfei#gmail.com" (column k [4] and k [5]) with lines 4 and 5.
Example_03
Currently, I have the email ready with the code below, but I receive the lines in separate emails, I need it to be in a single email in table format:
function enviarEmailJornada(){
// Linka a planilha de controle ao script e pega todas as colunas existentes
var planilha = SpreadsheetApp.getActive();
var sheet = planilha.getSheetByName("Analise_Maio");
var linhas = sheet.getRange(1, 1, 156).getValues();
var colunas;
// Cria as variáveis necessárias para enviar o e-mail
var toEmail;
var ccEmail;
var subject = "[URGENTE] Análise imediata de projetos sem ETC";
var message;
// Percorre as linhas da tabela e busca os dados de cada coluna
for(var i = 0; i < linhas.length; i++){
colunas = sheet.getRange(i+1,1,1,sheet.getLastColumn()).getValues()[0];
toEmail = colunas[9];
ccEmail = colunas[10];
if(colunas[0] == "1"){
message = "Caro(a), <br><br>";
message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome. <br><br>";
message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores. <br><br>";
message += "<br>————————————<br><br> " + " "+ colunas[1] +" " + colunas[2] + " " + colunas[3] + " " + colunas[4] + " " + colunas[5] + " " + colunas[6] + " " + colunas[7] + " " + colunas[8] + " " +"<br><br><br>";
message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências. <br><br>";
message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.<br><br>";
message += "Conto com a sua pronta atuação. <br><br>";
message += "Rafaela Feitosa <br><br>";
GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
}
}
}
Thank you!
You can do the following
Retrieve all managers from the sheet
Use ...new Set() to retrieve unique values of managers
For each distinct manager retrieve the relevant sheet values and push them into an html table
Send an email after iterating through all rows and retrieving all data for particular manager
SAMPLE
function enviarEmailJornada(){
// Linka a planilha de controle ao script e pega todas as colunas existentes
var planilha = SpreadsheetApp.getActive();
var sheet = planilha.getSheetByName("Analise_Maio");
// Cria as variáveis necessárias para enviar o e-mail
var subject = "[URGENTE] Análise imediata de projetos sem ETC";
var message;
var colunas = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getValues();
var managers = sheet.getRange(1, 8, sheet.getLastRow()).getValues().flat();
Logger.log(managers);
var uniqueManagers = [...new Set(managers)];
Logger.log(uniqueManagers);
uniqueManagers.forEach(myFunction);
function myFunction(manager) {
var table = "<table>"
var toEmail = "";
var ccEmail = "";
// Percorre as linhas da tabela e busca os dados de cada coluna
for(var i = 0; i < colunas.length; i++){
if(colunas[i][7] == manager && colunas[i][0] == "1"){
toEmail = colunas[i][9];
ccEmail = colunas[i][10];
table += "<tr><td>"+ colunas[i][1] +"</td><td>" + colunas[i][2] + "</td><td>" + colunas[i][3] + "</td><td>" + colunas[i][4] + "</td><td>" + colunas[i][5] + "</td><td>" + colunas[i][6] + "</td><td>" + colunas[i][7] + "</td><td>" + colunas[i][8] + " " +"</td></tr>";
}
}
Logger.log("table"+ table);
if(toEmail != ""){
message = "Caro(a), <br><br>";
message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome. <br><br>";
message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores. <br><br>";
message += "<br>————————————<br><br> "
message += table + "</table>";
message += "<br><br><br>";
message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências. <br><br>";
message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.<br><br>";
message += "Conto com a sua pronta atuação. <br><br>";
message += "Rafaela Feitosa <br><br>";
GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
}
}
}
References:
flat()
Set()
Spread

The Range.getValue method is widely used by the script an execution hint(the light bulb in the menu)

Hello I wrote a script that complets several Google Docs tables with values from different columns in a Spreadsheet.
I declared the columns variables : (8 in total)
var colonne_nom_de_projet = 3
var colonne_code_de_projet = 1
var colonne_chef_de_projet = 7
var colonne_service_pilote_de_projet = 8
var colonne_autres_services_projet = 11
var colonne_typede_projet = 10
var colonne_perimetre__projet = 12
var colonne_date_de_projet = 18
and var NUMERO_COLONNE_2019 = 2;
so the name of the project is in the third column ... and the date in 18 column and I want to create a doc only if I have yes in the second columnAfter that I started to complete my Google Doc table with this values
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME);
var data = sheet.getDataRange().getValues();
var targetFolder = DriveApp.getFolderById(FOLDER_ID);
Logger.log('targetFolder name: ' + targetFolder.getName());
var numRows=sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var nombre_projets_2019 = 0 ;
// à partir de 2 car la première ligne ne nous interesse pas
for(n=2;n<=data.length;++n) {
if (sheet.getRange(n,NUMERO_COLONNE_2019).getValue() == 'yes'){
if(child.getType()==DocumentApp.ElementType.TABLE && child.asTable().getNumRows() >= 8)
{
child.asTable().getCell(0, k).editAsText().setText( sheet.getRange(n,colonne_nom_de_projet).getValue() );
child.asTable().getCell(1, k).editAsText().setText( sheet.getRange(n,colonne_code_de_projet).getValue() ) ;
child.asTable().getCell(2, k).editAsText().setText(sheet.getRange(n,colonne_chef_de_projet).getValue()) ;
child.asTable().getCell(3, k).editAsText().setText( sheet.getRange(n,colonne_service_pilote_de_projet).getValue() ) ;
child.asTable().getCell(4, k).editAsText().setText( sheet.getRange(n,colonne_autres_services_projet).getValue() ) ;
child.asTable().getCell(5, k).editAsText().setText( sheet.getRange(n,colonne_typede_projet).getValue() ) ;
child.asTable().getCell(6, k).editAsText().setText( sheet.getRange(n,colonne_perimetre__projet).getValue() ) ;
child.asTable().getCell(7, k).editAsText().setText( sheet.getRange(n,colonne_date_de_projet).getValue() ) ;
and it works but I have a message and an execution hint(the light bulb in the menu)
"The Range.getValue method is widely used by the script.CollapseFile:
Code Line: 75The script uses a method that is considered expensive.
Each invocation generates a long-term call to a remote server. This
can have a critical impact on script execution time, especially on
large data. If the script has a performance problem, we recommend that
you use another method, such as Range.getValues ()." If you have any ideas it will be great ^^^^ because line 75 corresponds to
if (sheet.getRange(n,NUMERO_COLONNE_2019).getValue() == 'yes')
Edit edit : this is my very very slow code 4 minutes
function create_Google_Docs_2019_0() {
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var data = sheet.getRange(1,1,numRows,lastColumn).getValues()
var targetFolder = DriveApp.getFolderById(FOLDER_ID);
Logger.log('targetFolder name: ' + targetFolder.getName());
var numRows=sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var nombre_projets_2019 = 0 ;
// à partir de 2 car la première ligne ne nous interesse pas
for(n=1;n < data.length;n++) {
//verifier si c'est une projet 2019 >>>>>>>>>>>>>>>>>>> ici on fait notre travail
if ( data[n][1] == 'o'){
nombre_projets_2019 = nombre_projets_2019 + 1;
var nom_projet = data[n][2];
//var nom_document = 'Projet ' + nom_projet ;
var nom_document = nom_projet ;
/** Recherche si dans folder il y a déjà ce fichier avec ce nom on va l'actualiser avec les données changés**/
if( checkFile_in_a_Folder(nom_document,targetFolder) == 1){
//on ajoute le fichier dans le repertoire courant targetFolder
Logger.log('On va réecrire le ficher / overwrite le ficher ');
}
else
{
Logger.log('On va le créer avec les données qu on a dans le tableau ');
//Make a copy of the template file
var documentId = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy().getId();
//Rename the copied file
var name = DriveApp.getFileById(documentId).setName(nom_document);
var body = DocumentApp.openById(documentId).getBody();
if(body)
{
var ok = 0; //pour l'instant il n'y a pas de tableau
var numChildren=body.getNumChildren();
var i=0;
//tant qu'on n'a pas du tableau on va parcourir
while(ok ==0 && i<numChildren)
{
var child=body.getChild(i);
/** ============On est concerné par le premier tableau seulement qui a au plus 8 lignes d'information ================**/
Logger.log('Le type dans la boucle ' + child.getType());
//on a trouvé un tableau
if(child.getType()==DocumentApp.ElementType.TABLE && child.asTable().getNumRows() >= 8)
{
//on a trouve notre premier tableau
ok=1;
var numrows = child.asTable().getNumRows();
Logger.log('Le nombre de lignes dans notre Google Doc ' + numrows);
var insertion_position = n ;
Logger.log('Position pour inserer dans le spreadsheet ' + insertion_position);
var k = 1;
child.asTable().getCell(0, k).editAsText().setText( data[n][colonne_nom_de_projet-1]);
child.asTable().getCell(1, k).editAsText().setText( data[n][colonne_code_de_projet-1] ) ;
child.asTable().getCell(2, k).editAsText().setText( data[n][colonne_chef_de_projet-1]) ;
child.asTable().getCell(3, k).editAsText().setText( data[n][colonne_service_pilote_de_projet-1] ) ;
child.asTable().getCell(4, k).editAsText().setText( data[n][colonne_autres_services_projet-1] ) ;
child.asTable().getCell(5, k).editAsText().setText( data[n][colonne_typede_projet-1] ) ;
child.asTable().getCell(6, k).editAsText().setText( data[n][colonne_perimetre__projet-1] ) ;
child.asTable().getCell(7, k).editAsText().setText( data[n][colonne_date_de_projet-1] ) ;
}
i++;
}
}
}
}
Logger.log('Nombre de projets 2019 ' + nombre_projets_2019 );
}
}
it's a project so that by searching in the second column for 'o' (oui in French) means that the project will be in 2019 so i will get the information from several columns i want(name project,date,chef de project...) and then put this information in a Google Doc Table created using a Template with makecopy() with 8 rows and 2 columns so all the information will be put in the second colum.In fact my code is very slow and if you have any ideas to improuve it will be great because it does the work in about 4 min
Use range.getValues() to get the values in an array (single call to API), instead of using .getValue() multiple times (multiple calls, 'considered expensive').
Instead of:
for(n=2;n<=data.length;++n) {
child.asTable().getCell(0, k).editAsText().setText( sheet.getRange(n,colonne_nom_de_projet).getValue() );
child.asTable().getCell(2, k).editAsText().setText(sheet.getRange(n,colonne_chef_de_projet).getValue()) ;
//etc.
Use:
var values = sheet.getRange(0,0,20,20).getValues() //or whatever the range is
for(n=2;n<=data.length;++n) {
child.asTable().getCell(0, k).editAsText().setText( values[n][colonne_nom_de_projet]) );
child.asTable().getCell(2, k).editAsText().setText(values[n][colonne_chef_de_projet])) ;
//etc.
Something like that, you get the idea.

What is this function doing in Lua?

function splitSat(str, pat, max, regex)
pat = pat or "\n" --Patron de búsqueda
max = max or #str
local t = {}
local c = 1
if #str == 0 then
return {""}
end
if #pat == 0 then
return nil
end
if max == 0 then
return str
end
repeat
local s, e = str:find(pat, c, not regex) -- Dentro del string str, busca el patron pat desde la posicion c
-- guarda en s el numero de inicio y en e el numero de fin
max = max - 1
if s and max < 0 then
if #(str:sub(c)) > 0 then -- Si la longitud de la porcion de string desde c hasta el final es mayor que 0
t[#t+1] = str:sub(c)
else values
t[#t+1] = "" --create a table with empty
end
else
if #(str:sub(c, s and s - 1)) > 0 then -- Si la longitud de la porcion de string str entre c y s
t[#t+1] = str:sub(c, s and s - 1)
else
t[#t+1] = "" --create a table with empty values
end
end
c = e and e + 1 or #str + 1
until not s or max < 0
return t
end
I'd like to know what this function is doing. I know that it makes a kind of table taking a string and a pattern. Especially I want to know what *t[#t+1] = str:sub(c, s and s - 1)* is doing.
From what I get, it splits a long string into substrings that match a certain pattern and ignores everything in between the pattern maches. For example, it might match the string 11aa22 to the pattern \d\d, resulting in the table ["11", "22"].
t[#t+1] = <something> inserts a value at the end of table t, it's the same as table.insert(t, <something>)
#t returns the length of an array (that is, a table with consecutive numeric indices), for example, #[1, 2, 3] == 3
str:sub(c, s and s - 1) takes advantage of many of luas features. s and s - 1 evaluates to s-1 if s is not nil, and nil otherwise. Just s-1 would throw an error if s was nil
10 and 10 - 1 == 9
10 - 1 == 9
nil and nil - 1 == nil
nil - 1 -> throws an error
str:sub(a, b) just returns a substring starting at a and ending at b (a and b being numeric indices)
("abcde"):sub(2,4) == "bcd"

Lua - Error Attempt to perform arithmetic on field '?' -- This occurs at the end of the for loop

I'm developing a program for the Ti-nspire CX CAS calculator and at the time of execution it indicates an error on line 52, this is presented at the end of the for loop in the "area" function.
Sorry for my English.
local coX = {0,2,2,0}
local coY = {0,0,2,0}
local xmax = 2
local ymax = 2
-- Matriz de coordenadas para función "on.paint(gc)"
function conCoor(x,y)
local nx = x
for i=1, #x do
table.insert(nx,i*2,y[i])
end
return nx
end
-- Valor absoluto
function math.abs(valor)
if valor < 0 then
valor = valor*(-1)
end
return valor
end
-- Inercia del polígono respecto el eje X
function inerciex(x,y)
local E = 0
local z =0
for i = 1, #x-1 do
E = (x[i+1]-x[i])*(y[i+1]+y[i])*((y[i+1])^2+(y[i])^2)
z = E + z
end
return math.abs(z/12)
end
-- Inercia del polígono respecto el eje Y
function inerciey(x,y)
local E = 0
local z =0
for i = 1, #x-1 do
E = (y[i+1]-y[i])*(x[i+1]+x[i])*((x[i+1])^2+(x[i])^2)
z = E + z
end
return math.abs(z/12)
end
-- Área del poligono
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end -- Line 52, the line in question
return math.abs(z/2)
end
-- Centro de masa del polígono (eje x)
function centroix(x,y)
local Ac = area(x,y)
local z = 0
local cx = 0
for i = 1, #x-1 do
cx = (x[i]+x[i+1])*(x[i]*y[i+1]-x[i+1]*y[i])
z = cx + z
end
return z/(6*Ac)
end
-- Centro de masa del polígono (eje y)
function centroiy(x,y)
local Ac = area(x,y)
local z = 0
local cx = 0
for i = 1, #x-1 do
cx = (y[i]+y[i+1])*(x[i]*y[i+1]-x[i+1]*y[i])
z = cx + z
end
return z/(6*Ac)
end
-- Escala de figura
function escala(xmax,ymax)
local sc = 0
if xmax > ymax then
sc = 81/xmax
else
sc = 81/ymax
end
return math.floor(sc)
end
-- Coordenadas del origen en pantalla
function oriDispX(x,y,xmax,ymax)
return math.floor(212 + (-1)*centroix(x,y)*escala(xmax,ymax))
end
function oriDispY(x,y,xmax,ymax)
return math.floor(105 + (-1)*centroiy(x,y)*escala(xmax,ymax))
end
-- Cambio de coordenadas real
function coorCamb(x,y,xmax,ymax)
-- Escalado de coordenadas
local escx = x
local escy = y
local orix = oriDispX(escx,escy,xmax,ymax)
local oriy = oriDispY(escx,escy,xmax,ymax)
for i = 1, #escx do
escx[i] = math.floor(escx[i]*escala(xmax,ymax))
escy[i] = math.floor(escy[i]*escala(xmax,ymax))
end
-- Cambio de coordenadas
for i = 1, #escx do
escx[i] = escx[i] + orix
escy[i] = escy[i] + oriy
end
return conCoor(escx,escy)
end
function on.paint(gc)
local ox = oriDispX(coX,coY,xmax,ymax)
local oy = oriDispY(coX,coY,xmax,ymax)
local c = coorCamb(coX,coY,xmax,ymax)
gc:drawPolyLine(c)
gc:drawLine(ox-3,oy,ox+3,oy)
gc:drawLine(ox,oy-3,ox,oy+3)
gc:fillArc(ox-1,oy-1,2,2,0,360)
gc:fillArc(212-1,105-1,2,2,0,360)
gc:drawString(tostring(area(coX,coY)),10,10)
platform.window:invalidate()
end
More specifically, the error occurs here:
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end -- Line 52, the line in question
return math.abs(z/2)
end
Your code assumes both X and Y arrays are of equal size (because you use i index for both X and Y array), or at least Y never smaller than X. i index, however, runs from 1 to the size of X array which will be invalid for Y array of smaller size.
So, if the Y array is smaller than the X array, you get that error. And, here's the proof:
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end
return math.abs(z/2)
end
print(area({1,2,3},{4,5,6})) -- OK
print(area({1,2,3},{4,5})) -- ERROR
The solution was to initialize the variables and tables at the beginning of the whole script and then call the new values ​​using "var.recall" inside the on.paint function.

jquery ui 1.9.0 autocomplete autofocus not working

Antecedents:
jquery-ui-1.9.0.custom.min.css
jquery-1.8.2.js
jquery-ui-1.9.0.custom.min.js
The code is as follows:
$("#origen, #destino").autocomplete({
source: function(request, response){
$("#cargando").show();
// Para distinguir la cache del elemento origen y destino ya que van a jsp's diferentes. tolo (03/07/2012)
var term = request.term; var termCache = request.term + "-" + $(this.element).attr("id");
if ( termCache in cache ) {
response( cache[ termCache ] );
setTimeout("$('#cargando').hide();", 2000);//ocultamos con retraso 2 seg
return; }
if($(this.element).attr("id") == "origen"){
// El filtro de aeropuertos por pais es solo para el origen
if (parent.codMarca == 'NET')
paises = '|PT|ES|';
urlxx = "../../jsp/buscador/autocompletevuelos.jsp?sesion=" + sesion + "&term=" + term + "&codidi=" + codidi +
"&tipPro=VH&paises=" + codpai + "&codEmp=" + parent.codEmp + "&codMarca=" + parent.codMarca + "&codWcn=" +
parent.codWcn + "&orides=O"; }else{
urlxx = "../../jsp/buscador/autocompletepoblaciones.jsp?sesion=" + sesion +
"&term=" + term +
"&codidi=" + codidi +
"&tipoProducto=VH&codemp=" + codEmp +
"&codwcn=" + codWcn + "&codMarca=" + parent.codMarca; }
lastXhr = $.getJSON( urlxx, request, function( data, status, xhr ) {
cache[ termCache ] = data;
if ( xhr === lastXhr ) {
response( data );
setTimeout("$('#cargando').hide();", 2000);//ocultamos con retraso 2 seg
}
});
},
minLength: 2,
select: function(event, ui) {
var componente = $(this).attr("id");
if (ui.item) {
// El check de residente sólo tiene que estar habilitado cuando los dos aeropuertos son españoles, y al menos uno de ellos
// consta como residente.
if(componente == "origen"){
$("#oriCodApt").val(ui.item.id);
$("#orideszona").val(ui.item.value);
$("#oricodpai").val(ui.item.codpai.toUpperCase());
$("#oriresidente").val(ui.item.residente.toUpperCase());
}else{
$("#desCodApt").val(ui.item.codapt);
$("#desdeszona").val(ui.item.value);
$("#descodpai").val(ui.item.codpai.toUpperCase());
$("#desresidente").val(ui.item.residente.toUpperCase());
$("#zonaCodificada").val( ui.item.codpai.toUpperCase() + "#" +
ui.item.codepr.toUpperCase() + "#" +
ui.item.codpob.toUpperCase() + "#" +
ui.item.codare.toUpperCase());
$("#numAeropuertos").val(ui.item.numAeropuertos == undefined ? 0 : ui.item.numAeropuertos);
$("#fueraCiudad").val(ui.item.fueraCiudad == undefined ? "" : ui.item.fueraCiudad);
}
validaResidente();
}
},
open: function(e,ui) {
var autoData = $(this).data('autocomplete');
var reserText = ",de,del,el,la,las,los,en,";
var altoCombo = 200; // Altura del combo del autocomplete.
var componente = $(this).attr("id");
autoData.menu.element.css({'width':'' + anchoMinimo + 'px'});
autoData.menu.element.find('li').each(function() {
var fila = $(this);
var texto = fila.text().toLowerCase().replace(autoData.term.toLowerCase(), "<b>" + autoData.term.toLowerCase() + "</b>");
var autoText = "";
texto = texto.split(" ");
for(var i = 0; i < texto.length; i++){
if((reserText.indexOf( texto[i].replace("<b>","").replace("</b>","") ) != "-1") && (i > 0)){
autoText += texto[i] + " ";
}else if( texto[i].substring(0,3) == "<b>" ){
autoText += "<b>" + texto[i].charAt(3).toUpperCase() + texto[i].substring(4) + " ";
}else{
autoText += texto[i].charAt(0).toUpperCase() + texto[i].substring(1) + " ";
}
}
autoText = autoText.replace(" De "," de ").replace(" Del "," del ").replace(" Los "," los ").replace(" El "," el ").replace(" En "," en").replace(" La "," la ").replace(" Las "," las ");
// El código de aeropuerto, lo que va entre paréntesis, tiene que salir en mayúsculas.
if(componente == "origen"){
var tamPrimerCorte = autoText.split("(").length;
var textoEnParentesis = autoText.split("(")[tamPrimerCorte - 1];
textoEnParentesis = textoEnParentesis.split(")")[0];
autoText = autoText.replace("(" + textoEnParentesis + ")", "(" + textoEnParentesis.toUpperCase() + ")");
}
fila.find('a').text("");
fila.find('a').append( autoText );
// Ahora vamos a calcular el ancho de la cadena más ancha para saber qué ancho tiene que tener el combo.
ancho = autoText.length * 5; // Con esta fuente de letra, en IE, etc...
if(ancho > anchoFilaDestinos){
anchoFilaDestinos = ancho;
}
// Fin del cálculo del ancho.
fila.find('a').css({'white-space':'nowrap'});
});
// Hay que mantener un ancho mínimo.
if(anchoFilaDestinos < anchoMinimo){
anchoFilaDestinos = anchoMinimo;
}
numItems = 0;
// Hay que recorrer todas las filas otra vez, para ponerles a todas el mismo ancho.
autoData.menu.element.find('li').each(function() {
var fila = $(this);
fila.find('a').css({'white-space':'nowrap','width':'' + anchoFilaDestinos + 'px','text-align':'left'});
numItems++;
});
anchoFilaDestinos += 9;
autoData.menu.element.css({'width':'' + anchoFilaDestinos + 'px'});
anchoFilaDestinos = 0;
// Porque 9 son los que caben en 200 de alto.
if(numItems < 9){
altoCombo = numItems * 23;
$(".ui-autocomplete").css("height", altoCombo).css("overflow-y", "hidden").css("overflow-x", "hidden");
}else{
$(".ui-autocomplete").css("height", altoCombo).css("overflow-y", "scroll").css("overflow-x", "hidden");
}
},
error : function() {
if ( $(this).attr("id") == "origen" ){
parent.crearModal('Alerta', '<ml:message id="1" value="Hay un error en la peticion de ORIGEN."/>');
} else {
parent.crearModal('Alerta', '<ml:message id="2" value="Hay un error en la peticion de DESTINO."/>');
}
},
autoFocus: true,
focus: function(event, ui){
if (ui.item) {
var codzon = "P:" + ui.item.codpai + "#" + ui.item.codepr + "#" + ui.item.codpob + "#" + ui.item.codare;
if($(this).attr("id") == "origen"){
$("#oricodzona").val(codzon);
$("#orideszona").val(ui.item.value);
}else{
$("#descodzona").val(codzon);
$("#desdeszona").val(ui.item.value);
}
} else {
if($(this).attr("id") == "origen"){
$("#oricodzona").val("");
}else{
$("#descodzona").val("");
}
}
}
});
Finally, as you can see, the option autoFocus:true, but it doesn't work, even the list is filled up correctly.
Please, any help?
Ok, autoanswering: you must delete de selectFirst clause before including the autoFocus.

Resources