text:
Q: Weird matrix identity I stumbled upon a weird equality that I can't seem to explain:
For a $N\times N$ (symmetric) matrix $\mathbf{X}$ that satisfies the eigenvalue problem
$$\mathbf{X} \mathbf{v}_k = \lambda_k \mathbf{v}_k$$
and a $N\times1$ matrix $\mathbf{u}$ that is split in 2 (elements in the first half are equal to 1, equal to -1 for the second half), i.e.
$$\mathbf{u}^T := \frac{1}{\sqrt{N}}\bigl[\underbrace{1 ...\ 1}_{\times N/2}\ \underbrace{-1\ ....-1}_{\times N/2}\bigr]$$
the following (apparantly) holds
$$ \mathbf{u}^T(z \mathbf{I} - \mathbf{X})^{-1} \mathbf{u} = \sum_{k=1}^N \frac{(\mathbf{u}^T \mathbf{v}_k)^2}{z-\lambda_k}.$$
$z$ is complex but vanishingly close to the real axis.

I'm guessing it has something to do with the resolvent
$$ (z \mathbf{I} - \mathbf{X})^{-1} \equiv \sum_{k=0}^\infty \frac{\mathbf{X}^k}{z^{k+1}}$$
but I can't figure it...

A: You have an unstated assumption that $v_k$ are ortho-normal (ortho is ensured if the matrix has distinct eigenvalues). One can always choose $v_k$ so they are ortho-normal.
That said, we can write $u$ as
$$
u = \sum_1^k \sigma_k v_k
$$
where $$ \sigma_k = u^T v_k$$
Hence
$$ \begin{align} u^T (z I - A)^{-1} u &= u^T\sum_1^k \sigma_k(z I - A)^{-1} v_k \\
&=  \sum_1^k \sigma_k \frac{1}{z-\lambda_k} u^T v_k \\
&=  \sum_1^k  \frac{\left(u^T v_k\right)^2 }{z-\lambda_k} \\
\end{align}
$$
The above result is true for any real vector $u$.

A: I think the identity
$\mathbf{u}^T(z \mathbf{I} - \mathbf{X})^{-1} \mathbf{u} = \sum_{k=1}^N \frac{(\mathbf{u}^T \mathbf{v}_k)^2}{z-\lambda_k} \tag{1}$
holds for any $\mathbf u$, provided we take the $\mathbf v_k$ to be normalized to unity, which always a possible choice in the present context.  The matrix $\mathbf X$, being symmetric, is possessed of an orthonormal eigenbasis $\mathbf v_k$, and we can expand $\mathbf u$ in this basis, to wit:
$\mathbf u = \sum_1^N (\mathbf u^T \mathbf v_k) \mathbf v_k; \tag{2}$
now observe that $z$, being complex, satisfies $z \ne \lambda_k$ for all $k$, $1 \le k \le N$, whence $1 /(z - \lambda_k)$ is well-defined.  This being the case, we have, for each $\mathbf v_k$,
$(z - \mathbf X) \mathbf v_k = (z - \lambda_k) \mathbf v_k, \tag{3}$
which immediately leads to
$\mathbf v_k = (1 / (z - \lambda_k)) (z - \mathbf X)\mathbf v_k.  \tag{4}$
Substituting (4) into (2) yields
$\mathbf u = \sum_1^N (\mathbf u^T \mathbf v_k) (1 / (z - \lambda_k)) (z - \mathbf X)\mathbf v_k = (z - \mathbf X) \sum_1^N (\mathbf u^T \mathbf v_k)(1 / (z - \lambda_k)) \mathbf v_k, \tag{5}$
and since $z - \mathbf X$ is nonsingular by virtue of the fact that $z$ cannot be a (real) eigenvalue of $X$, we may write
$(z - \mathbf X)^{-1} \mathbf u = \sum_1^N (\mathbf u^T \mathbf v_k)(1 / (z - \lambda_k)) \mathbf v_k; \tag{6}$
taking the product of each side with $\mathbf u^T$ now gives
$\mathbf u^T (z - \mathbf X)^{-1} \mathbf u = \sum_1^N (\mathbf u^T \mathbf v_k)(1 / (z - \lambda_k)) (\mathbf u^T \mathbf v_k) =  \sum_1^N (1 / (z - \lambda_k)) (\mathbf u^T \mathbf v_k)^2, \tag{7}$
the desired result.
Note that if the $\mathbf v_k$ are not normalized, (2) would fail, and the ensuing equations would (presumably) have to be modified.
Hope this helps.  Holiday Greetings,
and as always,
Fiat Lux!!!


text:
Q: Provide parameter SchemaType for XmlObject I have a class like
public class CreditCardDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements creditcard.CreditCardDocument
{

   public CreditCardDocumentImpl(org.apache.xmlbeans.SchemaType sType)
   {
       super(sType);
   }
}

That class is implementing "CreditCardDocument" interface.
The interface is like
public interface CreditCardDocument extends org.apache.xmlbeans.XmlObject
{

Now, if I want to access that constructor as
CreditCardDocument creditCardDocument = new CreditCardDocumentImpl(CreditCardDocumentImpl.class.instanceType());

It throws as error,
groovy.lang.MissingMethodException: No signature of method: static creditcard.impl.CreditCardDocumentImpl.instanceType() is applicable for argument types: () values: []

I'm not getting what is the error. What could be the parameter that I need to pass to the constructor?

A: Did you generate these classes through CXF using XmlBeans? If so, probably your interface provides a public static property with the schema type, or even better, you can try:
CreditCardDocument creditCardDocument = CreditCardDocument.Factory.newInstance();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement custom Detail Pane in Expressionss view in Eclipse correctly? I have contributed to org.eclipse.debug.ui.detailPaneFactories and this replaced the detail pane inside Variables view in Eclipse debugger:

Detail Pane above is redefined to be yellow.
Unfortunately, Detail Pane in Expressions view does not work, it is gray below:

What did I did wrong?
I have tried to implement the following example: http://alvinalexander.com/java/jwarehouse/eclipse/org.eclipse.jdt.debug.tests/test-plugin/org/eclipse/jdt/debug/testplugin/detailpane/SimpleDetailPane.java.shtml
My plugin.xml is follows:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>

<plugin>
   <extension
         point="org.eclipse.debug.ui.detailPaneFactories">
      <detailFactories
            class="tests.debug.details.DetailPaneFactory"
            id="tests.debug.details.detailFactories">
      </detailFactories>
   </extension>

</plugin>

My DetailPaneFactory.java is follows:
package tests.debug.details;

import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.debug.ui.IDetailPane;
import org.eclipse.debug.ui.IDetailPaneFactory;
import org.eclipse.jface.viewers.IStructuredSelection;

public class DetailPaneFactory implements IDetailPaneFactory {

    private HashMap<String,Class<? extends IDetailPane>> classes = new HashMap<String,Class<? extends IDetailPane>>();

    private void addClass(Class<? extends IDetailPane> cls) {
        try {
            String paneID = (String) cls.getField("ID").get(null);
            classes.put(paneID, cls);
        } catch (IllegalArgumentException | IllegalAccessException
                | NoSuchFieldException | SecurityException e) {
            throw new RuntimeException(e);
        }
        finally {

        }

    }

    private Class<? extends IDetailPane> getClass(String paneID) {
        Class<? extends IDetailPane> ans = classes.get(paneID);
        return ans;
    }

    public DetailPaneFactory() {
        addClass(SimpleDetailPane.class);
    }

    @Override
    public IDetailPane createDetailPane(String paneID) {

        Class<? extends IDetailPane> cls = getClass(paneID);
        if( cls != null ) {
            try {
                return cls.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException();
            }
        }
        else {
            return null;
        }
    }

    @Override
    public String getDetailPaneName(String paneID) {
        Class<? extends IDetailPane> cls = getClass(paneID);
        if( cls != null ) {
            try {
                return (String)cls.getField("NAME").get(null);
            } catch (IllegalArgumentException | IllegalAccessException
                    | NoSuchFieldException | SecurityException e) {
                throw new RuntimeException(e);
            }
        }
        else {
            return null;
        }
    }

    @Override
    public String getDetailPaneDescription(String paneID) {
        Class<? extends IDetailPane> cls = getClass(paneID);
        if( cls != null ) {
            try {
                return (String)cls.getField("DESCRIPTION").get(null);
            } catch (IllegalArgumentException | IllegalAccessException
                    | NoSuchFieldException | SecurityException e) {
                throw new RuntimeException(e);
            }
        }
        else {
            return null;
        }
    }

    @Override
    public Set<String> getDetailPaneTypes(IStructuredSelection selection) {
        return new AbstractSet<String>() {

            @Override
            public Iterator<String> iterator() {
                return new Iterator<String>() {

                    private Iterator<Map.Entry<String,Class<? extends IDetailPane>>> it = classes.entrySet().iterator();

                    @Override
                    public void remove() {
                        it.remove();
                    }

                    @Override
                    public String next() {
                        return it.next().getKey();
                    }

                    @Override
                    public boolean hasNext() {
                        return it.hasNext();
                    }
                };
            }

            @Override
            public int size() {
                return classes.size();
            }

        };
    }

    @Override
    public String getDefaultDetailPane(IStructuredSelection selection) {
        return SimpleDetailPane.ID;
    }

}

and my SimpleDetailPane.java is as in example except that "other" color is made yellow.

A: The expressions view is provided by org.eclipse.debug.internal.ui.views.expression.ExpressionView which is a subclass of VariablesView.
The documentation for the org.eclipse.debug.ui.detailPaneFactories extension point says:

This extension point allows clients to contribute custom renderings
  for the detail pane in the variables, registers, expressions, and
  breakpoints views

so you should be able to use the same extension point for this view.


text:
Q: Interrupt ZStream mapMPar processing I have the following code which, because of Excel max row limitations, is restricted to ~1million rows:
ZStream.unwrap(generateStreamData).mapMPar(32) {m =>
  streamDataToCsvExcel
}

All fairly straightforward and it works perfectly. I keep track of the number of rows streamed, and then stop writing data. However I want to interrupt all the child fibers spawned in mapMPar, something like this:
ZStream.unwrap(generateStreamData).interruptWhen(effect.true).mapMPar(32) {m =>
  streamDataToCsvExcel
}

Unfortunately the process is interrupted immediately here. I'm probably missing something obvious...
Editing the post as it needs some clarity.
My stream of data is generated by an expensive process in which data is pulled from a remote server, (this data is itself calculated by an expensive process) with n Fibers.
I then process the streams and then stream them out to the client.
Once the processed row count has reached ~1 million, I then need to stop pulling data from the remote server (i.e. interrupt all the Fibers) and end the process.

A: Here's what I can come up with after your clarification. The ZIO 1.x version is a bit uglier because of the lack of .dropRight
Basically we can use takeUntilM to count the size of elements we've gotten to stop once we get to the maximum size (and then use .dropRight or the additional filter to discard the last element that would take it over the limit)
This ensures that both

*

*You only run streamDataToCsvExcel until the last possible message before hitting the size limit

*Because streams are lazy expensiveQuery only gets run for as many messages as you can fit within the limit (or N+1 if the last value is discarded because it would go over the limit)

import zio._
import zio.stream._

object Main extends zio.App {

