text:
Q: Why does my ajax call not returning my data from controller? I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
    var elemEmployee = 55;
    var startDT = $('#searchFilterStartDate').val();
    var endDT = $('#searchFilterEndDate').val();

    $.ajax({
        url: "/Modules/GetDTRRecord",
        type: "GET",
        data: {
            EmployeeID: elemEmployee,
            DateFrom: endDT,
            DateTo: startDT,
        },
        dataType: "json",
        success: function(data) {

            console.log('Data Success ');

             console.log(data);

        }
    });
}

here's my controller:

        [HttpGet]
        public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
        {
            var entity = new DTRRecordList();

            return entity.GetDTR(data);
        }

As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.

A: You need to return JSON from your Controller method. You can change your method to:
    [HttpGet]
    public JsonResult GetDTRRecord(DTRRecordList.Entity data)
    {
        var entity = new DTRRecordList();
        var getDTR= entity.GetDTR(data);
        return Json(new {dtrData= getDTR});
    }

And in your Ajax call:
$.ajax({
    url: "/Modules/GetDTRRecord",
    type: "GET",
    data: {
        EmployeeID: elemEmployee,
        DateFrom: endDT,
        DateTo: startDT,
    },
    dataType: "json",
    success: function(data) {
         console.log('Data Success ');
         console.log(data.dtrData);
    },
    error: function(error) {
        console.log(error)
    }
});

After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
    //On Clink "Search Button"
    $("#searchbtn").click(
    function () { GetRecord(); });
});

The data seems to be coming as expected.


