text:
Q: Generics in c# & accessing the static members of T My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:
Class test<T>{
     int method1(Obj Parameter1){
         //in here I want to do something which I would explain as
         T.TryParse(Parameter1);

         //my problem is that it does not work ... I get an error.
         //just to explain: if I declare test<int> (with type Integer)
         //I want my sample code to call int.TryParse(). If it were String
         //it should have been String.TryParse()
     }
}

So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!

Edit: Thank you all for your answers!
Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.
This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)

Though if you have some other suggestion I am still waiting (and willing to participate)

A: The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that the type passed into your class will have that function.  Unless you can contrain T in some way, you'll run into this a lot.
Constraints on Type Parameters

A: To access a member of a specific class or interface you need to use the Where keyword and specify the interface or base class that has the method.
In the above instance TryParse does not come from an interface or base class, so what you are trying to do above is not possible. Best just use Convert.ChangeType and a try/catch statement.
class test<T>
{
    T Method(object P)
    {
       try {
           return (T)Convert.ChangeType(P, typeof(T));
       } catch(Exception e) {
           return null;
       }
    }
}

A: Short answer, you can't.
Long answer, you can cheat:
public class Example
{
    internal static class Support
    {
        private delegate bool GenericParser<T>(string s, out T o);
        private static Dictionary<Type, object> parsers =
            MakeStandardParsers();
        private static Dictionary<Type, object> MakeStandardParsers()
        {
            Dictionary<Type, object> d = new Dictionary<Type, object>();
            // You need to add an entry for every type you want to cope with.
            d[typeof(int)] = new GenericParser<int>(int.TryParse);
            d[typeof(long)] = new GenericParser<long>(long.TryParse);
            d[typeof(float)] = new GenericParser<float>(float.TryParse);
            return d;
        }
        public static bool TryParse<T>(string s, out T result)
        {
            return ((GenericParser<T>)parsers[typeof(T)])(s, out result);
        }
    }
    public class Test<T>
    {
        public static T method1(string s)
        {
            T value;
            bool success = Support.TryParse(s, out value);
            return value;
        }
    }
    public static void Main()
    {
        Console.WriteLine(Test<int>.method1("23"));
        Console.WriteLine(Test<float>.method1("23.4"));
        Console.WriteLine(Test<long>.method1("99999999999999"));
        Console.ReadLine();
    }
}

I made a static dictionary holding a delegate for the TryParse method of every type I might want to use. I then wrote a generic method to look up the dictionary and pass on the call to the appropriate delegate. Since every delegate has a different type, I just store them as object references and cast them back to the appropriate generic type when I retrieve them. Note that for the sake of a simple example I have omitted error checking, such as to check whether we have an entry in the dictionary for the given type.

A: One more way to do it, this time some reflection in the mix:
static class Parser
{
    public static bool TryParse<TType>( string str, out TType x )
    {
        // Get the type on that TryParse shall be called
        Type objType = typeof( TType );

        // Enumerate the methods of TType
        foreach( MethodInfo mi in objType.GetMethods() )
        {
            if( mi.Name == "TryParse" )
            {
                // We found a TryParse method, check for the 2-parameter-signature
                ParameterInfo[] pi = mi.GetParameters();
                if( pi.Length == 2 ) // Find TryParse( String, TType )
                {
                    // Build a parameter list for the call
                    object[] paramList = new object[2] { str, default( TType ) };

                    // Invoke the static method
                    object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList );

                    // Get the output value from the parameter list
                    x = (TType)paramList[1];
                    return (bool)ret;
                }
            }
        }

        // Maybe we should throw an exception here, because we were unable to find the TryParse
        // method; this is not just a unable-to-parse error.

        x = default( TType );
        return false;
    }
}

The next step would be trying to implement
public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args );

With full parameter type matching etc.

A: This isn't really a solution, but in certain scenarios it could be a good alternative: We can pass an additional delegate to the generic method.
To clarify what I mean, let's use an example. Let's say we have some generic factory method, that should create an instance of T, and we want it to then call another method, for notification or additional initialization.
Consider the following simple class:
public class Example
{
    // ...

    public static void PostInitCallback(Example example)
    {
        // Do something with the object...
    }
}

And the following static method:
public static T CreateAndInit<T>() where T : new()
{
    var t = new T();
    // Some initialization code...
    return t;
}

So right now we would have to do:
var example = CreateAndInit<Example>();
Example.PostInitCallback(example);

However, we could change our method to take an additional delegate:
public delegate void PostInitCallback<T>(T t);
public static T CreateAndInit<T>(PostInitCallback<T> callback) where T : new()
{
    var t = new T();
    // Some initialization code...
    callback(t);
    return t;
}

And now we can change the call to:
var example = CreateAndInit<Example>(Example.PostInitCallback);

Obviously this is only useful in very specific scenarios. But this is the cleanest solution in the sense that we get compile time safety, there is no "hacking" involved, and the code is dead simple.

A: Do you mean to do something like this:
Class test<T>
{
     T method1(object Parameter1){

         if( Parameter1 is T )
         {
              T value = (T) Parameter1;
             //do something with value
             return value;
         }
         else
         {
             //Parameter1 is not a T
             return default(T); //or throw exception
         }
     }
}

Unfortunately you can't check for the TryParse pattern as it is static - which unfortunately means that it isn't particularly well suited to generics.

A: The only way to do exactly what you're looking for would be to use reflection to check if the method exists for T.
Another option is to ensure that the object you send in is a convertible object by restraining the type to IConvertible (all primitive types implement IConvertible). This would allow you to convert your parameter to the given type very flexibly.
Class test<T>
{
    int method1(IConvertible Parameter1){

        IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));

        T temp = Parameter1.ToType(typeof(T), provider);
    }
}

You could also do a variation on this by using an 'object' type instead like you had originally.
Class test<T>
{
    int method1(object Parameter1){

        if(Parameter1 is IConvertible) {

            IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));

            T temp = Parameter1.ToType(typeof(T), provider);

        } else {
           // Do something else
        }
    }
}

A: Ok guys: Thanks for all the fish. Now with your answers and my research (especially the article on limiting generic types to primitives) I will present you my solution.
Class a<T>{
    private void checkWetherTypeIsOK()
    {
        if (T is int || T is float //|| ... any other types you want to be allowed){
            return true;
        }
        else {
            throw new exception();
        }
    }
    public static a(){
        ccheckWetherTypeIsOK();
    }
}

A: You probably cant do it.
First of all if it should be possible you would need a tighter bound on T so the typechecker could be sure that all possible substitutions for T actually had a static method called TryParse.