  override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = {

    val expensiveQuery     = ZIO.succeed(Chunk(1, 2))
    val generateStreamData = ZIO.succeed(ZStream.repeatEffect(expensiveQuery))

    def streamDataToCsvExcel = ZIO.unit

    def count(ref: Ref[Int], size: Int): UIO[Boolean] =
      ref.updateAndGet(_ + size).map(_ > 10)

    for {
      counter <- Ref.make(0)
      _ <- ZStream
            .unwrap(generateStreamData)
            .takeUntilM(next => count(counter, next.size)) // Count size of messages and stop when it's reached
            .filterM(_ => counter.get.map(_ <= 10))                     // Filter last message from `takeUntilM`. Ideally should be .dropRight(1) with ZIO 2
            .mapMPar(32)(_ => streamDataToCsvExcel)
            .runDrain

    } yield ExitCode.success
  }
}

If relying on the laziness of streams doesn't work for your use case you can trigger an interrupt of some sort from the takeUntilM condition.
For example you could update the count function to
def count(ref: Ref[Int], size: Int): UIO[Boolean] =
  ref.updateAndGet(_ + size).map(_ > 10)
    .tapSome { case true => someFiber.interrupt }


text:
Q: PHP recursive version of function any improvement? I created a PHP function that will convert an array:
[
    'one/two' => 3,
    'one/four/0' => 5,
    'one/four/1' => 6,
    'one/four/2' => 7,
    'eight/nine/ten' => 11,
]

Into the following JSON string:
{
    "one":
    {
        "two": 3,
        "four": [ 5,6,7]
    },
    "eight":
    {
        "nine":
        {
            "ten":11
        }
    }
}

Here is the function:
<?php
function toJsonStr($array) {

    $final_array = [];

    foreach ($array as $key => $value) {

        $key_exploded = explode("/", $key);

        $array_index_at_end = is_numeric(end($key_exploded)) ? true : false ;

        if ($array_index_at_end === true) {
            $array_index = array_pop($key_exploded);
        }

        $ref = &$final_array;
        foreach ($key_exploded as $value2) {

            if (!isset($ref[$value2])) {
                $ref[$value2] = [];
            }

            $ref = &$ref[$value2];
        }

        if ($array_index_at_end === true) {
            $ref[$array_index]=$value;
        } else {
            $ref=$value;
        }
    }

    return json_encode($final_array);
}

$array = [
    'one/two' => 3,
    'one/four/0' => 5,
    'one/four/1' => 6,
    'one/four/2' => 7,
    'eight/nine/ten' => 11,
];

$json_str = toJsonStr($array);

echo "\n";
print_r($json_str);
echo "\n\n";

I'm almost positive that this can also be done recursively. I am new to recursion and am having trouble structuring an approach when creating a recursive version.
Would it even be worthwhile to create a recursive version? Maybe it would be too difficult to understand compared to the simple foreach within a foreach I have implemented above?
I know that recursive algorithms simplify and make code more compact but in this case would it be worth it?

A: IMHO a recursive approach would make sense if the structure of your input array can have a nested structure:
[
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
'eleven/twelve' => [
  'thirteen/fourteen' => 15,
  'sixteen/seventeen' => 18,
  'nineteen/twenty' => [
    'twentyone/twentytwo' => 23
    ],
  ],
]

Then you should implement a recursive function for that. Keep it simple when you don't need to implement things.

A: It can be shorter, though I usually do this without recursion, as it doesn't matter the depth.  You already have a grasp of doing it with references. See How to access and manipulate multi-dimensional array by key names / path?:
function toJsonStr($array, &$result=array()) {
    foreach($array as $key => $value) {
        $path = explode('/', $key);
        $temp =& $result;
        foreach($path as $key) {
            $temp =& $temp[$key];
        }
        $temp = $value;
    }
    $result = json_encode($result);
}

toJsonStr($array, $result);


text:
Q: Running multiple SSL Web Sites on IIS on Port 443 I have two Server but just one IP and the need to run on both a Site under the port 443.
I've found out that it is also possible to run multiple SSL web sites on 443 using a shared IP address by making use of Host Headers, however this requires a Wildcard Certificate and a metabase configuration change. But that sounds really bad so I would prefer to use any other solution.
I don't know if it is important that the Domain (certificate) mysub.domain.com is verified by verisign

A: The SSL negotiation, including the browser analyzing the Common Name field of the certificate to compare against the host it attempted to connect to, occur long before the server has a chance to see a request.  Because of this the server cannot deliver a certificate based upon the Host: head in the request.  A wildcard certificate resolves this only because the same certificate is used for each hosted site.
For example if you have a *.example.com cert and you use it to host (based on Host header):
blog.example.com
www.example.com

In each case the certificate is valid for the site hosted and the browser will be happy.

A: It is possible to handle different domains with different certificates correctly over the same IP/port, thanks to server name indication.
However, this only works with recent browsers (IE8/winXP does not support it), which means that unless you can afford to not support them, you really need to add either IP or ports.


text:
Q: Limesurvey - Results distribution Is there a way to make the survey results available without the need of user authentication?
For example. The link below allow for the user to see survey results, but he/she needs to be login as admin.
https://limesurvey-home/index.php/admin/statistics/sa/simpleStatistics/surveyid/924492

A: There is a setting for allowing statistics to be public.
Take a look here: https://manual.limesurvey.org/Statistics#Public_Statistics

LimeSurvey includes functionality to display simple statistics to the general public or to your participants after they have completed filling out an online survey.
There are two steps involved in activating and displaying statistics to your participants. Firstly you must enable public statistics for your survey (by default this is turned off). This setting is in your main survey toolbar, General Settings – in the Presentation and Navigation Tab. Look for the setting "Public Statistics". There is also a setting here called "Show graphs in public statistics" which – if turned on – will show graphs as well as the counts (by default only numerical statistics are displayed).
Once you've set your survey to display statistics, you need to indicate question-by-question which statistics are displayed to your participants. By default, no questions are selected for display.
You choose which questions will be shown in the public statistics page by editing each question. In the Statistics Tab for each question is an option "Show in public statistics". Once you set this setting to "On" the question will be included on the public statistics page.

Thanks!


text:
Q: VBA - Open XLS App On-Top of MSAccess I am creating and formatting an XLS Workbook from an Access Database using VBA, initiated via a user button press on a form.
I'd like to have the XLS App ALWAYS open on top of the AccessDB to permit the user to see the worksheet directly.  Currently it is intermittent, XLS usually opens UNDER Access on first iteration, but then on-top in subsequent iterations in the same session.  User review of the file is necessary prior to final save and export to our client portal.  There will typically only be a single iteration per user session.
I am using the following approach (pseudo):
Dim appXLS As Object
Dim wbkNew As Object
Dim wks1, wks2, wks3 As Object

Set appXLS = CreateObject("Excel.Application")
Set wbkNew = appXLS.Workbooks.Add

appXLS.Visible = True
wbkNew.Activate

...populate & format 3 worksheets from Access

wks1.Activate  ' go back to sheet 1
wbkNew.SaveAs AccessMode:=xlExclusive, FileName:=myFile

I am saving the file in this routine, so any "overwrite file" warnings also open under MSAccess.
I thought the .Activate lines would ensure the desired function.  Any thoughts or ideas on this?
Thanks!


text:
Q: Get value of the object by attribute value I'm stuck a little at this point.
Let's say, we have this XML:
<object>
    <data name="my name">Alex</data>
    <data name="somebody's name">Dan</data>
</object>

In PHP, I can select value of the object by simplexml's XPath:
<?
$result = $xml->xpath('/object/data[@name="my name"]'); //array of values
echo $result[0]; //output: Alex
?>

But I can't get it: how can I do the same using javascript? I mean, is there any method like .getElementByTagName(), but for attribute's value?
Thank you.

A: With jQuery:
$("data[name='my name']")

A: You can use querySelector
var result = document.QuerySelector('data[name="my name"]');
console.log(result);

If there can be multiple matching elements, use querySelectorAll; it will return a NodeList that you can iterate over and index.


text:
Q: ¿cual seria el equivalente de input[type=radio]:checked en un checbox? quiero darle diferente estilo cuando ya haya seleccionado el checkbox. con el radio boton pude hacerlo usando esto -> input[type=radio]:checked.

A: El equivalente es este:
input[type="checkbox"]:checked

Ver la pseudo variable checked en MDN.


text:
Q: How can I make the text of a UIBarButtonItem wrap to two lines? Some of the titles of view controllers in my UINavigationController are quite long, which makes the back button in the navigation bar of the next view controller in the hierarchy miss out some of the text, with a "..." instead.
How could I make the text of the back button wrap onto two lines, as with "Now Playing" in the navigation bar of iPod.app?
Thanks!

A: You could use the UIBarButtonItem method initWithCustomView: then set the rightBarButtonItem property in UINavigatiobItem.


text:
Q: C#.net Getting values from json I need to use some JSON data with a C# application, but i can't figure a way of getting the data.
I'm using SOCKET.IO, and here is a sample of a raw json string that is recieved
`socket.On("recieved", (data) =>
{
    MessageBox.Show(data.Json.ToJsonString());
    //outputs :  {'name':'received','args':[{'data':'somedata'}]}
    //get values from data
}`<br>

and i need to retrieve the value of 'data'

A: Look at the examples in the SocketIO4Net archive.
Define a class
using Newtonsoft.Json;

namespace TestProject
{
    [JsonObject(MemberSerialization.OptIn)]
    public class JSonData
    {
        [JsonProperty]
        public string data { get; set; }

