How many planets are there in the universe?

[quads id=5]

Translated from my original publication in Spanish

Every time we look at the sky we always see the stars that appear throughout the night, some are planets, others a cluster of stars and others are like our sun, but we always ask ourselves how many stars there are in the universe, but why not? how many planets there will be, and we also wonder, how many have living beings.

There is an equation to calculate the number of existing civilizations, but I will not focus on those aspects, since I am not a mathematician, and in that equation there are many unknown parameters and they are only suppositions, that equation is the Drake equation.

Now we will calculate curious facts by means of basic mathematics, without a scientific method, since it is absurd to do it when we do not have the real parameters, so I will only do some leisure with the data that we know through the observation that has been made of the universe for years.

It is estimated that there are one hundred billion (100,000,000,000) galaxies in the observable universe, from these galaxies there are several classifications in terms of the number of stars that exist in them, ranging from dwarfs, with 107 (10,000,000 ten million), to the giants, with 1012 (1,000,000,000,000 one trillion) but since we do not have an exact figure of how many dwarfs or giants we will take the average number that would be 109, which would be 1,000,000,000, a billon stars per galaxy.

We already have that there are 100,000,000,000 one hundred thousand million galaxies on the Universe of which each galaxy has (1,000,000,000) at least billion stars, so with a multiplication we would have to: 1011 x 109 = 1020 one hundred trillion stars in the universe (100,000,000,000,000,000,000).

Now we will remove the average planets per star, for this I will not get into much trouble; if we suppose that our solar system has 8 planets and 5 dwarf planets (those known until today 24-March-2012, Ceres, Pluto, Haumea, Makemake and Eris) we will take into account that most extrasolar systems that have been detected do not surpass the number of planets in our planetary system, perhaps due to lack of observation, that does not mean that they have less number, but so far is what we know, we will take as a reference half of our planetary system to get the number of planets, by which would have on average 5 planets plus 3 dwarf planets by planetary system, then we would have by a few simple multiplications to remove the planets of the universe:

1020 x 5 = 5020 five hundred trillion planets (500,000,000,000,000,000,000) and

1020 x 3 = 3020 three hundred trillion dwarf planets (300,000,000,000,000,000,000)

So in the universe with the data we know, there are approximately 3020 + 5020 = 8020 eight hundred trillion planets (800,000,000,000,000,000,000).

800 trillion planets of which if we assume that of every 15 one has life (fifteen planets of our solar system and only one has life) then:

8020/15 = 5319 fifty-three trillion habitable planets (53,000,000,000,000,000,000)

Although I do not think that of every 15 there is one alive but the number must be much smaller, but as we see that amount even though the number is huge, maybe there may be life in several satellites but those do not take them into account since the number would grow radically.

In summary:

  • In the universe there are 100,000,000,000 one hundred billion galaxies
  • Of which each galaxy has 1,000,000,000 billion stars
  • This gives us 100,000,000,000,000,000,000 one hundred trillion stars in the universe
  • Of which each star has an average of 8 planets (5 planets and 3 dwarfs)
  • This gives us a total of 800,000,000,000,000,000,000 eight hundred trillion planets in the universe.
  • Of which at best 53,000,000,000,000,000,000 fifty-three trillion planets alive in the universe

This last data is exaggerated but the point of this article is not to be exact, we should also take other factors such as how long a civilization or a planet lives and things like that, but the purpose of this article is to take as a curious fact, that In spite of our planet that seems enormous, the universe is too big, that only when one starts to see things carefully, we begin to see that we are only a grain of sand in this ocean, called the Universe.

As a detail since we are with this number and multiplication, the number of planets that exists approximately in the universe if for each planet we use the measure of a grain of sand (1 millimeter) and put each grain one on another forming a building, our structure would measure close to the width of the Milky Way.

Writted by Hector de Leon Guevara (2012)

 

 

¿Cómo convertir archivo PDF a Docx en C# .Net? – Spire.Pdf vs SautinSoft.PdfFocus

Te muestro como convertir un archivo PDF a un archivo Docx con dos librerías que tienen precio pero hacen su trabajo.