A: You may want to read my previous post on limiting generic types to primitives. This may give you some pointers in limiting the type that can be passed to the generic (since TypeParse is obviously only available to a set number of primitives ( string.TryParse obviously being the exception, which doesn't make sense).
Once you have more of a handle on the type, you can then work on trying to parse it. You may need a bit of an ugly switch in there (to call the correct TryParse ) but I think you can achieve the desired functionality.
If you need me to explain any of the above further, then please ask :)

A: Best code: restrict T to ValueType this way:
class test1<T> where T: struct

A "struct" here means a value type.
String is a class, not a value type.
int, float, Enums are all value types.
btw the compiler does not accept to call static methods or access static members on 'type parameters' like in the following example which will not compile :(
class MyStatic { public static int MyValue=0; }
class Test<T> where T: MyStatic
{
    public void TheTest() { T.MyValue++; }
}

=> Error    1   'T' is a 'type parameter', which is not valid in the given context
SL.

A: That is not how statics work.  You have to think of statics as sort of in a Global class even if they are are spread across a whole bunch of types.  My recommendation is to make it a property inside the T instance that can access the necessary static method.
Also T is an actual instance of something, and just like any other instance you are not able to access the statics for that type, through the instantiated value.  Here is an example of what to do:
class a {
    static StaticMethod1 ()
    virtual Method1 ()
}

class b : a {
    override Method1 () return StaticMethod1()
}

class c : a {
    override Method1 () return "XYZ"
}

class generic<T>
    where T : a {
    void DoSomething () T.Method1()
}


text:
Q: Can Anyone Tell Me Why This Text Is Not Centering In Android Studio? I'm attempting to align the text as you would expect to see if you were in a word pad and set your alignment to center, the middle of each line would be in the center of the screen and each margin to the left and right would be equidistant. However, using gravity does not appear to be working as the text is still starting from the left. Could someone shed light as to why? Here's the xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="3dp"
    android:paddingRight="3dp"
    android:paddingTop="3dp"
    android:paddingBottom="3dp"
    android:orientation="vertical"
    android:background="#111111"
    tools:context="eqlogic.annswingsandthings.AboutUs">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/chalkBoard"
        android:src="@drawable/ann_chalkboard_img"
        android:layout_weight="0.5"/>
    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:id="@+id/scrollView"
        android:layout_gravity="center_horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:textColor="#999999"
            android:text="@string/AboutUsText"
            android:textSize="24sp"
            android:id="@+id/textView"
            android:layout_gravity="center_horizontal"
            android:singleLine="false" />
    </ScrollView>
</LinearLayout>

A: You are not setting the gravity, use:
android:gravity="center"

Full tag:
<TextView
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:textColor="#999999"
        android:text="@string/AboutUsText"
        android:textSize="24sp"
        android:id="@+id/textView"
        android:layout_gravity="center_horizontal"
        android:singleLine="false" />

A: Set also android:gravity parameter in ScrollView to center.
For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.

A: Make your layout_width be fill_parent and use gravity instead of layout_gravity:
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:textColor="#999999"
        android:text="@string/AboutUsText"
        android:textSize="24sp"
        android:id="@+id/textView"
        android:gravity="center"
        android:singleLine="false" />

A: Set scrollview parameters Android:layout_width="match_parent" and Android:gravity="center".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prefix rails and rake commands with foreman automatically? When I'm in a Rails project, how do I save myself from typing
foreman run rails console

every time?  In other words, is there a way to automatically prefix rails and rake commands with foreman run automatically?

A: Use a bash function:
rails () {
    if test current directory is in a rails project  # left as an exercise
    then
        foreman run rails "$@"
    else
        command rails "$@"
    fi
}


text:
Q: Como habilitar y deshabilitar vistas html según el valor de un select necesito que cuando en el <select class="simple" name="Modalidad" id="modalidad"> del archivo CrearEvento1.html se escoja la opción de "Virtual" se ignore o se deshabilite el html CrearEvento2 y que cuando en el <select class="simple" name="Proposito" id="proposito"> se seleccione la opción de "No Benefica" se ingnore o deshabilite el html CrearEvento4. Anexo el código de los archivos html que tiene la pagina web que estoy programando, cualquier consejo se aprecia:
CrearEvento1.html

Crear Evento

Información General:

                Modalidad de Subasta
                <select class="simple" name="Modalidad" id="modalidad">
                    <option value="2">Seleccione</option>
                    <option value="0">Presencial</option>
                    <option value="1">Virtual</option>
                </select>

                Proposito
                <select class="simple" name="Proposito" id="proposito">
                    <option value="0">Benefica</option>
                    <option value="1">No Benefica</option>
                </select>

                Tipo de Subasta
                <select class="simple" name="Tipo" id="tipo">
                    <option value="0">Silenciosa</option>
                    <option value="1">Dinamica</option>
                </select>

                Hora Inicio:

            <button id="anterior1">Anterior</button>

            <button id="siguiente1" onclick="location.href='CrearEvento2.html'">Siguiente</button>

CrearEvento2.html

Crear Evento

Datos de Ubicación

                País
                <select class="simple" name="Pais">
                    <option value="1">Venezuela</option>
                </select>

                Estado
                <select class="simple" name="Estado">
                    <option value="0">Seleccione</option>
                    <option value="1">Amazonas</option>
                    <option value="2">Anzoátegui</option>
                    <option value="3">Apure</option>
                    <option value="4">Aragua</option>
                    <option value="5">Barinas</option>
                    <option value="6">Bolí;var</option>
                    <option value="7">Carabobo</option>
                    <option value="8">Cojedes</option>
                    <option value="9">Delta Amacuro</option>
                    <option value="10">Distrito Capital</option>
                    <option value="11">Falcón</option>
                    <option value="12">Guárico</option>
                    <option value="13">Lara</option>
                    <option value="14">Mérida</option>
                    <option value="15">Miranda</option>
                    <option value="16">Monagas</option>
                    <option value="17">Nueva Esparta</option>
                    <option value="18">Portuguesa</option>
                    <option value="19">Sucre</option>
                    <option value="20">Táchira</option>
                    <option value="21">Trujillo</option>
                    <option value="22">Vargas</option>
                    <option value="23">Yaracuy</option>
                    <option value="24">Zulia</option>
                </select>

                Dirección:

                <textarea name="direccion" cols="32" rows="5">Escriba aquí su dirección</textarea>

            <button id="anterior2" onclick="location.href='CrearEvento1.html'">Anterior</button>
            <button id="siguiente2" onclick="location.href='CrearEvento3.html'">Siguiente</button>

CrearEvento4.html

Crear Evento

                Organizaciones Benéficas
                <button class="buscar" id="buscar">
                    Buscar
                </button>

                <select multiple name="clubes" id="clubes">
                    <option value="1">Soparati</option>
                    <option value="2">Porción de Ezperanza</option>
                    <option value="3">Comparte por una Vida</option>
                    <option value="4">Barriga Llena corazón contento</option>
                    <option value="5">Manos Abiertas Maracaibo</option>
                    <option value="6">Una Sopa Amiga</option>
                    <option value="7">Apera Para Llevar</option>
                    <option value="8">Regalando Sonrisas Maracaibo</option>
                    <option value="9">La Olla Milagrosa</option>
                    <option value="10">Unos Chamos Ahí</option>
                    <option value="11">La Sopita de Fernan</option>
                    <option value="12">Nexo.ong</option>
                    <option value="13">Un Gran Arepazo</option>
                    <option value="14">Desayunos Sonrisas</option>
                    <option value="15">Sopas por Sonrisas</option>
                </select>

            <button onclick="location.href='CrearEvento3.html'">Anterior</button>
            <button onclick="location.href='CrearEvento5.html'">Siguiente</button>

A: Esto es lo máximo que puedo conseguir hacer para ayudarte, ya que dependiendo de los valores que haya en los distintos selects, cambie el location del botón.
La lógica detrás de esto no sería pues, inhabilitar los html, sino redirigir a qué campo quieres que vaya.
Igualmente, podrías hacer templates predefinidas, y según qué valor tenga el input, guardar dichos valores, y en vez de redirigir a OTRA pagina, en la misma, cambiar el DOM con dichas templates.
O al menos así es como yo lo haría vaya. Igualmente aquí tienes el resultado, espero que te sirva. Si no está bien la lógica detrás de los redireccionamientos solo es cambiar numeros y valores, pero es bastante lioso la forma en que lo explicaste.

let mod = document.getElementById('modalidad');
let pro = document.getElementById('proposito');
let btn = document.getElementById('siguiente1');

console.log(btn);

mod.addEventListener('change', (e) => {
  console.log(e.target.value);

  if (e.target.value == 0) {
    btn.removeAttribute('onclick');
    btn.setAttribute('onclick', 'location.href="CrearEvento2.html"');
  } else {
    btn.removeAttribute('onclick');
    btn.setAttribute('onclick', 'location.href="CrearEvento3.html"');
  }
});

pro.addEventListener('change', (e) => {

  if (e.target.value == 0 && mod.value == 0) {
    btn.removeAttribute('onclick');
    btn.setAttribute('onclick', 'location.href="CrearEvento4.html"');
  }
  if (e.target.value == 1 && mod.value == 1) {
    btn.removeAttribute('onclick');
    btn.setAttribute('onclick', 'location.href="CrearEvento5.html"');
  }

});
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>042</title>

Crear Evento

Información General:

        Modalidad de Subasta
        <select class="simple" name="Modalidad" id="modalidad">
          <option value="2" disabled="true" selected>Seleccione</option>
          <option value="0">Presencial</option>
          <option value="1">Virtual</option>
        </select>

 Proposito
        <select class="simple" name="Proposito" id="proposito">
          <option value="2" disabled="true" selected>Seleccione</option>
          <option value="0">Benefica</option>
          <option value="1">No Benefica</option>
        </select>

 Tipo de Subasta
        <select class="simple" name="Tipo" id="tipo">
          <option value="2" disabled="true" selected>Seleccione</option>
          <option value="0">Silenciosa</option>
          <option value="1">Dinamica</option>
        </select>

 Hora Inicio:

      <button id="anterior1">Anterior</button>
      <button id="siguiente1" onclick="location.href='CrearEvento2.html'">Siguiente</button>


text:
Q: Variant of the geometric series Can someone explain me how one computes
$$\sum_{k=1}^n kq^k = \dfrac{nq^{n+2}-(n+1)q^{n+1}+q}{(1-q)^2}$$
and what exactly the derivative has to do with it?

A: Let define the following function: $$f:x\in\mathbb{R}\mapsto\sum_{k=0}^nq^kx^k.$$
Beside, one has:
$$\forall x\in\mathbb{R},f'(x)=\sum_{k=1}^nkq^kx^{k-1}.$$
Therefore, one gets: $$f'(1)=\sum_{k=1}^nkq^k.$$
But using the formula for the geometric sum, one has: $$\forall x\in\mathbb{R},f(x)=\frac{1-(qx)^{n+1}}{1-qx}.$$
Hence, one is able to compute explicitely $f'(1)$.


text:
Q: Can't move jQuery to footer Below two methods did not help me. My jQuery is always on the head section. What can be the reason?
Method 1: (adding below code to function.php)
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js',array(),'1.9.0',true);

}

this one works when I change 'jquery', to some other string as first parameter in wp_enqueue_script. So why it doesn't work with jquery handle?
Method 2: (adding below code to function.php)
function pwcc_jquery_to_footer( &$wp_scripts ) {
      if ( is_admin() ) {
        return;
      }
      $wp_scripts->add_data( 'jquery',         'group', 1 );
      $wp_scripts->add_data( 'jquery-core',    'group', 1 );
      $wp_scripts->add_data( 'jquery-migrate', 'group', 1 );
    }
    add_action( 'wp_default_scripts', 'pwcc_jquery_to_footer' );

This code did not have any affect on the page, it modifies group which tells wheather the script should be in header or footer

A: Not the best way but removing the default WordPress actions that allow any scripts in the document's head can help:
function md_footer_enqueue_scripts() {
    remove_action('wp_head', 'wp_print_scripts');
    remove_action('wp_head', 'wp_print_head_scripts', 9);
    remove_action('wp_head', 'wp_enqueue_scripts', 1);
}
add_action('wp_enqueue_scripts', 'md_footer_enqueue_scripts');`


text:
Q: Can $z$ still be called "limit" when at some point $f(x)=z$? For the function:
$f(x) = {(x-1)^3 - (x+2)^3 \over (x+1)^2+2x+3}$ with $x \geq 1$
I have calculated that $\lim\limits_{x \to \infty} f(x) = -3 $
My question is: Can you call $-3$ the limit of function $f$, although $f(1)=-3$ ?


text:
Q: Geração automática dos Controllers e Views com .NET Entity Framework e MySQL EDIT: Resolvi o problema abaixo e outros que apareceram depois. Veja minha reposta.
Criei um projeto de Business usando a abordagem Code First do Entity Framework (EF). Tenho um banco em MySQL com 8 tabelas e todas elas se relacionam mesmo que indiretamente. O EF se conectou ao banco e me gerou as classes de contexto e tabelas. Tudo certo até aqui!
Em seguida, criei um projeto MVC, adicionei a referência para minha camada de Business e fui tentar adicionar um novo controlador com as views fazendo o scaffold de uma de minhas tabelas (o problema ocorre com qualquer tabela, mas vou exemplificar com a de Cliente).
Adicionar -> Novo item com scaffold -> Controlador MVC 5 com modos de exibição EF

E esse erro ocorre:

Uma de minhas tabelas possui alguns campos do tipo enum. Porém, já removi qualquer referência ao provedor do SQL server e estou deixando apenas o do MySQL. Por que ele ainda tenta o SqlServer provider??
Web.config
<connectionStrings>
    <add name="AtividadesNovaContext" connectionString="server=****;user id=****;password=****;database=atividadesnova;persistsecurityinfo=True" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.EntityFramework" />
    <providers>
        <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.18.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </providers>
</entityFramework>

Softwares e pacotes instalados

*

*.NET Framework 4.7.2

*MySQL for Visual Studio 2.0.5

*MySQL connector .NET 8.0.18

*MySQL.Data.EntityFramework 8.0.18

*EntityFramework 6.2.0

Alguém tem alguma ideia do que pode estar acontecendo?
EDIT: Atualizei a versão do MySQL for Visual Studio para a 2.0.5 (versão de desenvolvedor). Após isso o erro mudou (imagem atualizada). Adicionei novas informações do sistema.

A: Consegui gerar os controladores e views, mas tive que resolver muitos problemas além dos que postei aqui. Vou deixar listado os problemas com a solução que encontrei.
Object reference not set to an instance of the object

*

*Além de atualizar a versão do MySQL for Visual Studio, também colocar temporariamente os modelos no mesmo projeto da interface apenas para rodar o EF.

Unable to retrieve metadata for 'Cliente'.
The store type 'type' could not be found in the SqlServer provider manifest

*

*Definir um objeto MySqlEFConfiguration para o DbConfiguration no início da aplicação. No meu caso, um app ASP.NET MVC, defini na subrotina Application_Start() do arquivo Global.asax
DbConfiguration.SetConfiguration(New MySqlEFConfiguration())
Unable to retrieve metadata for 'Cliente'
There is no store type corresponding to the conceptual side type 'SByte' of primitive type 'SByte'

*

*Usar tipo Byte ao invés de SByte nos modelos para mapear o TINYINT do MySQL

Também tive um problema com o mapeamento do tipo TIMESTAMP do MySQL para o Date do VB.NET. (Não anotei o erro lançado.)

*

*Usar o tipo MySql.Data.Types.MySqlDateTime e anotar o tipo da coluna para DateTime

Imports MySql.Data.Types
'...
&ltColumn(TypeName:="DateTime")&gt
Public Property Horario As MySqlDateTime


text:
Q: How to include team name of selected player in tellraw I want to display a tellraw message which includes the team name of a selected player.
Example:  A player on Red team has reached x score!
Something like {"selector":"@p"} but instead of displaying player's name, I want it to display the player's team name.


text:
Q: How to prevent my textbox from clearing text on postback. I have a pretty interesting dilemma that is giving me a hurricane of a headache. I've seen a similar question asked here, but the user posted no code, so it was unresolved. This is a asp.net, sql server, and c# app.
In my application, I use JavaScript to display dummy data in a TextBox to entertain the user while a long process is running. (please note, this is a project, not a professional app).
The problem is, once the app is done executing, the app (I believe) refreshes the page and clears the TextBox. I want to prevent this from happening and continue to display the text after the program is completed.
My question is, where in the following code is the page being refreshed? How can I re-code it to prevent the text from being cleared?
I know there is no issue with the JavaScript or the .aspx page. I have not set or programmed any property to clear the text. If anyone could shed light on the issue, I would greatly appreciate it. If you need more code from me please let me know. I will be very active on this page until it is resolved. Thanks again!
public partial class SendOrders : System.Web.UI.Page
{
    protected enum EDIType
    {
        Notes,
        Details
    }

    protected static string NextBatchNum = "1";
    protected static string FileNamePrefix = "";
    protected static string OverBatchLimitStr = "Batch file limit has been reached.  No more batches can be processed today.";

    protected void Page_Load(object sender, EventArgs e)
    {
        Initialize();
    }

    protected void Page_PreRender(object sender, EventArgs e)
    { }

    protected void btnExit_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.GetCurrentProcess().Kill();
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        PutFTPButton.Enabled = false;
        Thread.Sleep(3000);
        Button btn = (Button)sender;
        KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
        KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();

        if (btn.ID == PutFTPButton.ID)
        {
            DirectoryInfo dir = new DirectoryInfo(@"C:\Kaplan");
            FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
            bool result = transmit.UploadBatchFilesToFTP(BatchFiles);

            if (!result)
            {
                ErrorLabel.Text += KaplanFTP.errorMsg;
                return;
            }

            bf.InsertBatchDataIntoDatabase("CTL");
            bf.InsertBatchDataIntoDatabase("HDR");
            bf.InsertBatchDataIntoDatabase("DET");
            bf.InsertBatchDataIntoDatabase("NTS");

            List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
            allfiles.AddRange(dir.GetFiles("*.txt"));
            bf.MoveFiles(allfiles);

            foreach (string order in bf.OrdersSent)
            {
                OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
            }

            btnExit.Visible = true;
            OrdersSentDiv.Visible = true;
            OrdersInfoDiv.Visible = false;
            SuccessLabel.Visible = true;
            NoBatchesToProcessLbl.Visible = true;
            BatchesToProcessLbl.Visible = false;
            PutFTPButton.Enabled = false;
            BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
            Thread.Sleep(20000);

            if (KaplanFTP.errorMsg.Length != 0)
            {
                ErrorLabel.Visible = false;
                SuccessLabel.Visible = true;
                ErrorLabel.Text = KaplanFTP.errorMsg;
            }
        }
    }

    private void Initialize()
    {
          KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();

          if (!IsPostBack)
          {
              FileNamePrefix = bf.FileNamePrefix;
              NextBatchNum = bf.NextBatchNum;
              BatchesCreatedLbl.Text = (int.Parse(NextBatchNum) - 1).ToString();

              if (bf.CheckLocalForNewBatch() == true)
              {
                  NoBatchesToProcessLbl.Visible = false;
                  BatchesToProcessLbl.Visible = true;
                  if (int.Parse(NextBatchNum) >= 50)
                  {
                      ErrorLabel.Text += ErrorLabel.Text + OverBatchLimitStr;
                      ErrorLabel.Visible = true;
                      PutFTPButton.Enabled = false;
                  }
                  else
                  {
                      bf.ReadyFilesForTransmission();
                      ErrorLabel.Visible = false;
                      PutFTPButton.Enabled = true;
                      List<string[]> detStream = bf.GetBatchStream("DET");
                      List<string[]> hdrStream = bf.GetBatchStream("HDR");
                      OrdersInfoDiv.Visible = true;

                      DataTable dt = new DataTable();
                      dt.Columns.Add("ORDER NUMBER");
                      dt.Columns.Add("LINE NUMBER");
                      dt.Columns.Add("ITEM NUMBER/ISBN");
                      dt.Columns.Add("DESCRIPTION");
                      dt.Columns.Add("QUANTITY");
                      dt.Columns.Add("SHIPPING");

                      Dictionary<string, string> orderShip = new Dictionary<string, string>();

                      foreach (string[] hdrItems in hdrStream)
                      {
                          orderShip.Add(hdrItems[0], hdrItems[2]);
                      }
                      foreach (string[] detItems in detStream)
                      {
                          List<string> detLineList = new List<string>(detItems);
                          detLineList.Add(orderShip[detItems[0]]);
                          detLineList.RemoveAt(13);
                          detLineList.RemoveAt(12);
                          detLineList.RemoveAt(11);
                          detLineList.RemoveAt(10);
                          detLineList.RemoveAt(9);
                          detLineList.RemoveAt(8);
                          detLineList.RemoveAt(7);
                          detLineList.RemoveAt(4);
                          detLineList.RemoveAt(2);
                          detLineList[1] = detLineList[1].TrimStart('0');
                          detLineList[4] = detLineList[4].TrimStart('0');
                          dt.Rows.Add(detLineList.ToArray());
                      }

                      BatchDetails.DataSource = dt;
                      BatchDetails.DataBind();
                  }
              }
              else
              {
                  NoBatchesToProcessLbl.Visible = true;
                  BatchesToProcessLbl.Visible = false;
                  PutFTPButton.Enabled = false;
              }
          }
      }
}

A: Yes. You will have to determine the state of your calculation and populate the control inside Page_Load in the case where IsPostBack is true:
protected void Page_Load(object sender, EventArgs e) {
   if (IsPostBack) {
      // re-populate javascript-fill UI
   } else {
   }
   Initialize();
}

You can probably also move Initialize() into the else clause as well.

A: Since you are handling the button click server side (I'm assuming the problem is happening once the user clicks the button?) there has to be a postback to handle it.
You could try putting your button and label into an updatepanel control - it uses AJAX to refresh its contents.
See this page for more information on updatepanels.


text:
Q: Why when updating an existing property value with spread operator the value gets added in the array? I have a state which contains an array of objects:
const initialState=[{a:1},{b:2},{c:{d:3}}]

const [state,setState]=useState(initialState)

I want to change the value of b to 5 in my event handler:
function changeBToFive() {
    setState((state) => [
      ...state,
      (state[1].b = 5),
    ]);
  }

And the result of the new state is:
[{a:1},{b:5},{c:{d:3}},5]

So it is updating the value of "b" correctly. But it is adding the value 5 at the end.
Why is that??
Thank you.

A: It is because (state[1].b = 5) returns 5, which becomes the last element in the array you are creating. Instead, change the value first and then use setState.
function changeBToFive() {
    setState((state) => {
        state[1].b = 5;
        return [...state];
     });
}


text:
Q: Accessing memory with Java I have a program loaded in the memory. Now I want to access the memory directly and change the OPCODE and DATA in the memory for that program. For this I need to write a Java program.
Can you please tell me if this is feasible? If yes, please let me know how to write such a program.
Thanks in advance!

A: Java is not designed for this.
The main aim of Java is to let the JVM manage the memory for you. Thus, your programs are sandboxed.
However, there seems to be a backdoor in HotSpot JVM:

Java was initially designed as a safe, managed environment.
  Nevertheless, Java HotSpot VM contains a "backdoor" that provides a
  number of low-level operations to manipulate memory and threads
  directly. This backdoor – sun.misc.Unsafe – is widely used by JDK
  itself in the packages like java.nio or java.util.concurrent. It is
  hard to imagine a Java developer who uses this backdoor in any regular
  development because this API is extremely dangerous, non portable, and
  volatile. Nevertheless, Unsafe provides an easy way to look into
  HotSpot JVM internals and do some tricks. Sometimes it is simply
  funny, sometimes it can be used to study VM internals without C++ code
  debugging, sometimes it can be leveraged for profiling and development
  tools.

Source: http://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/
The Unsafe class is, however, undocumented. You may want to have a look at this SO answer for more details: https://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe
Unoffical Docs: http://mishadoff.github.io/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
Absolute Beginners' Guide http://java-performance.info/string-packing-converting-characters-to-bytes/
http://javapapers.com/core-java/address-of-a-java-object/
P.S. I am aware that I must post some of the content of the link here but since the articles are really very detailed, I have skipped that part

A: You cannot directly reference memory in java, as their is no concept of pointers in java like c/c++
You must go through this referencing memory address
Hope it helps.


text:
Q: How do I get the attachments from an incoming Mailgun route? I am using aiohttp. I have an api which handles Mailgun routed data. The emails have multiple attachments. I am not able to read all of the attachments. It just gives me a single one.
data is what I receive.
str(list(data.keys())) gives me the list - ['Content-Type', 'Date', 'Dkim-Signature', 'From', 'Message-Id', 'Mime-Version', 'Received', 'Received', 'Received', 'Subject', 'To', 'X-Envelope-From', 'X-Mailgun-Incoming', 'X-Received', 'attachment-count', 'body-html', 'body-plain', 'from', 'message-headers', 'recipient', 'sender', 'signature', 'stripped-html', 'stripped-signature', 'stripped-text', 'subject', 'timestamp', 'token', 'attachment-1']
str(data.get('attachment-count') gives me 2/3/4 when I send multiple files in the email - which is fine. But there is only one key as attachment-1.
Doubts:
Does attachment-1 in the keys tell that there is only one file in the data?
If there are multiple files, does that mean there are keys as - attachment-1, attachment-2 ....
How do I retrieve all the files from the email?
I tried looking for the Mailgun's documentation but did not get concrete help for reading the files. Can someone redirect me to some code for the same. Other fields as from, subject is just fine.
This random thing I tried also reads just a single file. This seems wrong, though.
form_data_content_type = [(v.name, v.content_type, v.filename) if (
        v and hasattr(v, 'content_type') and hasattr(v, 'filename')) else None for v in
                              data.values()]
logger.info("No. of attachments " + str(len(form_data_content_type)) # returns 1

* UPDATE *
I tried running a flask server and tested emails with multiple files:
print(request.files) prints ImmutableMultiDict([('attachment-2', <FileStorage: 'Screen Shot 2015-09-02 at 10.18.37 am.png' ('image/png')>), ('attachment-1', <FileStorage: 'Screen Shot 2015-09-02 at 10.18.36 am.png' ('image/png')>)])
which shows there are two files indeed.
Now there is certainly an issue with how aiohttp is handling the mailgun's data:
printing request.post() gives only one file - 'attachment-1': Field(name='attachment-1', filename='Screen Shot 2015-09-02 at 10.40.18 am.png', file=<_io.BufferedRandom name=10>, content_type='image/png'). There is no attachment-2, god knows why!

A: as im not familair with python or aiohttp i cant give you the code example, but this is how it works.
POST
Mailgun sends a post request with all relevant information as an array,
Files
it also sends files along with the request, in php you can loop through the super-globe $_FILES to retrieve the attachments,
Inline Embedded Pictures
when someone sends a inline picture for example myimg.jpg you need to map the attachment to embedd and that why you only see attachment-1even though there are more attachments only one of them are embedded.
'attachment-count' => '3', Tells you how many attachments there are, in this case 3, in php you'd find it in $_FILES,
content-id-map' => '{"<ii_jgl9284x0_1631307716495e75>": "attachment-1"}',

Points to the embedded img
<img src="cid:ii_jgl9284x0_1631307716495e75" width="190" height="114">


text:
Q: How can multiple services re-use the authentication cookie? I want to understand how a static site with no backend can use okta with other custom API services hosted on other platforms.
Scenerio:
Website is a angluar/reactjs that is hosted as a "static" website.
I'm assuming when you authenticate using okta in e.g. react/angular website I am able to store the okta session id in local storage or cookie.
How say I create a web service and host that on heroku, how can I figure out if the user has authenticated or not and re-use the session?

A: The scenario where you have:

*

*A JavaScript frontend application, hosted statically

*A backend web service (API), that the JavaScript app makes API requests to

is a classic single-page app (SPA) scenario. The recommended authentication flow is the OpenID Connect implicit flow.
In plain English, you are:

*

*Setting up your JavaScript app to talk to Okta (or another OpenID Connect identity provider)

*Getting an access token from the identity provider

*Attaching the access token to an API request to authorize it

Your API service could be running on Heroku, or somewhere else. In your API service code, you have to validate the access token before you decide to accept the request. The API service can go back and talk to the identity provider to determine if the user's access token is still valid.
How the API service validates the token depends on what language you are using to build your API service. But, that's basic idea: the access token is what authorizes the user's requests.


text:
Q: Neither BindingResult nor plain target object for bean name 'user' available as request attribute error I am new on spring. I am just trying to create my own CRUD OneToMany project. I have user and course table in my database. Course table has user_id foreign key references user(id).
When user successfully logged into the page, homePage.jsp comes and user courses are listed. When we click "Add Course" button in homePage.jsp, course-form.jsp file comes and we should add course.
The problem is, when I try to add course, I lost my user modelAttribute because in this time another attribute is on process with spring mvc.
When addedCourse form action performed these error occurs,
 Cannot invoke "com.veg.entity.User.addCourse(com.veg.entity.Course)" because "user" is null

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

My Controller,
@PostMapping("/showFormForAdd")
    public String showFormForAdd(@ModelAttribute("user") User theUser, Model theModel) {

        Course theCourse = new Course();

        theCourse.setUser(theUser);

        theModel.addAttribute("course", theCourse);

        theModel.addAttribute("user", theUser);

        return "course-form";
    }

    @PostMapping("addedCourse")
    public String addedCourse(@ModelAttribute("course") Course theCourse, Model theModel) {

        User user = theCourse.getUser();

        userService.save(user, theCourse);

        theModel.addAttribute("user", user);

        return "homePage";
    }

homePage.jsp

Welcome ${user.username}

                <form:form action="showFormForAdd" modelAttribute="user" method="POST">

                    <form:hidden path="username"/>
                    <form:hidden path="password"/>

                    <input type="submit" value="Add Course" class="add-course"/>

                </form:form>

                        Course id
                        Course title

                    <c:forEach var="temp" items="${user.courses}">

                             ${temp.id}
                             ${temp.title}

                    </c:forEach>

course-form.jsp

Welcome ${user.username}

        <form:form action="loggedUser" modelAttribute="user" method="POST">

            <form:hidden path="username"/>
            <form:hidden path="password"/>

            <input type="submit" value="Back to Course List" class="add-course"/>

        </form:form>

    <form:form action="addedCourse" modelAttribute="course" method="POST">

                     Title
                     <form:input path="title"/>

                    <input type="submit" value="Add Course" class="add-course"/>

    </form:form>

I have @Transactional in my service, @Repository in my DAO and there is no problem with sessionFactory.


text:
Q: Custom Validation Attribute for three levels deep model Hi I have a situation in witch I have to create some custom validation attributes because  the way my model is created.The model looks something like this:
public class EvaluationFormDataContract
{
    public int StudentAssignmentInstanceId { get; set; }

    public int EvaluationType { get; set; }

    public List<CategoriesOnEvaluationDataContract> Categories { get; set; }
}

  public class CategoriesOnEvaluationDataContract
{
    public string Memo { get; set; }

    public int CategoryId { get; set; }

    public List<QuestionsOnEvalCategoryDataContract> Questions { get; set; }

    // Fields needed for validation
    public bool? HasMemo { get; set; }

    public bool MemoIsMandatory { get; set; }
}

    public class QuestionsOnEvalCategoryDataContract
{
    public string Memo { get; set; }

    public string Grade { get; set; }

    public int QuestionId { get; set; }

    // Fields needed for validation
    public bool HasGrade { get; set; }

    public bool HasMemo { get; set; }

    public bool ShowOnlyMemo { get; set; }
}

As it can be seem the model is composed two levels deep.
And I will have to validate starting from the second level , where I will check if the model HasMemo and if MemoIsMandatory.
The third validation should be done at the 3rd level where I have to check if it HasGrade and HasMemo.
Normaly if it were up to me I would split this in three separate calls to the server but we are depending on an legacy project and for the moment I have to make this work.
The post action will be called via an ajax call and will have all this data into it.
Now my question is where should I add the validation attribute?
Should it be added at the top on Categories , making it directly responsible for all the levels of the model?
Or I should place it on each model and find a way to make the data binder aware of it? If so how can I do this?

A: You can do both. If you implement System.ComponentModel.DataAnnotations.IValidatableObject interface at the top-most level, you can do whatever you want with the properties in the entire graph and return the errors.
public class EvaluationFormDataContract : IValidatableObject
{
        // All properties go here

        public IEnumerable<ValidationResult> Validate(
                                 ValidationContext validationContext)
        {
            if (// do what you want)
                yield return new ValidationResult("message");
        }
}

Or, you can apply attributes at the lower levels and automatically binding takes care of validating the properties in the graph. You don't need to do anything special.


text:
Q: If Plagueis Caused Anakin's Birth, Why Shmi Skywalker? Darth Plagueis had talked about creating life through the Force and it is speculated that he may be responsible for Anakin's birth via the Force.  Is there any reason he picked Shmi Skywalker for this experiment?  It would seem more logical to pick someone he could easily guard and keep close to him so she couldn't wander off and so others couldn't abduct or harm her during the pregnancy.
Why Shmi?  Is there anything about her that makes her particularly unique for such an experiment?

A: Darth Plagueis did not "choose" Shmi Skywalker. There is a recently published book, Star Wars: Darth Plagueis, that jossed the "Darth Plagueis is Anakin's father" fan theories. From the Anakin Skywalker Wookieepedia article:

In addition, although Darth Plagueis did attempt to influence the midichlorians to create the ultimate Sith weapon alongside Darth Sidious, the experiment was ultimately a failure, and the midichlorians, sensing the Sith's inherent malevolent intention, not only refused to do so, but in retaliation, conceived Anakin Skywalker in order to destroy the Sith once and for all.

So, according to this, it is the midi-chlorians who choose Shmi Skywalker, and there is no canon information about how and why they choose her, so any answer about that would be pure speculation, until new licensed material is published.

A: I think my theory solves a few problems. Both Darth Plagueis and Darth Sidious "created" Anakin, sort of, but really it was the Force.  Darth Plagueis attempted to manipulate midichlorians to create the Chosen One with the help of his apprentice, Sidious, who realized that this would mean his replacement as apprentice.
So having taught Sidious all that he knew, Plagueis was really dispensable, and Sidious killed him and tried to do create life himself.  Only Plagueis didn't teach Sidious everything he knew, that is, he taught him all the methods to create life, but didn't tell him that a powerful Sith could control his midichlorian essence after death and be reincarnated into a new body.
So, having given his apprentice all of the tools to create a powerful midichlorian life form, he allowed himself to be killed by Sidious to accomplish his plan. (c'mon, how else is a Sith Lord going to get killed in his sleep by his apprentice).
Sidious, believing that he had rid himself of his master, and obviously not loyal to his apprentices (Maul, Dooku), set out to create for himself this powerful chosen one as his new apprentice.
But in order to ensure that such a force sensitive child wouldn't be discovered by the Jedi, he had to go to the outer rim and get a person to experiment on, naturally a slave, Shmi Skywalker from Tatooine.  He used the power of the force to impregnate her with high density midichlorian essences (Plagueis).
But neither he, nor Plagueis realized that their Sith wills weren't stronger than the Force itself, so instead of all of the dark side midichlorian Plagueis Sith essence being reincarnated into Anakin, the Force provided half light side midichlorians, thus bringing forth a Force Balanced creation in Anakin.
None of this mind you would have been possible if the Force had not willed it, which is why Sidious couldn't repeat the experiments later.


text:
Q: Mail Sending problem with ASP.Net I want to send a mail with through ASP.Net.But,that's gives me "SendUsing" error.
Code:
<%
string strKime = "xxx@hot.com";
string strKimden = "deneme@hot.com";
string strKonu = "ASP.net mail gönderme işlemi";
string strMetin = "Bu sayfa asp.net mail komponenti     tarafından gönderildi";
System.Web.Mail.SmtpMail.Send(strKimden, strKime, strKonu, strMetin);

%>

A: Perhaps, SMTP Server is not configured correctly? it is recommended that we always specify the definite smtpserver names for when calling the System.Web.Mail components or CDO.
Not sure if you are using this directly in the markup. Ideally, you should have a common code that sends emails taking the required parameters. Check out the link in one of the other answers.

A: Did you add the SMTP settings in the web.config file?
<system.net>
<mailSettings>
  <smtp>
    <network
         host="ServerHostname"
         port="portNumber"
         userName="username"
         password="password" />
  </smtp>
</mailSettings>

Email sending requires SMTP settings.

A: You have to set the SmtpClient Host property to the "mail.hot.com" or the ip of your outgoing mail server.


text:
Q: How to display a toast notification from a WinForms project? I have found the following link explaining how to display a Toast notification using C#:
https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast-desktop
However, on Step 2: Reference the APIs, the Windows.UI and Windows.Data namespaces were not available in the Add Reference wizard.  I learned that it is because my project targets the .NET framework, not .NET core.  I don't want to convert my entire project to .NET core because I rely on certain NuGet packages that might not be compatible.
How can I display Toast notifications from a WinForms app that targets the .NET framework?  I found a nuget wrapper package, but it is for WPF applications.
EDIT:  The notification should persist within Windows Action Center.


text:
Q: I can use an interface in the html component but not in the typescript I'm using the Google Books Api in Angular. For that reason I created the following interface

    export interface DateBooks {
    kind:string,
    totalItems:number,
    items:Book[]
   }
   export interface Book {
   kind:string,
   id:string,
   etag:string,
   selfLink:string,
   volumeInfo: VolumeInfo[],
   saleInfo:SaleInfo,
   accessInfo:AccessInfo,
   searchInfo:SearchInfo
   }
   export interface VolumeInfo {
   title:string,
   subtitle:string,
   authors:string[],
   publisher:string,
   publisedDate:string,
   description:string,
   industryIdentifiers:IndustryIdentifiers[],
   readingModes:ReadingModes,
   pageCount:number,
   printType:string,
   categories:string[],
   maturityRating:string,
   allowAnonLogging:boolean,
   contentVersion:string,
   panelizationSummary:PanelizationSummary,
   averageRating:number,
   ratingCount:number,
   imageLinks:ImageLinks,
   language:string,
   previewLink:string,
   infoLink:string,
   canonicalVolumeLink:string
   }

   export interface ImageLinks {
   smallThumbnail:string,
   thumbnail:string
   }

   export interface IndustryIdentifiers{
       type:string,
       identifier:string
   }

   export interface ReadingModes{
       text:boolean,
       image:boolean
   }

   export interface PanelizationSummary{
       containsEpubBubbles:boolean,
       containsImageBubbles:boolean
   }

   export interface SaleInfo{
       country:string,
       saleability:string,
       isEbook:boolean
   }

   export interface AccessInfo{
       country:string,
       viewability:string,
       embeddable:boolean,
       publicDomain:boolean,
       textToSpeechPermission:string,
       epub:Epub,
       pdf:Pdf,
       webReaderLink:string,
       accessViewStatus:string,
       quoteSharingAllowed:boolean
   }

   export interface SearchInfo{
       textSnippet:string
   }

   export interface Epub{
       isAvailable:boolean
   }

   export interface Pdf{
       isAvailable:boolean
   }

This is  my typescript component

    databooks:DateBooks;
    books:Book[];
    title:string;
    constructor(private GoodreadsService:GoodreadsService) { }

      ngOnInit(): void {
      }

    getLibros(libro:string){
      this.GoodreadsService.getBooks(libro).subscribe(data=>{
        this.databooks=data;
        this.books=this.databooks.items;
      })

        }

This, the getBooks method

public getBooks(busqueda:string): Observable<DateBooks>{
    return this.http.get<DateBooks>(`https://www.googleapis.com/books/v1/volumes?q=${busqueda}&maxResults=40`);

And , this the html component

    <input type="text" id="namea" name="nameb" required
        minlength="4" maxlength="8" size="10" placeholder="introduzca texto" [(ngModel)]="title" (keyup)="getLibros(title) " >

 {{book.volumeInfo['title']}}

So, I can use the interface without problems in the html, besides if I run and write anything in the input, the page show correctly the titles of the books, and the cover. However, I cant get only a few properties of the interface on the ts. For instance, in the subscribe data is the object that getBooks return, the I can use data.items without problems, but if I write data.item.volumeInfo Visual code say this error: Property 'volumeinfo' does not exist on type 'Book[]', but I can use without problem in the html, the I don't know howw could I fix this issue?.
Could somebody tell me what is the problem or my error?

A: Concern #1 -
"but if I write data.item.volumeInfo Visual code say this error: Property 'volumeinfo' does not exist on type 'Book[]'"

*

*That is because you are trying to access the object property directly inside an array of Books

*Example:
// Mock Data
const books: Books[] = [
   { name: 'Book 1', volumeInfo: '123' },
   { name: 'Book 2', volumeInfo: '457' }
];

// This is what you are trying to do which will produce an error
// Directly accessing a property inside an array which is invalid since we are not accessing
// a mere object but we are accessing an array of object
books.volumeInfo

// What we must do to access them is through:
books[0].volumeInfo

// or through using .map, .filter, .forEach and other similar to iterate the array and access the properties inside
books.map(book => console.log(book))
books.forEach(book => console.log(book));

Concern #2 - but I can use without problem in the html

*

*That is because you have iterated the array through *ngFor="let book of books" just like how we can iterate through .map, .filter, and .forEach the array of objects

*Similar to:
books.forEach(book => console.log(book.volumeInfo));        // 123
                                                            // 457

In Summary, if we want to access an array of objects, use .map, .filter, .forEach or other similar for us to get an instance to all properties under that array


text:
Q: Qt/MySQL++/vector iteration question I've got a question regarding my vector iteration method within a Qt/MySQL++ project I'm working on at the moment.
I've been using for loops to iterate through them so far, and being quite a beginner at C++, didn't realise that the generally accepted method is to use vector::iterator. I've been trying to see a way I can convert them to this model, but I'm a bit stuck. My code reads as follows:
(connector is an instance of my custom db connection class)
mysqlpp::StoreQueryResult res = connector->getResults(searchTerm);
  int stock = res.field_num("stock");
  if(res.num_rows() > 0)
  {
    tblStock->setRowCount(res.num_rows());
    for(size_t i = 0; i &lt res.num_rows(); i++)
    {
      tblStock->setItem(i, 0,
                        new QTableWidgetItem(QString(res[i][stock].c_str())));
    }
  }
My problem is that I can't see a way to just use a vector::iterator instead of the incremental size_t, given that I am using i to define where to set the QTableWidgetItem. It definitely seems absurd to use both, though.
Any ideas?
Many thanks in advance for anybody and everybody!
X-T
UPDATE: Changed my program to use QSql objects, and a tableView, instead of a tableWidget, and it all works wonderfully! Thanks to anybody who took time to read the question!

A: Is it any serious reason you don't use QSql? I think QSqlQueryModel + QTableView can solve your problem without any vectors and iterators. A small example, right from Qt help:
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT name, salary FROM employee");
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model);  // binding model to view
view->show();