text:
Q: list of dictionaries comprehension - multiple conditions I have a problem with multiple conditions with list:
listionary = [{u'city': u'paris', u'id': u'1', u'name': u'paul'},
              {u'city': u'madrid', u'id': u'2', u'name': u'paul'},
              {u'city': u'berlin', u'id': u'3', u'name': u'tom'},
              {u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

I try to delete items that meet both conditions simultaneously.
[elem for elem in listionary if (elem.get('name')!='paul' and elem.get('city')!='madrid')]

In this case element is removed if meet at least one condition, I try to do it in several ways, any ideas?
Expected output:
[{u'city': u'paris', u'id': u'1', u'name': u'paul'}
{u'city': u'berlin', u'id': u'3', u'name': u'tom'}
{u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

I would like to remove element which meet both conditions.

A: Try changing the and to or.
[elem for elem in listionary if (elem.get('name')!='paul' or elem.get('city')!='madrid')]

Remember de morgan's laws. Informally: when you negate a boolean expression, you have to switch and with or in addition to switching "==" with "!=".

A: Your condition should have been like this
[e for e in data if not (e.get('name') == 'paul' and e.get('city') == 'madrid')]

Output
[{u'city': u'paris', u'id': u'1', u'name': u'paul'},
 {u'city': u'berlin', u'id': u'3', u'name': u'tom'},
 {u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

This checks if the current element's name is paul and city is madrid. If both the conditions are satisfied, the not outside will flip it, so you will get False and the item will be omitted.
Basically you are checking if the current item is the one which you don't want and make the if condition fail if it is.

A: You could use itemgetter to get all the values into a tuple and then compare that:
>>> from operator import itemgetter
>>> name_and_city = itemgetter('name', 'city')
>>> [e for e in listionary if name_and_city(e) != ('paul', 'madrid')]

A: Your data is in fact quite static. In this case you can use namedtuple for performance on large data.
from collections import namedtuple
Profile = namedtuple('Profile', ['city', 'id', 'name'])
listionary = [Profile(*d) for d in listionary]

To improve readability, you can refactor the condition as a lambda expression (this assumes you are using namedtuple):
removed = lambda ele: \
   ele.name == 'paul' or \
   ele.city == 'madrid'
output = [ele for ele in listionary if not removed(ele)]

I think this is easier to maintain and more readable, but it may depends on who is looking at it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve tags inside certain tag for XML using GetElementsByTagName/SelectNode/SelectSingleNode? Let say I have a XML with this format:
<TEST>
    <DRINK>
        <NAME>Ice tea</NAME>
        <NAME>Milo</NAME>
        <NAME>Coffee</NAME>
    </DRINK>
    <FOOD>
        <NAME>Fried Rice</NAME>
        <NAME>Hamburger</NAME>
        <NAME>Fried Noodles</NAME>
    </FOOD>
</TEST>

How to retrieve only food names and put them in the ASP.NET web form textbox?
This is my current code:
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
root = doc.DocumentElement;
TextBox1.Text = root.GetElementsByTagName("NAME")[0].InnerText;
TextBox2.Text = root.GetElementsByTagName("NAME")[1].InnerText;
TextBox3.Text = root.GetElementsByTagName("NAME")[2].InnerText;

This code will instead retrieve drink names instead of food names. How to make it read NAME tags in FOOD tag?

A: By using XmlNode.SelectNodes Method with providing the XPath.
var foodElements = root.SelectNodes("FOOD/NAME");

Console.WriteLine(foodElement[0].InnerText);
Console.WriteLine(foodElement[1].InnerText);
Console.WriteLine(foodElement[2].InnerText);

Sample .NET Fiddle

A: Basic xml parsing.
this:
    {
        string sXML
            =
          @"<TEST>
                <DRINK>
                    <NAME>Ice tea</NAME >
                    <NAME>Milo</NAME >
                    <NAME>Coffee</NAME>
                </DRINK>
                <FOOD>
                    <NAME>Fried Rice</NAME>
                    <NAME>Hamburger</NAME>
                    <NAME>Fried Noodles</NAME>
                </FOOD>
            </TEST>";

        XmlDocument myXml = new XmlDocument();
        myXml.LoadXml(sXML);

        XmlNodeList myNodes = myXml.SelectNodes("TEST/FOOD/NAME");

        foreach (XmlNode OneNode in myNodes)
        {
            Debug.Print(OneNode.InnerText);
        }
    }

output:


text:
Q: Bind items in generic list and Serialize This is my code:
List<Test> list = new List<Test>();
for (int j = 0; j < dss.Tables[0].Rows.Count; j++)
{
    list.Add(new Test(dss.Tables[0].Rows[j]["PSet"].ToString(),
                      Convert.ToInt32(dss.Tables[0].Rows[j]["Score"].ToString())));
}
StringBuilder data = new StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();
json.Serialize(list, data);
hdlineData.Value = list.ToString();

But it's not serializing my list, if i am not binding list correctly. Please suggest me how to bind list in Json format.

A: You can use the [Serializable()] attribute on your custom class and then:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var Json = serializer.Serialize(myObject);

To ignore specific properties in the object you're serializing, simply place the [NonSerialized] attribure on them.
I Just Referred From HERE


text:
Q: Mantener los datos al pulsar flecha atrás del navegador PHP Mi problema es el siguiente:
Estoy en la página A.php y si quiero navegar mediante un botón a la página B.php funciona correctamente. El problema viene cuando de B.php quiero pasar a (pulsando la flecha atrás en el navegador) A.php manteniendo los datos que tenía en A.php.
¿Por qué, además de no mantenerse los datos, me muestra la siguiente página?
Código que muestra al pulsar para atrás:
Confirmar reenvío del formulario
Esta página web necesita los datos introducidos anteriormente para mostrarse correctamente. Puedes volver a enviar los datos, pero se repetirán las acciones que haya realizado la página.
Pulsa el botón de actualización de página para que se vuelvan a enviar los datos necesarios para cargar la página.
ERR_CACHE_MISS

Por ejemplo, envío los datos mediante formularios con método POST. ¿Es correcto?
Muestro código de, por ejemplo, la página A.php en mi caso:
<?php
    include_once "Clases/BD.php";

    //Iniciar una nueva sesión o reanudar la existente.
    session_start();

    //Si existe la sesión "cliente"..., la guardamos en una variable.
    if (isset($_SESSION['cliente'])){
        $cliente = $_SESSION['cliente'];
    }

    //Si nos hemos salido de la sesión del administrador, destruimos la sesión.
    if(isset($_REQUEST["salir"])){
       //Borramos o destruimos la sesión "administrador".
       unset($_SESSION["administrador"]);
       //session_destroy();
    }
?>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Reservar</title>
        <link rel="stylesheet" href="css/estilos_reservar.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">

            <?php
            //Si existe la sesión "cliente"...
            if(isset($_SESSION['cliente'])){
                echo "
Bienvenido ".$cliente."   ";
                echo "Salir
";
                //Si existe y hemos pulsado el link "Salir"...
                if(isset($_REQUEST["salir"])){
                    //Borramos o destruimos la sesión "cliente".
                    unset($_SESSION["cliente"]);
                    //Redireccionamos a la página "iniciar_sesion_cliente.php" en 0 segundos.
                    header("Refresh:0; url=iniciar_sesion_cliente.php");
                }
            }
            ?>

                <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="mibusqueda" id="mibusqueda" method="POST" class="form_buscar">

RESERVAR

                    Entrada:
                    <input type="text" placeholder="Fecha de entrada" name="check_in" id="check_in" value="<?php if(isset($_POST['check_in'])){ echo $_POST['check_in']; }?>">

                    Salida:
                    <input type="text" placeholder="Fecha de salida" name="check_out" id="check_out" onchange="calculoNoches();" value="<?php if(isset($_POST['check_out'])){ echo $_POST['check_out']; }?>" disabled>

                    Personas:
                    <?php
                    echo "<select name='personas'>";
                        //Si la variable no existe, establecemos el valor por defecto. personas=2
                        if(!isset($_POST['personas'])){
                            $_POST['personas'] = 2;
                        }

                        for ($i=1; $i<11; $i++) {
                            if($i == $_POST['personas']){
                                echo "<option value='$i' selected='selected'>$i</option>";
                            }else{
                                echo "<option value='$i'>$i</option>";
                            }
                        }
                    echo "</select>";
                    ?>

                        <input type="submit" value="Buscar" name="buscar" id="buscar">

                </form>

                <?php
                //Si pulsamos el botón "buscar"...
                if(isset($_POST["buscar"]) && $_POST["check_in"]!="" && $_POST["check_out"]!=""){
                    $check_in = $_POST["check_in"];
                    $check_out = $_POST["check_out"];
                    //Llamamos al método "obtenerCabanasPorFecha" y le pasamos los parámetros del formulario.
                    $datos = BD::obtenerCabanasPorFecha($check_in, $check_out);
                    echo "
";
                    foreach($datos as $cabana){
                        echo "
Coste de la cabaña ".$cabana->getNombre()." por noche: ".$cabana->getPrecio()."€/noche

";
                        $personas = $_POST["personas"];
                        //Calcular el número de noches entre dos fechas.
                        $check_in_analizar = new DateTime($check_in);
                        $check_out_analizar = new DateTime($check_out);
                        $resta = $check_in_analizar->diff($check_out_analizar);
                        $noches = $resta->format('%a');
                        //Mostramos al cliente el coste TOTAL y el coste "parcial" por persona.
                        $pago_total = $cabana->getPrecio()*$noches;
                        $pago_pax = $pago_total/$personas;

                        $_SESSION["pago_total"] = $pago_total;

                        echo "".$personas." persona/s    ".$noches." noche/s    ".$pago_total."€/total (".round($pago_pax,2)."€/pax)"."";
                        echo "<form action='confirmacion_reserva.php' method='POST' name='mireserva'>";
                            //Campos hidden (oculto) donde guardamos un valor que NO queremos mostrar.
                            echo "<input type='hidden' name='idcabana' value='".$cabana->getIdcabana()."'/>";
                            echo "<input type='hidden' name='check_in' value='".$check_in."'/>";
                            echo "<input type='hidden' name='check_out' value='".$check_out."'/>";
                            echo "<input type='hidden' name='personas' value='".$personas."'/>";
                            echo "<input type='hidden' name='pago_total' value='".$pago_total."'/>";
                            echo "<input type='submit' name='reservar' value='Reservar'/>";
                        echo "</form>";
                        echo "
";

                        //Cargamos las imágenes en un array $imagenes.
                        $imagenes = $cabana->getImagenes();
                        foreach($imagenes as $imagen){
                            echo "     ";
                        }
                        echo "
";

                        //Cargamos la descripción de la cabaña.
                        echo "".$cabana->getDescripcion()."
";
                        echo "
";

                        //Cargamos los accesorios de la cabaña en cuestión.
                        $objeto_accesorios = BD::obtenerAccesoriosPorCabana($cabana->getIdcabana());
                        $todos_accesorios = BD::todosAccesorios();
                        //echo '
'; // Lo recogemos en un div
                        foreach($todos_accesorios as $objeto){
                            $existe = false;
                            foreach($objeto_accesorios as $columna){
                                //Si el accesorio global está en el accesorio de la cabaña, true.
                                if($objeto->getIdaccesorio() == $columna->getIdaccesorio()){
                                    $existe = true;
                                    break;
                                }
                            }
                            if($existe){
                                echo "

                                    getDescripcion().".png' height='28px' width='34px' />

                                    getIdaccesorio()."'>
                                        <input type='hidden' value='".$objeto->getIdaccesorio()."' id='accesorio".$objeto->getIdaccesorio()."' name='accesorios[]'>".$objeto->getDescripcion()."
";
                            }
                            $existe = false;
                        }
                        //echo '
';
                        //http://librosweb.es/referencia/css/clear.html
                        echo "

";

                        //Cargamos las opiniones de la cabaña.
                        $opiniones = BD::obtenerOpinionesPorCabana($cabana->getIdcabana());
                            if($opiniones == null){
                                //echo "

Aún no hay opiniones...

";
                            }else{
                                foreach ($opiniones as $comentario){
                                    $fecha = new DateTime($comentario["fecha"]);
                                    echo "

".$fecha->format ('d/m/Y')."(".$comentario["idemail"].") - ".$comentario["opinion"]."

";
                                }
                            }
                        echo "
";
                        echo "
";
                    }
                }
                ?>

Muestro código de, por ejemplo, la página B.php en mi caso:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Formulario de Login - Cliente</title>
        <link rel="stylesheet" href="css/estilos_iniciar_sesion.css">

        <form name="miformulario" id="miformulario" action="logueo_cliente.php" method="POST" class="form" onsubmit="return validar_iniciar_sesion_cliente();">

CLIENTE

INICIAR SESIÓN

            <input type="text" placeholder="🔐 Usuario" name="email" id="email" tabindex="1">
            <input type="password" placeholder="🔐 Contraseña" name="password" id="password" tabindex="2">

                <?php if(isset($_GET['error']) && $_GET['error'] == 'true'): ?>

¡Sus datos no son correctos!

                <?php endif; ?>

                <input type="submit" value="Iniciar sesión">

¿Aún no tienes una cuenta? Regístrate aquí

He olvidado mi contraseña

 Entrar como invitado

        </form>

Si en esta página B.php pulso la flecha para atrás del navegador para volver a A.php me sale la información del mensaje que puse anteriormente.
¿Por qué? ¿Una posible solución?

A: Creo que el problema viene por como mandas las variables, cuando envías los datos con tipo POST se mandan de una manera que procesa una solicitud de envío, intenta cambiando esta linea,
 <form name="miformulario" id="miformulario" action="logueo_cliente.php" method="POST" class="form" onsubmit="return validar_iniciar_sesion_cliente();">

por esta otra:
 <form name="miformulario" id="miformulario" action="logueo_cliente.php" method="GET" class="form" onsubmit="return validar_iniciar_sesion_cliente();">

y deberás hacer los arreglos correspondientes.
el problema radica en que cuando pasas de A a B se mandan los datos de una manera que tu pagina recibe la información, pero al no estar "visuales o tangibles" ( por así decirlo ) cuando regresas, tu pagina no logra obtener los valores, cambiando de POST a GET lo que haces es mandar la información por URL facilitando a tu pagina obtener los valores de nuevo, puedes manejarlo así, o para solucionar tu problema podrías manejar una sesión con la información para mantenerla si cambias de pagina y cuando guardes la información podrías destruir esa información para cargar nueva de ser necesario, espero te sirva.

A: @omaza1990 respondiendo a tu pregunta ( soy el mismo @user9186623 ya pude configurar bien mi cuenta ). afirmativamente tienes que cambiar POST por el GET creo que es la solución mas sencilla. intentalo y dime que tal te fue! exito!


text:
Q: Using EditText to pass data from fragment to fragment I use EditText to enter an integer value and Integer.parse it in the first fragment and use an interface to send the value to the second fragment. I applied the ViewPager2 as well. I am not that adept in using View Pager as this is my first time in using it. Please post code if possible.
So my questions are

*

*Where did i go wrong in my code for running it? (The error lies in
SM.sendData(Integer.parseInt(text1.getText().toString()));

which i don't get what is the mistake)

*Is there another way to transfer the value using another method such as Bundle?
First Fragment:
public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;
    SendMessage SM;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final EditText text1 = view.findViewById(R.id.text1);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SM.sendData(Integer.parseInt(text1.getText().toString()));
                NavHostFragment.findNavController(FirstFragment.this)
                       .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    interface SendMessage {
        void sendData(int number);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            SM = (SendMessage) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException("Error in retrieving data. Please try again");
        }
    }

}

Second Fragment:
public class SecondFragment extends Fragment {

    private FragmentSecondBinding binding;
    TextView textView;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentSecondBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        textView = view.findViewById(R.id.score_result);

        binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this).navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }

    protected void displayReceivedData(int number)
    {
        textView.setText(number);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

View Pager Adapter:
public class ViewPagerAdapter extends FragmentStateAdapter {
    public ViewPagerAdapter(FragmentManager fm, Lifecycle behavior) {
        super(fm,behavior);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        Fragment fragment = null;
        if (position == 0) {
            fragment = new FirstFragment();
        } else if (position == 1) {
            fragment = new SecondFragment();
        }
        assert fragment != null;
        return fragment;
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}

Main Activity:
public class MainActivity extends AppCompatActivity implements FirstFragment.SendMessage{

    ViewPager2 viewPager;
    ViewPagerAdapter viewPagerAdapter;
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);

        viewPager = findViewById(R.id.viewPager2);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),getLifecycle());
        viewPager.setAdapter(viewPagerAdapter);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    }

    @Override
    public void sendData(int number) {
        SecondFragment secondFragment=new SecondFragment();
        SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(String.valueOf(secondFragment));
        f.displayReceivedData(number);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_status) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

A:
There are many ways to pass data between fragments and especially for navigation components we have something called as SafeArgs. Use the below link to consider which method you wish to try out, the android docs for this is self-explanatory.
https://developer.android.com/guide/navigation/navigation-pass-data
Also since you specifically asked if bundles are possible, well yes it is.
// FirstFragment.class
Bundle bundle = new Bundle();
bundle.putString("data", text1.getText().toString());
NavHostFragment.findNavController(FirstFragment.this).navigate(R.id.action_FirstFragment_to_SecondFragment,bundle);

// SecondFragment.class
TextView textView = view.findViewById(R.id.score_result);
textView.setText(getArguments().getString("data"));


text:
Q: como puedo ejecutar stored procedure desde ventana modal bootstrap tengo una duda que no puedo resolver. Desde una página php llamo a una típica ventana modal en el cual siempre tenía un botón que actualizaba o agregaba o eliminaba registros, pero ahora tengo la necesidad de colocar 2 botones y que el nuevo botón me permita llamar a una página php en la cual tengo un código que descarga data y la pasa a un archivo excel.
No sé cómo hacer la llamada a esa página desde el boton en la ventana modal.

    <button type="submit" class="btn btn-primary">Actualizar</button>

    <button type="button" class="btn btn-success">Descargar detalle</button>

Agradeceré cualquier ayuda.
Gracias


text:
Q: Undefined variable on index.php I have been working on debugging a php site that implements a nav bar at the top of the page title navsection and a side nav bar titled sidenavcat. Upon run-time my navsection is displaying:

Notice: Undefined variable: navsection in
/Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 25
Hospitality
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 28
Sustainability
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 31
Events
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 34
Press
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 37
Catalogues
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 40
Locations
Notice: Undefined variable: navsection in /Applications/XAMPP/xamppfiles/htdocs/NOALivingWebsite/header.php on line 43
Shop Online

The following corresponding lines in header.php are as follows
<li <?php echo ($navsection == 'hospitality') ? ' class="current"' : ''; ?> >
   Hospitality

<li <?php echo ($navsection == 'sustainability') ? ' class="current"' : ''; ?> >
   Sustainability

<li <?php echo ($navsection == 'events') ? ' class="current"' : ''; ?> >
   Events

<li <?php echo ($navsection == 'press') ? ' class="current"' : ''; ?> >
   Press

<li <?php echo ($navsection == 'catalogue') ? ' class="current"' : ''; ?> >
   Catalogues

<li <?php echo ($navsection == 'retail') ? ' class="current"' : ''; ?> >
   Locations

<li <?php echo ($navsection == 'register') ? ' class="current"' : ''; ?> >
   Shop Online

Any advice you may lend will be greatly appreciate. Thank you for your time

A: The error message is rather than straight-forward. At the time where your ternary operator is executed, the variable $navsection is not defined.
A possible solution is to define that variable as Session variable and access it like that:
$_SESSION["navsection"]

So your code will look like that:
<li <?php echo ($_SESSION["navsection"] == 'register') ? ' class="current"' : ''; ?> >
   Shop Online

Note: Make sure that your session variable navsection is defined before the above check, possibly in another .php file.
You will need to use this one as well in your html file. This should be used at the top of your html file like that:
<?php
  session_start( );
  $_SESSION["navsection"] = "register"; // Temporary fix.
?>

.
.
.

So that you can access your session variable.


text:
Q: How to enable/disable all buttons in React App using a switch/toggle button I want to make a switch/toggle button that disables all the buttons in the app, and enables them when clicked on AND the user types in the correct password
handleToggleChange() {
    var elements=document.getElementsByClassName('MuiButtonBase-root');
    var i;
    if (this.state.lock ===  false) {
        this.setState({lock: true});
        for (i = 0; i < elements.length; i++) {
            elements[i].disabled = false;
        }
    } else {
        this.setState({lock: false});
        for (i = 0; i < elements.length; i++) {
            elements[i].disabled = true;
        }
    }
}

This is my ToggleButton Code
                       <ToggleButtonGroup onChange={this.handleToggleChange}>
                            <FormControlLabel
                                label={<Typography variant="caption">Unlock</Typography>}
                                control={<ToggleButton
                                        id="togglebutton"
                                        size="small"
                                        value="false"
                                        color="secondary"
                                        style={{right: 5}}
                                        selected={this.state.lock === false ? false : true}
                                    >
                                    <CheckIcon /></ToggleButton>}/>
                        </ToggleButtonGroup>

The problem is that it seems to be working, but they don't actually get disabled, despite the disable property appearing when I go into the debugger.
disabled
And then the disabled property disappears when the button is unchecked. enabled
I'm fairly new to javascript so I'm not even sure if this is the way I'm supposed to be doing something like this. Any help is appreciated.

A: Simply achieving this at a single level with props is relatively easy.  However, for app-wide state that needs to be injected at any level, you most likely want to leverage React Context, which is a React lifecycle-connected state that is injectable at any level.  Below is an example using the useContext hook to create a button that can be used anywhere at any level that will automatically pick up if the global disabled state has been toggled:

// Get a hook function
const { useContext, useState } = React;

const GlobalDisabledStateContext = React.createContext({ disableUI: false });

const App = () => {
  const [disableUI, setDisableUI] = useState(false);
  return (
    <GlobalDisabledStateContext.Provider value={{disableUI}}>

Hello world!

          Toggle Disabled UI
          <input type="checkbox" name="toggleDisableUI" id="toggleDisableUI" checked={disableUI} onChange={() => setDisableUI(!disableUI)} />

Below is a button wired into the app context state, which can be used at any level without wiring app state through props

        <AppStateConnectedButton onClick={() => console.log('hi')}>
          Click Me
        </AppStateConnectedButton>

    </GlobalDisabledStateContext.Provider>
  );
}

const AppStateConnectedButton = (props) => {
  const { disableUI } = useContext(GlobalDisabledStateContext);
  return (<button disabled={disableUI} {...props} />);
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

As I noted in the comments, any sort of DOM manipulation in the context of an MV* framework like React or Angular is an antipattern under 99% of scenarios.  The entire idea of MV* frameworks is that you create a data model, bind it to a view, and the all your logic is to update the data model and let the library handle updating the view.  If you ever find yourself interrogating or changing DOM in an MV* framework you are likely doing something wrong.


text:
Q: Uniqueness of CW approximations Hatcher's Algebraic Topology Corollary 4.19 states :
An $n$-connected CW model for $(X,A)$ is unique up to homotopy equivalence $\text{rel} ~A$. In particular, CW approximations to spaces are unique up to homotopy equivalence.
I understood the first statement, but I can't see how the second statement follows. A CW approximation to a space is by definition a weak homotopy equivalence $f:Z \to X$ where $Z$ is a CW complex. ($X$ is not necessarily path-connected)
On the other hand, an $n$-connected CW model for $(X,A)$ is by definition a CW pair $(Z,A)$ (thus, $A$ must be a CW complex, while $X$ need not) with a map $f:(Z,A)\to (X,A)$ such that $f|_A=1_A$, and $f_*:\pi_i(Z) \to \pi_i(X)$ is an isomorphism for $i>n$ and an injection for $i=n$ for all choices of basepoint. Also we cannot choose $A=\emptyset$, by definition (explained in p.354).
To show that CW approximations to spaces are unique up to homotopy equivalence, first let $X$ be an arbitrary space, and let $f:Z \to X, g:Z' \to X$ be two CW  approximations. I think should use the uniqueness statement of CW models, then I have to take a subspace $A$ of $X$, which is a CW complex, but I have no idea with this. How do I have to proceed?

A: You're right that the case of CW approximations does not follow in any obvious way.  Hatcher seems to have gotten himself in a little trouble through his insistence on avoiding empty sets, which is entirely unnecessary and seems to only be done for convenience of talking about homotopy groups with basepoints in a few arguments.  But you don't need a basepoint to talk about $\pi_0$ ($\pi_0(X)$ can be defined as just the set of path-components of $X$, and $\pi_0(X,A)$ being trivial means that $A$ intersects every path-component of $X$).  With this in mind, there is nothing wrong with allowing $A=\emptyset$ or $n=-1$ in the definition of an $n$-connected CW model, and all the proofs easily extend to include these cases.  A $(-1)$-connected CW model for $(X,\emptyset)$ is then the same thing as a CW approximation for $X$.
Alternatively, the uniqueness of CW approximations instead follows from Proposition 4.22 by essentially the same argument as the proof of Corollary 4.19 using Proposition 4.18.  If $f:Z\to X$ and $g:Z'\to X$ are two CW approximations, then by Proposition 4.22 $g$ induces a bijection $[Z,Z']\to [Z,X]$, and taking the preimage of $[f]$ under this bijection gives a map $h:Z\to Z'$ such that $gh\simeq f$.  Similarly there is a map $h':Z'\to Z$ such that $fh'\simeq g$.  You can then conclude that $h'h\simeq 1_{Z}$ since $fh'h\simeq gh\simeq f=f1_{Z}$ and composition with $f$ is an injection $[Z,Z]\to [Z,X]$, and similarly $hh'\simeq 1_{Z'}$.


text:
Q: Hadoop map side join conditional task I am learning hive map joins and came across conditional task. I have the following questions on conditional task

*

*What is a conditional task in hadoop map join ?

*How does conditional task help in identifying the small table in map join?

*what is difference between the following hive properties and their significance
set hive.auto.convert.join.noconditionaltask.size;
set hive.mapjoin.smalltable.filesize;
Could someone answers the above questions and help me understand conditional task in map side joins.

A:     1. What is a conditional task in hadoop map join ?

     During compilation time, the query processor generates a
 conditional task containing a list of tasks and among this one of the tasks gets resolved to run during execution time.

2. How does conditional task help in identifying the small table in map join?

During the execution stage, the conditional task knows the exact file size of each input table, even if the table is an intermediate one. If all the tables are too large to be converted into map join, then just run the common join task as previously. If one of the tables is large and others are small enough to run map join, then the conditional task will pick the corresponding map join local task to run. By this mechanism, it can convert the common join into a map join automatically and dynamically.

 3. What is difference between the following hive properties and their significance

    hive. Auto. Convert. Join

    default value: false

    This is used for auto join conversion. Once auto join is enabled, you need not specify the map-join in the query.

 hive. Auto. Convert. Join. Noconditionaltask

 default value: true

   This controls whether hive should enable the optimization of converting common join into map-join based on the input file size or not.If the total size of small tables is larger than 25MB, then the conditional task will choose the original common join to run.

 hive. Auto. Convert. Join. Noconditionaltask. Size

default value: 10000000

 If the sum of size for n-1 of the tables/partitions for an n-way join is smaller than this size, the join is directly converted to a map join (there is no conditional task). The default is 10mb. But this is dependent on hive. Auto. Convert. Join. Noconditionaltask and works only when it is true.

For more details:
https://cwiki.apache.org/confluence/download/attachments/27362054/Hive+Summit+2011-join.pdf


text:
Q: Debugging SSL handshake errors connecting to WireMock I'm getting cryptic SSL handshake errors when I attempt to connect to WireMock - error:140790E5:SSL routines:ssl23_write:ssl handshake failure:s23_lib.c:177:
WireMock standalone is running with --https-keystore pointing to a cert I've verified using keytool. Regular HTTP mocks are working fine.
I turned on --print-all-network-traffic and when I call openssl s_client -connect 127.0.0.1:443 -showcerts -status -state -debug this is what I'm seeing:
2017-07-08 23:36:55.881 Opened Socket[addr=/172.17.0.1,port=46404,localport=443]
2017-07-08 23:36:55.886 Problem decoding network traffic
java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
    at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:816)
    at com.github.tomakehurst.wiremock.http.trafficlistener.ConsoleNotifyingWiremockNetworkTrafficListener.incoming(ConsoleNotifyingWiremockNetworkTrafficListener.java:25)
    at com.github.tomakehurst.wiremock.jetty9.JettyHttpServer$NetworkTrafficListenerAdapter.incoming(JettyHttpServer.java:364)
    at org.eclipse.jetty.io.NetworkTrafficSelectChannelEndPoint.notifyIncoming(NetworkTrafficSelectChannelEndPoint.java:125)
    at org.eclipse.jetty.io.NetworkTrafficSelectChannelEndPoint.fill(NetworkTrafficSelectChannelEndPoint.java:48)
    at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:507)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:239)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Thread.java:748)
