text:
Q: Java ArrayList starts with 1 not 0? I'm retrieving some data from DB with the ff code:
List<modelA> list= new ArrayList<modelA>();
list = modelA.getList(parameter);

This is what has been retrieved:
list[1] = "var1"

list[2] = "var2"

list[3] = "var3"

list.size() = 3 and list[0] does not exist.
I transferred the list to a LinkedHashSet to set the indexes right, but it doesn't work. The list is still the same.
Set<modelA> hs = new LinkedHashSet<>();
hs.addAll(list);
list.clear();
list.addAll(hs);

Is there a way to fix the indexes so that it will start with 0 and not 1?
This is the error when I run list.get(0)
java.lang.NullPointerException
    at applicationmodels.f08.pv.F08PV008Model.search(F08PV008Model.java:221)
    at controllers.f08.pv.F08PV008.control(F08PV008.java:148)
    at Routes$$anonfun$routes$1$$anonfun$applyOrElse$99$$anonfun$apply$99.apply(routes_routing.scala:1510)
    at Routes$$anonfun$routes$1$$anonfun$applyOrElse$99$$anonfun$apply$99.apply(routes_routing.scala:1510)
    at play.core.Router$HandlerInvoker$$anon$7$$anon$2.invocation(Router.scala:183)
    at play.core.Router$Routes$$anon$1.invocation(Router.scala:377)
    at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:56)
    at play.db.jpa.TransactionalAction$1.apply(TransactionalAction.java:20)
    at play.db.jpa.TransactionalAction$1.apply(TransactionalAction.java:18)
    at play.db.jpa.JPA.withTransactionAsync(JPA.java:177)
    at play.db.jpa.TransactionalAction.call(TransactionalAction.java:15)
    at play.core.j.JavaAction$$anon$3.apply(JavaAction.scala:91)
    at play.core.j.JavaAction$$anon$3.apply(JavaAction.scala:90)
    at play.core.j.FPromiseHelper$$anonfun$flatMap$1.apply(FPromiseHelper.scala:82)
    at play.core.j.FPromiseHelper$$anonfun$flatMap$1.apply(FPromiseHelper.scala:82)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:249)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
    at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:37)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

A: list = modelA.getList(parameter);

Your method getList from modelA class returns a built list. The way it builts the list can be anything. It can starts even in position 99.
So, you need to check/fix how the objects are being placed in the list in your modelA class.

A: It seems that the getList method returns a List implementation which violates the API (assuming List is java.util.List). The api for List.get() specifies that all List implementations should throw IndexOutOfBoundsException if index == list.size().
You could create a list of some specific type you choose (e.g. an ArrayList) and put the contents of the broken List in the list you created:
List<modelA> list= new ArrayList<modelA>(modelA.getList(parameter));

Then you should get a list of size 3 where zero-based indexing is used.

Optionally, you could check what the type of the broken List implementation is:
System.out.println(modelA.getList(parameter).getClass().getName());

And try to fix the implementation of the broken List class. But this might be risky if there is code elsewhere which relies on the 1-based indexing of this List implementation.


text:
Q: Send parent's reference to child component I want to send a parent's reference to a child component, hopefully with something like this:
<parent-component #parentReference>
  <child-component Xdirective="parentReference">
    anything this component contain but with a reference to parent.
  </child-componet>
</parent-component>

A: You can access a reference to a component using the exportAs declaration of a component.
@Component({
    ....
    exportAs: 'parentReference'
})
export class ParentComponent {}

@Component({...})
export class ChildComponent {
    @Input()
    public parent: ParentComponet;
}

You have to assign the exported value parentReference to a template value, and then pass that into an input parameter.
<parent-component #ref="parentReference">
   <child-component [parent]="ref">
      anything this component contain but with a reference to parent.
   </child-componet>
</parent-component>

You can also inject a parent component via the constructor, but this will not work if the child is inside a <ng-content> block.
@Component({...})
export class ParentComponent {}

@Component({...})
export class ChildComponent {
    constructor(parent: ParentComponent) {
       ...
    }
}

A: If your child has an unique parent (always is the the child of the same class of Component) you can use @Optional() @Host(), see stackblitz
export class HelloComponent implements OnInit  {
  @Input() name: string;
  constructor(@Optional() @Host() private parent:AppComponent){
  }
  ngOnInit()
  {
    console.log(this.parent.anotherVariable)
  }
}

But, if you can resolve your problem using @Input ot @Output it's better solution

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scalar Product of Two Vectors Equals Product of Lengths by cosine of angle between them I am trying to understand a proof for this that I found online.

Let A $=$ vector $A$, B $=$ vector $B$, and C $=$ vector $C$ and $C=A-B$.
By the Law of Cosines: $c^2 = a^2 + b^2-2ab \text{cos} \theta$
So $||C||^2=||C||\cdot ||C||$
$=(A-B) \cdot (A-B)$
$=A^2 - A\cdot B - B\cdot A +B^2$
Since vectors have the property that they commute, $A\cdot B = B\cdot A$.
$C^2= A^2+B^2-2AB$

How can we automatically assume that $\textbf{2AB = 2ABcos $\theta$}$?


text:
Q: Analytical solution of integral $x^{1+n}\exp(-x) \sin(x)$ $$\int\limits_0^\infty x^{1+n} \exp(-x) \sin(xy) \mathrm{d}x $$
for real $n, x, y$ and $n\ge-3$ has the following analytic solution according to mathematica:
$$(1 + y^2)^{\left(-1 - \frac{n}{2}\right)} \Gamma(2 + n) \sin((2 + n) \arctan(y))$$
I tried to do the integration by hand, but don't know how to do it when $1+n$ is not a positive integer (if it is one can do partial integration and gets a factorial instead of the gamma function).
Is there any way to do this?
Or does one need to solve for integer $n$ and can then generalize to non-integer $n$ by inserting the gamma function for factorials?
I thought about doing this in the Complex plane using the residue theorem, but there are no poles, so this doesn't seem to work.

A: The integral is the imaginary part of
$\displaystyle \int\limits_0^\infty x^{1+n} \exp(-(1-i y)x)\mathrm{d}x$,
which suggests the change of variables $z=(1-i y)x$. You can check that the change in the contour doesn't matter, and you end up with
$\displaystyle\frac{\Gamma(2+n)}{(1-iy)^{2+n}}$,
the imaginary part of which is your answer.


