|
Mostrar Temas
|
Páginas: [1] 2 3 4 5 6 7 8 9
|
1
|
Programación / Programación General / Matrix de Pantalla
|
en: 9 Abril 2018, 23:16 pm
|
Hola a tod@s!! espero que todos anden bien por aqui, me gustaria que me den algun consejo acerca de algo que quiero crear les cuento mi necesidad a ver si me dan ese consejo.
tengo una pantalla de 320 X 480 (en pixeles todo) tengo un matrix (apuntador de c++) sin tamaño asignado supongamos que estoy usando c++ aunque la implementacion puede ser en otro lenguaje. y tengo una variable que maneja el tamaño de la fuente estare usando TTF aun no se que espacion tengo entre caracteres pero podria ser 2px y lo que me gustaria hacer es que esa matrix se le asignaran las columnas y las filas por la cantidad de caracteres especificos dependiendo del tamano de la fuente( se puede omitir el espacio en letras) la verdad ese el problema mas incomodo que he visto me gustaria por favor si es posible unas recomendaciones de ustedes, lo pongo en este foro por que no me gustaria si aparece alguien a limitarme a programadores de c++ o c, lo importante es como se podria implementar el algoritmo, la verdad no tengo nada aun hecho.
Gracias de antemano y disculpen las molestias!!
|
|
|
2
|
Programación / Programación C/C++ / lista enlazada opiniones [CODIGO FUENTE]
|
en: 14 Febrero 2017, 23:07 pm
|
un saludo a todos , ahora mismo me encuentro estudiando estructura de datos y estoy tratando de aprender a crear lista enlazada !! class Link{ struct node{ node *next; int vl; }; node *head; node *curr; node *temp; public: Link(){ head = curr = temp = NULL; } void Add(int d){ node *n = new node; n-> next = NULL; n->vl = d; if( head == NULL) { head = n; } else { curr = head ; while(curr->next){ curr = curr->next; } curr->next = n; curr = n; } } void Delete(int vl){ temp = head; curr = head; node *temp_; if(head != NULL){ if( head->vl == vl ) { if(head->next != NULL) { temp = head->next; temp_ = head; head = temp; delete temp_; temp_ = NULL; return; } } } while(curr != NULL && curr->vl != vl){ temp = curr; curr = curr->next; } if(curr == NULL) return; else{ temp_ = curr; curr = curr->next; temp->next = curr; delete temp_; temp_ = NULL; } } void Print(){ node *temp = head; if(temp != NULL){ while(temp != NULL) { cout << temp->vl <<endl; temp = temp->next; } } } }; int main(){ Link li; li.Add(0); li.Add(1); li.Add(2); li.Add(3); li.Add(4); li.Add(5); li.Add(6); li.Add(7); li.Add(8); li.Add(9); li.Delete(5); li.Delete(0); li.Delete(8); li.Print(); }
me gustaria opiniones. gracias de antemano...
|
|
|
3
|
Programación / Programación C/C++ / array y limite de array sobrepasado...
|
en: 31 Enero 2017, 21:31 pm
|
Buenas a todos !! tengo una duda sobre arreglos !! tengo la siguiente estructura. struct Tra{ char b[8]; char c[32]; }; ... int main(){ Tra tr; memset(&tr, 0x00, sizeof(tr)); strncpy(b, "123456789", 7); strncpy(c, "abecdefeghijklmnopqrstuvywz"); cout << b <<endl; }
salida : >> 123456789abecedefghi.....
me gustaria saber por que pasa eso con el valor de b si solo copio una cantidad especifica de caracteres en b? nota : entiendo que c y c++ no tiene bound check . el problema no es la compilacion ,esto lo edite rapido pero al parecer no entendieron asi que me explicare , como cree esta estructura Tra cree dos variable de tipo array a char , ambas con tamanos diferente , luego instancie un objeto de Tra en main , lo limpie ,luego le puse valores no importa que valor estos solo son ejemplo , luego lo imprimi solo el valor de la primera variable y la salida fue la mezcla de todos los valores de la variable c dentro de b , se que las estructura de array plano son como un super array pero por que salen todos los valore de c en b si solo copie cierta cantidad de char con strncpy?
|
|
|
4
|
Programación / Java / socket, serversocket, interoperacion con otros lenguaje.
|
en: 1 Enero 2017, 21:47 pm
|
Buenas a tod@s feliz inicio de año nuevo... bien, tengo una duda estoy tratando de crear un aplicacion te tipo webserver/server usando socket , serversocket, solamente por que quiero aprender y tambien quisiera saber si este servidor puede interactuar con aplicaciones escritas en otros lenguajes (c++, c.. obvio que si) quisiera entender por pasos y no soy nuevo en java pero para esta aplicacion mis conocimientos de socket son limitados , quisiera entender, quisiera que me recomendaran algun libro y link donde pueda leer acerca de este tema. pero como quiera les quiero mostrar algo sencillo , que quizas todos los que saben de estetema en el foro saben. package ConexionCliente; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.Socket; public class SocketCliente{ ///BufferedOutputStream bout = null; ///BufferedInputStream bin = null; boolean can = false; public SocketCliente(){ try{ sck = new Socket("localhost", 4444); } { e.printStackTrace(); } } public SocketCliente (String host, int port ){ try { sck = new Socket( host , port ); if(sck != null) System. out. println("Se Conecto con "+sck. getInetAddress(). getHostAddress() ); } { e.printStackTrace(); } System. out. println("SocketCliente"); } System. out. println("receive"); if(sck.isClosed()) { System. out. print("Socket is Close"); return ret; } try { while((t = input.readLine()) != null){ ret += t; } //br.close(); input.close(); e.printStackTrace(); } finally{ System. out. println("receive"); return ret; } } System. out. printf("%s\n", str ); try { if(sck.isClosed()) { System. out. print("Socket is Close"); return; } pw.print(str); pw.flush(); //output = new ObjectOutputStream(sck.getOutputStream()); //output.writeBytes(str); //output.flush(); //output.close(); // TODO Auto-generated catch block e.printStackTrace(); } finally{ } } public void Close(){ if(!sck.isClosed()) { try { sck.close(); // TODO Auto-generated catch block e.printStackTrace(); } } } }
este codigo es de Main public class Main { public static void main (String[] args ) { //try{ //Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80); //PrintWriter pw = new PrintWriter(s.getOutputStream()); //pw.print("GET / HTTP/1.1\r\nHost: stackoverflow.com\r\n\r\n"); /// pw.print("Host: stackoverflow.com\r\n\r\n"); //pw.flush(); //BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //String t; //while((t = br.readLine()) != null) System.out.println(t); //br.close(); //}catch(Exception e){ // e.printStackTrace(); //} str = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"; /// SocketCliente sck = new SocketCliente("google.com", 80); SocketCliente sck = new SocketCliente("localhost",4444); sck.Send(str); sck.Close();
ahora el codigo del servidor package Server; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; public class Server implements Runnable{ int puerto; boolean isrun = true; Server (int puerto, String sid ){ this.puerto = puerto; server_id = sid; try{ e.printStackTrace(); } } public void HandleRequest(){ System. out. println("manejando desde el Puerto "+ Integer. toString(puerto )); try{ sock = ssock.accept(); System. out. println("cliente Conectado desde la IP "+sock. getRemoteSocketAddress()); StringBuilder request = new StringBuilder(2048); while (true) { int c = in.read(); if (c == '\r' || c == '\n' || c == -1) break; request.append((char) c); } System. out. printf("%s", request. toString()); out.write(now.toString() +"\r\n"); out.flush(); sock.close(); isrun = false; System. out. println("Cliente desconectado"); e.printStackTrace(); } } @Override public void run() { while(isrun){ System. out. println("Esperando conexion...."); HandleRequest(); } } }
Bueno cada vez que trato de interactuar el servirdor lee solo hasta \n \t el reader no me permite leer una linea completa se queda colgado, me gustaria que me ayudaran por favor post-data la informacion que me respoda no importa esta parte se puede obviar. gracias de antemano por los consejos..
|
|
|
5
|
Programación / Java / Ejemplo real sobre thread
|
en: 13 Diciembre 2016, 17:31 pm
|
Buenas a todos de nuevo!!
ahora estoy tratando de enteder los hilos de java , he leido un par de escritos y todos con el mismio esquema de contar numeros hasta 10 y cosas asi ,si es posible alguien me podria mostrar un ejemplo de uso diario de los hilos. gracias de antemano.
|
|
|
6
|
Programación / Java / JPanel no dibuja imagen [inherit]
|
en: 9 Diciembre 2016, 14:10 pm
|
buenas a todos !! les cuento mi duda estoy tratando de ponerle un background a mi jpanel pasandole una image preeviamente cargada , cuando trato de dibujar con la funcion heredada de PaintComponent la imagen aparece null , es extrano por que todas las imagenes que pongo las uso en otro componente es mas antes de pasarla verifico de varias formas que no sea nulo pero al final es lo mismo siempre, mas abajo esta el codigo de jpanel public class RockPosPanel extends JPanel{ int x, y,w,h; public RockPosPanel(){ super(null); super.setLayout(null); } public RockPosPanel (String str ){ this(); x = 0; y = 0; w = 100; h = 100; url = str; if(str != null) { try { System. out. print("Cargando imagen"); System. out. println("La image es null desde que la cargan"); e.printStackTrace(); } } } public void SetImage (Image im, int x, int y, int w, int h ) { if(im != null) this.x = x; this.y = y; this.w = w; this.h = h; } @Override protected void paintComponent (Graphics g ) { super.paintComponent(g); { if(url !=null) try { // TODO Auto-generated catch block e.printStackTrace(); } System. out. println("La image es null desde que la cargan"); System. out. println("La image es null"); } if(Icoo) g. drawImage(Icon,x,y, w, h, this); ///System.out.println("image is null"); } }
y cuando pruebo la isntancia de la clase : Cargando imagen la imagen no es null image is null image is null image is null image is null image is null image is null
quizas me falto implementar algo pero la verdad no he encontrado informacion en la red si alguien me diera una recomendacion, seria mas que suficiente. gracias de antemano.
|
|
|
7
|
Programación / Bases de Datos / insertar en varias tablas fk y pk
|
en: 1 Diciembre 2016, 03:59 am
|
un saludo a tod@s en el foro!!
soy nuevo en esto de base de datos ,y quiero entender algo, le explico tengo varias tablas , normalizadas y como es entendible hay una relaccion donde una de las columna de la tabla es una llave foranea de otra tabla ,entonces me gustaria ver un ejemplo de como puedo hacer un insert en ambas tablas ejemplo...
tabla cliente ( idcliente, nombre....) tabla datoscliente ( idcliente fk, direccion,...)
esa seria mi tabla de prueba quisiera insertar datos en ambas tablas ,como podria hacerlo???
|
|
|
8
|
Programación / Programación C/C++ / Ayuda, con Opciones de compilacion
|
en: 4 Noviembre 2016, 21:42 pm
|
Buenas a todos!!
tengo como siempre un par de preguntas :
1- estoy tratando de linkear una libreria estatica (.a) desde una ruta alternativa al path que tiene el compilador por defecto y si siempre me dice que no encuentra la libreria, estoy usando GCC segun el manual pasando el path con la opcion -LC eso esta resuelto pero no es asi.
2- estoy tratando de utilizar la libreria .a pero sin el prefijo lib, segun varias fuentes en internet pasando -l:<Nombre_de_mi_libreira>.a eso deberia estar resuelta pero no, tambien puede ser que el problema dependa del punto 1.
quite todas las dependencias de la libreria solamente para probar la aplicacion y este seria le siguiente punto.
3-estoy tratando de hacer una prueba fuera de la maquina que tengo en desarrollo y cuando trato de correr la aplicacion ya creada , me sale un msg que dice, que la version de la aplicacion no es compatible con la version de windows que estoy utilizando, que verifique si necesito una version de 32 o 64 bit de la aplicacion y contacte al que publica la aplicacion.
agradezco por adelantado.
|
|
|
9
|
Programación / Java / [AYUDA] jdbc , conexion que se queda colgando.
|
en: 21 Octubre 2016, 18:37 pm
|
un Saludo a Todos !! tengo un incovenienten , les cuento estoy creado una clase para que me haga de manager con las bases de datos es decir que me cree la conexion , que ejecutes los query o alguna actulizacion y luego cierre la conexion , el siguiente incoveniente es el que tengo , mi clase se conecta bien a la base de datos (estoy usando Auntenticacion )si fallo me da error y luego si trato ingresar con un usuario valido como quiera me da la misma excepcion(rechanzando la conexion ), estoy usando Derby pero supongo que es problema de programacion, la verdad estoy perdido. dejare el codigo a ver si me pueden hechar una mano o consejo public class RockPosDBManager { private boolean debugEnable; private int engine; private int typeOfConn; private String Embeddeddriver = "org.apache.derby.jdbc.EmbeddedDriver"; private String Clientdriver = "org.apache.derby.jdbc.ClientDriver"; private String mySQLClientDriver = "com.mysql.jdbc.Driver"; private String DerbyServer = "jdbc:derby://localhost:1527/"; private String DerbyNoServer = "jdbc:derby:/"; private String MySQLServer = "jdbc:mysql://localhost:3306/"; private String finalConnectionString ; private boolean Authentication; private boolean create; private boolean isConnected; /** * @function Print * @brief this function Print Information on terminal console if the Debug Flag is enable. * @param String - this String is the value that will be print onto the screen * */ private void Print (String templ ){ if( debugEnable == false) return; if( templ != null ) { //System.out.printf("DEBUG : %s\n", templ ); } } /** * @function Print * @brief this constructor will set the current Engine, kind of connection, we have avaliable Derby engine and Mysql . * @param int sqlEngine =type of Engine rockPosClient = server, embedded or Client * @see RockPosDBEngine & RockPosTypeConn * */ public RockPosDBManager(int sqlEngine , int rockposClient, boolean created ){ this.engine = sqlEngine; this.typeOfConn = rockposClient; this.debugEnable = false; this.isConnected = false; this.create = created; } /** * @function setDebugVerbose * @brief this function will turn on the Debug Flag for Terminal. * @param none * @see * */ public void setDebugVerbose(boolean e){ debugEnable=e; } /** * @function isConnectedIntoDatabase * @brief this Function Verify if the databe is connected; * @param none * @see * */ public boolean isConnectedIntoDatabase(){ return this.isConnected; } /** * @function SetDBNameConn * @brief * @param * @see * */ public void SetDBNameConn (String DBname ){ try{ if(DBname == null) this.DBName = DBname; Print("DB name is : "+ DBName); switch(engine){ case RockPosDBEngine.SQL_DERBY: Print("ENGINE SQL_DERBY"); switch(typeOfConn) { case RockPosTypeConn.ROCKPOS_CLIENT: Print("Type Of Connection ROCKPOS_CLIENT"); finalConnectionString = DerbyServer + this.DBName; finalDriver = Clientdriver; break; case RockPosTypeConn.ROCKPOS_EMBEDDED: Print("Type Of Connection ROCKPOS_EMBEDDED"); finalConnectionString = DerbyNoServer + this.DBName; finalDriver = Embeddeddriver ; break; case RockPosTypeConn.ROCKPOS_SERVER: Print("Type Of Connection ROCKPOS_SERVER"); finalConnectionString = DerbyServer + this.DBName; finalDriver = Clientdriver; break; } break; case RockPosDBEngine.SQL_MYSQL: Print("ENGINE SQL_MYSQL"); switch(typeOfConn) { case RockPosTypeConn.ROCKPOS_CLIENT: /// Print("Type Of Connection ROCKPOS_CLIENT"); finalConnectionString = MySQLServer + this.DBName; finalDriver = mySQLClientDriver; break; case RockPosTypeConn.ROCKPOS_EMBEDDED: //// Print("Type Of Connection ROCKPOS_EMBEDDED"); Print("MySQL does not work in Embedded Mode yet."); finalDriver = mySQLClientDriver; break; case RockPosTypeConn.ROCKPOS_SERVER: //// Print("Type Of Connection ROCKPOS_SERVER"); finalConnectionString = MySQLServer + this.DBName; finalDriver = mySQLClientDriver; break; } break; } Print("Connection Driver is : "+ finalDriver); Print("Connection String is ===> "+ finalConnectionString); if(this.UserName != null && this.password != null) { Print("Authentication is On."); Print("User name is =[ "+this.UserName+ " ] password = [ "+ this.password +"]"); Authentication = true; } else { Print("Authentication is On."); Print("No user name was provide."); Authentication = false; } { e.printStackTrace(); } } /** * @function SetCredential * @brief * @param * @see * */ if(user != null) this.UserName = user; if(pass != null) this.password = pass; } public void RequireAuth(boolean auth){ this.Authentication = auth; } /** * @function Connect * @brief * @param * @see * */ public boolean Connect(){ this.connection = null; try{ Class.forName(finalDriver); } { e.printStackTrace(); this.isConnected = false; return this.isConnected ; } try{ if(create == false) { param = finalConnectionString +";user="+ this.UserName+";password="+ this.password; } else { param = finalConnectionString +";create=true;user="+this.UserName+";password="+ this.password; } System. out. printf("Param to Server : %s", param ); if(this.connection.isValid(30)){ this.isConnected = true; System. out. print("\nEsta Conectado."); } else{ this.isConnected = false; System. out. print("\nno Esta Conectado."); } } { int code = e.getErrorCode(); e.printStackTrace(); this.isConnected = false; return this.isConnected; } return this.isConnected; } public boolean Disconnect(){ try { this.connection.close(); e.printStackTrace(); return isConnected; } this.isConnected = false; return isConnected; } public boolean Execute (String sql ){ ///Print("Execute"); boolean res = true; if(this.isConnected == false ) { Print("theres is not Connection"); return false; } try { stmt = this.connection.prepareStatement(sql); stmt.executeUpdate(sql); e.printStackTrace(); Print("Error Executing that Query"); return false; } finally{ ///Print("Execute Finally"); try { stmt.close(); Print("Error closing Statement."); } } return res; } if(this.isConnected == false ) { Print("theres is not Connection"); return null; } try { this.connection.setAutoCommit(true); stmt = this.connection.createStatement(); result = stmt.executeQuery(sql); if(result == null) Print("Result is null"); Print("Error Executing that Query"); } try { stmt.close(); Print("Error closing Statement."); } return result; } public void CloseConn(){ try { this.connection.close(); Print("Closing Connection"); Print("Error Closing Conection."); } this.isConnected= false; } }
algo que me falto ponerle es una prueba de lo que quiero hacer RockPosDBManager rm = new RockPosDBManager(RockPosDBEngine.SQL_DERBY, RockPosTypeConn.ROCKPOS_CLIENT, true); rm.SetDBNameConn(RockPosConstant.DB_PATH+"d1234f"); rm.SetCredential("dbmanager", "dbmanager"); boolean creado = rm.Connect(); if(creado == true) System. out. println("prueba 1Creado"); else{ System. out. println("prueba 1 no Creado"); } String sql = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\'derby.database.defaultConnectionMode\',\'noAccess\')"; creado = rm.Execute(sql); if(creado == true) System. out. println(" prueba 2 Se Ejecuto"); else{ System. out. println(" prueba 2 no sejecuto Creado"); } rm.Disconnect(); rm.SetDBNameConn(RockPosConstant.DB_PATH+"d1234f"); rm.SetCredential("usuario2", "usuario2"); creado = rm.Connect(); if(creado == true) System. out. println("\n\n\n prueba 2 Creado\n"); else{ System. out. println("\n\n\n prueba 2 no Creado\n"); } rm.Disconnect(); rm.SetCredential("dbmanager", "dbmanager"); creado = rm.Connect(); if(creado == true) System. out. println(" prueba 4 prueba pasada "); else{ System. out. println("prueba 4 prueba no pasada"); return; }
|
|
|
10
|
Programación / Programación C/C++ / [ayuda] punteros en linklist
|
en: 14 Octubre 2016, 20:53 pm
|
Buenas a todos !! estoy actualmete aprendiendo a implementar una lista enlazada simple y me gustaria saber como es que los punteros estan trabajando de manerar interna para poder comunicarse, si es algo sencillo en teoria pero tengo una duda que ronda en mi cabeza hace un par de minutos, estoy siguiendo un tutorial y he entendido algunas cosas como que cada nodo (usando una estructura ) tieene un puntero a otro nodo que esta en una "lista" y al final de la lista hay uno que apunta a NULL y para este aproach estoy usando c++ y plantillas , le explico un poco como tengo mi codigo: tengo una clase llamada List esta contiene una estructura Node que contiene el dato T y el link al sugiente elemento de la estructura .... ahora en la clase tengo 2 puntero first y curr estos contienen el dato de la cabeza (Inicio de la estructura) y curr que contiene el frente de la estructura (front ) bien en la funcion siguiente void insert(T f) { Node<T> *temp= new Node<T>(f); if(first == NULL) { first= temp; curr = temp; } else { curr->next=temp; curr = temp; } }
el primer if esta bien pero esta parte en else me hace perderme por ejemeplo void Print(){ if(first == NULL) return; curr = first; while( curr ) { cout << "Value is : "<< curr->date<<endl; curr = curr->next; } }
donde curr = first toma el first pero en la funcion Insert la que se lleno fue curr por que first tiene el link de first, alguien podria explicarme eso por favor. #include <iostream> #include <string.h> using std::cout; using std::string; template<typename T> class List { private: template<class R> struct Node{ R date; Node *next; Node(T t){ date = t; next = NULL; } }; Node<T> *first; Node<T> *curr; public: List(){ first = NULL; curr = NULL; } List(int d) { Node<T> *temp= new Node<T>(d); first = temp; curr = temp; } void insert(T f) { Node<T> *temp= new Node<T>(f); if(first == NULL) { first= temp; curr = temp; } else { curr->next=temp; curr = temp; } } void Print(){ if(first == NULL) return; curr = first; while( curr ) { cout << "Value is : "<< curr->date<<endl; curr = curr->next; } } void DeleteData(int data) { Node<T> *delPtr = NULL; Node<T> *temp = first; curr = first; while(curr != NULL && curr->date != data) { temp = curr; curr = curr->next; } if(curr == NULL) { cout << "this data is not in the list;"; } else { delPtr = curr; curr = curr->next; temp->next = curr; if(delPtr == first) { first = first->next; temp = NULL; } delete delPtr; } } }; int main() { List<int > ls; ls.insert(12); ls.insert(345); ls.insert(345); ls.DeleteData(345); ls.Print(); }
|
|
|
|
|
|
|