text:
Q: Groovy String to Date I am coding this with Groovy
I am currently trying to convert a string that I have to a date without having to do anything too tedious.
String theDate = "28/09/2010 16:02:43";
def newdate = new Date().parse("d/M/yyyy H:m:s", theDate)

Output:
Tue Aug 10 16:02:43 PST 2010

The above code works just fine, however when my string changes to something like:
String testDate = "Tue Aug 10 16:02:43 PST 2010"
def newerdate = new Date().parse("d/M/yyyy H:m:s", testDate)

It tells me that "there is no such value for Tue". I tried to throw an 'E' in the parse for the date but it said the date was not able to be parsed.
Can someone explain how I should go about parsing the second example?

A: The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate) for it to work. (Note you don't need to create a new Date object, it's a static method)
If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.

A: Date#parse is deprecated . The alternative is :
java.text.DateFormat#parse

thereFore :
 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

A: Googling around for Groovy ways to "cast" a String to a Date, I came across this article:
http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/
The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asType method. Here is the code from the website.
class Convert {
    private from
    private to

    private Convert(clazz) { from = clazz }
    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

They provide a Convert class that wraps the Groovy complexity, making it trivial to add custom as-based type conversion from any type to any other:
Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.

A: Try this:
def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)

Here are the patterns to format the dates

A: JChronic is your best choice.  Here's an example that adds a .fromString() method to the Date class that parses just about anything you can throw at it:
Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

You can call it like this:
println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")

A: I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy
containing US-locale-constants only (e.g. Sat for Saturdays). Such a
string is generated by the toString method of Date

Example:
println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

A: Below is the way we are going within our developing application.
import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like
Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:
String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.


text:
Q: How do you override "-moz-user-select: none;" on a child element? The question CSS rule to disable text selection highlighting shows how to prevent text selection on an element. Once you have prevented selection, how can you then allow selection for a specific child element?
For example,

some text that cannot be selected

some text that can be selected

some text that cannot be selected