        public JSonData()
        {
        }

        public string ToJsonString()
        {
            return JsonConvert.SerializeObject(this);
        }
        public static JSonData Deserialize(string jsonString)
        {
            return JsonConvert.DeserializeObject<JSonData>(jsonString);
        }
    }
}

And after you get data like this :
JSonData JData = data.Json.GetFirstArgAs<JSonData>();

A: Ok i got that working, but if i want all args in JSON string {data:"somedata",anotherdata:'someanotherdata'} and get 'anotherdata', i tried `
JSonData part = data.Json.GetArgsAs();

A: Sorry for the double answers, but this did it for me
private Newtonsoft.Json.Linq.JObject get_data(SocketIOClient.Messages.JsonEncodedEventMessage data)
        {
            var inputdata = data;
            dynamic jsondata =  inputdata.GetArgsAs<Object>();
            jsondata = jsondata[0];
            return jsondata;
        }
and then just do
dynamic json = get_data(data.Json);


text:
Q: User defined module cannot find top level variables and modules I have a user defined module (called test.py) as such:
def getLastDate(currDt):
    prevDt = (currDt - dt.timedelta(days=1))
    return prevDt

I am trying to call it from another python script:
import datetime as dt
import test
currDt = dt.date.today()
print(test.getLastDate(currDt))

The problem is that when I run it, the scope of this is such that the inner module (test.py) is unable to find the dt module and gives the following error:
      1 def getLastDate(currDt):
----> 2     prevDt = (currDt - dt.timedelta(days=1))
      3     return prevDt

NameError: name 'dt' is not defined

Do I have to reload datetime module inside my test.py module? This does not seem right to me.
Thank you in advance for your help.

A: You need to import dt also in test.py file
#test.py
import datetime as dt
def getLastDate(currDt):
    prevDt = (currDt - dt.timedelta(days=1))
    return prevDt

A: Yes, as it's written you'll need to import datetime in test.py.
If you want to avoid importing datetime twice you could just import it in test.py and rewrite your function like:
def getLastDate(currDt, delta):
    prevDt = (currDt - dt.timedelta(days=delta))
    return prevDt


text:
Q: Validation of password and repassword with jquery This is the final part of a switch statement to validate a register form:
    case "contraseña":
    {
        if($(this).val().length < 9){
            $(".texto_req_reg").html("Debe tener más de 8 caracteres");
            $(".texto_req_reg").css("color", "#C60");
            contraseñaValida = false;
        }else{
            $(".texto_req_reg").html("Correcto");
            $(".texto_req_reg").css("color", "#990");
            contraseñaValida = true;
        }
    break;
    }
    case "repetirContraseña":
    {
        if($(this).val() === $("#contraseña").val()){
            $(".texto_req_reg").html("Correcto");
            $(".texto_req_reg").css("color", "#990");
            repContraseñaValida = true;
        }else{
            $(".texto_req_reg").html("Debe coincidir con su contraseña");
            $(".texto_req_reg").css("color", "#C60");
            repContraseñaValida = false;
        }
    break;
    }
    if($("#checkbox_legales").is(":checked")){
        checkbox_legalesValido = true;
    }else{
        checkbox_legalesValido = false;
    }
    habilitarBoton()
}
}

Something is wrong with the "repetirContraseña" case because firebug don't allow me to set stopping points in that part and the last if and the habilitarBoton() function isn't being called. Can you figure out what is wrong?

A: some thing like this:
case "repetirContraseña":
    {
        if($(this).val() === $("#contraseña").val()){
            $(".texto_req_reg").html("Correcto");
            $(".texto_req_reg").css("color", "#990");
            repContraseñaValida = true;
        }else{
            $(".texto_req_reg").html("Debe coincidir con su contraseña");
            $(".texto_req_reg").css("color", "#C60");
            repContraseñaValida = false;
        }
    if($("#checkbox_legales").is(":checked")){
        checkbox_legalesValido = true;
    }else{
        checkbox_legalesValido = false;
    }
    habilitarBoton()
    break;
    }

or
case "repetirContraseña":
    {
        if($(this).val() === $("#contraseña").val()){
            $(".texto_req_reg").html("Correcto");
           $(".texto_req_reg").css("color", "#990");
            repContraseñaValida = true;
        }else{
            $(".texto_req_reg").html("Debe coincidir con su contraseña");
            $(".texto_req_reg").css("color", "#C60");
            repContraseñaValida = false;
        }
    }
default : {
  if($("#checkbox_legales").is(":checked")){
        checkbox_legalesValido = true;
    }else{
        checkbox_legalesValido = false;
    }
    habilitarBoton()
}


text:
Q: Perform summation of integers on each line in a file in `cmd` Time for some command line fu in the least fu conducive shell, cmd.exe.
How can I perform a summation of integers contained in a file?
You might consider the following to work:
taskkill /f /im rsync.exe
echo %errorlevel% > %temp%/kill_site.log
taskkill /f /im ssh.exe
echo %errorlevel% >> %temp%/kill_site.log
taskkill /f /im 7za.exe
echo %errorlevel% >> %temp%/kill_site.log
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+%errorresult%

But, it appears that %errorresult% will always be the value before the for loop during the for loop.  Meaning, the resulting %errorlevel% always has [the integer value of the last line in %temp%/kill_site.log] + [the %errorlevel% set, which is 1].
In the case of exit codes provided by taskkill, if taskkill succeeds in killing an existing process, the exit code is 0, then resulting %errorresult% in this case will be 1.  If a process doesn't exist when taskkill is called to kill it, the exit code is 128; in this case the %errorresult% will be129`.
I'd like %errorresult% to be the total of all integers contained on lines in  %temp%/kill_site.log.  How do I do this?
[update]
Thanks to Stephen's answer below, I have a final script as follows that I wanted to include for future reference by other users:
setlocal enabledelayedexpansion
taskkill /f /im rsync.exe
echo %errorlevel% > %temp%/kill_site.log
taskkill /f /im ssh.exe
echo %errorlevel% >> %temp%/kill_site.log
taskkill /f /im 7za.exe
echo %errorlevel% >> %temp%/kill_site.log
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+!errorresult!
if %errorresult% lss 255 sendmail.vbs && eventcreate /l application /so backup_scripts /t warning /id 1 /d "website rsync has to be killed because it was long running."
endlocal

It utilizes endlocal.
I also just realized this is a bit backwards, as I should be checking if the processes are running previous to taking any invalid action against the non-existent processes, but the question is still resolved.  Finding if a specific running process exists with a batch script actually uses a similar method of checking the %errorlevel% is also quite easy.

A: within a forloop you need delayed expansion for your variables:
use
SETLOCAL ENABLEDELAYEDEXPANSION
at the beginning of your batchfile
and change your for-loop to
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+!errorresult!
This is because in your for-loop %errorresult% will always use the value at Parse-time. !errorresult! will use the value at run-time.

A: Stephan's answer works fine, but there is a simpler method that doesn't require delayed expansion.
The SET /A command does its own expansion of variable names, and it always uses the current value.
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+errorresult

Or better yet
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult+=%%G

Note - I don't understand why you initialize errorresult to 1. I should think 0 would make more sense.

A: Here is a non portable solution, but it is NOT the answer, but may assist others that come across this problem in the future:
taskkill /f /im rsync.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res1=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
taskkill /f /im ssh.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res2=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
taskkill /f /im 7za.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res3=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
set /A errorresult=%res1% + %res2% + %res3%

I have marked this as a community wiki as the question is still pending an answer.


text:
Q: Parameterizing a Jenkins job with the versions of multiple upstream jobs I need to create a build pipeline which consists of multiple projects that depend on each other. Here is a simplified illustration:
SVN A --> build A --\
                    |
SVN B --> build B --|
                    |
SVN C ----------------> build C

The pipeline should work so that when a change is committed to the SVN repository of any of the projects, then that project is build automatically. Additionally, after either A or B has been built, it triggers the building of C.
Each build produces binaries with a unique version number ("X.Y.BuildNumber") and C must get as a parameter the version numbers of both A and B, so that C can be built using those versions. C should default to using the latest successful builds of A and B, but it should also be possible to trigger C manually using an older version of A or B (e.g. if we want to deploy an older version of one of the projects).
Creating a pipeline like this can be done out-of-the-box on Go, but my company considers it too expensive. (Update 2014-02-27: Go is not open source and free!) So now I'm trying to find out how to achieve the same thing using Jenkins, but have not yet found a way. I've only found instructions for creating simple linear and diamond shaped pipelines in Jenkins, but not pipelines with multiple independent upstream projects.

A: It's possible to pass the version numbers from upstream jobs to downstream jobs by using the Copy Artifact Plugin. Write the version number to a file in the upstream job, archive it, and then use that plugin to read it in a downstream job. Select the Upstream build that triggered this project and Use "Last successful build" as fallback options in the plugin configuration.
For more details, see Interdependent Build Pipelines with Jenkins.

A: We use the build-pipeline-plugin for something similar and what we do is we provide a groovy script that stores runtime build information to be passed on to downstream projects:
A bit verbose, because we include SVN info for downstream builds:
import hudson.model.*
def thr = Thread.currentThread()
def build = thr?.executable

def workspace = build.getWorkspace()

def ant = new AntBuilder()
ant.exec(executable: "svn", outputproperty: "output", dir: workspace){
    arg(line: "info")
}
svnInfo = ant.project.getProperty("output")
print svnInfo

def pattern = /Last\s+Changed\s+Author:\s+(\w+)/
def matcher = (svnInfo =~ pattern)
def user = matcher[0][1]

def langs = new XmlParser().parseText(build.getParent().getWorkspace().child('pom.xml').readToString())
def appVer = langs.properties.release.text()
def artifactId = langs.artifactId.text()

def params = [
new StringParameterValue('PL_SVN_REVISION', build.getEnvVars()['SVN_REVISION']),
new StringParameterValue('PL_BUILD_NUMBER', build.getEnvVars()['BUILD_NUMBER']),
new StringParameterValue('PL_APP_NAME', 'FooApp'),
new StringParameterValue('PL_COMMITTER_NAME',user ),
new StringParameterValue('PL_APP_VERSION',appVer),
new StringParameterValue('PL_ARTIFACT_ID',artifactId)
]
build.addAction(new ParametersAction(params))

Then in the downstream build they should be available like so:
Example 1, Set Build Name input:
#${BUILD_NUMBER} - ${ENV,var="PL_APP_NAME"} - ${ENV,var="PL_APP_VERSION"} - ${ENV,var="PL_SVN_REVISION"}

Example 2, Invoke Ant target input:
deploy
  -Denvironment=ONT-base
  -DWAR-LOCATION=%war-repo%/%PL_APP_NAME%/%PL_BUILD_NUMBER%-%PL_SVN_REVISION%/
  -DWAR-NAME=%PL_ARTIFACT_ID%-%PL_APP_VERSION%.%PL_BUILD_NUMBER%-%PL_SVN_REVISION%.war

Beware however, when reusing a downstream project in multiple upstream projects, as there is an outstanding bug with variables not being passed down correctly.


text:
Q: How do I prevent my cd ripper from overwriting Unknown Album when metadata can't be found I'm starting the longish process of ripping my CD collection. I've got abcde installed with the config from Andrew's Corner. It seems to be working ok but when the metadata fetch fails, the MP3s get written as Unknown Artist and Unknown Album. Which isn't a problem until the second metadata fetch fails. Then the tracks get overwritten. What would be ideal is that the second album gets a number on the name like "Unknown Album 2". Any suggestions on how to accomplish this? Or how to keep the directories from being ovewritten?

A: You could automate the process by wrapping the abcde with a script that invokes abcde and checks for 'Unknown Artist/Unknown Album' directory existence after abcde completion.
If the test shows that directory exists then rename it with a name that includes the disk CDDB ID which you can get with cd-discid tool. This script obtains the ID early, otherwise auto-eject prevents obtaining the ID after abcde has completed.
#!/bin/bash

id=$(cd-discid /dev/cdrom)
abcde $@ || exit 1
if [ -d "Unknown Artist/Unknown Album" ]; then
    mv "Unknown Artist/Unknown Album" \
       "Unknown Artist/Unknown Album $id"
fi

A: Using Serge's idea above, I edited the mungefilename function in the .abcde.conf configuration file.
I started with the configuration file supplied here:
Andew's Corner has a very helpful tutorial
I edited the function to append the first bit of string returned from cd-discid.
mungefilename ()
    {
        CDDISKIDENT=$(cd-discid "$CDROM")

        FIRSTPARTID=$(echo $CDDISKIDENT | cut -d' ' -f1)
  echo "$@" | sed "s/Unknown\ Album/Unknown\ Album$FIRSTPARTID/" | sed -e 's/^\.*//' | tr -d ":><|*/\"'?[:cntrl:]"
}

A: This appends the PID of the parent process when ripping a disc.
This is because mungefilename is ran per file during the final copy process at the end of the rip, if you have set auto eject the disc won't be available to get the discid from. The parent PID is the only constant on a per disc basis.
mungefilename ()
{
        echo "$@" | sed "s/Unknown\ Album/Unknown\ Album$PPID/" | sed -e 's/^\.*//' | tr -d ":><|*/\"'?[:cntrl:]"
}


text:
Q: Test if any RCS-controlled files in tree are not checked in I have multiple project trees of legacy code that are using RCS for version control with multiple users. I'd like to be able to walk the tree and test if any files are checked out (and thus the tree is not ready to be packaged for distribution update).
For example, I have a test tree:  tree -p .
.
├── [-r--r--r--]  file1
├── [drwxrwxr-x]  RCS
│   └── [-r--r--r--]  file1,v
├── [drwxrwxr-x]  subdir1
│   ├── [drwxrwxr-x]  RCS
│   │   └── [-r--r--r--]  sfile1,v
│   └── [-rw-r--r--]  sfile1
└── [drwxrwxr-x]  subdir2
├── [drwxrwxr-x]  RCS
│   └── [-r--r--r--]  sfile2,v
└── [-r--r--r--]  sfile2

5 directories, 6 files

In which all files but sfile1 are checked in to their respective RCS dirs. sfile1 has been checked out and modified.
rlog subdir1/sfile1 (a file that is properly checked-out) returns:
RCS file: subdir1/RCS/sfile1,v
Working file: subdir1/sfile1
head: 1.1
branch:
locks: strict
    torfey: 1.1
access list:
symbolic names:
keyword substitution: kv
total revisions: 1; selected revisions: 1
description:
----------------------------
revision 1.1    locked by: torfey;
date: 2016/07/20 13:09:34;  author: torfey;  state: Exp;
Initial revision
=============================================================================

Whereas rlog subdir2/sfile2 (a file that is properly checked-in) returns:
RCS file: subdir2/RCS/sfile2,v
Working file: subdir2/sfile2
head: 1.1
branch:
locks: strict
access list:
symbolic names:
keyword substitution: kv
total revisions: 1; selected revisions: 1
description:
----------------------------
revision 1.1
date: 2016/07/20 13:10:04;  author: torfey;  state: Exp;
Initial revision
=============================================================================

So the command I'd like would, given a directory argument, search for all files under that dir that are part of RCS and return names of any that are not checked in. (Ideally, also if there's some other state that is detectable and bad, like not locked yet different from checked in version, report that too.)
test_rcs_tree .