text:
Q: Using ionic nav-bar, google Maps object doesn't load Map object I'm working with ionic, angularJS and Google Maps V3 API js and when I try to use the bar-navigation between different views, the google map doesn't load properly.
I have an intro, that has a button to open the view containing the map object, and when I touch on the button everything loads fine except the map.
 app.controller('MapController', function($scope, $ionicLoading) {

    google.maps.event.addDomListener(window, 'load', function() {

        var mapOptions = {
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map'), mapOptions);

        navigator.geolocation.getCurrentPosition(function(pos) {
            map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
        });

        $scope.map = map;

        $scope.$watch('$viewContentLoaded', function() {
        //call it here
        var element = (document.getElementById('map'));
        var windowHeight = window.self.outerHeight;
        var finalHeight = windowHeight * 0.62;
        element.style.height = finalHeight+'px';
        });
    });
});

This code works fine if I put the view containing the map as the first view of my web application.
How can I load properly the map, or is there a way to preload all the views?


text:
Q: How do I use X-Forwarded-For header with SharePoint? The WFEs for our OnPrem SharePoint farm sit behind an F5 load balancer. As a result, client requestor IPs are not captured in the IIS logs as everything appears to come from the F5.
One way to get around this is to use the X-Forwarded-For header to transfer the original client IP address through to the IIS server. Unfortunately, IIS 7 doesn't support collecting this header natively.
So can I use the X-Forwarded-For header with SharePoint, and if so, how?
What tools and/or IIS plug-ins should I use?
What configuration changes do I need to make to the load balancer, IIS and/or SharePoint?
I'm looking for SP2010 answers in particular, but post any 2007 tips you may have too.

A: I've never tried this but the IIS team seem to have created a module to solve this issue.

*

*Client-ip not logged on application server when using ARR
Its not clear if it will work in conjunction with SharePoint but there it seems worth a try.

A: From SharePoint Side :
I just study the case and I concluded that it is not possible to take into account the header for use in the OOTB Usage Reports (and Web Analytics). We have to "modify" the Microsoft.SharePoint.dll to achieve this goal: a job for the SharePoint Team.
If you still want to exploit this header you have to develop your own HTTP Module combined with a custom usage provider to generate ".usage" files and import them in the logging database.
From IIS Side :
Perhaps there is a possibility to alter the HttpRequest before the Http Module deployed by SharePoint (« Microsoft.SharePoint.ApplicationRuntime.SPRequestModule ») process it (not sure the request could be altered....)

A: Steve P is correct. The ARR Helper module that he linked to does the variable replace prior to the initialization of the SharePoint request. We have been using it on our SharePoint 2010 farm for several months and see the original requestor address in both the OOB SharePoint Analytics and the IIS Logs.
Application Request Routing 2.5 is supposed to include the same feature that the helper module added to v1 with additional configuration options but I have not tested it on my farm as the helper did all I needed it to.
-Robert Colbert


text:
Q: What does "legal vehicles" mean here? I used this link but i didn't get the meaning of "vehicle" in this sentence.
https://www.oxfordlearnersdictionaries.com/definition/english/vehicle?q=vehicle

The checks consisted of finding out whether one or more subsidiaries of the corporate group is listed on the Financial Secrecy Index (a system that ranks jurisdictions according to the secrecy of their offshore activities); seeing whether the group has participated in any financial scandals; looking to see whether the group has published its most recent accounts; asking whether the group has published information on who the beneficial owners are of all its legal vehicles; and requesting to see whether the group has committed to employee protection.

Source: https://www.cnbc.com/2020/05/19/coronavirus-eu-countries-deny-bailouts-to-firms-linked-to-tax-havens.html


text:
Q: Errors in python code when running in terminal import csv
import random
import math

def loadCsv(filename):
    lines = csv.reader(open(filename, "rb"))
    dataset = list(lines)
    for i in range(len(dataset)):
        dataset[i] = [float(x) for x in dataset[i]]
    return dataset

def splitDataset(dataset, splitRatio):
    trainSize = int(len(dataset) * splitRatio)
    trainSet = []
    copy = list(dataset)
    while len(trainSet) < trainSize:
        index = random.randrange(len(copy))
        trainSet.append(copy.pop(index))
    return [trainSet, copy]

def separateByClass(dataset):
    separated = {}
    for i in range(len(dataset)):
        vector = dataset[i]
        if (vector[-1] not in separated):
            separated[vector[-1]] = []
        separated[vector[-1]].append(vector)
    return separated

def mean(numbers):
    return sum(numbers)/float(len(numbers))

def stdev(numbers):
    avg = mean(numbers)
    variance = sum([pow(x-avg,2) for x in numbers])/float(len(numbers)-1)
    return math.sqrt(variance)

def summarize(dataset):
    summaries = [(mean(attribute), stdev(attribute)) for attribute in
    zip(*dataset)]
    del summaries[-1]
    return summaries

def summarizeByClass(dataset):
    separated = separateByClass(dataset)
    summaries = {}
    for classValue, instances in separated.iteritems():
        summaries[classValue] = summarize(instances)
    return summaries

def calculateProbability(x, mean, stdev):
    exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
    return (1 / (math.sqrt(2*math.pi) * stdev)) * exponent

def calculateClassProbabilities(summaries, inputVector):
    probabilities = {}
    for classValue, classSummaries in summaries.iteritems():
        probabilities[classValue] = 1
        for i in range(len(classSummaries)):
            mean, stdev = classSummaries[i]
            x = inputVector[i]
            probabilities[classValue] *= calculateProbability(x, mean, stdev)
    return probabilities

def predict(summaries, inputVector):
    probabilities = calculateClassProbabilities(summaries, inputVector)
    bestLabel, bestProb = None, -1
    for classValue, probability in probabilities.iteritems():
        if bestLabel is None or probability > bestProb:
            bestProb = probability
            bestLabel = classValue
    return bestLabel

def getPredictions(summaries, testSet):
    predictions = []
    for i in range(len(testSet)):
        result = predict(summaries, testSet[i])
        predictions.append(result)
    return predictions

def getAccuracy(testSet, predictions):
    correct = 0
    for i in range(len(testSet)):
        if testSet[i][-1] == predictions[i]:
            correct += 1
    return (correct/float(len(testSet))) * 100.0

def main():
    filename = 'processed.cleveland.data.csv'
    splitRatio = 0.67
    dataset = loadCsv(filename)
    trainingSet, testSet = splitDataset(dataset, splitRatio)
    print('Split {0} rows into train={1} and test={2} rows').format(len(dataset), len(trainingSet), len(testSet))
    summaries = summarizeByClass(trainingSet)
    predictions = getPredictions(summaries, testSet)
    accuracy = getAccuracy(testSet, predictions)
    print('Accuracy: {0}%').format(accuracy)

main()

The code above is a naive Bayes machine learning python script. I am trying to use the code on a dataset that is stored in processed.cleveland.data.csv. However, I keep getting the following errors:
Traceback (most recent call last):
File "./naivebayespython.py", line 101, in <module>
main()
File "./naivebayespython.py", line 91, in main
dataset = loadCsv(filename)
File "./naivebayespython.py", line 10, in loadCsv
dataset[i] = [float(x) for x in dataset[i]]
ValueError: could not convert string to float: ?

Could somebody please tell me what I am doing wrong and suggest how to fix this? I am relatively new to Python, so an explanation would also be helpful. Thanks!

A: You can catch conversion errors with try: and  except:
but aware of what is conversable to float - see this answer for an exhaustive list: https://stackoverflow.com/a/20929881/7505395
Modification to capture wrong conversion
def checkIfFloatable(something): # change the name ;)
    try:
        if float(something):
            return True
    except:
        return False

def loadCsv(filename):
    lines = csv.reader(open(filename, "rb"))
    dataset = list(lines)
    for i in range(len(dataset)):
        dataset[i] = [float(x) for x in dataset[i] if checkIfFloatable(x)] # else None
    return dataset


text:
Q: Getting colored results when using a pipe from grep to less I use the --colour option of grep a lot, but I often use less as well. How can I pipe grep results to less and still preserve the coloring. (Or is that possible?)
grep "search-string" -R * --colour | less

EDIT:
I'm looking for a direct solution or anything equivalent to this.

A: You can put this in your .bashrc file:
export GREP_OPTIONS="--color=always"

or create an alias like this:
alias grepc="grep --color=always"

and you will need to use the -R option for less, as pointed out by therefromhere

A: When you simply run grep --color it implies grep --color=auto which detects whether the output is a terminal and if so enables colors. However, when it detects a pipe it disables coloring. The following command:
grep --color=always -R "search string" * | less

Will always enable coloring and override the automatic detection, and you will get the color highlighting in less.
EDIT: Although using just less works for me, perhaps older version require the -R flag to handle colors, as therefromhere suggested.

A: Don't alias "grep", better to alias "less" which is never used by shells. In your .bashrc just put:  alias less="less -r".

A: In case like this, I prefer to actually create small sh files and put them on /usr/local/bin.
I usually use grep in the recursive way on the pwd, so thats my personal script:
#!/bin/sh
grep --color=always -r "$@" . | less -R

And then I've just copied it as /usr/local/bin/g (yes, I use it a lot)

A: You can run
grep --color=always -R "search string" * | less -r

with the -r flag after less, in order for this to work.


text:
Q: Importing .dot file as subgraph Is there -- either via a language feature or via a preporcessor -- a possiblity to include external .dot files as subgraphs into another one?
I am working on a relatively big graph, though manually maintained, not generated.
It would be convenient to be able to define some
subgraph01.dot:
digraph subgraph01 {
 /* lot of nodes and edges */
}

subgraph02.dot:
digraph subgraph02 {
 /* lot of nodes and edges */
}

And then do something like graph.dot:
digraph BigGraph {
    import subgraph01;
    import subgraph02;
    A -> subgraph01.Node1
    A -> subgraph02.Node1
    subgraph01.Node10 -> subgraph02.Node99
    /* etc. */
}

Is there a way?

A: Two options immediately occur to me. One would be to use a macro processor, e.g. m4. Given BigGraph.m4:
digraph BigGraph {
    define(`digraph',`subgraph')
    include(`subgraph01.dot')
    include(`subgraph02.dot')
    A -> subgraph01.Node1
    A -> subgraph02.Node1
    subgraph.Node10 -> subgraph.Node99
    /* etc. */
}

... running:
$ m4 BigGraph.m4

... produces:
digraph BigGraph {
    subgraph subgraph01 {
 /* lot of nodes and edges */
}

    subgraph subgraph02 {
 /* lot of nodes and edges */
}

    A -> subgraph01.Node1
    A -> subgraph02.Node1
    subgraph.Node10 -> subgraph.Node99
    /* etc. */
}

Another option that might allow a more sophisticated approach is to use
gvpr from GraphViz. I tried to create an example to do this with gvpr, however and I was unsuccessful, so I suggest only trying it if a graph-aware approach is required rather than the simple approach using m4.


text:
Q: I need to change the output of a button click times I know there's a way to do this. For whatever reason it's slipping and I can't figure this out... What I'm trying to do is get the text when you click 15 minutes button, to be green; when you click 60 minutes have it be yellow.

document.addEventListener('DOMContentLoaded', function() {
  let countdown;
  let overtime;
  const display = document.querySelector(".display");
  const timeDisplay = document.querySelector(".display-time");
  const hourDisplay = document.querySelector(".display-hour");
  const buttons = document.querySelectorAll("[data-time]");

  function time(seconds) {
    // Clear any existing timers
    timeDisplay.style.color = "white";
    clearInterval(countdown);
    clearInterval(overtime);
    const now = Date.now();
    const then = now + seconds * 1000;
    displayTimeLeft(seconds);
    displayEndHour(then);
    countdown = setInterval(() => {
      // Time left in seconds
      const secondsLeft = Math.round((then - Date.now()) / 1000);
      // Check if it should stop and go over
      if (secondsLeft <= 0) {
        timeDisplay.style.color = "white";
        hourDisplay.style.color = "white";
        display.style.backgroundColor = "black";
      }
      if (secondsLeft <= 0) {
        clearInterval(countdown);
        displayTimeOver();
        return;
      }
      // Display
      displayTimeLeft(secondsLeft);
      if (secondsLeft < 10) {
        timeDisplay.style.color = "red";
      }
    }, 1000);
  }

  function displayTimeOver() {
    let minutesOver = 0;
    let secondsOver = 0;
    timeDisplay.textContent = "0:00";
    overtime = setInterval(() => {
      secondsOver++;
      if (secondsOver === 60) {
        secondsOver = 0;
        minutesOver++;
      }
      console.log({
        minutesOver,
        secondsOver
      });
      let display = `-${minutesOver}:${((secondsOver < 10) ? "0" : "")}${secondsOver}`
      timeDisplay.textContent = display;
    }, 1000)
  }

  function displayTimeLeft(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainderSeconds = seconds % 60;
    console.log({
      minutes,
      remainderSeconds
    });
    let display = `${minutes}:${((remainderSeconds < 10 && remainderSeconds >= 0) ? "0" : "")}${remainderSeconds}`;
    document.title = display;
    timeDisplay.textContent = display;
    if (remainderSeconds <= 0) {
      timeDisplay.style.color = "darkorange";
      hourDisplay.style.color = "darkorange";
    }
  }

  function displayEndHour(timestamp) {
    const end = new Date(timestamp);
    const hour = end.getHours();
    const minutes = end.getMinutes();
    hourDisplay.textContent = `Break/Lunch End Time ${hour}:${minutes < 10 ? "0" : ""}${minutes}`;
  }

  function startTimer() {
    const seconds = parseInt(this.dataset.time);
    time(seconds);
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  }
  buttons.forEach(button => button.addEventListener("click", startTimer));
  document.customForm.addEventListener("submit", function(e) {
    e.preventDefault();
    const minutes = this.minutes.value;
    time(minutes * 60);
    this.reset();
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  })
});
p {
  background-color: black;
  border: darkorange;
  border-width: thick;
  border-style: solid;
  color: darkorange;
  padding: 10px10px;
  text-align: center;
  font-size: 50px;
  margin: 4px2px;
}
un {
  background-color: black;
  color: red;
  padding: 10px10px;
  text-align: center;
  font-size: 20px;
  margin: 4px2px;
}
body {
  background-color: black;
}

.container {
  background-color: black;
}

.choose-time {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 50px;
  font-color: black;
}

.timer {
  -webkit-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -moz-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  background-color: darkorange;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: black;
  text-align: center;
  font-size: 50px;
}

.timerbutton15 {
  background-color: black;
  border: lime;
  border-width: medium;
  border-style: solid;
  color: lime;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timerbutton60 {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timer-form {
  background-color: black;
  border: black;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  padding: 10px20px;
  cursor: pointer;
}

.timer-input {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  cursor: pointer;
}

.display {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
  cursor: pointer;
}

.display-time {
  background-color: black;
  border: darkorange;
  border-width: thin;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
}

Break/Lunch Timer

<display>

</display>

<un>Use Note: Please click either button for break or lunch timing. If you need a customer time, enter the time in minutes in the "Enter Custom Time" field and press return/enter. This will then run a timer for the time input. (ex. Entering 5 would run a 5 minute timer.)</un>

  <input type="button" button name="timerbutton15" class="timerbutton15 timer" value="15 Minutes (Break)" data-time="900"
  onclick="document.customForm.addEventListener("submit", function(e)">
  <input type="button" button name="timerbutton60" class="timerbutton60 timer" value="60 Minutes (Lunch)" data-time="3600"
  onclick="document.customForm.addEventListener("submit", function(e)">
    <form name="customForm" id="custom" class="timer-form">
      <input type="number" name="minutes" color="black" placeholder="Enter Custom Time" min="00.00" class="timer-input timer">
    </form>

As you can see I've got this figured out mostly, and I can change the text output color of a button. I just can't get it to sufficiently change both text outputs differently.


text:
Q: Android - AlarmManager recovery Thanks to TasKiller I have reliable way to shutdown updates coming to my AppWidget from the AlarmManager!
Now, sarcasm aside, how do I recover from such event? So far I only see that the Alerts are resurrected only after rebooting the phone.
I can stick recovery code into few places such as various Activity#onCreate that belong to my app and my widget but is there a better way?
Also what if the alerts are OK - is there a way to detect that and not run AlarmManager#setRepeating?
Or is there a harm to run it multiple times?

A:
Now, sarcasm aside, how do I recover
  from such event?

I have heard that single-malt Scotch helps.

So far I only see that the Alerts are
  resurrected only after rebooting the
  phone.

That is only if you are hooking the BOOT_COMPLETED broadcast Intent and re-establishing the alarms.
Task killers are remarkably thorough, but they cannot stop a BroadcastReceiver from receiving system broadcasts, like BOOT_COMPLETED. You are welcome to find some other broadcast that you would like to receive to help regain control and re-establish your alarms.

Also what if the alerts are OK - is
  there a way to detect that and not run
  AlarmManager#setRepeating? Or is there
  a harm to run it multiple times?

You can cancel() an existing alarm. So, if you are concerned about possible duplicates, cancel() the current alarm (which hopefully fails quietly if the alarm does not exist), then set the alarm.


text:
Q: How to add text before WordPress menu item href I'm working on a custom project for a client and having an issue adding in data-scroll before the links in WordPress. I want the output to be .
Data-scroll is what I am looking to add in just after the a, here href ="#"
Hope someone can help me out.

A: You'll want to use the following filter:
nav_menu_link_attributes
Example:
function filter_nav_menu_link_attributes($atts, $item, $args) {

    if ( isset($args->theme_location) && $args->theme_location === 'my-menu-location' ) {
        $atts['data-scroll'] = 'some-value';
    }

    return $atts;

}

add_filter('nav_menu_link_attributes', 'filter_nav_menu_link_attributes', 10, 3);

Use $item and $args to isolate and act on the specific menu or specific menu item in which you wish to add your attribute to.
Read more here: nav_menu_link_attributes

A: A Custom Walker would be the best way to add anything anywhere to your wp_nav_menu
You hav to keep the following in your function.php
            <?php
        class MV_Cleaner_Walker_Nav_Menu extends Walker {
            var $tree_type = array( 'post_type', 'taxonomy', 'custom' );
            var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );
            function start_lvl(&$output, $depth) {
                $indent = str_repeat("\t", $depth);
                $output .= "\n$indent
\n";
            }
            function end_lvl(&$output, $depth) {
                $indent = str_repeat("\t", $depth);
                $output .= "$indent
\n";
            }
            function start_el(&$output, $item, $depth, $args) {
                global $wp_query;
                $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
                $class_names = $value = '';
                $classes = empty( $item->classes ) ? array() : (array) $item->classes;
                $classes = in_array( 'current-menu-item', $classes ) ? array( 'current-menu-item' ) : array();
                $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
                $class_names = strlen( trim( $class_names ) ) > 0 ? ' class="' . esc_attr( $class_names ) . '"' : '';
                $id = apply_filters( 'nav_menu_item_id', '', $item, $args );
                $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
                $output .= $indent . '
';
                $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
                $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
                $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
                $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
                $item_output = $args->before;
                $item_output .= '';
                $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
                $item_output .= '';
                $item_output .= $args->after;
                $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
            }
            function end_el(&$output, $item, $depth) {
                $output .= "
\n";
            }
        }
        ?>

and then you can call the menu by
<?php wp_nav_menu( array( 'menu'=>'Footer Menu 1',
menu_class => 'menu vertical footer-menu',
'walker' => new MV_Cleaner_Walker_Nav_Menu() ) ); ?>

A: You need to add this code on functions.php file of current theme.
add_action( 'wp_footer', 'add_attr_nav_menu_link' );
function add_attr_nav_menu_link(){
    ?>

    <?php

}

Let me know if you have any query!!!!


text:
Q: Creating fully working alarm clock Hello I would like to create a basic but fully working alarm clock application just to increase my android programming skills but it has too many bug I have to rewrite it from scratch.

A pending intent that fires when the alarm is triggered. When you set a second alarm that uses the same pending intent, it replaces the original alarm.

What I did is whenever user creates new alarm i add new alarm to alarm SQLite table and even if the alarm repeats every day in week I use the lastInsertId of that alarm as unique id for my pending intent and it means 7 pending intens has the same ids...

A trigger time. If the trigger time you specify is in the past, the alarm triggers immediately.

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.DAY_OF_WEEK,1);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY * 7, alarmIntent);

Even if I hardcode the values it always triggers immediately, since the Monday has passed what do I need to do?


text:
Q: Vimeo video not working on mobile site hello I have embedded vimeo video in my website. It is showing accurately when view the website on desktop but it is not showing up on mobile. Here is the link of the website
http://bit.ly/1KtFBbq
Please any one has the idea whats wrong here.?

A: You have to be a pro member for vimeo to generate mobile versions automatically

A: Seems like you are using flash to play the video. This is not supported in many browsers and mobile. Better user HTML  tags.
<video id="my_video" controls class="pull-left hideit">
     <source src="thesource.mp4" type="video/mp4" />
</video>

They are best supported. Cheers!


text:
Q: Using Scheme interpreter in SublimeRepl package in sublime text 3 I've been up all night trying to figure out how to use the interpreter for SublimeREPL for Scheme in ST3. I read here that when you download the package for sublimeREPL it doesn't actually include the interpretor. So I tried moving my version of MIT-scheme into
/Users/Myname/Library/Application Support/Sublime Text 3/Packages/SublimeREPL/config/Scheme
but when I do: Tools --> SublimeREPL --> Scheme --> Scheme
I get:
Error loading syntax file "Packages/sublime-scheme-syntax/Scheme.tmLanguage": Unable to open Packages/sublime-scheme-syntax/Scheme.tmLanguage
has anyone had any experience being able to set up the interpretor for scheme in SublimeREPL in sublime text 3? I am using os x 10.9.2
Thanks!!!!!!!!

A: I have the same problem. Though I am using Sublime Text 2, my solution might be applicable to you.
The error message refers to the wrong path or directory to the Scheme.tmLanguage file.
In my case, this file is placed at "Packages/Scheme" here, not at the "Packages/sublime-scheme-syntax" folder. I just edit Main.sublime-menu file, change the "syntax": "Packages/sublime-scheme-syntax/Scheme.tmLanguage" line to the correct path and it works!
I found my solution reading this post at SublimeREPL Github site. Hopefully this also works for you.

A: I have the similar problem and this is how I fix for Sublime Text 2:

*

*install the package "Scheme" through package control.

*install the package "SublimeREPL"

*install a SCM implementation of Scheme

*open Preferences -> Browse Packages ->
SublimeREPL -> config -> Scheme -> Main.sublime-menu. edit the
section with the "id": "repl_scheme"

args:
"windows": ["scm", "-f", "$file_basename"]},
"syntax": "Packages/Scheme/Scheme.tmLanguage"

Thanks to: Sublime Text 2 with MIT Scheme, How to configure SublimeREPL for mit-scheme? and @Yenkaku's answer


text:
Q: Blazor custom component I want to build a custom component where i have the option to "leave out" part of the code.
Say i have this simpleCard component:

@cardTitle

@cardText

         <button> class="simpleCard-button">Click me</button>

`@code `{
    [Parameter]
    public string imageUrl { get; set; }
    [Parameter]
    public string cardTitle { get; set; }
    [Parameter]
    public string cardText { get; set; }
}

When this simplecard component is called, is there a way to "ignore" the button class? Say i want to create one card with button and one without?

A: Add a parameter in your component for a boolean value:
[Parameter]
public bool ButtonVisible { get; set; }

Then in your markup:
@if(ButtonVisible)
{

   <button> class="simpleCard-button">Click me</button>

}

And when you call the component, set the value to true or false as needed:
.....

<Component ButtonVisible="True" .... />

...

The button will only render if you have the value set to True.


text:
Q: Which number appeared once?
Given a list of 2n-1 numbers: all between 1 to n, all but one occur twice. Determine the number that occurs only once. Multiple ways preferred.

I think the problem is at fault, how can you determine which number without knowing the list of numbers?

A: *

*[O(1) space, O(n) time]: Just take the XOR of all the numbers. Since all the numbers occur two times except one, XOR of those numbers will be zero and the single occurring number will be the result.

*[O(1) space, O(n) time]: As said by user3386109  in comments, we can sum all the given numbers and compare that to the sum of numbers in the range [1, n] which will be n*(n+1) (since all numbers are supposed to occur twice). The difference of the two numbers is the answer.

*[O(n) space, O(n) time]: Create an array of size n and keep the count of all the elements in the array at their corresponding positions. At the end, traverse the array, and find the number whose count is only 1.


text:
Q: MongoDB reverse regex -> db.col.find({$where: "\"my regex\".match(this.regex)"}) if this.regex is array of regex strings I have a similar problem like Giovanni in this post: MongoDB reverse regex
Unlike his request I have an array of regex strings in my db which I would like to query the same way. The solution provided for Giovanni works fine on a field with type string, but isn't working on an array of strings.
The regex array inside my db has the following form:
"regex": [
       "test_.*?_reg",
       ".*?_hello_world"
],

test_123_reg should match, test-123-reg should not match. Same for the second and every other entry. "regex" is one field inside one Document.
This is the right solution for string type:
$where: "\"test_123_reg\".match(this.regex)"

Manny thanks in advance for your help.


text:
Q: Non-vanishing of sub gradient near optimal solution Consider the non-smooth optimization problem
  \begin{equation}
      \min_{x \in \mathbb{R}^n}    f(x).
\end{equation}
To solve the above problem, I am suing subgradient descent
\begin{equation}
       x_{t+1} = x_t - \eta\partial f(x_t)
\end{equation}
My question is: why subgradient $\partial f(x)$ is non-vanishing in the nbd of the optimal solution if learning rate $\eta$ is fixed?

A: Short answer: No. I general, you wouldn't expect the subgradient to vanish in the neighborhood of a minimum point $x^*$. All you can say is 0∈∂f($x^*$).
Indeed, consider the abolute-value function f:x↦|x|. A simple calculation reveals that ∂f(x)=sign(x) if x≠0 and ∂f(0)=[−1,1]. Also, we know (from purely algebraic considerations) that f attains a global minimum of 0 at the origin 0. However, no amount of subgradient descent will take you there (provably!) as @littleO already said. In particular, ∂f will never vanish no matter how close you come within 0 without hitting it.


text:
Q: System.IndexOutOfRangeException in function for findinding words in text with IndexOf I got function for finding word in text with indexof its returning list of objects with fields word and quantity,i want to use that function for different text and words to so im creating task and getting IndexOutOfRange on that line :
var r = Check_text(tnw.text[i], word);

For more understand thats my function:
    public static List<wordsinf> Check_text(string text,string[] words)
    {
        List<wordsinf> result = new List<wordsinf>();
        var pos = 0;
        var quantity = 0;
        foreach (string wf in words)
        {
            pos = 0;
            quantity = 0;
            while (true)
            {
                var foundPos = text.IndexOf(wf, pos);
                if (foundPos == -1)
                {
                    break;
                }
                pos = foundPos + 1;
                if (foundPos >= 0)
                {
                    quantity++;
                }
            }
            result.Add(new wordsinf(wf, quantity));
        }
        return result;
    }

thats example of inputs:
  -     word    {string[2]} string[]
            [0] "asd"   string
            [1] "qwe"   string
    -       tnw.text    {string[2]} string[]
            [0] "asd qwe ssd www "  string
            [1] "asd asd qwe sss "  string

Can anyone tell me solution for this problem?and what am i doing wrong there.
Also there is part with tasks:
 var numtasks = tnw.text.Length;
        AnalyzeObj[] analyzeobjs = new AnalyzeObj[numtasks];
        var word = tnw.words.Split(',');
        Task[] tasks = new Task[numtasks];
        Console.WriteLine(word);
        Console.WriteLine(tnw.text);
       for (var i = 0; i < numtasks; i++)
        {
            tasks[i] = new Task(() => {
                var r = Check_text(tnw.text[i], word);
                analyzeobjs[i].text = tnw.text[i];
                analyzeobjs[i].WordInfos=r;
                analyzeobjs[i].id=Guid.NewGuid();
                analyzeobjs[i].FindWords = word;
            });
            tasks[i].Start();
         }
        Task.WaitAll(tasks);

A: The problem is that the Lambda Expression will not copy the value of the parameter but just use that exact variable instead.
So after your Loop is over, i will be larger then the array length and therefor throw an exception.
To solve the problem, do the following in the for loop instead:
tasks[i] = new Task(new Action<object>((val) => {
            var c = (int)((object[])val)[1];
            var t = ((object[])val)[0].ToString();
            var r = Check_text(t, word); //Use the parameter val instead
            analyzeobjs[c].text = t; //Use the parameter val instead
            analyzeobjs[c].WordInfos=r;
            analyzeobjs[c].id=Guid.NewGuid();
            analyzeobjs[c].FindWords = word;
        }), new object[2] { tnw.text[i], i });
tasks[i].Start();

A:    for (var i = 0; i < numtasks; i++)
        {
            var i1 = i;
            tasks[i] = new Task(() =>
            {
                var item = new AnalyzeObj();
                var r = Check_text(tnw.text[i1], word);
                item.text = tnw.text[i1];
                item.WordInfos = r;
                item.id = Guid.NewGuid();
                item.FindWords = word;
                analyzeobjs.Add(item);
            });
            tasks[i1].Start();
        }


text:
Q: I do not have outlook installed in my Window Machine. How to send mail using powershell? I wrote one script using powershell for my work and I want to send the output every time the script run. Problem is that I do not have Outlook installed on my Window machine. Is there a way to send email using powershell without having outlook installed on Window Machine ? I am using powershell v2 /v3 .

A: you can use the send-mailmessage commandlet to send emails from a powershell script. No need for a dedicated mail client.
Technet Send-MailMessage


text:
Q: Seating in round table - arrangements with b next to a or c 8 people sit around a round table. Arrangements are considered the same if the same student is to the right/left. So, in total there are $7! = 5040$ ways to seat.
Part 1: How many arrangements are there with B sitting next to both A and C?

*

*For this one, I think that B would have to be in the middle, and there are 2 ways to place B between A and C. So, $2!\cdot5! =$ 240 ways.

Part 2: How many arrangements are there with B sitting next to A or C?

*

*For this one, I was thinking about subtracting from the opposite: B will sit next to anyone other than A/C.

*So, $7! - 6 \cdot 1\cdot 4\cdot 5!=$ 2160 ways.

Can anyone tell my approach looks good / verify my answers?

A: Your solution to part $1$ is correct.
When counting the arrangements where $B$ is next to neither $A$ nor $C$, there are...

*

*$5$ choices for the person sitting on $B$'s left; anyone but $A$, $B$ or $C$. [You had $6$ for this number, which was your mistake.]

*$4$ choices for the person sitting on $B$'s right; anyone but $A$, $B$, $C$, or the person sitting on $B$'s right.

*$5!$ ways to choose everyone else; $5$ choices for the person $2$ places to the right of $B$, $4$ choices for the person $3$ places to the right, etc.
Finally, the answer is $\boxed{7!-5\cdot 4\cdot 5!}$.


text:
Q: KML file not working? If I double Click on my KML file it does what it should and start GE and does as expected.  When I put it in to my HTML file it will not work.  I then put it into http://earth-api-samples.googlecode.com/svn/trunk/examples/kml-fetch-interactive.html  and it doesn't work from there either.  This is the link to the KLM https://dl.dropbox.com/u/61240296/myPoints.Kml.  It is bascially a direct copy of a Google Sample.  Are KML files dependent on other KML files?  One thing I have notice is there are no roads so it appears as though non of the KML files are open or active.
<?xml version="1.0" encoding="UTF-8"?>

xmlns:gx="http://www.google.com/kml/ext/2.2"

xmlns:kml="http://www.opengis.net/kml/2.2"

xmlns:atom="http://www.w3.org/2005/Atom">

  <Camera>

     <longitude>-93.2539393007755</longitude>

     <latitude>45.5456585437059</latitude>

     <altitude>139.629438</altitude>

     <heading>-70.0</heading>

     <tilt>75</tilt>

  </Camera>

  <Placemark>

     <name>Placemark from KML file</name>

     <Point>

        <coordinates>-93.2539393007755, 45.5456585437059</coordinates>

     </Point>

  </Placemark>

  </Document>

  </kml>

A: Your KML file is fine. It also works perfectly in the example page you link to. The problem is the sample page does not change the view after loading your kml file. It doesn't even try to.
Edit this function
function finishFetchKml(kmlObject) {
  // check if the KML was fetched properly
  if (kmlObject) {
    // add the fetched KML to Earth
    currentKmlObject = kmlObject;
    ge.getFeatures().appendChild(currentKmlObject);
  } else {
    // wrap alerts in API callbacks and event handlers
    // in a setTimeout to prevent deadlock in some browsers
    setTimeout(function() {
      alert('Bad or null KML.');
    }, 0);
  }
}

to look like this
function finishFetchKml(kmlObject) {
  // check if the KML was fetched properly
  if (kmlObject) {
    // add the fetched KML to Earth
    currentKmlObject = kmlObject;
    ge.getFeatures().appendChild(currentKmlObject);

    ///////////////////////////////////////////////
    // this is what you need to add
    var myView = currentKmlObject.getAbstractView();
            ge.getView().setAbstractView(myView);
    //////////////////////////////////////////////

  } else {
    // wrap alerts in API callbacks and event handlers
    // in a setTimeout to prevent deadlock in some browsers
    setTimeout(function() {
      alert('Bad or null KML.');
    }, 0);
  }
}

Then you need to decide if you want to assign that <Camera> view to the <Placemark> or the <Document>
and in case you didn't realise, your <Camera> view does NOT look at the <Placemark> it looks at the horizon from a spot directly above the <Placemark>

A: If you are trying to load a well formed KML file and the file doesn't load properly you should see the headers of the web server using the developer tools of chrome, firebug or similar.
If you are using apache as your webserver you should add to your httpd.conf:
AddType application/vnd.google-earth.kml+xml .kml
AddType application/vnd.google-earth.kmz .kmz


text:
Q: How to prove the binomial coefficient identity $\binom{n}{c}+ \binom{n}{c+1}= \binom{n+1}{c+1}$ by induction?
$$\binom{n}{c}+ \binom{n}{c+1}= \binom{n+1}{c+1}$$

How can I prove using induction for all values of $n$ and $c$?
I have no idea how to start it. Please help!

A: HINT:
Double Induction!
Fix n, and show true for c (one can say it's true for all c, noting that for c 'too large' the equation reads $0 + 0 = 0$). Then fix c, and show true for n. So it's like two induction proofs, and it is way overkill for this problem.

A: $\dbinom{n}{c}$ is the number of size-$c$ subsets of a size-$n$ set $S$.  Suppose you have a list of all of them.  Also make a list of all size-$(c+1)$ subsets of your size-$n$ set: there are $\dbinom{n}{c+1}$ of them.  Now let $x$ be something that is not a member of $S$, so that $S\cup\{x\}$ is a size-$(n+1)$ set.  To each size-$c$ subset in the first list, add $x$ as a new member, getting a size-$(c+1)$ subset, not of the original size-$n$ set, but of the larger set $S\cup\{x\}$.  You now have two lists:

*

*One list of size-$(c+1)$ subsets of $S\cup \{x\}$, each having $x$ as a member.  There are $\dbinom{n}{c}$ of these.

*One list of size-$(c+1)$ subsets of $S\cup\{x\}$, each not having $x$ as a member.  There are $\dbinom{n}{c+1}$ of these.

The union of those two lists contains $\dbinom{n}{c}+\dbinom{n}{c+1}$ members.  But the union of those two lists is also a list of all size-$(c+1)$ subsets of the size-$(n+1)$ set $S\cup\{x\}$.  Therefore $\dbinom{n}{c}+\dbinom{n}{c+1}=\dbinom{n+1}{c+1}$.


text:
Q: Problems with JQuery Mobile multiple pages template I am stuck with a problem using JQuery mobile and multiple pages: from the #first page I go to the #second, there I have a select with differents options and I have to update the #second page according the selection…so far no problem and it seems it works properly, but there is a rare behavior that I can't avoid any way: if I go forward and backward between the two pages, when I change the selection in the #second page the stuff I have to do is repeated as times as times I went backwards to the #first page.
Try this jsfiddle here :

*

*Go to the #second page

*Change option: one alert pops up

*Go back to the #first page

*Go again to the #second page

*Change again option: two alerts pops up !!!

*And so on…

<!DOCTYPE html>
   <title>Page Title</title>

   <link type="text/css" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" rel="stylesheet" />

Page Title1

Page content goes here.

            Go to second page

Page Footer1

Page Title2

                <select name="listtemp" id="listtemp" data-native-menu="false">
                <option value ='1'>option 1</option>
                <option value ='2'>option 2</option>
                <option value ='3'>option 3</option>
        </select>

Page Footer2

JS
     $(document).on('pagebeforeshow', '#second', function(){
       $('#listtemp').change(function() {
         alert('change option');
         //Do my stuff here when changing option
         //This code is done as times as times I go back first page…
       });
     });

A: Of course it would have this behavior since you have added the event inside the pagebeforeshow event. Which means each time the page is shown, the event is set.
You need to keep in mind that all jQuery event functions don't set but add the event. Hence you can replace $(document).on('pagebeforeshow', '#second' part with $(document).ready(


text:
Q: Custom content animations in UIStoryboardSegue I have been writing a mini framework for animating custom segues in iOS. It works well in iOS 7, but as soon as I started testing in iOS 8 all hell broke lose.
The reason I'm doing this is that I want to animate the view's content, not the frame. So far I think all segue animations I've seen animate the frame, like flipping, curling, and so on. Instead, I want to animate the constraints in the view. That is, buttons up, down, to the left, etc.
I did it by creating a custom segue class, HySegue, which polls the view controllers for presenting and dismissing animations, if they conform to given protocols. So far so good.
I now need to run the animations, but the problem is where. Here's what I'm doing:
    UIView * sourceView = sourceViewController.view;
    UIView * destinationView = viewControllerToPresent.view;

    // Force the source view to layout
    [sourceView addSubview:destinationView];
    [sourceView layoutIfNeeded];

So my idea is to add the destination view as a subview of the source view, run the animation, revert the previous changes, and finally present the destination view controller. Here it is:
    UIViewController * parentViewController = viewControllerToDismiss.parentViewController;
    UIView * destinationView = destinationViewController.view;

    // Break the view hierarchy that was setup earlier
    [destinationView removeFromSuperview];

    // When presenting in a UINavigationController stack, push the destination view controller
    if ([parentViewController isKindOfClass:[UINavigationController class]]) {

        [(UINavigationController *)parentViewController pushViewController:destinationViewController
                                                                  animated:NO];
    }

    // Otherwise use the standard method
    else {

        // Present the destination view controller
        [viewControllerToDismiss presentViewController:destinationViewController
                                              animated:NO
                                            completion:nil];

        [viewControllerToDismiss willMoveToParentViewController:nil];
        [viewControllerToDismiss.view removeFromSuperview];
        [viewControllerToDismiss removeFromParentViewController];
        [viewControllerToDismiss didMoveToParentViewController:nil];
    }

Again, this works well in iOS 7, but in iOS 8 I get:
Unbalanced calls to begin/end appearance transitions for <HyRegistrationNavigationController: 0x7bf540c0>

So it seems I'm trying to display a view controller before the previous one finishes displaying. How can I solve this? Ideally, there would a third view and view controller involved, which would serve as the container for the transition, but I can live without it.


text:
Q: Dice game, get close to $6$
You have been chosen to play a game involving a 6-sided die. You get
  to roll the die once, see the result, and then may choose to either
  stop or roll again. Your payoff is the sum of your rolls, unless this
  sum is (strictly) greater than 6. If you go over $6$, you get $0$. What's the best strategy?

I tried to set up equations with expected value. I think that the best strategy is to roll until you get at least some value, call it $x$. But I have not been able to make too much progress. Can someone please help me?

A: Suppose $f(x,t)$ is your expected return if so far you have rolled $x$ and you have a threshold $t$ where you stop when $x \ge t$.  Then

*

*$f(x,t)=0$ if $x\gt 6$ as you are bust

*$f(x,t)=x$ if $t \le x \le 6$ as you stop

*$f(x,t)=\frac16 \sum\limits_{y=x+1}^{x+6} f(y,t)$ if $0 \le x \lt t$ as you reroll
You are interested in $f(0,t)$ for different $t$, and you get
t   f(0,t)
1   3.5
2   3.888888889
3   4.083333333
4   3.969907407
5   3.396476337
6   2.161394033

So the optimal position is with $t=3$, rerolling if you have a total of $1$ or $2$ and otherwise stopping.  This makes the game worth $4.083333333$ as you found

A: If you have $x$, you fail and get $0$ with probability $\frac x6$, losing $x$.  If you succeed, you gain a number between $1$ and $6-x$, so on average gain $$\frac {6-x}6\cdot \frac 12(7-x)-\frac x6\cdot x$$
Just make a table of this and see where it goes negative.  It turns out the gain is $\frac 73$ at $x=1$, $1$ at $x=2$ and negative above that, so you should roll again when you have $2$ or less.


text:
Q: VM892:1 Uncaught SyntaxError: Unexpected token e in JSON at position 0 I'm presently working on a phx / phoenix API written in Elixir.  And I have created a frontend for the API using React.js.  However, I'm getting the below error message in the JS console of the browser.
I have successfully created a user using Postman, so I'm 99% sure the error isn't with the phx project, but rather somewhere with the React project.
I have both the frontend and backend hosted on github.  And a .env file will need to be created in the root of the React project with the below line,
REACT_APP_API_URL=http://localhost:4000/api

and was working my way through the following tutorial.
Any and all help would greatly be appreciated.

A: The output of localStorage.getItem("token") being
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJVc2VyOjEiLCJleHAiOjE0ODcyODI4ODcsImlhdCI6MTQ4NDY5MDg4NywiaXNzIjoiUGhvZW5peENoYXQiLCJqdGkiOiIwNzFlYzgwYi0wZmYzLTQyYzgtODA3Mi1kNzViZmVhZTg4NWEiLCJwZW0iOnt9LCJzdWIiOiJVc2VyOjEiLCJ0eXAiOiJhY2Nlc3MifQ.NsuqH50HooK8vjFfHtPH9iXSykZ9oYA0ul4b_C5fQtpu_zFvNNy-skcv9HI2i25X-NlB-9xOr-xzh2abnrpYUw

suggests that for some reason, the app stored the token without passing it through JSON.stringify, and calling JSON.parse on this string throws the Unexpected token e error, as expected.
I did not see any localStorage.setItem without JSON.stringify in the current code, so the token was probably stored like that in a previous version of the app. You should try clearing it manually and logging in again.

A: When we get the non-JSON response, we get such error..
To avoid such error, mention the responseType: Text in your api endpoint call.
This will work,
 return this.http.post(`${environment.apiUrl}/login`, user, {responseType: 'text'});

This will not work(If you mention type),
  return this.http.post<string>(`${environment.apiUrl}/login`, user, {responseType: 'text'});

A: This error message usually means you're getting a non-JSON response. If you look at the raw response in the Network tab of your debugger, you should be able to see what you're getting back from the server.


text:
Q: I want to call 20 UIView files random and non-repeating in xcode I have a game where each click of the "next" button is supposed to call one of 20 subviews in at random order without repeating any of the UIViews. At count 20 the code should call a new UIView for scores.
Can someone pls. help.
LasloV in San Francisco


text:
Q: How to set display none on  tag using css? I want that my categorybox display only subcategory
like
main category
subcategory 1
    subcategory 1_1
    subcategory 1_2
    subcategory 1_3
subcategory 2
    subcategory 2_1
    subcategory 2_2
subcategory 3
subcategory 4

I want to display like this
subcategory 1
subcategory 2
subcategory 3
subcategory 4

This is my HTML code and i am hide the parent category using css
but i am not understood how can i hide the  Shop by Brand and Concentrated Powders under   Herbal Products

             Product

         Accupuncher Niddels

              Herbal Products

           Concentrated Powders

           Shop by Brand

         Magnets, Pellets & Tapes

         New Arrival

My css like this
A.category-subs, A.category-subs:visited {

    color: #FF0000;

    text-decoration: none;

    }

    A.category-products, A.category-products:visited
    {
        display: none;
    }

but i am not get proper out put because it hide all the category-products and i want that it just hide only two as i mention above
Thanks in advance

A: Is this zen cart? If so i have just been through a similar issue myself creating a new categories menu where subcats appear on hover. I used the flyout categories menu (additional module - http://www.zen-cart.com/downloads.php?do=file&id=1290 ) which generates the categories subcats as a nested ul as suggested in comments, this is for zen cart 1.5 but similar things are available for older versions. if you delete the javascript, this one will work fine without animation and you can easily hide the elements you want to.
The only way I can think of to do it with the html you have is to use some jquery, you could then select a certain element and hide them that way. for example
$("#categoriesContent a:nth-child(4)").css('display','none');
to hide concentrated powders. But this would obviously go wrong if you added a category as the index of the elements would be altered. I suppose you could get round this instead by looping through the a elements with .each(), get their content with .html() of the a links to compare it to a particular string, eg, 'Concentrated powders' but this would get complicated and it would be much easier to change the html. In short I think you need to rethink your approach and check out the advanced categories mod or edit the current categoies template file which you will find in includes/templates/default_template/sideboxes/tpl_categories.php copy to your template directory and edit - ask another question if you need help with that.


text:
Q: jQuery add target attribute to many href elements in a variable I have a variable:
var myVar = "http://www.somelink.com"

Question: How do I add the target attribute to every single link in this variable using something like:
$("a[href^=]").attr('target', '_blank');

A: Quick typo. There's a nesting of ". So correct that first.
var myVar = "http://www.somelink.com"
//-------------------^---------------------------^--------------------------------^

What you have attempted is right. Only thing you need to do is to execute it on a real DOM element. So you need to put that content inside a dynamically created DOM element and execute the script on it:

var myVar = 'http://www.somelink.com';
var a = $('
').html(myVar);
a.find("a[href]").attr('target', '_blank');
myVar = a.html();
console.log(myVar);

If for some reason, this doesn't work in Snippets here, see the JSBin.


text:
Q: Why ctypes.c_int larger than regular int()? I've read the related question and sys.getsizeof(int()) i.e. size of an instance produces
>>> sys.getsizeof(int())
24

Assuming ctypes should be lighter, I decided to try out same thing with c_int() instance, which to my surprise showed
>>> sys.getsizeof(ctypes.c_int())
136

So why is c_int() so large compared to regular int() instance ?


text:
Q: ORA-01850 Error on TO_NUM(TO_CHAR(TO_DATE function I'm running into this "ORA-01850" error on only the LOGIN_TIME portion of my query. I believe this is because some people on my team are forgetting to logout at the end of their shift and thus their login time is exceeding 24 hours on some of those data fields (which it shouldn't).
So basically what I want my query to do is; read the login time and if it exceeds 24 hours then reduce that time back down to 24 hours, so that it can then be converted into seconds.
I think that will correct the error? But how do I even do that?
SELECT
CALL_DATE as "Date"
, TO_NUMBER(TO_CHAR(TO_DATE(CALL_TIME,'hh24:mi:ss'),'sssss'))/86400 as "Time"
, AGENT_GROUP as "Agent Group"
, AGENT_NAME as "Agent Name"
, STATE as "State"
, REASON_CODE as "Reason Code"
, TO_NUMBER(TO_CHAR(TO_DATE(LOGIN_TIME,'hh24:mi:ss'),'sssss'))/86400 as "Login Time"
, TO_NUMBER(TO_CHAR(TO_DATE(READY_TIME,'hh24:mi:ss'),'sssss'))/86400 as "Ready Time"
, TO_NUMBER(TO_CHAR(TO_DATE(NOT_READY_TIME,'hh24:mi:ss'),'sssss'))/86400 as "Not Ready Time"

FROM DB.AGENT_DETAILS

WHERE
AGENT_GROUP in ('Sales')
and TRUNC(CALL_DATE) BETWEEN '01-January-2017' and TRUNC(SYSDATE)

A: The problem is that your data is stored in VARCHAR2s, and they are using a non-standard method to store intervals greater than a day. Therefore, we need to do a little bit of string manipulation to get them into a format that can be consumed by a builtin Oracle function.
One such Oracle function that can help is TO_DSINTERVAL, which can optionally accept an ISO interval expressed in hours, minutes, and seconds - but it must look like PT24H03M55S.
Here is an example:
with q1 as (
  /*here is the source data*/
  select '24:03:45' as t from dual
), q2 as (
  /*parse and convert to iso interval format*/
  select 'PT' || substr(t,1,2) || 'H'
              || substr(t,4,2) || 'M'
              || substr(t,7,2) || 'S'
  as iso from q1
), q3 as (
  /*convert to an Oracle Day-To-Second Interval*/
  select to_dsinterval(iso) i from q2
)
  /*convert interval to whole number of seconds*/
select trunc((i + sysdate - sysdate) * 86400) as sssss from q3;

86625


text:
Q: Como extraer un extracto de un texto con Xpath Tengo este sitio inforegion.pe que extraigo su fecha de publicación con xpath, para ello utilizo la extension de chrome que se llama : xpath Helper, en este caso mi xpath es: //span[contains(@class, "box-date")]/text(), como resultado me extrae : Tocache - San Martín 01 febrero 2019 - 4:50 pm,. Como se puede apreciar la fecha tiene un texto como:Tocache - San Martín, cómo podría hacer para que mi xpath me identifique del texto completo solo desde que empiece un numero?, en este caso seria 01 en adelante, cosa que el resultado seria como este: 01 febrero 2019 - 4:50 pm, gracias
NOTA: Puede haber cualquier tamaño de texto antes del 01 febrero.., por lo tanto no seria util por ejemplo con subcadenas fijas.

A: Una vez que tengas el texto lo mejor que puedes hacer es usar expresiones regulares. Aqui te dejo un ejemplo de como hacerlo en Python:
patron = re.compile("(.*)\d{2} .* \d{4} - \d{1,2}:")
cadena = "Anta - Huancavelica 19 febrero 2019 - 6:10 pm"
resultado = patron.match(cadena).group(1).strip()

La expresion regular sigue el siguiente patron:

*

*(.*)\d{2} Toma cualquier caracter seguido por 2 numeros y lo guarda en el grupo 1

*.* \d{4} Encuentra cualquier cadena de caracteres, en este caso el mes, seguido por 4 numeros, el año.

*- \d{1,2}: Identifica el comienzo de la hora de publicacion


text:
Q: Flex - Easy way to set border on image Is there an easy way to add a simple border to an image?
I'm loading in image thumbs, and would like to add a border at runtime, instead of having to edit all the thumbs.
I'm using Spark Image.
Thanks!
EDIT:
I need to add a 1 px white border around these thumbs. I set the size of the tumbs to be 90x90, to make them fit if they are either horisontal or vertical, but the actual images in my example scales down to 90x51 (this is not fixed, only 90x90 as a maximum is fixed)
This is my code for adding thumbNails to a TileGroup (loading the gallery from an xml file):
private function loadPopUpThumbs():void{
            if(curThumbImg <= totThumbImg){
                var thumbImg:Image = new Image();
                var _loader:Loader = new Loader();
                var imageNr:int = curThumbImg;
                var thumbContainer:BorderContainer = new BorderContainer();

                _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void{
                    thumbImg.source = e.currentTarget.content;
                    popUpImgGroup.addElement(thumbImg);

                    thumbImg.width = 90;
                    thumbImg.height = 90;
                    thumbImg.scaleMode = "letterbox";
                    thumbImg.verticalAlign = "bottom";
                    thumbImg.smooth = true;
                    thumbImg.id = "thumbImg" + imageNr;

                    //thumbImg.drawRoundRect(0,0,thumbImg.width,thumbImg.height, null, 0xffffff);

                    thumbImg.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
                        popUpThumbClicked(imageNr.toString());
                    });

                    trace("Thumb added: " + popUpXMLList.(attribute('nr')==imageNr.toString()).@thumbURL);
                    curThumbImg++;
                    loadPopUpThumbs();
                });

                _loader.load(new URLRequest(encodeURI(popUpXMLList.(attribute('nr')==imageNr.toString()).@thumbURL)));

            }else{
                trace("DONE Adding thubs!!!");
            }
        }

Also: Would it be possible to add a linebreak in the items added to the TileGroup?
In my XML file I've defined a group attribute, so that I'm able to devide the images into groups. If I click a image from one group, I can skip next/prev within that group, but not to the next group. Is there any way for me to insert a linebreak to my TileGroup, so that I can listen for when the prevGroup != curGroup, and then add in some sort of spacing before continuing adding the next thumbs? All I need is a way to skip a line in the tileGroup :)
Thanks!

A: You can create new custom Image Class, extends spark Image. Very simple and clean. And set border size and color with css. See example:
package classes
{
    import flash.display.CapsStyle;
    import flash.display.JointStyle;
    import flash.display.LineScaleMode;

    import spark.components.Image;

    public class ImageBorder extends Image
    {

        public function ImageBorder()
        {
            super();
        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
        {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            if (imageDisplay && imageDisplay.bitmapData)
            {
                var borderSize:Number   = getStyle("borderSize") || 0;
                var borderColor:Number  = getStyle("borderColor") || 0xffffff;

                var half:Number = borderSize/2;
                imageDisplay.left = imageDisplay.top = imageDisplay.right =  imageDisplay.bottom = borderSize;

                graphics.clear();
                graphics.lineStyle(borderSize, borderColor, 1, false, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER);

                graphics.moveTo(0, half);
                graphics.lineTo(unscaledWidth -half, half);
                graphics.lineTo(unscaledWidth - half, unscaledHeight-half);
                graphics.lineTo(half, unscaledHeight-half);
                graphics.lineTo(half, half);

            }
        }
    }
}

In application use with css:
<fx:Style>
    @namespace s "library://ns.adobe.com/flex/spark";
    @namespace mx "library://ns.adobe.com/flex/mx";
    @namespace classes "classes.*";

    classes|ImageBorder
    {
        borderSize : 10;
        borderColor : "0xff00ff";
    }

</fx:Style>

<classes:ImageBorder source=" your source url " />

A: Spark image is a SkinnableComponent.

*

*You can create your custom skin that supports borders in any
convenient way, like styles or properties.

*Or you can set that
skin if you want to see border or remove it if you don't want

*Or you can put it inside BorderContainer, and set borderVisible to
true when you want to see the border.


text:
Q: Unable to start mqtt image with password file I have created a docker image of mqtt broker along with a config file. When I am trying to launch the image I am getting error saying: Error: Invalid password hash for user user.
Dockerfile:
FROM eclipse-mosquitto:1.4.12
RUN mkdir -p /mosquitto/data/
COPY mosquitto.conf /mosquitto/config/mosquitto.conf
COPY password.txt /mosquitto/config/password.txt
VOLUME /mosquitto/data/
EXPOSE 80

mosquitto config file:
## Logging

log_dest stdout
log_type error
log_type warning
log_type notice
log_type information

# per_listener_settings true
allow_anonymous false
password_file /mosquitto/config/password.txt
## MQTT Listener

listener 1883
protocol mqtt

## WebSockets Listener

listener 80
protocol websockets

## Persistence

persistence false

Password File:

Error:

I am trying to build an mqtt image with password file and websocket protocol


text:
Q: Can a function call be dynamic / based on caller function's parameters in Javascript? First of all, I'm sorry if this question has been asked a lot. I have tried to look for a solution and phrase my question in ten different ways, but I still can't find anything that applies to my question. I am fairly new to coding javascript, so I'm not entierly sure what to search for either.
So my situation is this:
I'm building an app that has a number of popups that will be displayed.
I'm writing in MVC format.
function showPopup(whichPopup){
   let mainPage = document.getElementById('mainPage');
   let html = '';

      if (whichPopup == 'report'){
          popupReport();
      }
}

The popupReport() function returns the popup content/HTML, and then the rest of
my showPopup() function makes the popup. The whichPopup attribute is 'report' in this case.
This works fine for now, but I'm in the process of adding more popup types, and instead of having multiple if-statements regarding the content, I would like to run the function that is relevant to the string coming from whichPopup.
Sidenote: the string coming from whichPopup is not capitalized and later in this writeup attempt to call it with the string capitalized. In my code I have written functions that capitalize it and send a different value, but I just simplified it here. In other words, capitalization is not the issue.
I was thinking about making a fetchPopupContent(whichPopup) function, which would run the corresponding function, f.ex. popupReport() , but I cannot seem to find out how to do it.
The most basic case I tried was to make a variable like this:
var popupContent = 'popup' + whichPopup + '();';

But I couldn't find out how to call on it.
I also tried to make an array with whichPopup as the value of the only array slot, and call on it like this:
function fetchPopupContent(whichPopup){
    var popupType = {
        'selectedType' : whichPopup,
    }

    popupType['selectedType']();

}

This didn't work either, and the error I got was "cannot read property of 'selectedType'". I also tried the same code without the **'**s.
Any ideas as to how I can define which function to call?


text:
Q: Spring Integration tcp-outbound-channel-adapter that detects connection loss and auto-reconnects I'm trying to do the exact opposite of what is being accomplished here:
How do I create a tcp-inbound-gateway which detects connection loss and auto-reconnects?
I have a set of collaborating client tcp adapters taken from the sample application. In general the application will be sending a high volume of client requests to a 3rd party over a shared connection, but there will be times when there are no requests coming through at all.
Because of this, there is a requirement from the 3rd party that says I should send them a ping message every 2 minutes. If the response to the ping isn't received in a predefined period of time(which could be shorter than the timeout for other calls, I should kill the connection and reconnect.
My first thought was to created a scheduled task that will send the ping every 2 minutes, but I'm not sure how I would kill the connection and re-establish it from inside the task. Another option, I was considering was to use the connection interceptor and time the request and response, but that doesn't seem right. I am brand new to SI, so any push in the right direction would be helpful.
Another I just had was autowiring the tcp-outbound-channel-adapter into the job and calling retryConnection()
<converter>
    <beans:bean class="org.springframework.integration.samples.tcpclientserver.ByteArrayToStringConverter" />
</converter>

<!-- Given we are looking for performance, let's use
     the most performant wire protocol. -->

<beans:bean id="fastestWireFormatSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer">
    <beans:constructor-arg value="1" />
</beans:bean>

<!-- Client side -->

<gateway id="gw"
    service-interface="org.springframework.integration.samples.tcpclientserver.SimpleGateway"
    default-request-channel="input" />

<ip:tcp-connection-factory id="client"
    type="client"
    host="localhost"
    port="${availableServerSocket}"
    single-use="false"
    serializer="fastestWireFormatSerializer"
    deserializer="fastestWireFormatSerializer"
    so-timeout="10000" />

<publish-subscribe-channel id="input" />

<ip:tcp-outbound-channel-adapter id="outAdapter.client"
    order="2"
    channel="input"
    connection-factory="client" /> <!-- Collaborator -->

<!-- Also send a copy to the custom aggregator for correlation and
     so this message's replyChannel will be transferred to the
     aggregated message.
     The order ensures this gets to the aggregator first -->
<bridge input-channel="input" output-channel="toAggregator.client"
        order="1"/>

<!-- Asynch receive reply -->
<ip:tcp-inbound-channel-adapter id="inAdapter.client"
    channel="toAggregator.client"
    connection-factory="client" /> <!-- Collaborator -->

<!-- dataType attribute invokes the conversion service, if necessary -->
<channel id="toAggregator.client" datatype="java.lang.String" />

<aggregator input-channel="toAggregator.client"
    output-channel="toTransformer.client"
    correlation-strategy-expression="payload.substring(0,3)"
    release-strategy-expression="size() == 2" />

<transformer input-channel="toTransformer.client"
    expression="payload.get(1)"/> <!-- The response is always second -->

Update
I am using SI 3.0.7.RELEASE
The only exception I see in the log is:
22:02:38.956 ERROR [pool-1-thread-1][org.springframework.integration.ip.tcp.connection.TcpNetConnection] Read exception localhost:4607:39129:464bd042-dd9c-4639-8d1d-cdda61dc988a SocketTimeoutException:Read timed out
This is when the so-timeout on the clientFactory is set to 10 seconds and I force the server to sleep for 15 seconds. Nothing is ever returned to the SimpleGateway call. It just sits there and waits forever.
Sample Code using the configuration listed above:
String input = "ping";
                String result = null;
                System.out.println("Sending message: " + input);
                try{
                    result = gateway.send(input);
                }catch(Exception e){
                    System.out.println("There was an exception sending the message");
                }
                System.out.println("response: " + result);

Output:
Sending message: test
22:12:17.093 ERROR [pool-1-thread-1][org.springframework.integration.ip.tcp.connection.TcpNetConnection] Read exception localhost:4607:39232:fe90d394-edc3-440a-ab68-34e7162db6ec SocketTimeoutException:Read timed out
The gateway call never returns.

A: There's a new component in 4.2 called Thread Barrier.
This allows you to wait for some (configurable) time until an async event occurs.
See the barrier sample for an example.
The ping reply would 'release' the waiting thread; in the case of the timeout you could use a request handler advice on the handler to catch the exception and take the action you need (you can get a list of open connections from the factory and close them by id).
BTW, we could probably rewrite that sample to use the barrier instead of an aggregator.
There's really no need to reopen the connection (unless you anticipate unsolicited responses on a new connection); it will be opened on the next send.
EDIT:
I need to see more of your log; I just tried it and got the following:
2015-09-28 09:05:53,995 [pool-2-thread-1] ERROR: org.springframework.integration.ip.tcp.connection.TcpNetConnection - Read exception localhost:5678:51323:f3537a39-feb4-4237-9508-7e67c1b79654
java.net.SocketTimeoutException: Read timed out
...
2015-09-28 09:05:53,996 [pool-2-thread-1] TRACE: org.springframework.integration.ip.tcp.TcpOutboundGateway - onMessage: localhost:5678:51323:f3537a39-feb4-4237-9508-7e67c1b79654([Payload=java.net.SocketTimeoutException: Read timed out][Headers={timestamp=1443445553996, id=0b3fae63-f431-c09c-ac4e-26ce4b012b6b, ip_connectionId=localhost:5678:51323:f3537a39-feb4-4237-9508-7e67c1b79654}])
2015-09-28 09:05:53,996 [main] DEBUG: org.springframework.integration.ip.tcp.TcpOutboundGateway - second chance
2015-09-28 09:05:55,998 [main] ERROR: org.springframework.integration.ip.tcp.TcpOutboundGateway - Tcp Gateway exception
org.springframework.integration.MessagingException: Exception while awaiting reply
...
Caused by: java.net.SocketTimeoutException: Read timed out
...

However, it is broken in 4.2 (and for single-use sockets) so I have opened a JIRA Issue. But yours is not single-use so I would expect the same results as mine.
EDIT 2:
Skipping a socket timeout because we have a recent send localhost:4607:26489:926b1c1f-49cc-4f44-b20d-78f2e94e82d1

I should have mentioned this before.
Because the connection factory supports completely asynchronous messaging, we might have to wait for 2 timeouts before closing the socket and propagating the exception to the gateway thread.
The reasoning is thus (using your 10 second so-timeout):

*

*Connection created at t+0; the read thread is started and is blocked in the socket (not interruptible).

*Message sent at t+9.

*Read times out at t+10.

*It would be too early to use this timeout so we ignore it because there has been a send within the last 10 seconds.

*Read times out again at t+20.

*Exception propagated to caller.

On average, the gateway thread will get the timeout at so-timeout * 1.5, but it will be in the range so-timeout to so-timeout * 2.
EDIT 3:
I can't tell from the log why it's not being propagated in your case.
I just reverted the tcp-client-server sample on this branch to 3.0.7 and changed the test to force a timeout (after skipping one), and it all worked fine for me.
We need to figure out what is different about your case and mine.
You can see the changes I made to the sample in the last commit on that branch.
If you can come up with a similar test case that reproduces the problem, I can help you debug it.


text:
Q: How to center an inline sub-menu
I am trying to center my sub-menu for my bootstrap 3 navbar.
This is my desired outcome:
A picture of what the menu is suppose to look like.
However, my sub-menu floats to the left.
The HTML:

Pages

About Team

404

CSS:
.nav-inline .nav .dropdown-menu {
  left: 0 !important;
  right: 0 !important;
  box-shadow: none;
  border: none;
  margin: 0 auto;
  max-width: 100%;
  background-color: #d5c298;
    color:#fff;
  padding: 0;
}
.nav-inline .nav .dropdown-menu li {
  float: left;
}
@media (max-width: 767px) {
  .nav-inline .nav .dropdown-menu li {
    float: none;
  }
}
.nav-inline .nav .dropdown-menu li a {
  width: auto !important;
  background: transparent;
  line-height: 49px;
  padding-top: 0;
  padding-bottom: 0;
  margin: 0;
  color: #fff;
}
.nav-inline .nav .dropdown-menu li a:hover {
  color: #000;
}

The codepen is https://codepen.io/anon/pen/vdNZWL

A: Just add:
    .navbar-links-custom .dropdown ul {
         text-align:center;
     }

     .navbar-links-custom .dropdown ul li {
         float: none;
         display:inline-block;
     }

In case that something of these is not working, try adding !important after the value.


text:
Q: Why does a topology contains its basis? The definition of a basis is given as:
Suppose a collection $\mathscr B$ of subsets of a given set $X$ satisfies:

*

*$\forall x \in X,  \exists B \in \mathscr{B}$ such that $x \in B$.

*$B_1 , B_2 \in \mathscr{B}$ and $x \in B_1\cap B_2\implies\exists B_3\in B$ such that $x\in B_3\subseteq B_1\cap B_2$.
Then the collection $\mathscr{T}$ defined as $\mathscr{T} = \{U \subseteq X : \forall x \in U \implies \exists B\in \mathscr{B}\text{ such that } x\in B\subseteq U \}$ is a topology on $X$ generated by $\mathscr{B}$ .
Now let's look at the following example:
$X = \{1 ,2, 3\}$
$\mathscr{B} = \{ \{1\}, \{2\}, \{3\} \}$,
$\mathscr{T} = \{ \varnothing, \{1\}, \{1,2,3\} \}$
Is $\mathscr{T}$ a topology generated by $\mathscr{B}$ ?  If not please elaborate the reason.

A: $\mathscr{B}$ does satisfy the axioms of a basis, and $\mathscr{T}$ is a topology, but $\mathscr{T}$ is not the topology generated by $\mathscr{B}$.
Since points are open in $\mathscr{B}$, any set is open, and the topology by $\mathscr{B}$ is the discrete topology.

A: Take $U=\{2,3\}$, then whenever $x\in U$ there is some $B\in\mathscr B$ such that $x\in B$ and $B\subseteq U$. Right?
In general, a topology always contains its basis, since every $B$ in the basis is a subset of $X$ such that whenever $x\in B$, then $B\subseteq B$ and $B$ is in the basis.

A: Your example is a trivial case for requirement of basis. Unlike simple cases, I intuitively understand this as:
 Sometimes it is not possible to define a superset of all topologies of a space.
Usually in case of continuous spaces, e.g. Set of all rectangles in a plane.
In that case,  we need a basis to check if something is a topology. For each topology X, we can generate a corresponding basis with given properties easily. And this helps in identifying whether 'A rectangle is a topology in metric space X.'

A: Let it be that $U=\bigcup_{\alpha\in A}B_{\alpha}$ where $B_{\alpha}\in\mathcal B$ for each $\alpha\in A$. Will $U$ belong to the topology $J$ as defined in your question? Yes! $x\in U$ means exactly that $x\in B_{\alpha_0}\subseteq U$ for some $\alpha_0\in A$ and here $B_{\alpha_0}\in\mathcal B$ matching the definition of $J$.
Conversely if $U\in J$ then for each $x\in U$ there is some $B_x\in \mathcal B$ s.t. $x\in B_x\subseteq U$. From this it follows that $U=\bigcup_{x\in U} B_x$. So it can be written as a union of elements of $\mathcal B$
These facts together show that $U\in J$ if and only if $U$ can be written as a union of elements of $\mathcal B$.
Applying this on the example in your question we find easily that each subset of $X$ must belong to the topology generated by the basis you mention. Note here that the empty set can be identified with the empty union ($A=\emptyset$). You are dealing here with the so-called discrete topology and the answer to your question (is $\mathscr T$ generated by $\mathscr B$?) is: "no".
Notice that each element of $\mathcal B$ can be written trivially as a union of elements of $\mathcal B$ hence belongs to the topology generated by $\mathcal B$.


text:
Q: How to purchase digital goods using Android app Currently, I am working on a project where I have 2 buttons "Add 500 Points" or "Add 1000 Points" and when they press on it, they will pay 5$ or 10$ using in-app payment.
The user can pay multiple time by pressing the buttons.
As I am doing first time this type of work, kindly let me know how can do this in Android.

A: First of all you need to implement in-app purchase, follow this for more : Implementing In-app Billing
after purchasing any product, you need to consume product : Consuming In-app Products
mService.consumePurchase(3, getPackageName(), token);

for more code you can check here : Consuming a Purchase
you can even follow this tutorial for easy use of in-app purchase.

A: This question is tagged with "android-pay" so I thought I would add some clarification. Android Pay cannot be used to sell digital goods. If you are selling digital goods or virtual goods you should use the Google Play in-app billing service.
See Android Pay questions

Q: Can I use the Android Pay API for selling digital goods?
A: No. The Android Pay API cannot be used for selling digital goods, whether they are consumed on the device or outside the device. The Android Pay API may be used only for the sale of merchandise, goods or services provided to a Buyer outside a digital environment in the physical world. The Android Pay API may not be used for the sale of any digital content or services provided through any means.
Developers who want to sell digital goods should use the Google Play in-app billing service.

For more info, see Google Play in-app billing service


text:
Q: Custom Related List with Custom Object I am quite new to Salesforce and have not yet any thing like the following.
We have a Paper object which is looking up for authors in Contact object. We want to create to have custom related list of all papers for each of the authors. In other words, when an author is viewed from Contact tab, we want to have a list of his publications in the custom related list. Each paper can have up to 10 authors. If it has 10 authors, the paper should appear in each author's page in custom related list.
Is there any way to create without apex/trigger coding ? (if I need to code, how to create related list from apex? )
Here is our Paper object:

Thanks.

A: This is a many to many object model which will utilize a 'junction object'. Employing a pair of lookups defined on the junction object with a structure that looks like this:
Author (Contact) <-- lookup Paper_Author__c lookup --> Paper__c
This model supports an Author on many Papers as well as a Paper having many Authors. It also will give you the ability to display the related lists per Author and per Paper which you're interested in by showing the Paper_Author__c list in each case.
You state that it is 'up to 10' Authors on a paper and I would highly recommend against you defining the object model with Author 1, Author 2, Author 3 etc. This is going to be a painful thing to overcome in the future when the '10 author' model doesn't work any longer.
The many to many model using the junction object, is the proper implementation of this concept, allows for an 'unlimited' number of Authors on a Paper and is 100% future-proof.
Additionally, the Author 1, Author 2, Author 3 lookup field model will not allow you to display a related list of Papers an Author has contributed to.
The junction object is the correct approach in all cases.

A: There are some good pointers how to create junction object:
https://help.salesforce.com/apex/HTViewHelpDoc?id=relationships_manytomany.htm&language=en


text:
Q: Modify programmatically a RaiseAndSetIfChanged property (To move the Selected item) Given this property that changes the Selected File every time I click an item I my listBox:
public IMediaFile SelectedPlayListFile
{
     get { return this.selectedPlayListFile; }
     set { this.RaiseAndSetIfChanged(ref selectedPlayListFile, value);
}

and called later with:
var file = this.SelectedPlayListFile;

How could i set the property without the RaiseAndSetIfChanged event? I need to change the SelectedPlayListFile programmatically and let the UI reflects that change too. (No more clicking)
So the SOLUTION was SO obvious...
this.SelectedPlayListFile = filesCollView.CurrentItem as IMediaFile;

Thank you for this newbie question.


text:
Q: NoSuchMethodError: org.openqa.selenium.remote.CommandInfo.(Ljava/lang/String;Lorg/openqa/selenium/remote/HttpVerb;)V i'm trying to run selendroid web for practice but i'm getting errors even i update selenium version (2.48.2) and set all paths correctly.
below is my code and i'm getting this error.
Please help me...
NoSuchMethodError: org.openqa.selenium.remote.CommandInfo.(Ljava/lang/String;Lorg/openqa/selenium/remote/HttpVerb;)V
 package com.guru.test;

 import io.selendroid.SelendroidCapabilities;
  import io.selendroid.SelendroidDriver;

  import org.openqa.selenium.By;
  import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
 import org.testng.annotations.AfterSuite;
 import org.testng.annotations.BeforeSuite;
  import org.testng.annotations.Test;

public class testWeb {

public WebDriver driver;

@BeforeSuite
public void setUp() throws Exception
{
    DesiredCapabilities caps = SelendroidCapabilities.android();
    driver = new SelendroidDriver(caps);
}

@Test
public void WebSiteTest() throws Exception
{
    driver.get("http://google.com");
    WebElement searchQuery = driver.findElement(By.name("q"));
    searchQuery.click();
    searchQuery.sendKeys("Test");
    WebElement submit = driver.findElement(By.name("btnG"));
    submit.click();
}

@AfterSuite
public void tearDown() throws Exception{
    driver.quit();
}

 }

A: I think you have mixed up selenium and selendroid jars. selendroid-standalone + selendroid-client should be enough for this.


text:
Q: Move-semantics vs const reference my class has string variables and I want to initialize them with values passed to the constructor.

My teacher thought us to pass strings as a const-reference:
MyClass::MyClass(const std::string &title){
  this->title = title
}

However Clang-Tidy suggest using the move command:
MyClass::MyClass(std::string title){
  this->title = std::move(title)
}

So I'm wondering what the correct way to do this in modern C++ is.
I already looked around, but nothing really answered my question. Thanks in advance!

A: None is optimal since they both default construct title first and then copy assign or move assign it. Use the member initializer list.
MyClass::MyClass(const std::string& title) : title(title) {}         // #1
// or
MyClass::MyClass(std::string title) : title(std::move(title)) {}     // #2
//or
MyClass::MyClass(const std::string& title) : title(title) {}         // #3
MyClass::MyClass(std::string&& title) : title(std::move(title)) {}   // #3

Let's look at them and see what happens in C++17:

#1 - A single converting constructor taking a const&.
MyClass::MyClass(const std::string& title) : title(title) {}

This will create 1 or 2 std::strings in one of these ways:

*

*The member is copy constructed.

*A std::string is constructed by a std::string converting constructor and then the member is copy constructed.

#2 - A single converting constructor taking a std::string by value.
MyClass(std::string title) : title(std::move(title)) {}

This will create 1 or 2 std::strings in one of these ways:

*

*The argument is constructed by return value optimization from a temporary (str1 + str2) and then the member is move constructed.

*The argument is copy constructed and then the member is move constructed.

*The argument is move constructed and then the member is move constructed.

*The argument is constructed by a std::string converting constructor and then the member is move constructed.

#3 - Combining two converting constructors.
MyClass(const std::string& title) : title(title) {}
MyClass(std::string&& title) : title(std::move(title)) {}

This will create 1 or 2 std::strings in one of these ways:

*

*The member is copy constructed.

*The member is move constructed.

*A std::string is constructed by a std::string converting constructor and then the member is move constructed.

So far, option #3 seems to be the most efficient option. Let's check a few options more.

#4 - Like #3 but replacing the moving conversion constructor with a forwarding constructor.
MyClass(const std::string& title) : title(title) {}                       // A
template<typename... Args>
explicit MyClass(Args&&... args) : title(std::forward<Args>(args)...) {}  // B

This will always create 1 std::string in one of these ways:

*

*The member is copy constructed via A.

*The member is move constructed via B.

*The member is constructed by a std::string (possibly converting) constructor via B.

#5 - A forwarding constructor only - removing the copying conversion constructor from #4.
template<typename... Args>
explicit MyClass(Args&&... args) : title(std::forward<Args>(args)...) {}

This will always create 1 std::string like in #4, but all is done via the forwarding constructor.

*

*The member is copy constructed.

*The member is move constructed.

*The member is constructed by a std::string (possibly converting) constructor.

#6 - A single argument forwarding conversion constructor.
template<typename T>
explicit MyClass(T&& title) : title(std::forward<T>(title)) {}

This will always create 1 std::string like in #4 and #5 but will only take one argument and forward it to the std::string constructor.

*

*The member is copy constructed.

*The member is move constructed.

*The member is constructed by a std::string converting constructor.

Option #6 can easily be used to do perfect forwarding if you want to take multiple arguments in the MyClass constructor. Let's say you have an int member and another std::string member:
template<typename T, typename U>
MyClass(int X, T&& title, U&& title2) :
    x(X),
    title(std::forward<T>(title)),
    title2(std::forward<U>(title2))
{}

A: Copying a reference creates a copy of the original variable (original and the new one are on different areas), moving a local variable casts to a rvalue your local variable (and again, original and the new one are on different areas).
From the compiler point of view, move may be (and is) faster:
#include <string>

void MyClass(std::string title){
  std::string title2 = std::move(title);
}

translates to:
MyClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >): # @MyClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)
        sub     rsp, 40
        mov     rax, rdi
        lea     rcx, [rsp + 24]
        mov     qword ptr [rsp + 8], rcx
        mov     rdi, qword ptr [rdi]
        lea     rdx, [rax + 16]
        cmp     rdi, rdx
        je      .LBB0_1
        mov     qword ptr [rsp + 8], rdi
        mov     rsi, qword ptr [rax + 16]
        mov     qword ptr [rsp + 24], rsi
        jmp     .LBB0_3
.LBB0_1:
        movups  xmm0, xmmword ptr [rdi]
        movups  xmmword ptr [rcx], xmm0
        mov     rdi, rcx
.LBB0_3:
        mov     rsi, qword ptr [rax + 8]
        mov     qword ptr [rsp + 16], rsi
        mov     qword ptr [rax], rdx
        mov     qword ptr [rax + 8], 0
        mov     byte ptr [rax + 16], 0
        cmp     rdi, rcx
        je      .LBB0_5
        call    operator delete(void*)
.LBB0_5:
        add     rsp, 40
        ret

However,
void MyClass(std::string& title){
  std::string title = title;
}

generates a bigger code (similar for GCC):
MyClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&): # @MyClass(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)
        push    r15
        push    r14
        push    rbx
        sub     rsp, 48
        lea     r15, [rsp + 32]
        mov     qword ptr [rsp + 16], r15
        mov     r14, qword ptr [rdi]
        mov     rbx, qword ptr [rdi + 8]
        test    r14, r14
        jne     .LBB0_2
        test    rbx, rbx
        jne     .LBB0_11
.LBB0_2:
        mov     qword ptr [rsp + 8], rbx
        mov     rax, r15
        cmp     rbx, 16
        jb      .LBB0_4
        lea     rdi, [rsp + 16]
        lea     rsi, [rsp + 8]
        xor     edx, edx
        call    std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_create(unsigned long&, unsigned long)
        mov     qword ptr [rsp + 16], rax
        mov     rcx, qword ptr [rsp + 8]
        mov     qword ptr [rsp + 32], rcx
.LBB0_4:
        test    rbx, rbx
        je      .LBB0_8
        cmp     rbx, 1
        jne     .LBB0_7
        mov     cl, byte ptr [r14]
        mov     byte ptr [rax], cl
        jmp     .LBB0_8
.LBB0_7:
        mov     rdi, rax
        mov     rsi, r14
        mov     rdx, rbx
        call    memcpy
.LBB0_8:
        mov     rax, qword ptr [rsp + 8]
        mov     qword ptr [rsp + 24], rax
        mov     rcx, qword ptr [rsp + 16]
        mov     byte ptr [rcx + rax], 0
        mov     rdi, qword ptr [rsp + 16]
        cmp     rdi, r15
        je      .LBB0_10
        call    operator delete(void*)
.LBB0_10:
        add     rsp, 48
        pop     rbx
        pop     r14
        pop     r15
        ret
.LBB0_11:
        mov     edi, offset .L.str
        call    std::__throw_logic_error(char const*)
.L.str:
        .asciz  "basic_string::_M_construct null not valid"

So yes, std::move is better (under these circumstances).

A: It' ok use a const reference, then use member initializer lists:
MyClass(const std::string &title) : m_title{title}

Where m_title is your member string in the class.
You can find useful help here: Constructor member initializer lists

A: there are 2 cases: lvalue or rvalue of std::string.
in std::string const& version, lvalue case is efficient enough, passed by reference and then copied. but a rvalue will be copied rather than moved, which is in much lower efficiency.
in std::string version, lvalue is copied when passed, and then moved to the member. rvalue will be moved twice in this case. but generally it's cheap, the move constructor.
besides, in std::string&& version, it can not receive a lvalue, but rvalue is passed by reference and then moved, better than moved twice.
so obviously, it's the best practice with both const& and &&, as what STL always does. but if move constructor is cheap enough, just passing by value and moving is also acceptable.