table.no-select {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

td.select {
    -webkit-touch-callout: all !important;
    -webkit-user-select: all !important;
    -khtml-user-select: all !important;
    -moz-user-select: all !important;
    -ms-user-select: all !important;
    user-select: all !important;
}

The .no-select rule above works, but my attempt at a .select rule does not. What is the correct way to do this?

A: Try -moz-user-select: text instead of all.
As a future reference, whenever concerned about the possible values for a CSS rule, check a site like MDN.
Here is the MDN link for user-select.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get no last modified timestamp when I request google people api I want to upgrade my little tool from google contact api to google people api. The authorization is working and I get contacts from peopeService.
But the person.Metadata source item array has only one item type "CONTACT". I do miss the 'updateTime' in person.Metadata.Sources.
The code snipped:
PeopleResource.ConnectionsResource.ListRequest peopleRequest =
   peopleService.People.Connections.List("people/me");

if (pageToken != null)
{
   peopleRequest.PageToken = pageToken;
}

peopleRequest.RequestMaskIncludeField =
   person.names,person.organizations,person.birthdays,person.biographies,
   person.emailAddresses,person.Metadata,person.PhoneNumbers,person.Addresses,
   person.userDefined";
ListConnectionsResponse people = peopleRequest.Execute();

if (people != null && people.Connections != null && people.Connections.Count > 0)
{
   foreach (var person in people.Connections)
   {
      ConvertGooglePerson2ContactItem(person);
   }

   if (people.NextPageToken != null)
   {
      GetAllContactItems(people.NextPageToken);
   }
}

Get Source data:
if (person.Metadata!=null)
foreach (var item in person.Metadata.Sources)
{
...
}

Screenshot of debug session:

Maybe this is an issue with the query parameters Link. But I don't know how to set this query parameter.
-------- added on  Jan 6 '21  as questions of comments --------
I have tried this API: https://developers.google.com/people/api/rest/v1/people.connections/list
With both fields set: personFields and requestMask.includeField:
400 Bad Request
{
  "error": {
    "code": 400,
    "message": "Please specify only one of requestMask or personFields.",
    "status": "INVALID_ARGUMENT"
  }
}

The result of personFields only please see questions.
The metaData with personFields only of person was given:
      "resourceName": "people/c623380167042605258",
      "etag": "%Eg4BAj0FBwk+Cz8MEEA3LhoEAQIFByIMcG9JRnpDRzBxS0U9",
      "metadata": {
        "sources": [
          {
            "type": "CONTACT",
            "id": "8a6b0f5889920ca",
            "etag": "#poIFzCG0qKE=",
            "updateTime": "2021-01-04T22:44:04.913Z"
          }
        ],
        "objectType": "PERSON"
      },

Maybe it's an API problem?
How can I get last modified time of the people contact?

A: The request is solved with this code snippet:
var updateTime = person.Metadata.Sources.FirstOrDefault().UpdateTime;

Be sure using the Google.Apis.PeopleService.v1 Google APIs Client Library in your project.


text:
Q: Mystery... Faked Referrer Generates 500 Instead of 404 Error I hope someone can provide some clues.I have begun receiving
regular 500 errors from a page that does not exist.  Without providing
the entire error page, here are the essentials:
  [Django] ERROR (EXTERNAL IP): Internal Server Error: /sample/

path/calendar.pl
  IOError: request data read error

  'HTTP_REFERER': 'http://mydomain.org/calendar.pl',
  'PATH_INFO': u'/sample/path/calendar.pl',

If I visit the page http://mydomain.org/calendar.pl, I get a 404
error, but the error message referencing the same page generates an
internal server (500) error.
QUESTIONS:
Should I be concerned?
Why do I get a 500 error instead of 404 error?
Any suggestions for troubleshooting?
This has been driving me nuts for a few days.  Any help is very
appreciated.
Thanks

A: Are you trying to change one of the attributes of request, which are read-only (or at least, should be considered to be read-only"). Are you trying to change request.META['HTTP_REFERER']?

A: This is still an open bug which might be resolved in v. 1.6.
In the meantime, though, you can use this workaround in your settings.py file.


text:
Q: ¿Qué es la semántica de movimiento en C++? Bueno, estoy muy interesado en aprender sobre esta nueva característica aparentemente útil, pero se me dificulta porque toda la información de calidad disponible se encuentra en ingles. De igual manera trato de aprender pero mi ingles no es tan bueno que digamos solo llego a comprender algunas cosas. Por eso consulto aquí si alguien podría explicar que es la semántica de movimiento y los detalles que lo acompañan.

A: El problema.
Las semánticas de movimiento son una herramienta que acude en ayuda del programador de C++ para resolver un problema de rendimiento que se lleva arrastrando desde la creación del lenguaje, vamos a ver un ejemplo de código ineficiente:
std::string Quijote("En un lugar de La Mancha de cuyo nombre no quiero acordarme ...");
// Continua durante centenares de miles de caracteres -------------------------> ~~~

std::string TO_UPPER(std::string in)
{
    std::transform(in.begin(), in.end(), in.begin(), std::toupper);
    return in;
}

int main()
{
    std::cout << TO_UPPER(Quijote);
    return 0;
}

Cuando se llama a TO_UPPER se copia la variable Quijote en la variable local de la función in, esta copia es procesada y después se devuelve la copia procesada y esta es a su vez copiada otra vez.
Antes de las semánticas de movimiento en C++ podíamos usar referencias para resolver el problema anterior:
std::string Quijote("En un lugar de La Mancha de cuyo nombre no quiero acordarme ...");
// Continua durante centenares de miles de caracteres -------------------------> ~~~

//          v------- referencia
std::string &TO_UPPER(std::string &in)
// referencia --------------------^
{
    std::transform(in.begin(), in.end(), in.begin(), std::toupper);
    return in;
}

int main()
{
    std::cout << TO_UPPER(Quijote);
    return 0;
}

Usando referencias evitamos hacer copias innecesarias de las variables y mejora el rendimiento del código. Pero las referencias no resuelven todos los problemas:
std::vector<std::string> &read_table(std::string table)
{
    std::vector<std::string> result;
    // fill result...
    return result;
}

int main()
{
    auto customers = read_table("customers");
    return 0;
}

En el código anterior tenemos una referencia colgante ya que la variable result interna de la función read_table deja de existir en el momento en que se sale de la función y por ello, usarla fuera de la función provocará errores... así que volvemos a las socorridas referencias:
//                                  referencia -------------v
void read_table(std::string table, std::vector<std::string> &result)
{
    // fill result...
}

int main()
{
    std::vector<std::string> customers;
    read_table("customers", customers);
    return 0;
}

La solución.
Imagina que en lugar de copiar datos de una función a otra pudiéramos mover estos datos, eso son las semánticas de movimiento.
Las semánticas de movimiento se apoyan en las "Referencia a Valor Derecho" (RvD), que permiten referenciar valores temporales, cosa imposible antes de C++11.
Las Referencias a Valor Derecho usan el declarador && (en el contexto de declaración se corresponde a "Referencia a Valor Derecho" en expresión es el operador AND lógico ).
Pero ¿Qué es una RvD?, un Valor Derecho es todo aquello que tenga capacidad de estar a la derecha de una expresión y generalmente un valor temporal, todas las siguientes expresiones a la derecha del = son Valores Derechos temporales:
const float PI          = 3.14159265359f;
float sqrPi             = std::sqrt(PI);
auto t                  = std::time(nullptr);
auto f                  = t & 1? PI : sqrPi;
std::string hocus_pocus = "Hocus Pocus!";
auto lorem_ipsum        = std::string("Lorem Ipsum!");

Antes de C++11 no se podía referenciar Valores Derechos, pero al añadir las semánticas de movimiento estos valores son referenciables y se pueden sobrecargar funciones para aceptarlos:
std::string hocus_pocus = "Hocus Pocus!";

/* 1 */ void f(std::string &s);  // Funcion que recibe una referencia normal.
/* 2 */ void f(std::string &&s); // Funcion que recibe una RvD.

f(hocus_pocus);                // Llama a la primera sobrecarga.
f("Hocus Pocus!");             // Llama a la segunda sobrecarga.
f(std::string("Lorem Ipsum!"); // Llama a la segunda sobrecarga.

Para objetos que manejan recursos, cuando reciben un valor temporal (un valor que sabemos que va a ser eliminado después de evaluar la expresión) podemos decidir intercambiar el recurso del temporal para evitar operaciones más costosas:

Semánticas de movimiento ¡gratis!.
La librería estándar adapta a partir de C++11 todos sus constructos para sacar provecho de las semánticas de movimiento, así que cambiando a un compilador de C++11 o superior obtenemos estas semánticas sin cambiar el código. ¡Esto generalmente implica una mejora del rendimiento con tan sólo recompilar!
Así que ahora podemos solucionar los problemas que antes teníamos:
// Referencia a Valor Derecho ---vv
std::string TO_UPPER(std::string &&in)
{
    std::transform(in.begin(), in.end(), in.begin(), std::toupper);
    return std::move(in);
 // ~~~~~~~~~~~~~~~~~~~~ <----- mover el valor fuera de la función.
}

Dado que la plantilla std::string de C++11 incorpora las semánticas de movimiento, cuando llamemos a la función TO_UPPER con valores temporales, se moverán los valores ahorrando copias innecesarias. La función std::move transforma un valor en RvD, así que volviendo al ejemplo de funciones sobrecargadas:
std::string hocus_pocus = "Hocus Pocus!";

/* 1 */ void f(std::string &s);  // Funcion que recibe una referencia normal.
/* 2 */ void f(std::string &&s); // Funcion que recibe una RvD.

f(hocus_pocus);                 // Llama a la primera sobrecarga.
f("Hocus Pocus!");              // Llama a la segunda sobrecarga.
f(std::string("Lorem Ipsum!")); // Llama a la segunda sobrecarga.
f(std::move(hocus_pocus));      // Llama a la SEGUNDA sobrecarga.

Es importante remarcar que std::move, pese a recibir el nombre mover, no mueve nada, tan sólo transforma una variable a RvD, así que esta instrucción no mueve nada a ningún lado:
std::string hocus_pocus = "Hocus Pocus!";

std::move(hocus_pocus); // Esto NO HACE NADA de nada.

¿Qué pasa con lo que muevo?
Como hemos visto, std::move transforma de referencia (&) a RvD (&&) y es en realidad la instrucción o constructor que recibe dicha RvD la que realiza la operación de movimiento, pero ¿Qué pasa con los objetos movidos?
std::string hocus_pocus = "Hocus Pocus!"; // Crear objeto

void f(std::string &&s);

f(std::move(hocus_pocus)); // Mover objeto dentro de funcion...

std::cout << hocus_pocus; // Que contiene ahora hocus_pocus?

Según el estándar de C++ , los objetos movidos son válidos aunque su contenido es indeterminado (traducción y resaltado míos):

7.6.5.15 Estado de los tipos de librería movidos
Los objetos con tipos definidos en la librería estándar de C++ pueden ser movidos. Las operaciones de movimiento pueden ser generadas explícitamente o implícitamente. Salvo que se indique lo contrario, estos objetos movidos serán establecidos a un estado válido pero indeterminado.

No es oro todo lo que reluce.
Como casi siempre que se añade una característica nueva, surgen usos incorrectos de la misma, no es conveniente abusar de std::move ya que puede derivar en un empeoramiento del rendimiento al evitar que el compilador aplique optimizaciones, por ejemplo el siguiente código tiene un problema:
std::string Publicar_Quijote()
{
    std::string Quijote("En un lugar de La Mancha de ..."
    return std::move(Quijote);
}

Según el estándar de C++  (traducción y resaltado míos):

« 12.8, 31.1 y 31.3 Copiar y mover objetos »
En una instrucción return en una función, cuando la expresión es el nombre de un objeto, la operación de copiar/mover puede ser omitida construyendo el objeto directamente en el valor de retorno de la función.
Cuando un objeto temporal pueda ser copiado/movido, la operación de copiar/mover puede ser omitida construyendo el objeto temporal directamente en el destino del objeto copiado/movido.

Así que conviene no abusar de las llamadas a std::move pues evitan estas optimizaciones del compilador conocidas como "Optimización del Valor de Retorno" (OvR) (RVO en Inglés ). Vale la pena destacar que la OvR existe en C++ antes que C++11 y no requiere ninguna acción por parte del programador para sacarle provecho.
Más Información.
Puedes ver esta explicación de las semánticas de movimiento en este vídeo (vídeo en Español, texto en Inglés).


text:
Q: Filter array with values from another array Javascript Essentially, I am trying to filter out specific indices that are not in criteria array. Data that I am getting from JSOn file looks like this:
let data = [
        {
            "category": ["business"],
            "title": "some title"
        },
        {
            "category": ["travel", "business"],
            "title": "some title"
        },
        {
            "category": ["sport"],
            "title": "some title"
        },
        {
            "category": ["business", "sport"],
            "title": "some title"
        }
    ]

The array that should filter category of each object from the data above:
var criteria = ["business", "travel"]

I've tried numerous options, the ones that I've listed below are only the ones that either return something or not bring any errors, however, both methods do not bring desired outcome.
const filtered = data.filter((item) =>
   // this returns only first "business" category while ignoring the rest
   criteria.find(element => item.category == element)
)

const filtered = data.filter((item) =>
   // this simply returns all data entries, even the ones that are not in criteria array.
   criteria.filter(element => item.category == element)
)

const filtered = spanishData.filter(function (item) {
    // returns all data entries as well
        return criteria.indexOf(item.category) === -1
    })

How can I filter the data > category array according to the criteria array?
Thank you

A: You can use Array#filter along with Array#some.

let data=[{category:["business"],title:"some title"},{category:["travel","business"],title:"some title"},{category:["sport"],title:"some title"},{category:["business","sport"],title:"some title"}],
criteria=["business","travel"];
let res = data.filter(x => x.category.some(c => criteria.includes(c)));
console.log(res);


text:
Q: Undefined index, android doesn't send data to php code I wrote a program to send JSON from my android device to my server (XAMPP). I tested my PHP code using a form and it received the data correctly.
My app, on the other hand, sends no data to my server. Executing var_dump($_POST) returns array(0) on the server side.
Here's my android code:
public BackGround(Context context){
    this.context=context;
}

@Override
protected String doInBackground(String... params){

    String location_url ="http://192.168.1.90/server_connection.php";
    try{

        URL url1=new URL(location_url);
        HttpURLConnection httpURLConnection =(HttpURLConnection)url1.openConnection();
        httpURLConnection.setRequestMethod("POST");
       // httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        httpURLConnection.setRequestProperty("Accept", "application/json");

        OutputStream stream_upload=httpURLConnection.getOutputStream();
        BufferedWriter buffer_writer=new BufferedWriter(new OutputStreamWriter(stream_upload,"UTF-8"));
        String PostData= URLEncoder.encode(String.valueOf(params));

        buffer_writer.write(PostData);

        buffer_writer.flush();
        buffer_writer.close();
        stream_upload.close();

        int HttpResult = httpURLConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            InputStream stream_dawnload = httpURLConnection.getInputStream();

            BufferedReader bufferreader = new BufferedReader(new InputStreamReader(stream_dawnload, "iso-8859-1"));
            String result = "";
            String line;
            while ((line = bufferreader.readLine()) != null) {
                result += line;
            }
            bufferreader.close();
            stream_upload.flush();
            stream_dawnload.close();
            httpURLConnection.disconnect();

            return result;
        }

    }catch (Exception e){
        e.printStackTrace();
    }

    return null;
}

I send the data with this code where send_json is my JSON object:
backGround.execute(String.valueOf(send_json));

I think the problem is caused by the JSON object not being correctly inserted into the POST request body.
I know there are questions with similar issues but none of the solutions helped me.
I appreciate any help.

A: There are a couple of points here that you should pay attention.
First, as you mentioned, it seems the problem is mainly because your JSON data is not being properly formatted into your request. You are passing the data to what seems to be an AsyncTask with a varargs parameter: doInBackground(String... params). This will transform the String object you passed when calling execute(send_json) into a String[] object. Calling String.valueOf(params) will not return anything resembling the data you initially passed to the AsyncTask but a text representation of a String array that contains your data.
Second, I'd strongly suggest you use a 3rd party library to handle the networking code for you. The code you have to write in order to properly manage an HTTP connection is neither trivial nor concise. There are much better alternatives out there. OkHttp is a great example and I'd highly encourage you to use it.
By the way, I'm not discouraging you from knowing how to create and manage HTTP connections in java/android. You should definitely try to understand what is going on when you send and receive data. I'm just saying that you don't need to handle all that complexity yourself since there are libraries that do a very good job doing exactly that.

A: After reading this question's solution  I edited my code :
first I eliminate backGround.execute(String.valueOf(send_json));from my service   and i sent the vriables as parameters to asyncTask,like below:
backGround.execute(String.valueOf(mylocation.getLatitude()),String.valueOf(mylocation.getLongitude()));

then in asyncTask class I make my json object.
this is my doInbackground's code:
 @Override
protected String doInBackground(String... params){

    String location_url ="http://192.168.1.90/connection.php";

try{
        URL url1=new URL(location_url);

        HttpURLConnection httpURLConnection =(HttpURLConnection)url1.openConnection();

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setRequestProperty("Accept", "application/json");
        httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

        OutputStream stream_upload=httpURLConnection.getOutputStream();
        BufferedWriter buffer_writer=new BufferedWriter(new OutputStreamWriter(stream_upload,"UTF-8"));

    JSONObject obj = new JSONObject();

    try {
        obj.put("Latitude", params[0]);
        obj.put("Longitude", params[1]);

    }catch (JSONException e){
        e.printStackTrace();
    }

    httpURLConnection.connect();

    buffer_writer.write(obj.toString());
    buffer_writer.flush();
    buffer_writer.close();
    stream_upload.close();

        int status = httpURLConnection.getResponseCode();
        if(status ==httpURLConnection.HTTP_OK) {
            InputStream stream_dawnload = httpURLConnection.getInputStream();
            BufferedReader bufferreader = new BufferedReader(new InputStreamReader(stream_dawnload, "iso-8859-1"));
            String result = "";
            String line;
            while ((line = bufferreader.readLine()) != null) {
                result += line;
            }
            bufferreader.close();
            stream_upload.flush();
            stream_dawnload.close();
            httpURLConnection.disconnect();

            return result;
        }

    }catch (Exception e){
        e.printStackTrace();
    }

    return null;

}

and the most important note is that : if u want to send json object to server ,u should add this code :
$json = file_get_contents('php://input');

echo (file_get_contents('php://input'));//for being aware of what is in the object.
 $request = json_decode($json, true);

and for using json's values:
$location_lat=$request['Latitude'];
$location_long=$request['Longitude'];

And one thing else,I tryed $location_lat=$_POST['Latitude'] , and again this error that i asked ,is apeared: Undefined Index.So I resulted for using json objects this method is not correct.
Hope be useful .


text:
Q: How does java GC work if there is no reference variable? I know java GC can destroy an object on the heap if the reference variable that points to the object is manually set to null or set to point to another object:
TestObject test = new TestObject();
test.dosomething();
test = null;

My question is that if I did not give that object a name (reference variable) when I created it, how do I free the memory that object occupies after I'm done with the object:
(new TestObject()).dosomething();

Will this object live on the heap forever before the program ends?

A: After you create the object with new and call the method dosomething() on it there are no references left to it so it becomes eligible for garbage collection.
Even if you create two objects which point to each other with references and they no longer have a connection to the root reference they will become eligible to gc as well (the jvm can detect this circular reference without root connection).
So to answer your question: No that object in your second example will be gc-ed after you call dosomething on it.
Just a note: In practice you don't need to nullyour references (I actually nearly never do it) it is enough if you keep them in local scope so when you leave it the local variables get cleaned up.

A: I'm going to explain this through byte code. First thing to note is that while a reachable reference exists to an object, that object cannot be collected. A important aspect of this is that if a reference value is on the stack in a method's stack frame, the object being referenced is accessible. It therefore cannot be garbage collected.
Compile the following program
public class Example {
    public static void main(String[]args) {
        new Example().sayHello();
    }

    public void sayHello() {}
}

Running javap -c Example will give you something like
  public static void main(java.lang.String[]);
    Code:
      stack=2, locals=1, args_size=1
         0: new           #2                  // class Example
         3: dup
         4: invokespecial #3                  // Method "<init>":()V
         7: invokevirtual #4                  // Method sayHello:()V
        10: return

A index 0, the new byte code instruction, creates a new object and pushes the reference to that object onto the stack. The dup instruction copies that value and pushes it on top of the stack. So you now have two references to that object. invokespecial uses one, invokevirtual uses the other (they pop the reference value they use). Once that is done, there are no more references to the object and it can be garbage collected.
For reference, here are the byte code instructions.


text:
Q: Idempotent ideals in certain commutative rings
Let $R$ be a commutative ring with zero Jacobson radical such that each maximal ideal of $R$ is idempotent. Does it guarantee that each ideal is idempotent?

I know only that if each maximal ideal is generated by an idempotent element then $R$ turns out to be semisimple Artinian. I think this fact is associated with my question, at least if one could show that any maximal ideal is generated by an idempotent element.
Thanks for any suggestion!

A: In a commutative ring $R$ every ideal is idempotent (iff every ideal is radical) iff $R$ is VNR.

Then the question asks if a commutative ring $R$ with $J(R)=0$ and $\mathfrak m^2=\mathfrak m$ for every maximal ideal $\mathfrak m$ is VNR.

The answer is negative: the ring of continuous functions $R=\mathcal C[0,1]$ satisfies both conditions and it's not VNR.

A: The book "Algebra" by "Hungerford", page 437, Corollary 3.5: If $I$ is an ideal in a semisimple left Artinian ring $R$, then $I = Re$, where $e$ is an idempotent which is in the center of $R$.

Edition by OP comment.
 Assuming every maximal ideal is finitely generated, there is a positive answer to the question; see here


text:
Q: Maintaining Structure of Pdf while Extracting Data
I am trying to extract the data from PDF documents using the iText library. I am able to extract PDF document but I am not able to maintain the structure of the PDF file while parsing.
I tried with Apache Tika and pdfbox also but still I am not able to maintain the structure of the file. Code which I tried so far is as follows:
import java.io.PrintWriter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

public class ExtractPageContent {

    public static final String source = "C:/Users/xyz/Test.pdf";

    public static final String dest = "C:/Users/xyz/Test.txt";

    public void parsePdf(String pdf, String txt) throws IOException {
        PdfReader reader = new PdfReader(pdf);
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        PrintWriter out = new PrintWriter(new FileOutputStream(txt));
        TextExtractionStrategy strategy;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            out.println(strategy.getResultantText());
        }
        out.flush();
        out.close();
        reader.close();
    }
    public static void main(String[] args) throws IOException {
        new ExtractPageContent().parsePdf(source, dest);
    }
}

A: Try this.. it worked for me. You need to use PDFBox api. It's the best library to extract text from the pdf document.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public void readText(){
try {
    PDDocument document = null;
    document = PDDocument.load(new File("test.pdf"));
    document.getClass();
    if (!document.isEncrypted()) {
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();
        stripper.setSortByPosition(true);
        PDFTextStripper Tstripper = new PDFTextStripper();
        String st = Tstripper.getText(document);
        System.out.println("Text:" + st);
    }
} catch (Exception e) {
    e.printStackTrace();
}
}


text:
Q: Flutter_Blue Read response from write I do not have the Rep to create a tag for Flutter_Blue. But this uses Flutter_Blue in Android Studio.
I am trying to send commands to a device that my company creates devices and I am developing and Android/IOS application that connects to the devices and sends commands and reads what the device returns.
I have transplanted the example code to find devices and then write to them. I have the following code.
    _writeCharacteristic(BluetoothCharacteristic c) async {

await device.writeCharacteristic(c, [0x076, 0x0d, 0x0a],
    type: CharacteristicWriteType.withResponse);

setState(() {});
}

This sends a v and crlf to a device. How do I read the device response?
Let me know if there is more I need to accomplish this question properly.
I figured it out, See Below

A: I could be wrong but I found the spot that gets the response i'm looking for.
I Added this
String x = "";
        d.forEach((f) => x+=String.fromCharCode(f));

to
_setNotification(BluetoothCharacteristic c) async {
    if (c.isNotifying) {
      await device.setNotifyValue(c, false);
      // Cancel subscription
      valueChangedSubscriptions[c.uuid]?.cancel();
      valueChangedSubscriptions.remove(c.uuid);
    } else {
      await device.setNotifyValue(c, true);
      // ignore: cancel_subscriptions
      final sub = device.onValueChanged(c).listen((d) {
        String x = "";
        d.forEach((f) => x+=String.fromCharCode(f));
        Response = x;
        setState(() {

          print('onValueChanged $x');
        });
      });
      // Add to map
      valueChangedSubscriptions[c.uuid] = sub;
    }
    setState(() {});
  }

and outputs
    onValueChanged DT8610CI-7125


text:
Q: Using Annotation for Authorization Checks in Java I have some methods like the following in my Class:
addOrder(long orderId){...}
updateOrder(long orderId, int qty){...}
deleteOrder(long orderId){...}

I want add Authorization behavior to them. For example:
Only if you are owner of the Order, you can updateOrder.
Only if you are a paid user, you can addOrder.
Only if your Order is in status 'NEW', you can deleteOrder.
What is the best way to do this?
Can we do this using Annotations?
@checkAuthorization
addOrder(long orderId){...}

@checkAuthorization
updateOrder(long orderId, int qty){...}

@checkAuthorization
deleteOrder(long orderId){...}

The checkAuthorization annotation presence should itself result in a call to a custom method that i would implement where i check if this invocations is allowed or not.
If not Annotations, any other best practice?
If it matters this code exists in a web-application (Struts-1).

A: Checks like this could be performed with Aspect Oriented Programming (AOP). A practical implementation is Spring Security. You can also check object permissions with Access Control Lists (ACL) or custom implementations. To do this you can reference parameters with Spring Expression Language:
@PreAuthorize("#c.name == authentication.name")
public void doSomething(@P("c") Contact contact);


text:
Q: Prove that $C_g(x) = gxg^{-1}$ is an isomorphism Let $G$ be a group and $g \in G$. Define $C_g : G \to G$ as $C_g(x) = gxg^{-1}$
Prove that $C_g$ is an isomorphism.
Homomorphism:
$C_g(xy) = gxyg^{-1} = gx(gg^{-1})yg^{-1} = (gxg^{-1})(gyg^{-1}) = C_g(x)C_g(y)$
Injective:
Assume $C_g(x) = C_g(y)$
$$gxg^{-1} = gyg^{-1}$$
Left multiply by $g^{-1}$ and right multiply by $g$ to get $x=y$
Surjective:
Let $C_g(x) = y$ for some $y$.
Therefore, $y = gxg^{-1} \therefore x = g^{-1}yg \in G$ since it is the multiplication of elements of a group and, by closure it is part of a group.
I feel that something is wrong on the part about proving surjectivity.

A: The proof of $C_g$ being a homomorphism is good. In order to show bijectivity it's easier to find the inverse map.
Note that
$$
C_g(C_h(x))=C_g(hxh^{-1})=g(hxh^{-1})g^{-1}=(gh)x(gh)^{-1}=C_{gh}(x)
$$
so that $C_g\circ C_h=C_{gh}$.
Also $C_1$ is the identity map. Thus $C_{g^{-1}}$ is the inverse map of $C_g$.

A: You almost got the surjectivity right, and the idea is exactly the right one.  You are kind of working backwards, which is good, but when writing it down the way you did, it is not really a proof.  The rest looks good.  Let me show you how I would write it down:
Surjectivity means to show that that $\operatorname{im}C_g = G$, or in other words that for any $y \in G$ there exists an $x \in G$ such that $C_g(x) = y$.  Your Ansatz started with a given $y \in \operatorname{im}C_g$, which doesn't help us to show that $\operatorname{im}C_g = G$.
So, to show surjectivity we shall start with some arbitrary $y \in G$.  We then have $ x:= g^{-1}yg \in G$, and we compute $C_g (x) = C_g (g^{-1}yg) = gg^{-1}ygg^{-1} = y$, which shows that $ y \in \operatorname{im}C_g$.  Since $y \in G$ was arbitrary, we have shown that $ \operatorname{im}C_g = G$, in other words we have shown surjectivity.

A: You proof about surjectivity is fine, except for this point: "...Let $C_g(x) = y$ for some $y$....": no, you have to prove that for every $y\in G$ there is some $x\in G$ such that $G_g(x)=y$, which is what you have correctly done.


text:
Q: Unobtrusive validation C# MVC Razor Is it possible to have unobtrusive validation to  make a field required but only if other properties change?
For Example
[Required]
public Decimal Income {get; set;}
[Required]
public Decimal Tax {get; set;}
//Required if tax or income changes
public string ChangeReason {get; set;}

I thought about having multiple backing store fields and writing a Custom Validator to compare these, but wondered if anyone had a better suggestion?

A: It is possible. You can write your own attribute, to do this exactly.

It basically requires two steps:

*

*Write your own attribute, make it inherit ValidationAttribute amd implement IClientValidatable

*Write a Jquery validation adapter to support it

A good working sample is described in this post.
 I used a similar approach to create a dependency validation (one field could have values only if another was filled)

A: Custom Validator is the way to go. I had to build something similar a while back.
I'd set up a hidden value - "Changed" - set it to true whenever the user mods the fields of interest.
Set a RequiredIf validator on the 2 properties of interest:
 [RequiredIf("Changed", true, ErrorMessage = "Required")]

The code for a RequiredIf validator is shown below:
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private RequiredAttribute _innerAttribute = new RequiredAttribute();

    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public RequiredIfAttribute(string dependentProperty, object targetValue)
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get a reference to the property this validation depends upon
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty(this.DependentProperty);

        if (field != null)
        {
            // get the value of the dependent property
            var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

            // compare the value against the target value
            if ((dependentvalue == null && this.TargetValue == null) ||
                (dependentvalue != null && dependentvalue.Equals(this.TargetValue)))
            {
                // match => means we should try validating this field
                if (!_innerAttribute.IsValid(value))
                    // validation failed - return an error
                    return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
            }
        }

        return null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "requiredif",
        };

        string depProp = BuildDependentPropertyId(metadata, context as ViewContext);

        // find the value on the control we depend on;
        // if it's a bool, format it javascript style
        // (the default is True or False!)
        string targetValue = (this.TargetValue ?? "").ToString();
        if (this.TargetValue.GetType() == typeof(bool))
            targetValue = targetValue.ToLower();

        rule.ValidationParameters.Add("dependentproperty", depProp);
        rule.ValidationParameters.Add("targetvalue", targetValue);

        yield return rule;
    }

    private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
    {
        // build the ID of the property
        string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(this.DependentProperty);
        // unfortunately this will have the name of the current field appended to the beginning,
        // because the TemplateInfo's context has had this fieldname appended to it. Instead, we
        // want to get the context as though it was one level higher (i.e. outside the current property,
        // which is the containing object (our Person), and hence the same level as the dependent property.
        var thisField = metadata.PropertyName + "_";
        if (depProp.StartsWith(thisField))
            // strip it off again
            depProp = depProp.Substring(thisField.Length);
        return depProp;
    }
}