It would return, for my above simple case:
./subdir1/sfile1 checked-out

What I'm struggling with is whether there's maybe something out there that already does this that I'm just missing in all my searches.
I'm running on RHEL 6.7 which has rcs 5.7, gnu awk 3.1.7, gnu make 3.81, bash 4.1.2

A: I have a legacy rcs status script:
#!/bin/bash
find ${@:-.} -type f |
sed '\;/RCS/;d' |
while read file
do  msg=
    if [ -z "$(rlog -R "$file" 2>/dev/null)" ]
    then    msg="$msg no RCS"
    else    if co -q -kk -p "$file" | cmp -s - "$file" ||
               co -q -p "$file" | cmp -s - "$file"
            then    msg="$msg same"
            else    msg="$msg differs"
            fi
            if [ -z "$(rlog -L -R "$file")" ]
            then    msg="$msg not locked"
            else    msg="$msg locked"
                    user=$(rlog -h "$file" |
                           awk '/locks:/{ getline;
                                    sub(":"," "); print $1 }')
                    if [ -n "$user" ]
                    then    msg="$msg by $user"
                    fi
            fi
    fi
    if [ -w "$file" ]
    then    msg="$msg writeable"
    fi
    echo "$file: $msg"
done

Give it a directory or files and it will produce output like
whenerror: same not locked
kshrc: same not locked writeable
mylua.lua: no RCS writeable
subshell: differs locked by meuh writeable
mshrc: differs locked by meuh

where "same not locked" means it is checked in, and read-only, normally the desired state.

A: I use a utility checkup, which I wrote in the late 1980s, and pipe the results into my directory editor ded, from which I can run rcsdiff, or unlock or revert changes.
For the sake of example, a screenshot showing some files which are not checked-in, as well as one newer than the last check-in date:


text:
Q: devise session time_out I need to make timeout_in as dynamic value like below,But here self is not a instance of User model. can any one have idea how I can use that condition .
devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :token_authenticatable,  :confirmable, :lockable, :timeoutable , :omniauthable,:timeout_in =>  (self.email.nil? ? 111.minutes : 112.minutes)

A: This feature is on Devise master and should be released on a new Devise version soon. You can point your Gemfile to Devise git repository and start using it right now.
https://github.com/plataformatec/devise/wiki/How-To:-Add-timeout_in-value-dynamically
https://github.com/plataformatec/devise/pull/1462

A: I don't know if you can do that this way, since you are on a class scope.
To do what you want, define a method called timeout_in method that implements this logic. Because it has this method Devise tries to load timeout_in from an instance method, and after this it tries to get it from the class method.
EDIT: removed the monkey patch solution added a better one.
EDIT2: Improving the answer.


text:
Q: How to delay each iteration of a looping a-frame animation with aframe-animation-component In the included example, there are two animations using practically identical settings, with the exception of <a-animation>'s begin property being swapped with aframe-animation-component's delay.
<a-animation>'s begin property delays the animation in each iteration, which is the desired effect in this case. The aframe-animation-component doesn't seem to mirror this functionality with delay, at least with these settings.
Is this possible using aframe-animation-component without needing to use AFRAME.anime directly?
CodePen Example
Code:
<!-- Using <a-animation> begin -->

<a-box color="red" position="-1 1 -4">
  <a-animation attribute="material.opacity"
             begin="4000"
             from="0.1"
             to="1"
             dur="1000"
             repeat="indefinitely">
  </a-animation>
</a-box>

<!-- Using aframe-animation-component delay -->

<a-box color="red" position="1 1 -4"
     animation="property: material.opacity;
                delay: 4000;
                from: 0.1;
                to: 1;
                dur: 1000;
                loop: true;">
</a-box>

Thanks in advance.