You probably have to read something about Qt model/view classes and about QSql to fully understand this example, but this is worth reading. I think you will have no problem reading Qt Reference, it is very detailed.


text:
Q: Got some issues with a case in my reducer im working on a react native project and ive got a small bug. What im trying to do is edit some notes that are fairly deeply nested in an object.
what i expect to happen is that it goes into characters, finds the correct character then finding the correct scene related to said character before adding the text. What returns is for each letter added it will copy every single part of the state.
Reducer:
`case EDIT_SCENENOTES:
            console.log(state)
            return {
                ...state,
                    currentProduction: {
                        ...state.currentProduction,
                        characters:
                            state.currentProduction.characters.map(charObj => charObj.id === action.CharacterId ?
                                {
                                    ...charObj,
                                    scenes: charObj.scenes.map(correctScene => correctScene.sceneId === action.SceneId ?
                                        {
                                            ...correctScene,
                                            [action.sceneName]:action.sceneObject
                                        }:state),
                                }:state)

                    }
                };


text:
Q: Do any of these properties of unlabeled rooted trees have commonly understood names? I've been trying to write up a proof recently which involves several properties of unlabeled rooted trees. Do any of these properties have commonly used names I am not aware of (so that I need not define them in my proof), or are any of the names I have chosen used for other properties of trees (so that I should choose a different name to avoid confusion)?
An exhaustive list of terms I'm using, to be on the safe side:

*

*Given an unlabeled rooted tree, I say that a node in the tree has depth equal to the distance between it and the root and the tree has depth equal to the maximum depth among all non-leaf roots.

*A node is maximal if its depth equals that of the tree and no other node at that depth has greater degree. The number of leaves adjacent to the maximal node in a tree (0 if no such node exists) is the deepest degree of the tree.

*The subtree descending from each child of the root is a branch of the tree, and a branch containing a maximal node of the tree is a maximal branch.

*Finally, a branch is undecorated if every leaf in the branch is at the same depth.


text:
Q: Unauthorized error while trying to create a new namespace in K8S I am trying to create a namespace on a K8s cluster on Azure using teh fabric8 java client . Here is the code
 @Before
    public void setUpK8sClient() {
    apiServer = "";
    config = new ConfigBuilder().withMasterUrl(apiServer).withUsername("user").withPassword("pass").build();
    client = new DefaultKubernetesClient(config);
    System.setProperty(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, "true");

    }

    @Test
    public void getClientVersion() {
    System.out.println("Client version "+client.getApiVersion());
    }

    @Test
    public void createNamespace() {
    Namespace myns = client.namespaces().createNew()
        .withNewMetadata()
        .withName("myns")
        .addToLabels("a", "label")
        .endMetadata()
        .done();
    System.out.println("Namespace version " + myns.getStatus());
    }

This gives me the following error
i
o.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: "https://...api/v1/namespaces. Message: Unauthorized! Token may have expired! Please log-in again. Unauthorized

What did I miss?

A: Since you are working on Azure, I guess you could follow the instructions to configure kubectl and then use the token from the kubeconfig file to access the cluster from the fabric8 client.
That token is probably an admin token, so you can also create new credentials (user/password) if you want to limit what the fabric8 client could do. API requests are tied to either a normal user or a service account, or are treated as anonymous requests.

*

*Normal users are assumed to be managed by an outside, independent service (private keys, third parties like Google Accounts, even a file with a list of usernames and passwords). Kubernetes does not have objects which represent normal user accounts.

*Service accounts are users managed by the Kubernetes API, bound to specific namespaces. Service accounts are tied to a set of credentials stored as Secrets. To manually create a service account, simply use the kubectl create serviceaccount ACCOUNT_NAME command. This creates a service account in the current namespace and an associated secret that holds the public CA of the API server and a signed JSON Web Token (JWT).


text:
Q: How do I sort a list of files and concatenate the contents in bash? This works:
find . -name "*.1" -print0 | xargs -0 cat > list.txt

But when I try to sort the the filenames, remove the newline the list of filenames that are piped to cat look identical to the previous but sorted:
find . -name "*.1" | sort | sed ':a;N;$!ba;s/\n//g' | xargs -0 cat > list.txt

However cat returns this error:
: No such file or directory

A: Your xargs statement is expecting null terminated entries.
find . -name '*.1' | sort | tr '\n' ' ' | xargs cat > list.txt

If your filenames or directories have spaces, then yes, use the null terminated way.

A: Just use nul terminators all the way:
find . -name "*.1" -print0 | sort -z | xargs -0 cat > list.txt

Your attempt failed because you just deleted all line feeds (effectively concatenating all filenames). This renders the same way in a terminal as NUL-separated filenames, but doesn't work the same way.


text:
Q: why is this code not working--django paginate I'm trying to paginate a page in order to display 1 status per page...it fails to paginate and it doesn't display the link to the next pages
views.py
def post_list(request):

        posts= Post.objects.all()
        paginator = Paginator(post_list, 1)
        page = request.GET.get('page')
        return render(request, 'news.html', {'posts':posts})

templates
{% for num in posts.paginator.page_range %}

    {% if posts.number == num %}

        {{ num }}

            {% else %}

           {{ num }}

        {% endif %}

{% endfor %}

A: posts is still the Post.objects.all(..) queryset, you still need to retrieve the page with .get_page(..) [Django-doc]:
from django.core.paginator import Paginator

def post_list(request):
    post_list = Post.objects.all()
    paginator = Paginator(posts, 1)
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    return render(request, 'news.html', {'posts':posts})
Without making a page, you do not do much more than just constructing a pagiantor, and then throw that away.
In your template, you can thus render this as:
{{ posts.number }}


text:
Q: VB.NET SerialPort.Write(string) throws an uncatchable exception, and breaks COM port I'm working with the VB.NET SerialPort class and I have created a collection of objects that represent the configuration our hardware devices so that I can alter the configuration and update the devices through the a USB virtual serial port. These objects are of a polymorphic nature and each device eventually inherits form a class called CmdSender which handles the COM IO.
When finally removing all known bugs and publishing an application to another PC (which has .NET run-time installed but not Visual Studio) occasionally an uncatchable exception is thrown when calling SerialPort.Write(string) from my code.
This is the error message and topmost part of the stacktrace.

System.IO.IOException: A device attached to the system is not
  functioning.
at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode,
  String str)    at System.IO.Ports.SerialStream.EndWrite(IAsyncResult
  asyncResult)    at System.IO.Ports.SerialStream.Write(Byte[] array,
  Int32 offset, Int32 count, Int32 timeout)    at
  System.IO.Ports.SerialPort.Write(String text)    at
  TDDevice.CmdSender.SendPure(String Cmd, Boolean AddCheckSum)

I can't find any solutions online to this problem.
It's also worth noting that when this exception is thrown that the application cannot simply be restarted (although that's still not ideal anyway) but the USB COM device must be removed and reinserted into the machine, without doing this my application warns me that no COM port can be found (a check that I've built in), this is telling me that .NET cannot interact with the COM port after this, I am yet to test whether other API's are able to still use the port after this occurs to confirm whether the issue affects just .NET or the port itself (however device manager still lists the port).
My question is why is this happening, and how can it be prevented?
(any answers in C# should be fine as I can hopefully translate but VB would be appreciated)

A: I worked a little with serial port communicating with a PIC microcontroller and a got errors like this. My solution at that time was to close the port after sending the data, and open again when needed to send again. I think since is a USB convertor the device may enter sleep mode or something similar.
 sendData(){
     open port
     send data
     wait for response if needed
     close port
    }

sorry for not posting code but you get the ideea


text:
Q: Is it possible to edit origin of indexeddb? I am using a third party script in my web page which has logic for storing data in localstorage and indexeddb. The storage is having the origin as the domain of the web page hosted in my domain. I want to have domain of the third party script where the storage logic is. Is that possible?
Edit: I should have been more clear: Why is indexeddb using origin of html page than of origin of javascript file when they are hosted in 2 different domains?

A: It is not possible. Cookies, localStorage or indexedDB resourced are límited to domain which has issued them. It is called same-origin policy
https://en.m.wikipedia.org/wiki/Same-origin_policy
Note that if you use a third party script in your domain, local storage of your domain will be used
To use localStorage issued in a secondary domain (which you control), you can use an embedded iframe of the other domain to access resources, and communicate with the main domain with postMessage
See http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage
And in this project you have a full example of a cross domain SSO sharing an authentication token stored in localStorage between several domains
https://github.com/Aralink/ssojwt


text:
Q: открытие окошка редактирования для календаря как сделать так что б при клике на ячейку таблицы, открывалось окно в которое бы вписывались данные события и оно сохранялось в localstorage
как на картинке, как записать в localstorage я понимаю, а как сделать так что б при клике на другое окошко, это пропадало и как правильно добавлять к ячейке это окошко.
главное условие нельзя использовать jquery

https://jsfiddle.net/ovutdzef/1/

A: Достаточно окну добавить id, и в событие "onclick" добавить удаление этого окна если, оно есть на странице.
var emptyCreateEventWindow = '

<input type="text" placeholder="Событие"><input type="text" placeholder="День, месяц, год"><input type="text" placeholder="Имена уччастников">
<textarea name="" id="" cols="30" rows="8" placeholder="Описание"></textarea><input type="submit" value="Готово" class="create_event_button "><input type="submit" value="Удалить" class="create_event_button edit-cancel">
+

';
function addHandlers(table) {
  var tds = table.querySelectorAll("td");
  for (var i = 0; i < tds.length; i++) {

    tds[i].onclick = function() {
        if(document.getElementById('openWindow'))
        document.getElementById('openWindow').remove();
      this.innerHTML = emptyCreateEventWindow;
    };
  }
}


text:
Q: Font not working in Google Chrome extension I'm developing an extension for Google Chrome. I want to use custom fonts in my extension. I have declared a @font-face rule in my stylesheet like this:
@font-face {
    font-family: "Anonymous Pro";
    src: url("../assets/fonts/Anonymous-Pro/Anonymous-Pro-700.ttf");
}

But, this doesn't seem to work. I get an error like this:
GET chrome-extension://klcdnidgljemjhocdlalimcigcfmlbbk/assets/fonts/Anonymous-Pro/Anonymous-Pro-700.ttf net::ERR_FILE_NOT_FOUND

Do I need to set any permissions in my manifest file to use custom fonts?
Please help.

A: It's likely that the font doesn't exist in the set location. Recheck your URL
Here is a much detailed answer on Packaging a font with a Google Chrome extension.


text:
Q: Python request .json() method change symbols i will be very appreciated for any help
I'm getting info from website... And generally everyting works fine... But, just look at code:
r = requests.get(s_url)
print r.text
>>>[{"nameID":"D1","text":"I'll understand what actually happened here."}]
print r.json()
>>>[{u'nameID':u'D1',u'text':u'I\u2019ll understand what actually happened
   here.'"}]

As you see after r.json() ' was changed to \u2019.
Why it did it? How I can force to don't make such changes?
Thanks

A: It is not an apostrophe (') in your string, but a (unicode) character "right single quotation mark" ('). Which may not be as obvious to a naked eye (depending on a font used easier or more difficult to spot), but it is still a completely different character to the computer.
>>> u"'" == u"'"
False

The difference you see between displaying text attributed and what json() method returns is just a matter of representation of that character.
For instance:
>>> s = u'''
>>> print s
'

But when you do the same with a dictionary returned by json() individual keys and values thereof are formatted using repr() resulting in:
>>> d = {'k': s}
>>> print d
{'k': u'\u2019'}

Just as in:
>>> print repr(s)
u'\u2019'

Nonetheless, it is still the same thing:
>>> d['k'] == s
True

For that matter:
>>> u''' == u'\u2019'
True

You may want to have a look at __str__() and __repr__() methods as well as description of print for more details:

*

*https://docs.python.org/2.7/reference/datamodel.html#object.str

*https://docs.python.org/2.7/reference/datamodel.html#object.repr

*https://docs.python.org/2.7/reference/simple_stmts.html#print


text:
Q: Ordering of energy levels of bound states of central potential I have been attempting to solve the following central potential using schrodinger equation.$$V(r)=a_{1}r^{2}+\frac{a_{2}}{r^{2}}+a_{3}$$
The radial equation becomes, $$\Bigg[\frac{-\hbar^{2}}{2m}\dfrac{d^{2}}{dr^{2}}+V(r)+\frac{l(l+1)}{r^{2}}\Bigg]u(r)=Eu(r)$$
I have used laplace transform to solve this problem to get the eigen values. Defining $$u(y)=y^{-\frac{\nu}{2}}\phi(y)$$ I get the following differential equation,$$\Bigg[y\dfrac{d^{2}}{dy^{2}}-\bigg(\nu-\dfrac{1}{2}\bigg)\dfrac{d}{dy}-\dfrac{1}{4}\bigg(\mu^{2}y-\epsilon^{2}\bigg)\Bigg]\phi(y)=0$$
where, $$\nu(\nu+1)=\dfrac{2ma_{2}}{\hbar^{2}}+l(l+1)$$  $$\mu^{2}=\dfrac{2ma_{1}}{\hbar^{2}}$$ $$\epsilon^{2}=\dfrac{2mE}{\hbar^{2}}$$ Now after doing laplace transform I have the following result $$\bigg(t^{2}-\dfrac{\mu^{2}}{4}\bigg)\dfrac{df(t)}{dt}+\bigg[\bigg(\nu+\dfrac{3}{2}\bigg)t-\dfrac{\epsilon^{2}}{4}\bigg]f(t)$$ The soluion in laplace space is,
$$f(t)=N\bigg(t+\dfrac{\mu}{2}\bigg)^{-\dfrac{\epsilon^{2}}{4\mu} -\dfrac{1}{2}\bigg(\nu+\dfrac{3}{2}\bigg)}\bigg(t-\frac{\mu}{2}\bigg)^{\dfrac{\epsilon^{2}}{4\mu}+\dfrac{1}{2}\bigg(\nu+\dfrac{3}{2}\Bigg)}$$
To get a finite wave functions the solutions have to be a finite polynomial $$\dfrac{\epsilon^{2}}{4\mu}-\dfrac{1}{2}\bigg(\nu + \dfrac{3}{2}\bigg)=n$$ where, $$n=0,1,2,3...$$ The energy eighen values are ,$$E_{nl}=\sqrt{\dfrac{8\hbar^{2}a_{1}}{m}}\bigg(\dfrac{1}{2}+\dfrac{1}{4}\sqrt{1+4l(l+1)+\dfrac{8ma_{2}}{\hbar^{2}}}\bigg)$$
I have understood everything except the condition to be imposed on the angular quantum number $l$ for a given value of radial quantum number $n$. For instance, suppose $n$=3 the minimum value of $l$ = 0, but the what is the maximum value of $l$ ? What is the condition on $l$ for a given $n$ ? I have followed the following research article
*Exact solutions of the Schrödinger equation via Laplace transform approach: pseudoharmonic potential and Mie-type potentialshttps://link.springer.com/journal/10910 *


text:
Q: What are the differences between memory coherence and cache coherence? https://en.wikipedia.org/wiki/Memory_coherence says:

Memory coherence is an issue that affects the design of computer
systems in which two or more processors or cores share a common area
of memory.[1][2][3][4]
In a uniprocessor system (whereby, in today's terms, there exists only
one core), there is only one processing element doing all the work and
therefore only one processing element that can read or write from/to a
given memory location. As a result, when a value is changed, all
subsequent read operations of the corresponding memory location will
see the updated value, even if it is cached.
Conversely, in multiprocessor (or multicore) systems, there are two or
more processing elements working at the same time, and so it is
possible that they simultaneously access the same memory location.
Provided none of them changes the data in this location, they can
share it indefinitely and cache it as they please. But as soon as one
updates the location, the others might work on an out-of-date copy
that, e.g., resides in their local cache. Consequently, some scheme is
required to notify all the processing elements of changes to shared
values; such a scheme is known as a memory coherence protocol, and if
such a protocol is employed the system is said to have a coherent
memory.

https://en.wikipedia.org/wiki/Cache_coherence says

In computer architecture, cache coherence is the uniformity of shared resource data that ends up stored in multiple local caches. When clients in a system maintain caches of a common memory resource, problems may arise with incoherent data, which is particularly the case with CPUs in a multiprocessing system.
In the illustration on the right, consider both the clients have a cached copy of a particular memory block from a previous read. Suppose the client on the bottom updates/changes that memory block, the client on the top could be left with an invalid cache of memory without any notification of the change. Cache coherence is intended to manage such conflicts by maintaining a coherent view of the data values in multiple caches.

What are the differences between memory coherence and cache coherence?  They look identical.
Thanks.

A: When you use caches, data isn't usually written to memory immediately. Consider two cores A and B with caches X and Y and memory M.
If A writes data, it will update cache X but not immediately memory M. If B tries to read this data, the old version might be in cache Y (and B gets the wrong data), or Y might transfer the data from M to Y (and B gets again the wrong data).
The most efficient way to solve the problem would be to move the data from X to Y, avoiding writing to and reading from memory altogether. That would be "cache consistency".
And since this is all quite inefficient, processors won't do this automatically. And most programming languages say that if you read data modified by another thread, that's your own problem until you use special precautions.

A: Cache coherence defines some ordering of loads/stores over a single address.
Memory consistency defines some ordering loads/stores over multiple addresses.
When looking at the wiki, it seems that memory coherence is the same as cache coherence.
For more information see (you can download the book for free)
https://www.morganclaypool.com/doi/10.2200/S00962ED2V01Y201910CAC049


text:
Q: Why do I see a tiny number in the corner of VMware Workstation? In the corner of VMware Workstation, I see a tiny, inexplicable, unclickable, un-Googlable number. It appears on top of everything. I think it used to be a 1, now it's a 2.
What's up with this number?


text:
Q: Why use double pointer when inserting node in sorted order in linkedlist? typedef struct node node;
struct node {
    int data;
    node *next;
};

int insert_asc(node **phead, int data) {
    node **traser;
    node *newnode = malloc(sizeof(node));
    if (newnode == 0)
        return 0;
    newnode->data = data;

    for (traser = phead; *traser != 0; traser = &(*traser)->next)
        if (data <= (*traser)->data)
            break;

    newnode->next = *traser;
    *traser = newnode;
    return 1;
}

The confusing part for me is when you dereference a double pointer traser.
how come (*traser)->next holds the next node's address?
and what exactly is *traser here?

A: You are using a double pointer here in order to keep track of the head of your list.
If you were using a simple pointer here and exchanged the nodes, you would risk loosing the address of some nodes of your list.
This is because if you were passing a simple pointer to the head of your list, you would then manipulate a copy of you head address in your function, therefore when you exchange positions in your function, the address of your head would still be the same, if you exchanged the head with another node, then the address of all nodes before the old head would be lost after your function modifies your list.
Edit: pythontutor.com is a tool that helped me understanding the behavior of linked list quite easily thanks to its excellent visualization tool, I would highly recommend you to use it.

A: Double pointers are used in the posted code for two separate purposes:

*

*node **phead: the head of the list is passed by referenced so it can be updated by insert_asc if the new node must be inserted at the head of the list. Passing by reference is not possible in C, the idiomatic way to achieve it is to pass a pointer to the value to be updated by the function, hence a double pointer phead.

*node **traser: To avoid making a special case of the empty list and the insertion at the head of the list, the programmer uses a pointer to keep track of the place to insert the new node. traser first points to the head of the list which in this case is the value of phead and is updated to point to the link between nodes, the next member of the current node, when it is determined that the new node must be inserted after the current one. This is an elegant way to implement insertion without a special case. C allows thanks to pointers, it is not possible in java nor javascript because these language do not have generalised pointers.
Note however that the code could be make more readable by use NULL instead of 0 when comparing pointers:
typedef struct node node;
struct node {
    int data;
    node *next;
};

int insert_asc(node **phead, int data) {
    node **traser;
    node *newnode = malloc(sizeof(node));
    if (newnode == NULL)
        return 0;
    newnode->data = data;

    for (traser = phead; *traser != NULL; traser = &(*traser)->next) {
        if (data <= (*traser)->data)
            break;
    }
    newnode->next = *traser;
    *traser = newnode;
    return 1;
}

Note also that new nodes with a given value of data are inserted before nodes with the same data value. It does not make a difference in this case and may be a little faster for lists with many duplicates, but if the payload was more elaborate, this insertion method would implement a non-stable sort, whereas using < instead of <= would make the sort stable.
For illustration, here is alternative implementation that does not use a double pointer for the insertion point and needs extra tests for the special cases:
int insert_asc(node **phead, int data) {
    node *cur;
    node *newnode = malloc(sizeof(node));
    if (newnode == NULL)
        return 0;
    newnode->data = data;

    cur = *phead;
    if (cur == NULL || cur->next == NULL) {
       newnode->next = cur;
       *phead = newnode;
    } else {
        while (cur->next != NULL && data < cur->next->data)
            cur = cur->next;
        newnode->next = cur->next;
        cur->next = newnode;
    }
    return 1;
}


text:
Q: single click and double click I have created coding for single and double click.  I want to prevent single click event when making double click.
When making single click, the shape will changed circle to rectangle and vice versa.
When making double click, the shape is destroyed.
While making double click, the single click event is also executed.  I want to prevent single click event at that time.
Any idea should help me.
Here the coding
void HelloWorld::ccTouchesEnded(CCSet *touch, CCEvent *pEvent)
{
   CCTouch* myTouch = (CCTouch*)touch->anyObject();
   CCTime::gettimeofdayCocos2d(&endTime, NULL);
   duration = CCTime::timersubCocos2d(&startTime, &endTime); //duration of tap in milliseconds
   finalPosition = myTouch->getLocation();
   float distance = distanceBetweenPoints(finalPosition,initialPosition);

   if (duration<kTapMaxDuration && distance <kTapMaxDistance)
   {
      taps++;
   }
   else
     taps=0;

    CCPoint touchLocation=myTouch->locationInView();
touchLocation=CCDirector::sharedDirector()->convertToGL(touchLocation);
    CCPoint nodePosition = this->convertToNodeSpace(touchLocation);
this->mouseUp(b2Vec2(nodePosition.x/kPhysicsPTMRatio,nodePosition.y/kPhysicsPTMRatio));
    CCTime::gettimeofdayCocos2d(&startTime, NULL);
 }

And the mouse up event,
 void HelloWorld::mouseUp(b2Vec2 p)
 {
     b2AABB aabb;
 b2Vec2 d = b2Vec2(0.001f, 0.001f);
 aabb.lowerBound = p - d;
 aabb.upperBound = p + d;

 MyQueryCallback callback(p);

 world_->QueryAABB(&callback, aabb);

     if (callback.m_fixture)
 {
       b2Body *body = callback.m_fixture->GetBody();
       BodyNode *node = (BodyNode*) body->GetUserData();
   if( node && node->isTouchable_ )
       {
        if( (dynamic_cast<Shape1*>(node) != NULL))
        {
            if (taps == 1)
            {
                this->removeB2Body(body);
            }
            else if(taps < 1)
            {
                dynamic_cast<Shape1*>(node)->toggleShape();
            }
        }
    }
}

}


text:
Q: Freeplane reports it's not compatible with Java 10 when attempting to install and run on Ubuntu 18 how do I resolve? I have been trying to install mindmapping software on Ubuntu 18 Bionic Beaver now for the last 3 days.  I'm getting a little weary from all of the application research and many, many failed install and run attempts for various mindmapping s/w.  I first tried to install XMind8 and then XMind 7.5 and could not get it to run even though I followed 4 dif "solution instructions"  I gave up because I realized that many people were having the same problem and asking for the same help.  I figured the XMind folks, just wasn't going to make it easy for use to install their product.  Now I'm started on Freeplane 1.7.7.  I am certain it's the lasted version.  I did the unzip and execution command
sh freeplan.sh
and I get this error message:  Dialog box heading -->  "Incompatible JRE version"  and in the dialog box "Freeplane is not compatible with Java 10, exiting"
I did the command         java -version     in the terminal window to verify that yes ai am running java 10.
How do I get Freeplane 1.7.7 to work on my computer without uninstalling Java 10 which seems to be the default and latest JDK for Ubuntu 18??  I really want to get started with my mindmapping and I am at my limit of doing things to resolve my issue.  Please someone help me!!!  I believe Freeplane 1.7.7 needs JDK version 8.  I don't want to disrupt anything else that is going on where other applications may need JDK 10.  Thank You in advance.

A: You can have more then one Java installation on your Ubuntu. You can install Java 8 (1.8) next to Java 10 (Java 11).
sudo apt update
sudo apt install openjdk-8-jdk
See if you can point somehow only Freeplane 1.7.7 to start with java 8. If there is configuration file (inside Freeplane 1.7.7) with java virtual machine path or something. If you can set it to the Java 8.
If not then you can try to put Java 8 as default and see if you have some problems.
Attention: you can get some problems with other programs that use Java 10 (Java 11) if you execute the next steps!
For more information how to do it in section (Managing Java): https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-on-ubuntu-18-04
I hope I don't miss some steps but first you set which should be the default Java.
sudo update-alternatives --config java
Also many programs need to know JAVA_HOME. You have to set it for your Java version.
Check again which is your active version:
sudo update-alternatives --config java
Java default install directories are:
OpenJDK 11 is located at /usr/lib/jvm/java-11-openjdk-amd64/bin/java.

OpenJDK 8 is located at /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java.

Oracle Java 8 is located at /usr/lib/jvm/java-8-oracle/jre/bin/java.

You have to set it inside: /etc/environment
sudo nano /etc/environment
then add in the end of the file you active Java 8 installation
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java"
or
JAVA_HOME="/usr/lib/jvm/java-8-oracle/jre/bin/java"
And then reload:
source /etc/environment
And check if it correct:
echo $JAVA_HOME
Check if your program is working. If you see something broken you can set it back to Java 11.
Good luck to all!


text:
Q: React form can be submitted twice despite conditional render I have a React application coupled to Redux. There is a component rendering a form wrapper (a custom implementation of Formik), while the form inputs themselves are rendered by a child component.
(Not the exact code, but gets the point across.)
...
render() {
  const {
    config,
    updateContactDetails,
    errorMessages,
    contactDetails,
    previousFormValues,
    isUpdating,
  } = this.props;
  const { apiBaseUrl, fetchTimeout, globalId } = config;
  const initialValues = previousFormValues || getInitialContactDetailsValues(contactDetails);

  if (isUpdating) return <Spinner />;
  return (
      <Form
        initialValues={initialValues}
        validate={(values) => validate(values, errorMessages)}
        onSubmit={(values) => {
          updateContactDetails(apiBaseUrl, globalId, values, fetchTimeout); // dispatch action
        }}
      >
        <ContactDetailsForm content={content} />
      </Form>
  );
}
...

When you click the submit button in ContactDetailsForm, the value of isUpdating in the Redux store is set to true. As you can see above, that causes the the form to be replaced with a spinner component. However, it is somehow possible to submit the form twice by clicking the button twice.
How can this be? Could there be re-render happening before the one that replaces the form with the spinner? I know I can solve the problem by passing isUpdating into ContactDetailsForm and using it to disable the button, but I still want to illuminate the cause.
EDIT
The reducer looks something like this, in case it helps:
case UPDATE_CONTACT_DETAILS_START: {
  return {
    ...state,
    errorUpdatingContactMethods: {},
    hasUpdatedContactDetails: false,
    isUpdating: true,
    contactDetailsValues: action.values,
  };
}

A: You should instead set a disabled property on the button based on the isUpdating prop. It might be that it's just a race condition.