Javascript:
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

$.validator.addMethod('requiredif',
function (value, element, parameters) {
    var id = '#' + parameters['dependentproperty'];

    // get the target value (as a string,
    // as that's what actual value will be)
    var targetvalue = parameters['targetvalue'];
    targetvalue =
      (targetvalue == null ? '' : targetvalue).toString();

    // get the actual value of the target control
    // note - this probably needs to cater for more
    // control types, e.g. radios
    var control = $(id);
    var controltype = control.attr('type');
    var actualvalue =
        controltype === 'checkbox' ?
        control.attr('checked').toString() :
        control.val();

    // if the condition is true, reuse the existing
    // required field validator functionality
    if (targetvalue === actualvalue)
        return $.validator.methods.required.call(
          this, value, element, parameters);

    return true;
 }
 );

 $.validator.unobtrusive.adapters.add(
'requiredif',
['dependentproperty', 'targetvalue'],
function (options) {
    options.rules['requiredif'] = {
        dependentproperty: options.params['dependentproperty'],
        targetvalue: options.params['targetvalue']
    };
    options.messages['requiredif'] = options.message;
});


text:
Q: Apply row background based on values in certain column (WPF DataGrid) I have made a tool for database that is showing items with certain filtering options. However after reading some more about WPF and C#. I used this https://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings tutorial to modify my application to deal with ItemCollectionViewSource
I am trying to apply certain background to different rows. I have created Class:
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace Liinos_inspector_FilterTest
{
    class LiinosIDToBackgroundConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
            {
                string LiinosID = "";
                if (LiinosID.Trim().StartsWith("7")) return Brushes.Blue;
                if (LiinosID.Trim().StartsWith("6")) return Brushes.Yellow;
            }
            return Brushes.Red;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

    }
}