A: I looked into aframe-animation-component code (the version you're using) and it seems that the delay is applied before first run of animation. You can either:

*

*Copy the component's code and modify it so it works as you expect it to.

*According to this piece of source code from aframe-animation-component:
onStartEvent: function () {
    // Include the delay before each start event.
    if (this.data.delay) {
      setTimeout(this.beginAnimation, this.data.delay);
      return;
    }
    this.beginAnimation();
  },

You can use a little workaround. Don't use loop: true, instead use startEvents: your-custom-event. The animation will start every time your-custom-event will be emitted by your entity. In addition, your entity will emit animationcomplete (docs) when animation ends - so you can listen for animationcomplete event and call el.emit("your-custom-event") to trigger it again and again to mock loop: true functionality and achieve desired effect, without modifying original component.


text:
Q: hive query in Job tracker Hi we are running hive queries in CDH 4 environment to which we recently upgraded. One thing I notice is that earlier in CDH 3 we were able to track our queries in Job tracker.
The link similar to "hostname:50030/jobconf.jsp?jobid=job_12345" would have a parameter "hive.query.string" or "mapred.jdbc.input.bounding.query" which contains the actual query for which the MR job is executed.
But in CDH4 I do not see where I can get the query. Many queries are run in parallel to keep track of which is the query we are concerned.

A: You can still view the hive queries in job tracker.
Get the job information based on the job id from below url         hostname:50030/jobtracker.jsp
You will find some details as mentioned below at the top of the page.

Hadoop Job 4651 on History Viewer
  User: xxxx JobName: test.jar
  JobConf:
  hdfs://domain:port/user/xxxx/.staging/job_201403111534_4651/job.xml
  Job-ACLs: All users are allowed Submitted At: 14-Mar-2014 03:15:19
  Launched At: 14-Mar-2014 03:15:19 (0sec) Finished At: 14-Mar-2014
  03:18:04 (2mins, 44sec) Status: FAILED Analyse This Job

Now click the URL next to the Job Conf you will find your submitted hive query.

A: I see that the query parameters for each job can be found in .staging folder in HDFS itself and can be parsed to get the Job_Ids associated query.


text:
Q: Drodpwn goes off the mobile width when expanded in lighnining component I have one lightning component. In that lightning component, I have one dropdown which goes out of the mobile width when expanded in mobile devices.
How can i make it responsive so that its width gets adjusted according to mobile device width?
Here is one snapshot.


text:
Q: Prevent Unpacked Usage of Chrome Extension My extension is proprietary licensed. I see some users download crx file from Chrome Store, extract it, modify it and run the extension as Unpacked which gives them ability to bypass paid functionality.
How can I prevent users to run local unpacked extension?

A: This may not fully answer your question, but if you want to check if the app is running in unpacked mode  or from the store, you can check the "update_url" key of the manifest, which is not present in unpacked mode.
if (! chrome.runtime.getManifest().update_url) {
    console.log('UNPACKED - DEV MODE!')
    DEVMODE = true
}


text:
Q: How to set the text of an NSTextView in Xamarin Mac? OK, from the "I never expected THIS to be the hard part" department: how do I set the text of a NSTextField in Xamarin Mac?
  NSTextView view = new NSTextView(new RectangleF(0, 500, 200, 40));
  view.StringValue = "Foo";

does not compile (no method "StringValue").  Nor does SetStringValue("Foo").  Nor does there appear to be any SetText method.  There's an InsertText method, but it doesn't take a C# string; it wants an NSObject (which makes me think it's not really intended for direct use).
Note that if I use NSTextField instead of NSTextView, I can assign to StringValue just fine.  But with NSTextField, the same code fails.
I'm experienced in ObjC programming on iOS, but pretty much a noob to both Mac Cocoa and Xamarin Mac.  So I'm sure I'm missing some obvious answer, but my googling hasn't found an answer (and the Xamarin forums are down today).  Any help will be greatly appreciated.

A: Have you tried the Value property?
http://forums.xamarin.com/discussion/14870/how-to-add-text-to-a-text-view-nstextview-in-a-nsscrollview-from-ib


text:
Q: Getting an error when trying to use my add and remove functions in mysql-python Whenever I try to use my addTask() and removeTask() functions I get a very long wait time followed by an error.
Here are the functions:
def addTask():

    name = raw_input("Enter the name of the task you would like to add: ")
    exists = cur.execute("SELECT Name FROM Tasks WHERE Name = '%s';" % name)
    if exists:
        print("Task already exists.")
    else:
        cur.execute("INSERT INTO Tasks(Name, Time) VALUES('%s', 0);" % name)
        print("'%s' has been added to the task list." % name)

def removeTask():

    name = raw_input("Enter name of the task you would like to delete: ")
    exists = cur.execute("SELECT Name FROM Tasks WHERE Name = '%s';" % name)
    if exists:
        cur.execute("DELETE FROM Tasks WHERE Name = '%s';" % name)
        print("'%s' has been removed from the task list." % name)
    else:
        print("Task doesn't exist.")

If I input a name that already exists in the addTask() function it works fine.  However, if I try to add a new task with a new name in the addTask() function I get this error:
Traceback (most recent call last):
  File "./timelog3.py", line 137, in <module>
    main()
  File "./timelog3.py", line 23, in main
    addTask()
  File "./timelog3.py", line 44, in addTask
    cur.execute("INSERT INTO Tasks(Name, Time) VALUES('%s', 0);" % name)
  File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-    x86_64.egg/MySQLdb/cursors.py", line 202, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1205, 'Lock wait timeout exceeded; try restarting     transaction')

Similarly for the remove function if I try with a non existential task name then it works fine.  But if I try to remove a task that exists I get the same error.
The thing that really perplexes me is that it was working just fine a few minutes before and I hadn't even changed anything (or I can't recall what I changed).

A: The error you're getting is saying that someone has a lock on the table (or the whole database, or some other subset of the data).
So, either another program is using the database, your program has multiple connections to the database, or your program has a single connection and is trying to do two things on it interleaved (or even at the same time, if you have multiple threads).
One common possibility is that you started the script, put it in the background, and then started the same script again, and they're now fighting with each other. A few minutes ago, you didn't have two copies running, so it all worked fine.


text:
Q: Socket.io extend Socket class I want to create a new function for the Socket class in socket.io but i have no idea how to accomplish this.
I would like to call the function like this socket.nearby().emit().
My code below:
const server = require('http').createServer()
const socketio = require('socket.io')
const io = socketio(server)

io.on('connection', (socket) => {
    socket.on('join', (data, callback) => {
        // process data

        socket.nearby().emit('join', data)

        callback(data)
    })
})

io.prototype.nearby = function() {
    // do function
}

A: io is not the constructor for the socket.io Socket class so that's why what you showed wouldn't work as you don't have the correct prototype.
The simplest way, without delving into the socket.io source code to try to find how you can access the socket prototype, would be to just do this:
const server = require('http').createServer()
const socketio = require('socket.io')
const io = socketio(server)

io.on('connection', (socket) => {

    // add our custom method to each newly created socket object
    socket.nearby = function() {
        // add implementation code here
    }

    socket.on('join', (data, callback) => {
        // process data

        socket.nearby().emit('join', data)

        callback(data)
    })
})


text:
Q: How to enable async boost::beast websocket applications to support multiple connections for load balance? Reference:
https://www.boost.org/doc/libs/1_80_0/libs/beast/example/websocket/client/async-ssl/websocket_client_async_ssl.cpp
My websocket client application was built based on the above example. Now I experience a bottleneck where one websocket connection subscribes too many channels from server and the server has a limit on how many messages a single connection can receive. In order to fix the issues, the solution is to load balance multiple channels across a few websocket connections. The platform I am using is Linux.
Question> Does the boost::beast framework offer a way so that I can easily add support for multiple websocket connections without locks(i.e. still use the asynchronous operations shown in above example). It is best if there is an example to illustrate the basic idea.
class WebSocketConnection {
  ...
  void on_read(beast::error_code ec, std::size_t) {
      if (ec)
        return fail(ec, "read");

      // trigger MainClass::message_callback
      msg_callback(std::move(buffered_message_from_server));

      // continue to read further messages from server
    }
    ...
}

class MainClass {
  void message_callback(std::string msg) {

    }
  ...
  WebSocketConnection websocket_;
};

Updated:
One solution I could figure out is follows but I am not sure whether this is applicable.
class WebSocketConnection {
  ...
  void on_read(beast::error_code ec, std::size_t) {
      if (ec)
        return fail(ec, "read");

      // trigger MainClass::message_callback
      msg_callback(std::move(buffered_message_from_server));

      // continue to read further messages from server
    }
    ...
}

class MainClass {
  void message_callback(std::string msg) {

    }
  ...
  std::vector<WebSocketConnection> websockets_;
};

Basically, I define a vector of WebSocketConnection within MyClass. Each instance of WebSocketConnection will be registered a same callback function(i.e. MainClass::message_callback). Also each instance of WebSocketConnection will be passed the same net::io_context and net::strandnet::io_context::executor_type, so that all message_callback from the pool of websocket will be a sequential event.
Question> Can I do this setup without introducing race condition?
Thank you


text:
Q: javascript : How do I make a function wait for another to complete? I have some code similar to this :
$(function() {
  var focusOutEvent = function() {
    $.when(
      getCounterValue()
    ).done(function() {
      console.log('catchValidateButtonClick');
    });
  }

  var getCounterValue = function() {
    $.when(
      console.log('updateCacheData')
    ).done(function() {
      computeCounterValue(function() {
        console.log('counterValueComputation done');
      });
    });
  }

  var computeCounterValue = function(callback) {
    setTimeout(function() {
      callback();
    }, 3000);
  }

  focusOutEvent();
});

Currently, the console prints statements in this order :

*

*"updateCacheData"

*"catchValidateButtonClick"

*"counterValueComputation done"

How do I make the console print "counterValueComputation done" before "catchValidateButtonClick" ?

A: Make getCounterValue return a Promise. Here's an example with minimal changes:
  var getCounterValue = function() {
    return $.when(
      console.log('updateCacheData')
    ).then(function() {
      let d = $.Deferred();
      computeCounterValue(function() {
        console.log('counterValueComputation done');
        d.resolve();
      });
      return d;
    });
  }

Here's a cleaner way to do it:
  var getCounterValue = function() {
    return $.when(
      console.log('updateCacheData')
    ).then(function() {
      return computeCounterValue().then(function() {
        console.log('counterValueComputation done');
      });
    });
  }

  var computeCounterValue = function() {
    return new Promise(resolve => setTimeout(resolve, 3000));
  }

And here's what it could look like with async/await.

$(function() {
  var focusOutEvent = async function() {
    await getCounterValue();
    console.log('catchValidateButtonClick');
  }

  var getCounterValue = async function() {
    console.log('updateCacheData');
    await computeCounterValue();
    console.log('counterValueComputation done');
  }

  var computeCounterValue = function() {
    return new Promise(resolve => setTimeout(resolve, 3000));
  }

  focusOutEvent();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: From a triangular matrix to a symmetric square matrix I am a computational physics postgrad student, working with libraries like ATLAS and MAGMA.  I have a matrix which is upper-triangular, and is the result of a Cholesky decomposition.  I need to convert the upper-triangular matrix in to a symmetric, square matrix where the elements of the lower triangle are
mat(j,i) = mat(i,j)
I have a naive routine in C++ that simply does the above in a loop, but it's incredibly slow.  I believe it's so slow because the CPU cache is poorly utilised - element i,j is quite far from element j,i.
Is there a clever mathematical trick that I can use to optimise this loop?  Or alternatively, does anyone know of any fuctions in BLAS/similar libraries that can do this kind of operation?
Many thanks in advance for any advice you can give.


text:
Q: Why does it take maximum of $n/\log n$ digits to represent the number $2^n - 1$ in base of $n$? Given the number $n$. Why does it take maximum of $\frac{n}{\log n}$ digits to represent the number $2^n - 1$ in base of $n$?

A: Hint:  to express any number $m$ in base $n$ takes $\lfloor \log_n m \rfloor +1$ digits.  To see this, think about base $10$.  With one digit you can express any number up to $9$, for which the floor of the log is $0$.  With three digits you can express numbers up to $999$, for which the floor is $2$.  What base of logs were you planning to use?


text:
Q: Ngrx Store Resets after browser refresh. How to make the application preserve the state? I Dispatch a action from one component
this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});