2017-07-08 23:36:55.895 Closed Socket[addr=/172.17.0.1,port=46404,localport=443]
2017-07-08 23:36:55.896 Closed Socket[addr=/172.17.0.1,port=46404,localport=443]

Any ideas on where to go from here?

A: That's what it looks like when you only give a public cert.


text:
Q: 'There shall be reheating' and other inflation-related questions I've some basic questions about inflation:

*

*What is reheating exactly?
What triggered the reheating? Is it something that one pulls out of a hat?
Through which force did the decay of the inflation occur ?

*How can I picture the inflaton? It is a scalar field, like the Higgs, could we ever hope to observe the inflaton? Can we assign to the field excitation a mass?

*On the blog Quantum Frontier I read the following:

"A possible solution the the super-Planckian value of the change of the inflaton field during the inflation is that the field didn't go in a straight line but somehow turned in circles."
  (Preskill's post on Quantum Frontiers)

What is meant by "going into circles" ? That it oscillated around a minimum of the potential (but isn't that the phenomenon associated to reheating ?) Or is it an identification, e.g.  $\phi(x)= \phi (x+2\pi)$? (This seems even stranger :S.)
Thanks in advance.

A: *

*Reheating is the decaying of the inflaton into the particles that we are currently observing. In the context of quantum field theory this happens simply because there is a coupling of the inflaton field to either the Standard Model (and possibly other, yet unobserved, particles) directly, or to a field $\chi$ which then couples to the Standard Model and possible extensions. In the context of quantum theory, the concept of a 'force' is perhaps not always the best way of thinking about particle interactions.

*The inflaton is usually taken to be a scalar field. Some models take the Higgs field to be the inflaton, although there has been a recent discussion whether the new BICEP2 data rules out such Higgs inflaton scenarios. Alternatively, one can use a large number $N\gg 1$ of scalar fields that together generate inflation. This seems like a very reasonable option if one starts from string theory, which typically gives rise to many scalar fields (if someone knows more about this any input would be much appreciated).

*Many people are trying to think about a way for the inflaton field to undergo super-Planckian displacement, something which seems favored by the BICEP2 results. The oscillations around a minimum that you mention are something different. In the context of (p)reheating, people often consider a so-called curvaton scenario. The equation of motion for the scalar field(s) (assuming the standard potential $V(\phi)=\frac{1}{2}m^2\phi^2$) is
$$\phi''+3H\phi'+m^2\phi=0$$
Therefore, if $H\ll m^2$, the field(s) will oscillate. This happens when the field(s) is/are near the minimum of the potential, because $H$ is related (under slow-roll conditions) to the inflaton potential via the Friedmann equation:
$$H^2=\frac{V}{3M^2_\text{Planck}}$$
Around the minimum, therefore, $H$ is small and the solution to the equation of motion is oscillatory. This is the curvaton scenario; it is one of the possible ways to model (p)reheating which is currently under investigation.


text:
Q: Add to ggplot with element of different length I'm new to ggplot2 and I'm trying to figure out how I can add a line to an already existing plot I created. The original plot, which is the cumulative distribution of a column of data T1 from a data frame x, has about 100,000 elements in it. I have successfully plotted this using ggplot2 and stat_ecdf() with the code I posted below. Now I want to add another line using a set of (x,y) coordinates, but when I try this using geom_line() I get the error message:
Error in data.frame(x = c(0, 7.85398574631245e-07, 3.14159923334398e-06,  :
arguments imply differing number of rows: 1001, 100000

Here's the code I'm trying to use:
> set.seed(42)
> x <- data.frame(T1=rchisq(100000,1))
> ps <- seq(0,1,.001)
> ts <- .5*qchisq(ps,1) #50:50 mixture of chi-square (df=1) and 0
> p <- ggplot(x,aes(T1)) + stat_ecdf() + geom_line(aes(ts,ps))

That's what produces the error from above. Now here's the code using base graphics that I used to use but that I am now trying to move away from:
plot(ecdf(x$T1),xlab="T1",ylab="Cum. Prob.",xlim=c(0,4),ylim=c(0,1),main="Empirical vs. Theoretical Distribution of T1")
lines(ts,ps)

I've seen some other posts about adding lines in general, but what I haven't seen is how to add a line when the two originating vectors are not of the same length. (Note: I don't want to just use 100,000 (x,y) coordinates.)
As a bonus, is there an easy way, similar to using abline, to add a drop line on a ggplot2 graph?
Any advice would be much appreciated.

A: ggplot deals with data.frames, you need to make ts and ps a data.frame then specify this extra data.frame in your call to geom_line:
 set.seed(42)
 x <- data.frame(T1=rchisq(100000,1))
 ps <- seq(0,1,.001)
 ts <- .5*qchisq(ps,1) #50:50 mixture of chi-square (df=1) and 0
 tpdf <- data.frame(ts=ts,ps=ps)
 p <- ggplot(x,aes(T1)) + stat_ecdf() + geom_line(data=tpdf, aes(ts,ps))


text:
Q: Find the equation of the plane that passes through the line of intersection of the planes... Find the equation of the plane that passes through the line of intersection of the planes $4x - 2y + z - 3 = 0$ and $2x - y + 3z + 1 = 0$, and that is perpendicular to the plane $3x + y - z + 7 = 0$.
This is what I got: $3x + 4y - z + 15 = 0$.
Can you please tell me if this is right?
Thanks in advance!
Here is my work:

EDIT:
Changed my answer to: 2x + 3y + 9z - 9 = 0

A: Hint: Any plane passing through intersection of $4x - 2y + z - 3 = 0$ and $2x - y + 3z + 1 = 0$ is given by $$(4x - 2y + z - 3) + k(2x - y + 3z + 1) = 0$$ or what is the same as $$(2k + 4)x - (k + 2)y + (3k + 1)z + k - 3 = 0$$
This is perpendicular to $3x + y - z + 7 = 0$. Using dot product of normal vectors you can now find $k$.
EDIT: If you do calculations you will find $k = -9/2$ and final answer would be same as that provided in another answer namely $-2x + y - 5z = 3$ or $2x - y + 5z + 3 = 0$

A: Hint: The line of intersection of the 2 planes is parallel to
$$ \begin{pmatrix} 4 \\ -2 \\ 1 \\ \end{pmatrix} \times \begin{pmatrix} 2 \\ -1 \\ 3 \\ \end{pmatrix} = \begin{pmatrix} -5 \\ -10  \\ 0 \end{pmatrix}.$$
Hint: The plane that you are interested in is parallel to $\begin{pmatrix} 1 \\ 2  \\ 0 \end{pmatrix}$ and parallel to $\begin{pmatrix}3 \\ 1 \\ -1 \end{pmatrix}$. Hence, it also is perpendicular to
$$ \begin{pmatrix} 1 \\ 2 \\ 0 \\ \end{pmatrix} \times \begin{pmatrix} 3 \\ 1 \\ -1 \\ \end{pmatrix} = \begin{pmatrix} -2 \\ 1 \\-5 \end{pmatrix}.$$
Hint: You found that the point $(3,4,-1)$ lies on both planes, hence lies on the line of intersection, hence lies on the plane that you are interested in.
Thus, the equation of the plane is $$-2x+y-5z = 3.$$

A: The answer $-2x + y - 5z = 3$  is the right answer. The simple way to go about it is to first find a vector which lies on the plane. This vector is parallel to the line of intersection of the two planes.  We therefore find the cross product of the two normals to the intersecting planes. We get the vector $-5i - 10j$  this is then crossed with the normal to the third plane to which  the required plane is perpendicular. This gives us the normal to the required plane which is $2i - j + 5k$.                                                       Then a point on the plane is obtained from the equations of the intersecting planes. Set say $z=0$. Solve simultaneously for $x$ and $y$.    Thank you.

A: Here is a different approach which gives us the same answer in the end. Let:
Let Plane P1 be: 4x-2y+z=3 with normal vector $\vec{n_1}$=[4 -2 1]
$$ $$
Plane P2: 2x-y+3z=-1 has $\vec{n_2}$=[2 -1 3] as its normal vector.
$$ $$
Plane P3: 3x+y-z=-7 has $\vec{n_3}$=[3 1 -1] as its normal vector.
$$ $$
Plane P4: is the plane that we are seeking.
$$ $$
To find the line of intersection of P1 with P2, we can perform gaussian on those two planes:  \begin{bmatrix}2&-1&3&-1\\4&-2&1&3\end{bmatrix}
which will give us a solution of the form: $$\begin{bmatrix}x&\\y&\\z\end{bmatrix} =\begin{bmatrix}1&\\0&\\-1\end{bmatrix}+
t\begin{bmatrix}1&\\2&\\0\end{bmatrix} \qquad[1]$$ where t $\epsilon$ R.
Equation [1] is the line of intersection of P1 with P2 and has a direction vector equal $$\vec{v}= \begin{bmatrix}1&\\2&\\0\end{bmatrix}$$. To get the equation of the plane P4, we first find its normal vector by taking the following cross product:
$$ \vec{n_4}=\vec{n_3}\times \vec{v}=\begin{bmatrix}\vec{i}&\vec{j}&\vec{k}\\1&2&0\\3&1&-1\end{bmatrix} =-2i+j-5k$$
So $\vec{n_4}$ is the normal vector of P4.
$$ $$
Next, we have to find a point that lies on P4. Since P4 passes through the line of intersection of P1 and P2, P4 contains the line of intersection give by equation [1] above. So any points on the line of intersection will do. Indeed, pt (3,4,-1) as you found lies on the line of intersection (this can also be achieved by letting t=2 in equation [1] above)  and so does (1,0,-1). Suppose we choose (1,0,-1), then the equation of the plane P4 is:
$$-2x+y-5z=3$$
which is the same answer as given by others above as expected.


text:
Q: How to convert PNGs to GIF with very short delay in Python? The only similar thread I found on this is Gif Frame Duration Seems Slower Than Expected which somewhat captured my problem, but the 'solution' doesn't work.
My problem is that I am using Pillow to convert PNGs to GIF with the following code:
frames = [Image.open("_bg0.png"), Image.open("_bg1.png"), Image.open("_bg2.png"), Image.open("_bg3.png")]

frames[0].save('_test.gif', format='GIF',
               append_images=frames[1:],
               save_all=True,
               disposal = 2,
               duration=4, loop=0, transparency=0)

I want the duration to be 4ms, however the output looks much slower than this. Here is an example (top is Pillow, bottom is EzGif, same delay specified).

I saw it has something to do with the frame rate, however everything I tried in the linked thread didn't work (particularly setting a value slightly above 1). I've tried setting it to 0, 1, 2, 3, 4 and many values in between.
How do I fix this? I want to be able to do this conversion in Python.

A: As mentioned in the comments, I set mine to 20 ms (I had tried 2/100 ms rather than 2/100 s which caused the issue described earlier).
This has fixed the problem, and indeed there was already a 'speed cap' when using EzGif I just didn't realise.


text:
Q: React-Mapbox-GL keeps refreshing on state update I have the following simple React Component using the react-mapbox-gl wrapper. So far, it's great, however I find a small annoyance when trying to update state, using the useState hook.
    function Location(props) {
       const [selectedMarker, setSelectedMarker] = useState(null);
       const [markerBlock, setMarkerBlock] = useState(false)
      const {payload} = useContext(MarkerContext);
      const [latlong, setLatlong] = useState(null);

      console.log(payload);

        const Map = ReactMapboxGl({
            accessToken:
              'tokenHiddenforstackoverflow',

          });

          const getLatlng = (map, event) => {

              setLatlong(event.lngLat);
          }

        return (
            <>
    <Map
      style="mapbox://styles/mapbox/satellite-streets-v9"
      containerStyle={{
        height: '100vh',
        width: '100%'
      }}
      onClick={getLatlng}
      center={[18.432723671572944, -33.926210020024826]}
    >
    <ZoomControl />

    </Map>

            </>

        );
    }

    export default Location;

Whenever I update the LatLong state, the mapbox background turns black and the whole map reloads. Not sure if a coding / structural error or a bug from Mapbox. I tried restructuring this into smaller components as well, but no difference.
Any ideas?

A: This is expected behavior since with every state change, ReactMapboxGl gets re-created. One solution (to prevent map API reload and maps re-render) would be to create a single instance of ReactMapboxGl outside of Location function:
//create a single instance of WebGl Mapbox map
const Map = ReactMapboxGl({
  accessToken:
    "--your token goes here--"
});

function Location(props) {
  const [position, setPosition] = useState(null);

  const handleClick = (map, event) => {
    setPosition([event.lngLat.lat, event.lngLat.lng]);
  };

  return (
    <Map
      style="mapbox://styles/mapbox/satellite-streets-v9"
      containerStyle={{
        height: "100vh",
        width: "100%"
      }}
      onClick={handleClick}
      center={[18.432723671572944, -33.926210020024826]}
    ></Map>
  );
}

export default Location;


text:
Q: sweetalert is not working if i unset the session I have a session named success and I am doing if the session is isset then show a sweetalert and it's working properly before i unset the session

<?php

if(isset($_SESSION['success'])){
    // unset($_SESSION['success']);
    ?>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script>
        swal({
          title: "Thank You!",
          text: "Our Volunteer Will Contact You Soon!",
          icon: "success",
          button: "Close!",
        });
    </script>
    <?php
}
?>

If i remove the comment on unset then alert is not coming

A: When you are redirecting to the page where you want to show the SweetAlert then use exit(0) after the header redirect.
header("Location: $self");
exit(0);

A: I found a way to make it work i hope it works on you too
Make a php file and this is the content
script.php content:
 <script>
    swal({
      title: "Thank You!",
      text: "Our Volunteer Will Contact You Soon!",
      icon: "success",
      button: "Close!",
    });
</script>

Then do it like this
    <?php

if(isset($_SESSION['success'])){
    ?>
            <?php include('script.php'); ?>
    <?php
   unset($_SESSION['success']);
}
?>

This is my first answer on any question i hope it helps :)


text:
Q: How to add new Action buttons to related list? We are using the Service Console app to log incoming calls as cases. Our current process is to use Global Search to find the Account, find the contact and create a new case on from the contact. I am trying to save some clicks by adding a Left Sidebar Component to the Account view that brings in the Contacts related list:

This works great, actually. I can see the related list of contacts in the account view. But I was to add a button next to each contact in the list for "New Case". Any ideas how to accomplish this?

A: Sadly, at this time the native Related List components do not support custom buttons. In fact, they do not support certain standard buttons either:

*

*Add to Campaign

*Send an Email

One alternative for you might be to tweak your process:

*

*User opens account

*User opens contact from your sidebar

*You add a New Case quick-action to your contacts page layout

*User clicks your New Case action to create the case


text:
Q: How to use Miguel's Reachability classes? I'm currently using Miguel's Reachability class to figure out if my device can connect a certain server. However, there are situations when checking takes very long. My call is:
Reachability.IsHostReachable ( sUrl )

And I'm trying to reach my server's URL.
But I'm not really interested in that. It would be enough to know if the device is currently registered in a WiFi network and if not, if it is connected through the carrier's GSM network. Wether it reach a host or not is secondary. As Reachability is not very well commented, I wonder if somebody knows what methods I would have to call?
EDIT:
It would already be enough if somebody explained the meaning of InternetConnectionStatus() and LocalWifiConnectionStatus() to me. The funny thing is: the first one always returns true even if I turn WiFi off.

A: I tend to use
Reachability.RemoteHostStatus() == NetworkStatus.NotReachable

to check for a connection. The NetworkStatus enumeration also includes ReachableViaCarrierDataNetwork and ReachableViaWiFiNetwork which may come in handy for what you desire.


text:
Q: Can't build docker image (it gives error in requirements.txt) i have been woek on a project and i had a problem which is really annoying.
I have tried so many ways to get rid off it .
I tried to install manually from requirements.txt after that it gives same error.I tried upgrade pip3 but my pip3 is latest version.
I tried restart the subsystem etc. so it didn't work
When i run command:
docker build -t main-app .

it gives me this error down bellow:
error image
this is my requirements.txt:
aiodns==3.0.0
aiohttp==3.7.4.post0
aiohttp-socks==0.6.0
async-timeout==3.0.1
attrs==19.3.0
Automat==0.8.0
beautifulsoup4==4.9.3
blinker==1.4
cchardet==2.1.7
certifi==2019.11.28
cffi==1.14.5
chardet==3.0.4
Click==7.0
cloud-init==21.2
colorama==0.4.3
command-not-found==0.3
configobj==5.0.6
constantly==15.1.0
cryptography==2.8
cssselect==1.1.0
dbus-python==1.2.16
distro==1.4.0
distro-info===0.23ubuntu1
elasticsearch==7.13.1
entrypoints==0.3
fake-useragent==0.1.11
geographiclib==1.50
geopy==2.1.0
googletransx==2.4.2
h2==3.2.0
hpack==3.0.0
httplib2==0.14.0
hyperframe==5.2.0
hyperlink==19.0.0
idna==2.8
importlib-metadata==1.5.0
incremental==16.10.1
itemadapter==0.2.0
itemloaders==1.0.4
Jinja2==2.10.1
jmespath==0.10.0
jsonpatch==1.22
jsonpointer==2.0
jsonschema==3.2.0
keyring==18.0.1
language-selector==0.1
launchpadlib==1.10.13
lazr.restfulclient==0.14.2
lazr.uri==1.0.3
lxml==4.6.3
MarkupSafe==1.1.0
more-itertools==4.2.0
multidict==5.1.0
netifaces==0.10.4
numpy==1.20.3
oauthlib==3.1.0
p5py==1.0.0
pandas==1.2.4
parsel==1.6.0
pep517==0.10.0
pexpect==4.6.0
priority==1.3.0
Protego==0.1.16
pyasn1==0.4.2
pyasn1-modules==0.2.1
pycairo==1.20.1
pycares==4.0.0
pycparser==2.20
PyDispatcher==2.0.5
PyGObject==3.36.0
PyHamcrest==1.9.0
PyJWT==1.7.1
pymacaroons==0.13.0
PyNaCl==1.3.0
pyOpenSSL==19.0.0
pyrsistent==0.15.5
pyserial==3.4
PySocks==1.7.1
python-apt==2.0.0+ubuntu0.20.4.4
python-dateutil==2.8.1
python-debian===0.1.36ubuntu1
python-socks==1.2.4
pytz==2021.1
PyYAML==5.3.1
queuelib==1.6.1
requests==2.22.0
requests-unixsocket==0.2.0
schedule==1.1.0
Scrapy==2.5.0
SecretStorage==2.3.1
service-identity==18.1.0
simplejson==3.16.0
six==1.14.0
sos==4.0
soupsieve==2.2.1
ssh-import-id==5.10
systemd-python==234
toml==0.10.2
twint==2.1.20
Twisted==18.9.0
typing-extensions==3.10.0.0
ubuntu-advantage-tools==20.3
ufw==0.36
unattended-upgrades==0.1
zipp==1.0.0
zope.interface==4.7.1

This is my Dockerfile:
FROM python:3.8-slim-buster

WORKDIR /main

COPY requirements.txt requirements.txt

RUN  pip3 install --upgrade pip==21.1.2 setuptools

RUN pip3 install Scrapy

RUN pip3 install twint

RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "./main.py"]

This is my project structure down bellow:
Project Structure


text:
Q: Android button looks strange after applying a theme I have a problem applying a theme to my buttons. without using the theme everything looks fine as you can see on this screenshot:
http://i47.tinypic.com/2czyctv.jpg
after I have applied my theme it looks like this:
http://i48.tinypic.com/w03s6x.png
the color is fine, but the height of the button is wrong and also the space between the upper button and the horizontal line disappeared. actually the themed buttons should look like the unthemed buttons for their size because the only thing i wanted to change was the color.
values/themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

<style name="Theme.KIT.Styled" parent="Theme.Sherlock.Light.DarkActionBar">

    <item name="actionBarStyle">@style/ActionBar</item>
    <item name="android:actionBarStyle">@style/ActionBar</item>
    <item name="android:buttonStyle">@style/Button</item>

</style>

<style name="ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid.Inverse">
    <item name="background">@drawable/actionbar_background_shape</item>
    <item name="android:background">@drawable/actionbar_background_shape</item>
</style>

<style name="Button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/kit_button</item>
</style>
</resources>

drawable/kit_button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_enabled="false"
    android:drawable="@drawable/kit_button_background_shape" />
<item
    android:state_pressed="true"
    android:state_enabled="true"
    android:drawable="@drawable/kit_button_background_shape" />
<item
    android:state_focused="true"
    android:state_enabled="true"
    android:drawable="@drawable/kit_button_background_shape" />
<item
    android:state_enabled="true"
    android:drawable="@drawable/kit_button_background_shape" />
</selector>

drawable/kit_button_background_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
    android:startColor="@color/KIT_GREEN"
    android:endColor="@color/KIT_GREEN_LIGHT"
    android:angle="90"
    android:centerX="0.5"
    android:centerY="0.5" />
</shape>

i hope s.o. can help me. and sorry for my bad english...

A: Your buttons padding used to be declared within the 9-patch background, a GradientDrawable doesn't do that for you. You need to add a android:padding attribute to your theme or use a 9-patch.


text:
Q: Dojo - Upload two files in one Form I use Dojo and want to send two files and one String to a REST Service. The HTML for that is the following:

//...

//..
    <form action="http://localhost:8080/service" enctype="multipart/form-data" method="POST" name="inputDataForm" id="inputDataForm">

       Dataset1
       <input name="train" type="file" value="Browse" data-dojo-type="dojox/form/Uploader"/>

       Dataset2
       <input name="test" type="file" value="Browse" data-dojo-type="dojox/form/Uploader"/>

       Number of Customers
       <input name="numberCustomers" size="40" type="text" data-dojo-type="dijit/form/TextBox" />

<input name="runButton" type="submit" value="Run" data-dojo-type="dijit/form/Button" id="submitButton" />

    </form>

However: If I press the submit button, I can see via Firebug that there are sent TWO POST-Requests. One with the first file and the "Number of Customers" field and one with the second file and the "Number of Customers" field. However, my REST Service wants to have both files and the "Number of Customers" fields in one POST Request. How can i do that? What am I doing wrong?
Thanks a lot in advance
Natan


text:
Q: Common practice to name project directory which hold support scripts, configs, docs, etc for developers I work with small set of projects so lack of knowledge about naming convention for directory in software project file hierarchy which desired to hold project development.
I look to well-known projects (like Firefox, GCC, binutils, Linux, Emacs, VIM, etc) and collect some common directories (comments written myself so they don't pretend to be true...):

*

*examples or samples to show practical usage of project in mini-scripts or mini-programs, or mini-configs.

*scripts, support - wrappers or copy of missing scripts/utilities to provide cross-environment build.

*tools - extra utilities to profile or debug project.

*contrib - user supplied scripts, configs, etc...

*misc, etc - uncategorised files (if you don't know the right place for it).

*config, extra - don't know...

While src/, test/, build/, dist/, lib/ and  other directories naming convention dictated by prog-langs/platforms/frameworks etc, this directories seems common for all type of projects.
So I look for guide (official or unofficial) for naming convention for directories that hold support files for project.
Most essential distinct from regular project files that these file isn't used in project release build, or is used in rare cases.
PS. Someone can argue that this is not SO question. But I have real task to commit several scripts (sql script to dump menu from DB, script which dump url mapping for web-controllers, etc) and look for directory name that shoud hold these files...
PPS. My effort to collect conventions:

*

*http://tips.defun.work/devel-proj-files.html

*http://gavenkoa.users.sourceforge.net/tips-html/devel-proj-files.html (mirror)

A: There are:

*

*The Software Package Data Exchange® (SPDX®)

*GNU Coding Standards

*Maven Standard Directory Layout


text:
Q: SharedPreferences changing one variable affect others as well in Android I have a very weird problem. And I spend 3-4 hours correcting as well as googling for solutions but nothing. I am storing a variable in "QuestionAsked" string but don't know why all other strings show same values.
i.e. if "QuestionAsked" was 40 and RecordQuestionAsked() was called, now not only "QuestionAsked" but all other even strings "xyz" created after this call, will show 41. :( What could be the problem?
private void RecordQuestionAsked(){
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        int prev = sharedPref.getInt(getString(R.string.QuestionAsked),0);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(getString(R.string.QuestionAsked), prev+1);
        editor.commit();
}

if (id == R.id.menuProg) {
            if(ll1.getVisibility()==View.VISIBLE) {
                ll1.setVisibility(View.GONE);
                ll3.setVisibility(View.VISIBLE);
                SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
                int ca = sharedPref.getInt(getString(R.string.xyz),1);
                int qa = sharedPref.getInt(getString(R.string.QuestionAsked),0);
                pba.setProgress(ca/qa*100);
                pbi.setProgress((qa-ca)/qa*100);
                txtProg.setText("Correct Answers / Total Questions : " + ca + "/" + qa );
            }
        }

A: It seems that posting questions here is useless :(
However, after banging my head for 3-4 days, instead of getString(R.string.xyz), "xyz" for both get and put worked for me if anybody is interested.


text:
Q: AWS Athena partition fetch all paths Recently, I've experienced an issue with AWS Athena when there is quite high number of partitions.
The old version had a database and tables with only 1 partition level, say id=x. Let's take one table; for example, where we store payment parameters per id (product), and there are not plenty of IDs. Assume its around 1000-5000. Now while querying that table with passing id number on where clause like ".. where id = 10". The queries were returned pretty fast actually. Assume we update the data twice a day.
Lately, we've been thinking to add another partition level for day like, "../id=x/dt=yyyy-mm-dd/..". This means that partition number grows  xID times per day if a month passes and if we have 3000 IDs, we'd approximately get 3000x30=90000 partitions a month. Thus, a rapid grow in number of partitions.
On, say 3 months old data (~270k partitions), we'd like to see a query like the following would return in at most 20 seconds or so.
select count(*) from db.table where id = x and dt = 'yyyy-mm-dd'
This takes like a minute.
The Real Case
It turns out Athena first fetches the all partitions (metadata) and s3 paths (regardless the usage of where clause) and then filter those s3 paths that you would like to see on where condition. The first part (fetching all s3 paths by partitions lasts long proportionally to the number of partitions)
The more partitions you have, the slower the query executed.
Intuitively, I expected that Athena fetches only s3 paths stated on where clause, I mean this would be the one way of magic of the partitioning. Maybe it fetches all paths

*

*Does anybody know a work around, or do we use Athena in a wrong way ?

*Should Athena be used only with small number of partitions ?

Edit
In order to clarify the statement above, I add a piece from support mail.
from Support

...
  You mentioned that your new system has 360000 which is a huge number.
  So when you are doing select * from <partitioned table>, Athena first download all partition metadata and searched S3 path mapped with
  those partitions. This process of fetching data for each partition
  lead to longer time in query execution.
  ...

Update
An issue opened on AWS forums. The linked issue raised on aws forums is here.
Thanks.

A: This is impossible to properly answer without knowing the amount of data, what file formats, and how many files we're talking about.
TL; DR I suspect you have partitions with thousands of files and that the bottleneck is listing and reading them all.
For any data set that grows over time you should have a temporal partitioning, on date or even time, depending on query patterns. If you should have partitioning on other properties depends on a lot of factors and in the end it often turns out that not partitioning is better. Not always, but often.
Using reasonably sized (~100 MB) Parquet can in many cases be more effective than partitioning. The reason is that partitioning increases the number of prefixes that have to be listed on S3, and the number of files that have to be read. A single 100 MB Parquet file can be more efficient than ten 10 MB files in many cases.
When Athena executes a query it will first load partitions from Glue. Glue supports limited filtering on partitions, and will help a bit in pruning the list of partitions – so to the best of my knowledge it's not true that Athena reads all partition metadata.
When it has the partitions it will issue LIST operations to the partition locations to gather the files that are involved in the query – in other words, Athena won't list every partition location, just the ones in partitions selected for the query. This may still be a large number, and these list operations are definitely a bottleneck. It becomes especially bad if there is more than 1000 files in a partition because that's the page size of S3's list operations, and multiple requests will have to be made sequentially.
With all files listed Athena will generate a list of splits, which may or may not equal the list of files – some file formats are splittable, and if files are big enough they are split and processed in parallel.
Only after all of that work is done the actual query processing starts. Depending on the total number of splits and the amount of available capacity in the Athena cluster your query will be allocated resources and start executing.
If your data was in Parquet format, and there was one or a few files per partition, the count query in your question should run in a second or less. Parquet has enough metadata in the files that a count query doesn't have to read the data, just the file footer. It's hard to get any query to run in less than a second due to the multiple steps involved, but a query hitting a single partition should run quickly.
Since it takes two minutes I suspect you have hundreds of files per partition, if not thousands, and your bottleneck is that it takes too much time to run all the list and get operations in S3.


text:
Q: Does "identical eigenvalues" mean that there is no diagonal matrix? If I have a 2 x 2 matrix and eigenvalues for that matrix are 3,3, does this mean that there exits no diagonal matrix?
If I have 2 distinct eigenvalues, then eigenvectors corresponding to two distinct
eigenvalues are independent and form a basis. Then I can find out a diagonal matrix having
eigenvalues as entries. But, I am not sure whether having identical eigenvalues means that
there is no diagonal matrix.

A: The eigenvalues for the diagonal matrix $\left(\begin{smallmatrix} x & 0 \\ 0 & x\end{smallmatrix}\right)$ are $x$ and $x$... so having repeated eigenvalues certainly doesn't mean non-diagonalizability.

A: What are the eigenvalues of the identity matrix?

A: Well, you can consider the identity matrix, $I$, which has unique eigenvalue $1$ - and it is already in diagonal form.
What we want here is that the $2\times2$ matrix is diagonalisable iff:
either there are two eigenvalues with corresponding eigenbases of dimension $1$ or there is a unique eigenvalue with an eigenbasis of dimension $2$.
More generally, a $n\times n$ matrix is diagonalisable if the dimension of the space, which is the direct sum of all eigenspaces, is $n$.
Now, the eigenbasis corresponding to eigenvalue $1$ for $I$ is of dimension $2$. However, consider $M=\begin{pmatrix}1 & 1\\ 0 & 1\end{pmatrix}$. It only has one eigenvalue, namely $\lambda = 1$, but its eigenbasis for $M$, namely the span of $e_{1}$, is of dimension $1$. And so it is not diagonalisable.
I mention for posterity's sake  that if the eigenvalues are the same, then the matrix is diagonalisable iff it is already in diagonal form, since $P^{-1}DP = P^{-1}(nI)P = nP^{-1}P = nI$.

A: When you diagonalize the rest (the distinct eigenvalues), the subspace with the degenerate eigenvalue can behave in two ways:
*) Diagonalizable. Geometric multiplicity (the number of eigenvectors) is the same as the multiplicity of the eigenvalues. In this case, when you diagonalize the rest, the remaining block is already diagonal.
*) Not enough eigenvectors: you can put the degenerate block into a Jordan normal form, but nondiagonal terms will be nonzero.
For some matrices, you can be sure it's diagonalizable (for instance, symmetric matrices always are).


text:
Q: loosing values in user controls after postback  I have a page that has a user control in it. In the user control text boxes generate dynamically in a place holder and there is a button that will save all of them into the database. But here is the problem: When i click on save button, first, my page's page load event runs, then  it loads user control, then user control page load event runs. so text boxes loose their content from last page. any idea?

A: Within your Page_Load, continue to always generate your textbox controls (regardless of IsPostBack).  However within the control, only set an initial value if IsPostBack = false.  That way when IsPostBack is true the textbox will take it's value from the ViewState instead.


text:
Q: Exclude specific products from Product Indexer in Shopware 6 We have four specific products with a massive amount of variants. When running the Product Indexer we run out of memory because of these products.
So we want to exclude these specific products from the Product Indexer Job.
My first approach was to use the ProductIndexerEvent, but the event is dispatched at the end of the handle() method :
(vendor/shopware/core/Content/Product/DataAbstractionLayer/ProductIndexer.php:187),
which is probably too late.
What is the best approach to implement that behaviour?

A: I would advise against excluding products from being indexed. There's business logic relying on the data being indexed.
If you're confident in what you're doing and know about the consequences, you could decorate the ProductIndexer service.
<service id="Foo\MyPlugin\ProductIndexerDecorator" decorates="Shopware\Core\Content\Product\DataAbstractionLayer\ProductIndexer">
    <argument type="service" id="Foo\MyPlugin\ProductIndexerDecorator.inner"/>
</service>

In the decorator you would have to deconstruct the original event, filter the WriteResult instances by excluded IDs and then pass the reconstructed event to the decorated service.
class ProductIndexerDecorator extends EntityIndexer
{
    const FILTERED_IDS = ['9b180c61ddef4dad89e9f3b9fa13f3be'];

    private EntityIndexer $decorated;

    public function __construct(EntityIndexer $decorated)
    {
        $this->decorated = $decorated;
    }

    public function getDecorated(): EntityIndexer
    {
        return $this->decorated;
    }

    public function getName(): string
    {
        return $this->getDecorated()->getName();
    }

    public function iterate($offset): ?EntityIndexingMessage
    {
        return $this->getDecorated()->iterate($offset);
    }

    public function update(EntityWrittenContainerEvent $event): ?EntityIndexingMessage
    {
        $originalEvents = clone $event->getEvents();

        if (!$originalEvents) {
            return $this->getDecorated()->update($event);
        }

        $event->getEvents()->clear();

        /** @var EntityWrittenEvent $writtenEvent */
        foreach ($originalEvents as $writtenEvent) {
            if ($writtenEvent->getEntityName() !== 'product') {
                $event->getEvents()->add($writtenEvent);

                continue;
            }

            $results = [];
            foreach ($writtenEvent->getWriteResults() as $result) {
                if (\in_array($result->getPrimaryKey(), self::FILTERED_IDS, true)) {
                    continue;
                }

                $results[] = $result;
            }

            $event->getEvents()->add(new EntityWrittenEvent('product', $results, $event->getContext()));
        }

        return $this->getDecorated()->update($event);
    }

    public function handle(EntityIndexingMessage $message): void
    {
        $data = array_diff($message->getData(), self::FILTERED_IDS);

        $newMessage = new ProductIndexingMessage($data, $message->getOffset(), $message->getContext(), $message->forceQueue());

        $this->getDecorated()->handle($newMessage);
    }

    public function getTotal(): int
    {
        return $this->getDecorated()->getTotal();
    }

    public function getOptions(): array
    {
        return $this->getDecorated()->getOptions();
    }
}


text:
Q: Delete file on process termination Is there a way to create/access a temporary file (e.g. GetTempFileName) and delete it right after the process has been killed/terminated? I know it is possible with the JobAPI to terminate all child processes but I was wondering if you could use such a method with a file.

A: Pass the FILE_FLAG_DELETE_ON_CLOSE flag to CreateFile and the file will be deleted when all of its handles are closed. The documentation says:

The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.


text:
Q: Why is Eigenvalue different from Variance.percent? I am conducting PCA analysis on results from a Likert-scale (10-point base) survey on user preferences. When using the code below, I obtain the list of variables with their respective eigenvalues. However these eigenvalues are different from the adjacent column which shows variance.percent (in the reference guide, it's one-tenth of the eigenvalue.
Could anyone explain why this might be or if there is anything off with my approach?
res.pca <- PCA(mydata, graph = FALSE)
print(res.pca)
library("factoextra")
eig.val <- get_eigenvalue(res.pca)
eig.val

A: Everything is OK. Sum of eigenvalues is always equal to number of variables (10 on the left and 13 on the right). So variance.percent is always eigenvalue divided by number of variables.


text:
Q: Multiple GUI Threads in Qt As mentioned in Qt documentation, each program has one "main thread" (also known as the "GUI thread") when it is started. The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads.
So you can not have GUI components in any worker thread in anyway.
I have some questions related to this topic:

*

*Is there any workaround or hack in a Qt implementation which does not force this mechanism?

*Is it probable that this restriction be omitted in a far future release of Qt?


text:
Q: Error "'un.fn.init' is null or not an object" - Internet Explorer 8 (IE8) - jQuery 1.11.3 I'm cross browser testing a site in Internet Explorer 8 and getting 'un.fn.init' is null or not an object. The specific line has the following:
re=function un(e,t){return new un.fn.init(e,t)}
I'm using jQuery 1.11.3, since it's supposed to run on ie8. The site is being compiled with gulp.js. The site is also using a number of different libraries to help ie8 work in the head:
<!--[if lt IE 9]>
    <script src="/js/other/object-keys-polyfill.js"></script>
    <script src="/js/other/html5shiv.js"></script>
    <script src="/js/other/nwmatcher.js"></script>
    <script src="/js/other/selectivizr.js"></script>
    <script src="/js/other/respond.js"></script>
<![endif]-->

and this in the footer:
<!--[if lt IE 9]>
    <script src='/js/other/rem.js'></script>
<![endif]-->

This error breaks everything; does anyone have any ideas about how to get rid of it?

A: No such syntax exists in the jQuery library.
It looks like your code is scrambled or obfuscated using some kind of tool. Most of the time, old browsers will not support completely scrambled or obfuscated JS.


text:
Q: How to create multi image component with image preview In adobe cq5? I want to build a component in which user can drag & drop two images from content finder. For this i created another tab in my dialog but when i am authoring the component its showing the 1st tab image in both div's. Can you please tell me where i'm wrong here is my code.
dialog.xml
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Dialog"
    activeTab="{Long}0"
    helpPath="en/cq/current/wcm/default_components.html#Image"
    xtype="tabpanel">
    <items jcr:primaryType="cq:WidgetCollection">
        <image
            jcr:primaryType="cq:Widget"
            cropParameter="./imageCrop"
            ddGroups="[media]"
            fileNameParameter="./fileName"
            fileReferenceParameter="./fileReference"
            mapParameter="./imageMap"
            name="./file"
            requestSuffix=".img.png"
            rotateParameter="./imageRotate"
            title="Image"
            xtype="html5smartimage"/>
        <advanced
            jcr:primaryType="cq:Widget"
            title="Advanced"
            xtype="panel">
            <items jcr:primaryType="cq:WidgetCollection">
                <title
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Title"
                    name="./jcr:title"
                    xtype="textfield"/>
                <alt
                    jcr:primaryType="cq:Widget"
                    fieldDescription="(leave empty to use the title defined above)"
                    fieldLabel="Alt Text"
                    name="./alt"
                    xtype="textfield"/>
                <linkURL
                    jcr:primaryType="cq:Widget"
                    fieldDescription="Drop files or pages from the Content Finder"
                    fieldLabel="Link to"
                    name="./linkURL"
                    xtype="pathfield"/>
                <description
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Description"
                    name="./jcr:description"
                    xtype="textarea"/>
                <size
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Size"
                    heightParameter="./height"
                    widthParameter="./width"
                    xtype="sizefield"/>
            </items>
        </advanced>
        <image4
            jcr:primaryType="cq:Widget"
            cropParameter="./image4Crop"
            ddGroups="[media]"
            fileNameParameter="./image4/fileName"
            fileReferenceParameter="./image4/fileReference"
            mapParameter="./imageMap"
            name="./image4/file"
            requestSuffix=".img.png"
            rotateParameter="./image4/imageRotate"
            title="Image"
            xtype="html5smartimage"/>
    </items>
</jcr:root>

image.jsp is
<%@ page import="com.day.cq.commons.Doctype,
    com.day.cq.wcm.api.components.DropTarget,
    com.day.cq.wcm.foundation.Image" %><%
%><%@include file="/libs/foundation/global.jsp"%><%
    Image image = new Image(resource);

    //drop target css class = dd prefix + name of the drop target in the edit config
    image.addCssClass(DropTarget.CSS_CLASS_PREFIX + "image");
    image.loadStyleData(currentStyle);
    image.setSelector(".img"); // use image script
    image.setDoctype(Doctype.fromRequest(request));

    Image image4 = new Image(resource);

    //drop target css class = dd prefix + name of the drop target in the edit config
    image4.addCssClass(DropTarget.CSS_CLASS_PREFIX + "image4");
    image4.loadStyleData(currentStyle);
    image4.setSelector(".img"); // use image script
    image4.setDoctype(Doctype.fromRequest(request));
    // add design information if not default (i.e. for reference paras)
    if (!currentDesign.equals(resourceDesign)) {
        image.setSuffix(currentDesign.getId());
    }
    String divId = "cq-image-jsp-" + resource.getPath();
    %><div id="<%= divId %>"><% image.draw(out); %>
<%
    %><cq:text property="jcr:description" placeholder="" tagName="small" escapeXml="true"/>
    <div id="<%= divId %>"><% image4.draw(out); %>

    <%@include file="/libs/foundation/components/image/tracking-js.jsp"%>

A: I ran into a problem like this using with multiple images within the dialog. You might check the resourceType after you save the images in CRXDE to make sure they both have a resourceType property set. If either images are missing this property you can add the property using a hidden widget. Reference https://forums.adobe.com/message/4623838 for more
                    <resType1
                        jcr:primaryType="cq:Widget"
                        ignoreData="{Boolean}true"
                        name="./file/sling:resourceType"
                        value="foundation/components/image"
                        xtype="hidden"/>
                    <resType2
                        jcr:primaryType="cq:Widget"
                        ignoreData="{Boolean}true"
                        name="./image4/sling:resourceType"
                        value="foundation/components/image"
                        xtype="hidden"/>


text:
Q: Why do I get the error 'Forbidden.' when executing Add-AzKeyVaultManagedStorageAccount using a Service Principal? Using Powershell in an Azure DevOps pipeline, I am trying to assign the key vault a new storage account by calling the command Add-AzKeyVaultManagedStorageAccount.
All the scripting seems to have worked so far except for that last command which fails with the Forbidden error.
I found a similar issue on the MSDN but it seems the KeyVault's policies are properly set.
Permissions of the service principal
Here are the permissions of the service principal (named Azure DevOps - Azure Resource Manager) under which the command is run:

The command is run as a Service Principal that has the Owner role in the subscription:

The resource group created in that subscription is also owned by that Service Principal:

The Key Vault principal has been given the role of
Storage Account Key Operator Service Role on the storage account:

The proper policies have configured for the Key Vault, most importantly the Permissions to (Key Vault Managed) Storage section:
Vault Name                          : accountsmanager-test
Resource Group Name                 : accountsmanager-test-global-rg
Location                            : Canada Central
Resource ID                         : /subscriptions/***/resourceGroups/accountsmanager-test-global-rg/providers/Microsoft.KeyVault/vaults/accountsmanager-test
Vault URI                           : https://accountsmanager-test.vault.azure.net/
Tenant ID                           : ***
SKU                                 : Standard
Enabled For Deployment?             : False
Enabled For Template Deployment?    : False
Enabled For Disk Encryption?        : False
Enabled For RBAC Authorization?     : False
Soft Delete Enabled?                : True
Soft Delete Retention Period (days) :
Access Policies                     :
                                      Tenant ID                                  : ***
                                      Object ID                                  : ***
                                      Application ID                             :
                                      Display Name                               : accountsmanager-test (6c55f481-78bf-4f5c-ab40-d8c93d7707df)
                                      Permissions to Keys                        :
                                      Permissions to Secrets                     : get
                                      Permissions to Certificates                :
                                      Permissions to (Key Vault Managed) Storage :

                                      Tenant ID                                  : ***
                                      Object ID                                  : <Service Principal's Object ID>
                                      Application ID                             :
                                      Display Name                               :
                                      Permissions to Keys                        :
                                      Permissions to Secrets                     :
                                      Permissions to Certificates                :
                                      Permissions to (Key Vault Managed) Storage : get, list, delete, set, update, regeneratekey, getsas, listsas,
                                      deletesas, setsas, recover, backup, restore, purge

Network Rule Set                    :
                                      Default Action                             : Allow
                                      Bypass                                     : AzureServices
                                      IP Rules                                   :
                                      Virtual Network Rules                      :

Tags                                :

Question
In the script, I run the following command, like described in the documentation:
Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName 'key1' -DisableAutoRegenerateKey

I get the following error:
Operation returned an invalid status code 'Forbidden'

Why do I get the error Forbidden when executing the command Add-AzKeyVaultManagedStorageAccount?

A: It's a little strange. I have the same issue.
But when I use the preview feature Azure role-based access control (preview), I can run it successfully.
Here are my steps for your reference:

Assign key vault admin role to the service principal.


text:
Q: Equivalent Carbon 32-bit call for using in 64-bit application - GetApplicationEventTarget() I'm writing a 64-bit Cocoa application. I need to register for global key events. So I wrote this piece of code :
- (void)awakeFromNib
{
    EventHotKeyRef gMyHotKeyRef;
    EventHotKeyID gMyHotKeyID;
    EventTypeSpec eventType;
    eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;
    eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;
    InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,NULL,NULL);
    gMyHotKeyID.signature='htk1';
    gMyHotKeyID.id=1;
    RegisterEventHotKey(49, cmdKey+optionKey, gMyHotKeyID,
     **GetApplicationEventTarget**(), 0, &gMyHotKeyRef);
}

But since GetApplicationEventTarget() is not supported for 64-bit applications I'm getting errors. If I declare it, then I don't get any errors but the application crashes.
Is there any equivalent method for GetApplicationEventTarget() (defined in Carbon framework) to use in 64-bit applications.
Or is there any way to get the global key events using cocoa calls?
Any help is appreciated.
Thanks,
Dheeraj.

A: I wrote a Cocoa wrapper for Carbon hot keys (and as far as my testing showed, it works in 64-bit apps), and you can find it on github here:  http://github.com/davedelong/DDHotKey
I'm using GetEventDispatcherTarget() for hotkey registration.

A: I think it is a documentation error when it says that GetApplicationEventTarget is not supported in 64 bits.  If you look in CarbonEvents.h (from the 10.6 SDK), you see that the declaration of GetUserFocusEventTarget is bracketed by #if !__LP64__ ... #endif, but just above it, the declaration of GetApplicationEventTarget is not.  GetApplicationEventTarget is probably not the cause of the crash.  In your code, gMyHotKeyRef and gMyHotKeyID look like they were intended to be global variables, but they're local.

A: Carbon isn't supported in 64-bit applications. See the answer to this question for information on how to use CGEventTap to do this in a supported way in Cocoa.


text:
Q: Python TypeError: string indices must be integers error I am trying to use ycombinators api in order to get the top news articles. However I keep on getting this error TypeError: string indices must be integers
Heres my code
articles_list = []
y= requests.get("https://hacker-news.firebaseio.com/v0/newstories.json")
y = y.json()
print(y)
print("https://hacker-news.firebaseio.com/v0/item/" + number +".json" +"?print=pretty")
for number in y:
    req = requests.get("https://hacker-news.firebaseio.com/v0/item/" + str(number) +".json" +"?print=pretty")
    req = req.json()
    print(req)
    break
for thing in req["url"]:
    articles_list.append(thing["url"])

I can not understand whats wrong....


text:
Q: Swagger Spec - SmartDocs - Parameters name - alias Is there a way to set an alias to the name property of Parameters in swagger specs for SmartDocs to display different value?
For example:
parameters:
  - name: consumer_key
    in: formData
    description: >-
    Your Consumer Key (from My Apps)
    required: true
    type: string

When sending the request, it actually sends the consumer_key=ABC rather than client_id=ABC. The reason why I try to do this is, developer will get a consumer_key (as a client_id) after they register a developer app successfully.
Alternatively, I can map them in the description field 'This client_id is the consumer_key of your app.' or something like that, but I would like to see if there is a way to set 'alias' for the name field in swagger spec.

A: Swagger does not support alias names for parameters. And it would probably confuse the developers if the docs used different parameter names than in the actual request.
Use description to explain where the parameter value comes from. This will be enough.


text:
Q: $p$-adic unit for $p\neq 2$ is a square in $\mathbb{Z}_p$ if and only if its first digit is quadratic residue modulo $p$. I heard the statement from the title of this question.
$\newcommand{\of}[1]{\left(#1\right)}$
$\newcommand{\df}{\mathrel{\mathop:}=}$
So if I am not totally confused, this formalizes to:

Let $p\neq 2$ and $u\in\mathbb{Z}_p^*$ with canonical form $\sum_{i=0}^\infty u_ip^i$. Then
  \begin{align*}
\exists\ x\in\mathbb{Z}_p:\ x^2=u \quad \Leftrightarrow \quad u_0 \ \text{is a quadratic residue modulo} p.
\end{align*}

I think that the direction "$ \Rightarrow $" is straightforward:

Let $x\in\mathbb{Z}_p$ with canonical form $\sum_{i=0}^\infty x_ip^i\in\mathbb{Z}_p$ such that $x^2 =u$. By the Cauchy-Product-Fomrula, we have that
  \begin{align*}
x^2=\of{\sum_{i=0}^\infty x_ip^i}^2=\sum_{i=0}^\infty \sum_{j=0}^i x_{i-j} x_jp^i\stackrel{!}{=}\sum_{i=0}^\infty u_ip^i.
\end{align*}
  Comparing the coefficient of $p^0$ yields $x_0^2=u_0$ which means that $u_0$ is a quadratic residue modulo $p$.

Now it is left to prove the direction "$ \Leftarrow $" and that's where I get stuck. Here is what I have:

Define $f(X)\df X^2-u_0$. Since $u_0$ is a quadratic residue modulo $p$, we have that
  \begin{align*}
\exists\ 0<y<p:\ u_0=y^2\pmod{p}
\end{align*}
  which means that $f(y)\equiv 0\pmod{p}$ and since $\gcd\of{y,p}=1$ and $\gcd\of{p,2}=1$, we get that $f'(y)=2y\not\equiv 0\pmod{p}$. So the conditions for Hensel's lemma are fullfilled and we get a unique $a\in\mathbb{Z}_p$ with $a\equiv y\pmod{p}$ and $f(a)=0$.

I am quite sure that I need to use the condition that $u$ is a unit i.e. that $\left|| u \right||_p=1$ or that $u^{-1}\in\mathbb{Z}_p$ but I don't know how. Or maybe I got the statement wrong and am missing any premises?

A: You can see that $u$ is a square in $\mathbb Z_p$ simply by computing successive digits of its square root $x$:
Choose $x_0$ such that $x_0^2\equiv u_0 \mod p$ (either square root will do).
Then $x_1$ is determined uniquely by $(x_1p+x_0)^2 \equiv u \mod p^2$
$x_2$ is determined uniquely by $(x_2p_2+x_1p+x_0)^2 \equiv u \mod p^3$
And so on.
At each stage, we have $(x_{r-1}p^{r-1}+\cdots+x_0)^2 \equiv u \mod p^r$, so the equation for $x_r$ is of the form $(x_rp^r+y)^2 \equiv u \mod p^{r+1}$ for some $y$ with $y^2\equiv u \mod p^r$. This reduces so a linear equation which is always soluble.
Edited to add: The equation for $x_1$ has a solution only if $x_0 \ne 0 \mod p$, which is why $u$ is required to be a unit.