Here is XAML part:
    <DataGrid Margin="0,146,0,0" Background="{x:Null}" BorderBrush="{x:Null}"
              CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" IsReadOnly="True"
              HorizontalGridLinesBrush="#FF377A6C" VerticalGridLinesBrush="#FF377A6C"
          DataContext="{StaticResource ItemCollectionViewSource}"
          ItemsSource="{Binding}"
          AutoGenerateColumns="False" FontFamily="Arial Nova" Foreground="White" >
        <!--RowBackground="Transparent"-->

        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow" >
                <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Item.YRNRO, Converter={StaticResource LiinosIDToBackgroundConverter}}" />
            </Style>
        </DataGrid.RowStyle>

Here is XAML for columns:
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding YRNRO}">
                <DataGridTextColumn.Header>
                    <TextBlock Text="LIINOS ID" FontWeight="Bold" TextAlignment="Left"/>
                </DataGridTextColumn.Header>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding HAKUNIMI}">
                <DataGridTextColumn.Header>
                    <TextBlock Text="SEARCH NAME" FontWeight="Bold" TextAlignment="Left"/>
                </DataGridTextColumn.Header>
            </DataGridTextColumn>
        </DataGrid.Columns>

Currently all rows are red as it looks like this is not true if (value is string). Do anyone have any suggestions how this can be fixed?

A: The problem, or one of them anyhow, is your binding.  When you do:
 Value="{Binding RelativeSource={RelativeSource Self}, Path=Item.YRNRO,

It's looking for a property Item on the DataGridRow which has a property YRNRO.
It is more likely you will want to bind to something which is the datacontext of the datagridrow which means you should remove the relativesource binding.
You have a collection of something which is the collectionviewsource. Each row in the datagrid gets a something as datacontext.
Depending on exactly what that is you should use:
   <Setter Property="Background" Value="{Binding YRNRO, Converter={StaticResource LiinosIDToBackgroundConverter}}" />

Or if something has a property called Item which is a complex object with a proprty YNRNO then
   <Setter Property="Background" Value="{Binding Item.YRNRO, Converter={StaticResource LiinosIDToBackgroundConverter}}" />