and in the other component i select from the store using
this.store.select(state => state.table.teamCrest).subscribe(data => this.teamCrest = data);

This works fine if my app is going sequentially backward or forward, but once i do a browser refresh the state loses it's value. How to preserve it's value so that it works on browser refresh?

A: Your store has a subscribe function which will be called any time an action is dispatched, and some part of the state tree may potentially have changed. For a simple solution, you could persist the state to local storage here:
this.store.subscribe(function() {
    localStorage.setItem('state', JSON.stringify(this.store.getState()));
})

Documentation here
Notice that you will need to stringify your state to store it in local storage
To use this state, you will need to pass the local storage state localStorage.getItem('state') (if it exists) as your default state in your reducer. To achieve this, i normally have a helper function check whether an item with key 'state' exists in local storage and calls JSON.parse on the value if it exists.
default reducer case:
default:
        if (retrieveState()) {
            var newState = JSON.parse(retrieveState())
            return newState
        }
        else {
            return {...whatever your default state is};
        }

Also after a quick look around, there does appear to exist a middleware which should achieve what you are wanting: https://github.com/btroncone/ngrx-store-localstorage

A: Here is a cool medium article. This guy wraps the default create reducer function with a rehydrate one which saves data to local storage.
P.S. In case of ts errors check the comments of the article.


text:
Q: How to map array of elements inside the marquee tag in react I want to display array of elements one by one in marquee.
How to map array of elements inside the marquee in the react

A: In the react you can map the array of the elements one by one using the Array.prototype.map method like this:
    render() {
       return (
         <marquee>
           {theArray.map(theElement => theElement.toString())}
         </marquee>
       );
    }

of course you can change theElement.toString() to whatever you prefer
as a side note, marquee is a deprecated/obsolete html element and you should avoid using it
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee


text:
Q: Strip PHP extension using .htaccess I am using
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

in .htaccess file.
It works ok in that www.site.com/about shows the about.php page, but it still allows users to strictly specify .php, for e.g. www.site.com/about.php does not strip the .php.
Is it possible to do this, so even when they type the .php extension it strips it but still shows that page?
Thanks

A: You can add this rule before your current rule:
RewriteCond %{THE_REQUEST} \s/+(.*?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]


text:
Q: How to display unique records in a table using MySQL I am trying to display all unique records from table.
SQL Script:
CREATE TABLE certificate(
    id INT PRIMARY KEY,
    full_name VARCHAR(200),
    address VARCHAR(200),
    date_of_birth DATETIME,
    special_code INT,
    validity VARCHAR(200)
);

INSERT INTO certificate VALUES('1','Walter White','Albuquerque 87107','1970-10-10','1000','VALID');
INSERT INTO certificate VALUES('2','Skyler White','Albuquerque 87107','1978-10-10','1001','VALID');
INSERT INTO certificate VALUES('3','Jesse Pinkman','Santa Fé 28','1979-10-10','1002','INVALID');
INSERT INTO certificate VALUES('4','Hank Schrader','El Paso 17','1980-10-10','1003','VALID');
INSERT INTO certificate VALUES('5','Hank Schrader','El Paso 17','1980-01-10','1004','VALID');
INSERT INTO certificate VALUES('6','Walter White','Albuquerque 87107','1970-10-10','1005','VALID');
INSERT INTO certificate VALUES('7','Saul Goodman','El Paso 14','1973-10-10','1006','VALID');
INSERT INTO certificate VALUES('8','Gustavo Fring','Santa Fé 190','1964-10-11','1007','INVALID');
INSERT INTO certificate VALUES('9','Walter White','Albuquerque 87107','1978-01-08','1008','VALID');
INSERT INTO certificate VALUES('10','Hank Schrader','El Paso 17','1980-10-10','1009','VALID');
INSERT INTO certificate VALUES('11','Walter White','Albuquerque 87107','1978-01-08','1010','VALID');
INSERT INTO certificate VALUES('12','Hank Schrader','El Paso 98','1980-10-10','10011','VALID');
INSERT INTO certificate VALUES('13','Hank Schrader','El Paso 98','1980-10-10','10012','VALID');

Queries:
The numbers of special code entries with valid certificates
select full_name, count(*) from certificate where validity = 'VALID' group by full_name;

All persons with valid certificates
select * from certificate where validity = 'VALID' order by full_name;

There are two people with this name but they live at a different address, so we can assume that it's not the same person and the result from first select is "incorrect"
select * from certificate where validity = 'VALID' and full_name = 'Hank Schrader';

In this selection there are three records belonging to two persons father and son.Both live at the same address but do not have the same date of birth result from first select is too "incorrect"
select * from certificate where validity = 'VALID' and full_name = 'Walter White';

So what I need:

*

*If the name is the same, I check the address with the other entries
in the table with the same name.

*If the address is the same, I will
check the date of birth with the other entries in the table with the
same name.

*If this is the case, it is the same person, if not, the
person is different and only

Then can I add the record.
Ultimately, I need a list of all unique people with their ids who have a valid certificate and have more than one entry in the table (Walter White with ID 11 does not represent the same person as Walter White with ID 8)
So result will be:
full_name     | ids
----------------------
Walter White  | 1,6
Walter White  | 9,11
Hank Schrader | 4,5,10
Hank Schrader | 12,13

The full code is available on:
http://sqlfiddle.com/#!9/71c251/1

A: You can try below - use group by full_name,address,date_of_birth
DEMO
select full_name,
count(id) from certificate where validity = 'VALID'
group by full_name,address,date_of_birth having count(id)>1

A: E.g.:
SELECT x.full_name
     , x.date_of_birth
     , GROUP_CONCAT(y.id) aliases
  FROM certificate x
  JOIN certificate y
    ON y.full_name = x.full_name
   AND y.address = x.address
   AND y.date_of_birth = x.date_of_birth
   AND y.id >= x.id
 GROUP
    BY x.full_name
     , x.date_of_birth
HAVING COUNT(aliases) > 1;


text:
Q: How does visual studio colorize c# code? How does visual studio colorize c# code?
I know visual studio has an abstract class LanguageService, it has a property GetColorizer, may colorize code.
But I can't find c# language's implement of LanguageService class.
Help me.
Or any other method to use visual studio's way to colorize is acceptable.

A: You are looking in the wrong place. The editor is the component that does the coloring, not the language service.
http://msdn.microsoft.com/en-us/library/dd885244.aspx
There is also sample code in the MSDN gallery that implements color highlighting for IronRuby.  I would study that code for an example.


text:
Q: Multiple Mootools Carousels on a single page I have been looking around online for a MooTools carousel plug-in that will allow me to have multiple on a single page.
I currently have this one working successfully for a single carousel, but it doesn't seem to allow multiple on a page.
Am I doing something wrong with the plug-in mentioned, or is there a recommended plug-in that exists somewhere?


text:
Q: iOS Simulator failed to install the application - nothing has worked I been trying to figure out the problem for this and cannot figure it out. Every time I run my Xcode project in the simulator I get an iOS Simulator failed to install the application error. I have tried resetting the content and settings in the simulator and that has not worked. I have tried running other projects in the simulator and they work fine. One thing I did do right before it stopped working was add a font into the plist. I am not sure if that is the problem but here is my current plist (maybe i accidentally deleted something?):

Thanks.

A: I just figured it out, I was missing the Executable file Thanks!


text:
Q: How do I database level contraints to my rails application long after I've migrated everything? 1) I've created an entire Rails JSON API as my first project. It's fairly sizeable, and I put off database level constraints at the time. It's time to do it now.
I have 30+ or so migrations. For example
    class CreateItems < ActiveRecord::Migration
      def change
        create_table :items do |t|
          t.string :name
          t.text :description

          t.timestamps
        end
      end
    end

When I go in and edit
t.string :name

to be
t.string :name, null: false

and run a bundle exec db:reset db:migrate it doesn't work. What do I need to do to add db level constraints to my migrations files, and re migrate them?
2) Also, my 30+ migrations all have a "def change" and that's it. I believe somewhere a long time ago I saw something like def up, def down or something like that. It looks like it was used for rollbacks. Do I need to have "def down" for all of my migrations? Is that how I solve #1? Put "def down" in all of my 30 migrations, rollback the entire thing, then put in my db level constraints, and migrate the whole thing again?

A: You have two options: you can write new migrations to make changes to the existing columns. In console:
rails g migration add_null_to_name

In the migration file:
class ChangeNumbericFieldInMyTable < ActiveRecord::Migration
  def self.up
    change_column :my_table, :name, :string, :null => false
  end

  def self.down
    change_column :my_table, :name, :string
end

Rinse and repeat for all the changes you need to make. Note that you can define them in the same migration file, but then if you had to rollback in the future it would roll back all of them.
Your second option is to roll everything back (or just start over), fix your migration methods and remigrate. This might be a cleaner approach, but that's not necessarily a good thing: it would also delete the existing data, if you have any.
I know I said you have two options, but you actually also have a third option, which is to to rely on model validations instead. These are more appropriate in most situations and can make testing much easier. Database validations are more reserved for complex scenarios where the database is used by other applications in addition to yours, and a few other edge cases.
As for your second question, every migration is a two-way street. When you migrate something, you should also be able to roll it back. In a lot of cases Rails can guess the reverse operation. For example, if you add_column in a migration, the opposite of that is obviously remove_column so you don't need to define it explicitly. But certain operations, such as change_column in the example above, don't have an obvious reverse. Rails can understand that something changed, but it can't tell what it changed from. So in those situations you need to explicitly define the down operation. In the case above, it's changing the column back to a state where it doesn't have a validation.