Código del ejemplo:


  class Program
    {
        //ORIGEN PDF
        static string pathPDF = @"C:\AlgunaRuta\archivo.pdf";

        //DESTINOS ARCHIVO DOCX
        static string pathDoc1 = @"C:\AlgunaRuta\archivo-spire.docx";
        static string pathDoc2 = @"C:\AlgunaRuta\archivo-sautin.docx";

        static void Main(string[] args)
        {
            //llamamos para convertir el pdf con spire
            UsandoSpirePdf();

            //llamamos para convertir el pdf con sautinsoft
            UsandoSautin();

        }

        public static void UsandoSpirePdf()
        {

            PdfDocument pdf = new PdfDocument();
            //cargamos el pdf
            pdf.LoadFromFile(pathPDF);

            //guardamos el docx
            pdf.SaveToFile(pathDoc1, FileFormat.DOCX);

            //abrimos el archivo
            System.Diagnostics.Process.Start(pathDoc1);

        }

        public static void UsandoSautin()
        {

            SautinSoft.PdfFocus oPdfFocus = new SautinSoft.PdfFocus();

            //cargamos el pdf
            oPdfFocus.OpenPdf(pathPDF);

            //si se tiene mas de 1 pagina
            if (oPdfFocus.PageCount > 0)
            {
                //asignamos el tipo de documento al que convertiremos
                oPdfFocus.WordOptions.Format = SautinSoft.PdfFocus.CWordOptions.eWordDocument.Docx;

                //guardamos el dox
                int resultado = oPdfFocus.ToWord(pathDoc2);

                if (resultado == 0)
                {
                    //abrimos el documento
                    System.Diagnostics.Process.Start(pathDoc2);
                }
            }
        }
    }

Spire.Pdf: https://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html

SautinSoft.PdfFocus: http://www.sautinsoft.com/products/pdf-focus/

¿Como recorrer una tabla con la instrucción while en SQL?

Te muestro cómo es posible recorrer una tabla por medio de una instrucción while en sql.

En el caso de mysql u otro motor solo remplazar top por su equivalente, por ejemplo en mysql: limit 0,1.

Tabla people

Código utilizado:


insert into @tabla(id,name) select id,name from people

declare @count int = (select count(*) from @tabla)

while @count > 0
begin

	declare @name varchar(max) = (select top(1) name from @tabla order by id)
	declare @id int = (select top(1) id from @tabla order by id)

	print 'Hola '+@name

	delete @tabla where id=@id

	set @count = (select count(*) from @tabla)

end 

¿Cómo liberar el espacio en el archivo .ldf de una base de datos en SQL SERVER?

El archivo .ldf de toda base de datos en sql server sirve para llevar un log de toda consulta hecha en la base de datos (todos los insert, update, select, etc etc).

Esto es útil para regresar en un punto en el tiempo y ver la base de datos como se encontraba en ese punto en su estructura y en sus datos.

Pero qué pasa cuando nuestra base de datos pesa ya un tamaño exagerado y queremos liberar el espacio de nuestro servidor. Optamos por realizar una liberación de este archivo (obviamente después de hacer los backups correspondientes).

A continuación te muestro como se debería hacer para una base de datos llamada PATODB:


ALTER DATABASE PATODB SET RECOVERY SIMPLE

GO

/* el 5 es 5 MB, se dejara el log con un tamaño de 5MB*/
DBCC SHRINKFILE (PATODB_Log, 5)

GO

ALTER DATABASE PATODB SET RECOVERY FULL

GO

Y así de simple liberamos el espacio de nuestro archivo .ldf.

Borrar el cache al subir una imagen y mostrarla en el navegador en MVC .Net #Razor

Cuando hacemos un módulo para actualizar una imagen, ya sea el logotipo o una galería, muchas veces tenemos el problema de que sigue saliendo en el navegador la imagen vieja hasta que borramos el cache del navegador.

Lamentablemente los usuarios no saben que es el cache y esperan ver su imagen nueva, al seguir viendo la imagen vieja, el usuario piensa que no se ha subido con éxito la nueva imagen.

En el caso de Mvc .Net esto re se resuelve con un truco, e igual puede resolverse con su equivalencia en cualquier otro lenguaje de programación.

Para esto vamos a hacer uso de la funcionalidad Random, funcionalidad que existe en todo lenguaje de programación y basta con hacerlo de la siguiente manera, en el caso de MVC .Net lo haremos en razor (en la vista):


@{
    //creamos el objeto random y asignamos a una variable string
    Random r = new Random();
    string a = r.Next().ToString();
}

<img src='http://unsitio.com/unaimagen.jpg?a=@a'>

Al poner una variable con un valor nuevo al final de nuestra url de la imagen, obligamos al navegador a volver a cargarla y no utilizar la que tiene en cache.

Un truco viejo, pero que pocos conocen.

¿Cómo enviar un objeto json en una solicitud Get o Post en C# .Net?

Ahora que estamos en la era de los webservice todos tenemos la necesidad de saber la forma de enviar datos por medio de Get o Post. En C# la forma de hacer una solicitud a un servicio o a un api es muy sencilla y en el siguiente ejemplo te muestro como hacerlo por medio de una clase que yo hice.