text:
Q: Make a submit  work outside of  block? I want to place a submit <button> outside of a <form> block. How to make a submit  that can execute method="post" action="/order/setup" from form block`?
<form id="order-form" role="form" method="post" action="/order/setup">
 <input type="text name="first_name" />
</form>

        <button type="submit" class="btn btn-block btn-dark right shadow arrow">Next </button>

A: In browsers that support the new form attribute from HTML 5:
<button form="order-form">…</button>

… but don't. Adjust your design so that form controls are inside the form they are associated with. It doesn't make semantic sense to split them up.

A: $("form#order-form").submit();

http://api.jquery.com/submit/

A: Try something like this, giving your submit button an id of submitButton:

   <button id="submitButton" type="submit" class="btn btn-block btn-dark right shadow arrow">
      Next

   </button>

Then with jQuery:
$("#submitButton").on("click", function () {
   $("form#order-form").submit();
});


text:
Q: How to filter double elements in an object C# Well I have a list which is called employeeList. In the emoloyee Liste there are stored employees with some attributes like id, lastname ...
One of the attributes is Department. Now I want to create Radio Buttons with the Department. As there are more employees per department one department can appear several times but this I'd like to avoid. This is what I already got:
for (int i = 0; i < employeeList.Count(); i++)
{
   panDepartments.Children.Add(new RadioButton() { Content = employeeList.ElementAt(i).Department.Distinct()});
}

A: Just filter the list before you iterate over it. One possibility would be LINQ (i.e. Distinct()) or just do the filtering yourself.

A: I think you can try something like this.
//First of all we need to get unique departments.
var departments = employeeList.Select(e => e.Department).Distinct();

//And after that we can create radio buttons and add them as children elements.
foreach(var dep in departments)
{
    panDepartments.Children.Add(new RadioButton() { Content = dep });
}

//foreach loop can be replaced something like this if "panDepartments.Children"
//supports "AddRange" method
var radioBtns = departments.Select(d => new RadioButton() { Content = dep });
panDepartments.Children.AddRange(radioBtns);


text:
Q: How do I change a LUKS password? I would like to change a LUKS password. I want to remove my old password, but I would like to try out my new password before removing the original. I obviously know the old password. I would like to use the terminal not GUI.
I have sensitive data on the drive and would rather not have to use my backup so I need the method to be safe.

A: In LUKS scheme, you have 8 "slots" for passwords or key files. First, check, which of them are used:
cryptsetup luksDump /dev/<device> |grep BLED

Then you can add, change or delete chosen keys:
cryptsetup luksAddKey /dev/<device> [/path/to/<additionalkeyfile>, optional]

cryptsetup luksChangeKey /dev/<device> -S 6

As for deleting keys, you have 2 options:
a) delete any key that matches your entered password:
cryptsetup luksRemoveKey /dev/<device>

b) delete a key in specified slot:
cryptsetup luksKillSlot /dev/<device> 6


text:
Q: comparing multi dimension arrays I have 2 images and each is partial of a complete image, and the 2 combined could create the complete image.
However there is overlap on the 2 images, and I am trying to create a program that will find where the top row of image2 meets whichever row of pixels in image 1.
I created a for loop to gather each row of pixels per image in an array.
this is my code:
int row = 0;
    for (int i = 0; i < imageArray1.length; i++) {

        for (int j = 0; j < imageArray1[i].length; j++) {
            if (imageArray1[i][j] == (imageArray2[0][0])) {
                row = imageArray1[i][j];
            }
        }

    }

the problem is I am pretty sure I am only gathering a with the individual pixel that is top left of the second image, rather than the whole row.
Any ideas how to get around this?
new to java

A: You need to fix the imageArray2[0][0] so it's always comparing with the first index of imageArray2 only. You need to iterate your imageArray2 along with imageArray1 for full comparison. For this I would suggest you to use a nested for loop for imageArray2.

A: You need to cross check each rows in image1 against each rows in image2. Therefore, 3 levels of looping: 1) loop through the rows in image1 2) loop through the rows in image2 3) loop through the columns in the current row in image1 and image2 to decide if they are overlapping
    int overlappingRowInImage1 = 0;
    int overlappingRowInImage2 = 0;
    int[][] imageArray1 = null;
    int[][] imageArray2 = null;
    // loop through the rows in the first image
    for (int row1 = 0; row1 < imageArray1.length; row1++) {
        boolean foundIdenticalRow = false;
        // loop through the rows in the second image
        for (int row2 = 0; row2 < imageArray2.length; row2++) {
            foundIdenticalRow = true;
            // two rows are identical if each column in both rows are the same
            for (int col = 0; col < imageArray1[row1].length; col++) {
                if (imageArray1[row1][col] != (imageArray2[row2][col])) {
                    foundIdenticalRow = false;
                    break;
                }
            }
            if (foundIdenticalRow) {
                overlappingRowInImage1 = row1;
                overlappingRowInImage2 = row2;
                break;
            }
        }
        if (foundIdenticalRow) {
            System.out.println("Row " + overlappingRowInImage1 + " in image 1 is overlapping with Row " +
                    overlappingRowInImage2 + " in image 2");
            break;
        }
    }


text:
Q: scrapy lazy loader images in scrapy with splash i am abel to scrap only 12 images from scrapy from following website.
'https://www.farfetch.com/fr/shopping/men/shoes-2/items.aspx'.

In the rest of the images src tag is empty. but when I open the browser it shows that there is scr tag.
How do I scrap URL of the all the images?


text:
Q: Windows 10 Authentication Provider Setup Can anybody point out to me how I can enable Windows 10 to display multiple Authentication Providers? For some reason, I am not able to see the "Switch Users" button on the login screen.
I do understand that there are options to change authentication providers in the system registry and gpedit.msc. However, any changes I make seem to not make a difference and the default userid/password login keeps displaying. I can disable the default userid/login but nothing else comes up as a choice if I have it enabled.
Does Windows 10 work like Windows 7 in this regard or is it completely different? I have been able to get it to work on Windows 7...just not 10.
Any feedback, examples, instructions, would be greatly appreciated.


text:
Q: how to download jwplayer streaming video? i subscribe to drupalize.me .but due to my slow internet connection i am not able to see video tutorials properly.i think this site use jwplayer and site provide no downloading option for videos.can anyone tell how to find direct downloading link of streaming video? if anyone give direct downloading link of drupalize.me free sample video it will be great.please help me

A: There is a way that works for me.
In an addition I removed -a vod option because it caused an error.

A: Real player has a browser plugin that does that, (works well only in IE)
Also IDM (internet download manager) does the same (again IE only) I've disable both plugins on chrome after having problems with it.
http://www.internetdownloadmanager.com/
https://www.youtube.com/watch?v=xY_7HRgsw8g
Real Player is free IDM is not (other than the cracked versions on torrent ;) )
IDM allows to select what video stream to download
(if you change resolution on youtube, you'll see 2 files for download, 1 for each resolution)


text:
Q: Java Thread in Multi Threading Hang for ever, without throwing any exception I have a java code to scrap content of a page. At a time i execute 2500 threads and each thread having 100 urls to scrap. All the thread execute successfully but few thread hang for ever without throwing any exception. Using ubuntu as production server.
The code stuck in below line:
InputStream in = urlConnection.getInputStream();

I have doing connection and read time out, that is effective. With few threads even read time out not works and it hangs for ever.
I have tried and failed with many work around.
I have even killed the hanged thread using thread.stop() (Not recommended approach) but the hanged thread tcp connection persists on linux server.
java    7325 root 2675u  IPv4          284078467        0t0       TCP scrapper-new-instance-2.c.quantum-tracker-93805.internal:37068->104.131.210.5:22225 (ESTABLISHED)
java    7325 root 2688u  IPv4          284077787        0t0       TCP scrapper-new-instance-2.c.quantum-tracker-93805.internal:38132->104.131.210.5:22225 (ESTABLISHED)
java    7325 root 2723u  IPv4          284057771        0t0       TCP scrapper-new-instance-2.c.quantum-tracker-93805.internal:43661->104.131.210.5:22225 (ESTABLISHED)

Any one have idea, how i can debug and fix this isse?
Below is the code piece:
    int counter = 0;
    int maxAttempts = (config.getProperty("maxAttempts") != null ? Integer.parseInt(config
                .getProperty("maxAttempts")) : 100);
    Proxy proxy = null;
    while (counter < maxAttempts) {
        try {
            Type proxyType = Proxy.Type.HTTP;
            String proxyIP = "";
            int proxyPort;

            int proxyIndex = getRandomNumber(1, httpProxies.size());

            if(httpProxies.get(proxyIndex).split(":").length == 4){
                proxyIP = httpProxies.get(proxyIndex).split(":")[0];
                proxyPort = Integer.parseInt(httpProxies.get(proxyIndex).split(":")[1]);

                if (httpProxies.get(proxyIndex).split(":").length == 3) {
                    if (httpProxies.get(proxyIndex).split(":")[2].toLowerCase().contains("socks"))
                        proxyType = Proxy.Type.SOCKS;
                }
            }else{
                counter = counter - 1;
                throw new Exception("Escapeing for IP --- "+httpProxies.get(proxyIndex));

            }

            URL url = new URL(urlSring);
            InetSocketAddress inetSocketAddress = new InetSocketAddress(proxyIP, proxyPort);
            proxy = new Proxy(proxyType,inetSocketAddress);

            int userAgentIndex = getRandomNumber(1, userAgents.size());

            logger.info("Attempt = " + counter + " using proxy " + httpProxies.get(proxyIndex) + " (" + proxyType.name()
                        + ") for url " + urlSring);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(proxy);

            if (config.getProperty("connectionTimeoutInMilliSecs") != null)
                urlConnection
                            .setConnectTimeout(Integer.parseInt(config.getProperty("connectionTimeoutInMilliSecs")));
            else
                urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_VALUE);

            if (config.getProperty("readTimeoutInMilliSecs") != null)
                urlConnection.setReadTimeout(Integer.parseInt(config.getProperty("readTimeoutInMilliSecs")));
            else
                urlConnection.setReadTimeout(READ_TIMEOUT_VALUE);

            System.setProperty("http.agent", "");

            urlConnection.setRequestProperty("User-Agent", "");
            urlConnection.setRequestProperty("User-Agent", userAgents.get(userAgentIndex));
            urlConnection.addRequestProperty("Accept-Encoding", "gzip, deflate, br"); // to avoid server returned http response code 403
            urlConnection.setInstanceFollowRedirects(true);

            //Few  Thread hang here for ever
            InputStream in = urlConnection.getInputStream();

            if(null !=  urlConnection.getContentEncoding() && urlConnection.getContentEncoding().equals("gzip")){
                in = new GZIPInputStream(in);
            }

            String output = IOUtils.toString(in, Charset.forName("UTF-8").name());

            logger.info("Proxy Address:-"+proxy.address()+ " HTTP Response Code : " + urlConnection.getResponseCode() + " HTTP Response Message : "
                        + urlConnection.getResponseMessage() + " for url ---" + urlSring);

            logger.info("Success scraping for url --- "+urlSring+ " --- using proxy --- "+httpProxies.get(proxyIndex));
            // Close Input Stream
            if(in != null){
                in.close();
            }

            // Close url connection and release underlying socket if exists.
            if(urlConnection != null){
                urlConnection.disconnect();
            }

            url = null;
            urlConnection = null;
            return output;

        } catch (Exception e) {
            logger.info(e);
            counter++;
            /*
             * logger.info("Exception : " + e.getMessage() + " while using proxy " + proxy.address() +
             * ".Trying next proxy.");
             */

            if (config.getProperty("shouldSleepBetweenRequests") != null
                        && config.getProperty("shouldSleepBetweenRequests").equalsIgnoreCase("true")) {
                Random r = new Random();
                int low = config.getProperty("minSleepTime") != null ? Integer.parseInt(config
                            .getProperty("minSleepTime")) : 0;
                int high = config.getProperty("maxSleepTime") != null ? Integer.parseInt(config
                            .getProperty("maxSleepTime")) : 5;
                int timeToSleep = r.nextInt(high - low) + low;
                logger.info("Sleeping for " + timeToSleep + " seconds ... ");
                try {
                    Thread.sleep(timeToSleep * 1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    if (counter >= maxAttempts)
        logger.info("Stoping after " + maxAttempts + " attempts ...for url "+ urlSring);

    return "";

Please share your idea and let me know how i can fix the issue.
I don't want to kill the hanged thread rather i want to implement some short of Timeout for that scenario if possible.

A: Try using a more sophisticated HTTP client, i.e. with Jetty you can set a timeout for socket connection:
HttpClient httpClient = new HttpClient();
 httpClient.start();

 //socket connection timeout in ms
 httpClient.setConnectTimeout(500)

 // One liner:
 httpClient.GET("http://localhost:8080/").getStatus();

 // Building a request with a timeout for request/response conversation
 ContentResponse response = httpClient.newRequest("http://localhost:8080")
         .timeout(5, TimeUnit.SECONDS)
         .send();


text:
Q: Que función o método debo utilizar para validar información desde la BD Tengo el siguiente inconveniente, un vista con un menú de la cual un link se llama DCER, ese link me trae una vista con un listado de datos que se llama de un controlador y un modelo relacionado a una BD. la cuestión esta es que ese link llamado DCER se muestre siempre y cuando haya información desde la BD sino no se muestre, el paso es lógico con una validación desde el controlador diciendo que si la consulta es null o cero(en este caso se valida con un boolean) pues se muestre la información y el link DCER se muestre.
Pero esa validación se hace siempre y cuando se use el controlador, hay alguna forma o método o función propia de asp que haga el procedimiento anterior desde un principio o inicio de la aplicación, que documentación me puede servir? como debería de hacerlo? muchas gracias.
public Boolean EstacionesDecer()
        {
            //Consultamos si hay datos para DCER.
            var RadicadosEstaciones = _context.RadicadoEstacionDb
                .Include(re => re.Estacion.Depto)
                .Include(re => re.Estacion.Mupio)
                .Where(re => re.Estacion.IdUsuario == _contextListas.getUsuarioPadre(User.getUserId()))
                .Where(re => re.IdProceso == 2 && re.Estacion.TipoEstacion == 1);

            //DCER Menu o Sidebar si hay estaciones para DCER
            int dcer = RadicadosEstaciones.Count();
            Boolean estacionDcer;
            if (dcer != 0)
            { estacionDcer = true; ViewBag.DCER = estacionDcer; }
            else { estacionDcer = false; ViewBag.DCER = estacionDcer; }

            return  estacionDcer;

        }

El anterior es el código desde el controlador, como lo digo solo se ejecuta siempre y cuando sea utilizado, pero se necesita que se renderize o se ejecute desde un inicio de la aplicación. Como este se necesita hacer mas para mostrar mas menú.


text:
Q: Computer gets slow after some time. Sound starts to stutter I'm having a problem with my computer.
After some time using the PC, the sound starts to stutter whenever i watch a video on the browser or in VLC.
It just happen without any reason. I could be browsing the internet and everything is fine, then i leave the computer and when i come back the sound is jerky.
I've tried to check if there was something abnormal on system monitor, but everything seems fine. No high processor or memory usage. No process using to much memory. Nothing.
The only thing that seems to fix it is a restart. Not even a log out will do it.
What do you guys think i could to to diagnose this problem?

A: I also got same error with VLC. I simply change my Player to KMPlayer.
Its working fine with my lap.
You Can download on here or
sudo apt-get install kmplayer

As well as you can check VLC Player Bugs on launchpad.net , askubuntu.com Question and ubuntuforums.org

A: I got the same error with my browser (chrome). I have to use it without gpu sandbox to be more smooth when whatching video.

google-chrome-stable --no-gpu-sandbox

This is not perfect but it's better than nothing. Video are still smooth on firefox by the way.


text:
Q: Python: Dealing with mess txt file I have a txt file like below structure:
Product: 1010
Account    Amount    Date
123                      50$          2019-12-29
Product: 1020
Account    Amount    Date
124                      100$          2019-12-30*

And I'm new to python esp pandas, so I wonder if I could use python to structure the output like:
Product,Account,Amount,Date
1010,123,50%,2019-12-29

Thank you all!

A: Although it's not a regular format, you should be able to read your file line by line, expecting the following format:
Product: (\d+)

If and only if you have a match, then the next line must match this format:
Account    Amount    Date

And then you just need to parse a line of this format:
^(\d+)\s+(\d+\$)\s+(\d+-\d+-\d+)$

Repeat for however long the file is, and from that, you should be able to convert your TXT file to a CSV and load it with the csv module.
Use regular expressions from the re module to validate the format and extract the values.

A: Here's a solution with regular expressions. This assumes that every entry has 4 fields and that the first one is delimited by a colon:
import re
import pandas as pd

content = '''
Product: 1010
Account    Amount    Date
123                      50$          2019-12-29
Product: 1020
Account    Amount    Date
124                      100$          2019-12-30*
'''

pattern = re.compile(r'(\S+):\s*(\S+)\n(\S+)\s+(\S+)\s+(\S+)\n(\S+)\s+(\S+)\s+(\S+)')
df = pd.DataFrame([
    dict(zip([k]+kv[:3], [v]+kv[3:]))
    for k, v, *kv in pattern.findall(content)
])

>>> df
  Product Account Amount         Date
0    1010     123    50$   2019-12-29
1    1020     124   100$  2019-12-30*

A: My assumptions: you know the file structure in advance and IT IS FIXED and you have tabs (\t) as a separators
import pandas as pd
product_columns = ['Product','Account','Amount','Date']
product_data_list = []
fp = open('./data.txt', 'r');
line = fp.readline().strip()
product_id = None

while line:
    if line.find('Product:') == 0:
        product_id = line[9:]
    elif line.find('Account') == -1:
        record_data = line.split('\t')
        account = record_data[0]
        amount = record_data[1]
        date = record_data[2]
        record = {
                        'Product': product_id,
                        'Account': account,
                        'Amount': amount,
                        'Date': date
                        }

        product_data_list.append(record)

    line = fp.readline().strip()

fp.close()
product_data = pd.DataFrame.from_records(product_data_list)
print(product_data)

A: If your file is not formatted neatly for tabular data, you can try this sample below:
import pandas as pd

file = '''
  Product: 1010
  Account    Amount    Date
  123                      50$          2019-12-29
  Product: 1020
  Account    Amount    Date
  124                      100$          2019-12-30*
'''

l = []
place = 0

for i, line in enumerate(file.split()):
  i+1
  if i % 8 == 1:
    l.append([line])
  elif i % 8 == 5 or i % 8 == 6 or i % 8 == 7:
    l[place].append(line)
  if i % 8 == 7:
    place += 1

columns = ['Product', 'Account', 'Amount', 'Date']

df = pd.DataFrame(l, columns=columns)
print(df)

>>>
 Product Account Amount         Date
0    1010     123    50$   2019-12-29
1    1020     124   100$  2019-12-30*

This will get the job done if there are no null values. Using regex might be cleaner too.


text:
Q: How do I send data like an array from an html file to another html page? I want to send an array of values from an html file to another to plot a bar graph on a html page. I do not want to use any sever side languages but I am open to use js,json, jquery and ajax.
The array looks like:
        arrVisitors[0] = "a, 750";
        arrVisitors[1] = "b, 425";
        arrVisitors[2] = "c, 1000";
        arrVisitors[3] = "d, 700";
        arrVisitors[4] = "e, 800";
        arrVisitors[5] = "f, 975";
        arrVisitors[6] = "g, 375";
        arrVisitors[7] = "h, 775";
So how do I store it in the 1st html file and how do I call it in the second file where I am plotting the graph based on the values.

A: You need to send the data as Post-Parameter to the server and use that data when processing the request for the second page.
Since you didn't specify what you want to do exactly, I can't be more precise ...

A: use $_POST['data'] to catch variable and $.post('your.html',{data:$('form').serialize()},function(data){alert(data);})

A: You can use LocalStorage - since it's isolated per domain it will be visible across all the subpages in your domain.

*

*Page A: store the array you need in the localstorage.
localStorage.setItem("name", ['my_array']);

*Page B: listen for changes in the localstorage and act appriopriately when values are updated.
window.addEventListener("storage", my_function, false);
No server-side language involved here. No strange hacks. Just pure HTML5.
http://diveintohtml5.info/storage.html

A: Considering that you have pure HTML files and there is no scripting language in place...
It would be difficult to get and process data passed from one html page in another one..
But you can do this operation using Javascript..
Pass the data with GET method of <form> and try to access that data on another page with the help of javascript. You can get the entire url by
window.location

and then you can use string functions to get all possible values.
Or you can use the local storage utility of html 5.
Check this link


text:
Q: Why foreach creating only one value in array? I create a module for PrestaShop 1.6. I have trouble getting the columns created by this module in the table. I have no idea what might be wrong. '$fields' only takes the last column. '$result' is ok. As if PHP did not create an index.
public function getNewDescriptionFields()
{
    $db = Db::getInstance();
    if(!$db)
        return false;

    $result = $db->ExecuteS('SHOW COLUMNS FROM '. _DB_PREFIX_ .'product_lang');
    if(!$result)
        return false;

    $fields = array();
    foreach($result as $key => $field);
    {
        $fields[] = $field['Field'];
    }

    file_put_contents('/home/www/test4', var_export($fields, true));
    file_put_contents('/home/www/test3', var_export($result, true));
    $fields = preg_grep("/desc([0-9]?[0-9])_(name|text)/", $fields);
    return $fields;
}

From test3 (part):
  19 =>
  array (
    'Field' => 'desc4_text',
    'Type' => 'text',
    'Null' => 'YES',
    'Key' => '',
    'Default' => NULL,
    'Extra' => '',
  ),
  20 =>
  array (
    'Field' => 'desc5_name',
    'Type' => 'varchar(64)',
    'Null' => 'YES',
    'Key' => '',
    'Default' => NULL,
    'Extra' => '',
  ),
  21 =>
  array (
    'Field' => 'desc5_text',
    'Type' => 'text',
    'Null' => 'YES',
    'Key' => '',
    'Default' => NULL,
    'Extra' => '',
  ),
  22 =>
  array (
    'Field' => 'desc6_name',
    'Type' => 'varchar(64)',
    'Null' => 'YES',
    'Key' => '',
    'Default' => NULL,
    'Extra' => '',
  ),
  23 =>
  array (
    'Field' => 'desc6_text',
    'Type' => 'text',
    'Null' => 'YES',
    'Key' => '',
    'Default' => NULL,
    'Extra' => '',

From test3:
array ( 0 => 'desc6_text', )

A: You are using ; at the end of foreach loop and loop body ends up at the first ; so please remove it.
Code should be like this for foreach
foreach($result as $key => $field)
{
  $fields[] = $field['Field'];
}

Demo


text:
Q: Qual ferramenta utilizar para gerar releases em Java? Estou desenvolvendo meu primeiro projeto em Java, a aplicação é uma API utilizando várias bibliotecas, entre elas: Jetty, Hibernate, HttpClient, JasperReport...
Nesse projeto eu utilizo o framework Maven, eu gostaria de saber quais ferramentas utilizar para gerar releases em Java?

A: Alternativamente ao Maven, você pode usar o Gradle. É uma ferramenta que automatiza os Builds e Testes, e é muito simples de trabalhar, e que utiliza o imenso repositório do próprio Maven. Eu comecei a mexer com ela a 2 dias, e estou gostando muito. O arquivo de definição do projeto, o "gradle.build" é muito mais fácil de trabalhar e ler do que o "pom.xml"
Segundo a definição da homepage do Gradle: "... combina o poder e flexibilidade do Ant, com o gerenciamento de dependências e convenções do Maven..."
Mais info:
http://www.gradle.org/

A: Gerar um release é algo bem amplo e envolve muitas coisas. Mas o mais básico pode ser conseguido com o próprio maven, via "release:prepare" e "release:perform". Mais detalhes sobre o plugin "release" podem ser encontrados na documentação oficial.
Com base então nos comentários desta respostas: com o Maven, você especifica o tipo de projeto que você tem (jar, war, ear), e o maven gera o artefato automaticamente via "mvn package". O pacote fica no diretório "target". As bibliotecas que são definidas como dependências "normais" (scope=compile, ou sem escopo definido), são colocadas no pacote final, caso seja um war ou ear. Caso seja um jar, você precisa utilizar um plugin como o "assembly", que vai acabar gerando um grande jar com todas as dependências incluídas.


text:
Q: How to map segmentation fault address to the corresponding C code? I see a segmentation fault like this segfault at 157e8250 ip 157e8250 sp bfa3fdfb how do I map the this address to the corresponding code where the fault occurs?

A: Use the addr2line utility from the GNU binutils suite.  For example, this prints out the filename, line number, and function name (demangling it if it's a C++ function) for the faulting address 0x157e8250:
addr2line -e my_executable_file -C -f 0x157e8250

You can also pass on any number of addresses in the command line, e.g. if you have a stack trace of only instruction addresses.
Make sure you compile your program with the -g compiler option to generate debugging symbols, otherwise addr2line will not be able to symbolicate anything for you.

A: *

*you should add the "-g" option of gcc

*use gnu tool "addr2line", like,
# addr2line -e a.out 0x80484c8 -f

-e: executable file name
-f: generate function name

A: Assuming you have the source code that you can compile. If you compile it with debugging symbols and run it in gdb, it will print you the stack trace with line numbers and other good stuff.

A: I'd suggest using Valgrind.  The usage is:
valgrind <your program name> <command-line arguments to your program>.  If you compile with debug symbols on (use the -g option in gcc) you'll get the exact line number of every level in the stack where the segfault occurred.


text:
Q: Ищет Класс "Redis" как собственный. "Class 'Journal3\Opencart\Redis' not found" В одном из функций класса вызываю $redis = new Redis().
namespace Journal3\Opencart;
use Journal3\Utils\Arr;
class Controller extends \Controller implements Autocomplete {}

Но ищется он как свой, не находится и выдаёт ошибку Fatal error: Class 'Journal3\Opencart\Redis' not found. Хотя Redis подключён и в контексте другого класса вызывается и работает.


text:
Q: Weka, SimpleKMeans cannot handle string attributes I am using Weka in Scala (although the syntax is virtually identical to Java).  I am trying to evaluate my data with a SimpleKMeans clusterer, but the clusterer won't accept string data.  I don't want to cluster on the string data; I just want to use it to label the points.
Here is the data I am using:
@relation Locations
@attribute ID string
@attribute Latitude numeric
@attribute Longitude numeric
@data
'Carnegie Mellon University', 40.443064, -79.944163
'Stanford University', 37.427539, -122.170169
'Massachusetts Institute of Technology', 42.358866, -71.093823
'University of California Berkeley', 37.872166, -122.259444
'University of Washington', 47.65601, -122.30934
'University of Illinois Urbana Champaign', 40.091022, -88.229992
'University of Southern California', 34.019372, -118.28611
'University of California San Diego', 32.881494, -117.243079

As you can see, it's essentially a collection of points on an x and y coordinate plane.  The value of any patterns is negligible; this is simply an exercise in working with Weka.
Here is the code that is giving me trouble:
val instance = new Instances(new StringReader(wekaHeader + wekaData))

val simpleKMeans = new SimpleKMeans()
simpleKMeans.buildClusterer(instance)

val eval = new ClusterEvaluation()
eval.setClusterer(simpleKMeans)
eval.evaluateClusterer(new Instances(instance))

Logger.info(eval.clusterResultsToString)

I get the following error on simpleKMeans.buildClusterer(instance):
[UnsupportedAttributeTypeException: weka.clusterers.SimpleKMeans: Cannot handle string attributes!]
How do I get Weka to retain IDs while doing clustering?

Here are a couple of other steps I have taken to troubleshoot this:
I used the Weka Explorer and loaded this data as a CSV:
ID, Latitude, Longitude
'Carnegie Mellon University', 40.443064, -79.944163
'Stanford University', 37.427539, -122.170169
'Massachusetts Institute of Technology', 42.358866, -71.093823
'University of California Berkeley', 37.872166, -122.259444
'University of Washington', 47.65601, -122.30934
'University of Illinois Urbana Champaign', 40.091022, -88.229992
'University of Southern California', 34.019372, -118.28611
'University of California San Diego', 32.881494, -117.243079

This does what I want it to do in the Weka Explorer.  Weka clusters the points and retains the ID column to identify each point.  I would do this in my code, but I'm trying to do this without generating additional files.  As you can see from the Weka Java API, Instances interprets a java.io.Reader only as an ARFF.
I have also tried the following code:
val instance = new Instances(new StringReader(wekaHeader + wekaData))
instance.deleteAttributeAt(0)

val simpleKMeans = new SimpleKMeans()
simpleKMeans.buildClusterer(instance)

val eval = new ClusterEvaluation()
eval.setClusterer(simpleKMeans)
eval.evaluateClusterer(new Instances(instance))

Logger.info(eval.clusterResultsToString)

This works in my code, and displays results.  That proves that Weka is working in general, but since I am deleting the ID attribute, I can't really map the clustered points back on the original values.

A: I am answering my own question, and in doing so, there are two issues that I would like to address:

*

*Why CSV works with string values

*How to get cluster information from the cluster evaluation

As Sentry points out in the comments, the ID does in fact get converted to a nominal attribute when loaded from a CSV.
If the data must be in an ARFF format (like in my example where the Instances object is created from a StringReader), then the StringToNominal filter can be applied:
  val instances = new Instances(new StringReader(wekaHeader + wekaData))

  val filter = new StringToNominal()
  filter.setAttributeRange("first")
  filter.setInputFormat(instances)

  val filteredInstance = Filter.useFilter(instances, filter)

  val simpleKMeans = new SimpleKMeans()
  simpleKMeans.buildClusterer(instance)
  ...

This allows for "string" values to be used in clustering, although it's really just treated as a nominal value.  It doesn't impact the clustering (if the ID is unique), but it doesn't contribute to the evaluation as I had hoped, which brings me to the next issue.

I was hoping to be able to get a nice map of cluster and data, like cluster: Int -> Array[(ID, latitude, longitude)] or ID -> cluster: Int.  However, the cluster results are not that convenient.  In my experience these past few days, there are two approaches that can be used to find the cluster of each point of data.
To get the cluster assignments, simpleKMeans.getAssignments returns an array of integers that is the cluster assignments for each data element.  The array of integers is in the same order as the original data items and has to be manually related back to the original data items.  This can be easily accomplished in Scala by using the zip method on the original list of data items and then using other methods like groupBy or map to get the collection in your favorite format.  Keep in mind that this method alone does not use the ID attribute at all, and the ID attribute could be omitted from the data points entirely.
However, you can also get the cluster centers with simpleKMeans.getClusterCentroids or eval.clusterResultsToString().  I have not used this very much, but it does seem to me that the ID attribute can be recovered from the cluster centers here.  As far as I can tell, this is the only situation in which the ID data can be utilized or recovered from the cluster evaluation.

A: I got the same error while having String value in one of the line in a CSV file with couple of million rows. Here is how I figured out which line has string value.
Exception "Cannot handle string attributes!" doesn't give any clue about the line number. Hence:

*

*I imported CSV file into Weka Explorer GUI and created a *.arff file.

*Then manually changed type from string to numeric in the *.arrf file at the beginning as show below.

*After that I tried to build the cluster using the *.arff file.

*I got the exact line number as part of exception

*I removed the line from *.arff file and loaded again. It worked without any issue.

Converted string --> numeric in *.arff file
@attribute total numeric
@attribute avgDailyMB numeric
@attribute mccMncCount numeric
@attribute operatorCount numeric
@attribute authSuccessRate numeric
@attribute totalMonthlyRequets numeric
@attribute tokenCount numeric
@attribute osVersionCount numeric
@attribute totalAuthUserIds numeric
@attribute makeCount numeric
@attribute modelCount numeric
@attribute maxDailyRequests numeric
@attribute avgDailyRequests numeric

Error reported the exact line number
java.io.IOException: number expected, read Token[value.total], line 1750464
    at weka.core.converters.ArffLoader$ArffReader.errorMessage(ArffLoader.java:354)
    at weka.core.converters.ArffLoader$ArffReader.getInstanceFull(ArffLoader.java:728)
    at weka.core.converters.ArffLoader$ArffReader.getInstance(ArffLoader.java:545)
    at weka.core.converters.ArffLoader$ArffReader.readInstance(ArffLoader.java:514)
    at weka.core.converters.ArffLoader$ArffReader.readInstance(ArffLoader.java:500)
    at weka.core.Instances.<init>(Instances.java:138)
    at com.lokendra.dissertation.ModelingUtils.kMeans(ModelingUtils.java:50)
    at com.lokendra.dissertation.ModelingUtils.main(ModelingUtils.java:28)


text:
Q: Firebase Admin SDK configured to access wrong app Hopefully this isn't too similar to another question I posted. I am trying to read/write to my app's database from Firebase Functions using the Admin SDK. Been having issues.
Here is the function:
exports.createAssetMux = functions.https.onCall((data, context) => {

    console.log('data: ', data)

    return admin.firestore().collection('users').doc(data.id).get()
    .then((doc) => {
        console.log('firestore document: ', doc)
        return {data: 'success'}
    }).catch(error => {
        console.log('error message: ', error)
        return {data: 'there was an issue'}
    });

});

And here is the response:
firestore document:  DocumentSnapshot {
>    _fieldsProto: undefined,
>    _ref: DocumentReference {
>      _firestore: Firestore {
>        _settings: [Object],
>        _settingsFrozen: true,
>        _serializer: [Serializer],
>        _projectId: 'live-from-868ea',
>        registeredListenersCount: 0,
>        _lastSuccessfulRequest: 1590544300258,
>        _backoffSettings: [Object],
>        _preferTransactions: false,
>        _clientPool: [ClientPool]
>      },
>      _path: ResourcePath { segments: [Array] },
>      _converter: {
>        toFirestore: [Function: toFirestore],
>        fromFirestore: [Function: fromFirestore]
>      }
>    },
>    _serializer: Serializer { createReference: [Function (anonymous)] },
>    _readTime: Timestamp { _seconds: 1590544300, _nanoseconds: 250711000 },
>    _createTime: undefined,
>    _updateTime: undefined
>  }

When I try to write to the db, or update anything, this is the response I get:
error message:  Error: 5 NOT_FOUND: no entity to update: app: "dev~my-firestore"
path <
  Element {
    type: "users"
    name: "kPuVNXsFFIyhs3Qad06B"
  }
>

  code: 5,
  details: 'no entity to update: app: "dev~my-firestore"\n' +
    'path <\n' +
    '  Element {\n' +
    '    type: "users"\n' +
    '    name: "kPuVNXsFFIyhs3Qad06B"\n' +
    '  }\n' +
    '>\n',
  metadata: Metadata {
    internalRepr: Map(1) { 'content-type' => [Array] },
    options: {}
  }
}

Note: My actual app name has been replaced with my-firestore, but I think the issue is with the dev~ part before it, that part I left in place. Do I need to change some config setting? I've  checked in every config file I have and none of them contain the dev~ part.

A: I was running firebase emulators:start which was starting up a dev db. It seems obvious now. Running firebase serve --only functions was the workaround I used if I didn't want to fuss with the emulators. It does connect right to your production db, so be careful.


text:
Q: Why is my data only showing up sometimes in CloudKit? I made an app that is supposed to upload a term and an answer from an array of tuples, however, it will only show up sometimes in cloudKit. Sometimes it will upload 3 sets of terms and answers, but then other times it will only upload one set of terms and answers. Is it possible that I am overwriting the Cloudkit data rather than appending it?
Thanks in advance
Heres my code:
let term = termTextField.text!
let answer = answerTextField.text!
termAnswer.append((term,answer))
print(termAnswer.self)
let newTA = CKRecord(recordType: "Terms")

newTA["answers"] = answer as CKRecordValue?
var publicData = CKContainer.default().publicCloudDatabase
publicData.save(newTA, completionHandler: {(record, error) -> Void in
    if error == nil{
        print("TA Saved")
    }
    else{
        print("Not Saved")
    }
})

newTA["terms"] = term as CKRecordValue?
publicData = CKContainer.default().publicCloudDatabase
publicData.save(newTA, completionHandler: {(record, error) -> Void in
        if error == nil{
            print("TA Saved")
        }
        else{
            print("Not Saved")

        }
    })


text:
Q: Construct a master curve from data I will try to be as informative as possible.
Clear["Global`*"]