text:
Q: Autoplay Youtube video - iframe As you could make a Youtube video it will automatically run ?
I used autoplay = 1 and does not work
The video is for Android app
The code from the video is:

        Tutorial

            continuar

A: Replace the ; before autoplay=1 with &.
EDIT: autoplay doesn't work on webviews. You have to use youtube api to achieve that.

A: Use the url like this:
https://www.youtube.com/embed/*******?rel=0&autoplay=1


text:
Q: Elasticsearch group and aggregate nested values I want get in one request data to build something like this:
Categories:
 - laptops (5)
 - accessories (50)
 - monitors (10)
 -- above part is easy --

Attributest for actual category ex. laptops:
 - card reder:
  - MMC (1)
  - SD (5)
 - resolution:
  - 1024x768 (2)
  - 2048x1536 (3)

First I make mapping on my Elasticsearch like this:
{
    "mappings": {
    "product": {
        "properties": {
            "name": {
                "type": "string"
            },
            "categoryName": {
                "type": "string",
               "index": "not_analyzed"
            },
            "priceBrutto": {
                "type": "float"
            },
            "categoryCode": {
                "type": "integer"
            },
            "productAttributeFields" : {
                "properties" : {
                    "name" : {
                        "index" : "not_analyzed",
                        "type" : "string"
                    },
                    "value" : {
                        "index" : "not_analyzed",
                        "type" : "string"
                    }
                }
            }
         }
      }
   }
}

Then I add objects looks like below.
In productAttributeFields will be many attributes. If laptop has many ports, every port is another array in productAttributeFields.
Array
(
    [name] => Macbook Pro
    [categoryCode] => 123
    [categoryName] => Notebooks
    [priceBrutto] => 1500
    [productAttributeFields] => Array
        (
            [0] => Array
                (
                    [name] => Resolution
                    [value] => 2048x1536
                )

            [1] => Array
                (
                    [name] => Memory Readers
                    [value] => MMC
                )
            [2] => Array
                (
                    [name] => Memory Readers
                    [value] => SD
                )
        )
)

Now I want get result like this:
Array
(
    [took] => 132
    [timed_out] =>
    [_shards] => Array
        (
            [total] => 1
            [successful] => 1
            [failed] => 0
        )

    [hits] => Array
        (
            [total] => 631
            [max_score] => 0
            [hits] => Array
                (
                )

        )

    [aggregations] => Array
        (
            [attrs] => Array
                (
                    [doc_count_error_upper_bound] => 0
                    [sum_other_doc_count] => 4608
                    [buckets] => Array
                        (
                            [0] => Array
                                (
                                    [key] => Resolution
                                    [doc_count] => 619
                                    [attrsValues] => Array
                                        (
                                            [doc_count_error_upper_bound] => 0
                                            [sum_other_doc_count] => 14199
                                            [buckets] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [key] => 2048x1536
                                                            [doc_count] => 123
                                                        )

                                                    [1] => Array
                                                        (
                                                            [key] => 1024x768
                                                            [doc_count] => 3
                                                        )

                                                )

                                        )

                                )

                            [1] => Array
                                (
                                    [key] => Memory Readers
                                    [doc_count] => 618
                                    [wartosci] => Array
                                        (
                                            [doc_count_error_upper_bound] => 0
                                            [sum_other_doc_count] => 14185
                                            [buckets] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [key] => MMC
                                                            [doc_count] => 431
                                                        )

                                                    [1] => Array
                                                        (
                                                            [key] => SD
                                                            [doc_count] => 430
                                                        )

                                                )

                                        )

                                )

                        )

                )
        )
)

I'm close to solving the problem (below my query), but in second level aggregation I have all of values (ex. in "resolution" I have 2048x1536, MMC and SD). I want to have in "resolution" only "2048x1536", "1024x768" and other values which has key "resolution", on "card readers" only "MMC", "SD" and other values which has key "card readers".
'body' => [
    'query' => [
        'match' => [
            categoryCode = 123
        ],
    ],
    'aggs' => [
        'attrs' => [
            'terms' => [
                'field' => 'productAttributeFields.name',
            ],
            'aggs' => [
                'attrsValues' => [
                    'terms' => [
                        'field' => 'productAttributeFields.value',
                        'size' => 100,
                    ],
                ],
            ],
        ],
    ],
]

A: You need to change your mapping and make productAttributeFields a nested field so that you can retain the association between productAttributeFields.name and productAttributeFields.value.
The mapping should look like this:
{
  "mappings": {
    "product": {
      "properties": {
        "name": {
          "type": "string"
        },
        "categoryName": {
          "type": "string",
          "index": "not_analyzed"
        },
        "priceBrutto": {
          "type": "float"
        },
        "categoryCode": {
          "type": "integer"
        },
        "productAttributeFields": {
          "type": "nested",
          "include_in_parent": true,
          "properties": {
            "name": {
              "index": "not_analyzed",
              "type": "string"
            },
            "value": {
              "index": "not_analyzed",
              "type": "string"
            }
          }
        }
      }
    }
  }
}

And the query changes to
{
  "query": {
    "match": {
      "categoryCode": 123
    }
  },
  "aggs": {
    "attrs_root": {
      "nested": {
        "path": "productAttributeFields"
      },
      "aggs": {
        "attrs": {
          "terms": {
            "field": "productAttributeFields.name"
          },
          "aggs": {
            "attrsValues": {
              "terms": {
                "field": "productAttributeFields.value",
                "size": 100
              }
            }
          }
        }
      }
    }
  }
}


text:
Q: How to keep form at centre using bootstrap 2.2.2 In this bootply the welcome as well as the form is coming on the left hand side.But I want to bring it at the centre.Can any body please tell me how to do?
<form id="form1">

Welcome

                        Please login with your Username and Password.

                        <fieldset>

                                <input autofocus="" class="input-large span10" name="j_username" id="username" type="text" value="">

                                <input class="input-large span10" name="j_password" id="password" type="password" value="">

                            <input type="checkbox" id="remember" style="display:">Remember me

                            <button type="submit" class="btn btn-primary">Login</button>
                            New Userregister

                        </fieldset>

</form>

A: try to set your welcome div in another div like this

Welcome

use offset

Move columns to the right using .offset* classes. Each class increases
  the left margin of a column by a whole column. For example, .offset4
  moves .span4 over four columns.

DEMO

A: Try using this in your CSS
.row-fluid .login-header,
.row-fluid .login-box{
      float:none;
      margin:0 auto !important;
}

A: Since .span* has float: left style by default, you can override it by using float:none;
.login-box {
    margin:0 auto;
    float:none;
}

margin:0 auto; is used to center your loginbox horizontally.


text:
Q: Can this shape of matrix elements in the path integral formalism be linked to some sort of expectation value? This question is about expressions of the form
$$
\langle x_f, t_i | \hat{x}(t) | x_i, t_i \rangle = \frac{1}{N} \int_{x(t_i) = x_i}^{x(t_f) = x_f} \mathcal{D} x~x(t)e^{i S[x]}.
$$
In the following the states and operators are meant to be understood in the Heisenberg picture.
I know how to arrive at the rhs of the equation: Putting an identity into the lhs:
$$
\langle x_f, t_i | \hat{x}(t) \int dx |x, t \rangle \langle x,t | | x_i, t_i \rangle  \\
=
 \int dx  \langle x_f, t_i |x, t \rangle x \langle x, t | x_i, t_i \rangle \\