La clase siguiente está preparada para enviar cualquier tipo de objeto ya que recibe el tipo de objeto que se enviara y lo serializa en json.

Recuerda que si el objeto tiene referencias circulares, la siguiente clase no funcionara.

Clase:


public class RequestHdeleon

  //esta clase nos sirve para tener control del resultado regresado por la solicitud
  public class Reply
    {
        public Reply()
        {
            this.success = 0;
            message = "";
        }

        public int success { get; set; }
        public object data { get; set; }
        public String menssage { get; set; }

    }

  public Reply Send<T>(string url,T objectRequest, string method="POST"){

            try {
		Reply oReply= new Reply();                

                JavaScriptSerializer js = new JavaScriptSerializer();

		//serializamos el objeto
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(objectRequest);

                //peticion
                WebRequest request = WebRequest.Create(url_callback);
                //headers
                request.Method = method;
                request.PreAuthenticate = true;
                request.ContentType = "application/json;charset=utf-8'";
                request.Timeout = 10000; //esto es opcional

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
                oReply.success = 1;
                //y aquí va nuestra respuesta, la cual es lo que nos regrese el sitio solicitado
                oReply.data = result;
            }catch(Exception e){

                oReply.result = 0;
		//en caso de error lo manejamos en el mensaje
                oReply.menssage = e.Message;

            }

            return oReply;
        }
}

Ejemplo de como utilizarla:


public class UnaClase(){
   public string algo{get;set;}
}

//creamos la clase para enviar los parametros
UnaClase oUnObjeto= new UnaClase();
oUnObjeto.algo="pato feliz";

//Creamos el objeto para solicitud
RequestHdeleon oRequest= new RequestHdeleon();

//primer parametro url
//segundo parametro el objeto
//tercer parametro el metodo: POST, GET, PUT, DELETE
RequestHdeleon.Reply oReply=oRequest.Send<UnaClase>("http://somesite.com/api/somecontroller/",oUnObjeto,"POST");

¿Cómo enviar un valor en ViewBag por RedirectToAction en C# MVC .Net?

Algunas veces tenemos la necesidad de llamar un método por medio de otro, y para ello hacemos uso de RedirectToAction.

RedirectToAction nos sirve para redirigir al usuario a otro controlador o a otro método dependiendo de la lógica de negocio, pero aparte, a veces necesitamos recibir en nuestro elemento destino algún valor para mostrarle al usuario o para realizar alguna validación. Para ello lo primero que se nos viene a la mente es por medio de ViewBag.

Lamentablemente ViewBag no tiene un tiempo de vida más allá del dominio del método, pero podemos apoyarnos de otro diccionario llamado TempData el cual se mantiene en toda la vida de la solicitud HTTP.

A continuación muestro un ejemplo sencillo de cómo quedaría:


public ActionResult Accion1 {
 TempData["mensaje"] = "Un mensaje feliz :)";

 //redirigimos a la Accion2 del mismo controlador
 return RedirectToAction("Action2");

}

public ActionResult Accion2 {

  if(TempData["mensaje"])
     ViewBag.mensaje = TempData["mensaje"].ToString();

  //de esta manera nuestra vista recibiria el ViewBag.mensaje solo cuando TempData no sea null
  return View();
}

¿Cómo obtener una cadena (string) a partir del contenido de un archivo en C# .Net?

En c# es muy fácil obtener una cadena del contenido de un archivo, esto es algo muy útil ya que podemos almacenar información en texto plano en archivos y esta misma obtenerla en cadenas para darle alguna funcionalidad. Por ejemplo un archivo que contenga el cuerpo de un e-mail en .html y así leerlo como string, manipularlo y después enviarlo.

Anexo una clase que tiene un método estático el cual regresa un string a partir de la ruta de un archivo:


 public class Archivo
    {

        public static string GetStringOfFile(string pathFile)
        {
            try
            {
                var contenido = File.ReadAllText(pathFile);

                return contenido;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }

Y así se utiliza:


string ContenidoArchivo= Archivo.GetStringOfFile("Carpeta/otraCarpeta/AlgunArchivo.html");

Funciona con cualquier extensión: .html, .txt, .xml etc etc.

Código de analizador lexicográfico en Visual Basic 6

Escarbando en mi cajón de códigos escolares me encontré algunas cosas que sería bueno compartirlas.

Comparto mi analizador lexicográfico el cual le servirá a más de uno. El código fuente esta hecho en visual basic 6.0 (no es .Net).

El diagrama de estados es el siguiente (diagrama de transición):

Para descargar el código fuente y el .exe den clic aquí.