I have the following data
data91 = {{-0.209091`, 2.89296`}, {0.281818`, 2.92958`}, {0.8`,
    2.97535`}, {1.28182`, 3.03028`}, {1.8`, 3.07606`}, {2.28182`,
    3.11268`}, {2.5`, 3.1493`}, {2.8`, 3.18592`}};

data88 = {{-0.2`, 2.74648`}, {0.272727`, 2.79225`}, {0.8`,
    2.83803`}, {1.27273`, 2.8838`}, {1.80909`, 2.92958`}, {2.28182`,
    2.95704`}, {2.50909`, 2.99366`}, {2.8`, 3.03028`}};

data85 = {{-0.209091`, 2.58169`}, {0.272727`, 2.63662`}, {0.790909`,
    2.69155`}, {1.27273`, 2.74648`}, {1.8`, 2.77394`}, {2.28182`,
    2.81972`}, {2.50909`, 2.82887`}, {2.8`, 2.87465`}};

data82 = {{-0.2`, 2.43521`}, {0.281818`, 2.49014`}, {0.8`,
    2.55423`}, {1.27273`, 2.59085`}, {1.8`, 2.63662`}, {2.28182`,
    2.66408`}, {2.50909`, 2.69155`}, {2.8`, 2.71901`}};

data79 = {{-0.2`, 2.27958`}, {0.281818`, 2.33451`}, {0.790909`,
    2.38944`}, {1.27273`, 2.43521`}, {1.80909`, 2.48099`}, {2.28182`,
    2.50845`}, {2.5`, 2.52676`}, {2.81818`, 2.56338`}};