= \int dx K(x_f, t_f, x, t)  x K(x, t, x_i, t_i) \\
= \int dx \frac{1}{N_f} \int_{x(t) = x}^{x(t_f) = x_f} \mathcal{D} x e^{i S[x]}  x \frac{1}{N_i} \int_{x(t_i) = x_i}^{x(t) = x} \mathcal{D} x ~ x(t)e^{i S[x]} \\
= \frac{1}{N} \int_{x(t_i) = x_i}^{x(t_f) = x_f} \mathcal{D} x  x(t)e^{i S[x]}.
$$
What is the meaning of this object? Can this be thought of an "expectation value" of some sort?
Of course, the argument is somewhat clear (as also mentioned in this question:For a given $x$, $x_i$ and $x_f$ you get (by $K(x_f, t_f, x, t)$ the probability-AMPLITUDE that a particle that was at $x_i$ at time $t_i$ will be at $x$ at time $t$, and with $K(x, t, x_i, t_i)$ the probability-amplitude that a particle starting at $x$ at time $t$ will be found at $x_f$ at time $t_f$.
So if you definitely know that the particle started at $x_f$ and ended at $t_f$ then the product of both yields the Amplitude by which the particle was at $x$ at time t. Integrating over all x might then give you what is widely called "expectation value" - except for some difficulties (that the cited question sadly doesn't resolve):

*

*For the expectation value interpretation to hold, wouldn't we need the probability (absolute square of $K * K$? )

*Can we be sure that the result is real? I tried to take the complex conjugate, but in order to proof that it will be the same result, I need to make additional assumptions on $K$

*Usually expectation values are taken between the same states, but even between same states, we still have problems with expression not neccessarily being real.


text:
Q: Part title in list of figures and tables? I'm using KOMAScript. I have a \listoffigures and a \listoftables. My document has several \part{}'s. In the two lists the figures and tables are already grouped (small vertical space) by the chapters.
What I'd like to have additionally to the ("anonymous") chapter vspace grouping is the part title over each "part group" of figures and tables in the two lists. Is this somehow possible without having to code a list from scratch?

A: You can setup your own entry by:
\newcommand{\addtocentrylistof}[3]{%
  \ifstr{#2}{}{%
    \addcontentsline{lof}{#1}{#3}%
    \addcontentsline{lot}{#1}{#3}%
  }{%
    \addcontentsline{lof}{#1}{\protect\numberline{#2}#3}%
    \addcontentsline{lot}{#1}{\protect\numberline{#2}#3}%
  }%
}

\renewcommand*{\addparttocentry}[2]{%
  \addtocentrydefault{part}{#1}{#2}%
  \addtocentrylistof{part}{#1}{#2}%
}

Here a small example:
\documentclass[english]{scrreprt}
\usepackage{babel}
\newcommand{\addtocentrylistof}[3]{%
  \ifstr{#2}{}{%
    \addcontentsline{lof}{#1}{#3}%
    \addcontentsline{lot}{#1}{#3}%
  }{%
    \addcontentsline{lof}{#1}{\protect\numberline{#2}#3}%
    \addcontentsline{lot}{#1}{\protect\numberline{#2}#3}%
  }%
}

\renewcommand*{\addparttocentry}[2]{%
  \addtocentrydefault{part}{#1}{#2}%
  \addtocentrylistof{part}{#1}{#2}%
}
\def\examplefig{\begin{figure}[!ht]\caption{foo}\end{figure}\begin{table}[!ht]\caption{foo}\end{table}}
\begin{document}
\tableofcontents
\listoffigures
\listoftables

\part{O I}
\chapter{foo}
\examplefig\examplefig\examplefig
\chapter{foo}
\examplefig\examplefig\examplefig
\chapter{foo}
\examplefig\examplefig\examplefig
\part{O II}
\chapter{bar}
\examplefig\examplefig\examplefig
\chapter{bar}
\examplefig\examplefig\examplefig
\chapter{bar}
\examplefig\examplefig\examplefig

\end{document}

A: This is just an adaptation from this answer to Include chapters in List of Figures with titletoc? . The inclusion is made automatically using the standard commands and only for the parts with figures:
\documentclass{scrreprt}
\usepackage{etoolbox} % or xpatch

\makeatletter
% initial definitions of the chapter info (name and number)
\def\thischaptertitle{}\def\thischapternumber{}
\newtoggle{noFigs}
\newtoggle{noTabs}

\apptocmd{\@part}%
  {\gdef\thisparttitle{#1}\gdef\thispartnumber{\thepart}%
    \global\toggletrue{noFigs}\global\toggletrue{noTabs}}{}{}

% the figure environment does the job: the first time it is used after a \chapter command,
% it writes the information of the chapter to the LoF
\AtBeginDocument{%
  \AtBeginEnvironment{figure}{%
    \iftoggle{noFigs}{
      \addtocontents{lof}{\protect\contentsline {part}%
        {\protect\numberline {\thispartnumber} {\thisparttitle}}{}{} }
      \global\togglefalse{noFigs}
    }{}
  }%
  \AtBeginEnvironment{table}{%
    \iftoggle{noTabs}{
      \addtocontents{lot}{\protect\contentsline {part}%
        {\protect\numberline {\thispartnumber} {\thisparttitle}}{}{} }
      \global\togglefalse{noTabs}
    }{}
  }%
}

\makeatother

\begin{document}

\tableofcontents
\listoffigures
\listoftables

\part{Test Part With Figures and Tables}
\chapter{Test Chapter with Figures and Tables}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{table}
\caption{caption text for a table}
\end{table}

\part{Test Part with no Figures and no Tables}

\part{Test Part with no Figures and Tables}
\chapter{Test Chapter with Table}
\begin{table}
\caption{caption text for a table}
\end{table}

\part{Test Part with no Tables and Figures}
\chapter{Test Chapter with Figure}
\begin{figure}
\caption{caption text}
\end{figure}

\part{Another Test Part With Figures and Tables}
\chapter{Another Test Chapter}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{table}
\caption{caption text for a table}
\end{table}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{table}
\caption{caption text for a table}
\end{table}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{figure}
\caption{caption text}
\end{figure}

\end{document}

An image of the LoF:

An image of the LoT:


text:
Q: C# GridView Cell - hyperlink I have this code to get data from my database to a Gridview:
public void mainSelect(DataGridView gvMain)
        {
            string sSQL = " SELECT" +
                "      tbMain.id, tbBrand.name AS brand, tbModel.name AS model, tbMain.name, tbType.name AS type, tbClub.name AS club, tbMain.serial, tbMain.porder, tbMain.link, tbUser.name AS lastEditBy, tbMain.lastEditDate" +
                          "  FROM" +
                          "      tbMain, tbBrand, tbModel, tbType, tbClub, tbUser" +
                          " WHERE" +
                          "     tbBrand.id = tbMain.brand" +
                          " AND" +
                          "     tbModel.id = tbMain.model" +
                          " AND" +
                          "     tbType.id = tbMain.type" +
                          " AND" +
                          "     tbClub.id = tbMain.club" +
                          " AND" +
                          "     tbUser.id = tbMain.lastEditBy" +
                          " ORDER BY " +
                          "     club ASC";

            sqlConnect connect = new sqlConnect();
            DataTable dt = new DataTable();
            dt = connect.getBD(sSQL);

            gvMain.DataSource = dt;
            gvMain.Columns[0].HeaderText = "ID";
            gvMain.Columns[1].HeaderText = "Brand";
            gvMain.Columns[2].HeaderText = "Model";
            gvMain.Columns[3].HeaderText = "Computer Name";
            gvMain.Columns[4].HeaderText = "Type";
            gvMain.Columns[5].HeaderText = "Site";
            gvMain.Columns[6].HeaderText = "Serial Number";
            gvMain.Columns[7].HeaderText = "Purchase Order";
            gvMain.Columns[8].HeaderText = "Invoice Link";
            gvMain.Columns[9].HeaderText = "Last Edit By";
            gvMain.Columns[10].HeaderText = "Last Edit Date";

It work fine, what I need now is to set the 8th column (invoice link) to be a link field so I can click and open it.
how can I accomplish this ? thanks

A: try using DataGridViewLinkColumn
DataGridViewLinkColumn link = new DataGridViewLinkColumn();
link.DataPropertyName = "InvoiceLink";
link.Name = "Invoice Link";
dataGridView1.Columns.Add(link);

add it to your grid, after binding your grid
you might need to set AutoGenerateColumns to false

A: Use templatefields in Gridview:
<asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Bind("LeadID") + Request.QueryString("type") %>'
                            Text=""></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>


text:
Q: how to assign a role to user for Specified time, asp.net mvc5, Identity 2.0 how to assign a role to user for Specified time (for example 10 day) using asp.net mvc5, Identity 2.0
I think we can do it by adding an expiration field to AspNetUsersRoles table like below, but I dont know how?
AspNetUsersRoles

A: I would keep Identity intact and use antoher table to store that (Extension Table).
With that, the additionnal table would store FK_UserRole and a Date.
Then you can check the date of the person on each conneciton of this person and remove the role if neccessary.


text:
Q: how to calculate this limit? calculus I. $$\lim_{x\to 4} \frac{\sqrt{x^2 -3x} -2}{2^x-2^4}$$
I cannot use l'hospitale rule or any other,just with modificating the limit,it's for calculus I.

A: $\lim_{x\to 4} \frac{\sqrt{x^2 -3x} -2}{2^x-2^4} =\lim_{x\to 4} \frac{\sqrt{x^2 -3x} -2}{2^x-2^4} \cdot \frac{\sqrt{x^2 -3x} +2}{\sqrt{x^2 -3x} +2}=\lim_{x\to 4} \frac{x^2 -3x -4}{(2^x-2^4)(\sqrt{x^2 -3x} +2)}=\lim_{x\to 4} \frac{(x-4)(x+1)}{(2^x-2^4)(\sqrt{x^2 -3x} +2)}=\lim_{x\to 4} \frac{x-4}{2^x-2^4} \frac{x+1}{\sqrt{x^2 -3x} +2}=\frac{1}{(2^x)'|_{x=4}} \cdot \lim_{x \rightarrow 4}\frac{x+1}{\sqrt{x^2 -3x} +2} \\ \text{ You said you are given that } \\ \lim_{u \rightarrow 0} \frac{2^u-1}{u}=\ln(2) \text{ Sub in } u=x-4 \\ \lim_{x \rightarrow 4}\frac{2^{x-4}-1}{x-4}=\ln(2)  \text{ multiply both sides by } 2^4 \\ \lim_{x \rightarrow 4} \frac{2^x-2^4}{x-4}=2^4 \ln(2)\\ $


text:
Q: Why does boost::program_options throw an error about a required argument when the default is defined This is my code:
#include <iostream>
#include <string>
#include "boost/program_options.hpp"
namespace po = boost::program_options;

int main(int argc, char *argv[]) {
    po::options_description cli_opts_desc("General flags");
    cli_opts_desc.add_options()
        ("help,h", po::value<std::string>()->default_value("all"), "Show this help message.")
    ;
    po::variables_map flags;
    po::store(po::parse_command_line(argc, argv, cli_opts_desc), flags);
    if (flags.count("help")) {
        std::cout << "flags['help'] is " << flags["help"].as<std::string>() << std::endl;
        if (flags["help"].as<std::string>() != "all") std::cout << "specific description for "
                                                              << flags["help"].as<std::string>() << std::endl;//todo
        else std::cout << cli_opts_desc << std::endl;
    } else {
        std::cout << "no --help provided" << std::endl;
    }
}

Or rather, a simplified version of it. When I run
./test

it shows the help message, as expected. However, if I run
./test --help #or
./test -h

then it throws an error:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::invalid_command_line_syntax> >'
  what():  the required argument for option '--help' is missing
Aborted

I don't understand why this is happening even when I declare a default value.
What's causing this error? How can I fix it?
NB: I'd like to avoid using implicit_value if possible; in the real world, this isn't limited to my --help, and being able to specify arguments to short options with a space between is a nice little thing that avoids stupid errors.

A: Try this:
("help,h", "Show this help message.")

No parameter, but no complaint when there is no parameter supplied.


text:
Q: CartoDB preferred file type I was wondering if anyone knew the preferred upload file type is for CartoDB.I upload zipped .shp files for polygons, and sometimes .csv file for point data. I noticed that when I uploaded a zipped .shp file it hit the 50mb account limit even though the file only ended up being 9mb in cartodb when I upgraded accounts.
Is this becasue it is duplicating the table during processing? Is there a preferred file type for cartoDB? GeoJSON?
thanks,

A: I tend to recommend shapefiles, since they retain the type information better than CSV. With CSV you have to change your data type to number if you want to do choropleth and bubble maps.
GeoJSON works too, but will be a bit bulkier to upload.
Hitting the account limit when uploading a 5mb file sounds like it might just be a bug. Could you email support [at] cartodb.com with the shapefile (if you can share it?) - the team can try it out and see what's going wrong.