data76 = {{-0.2`, 2.07817`}, {0.272727`, 2.14225`}, {0.790909`,
    2.21549`}, {1.28182`, 2.27042`}, {1.80909`, 2.30704`}, {2.27273`,
    2.36197`}, {2.5`, 2.37113`}, {2.8`, 2.40775`}};

data73 = {{-0.2`, 1.83099`}, {0.272727`, 1.93169`}, {0.790909`,
    2.01408`}, {1.28182`, 2.07817`}, {1.80909`, 2.14225`}, {2.29091`,
    2.16972`}, {2.50909`, 2.20634`}, {2.80909`, 2.2338`}};

data70 = {{-0.2`, 1.54718`}, {0.281818`, 1.65704`}, {0.8`,
    1.77606`}, {1.29091`, 1.84014`}, {1.8`, 1.92254`}, {2.29091`,
    1.97746`}, {2.50909`, 1.99577`}, {2.80909`, 2.03239`}};

data67 = {{-0.2`, 1.21761`}, {0.281818`, 1.32746`}, {0.8`,
    1.47394`}, {1.27273`, 1.57465`}, {1.80909`, 1.6662`}, {2.28182`,
    1.72113`}, {2.50909`, 1.7669`}, {2.80909`, 1.80352`}};

data64 = {{-0.2`, 0.869718`}, {0.263636`, 1.0162`}, {0.781818`,
    1.15352`}, {1.29091`, 1.26338`}, {1.80909`, 1.39155`}, {2.29091`,
    1.46479`}, {2.5`, 1.51972`}, {2.80909`, 1.55634`}};

data61 = {{-0.2`, 0.622535`}, {0.272727`, 0.714085`}, {0.809091`,
    0.851408`}, {1.28182`, 0.988732`}, {1.79091`, 1.09859`}, {2.28182`,
    1.21761`}, {2.5`, 1.25423`}, {2.81818`, 1.3`}};

data58 = {{-0.209091`, 0.411972`}, {0.272727`, 0.494366`}, {0.8`,
    0.63169`}, {1.28182`, 0.723239`}, {1.80909`, 0.851408`}, {2.3`,
    0.961268`}, {2.5`, 1.02535`}, {2.80909`, 1.07113`}};

data55 = {{-0.209091`, 0.265493`}, {0.281818`, 0.338732`}, {0.8`,
    0.430282`}, {1.28182`, 0.521831`}, {1.8`, 0.640845`}, {2.28182`,
    0.759859`}, {2.50909`, 0.796479`}, {2.80909`, 0.860563`}};

data52 = {{-0.209091`, 0.183099`}, {0.281818`, 0.219718`}, {0.790909`,
    0.292958`}, {1.28182`, 0.375352`}, {1.80909`, 0.466901`}, {2.28182`,
    0.576761`}, {2.49091`, 0.61338`}, {2.80909`, 0.677465`}};

data49 = {{-0.209091`, 0.109859`}, {0.272727`, 0.146479`}, {0.8`,
    0.201408`}, {1.28182`, 0.256338`}, {1.80909`, 0.338732`}, {2.28182`,
    0.430282`}, {2.50909`, 0.466901`}, {2.8`, 0.521831`}};

Here is their visualization:
    temps = -{91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49};
    ListLinePlot[{data91, data88, data85, data82, data79, data76, data73,
data70, data67, data64, data61, data58, data55, data52, data49}, Frame -> True,
     PlotRangePadding -> Scaled[0.1], Axes -> False,
     PlotMarkers -> {{\[EmptyCircle], Medium}},
     PlotStyle -> Map[ColorData[{"Rainbow", {-91, -49}}], temps],
     PlotLegends -> Quantity[temps, "DegreesCelsius"], ImageSize -> 600,
     FrameLabel -> {"log\[Omega]", "E'(\!\(\*SubscriptBox[\(T\), \(0\)]\)/T)"},
     FrameStyle -> Directive[14], RotateLabel -> False]

-61oC is chosen as the reference temperature. What I want now is to shift horizontally the points of the other temperatures in order to construct a "master" curve at -61oC which spans a bigger range of log\[Omega] values. I can do this manually as follows
data49shift = data49 /. {x_, y_} -> {x - 3.5, y};
data52shift = data52 /. {x_, y_} -> {x - 2.8, y};
data55shift = data55 /. {x_, y_} -> {x - 2, y};
data58shift = data58 /. {x_, y_} -> {x - 1, y};
data64shift = data64 /. {x_, y_} -> {x + 1.2, y};
data67shift = data67 /. {x_, y_} -> {x + 2.5, y};
data70shift = data70 /. {x_, y_} -> {x + 4.1, y};
data73shift = data73 /. {x_, y_} -> {x + 5.8, y};
data76shift = data76 /. {x_, y_} -> {x + 7.4, y};
data79shift = data79 /. {x_, y_} -> {x + 8.9, y};
data82shift = data82 /. {x_, y_} -> {x + 10.6, y};
data85shift = data85 /. {x_, y_} -> {x + 12.2, y};
data88shift = data88 /. {x_, y_} -> {x + 14., y};
data91shift = data91 /. {x_, y_} -> {x + 15.7, y};

and the result is
ListLinePlot[{data91shift, data88shift, data85shift, data82shift,
  data79shift, data76shift, data73shift, data70shift, data67shift,
  data64shift, data61, data58shift, data55shift, data52shift,
  data49shift}, Frame -> True, PlotRangePadding -> Scaled[0.1],
 Axes -> False, PlotMarkers -> {{\[EmptyCircle], Medium}},
 PlotStyle -> Map[ColorData[{"Rainbow", {-91, -49}}], temps],
 PlotLegends -> Quantity[temps, "DegreesCelsius"], ImageSize -> 600,
 FrameLabel -> {"log\[Omega]",
   "E'(\!\(\*SubscriptBox[\(T\), \(0\)]\)/T)"},
 FrameStyle -> Directive[14], RotateLabel -> False]

The article that I follow says that the authors made the horizontal shifting in OriginPro but they do not provide any further information. Since I do not have OriginPro I am trying to develop a less manual procedure in Mathematica.
Any ideas?
The algorithm should be such, that given two sets of data (the one of the reference temperature and the one to be shifted) it will make the horizontal shifting and return the horizontal shift factor for the best possible shifting.
E.g. for data91 it will evaluate a value close to 15.7 that I found with the eye.
Thank you very much.

A: Let's first make interpolations of the data:
data = {data91, data88, data85, data82, data79, data76, data73,
   data70, data67, data64, data61, data58, data55, data52, data49};

ints = Interpolation /@ data;

Now define a routine that shifts the curves in the set above the 61 deg curve so that their left-most point touches the next curve (recursively, so that previous shifts are taken care of). For the curves below the 61 deg curve shift such that the right-most point touches its neighbor.
ClearAll[sol]
master = 11; (* position of the reference curve in the data list *)
sol[i_ /; i < master] :=
 sol[i] = m /.
   Last@NMinimize[
         {
          EuclideanDistance[
            {data[[i, 1, 1]] + m, ints[[i]][data[[i, 1, 1]]]},
            {k + sol[i + 1]     , ints[[i + 1]][k]          }
          ],
          data[[i + 1, 1, 1]] <= k <= data[[i + 1, -1, 1]]
        }, {{m, 0.1, 0.8}, {k, 0.1, 0.2}}
       ]
sol[i_ /; i > master] :=
 sol[i] = m /.
   Last@NMinimize[
          {
            EuclideanDistance[
              {data[[i, -1, 1]] + m, ints[[i]][data[[i, -1, 1]]]},
              {k + sol[i - 1]      , ints[[i - 1]][k]           }
            ],
            data[[i - 1, 1, 1]] <= k <= data[[i - 1, -1, 1]]
          }, {{m, 0.1, 0.8}, {k, 0.1, 0.2}}
        ]
sol[master] = 0;

Calculate all shifts:
shifts = sol /@ Range[Length@data]
(* {14.0704, 12.49, 11.0173, 9.66209, 8.18936, 6.57826, \
5.09644, 3.68002, 2.3482, 1.0713, 0, -1.14927, -2.02456, -2.89625, \
-3.65812} *)

Apply shifts:
dataShift = MapIndexed[Function[v, {#1, 0} + v] /@ data[[#2[[1]]]] &, shifts];

And plot:
temps = -{91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49};

ListLinePlot[dataShift, Frame -> True,
 PlotRangePadding -> Scaled[0.1], Axes -> False,
 PlotMarkers -> {{○, Medium}},
 PlotStyle -> Map[ColorData[{"Rainbow", {-91, -49}}], temps],
 PlotLegends -> Quantity[temps, "DegreesCelsius"], ImageSize -> 600,
 FrameLabel -> {"logω",
   "E'(\!\(\*SubscriptBox[\(T\), \(0\)]\)/T)"},
 FrameStyle -> Directive[14], RotateLabel -> False]

A: As Sjoerd treacherously spoiled my answer I'm posting an interpolation (slower) version that spans a 10% larger domain:

Edit
The following replacement in the code below serves the same function and is much faster, but it exploits a geometric symmetry of your particular curves:
bestShift[{d1_List, d2_List}] :=(x /. FindRoot[superpos[d1, d2, x], {x, -1, -2, 0},
    AccuracyGoal -> 3])

data = {data91, data88, data85, data82, data79, data76, data73,
   data70, data67, data64, data61, data58, data55, data52, data49};

dataS = SortBy[data, #[[1, 2]] &];
Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];
superpos[d1_, d2_, x_?NumericQ] :=
 Module[{f1 = Interpolation@d1, f2 = Interpolation[{x, 0} + # & /@ d2], dom},
  dom = IntervalIntersection @@ ((Interval @@
                     InterpolatingFunctionDomain[#]) & /@ {f1, f2}) // First;
  Abs@NIntegrate[f1@y - f2@y, {y, dom[[1]], dom[[2]]}]
  ]

(* replace with the function in the edit above *)
bestShift[{d1_List, d2_List}] := (x /.
                      Last@NMinimize[{superpos[d1, d2, x], -2 <= x <= 0}, x,
                             AccuracyGoal -> 3, Method -> "SimulatedAnnealing"])

bs = bestShift /@ Partition[data, 2, 1]

(* we want data[[11]] not shifted *)

accBs = # - #[[11]] &@Join[{0}, Accumulate@bs]
(*
 {16.0986, 14.5014, 12.818, 11.1625, 9.38324, 7.5946, 5.87548,
  4.19353, 2.58556, 1.19733, 0., -1.03404, -1.93369, -2.7309, -3.44727}
*)
MapThread[Function[{d, s}, {s, 0} + # & /@ d], {data, accBs}, 1] // ListLinePlot

Then you can build a smooth interpolating function:
pts = Sort[Join @@ MapThread[Function[{d, s}, {s, 0} + # & /@ d], {data, accBs}, 1]];
smooth = Transpose[GaussianFilter[#, 5] & /@ Transpose@pts];
f = Interpolation[smooth];
dom = First@InterpolatingFunctionDomain@f;
Plot[f@x, {x, dom[[1]], dom[[2]]}]