text:
Q: Display data on a Jtable after excuting a search basically currently my code is searching for the first name or surname in the table. Once the search has been done, for example 'Peter' , what will occur is the data will be placed into the text boxes.
The issue is I want the data to be displayed onto my table, I have tried this many times but it does not seem to work, I have tried using this line of code. The 'table_stats' is the name of the table. table_stats.setModel(DbUtils.resultSetToTableModel(Result));
I am pretty new to this, can any one please help, much appreciated thank you!
private void searchKeyReleased(java.awt.event.KeyEvent evt) {
    // TODO add your handling code here:
    try{
      String sql = "select * from statistics where first_name =? "  ;
       String sql2 = "select * from statistics where surname =? "  ;
      Prepared=conn.prepareStatement(sql);
      Prepared=conn.prepareStatement(sql2);
      Prepared.setString (1, search.getText());
      Result = Prepared.executeQuery();
      if(Result.next()){
          String add1 = Result.getString("player_id");
          player_id.setText(add1);
          String add2 = Result.getString("first_name");
          first_name.setText(add2);
          String add3 = Result.getString("surname");
          surname.setText(add3);
          String add4 = Result.getString("goal_scored");
          goal_scored.setText(add4);
          String add5 = Result.getString("assist");
          assist.setText(add5);

      }

    }
    catch(Exception e)

    {

    JOptionPane.showMessageDialog(null, e);
    }

}

A: I think you can use the DefaulTableModel: (http://docs.oracle.com/javase/7/docs/api/javax/swing/table/DefaultTableModel.html)
Or you can implement your own subclass of AbstracTableModel: (http://docs.oracle.com/javase/7/docs/api/javax/swing/table/AbstractTableModel.html)
Anyway you should separate code like querying a database table from your GUI code (for example create a separate class with a method getPlayers which returns a table model).


text:
Q: What are "domain-specific languages"?
Possible Duplicate:
What is a DSL and where should I use it?

I've heard the term used a lot... what exactly does it mean for a language to be "domain-specific"?
Also, what does it mean for a language (e.g. Groovy) to support domain-specific languages?

A: For your first question a bit of googling will be sufficient.
As for the second question: you can implement DSLs in any language. You can even implement eDSLs in almost any language. But some languages are much better in that than the others. The key feature is metaprogramming  - an ability to generate code in your host language, which means you can plug in a compiler of your eDSL anywhere. Features which facilitate compiler construction are also useful - e.g., out of box parsing tools, extensible or just flexible syntax of the host language, algebraic data types for representing ASTs, pattern matching for simplifying compiler transformations, etc. There is a continuum of possibilities, with entirely static and unextensible languages on one side and absolutely flexible languages at the other side.

A: A "domain specific language" is one in which a class of problems (or solutions to problems) can be expressed succinctly, usually because the vocabulary aligns with the that of the problem domain, and the notation is similar (where possible) to that used by experts that work in the domain.
What this really means is a grammar representing what you can say, and a set of semantics that defines what those said things mean.   This makes DSLs just like other conventional programming langauges (e.g., Java) in terms of how they are implemented.  And in fact, you can think of such conventional languages as being "DSL"s that are good at describing procedural solutions to problems (but not necessary good at describing them).   The implications are that you need the same set of machinery to process DSLs as you do to process conventional languages, and that's essentially compiler machinery.
Groovy has some of this machinery (by design) which is why it can "support" DSLs.
See Domain Specific Languages for a discussion about DSLs in general, and a particular kind of metaprogramming machinery that is very helpful for implementing them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using pairwise differences as variable in regression I have a dataset consisting of 72 data points, with 1 dependent variable $y$ and 37 predictors $X_j$.
The typical way to perform a linear regression would be to model $y$ as
$$y = XB + \epsilon$$
where an intercept may or may not be included in the matrix of predictors.
I thought about an alternative model, in which the difference in $y$ for pairs of cases is regressed on the difference in the predictor's values for those same cases, i.e., defining
$$ \{y_i - y_j\} \equiv y^*\\ \{X_i - X_j\} \equiv X^*$$
for all possible $(i,j)$ pairs (or a subset of all possible pairs), and then performing a linear regression on these variables
$$y^* = X^*B^* + \epsilon^*$$
I just wonder whether this is would be valid approach or if there is something inherently wrong in it. I could not find find any useful information on the web. I would be very grateful for any helpful comments or advice.
Additional information
Simple tests with synthetic data suggest that the two models give identical results, as expected.
However, there is a situation in which it seems to me that the second model could be preferable: suppose that the data was collected over several days, and that the measurements of $y$ are subject to a systematic bias due to, e.g., the temperature of the room which varies randomly from day to day. In this situation, taking the pairwise differences of all data points collected on the same day would remove the temperature bias, and thus yield a more accurate regression.
Again, a simple test with synthetic data showed that as expected, in the situation described above the pairwise-difference model produces smaller errors in the estimation of the regression weights than does the regular model.

A: It's an interesting idea, but it's a different model and there are inherent difficulties in fitting it.
You did well by explicitly including the error term $\epsilon$ in the original model.  This determines the error term in the differenced model; to wit,
$$\eqalign{
y^{*}_{ji} = y_j - y_i &= (x_iB + \epsilon_j) - (x_jB + \epsilon_i) \\
&= (x_i-x_j)B + (\epsilon_j-\epsilon_i) \\
&= x^{*}_{ji}B^{*} + \epsilon^{*}_{ji}.
}$$
Comparing the last two lines shows $B^{*}=B$ (as you had hoped) and $\epsilon^{*}_{ji} = \epsilon_j - \epsilon_i.$
The usual assumptions are that the $\epsilon_i$ are independent, have zero means, and have (at least approximately) the same common variance.  Although the latter two will be the case for the differenced model when they are true originally, the $\epsilon^{*}_{ji}$ are decidedly not independent!  Indeed, assuming the $\epsilon$ have a common (finite) variance $\sigma^2,$ their independence implies
$$\operatorname{Var}(\epsilon^{*}_{ji}) = \operatorname{Var}(\epsilon_j) + \operatorname{Var}(\epsilon_i) = \sigma^2 + \sigma^2 = 2\sigma^2,$$
showing that the errors in the differenced model have twice the variance of the original errors and for $k\ne i,$
$$\operatorname{Cov}(\epsilon^{*}_{ji}, \epsilon^{*}_{jk}) = \operatorname{Cov}(\epsilon_j-\epsilon_i, \epsilon_j-\epsilon_k) = \sigma^2 - 0 - 0 + 0 = \sigma^2;$$
$$\operatorname{Cov}(\epsilon^{*}_{ij}, \epsilon^{*}_{jk}) = \operatorname{Cov}(\epsilon_i-\epsilon_j, \epsilon_j-\epsilon_k) = 0 - \sigma^2 - 0 + 0 = -\sigma^2,$$
showing that when one $\epsilon^{*}$ shares a subscript with another $\epsilon^{*},$ their correlation is $\pm1/2.$  Although you could handle this circumstance with generalized least squares, the matrices involved will grow large rather quickly: for instance, with your tiny dataset of just 72 observation, the weights matrix is square with dimension $72(71)/2 = 2556,$ containing almost seven million entries (albeit somewhat sparsely).
What are the consequences of ignoring this lack of independence?  I'm afraid your synthetic data may have misled you in several ways into drawing false conclusions.

*

*When there is a constant term, all its differences are zero and therefore drop out of the model.  Thus, the differenced model should include no constant term (intercept) at all, and if it does, its estimate should be insignificantly different from zero--but usually won't be.  Regardless, by taking differences of the responses, you can no longer estimate the constant term: because it always multiplies $1-1=0,$ it is not identifiable.

*The strong correlations among the errors imply the effective amount of data--"degrees of freedom"--to use for computing standard errors and p-values is much smaller than the number of pairs.  Indeed, because subtracting the paired data introduces no new information at all, a correct calculation of the degrees of freedom is the same as before: $72-37=35$ (without an intercept), even though it appears you have $2556$ observations!

*As a result, if you do not use generalized least squares, all p-values will be (far) too small and many estimates may appear to be "significant" when they are the result of noise alone.

*If you include an intercept in the difference model, the parameter estimates will differ.  If you leave it out, you should obtain correct estimates: after all, you are estimating exactly the same parameters $B$ using exactly the same data.
Finally, although it is instructive to compare these approaches, one wonders what could possibly be the advantage of turning a problem involving computing with a $72\times 37$ matrix into one involving a $2556\times 37$ matrix: it takes (much) more computation to obtain the same estimates (ignoring the loss of ability to estimate the intercept) and far more work to obtain correct p-values, confidence intervals, hypothesis tests, and so on.

This R code produces sample data, fits both models, and compares their results.  It can be instructive to review the model summaries that it outputs.
n <- 72                   # Number of observations
k <- 37                   # Number of variables, apart from the constant
beta <- (-1)^seq_len(k+1) # The model coefficients, beginning with the intercept
sigma <- 0.5              # Error s.d.
#
# Create data.
#
X <- as.data.frame(matrix(rnorm(n*k), nrow=n, dimnames=list(NULL, paste0("x.", 1:k))))
X$y <- cbind(1, as.matrix(X)) %*% beta + rnorm(n, 0, sigma) # The response
#
# Base model.
#
fit <- lm(y ~ ., X)
summary(fit)
#
# Paired model.
#
xx <- as.matrix(X)
XX <- as.data.frame(t(apply(combn(1:n, 2), 2, function(ij) xx[ij[1], ] - xx[ij[2], ])))
names(XX) <- paste0("d", names(XX))
fit.d <- lm(dy ~ . - 1, XX)         # No intercept!
summary(fit.d)
#
# Check whether coefficients agree.
#
all.equal(coefficients(fit)[-1], coefficients(fit.d), check.attributes=FALSE)
#
# Plot the data.
#
# pairs(X)
# pairs(XX)

A: This second approach is often used in experimental situation where some data is collected before and after treatment for same subjects. If you would have all observation from two time periods then observations would not be independent and you should specify covariance structure for generalized regression model. It is easiear to use difference approach in this case.
So I would say your approach is OK.

A: A quick simulation shows that doing this just gives you anti-conservative (rejects the null too often) normal regression
Example:
set.seed(123)
x <- seq(-3,3, by=0.1)
y <- rnorm(length(x), x, 1)

dx <- outer(x,x,`-`)
dy <- outer(y,y,`-`)

summary(lm(c(dy) ~ c(dx)))
summary(lm(y ~ x))

gives a test stat of 15 in the "normal" case and 122 in the pairwise difference case.
You might be interested to know that the linear regression coefficient is the weighted average of the pairwise slope. That is:
$$\hat{\beta}_{OLS} = \sum_{i=1}^n \sum_{j \ne i} w_{ij} \frac{Y_i - Y_j}{X_i - X_j} / \sum_{i=1}^n \sum_{j \ne i} w_{ij} $$
where $w_{ij} = (X_i - X_j)^2$.


text:
Q: Animation Drawing in MFC One parent window have some child window for animation.
Each child window have thread, Its thread calculate next animation location and then, call the invalidate method.
So, each child window receive WM_PAINT message, and then paint.
When parent window have many child window for animation, WM_PAINT message was too many occurred.
Although I have been painting using D2D library, Performance is not satisfaction.
Please advise me


text:
Q: A way to clean up class constructor in TypeScript? At the moment I am defining my class constructors in the following way
class MyClass {

  routerStore: RouterStore
  characterStore: CharacterStore
  characterPrivateStore: CharacterPrivateStore

  constructor(
    routerStore: RouterStore,
    characterStore: CharacterStore,
    characterPrivateStore: CharacterPrivateStore
  ) {
    super()
    this.routerStore = routerStore
    this.characterStore = characterStore
    this.characterPrivateStore = characterPrivateStore
  }
}

This feels verbose and repetitive to me. Given that TypeScript takes advantage of some latest JavaScript proposals I wanted to ask if it is possible to clean this up somehow?

A: You can add an access modifier to the constructorparameter. This will make the parameter also a class field that will be initialized with the value of the parameter.
class MyClass {

   constructor(
       public routerStore: RouterStore,
       public characterStore: CharacterStore,
       public characterPrivateStore: CharacterPrivateStore
    ) {
       super()
   }
}

You can also use Object.assign declare the fields on the class and use a mapped type to extract just the field keys (exclude the methods):
type JustFieldKeys<T> = { [P in keyof T] : T[P] extends Function ? never : P }[keyof T]
class MyClass {

    public routerStore!: RouterStore,
    public characterStore!: CharacterStore,
    public characterPrivateStore!: CharacterPrivateStore
    constructor(params: Pick<MyClass, JustFieldKeys<MyClass>>) {
        Object.assign(this, params);
    }
}
new MyClass({
    characterPrivateStore: null,
    characterStore: null,
    routerStore: null
})


text:
Q: POST an array with similar names and similar values I am posting this because I do not really know what I could search for. Please note that I have basic knowledges and am still learning ; also, I might sometimes use wrong terms, sorry about that.
I am setting up a web application through PHP/MySQL, HTML, Bootstrap, and JQuery.
I need to post an array to my database. The problem is, this array might contain several times the same value. Indeed, the array is made out of values inside a html table, to which rows can be added to add more data at the same time thanks to JQuery and DataTable.
So far, I did not even know how to post an array, and found the following solution to be working to do so, as the following code:
<form method="post">
    <input name="country[]" value="France">
    <input name="country[]" value="Spain">
    <input name="country[]" value="Germany">
    <input type="submit">
</form>

$country = $_POST['country'];
print_r $country;

Would contain the following array result:
|country|
|-------|
|France |
|Spain  |
|Germany|

Wonderful.
But what I need to do sometimes, is something like this:
<form method="post">
    <input name="country[]" value="France">
    <input name="country[]" value="France">
    <input name="country[]" value="France">
    <input type="submit">
</form>

And I would like this:
$country = $_POST['country'];
print_r $country;

To contain the array:
|country|
|-------|
|France |
|France |
|France |

But instead, the POST contains only
|country|
|-------|
|France |

Whereas Firefox Developer Tools clearly indicates me that the page sent the exact array I need to receive.
Form Data
   country[]: [...]
      0: France
      1: France
      2: France

Could you please help me with that?
Thank you very much for your time and attention.

A: Thank you Daan for asking me how I checked what $_POST['country']; contains.
I modified my original post to include these information. By doing so, I saw that I checked it once I changed it, as I use it again later in a foreach, to display all the rows in another array.
So I checked it the right way.
It turned out my problem was a lot more different, and is related to my use of the foreach.
Indeed, I use the country name as an index for the foreach. As it can only use unique indexes, it uses only once "France".
To scaisEdge: This is data I modified to be anonymous, and country was the easiest way to do so. Imagine products instead of countries, and this is why the user can add several times one unique name.


text:
Q: How are fast-math flags added int the LLVM C++ API during code generation? I have a builder that builds an operaion:
return BuilderBinop.CreateFMul(L, R, "multmp");

This generates
%multmp23 = fmul float %d22, %e21

Now I want to add fast-math flags to this. Specifically, I want to add the fast flag. How do I go about doing this?

A: FastMathFlags fmf;
fmf.setFast(true);
BuilderBinop.setFastMathFlags(fmf);

The FastMathFlags class has helper methods to set flags. Since the interest here is to set the fast flag to true, the .setFast() comes in handy.
To clear the flags, the .clear() can be used.


text:
Q: $w.at Event Handler runs recursive when fired on repeater. WIX / Corvid / Velo I have a pretty simple example of export function (event handler mouseIn) which works somehow odd for me.
I have a repeater filled with 150 elements. When I had 10 elements all was fine. But the more elements there are, the slower the function works. Although the problem is different.
Repeater elements
In the editor the #repeater looks like this: there are a container2 with all elements inside it and the box1 which is collapsed by default. box1 contain 3 dropdowns. These elements are not connected to any dataset. I mean container2 box1 and any of dropdowns.
Repeater in Editor
And here are the functions I have on my site:
export function container2_mouseIn(event) {
 let $item = $w.at(event.context);
    $item("#box1").expand();
}
export function container2_mouseOut(event) {
 let $item = $w.at(event.context);
    $item("#box1").collapse();
}
export function box1_mouseIn(event) {
 let $item = $w.at(event.context);
    $item("#box1").expand();
}

So, as you can see from the functions above I want to achieve with this code is to show dropdowns of the related element #OnMouseIn and to hide it #OnMouseOut of container2.
And this works just fine and fast if you have 3-10 items in the repeater. But if you have 20 f.e. you can see that delays of dropdowns appearance. When I have 150 items is just working very slow and as I have not only these event handlers I even have an error in Chrome console.
The errors are following:
Errors
What was done next:
I've opened a performance tab in the Chrome and recorded exactly the hover action to look what's going on with it.
And here is the result
So mouse out event took 813.6ms. Almost a second. Isn't it weird?
These whole green columns which is beyond the / Task =>Event Mouse out=>Function Call / consists of three repeating
(anonymous)
         _t
          r
Again and again. I don't know what kind of a #recursion is it and why it happens...
Recursion
This happens even when I have 10 elements on the site. Just if I have 150 it can be seen much better. And I'm starting to have an errors Uncaught RangeError: Maximum call stack size exceeded.
I know a little about the stacks but I really don't have an idea from this WIX code what's wrong and why it so?
Does anyone know what's wrong with my code? And why this kind of recursion happens?
I was also recording an events related to non-repeater elements. I mean just a separate button on my page. And there is no recursion in this case. Just fast and short function call in the console.
Thank you in advance. I appreciate any help on this.


text:
Q: JavaScript. Please advise on better code reuse and/or structure As the title suggests, A better coding structure or implementation for my JavaScript below. This checks a ID element values from a form before submitting to a database.
I'm interested to know if I could have reduced the code size/could have implemented reuse of code which will give me some tips for the future!
Thanks.

function validateRunnerID()
{
    var runnerID = document.getElementById('RunnerID').value;
    if (isNaN(runnerID) || runnerID < 1 || runnerID > 9999)
    {
        return "RunnerID: Enter a Integer Value between 1-9999 \n\n";
    }else{
        return "";
    }
}

function validateEventID()
{
    var eventID = document.getElementById('EventID').value;
    if (isNaN(eventID) || eventID < 1 || eventID > 9999)
    {
        return "EventID: Enter a Integer Value between 1-9999 \n\n";
    }else{
        return "";
    }
}

function validateDate()
{
    var checkDate= /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/;
    var date= document.getElementById('Date');
    var tof= date.value.match(checkDate);

    return tof? "" : "Date: Enter a Valid Date with parameters: YYYY-MM-DD \n\n";
}

function validateFinishTime()
{
    var finishTime = document.getElementById("FinishTime").value;
    if (finishTime.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/))
    {
        return ""
    }else{
        return "Finish Time: Enter a valid Time with parameters: HH:MM:SS \n\n";
    }
}
//
//
function validatePosition()
{
    var position = document.getElementById('Position').value;
    if (position.length == 0)
    {
        document.getElementById('Position').value = -1;
        return "";
    }else{
        return "";
    }
}
function validateCategoryID()
{
    var categoryID = document.getElementById('CategoryID').value;
    if (categoryID.length == 0)
    {
        document.getElementById('CategoryID').value = -1;
        return "";
    }else{
        return "";
    }
}
function validateAgeGrade()
{
    var ageGrade = document.getElementById('AgeGrade').value;
    if (ageGrade.length == 0)
    {
        document.getElementById('AgeGrade').value = -1;
        return "";
    }else{
        return "";
      }
}
function validatePB()
{
    var pBest = document.getElementById('PB').value;
    if (pBest.length == 0)
    {
        document.getElementById('PB').value = 0;
        return "";
    }else{
        return "";
    }
}
//
//
function validateForm()
{
    var result = validateRunnerID() + validateEventID() + validateDate() + validateFinishTime() + validatePosition() + validateCategoryID() + validateAgeGrade() + validatePB();

    if ( result == "" )
    {
        alert("Data Accepted and Submitted \n\n");
        return true;
    }else{
        alert("Please Fix Errors Listed: \n\n" + result);
        return false;
    }
}

A: One thing you can do is to accept an elementId as input to your validation functions. This allows to reuse the same logic for different fields.
For example:
function validate4DigitInt(elementId)
{
    var value = document.getElementById(elementId).value;
    if (isNaN(value) || value < 1 || value > 9999)
    {
        return elementId + ": Enter a Integer Value between 1-9999 \n\n";
    }else{
        return "";
    }
}

Now you can validate both RunnerId and EventId using the same function:
var result="";
result+=validate4DigitInt("RunnerId");
result+=validate4DigitInt("EventId");


text:
Q: How to set scrollcomposite for one TabItem in SWT? I am trying the following code to set scrollcomposite for TabItem "item2". But couldn't get the scroll bar.
Here I created two tabItem , where I need to set scrollcomposite / scrollbar for only item2 not for item1
Display display = new Display();
final Shell shell = new Shell(display);
final TabFolder tabFolder = new TabFolder(shell, SWT.BORDER);
Rectangle clientArea = shell.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
// First Tab Item
TabItem item = new TabItem(tabFolder, SWT.NONE);
item.setText("TabItem " + 1);
Composite comp = new Composite(tabFolder, SWT.NONE);
GridLayout gl = new GridLayout();
GridData wgd = new GridData(GridData.FILL_BOTH);
comp.setLayout(gl);
comp.setLayoutData(wgd);
Button button = new Button(comp, SWT.PUSH);
button.setText("Page " + 1);
Button button2 = new Button(comp, SWT.PUSH);
button2.setText("Page " + 1);
Button button3 = new Button(comp, SWT.PUSH);
button3.setText("Page " + 1);
Button button4 = new Button(comp, SWT.PUSH);
button4.setText("Page " + 1);
item.setControl(comp);

ScrolledComposite sc = new ScrolledComposite(tabFolder, SWT.BORDER
            | SWT.H_SCROLL | SWT.V_SCROLL);

// second tab item
TabItem item2 = new TabItem(tabFolder, SWT.NONE);
item2.setText("TabItem " + 1);
Composite comp2 = new Composite(tabFolder, SWT.NONE);
GridLayout gl2 = new GridLayout();
GridData wgd2 = new GridData(GridData.FILL_BOTH);
comp2.setLayout(gl2);
comp2.setLayoutData(wgd2);
Button buttonq = new Button(comp2, SWT.PUSH);
buttonq.setText("Page " + 1);
Button button2q = new Button(comp2, SWT.PUSH);
button2q.setText("Page " + 1);

sc.setContent(comp2);
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
sc.setMinSize(comp2.computeSize(SWT.DEFAULT, SWT.DEFAULT));
sc.setShowFocusedControl(true);
item2.setControl(comp2);

tabFolder.pack();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
        display.sleep();
}
display.dispose();

When I added following code, tabItem2 was empty:
item2.setControl(comp2);

Please help me to solve this

A: Several things here.
First use layouts for everything. The tabFolder.setLocation is causing confusion, use FillLayout instead.
So replace
Rectangle clientArea = shell.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);

with
shell.setLayout(new FillLayout());

Second, the Composite for the second tab must be owned by the ScrolledComposite.
So change
Composite comp2 = new Composite(tabFolder, SWT.NONE);

to
Composite comp2 = new Composite(sc, SWT.NONE);

Finally the ScrolledComposite must be the control for the second tab, so change
item2.setControl(comp2);

to
item2.setControl(sc);


text:
Q: How to take out strings from lists and compare them one character at a time I have two lists looking like:

L1 = [[25, 34, 'ABCD', 'EFG']]

L2 = [[12, 22, 'ABCD', 'EGH']]

I want to extract "ABCD" from both lists and compare them one character at a time.
To extract the strings from the lists I used:

string1 = [string[3] for string in L1]

string2 = [string[3] for string in L2]

To compare them I used: (Because I both want the character and position)

if len(string1) == len(string2):

    for i, char in enumerate(string1):
        print(i)
        print(char)

When printing I only get position 0 and for char I get the whole string (ABCD).
How should I do to get each position and get each character one at a time?

A: Using:
[string[3] for string in L1]

To get "ABCD" from L1 will only get the last string, irregardless if it is "ABCD" or not. Just keep it simple at write a function that extracts this for you:
def extract(lst, ext):
    for l in lst:
        for string in l:
            if string == ext:
                return string
    return None

Which behaves accordingly:
L1 = [[25, 34, 'ABCD', 'EFG']]
L2 = [[12, 22, 'ABCD', 'EGH']]

str1 = extract(L1, "ABCD")
str2 = extract(L2, "ABCD")
fail = extract(L1, "ABC")

>>> print(str1)
"ABCD"
>>> print(str2)
"ABCD"
>>> print(fail)
None

Then just loop over both strings at once with zip(), once both strings have been checked to be valid:
if str1 and str2 and len(str1) == len(str2):
    for i, char in enumerate(zip(str1, str2)):
        print(i, char[0], char[1])

Which outputs:
0 A A
1 B B
2 C C
3 D D


text:
Q: Why do I get two different results with minitest assert equal when using a helper function and using string interpolation or concatenation ** helper method that passes test **
module ApplicationHelper
  def full_title(page_title= '')
    base_title = 'Tweeter_clone'
    if page_title.empty?
      base_title
    else
    page_title + " | " + base_title
    end
  end
end

** helper method that does not pass test and returns an empty string "" **
module ApplicationHelper
  def full_title(page_title= '')
    base_title = 'Tweeter_clone'
    if page_title.empty?
      base_title
    else
    `#{page_title} | #{base_title}`
    end
  end
end

Below is the actual test. I really don't understand why string interpolation won't work in this case, but concatenation does.
require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  test "full title helper" do
      assert_equal 'Tweeter_clone', full_title
    assert_equal "Help | Tweeter_clone", full_title("Help")
  end
end

I did include the applicationHelper in test_helper.rb

A: Syntax issue. Use double quotes in Ruby, and backticks in Javascript.


text:
Q: Disable resizing of fixed flex I'm using this html below to display a flex view on my website. But changing the text (length of the text) from a div will lead to the crazy-looking autoresizing.
How can I avoid this resizing in relation to this special div element below? How to keep the same layout when the click button is clicked?
Edit: I would like that neither the size nor the position of any element changes. (No matter how much text is inside!)

Info A

text1

Info B

text2

Info C

text3

<input onclick="document.getElementById('text').innerHTML+='.'" type="button" value="click">

A:

 .wrapper{
    width:100%;
    background: black;
    display: flex;
    justify-content: space-around;
    text-align: center;
    color: white;
}

.wrapper > div{
    flex: 1;
    text-overflow: ellipsis;
    overflow: hidden;
}

Info A

text1

Info B

text2

Info C

text3

    <input onclick="document.getElementById('text').innerHTML+='.'" type="button" value="click">

A: Here's the solution:

document.addEventListener("click", function(e){
  if(e.target.id == "button")
   document.getElementById('text').innerHTML+='.';
});
#navigation {
  position: fixed;
  width: 100%;
  height: 30%;
  left: 0%;
  top: 0%;
  background: black;
  display: flex;
  justify-content: space-around;
  text-align: center;
  color: white;
  flex-basis: 1 1 100%;
}
#navigation > div {
  flex-direction: column;
  overflow: hidden;
  width: 100%;
}
#button {
  position: relative;
}

Info A

text1

Info B

text2

Info C

text3

<button id="button">click</button>

Edit: To lock the tekst as well. I would do it with align it left and than adding a padding to it:
#navigation > div > div:nth-child(2) {
  padding-left: 10%;
  text-align: left;
}

A: Here's an example of using max-width with your code. The first block will never be wider than 150px and text which which will overflow will be hidden.

.wrapper{
    width:100%; background: black; display: flex; justify-content: space-around; text-align: center; color: white;
}

.wrapper > div{
    flex: 1;
    text-overflow:ellipsis;
    overflow:hidden;
}

Info A

text1

Info B

text2

Info C

text3

<input onclick="document.getElementById('text').innerHTML+='.'" type="button" value="click">

A: Add flex: 1 0 33%; to the elements you don't want to resize. This is equivalent to:
flex-grow: 1;
flex-shrink: 0;
flex-basis: 33%;

Info A

text1

Info B

text2

Info C

text3

<input onclick="document.getElementById('text').innerHTML+='.'" type="button" value="click">


text:
Q: After upgrade to Angular 6/Material 6 why am I facing 'mat-input-container is not a known element'? Below code was running fine before I upgraded to 6. Not sure what changed in between! I have required modules imported as well
MatInputModule,
MatSelectModule,
MatFormFieldModule

  <mat-input-container>
    <mat-select placeholder="Sort By" formControlName="sortBy">
      <mat-option *ngFor="let sortByObject of sortByList" [value]="sortByObject.value">
        {{ sortByObject.label }}
      </mat-option>
    </mat-select>
  </mat-input-container>

A: As per https://material.angular.io/components/form-field/overview we are now supposed to use mat-form-field
  <mat-form-field>
    <mat-select placeholder="Select">
      <mat-option value="option">Option</mat-option>
    </mat-select>
  </mat-form-field>

A: This CSS class has been removed beginning version

6.0.0-beta.5 (2018-03-23)

mat-input-container has been deprecated, instead use mat-form-field
For details of breaking changes in 6.0.0-beta.5:
https://github.com/angular/material2/blob/master/CHANGELOG.md#600-beta5-2018-03-23
For details of breaking changes in general, refer:
https://github.com/angular/material2/blob/master/CHANGELOG.md


text:
Q: qtip2 tooltip - mouse tracker - how find content of many controls with a same class? i have many controls like below :

                        <asp:CustomValidator ID="cvCaptcha" runat="server" Display="Dynamic" OnServerValidate="cvCaptcha_ServerValidate">
                            <asp:Image ID="img4cvCaptcha" CssClass="imgValidate" runat="server" AlternateText="attention"
                                ImageUrl="~/Images/Login/Exclamation.png" />
                        </asp:CustomValidator>

                       captcha is incorrect!!!

as you see i put the ttContent of each control in the below of it (inside a div) and i have many controls with ttTarget class...
the qtip2 codes for mouse tracker tooltips is like below :
        $('#target').qtip({
            content: 'i am tool tip',
            position: {
                my: 'top left',
                target: 'mouse',
                viewport: $(window), // Keep it on-screen at all times if possible
                adjust: {
                    x: 10, y: 10
                }
            },
            hide: {
                fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
            },
            style: 'ui-tooltip-shadow'
        });

when we use id s for qtip every thing is so simple and we can find target's content easily!
but in my scenario i have many id s that i do n't know how can i recognize their content by the upper code !
i mean :
        $('.ttTarget').qtip({
            content: '______________' -> here is my problem (how can i find ttContents),
            position: {
                my: 'top left',
                target: 'mouse',
                viewport: $(window), // Keep it on-screen at all times if possible
                adjust: {
                    x: 10, y: 10
                }
            },
            hide: {
                fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
            },
            style: 'ui-tooltip-shadow'
        });

thanks in advance

A: Way 1 :
$(function () {
            $('.ttTarget').qtip({
                overwrite: false,
                content: {
                    text: function (api) {
                        return $(this).parent('div').find('div.ttContent').html();
                    }
                },
                position: {
                    my: 'top left',
                    target: 'mouse',
                    viewport: $(window),
                    adjust: {
                        x: 10, y: 10
                    }
                },
                hide: {
                    fixed: true
                },
                style: 'ui-tooltip-shadow'
            });

way 2 :
    $('.ttTarget').live('mouseover', function (event) {
        //alert($(this).next('div.ttContent').text());
        //alert($(this).parent('div').find('div.ttContent').html());
        $(this).qtip({
            overwrite: false,
            content: $(this).parent('div').find('div.ttContent').html(),
            position: {
                my: 'top left',
                target: 'mouse',
                viewport: $(window),
                adjust: {
                    x: 10, y: 10
                }
            },
            hide: {
                fixed: true
            },
            show: {
                event: event.type,
                ready: true
            },
            style: 'ui-tooltip-shadow'
        }, event);
    });


text:
Q: Fast scraping of dynamic web page using Python I've been testing grabbing data from a motor racing live timing page. It updates several times a second.
I've been using Selenium to grab by id the data I'm after.
But there are 20 drivers times about 11 stats.
This means that it takes about 3 seconds to grab this data before it starts again.
Is there a faster way?
driverList = []
drivernums = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17',
              '18', '19', '20']
for d in range(1, 22):
    driverList.append(
        {"Pos": 0, "Name": '', "Lap": 0, "Gap": 0, "Interval": 0, "Pits": 0, 'Tyres': 0, 'S1': 0, 'S2': 0, 'S3': 0,
         'Laptime': 0})

while True:
    sessiontimeremaining = driver.find_element_by_id('stats_si_time')
    safetycar = driver.find_element_by_id('stats_si_safetycar')
    racelaps = driver.find_element_by_id('stats_si_laps')
    for d in drivernums:
        driverList[int(d)]['Pos'] = driver.find_element_by_id(f'i_{d}_pos').text
        driverList[int(d)]['Name'] = driver.find_element_by_id(f'i_{d}_nick').text[0:3].upper()
        driverList[int(d)]['Lap'] = driver.find_element_by_id(f'i_{d}_lap').text
        driverList[int(d)]['Gap'] = driver.find_element_by_id(f'i_{d}_gap').text
        driverList[int(d)]['Interval'] = driver.find_element_by_id(f'i_{d}_int').text[:-1]
        driverList[int(d)]['Pits'] = driver.find_element_by_id(f'i_{d}_pits').text
        driverList[int(d)]['Tyres'] = driver.find_element_by_id(f'i_{d}_tyres').text
        driverList[int(d)]['S1'] = driver.find_element_by_id(f'i_{d}_s1').text
        driverList[int(d)]['S2'] = driver.find_element_by_id(f'i_{d}_s2').text
        driverList[int(d)]['S3'] = driver.find_element_by_id(f'i_{d}_s3').text
        driverList[int(d)]['Laptime'] = driver.find_element_by_id(f'i_{d}_t').text


text:
Q: I am using Xcode 3.2.5. I have iAds running. Confused about about targest, iOs versions Trying to keep up with the curve. I'm reading almost too much and is sending me in a tail spin.  Is there a one stop link which will tell me what my target should be to run my app on all platforms based on what frameworks I have included? I make heavy use of Mapkit, and want to include iAds. My current apps seem dead on 3G.
Does Apple force you to support only the latest iOS? I have no problem with that, but not sure if someone who has and ancient 3G, how do I tell them, NO I don't support your phone, please upgrade?

A: Set your project's base SDK to the latest version of the SDK. Set the deployment target to the oldest version of the OS that you plan to support. You can use features introduced in versions later than your deployment target, but you'll need to check for them before you use them, else your app will crash.
Read the release notes for each version of the OS to get a good idea of what features were introduced when. In fact, make it a habit to read the release notes thoroughly each time a new version comes out.
iOS 4.2 runs pretty well on an iPhone 3G, so there's no need to drop support for the 3G anytime soon. If your apps currently don't work on the 3G, fire up your debugger and figure out why. What version of iOS are you running on that device? Where does it crash? This is typical debugging stuff.


text:
Q: Alert: Behavior:EC2/NetworkPortUnusual use port:80 to AWS S3 Webpage The other day, I received the following alert in GuardDuty.
Behavior:EC2/NetworkPortUnusual
port:80
Target:3.5.154.156
The EC2 that was the target of the alert was not being used for anything in particular. (However, it had been started up.)
There was no communication using port 80 until now.
Also, the IPAddress of the Target seems to be AWS S3.
The only recent change is that I recently deleted the EC2 InstanceProfile.
Therefore, there is currently no InstanceProfile attached to anything.
Do you know why this EC2 suddenly tried to use port 80 to communicate with the S3 page?
I looked at CloudTrail, etc., and found nothing suspicious.
(If there are any other items I should check, please let me know.)
Thankyou.

A: We have experienced similar alerts and after tedious debugging we found that SSM agent is responsible for this kind of GuardDuty findings.
SSM Agent communications with AWS managed S3 buckets
"In the course of performing various Systems Manager operations, AWS Systems Manager Agent (SSM Agent) accesses a number of Amazon Simple Storage Service (Amazon S3) buckets. These S3 buckets are publicly accessible, and by default, SSM Agent connects to them using HTTP calls."
I suggest to review CloudTrail logs and look for "UpdateInstanceInformation" event (this is how we found it eventually)


text:
Q: How to add several jars to module path? I am having the following situation:
Module Address:
module org.abondar.experimental.address {
    exports org.abondar.experimental.address;
}

Module Person:
module org.abondar.experimental.person {
    requires org.abondar.experimental.address;
    exports org.abondar.experimental.person;
}

I am building them using Maven, so every module has it's own target dir with jar file.
I am trying to run module Person which has main class like this
java --module-path Address/target/Address-1.0.jar;Person/target/Person-1.0.jar -m org.abondar.experimental.person/org.abondar.experimental.person.Main

But I am getting permission denied. How do I need to set up module path including several modules?

A: Well trying this on one of my projects with MacOS, I almost ended up with something similar as this -

zsh: permission denied: .../.m2/repository/test/test/1.0.0-SNAPSHOT/test-1.0.0-SNAPSHOT.jar
zsh: permission denied: .../.m2/repository/org/slf4j/slf4j-log4j12/1.7.12/slf4j-log4j12-1.7.12.jar
zsh: permission denied: .../.m2/repository/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar

The reason for that error is that the paths to the JARs are specified as a command to be executed on MacOS instead.
If you consider the module path as a list of directories for MacOS(might be Unix in general) it doesn't match the java tool documentation. Instead what you could seek for is
java --help

which states

--module-path <module path> ...
                    A : separated list of directories, each directory
                    is a directory of modules.

and in that case the command that shall work for you shall be :-
java --module-path Address/target/Address-1.0.jar:Person/target/Person-1.0.jar -m org.abondar.experimental.person/org.abondar.experimental.person.Main


text:
Q: IIS express, access to large video I'm using IIS Express, which installed with VS17.
Currently i'm developing asp.net mvc application, which allows users to upload large videos (e.g. 1.5 hours and 4 GB).
For develop i'm using git.
Situation:
In last release my web app allows to play videos on iis (by direct link, e.g. localhost:PORT/Videos/FILENAME.mp4) - these vids are uploaded from users;
From last release i made some changes, which doesn't touch IIS configuration and video module.
But i've got error: Now when i'm tryin' to play video by direct link i'm getting nothing (default html player cant play video [image])
And in dev console (chrome) message:

Resource interpreted as Document but transferred with MIME type video/mp4: "http://localhost:PORT/Videos/FILENAME.mp4"

Video file is OK (not corrupted).

A: I had this same problem with IIS Express and VS 2017 on Chrome. Other browsers play the video fine. I tried to isolate the issue and created a single html page with just a video tag. Chrome will play the video if you open the HTML directly without using IIS Express.
After that I just moved the project from IIS Express to IIS and the problem was solved.
If you can, move it to IIS. The issue I believe is with IIS Express only.


text:
Q: How to get a diameter of circle from based on its flattened width I have a problem here where-in heat shrink tube that im going to buy are sold classified by its flattened width, now this makes it hard for me to determine if the one im going to choose will fit on where i will place them as wires cannot just be simply flattened and i can ruler them up.
How would i extrapolate the radius/diameter of tube if for example the tube is advertised to have a flattend width of 6mm. What formula would i use ?

A: I think this can be solved using only basic circle geometry formulas.
The flattened width of the tube is half the circumference of the tube, and we can relate the circumference of the circle to the diameter. If $w$ is the flattened width and $d$ is the diameter,
we have $2w=\pi d$, so $d=\frac{2w}{\pi}$
In your example, the diameter of a 6 mm wide flattened tube is approximately $3.82$ mm


text:
Q: the choosing of an independent set in a specific $k$-partite graph Let $k\geq2$ be an integer, a graph $G=(V,E)$ is called $k$-partite if $V$ admits a partition into $k$ classes such that every edge of $G$ has its ends in different classes: vertices in the same class must not be adjacent.
Now let $G=(V,E)$ be $k$-partite and $V_1,V_2,\cdots,V_k$ be the $k$ classes into which $V$ Is partitioned such that:
$(1)\Delta (G)=2;$
$(2)|V_i|=3,i=1,2,\cdots,k;$
$(3)$For any $1\leq i\neq j\leq k$, there does not exist $u\in V_i$ and $v,w\in V_j$ such that $u$ are adjacent with both $u$ and $w$.
I want to ask if I can choose $v_i$ from $V_i, i=1,2,\cdots,k$ such that $\{v_1,v_2,\cdots,v_k\}$ is an independent set in $G$.


text:
Q: GoLang Gin - Binding JSON data from POST request rewrites all Identifier Fields to 0 I am taking my first steps with GoLang, and currently setting up an API Server, which is able to read JSON file from POST Request and save that to Memory.
I have a JSON File as Following:
[
    {
        "id": 0,
        "name": "kubernetes",
        "uri": "https://github.com/kubernetes/kubernetes"
    },
    {
        "id": 1,
        "name": "jenkins",
        "uri": "https://github.com/jenkinsci/jenkins"
    }
]

Which I am POST:ing to the API Server running on local port.
Here is my setupRoutes() - function:
func setupRoutes() {

    // Initialize Router
    router := gin.Default()

    // Initialize Routes
    router.GET("/api/projects", getProjects)
    router.GET("/api/projects/:id", getProjectByIdentifier)
    router.POST("/api/projects", uploadProjects)

    // Start the Router
    router.Run("localhost:8080")
}

and here is my uploadProjects() - function:
// Reads file from POST request, and saves that to Memory.
func uploadProjects(c *gin.Context) {

    // Initialize Object
    var obj []Project

    // Bind JSON Data to Object
    c.BindJSON(&obj)

    fmt.Println(obj) // For Testing: What is binded.

    // Save Data to Memory
    proj = obj

}
and here is the Project Struct:
type Project struct {
    Identifier int64    `json: id`
    Name string         `json: name`
    Uri string          `json: uri`
}

After executing this - I can print that data out right away, what is being binded or I can fetch that with my GET /api/projects - call, and the result is always:
[{0 kubernetes https://github.com/kubernetes/kubernetes} {0 jenkins https://github.com/jenkinsci/jenkins}]

What I've tried:

*

*I've tried to swap between string, int and int64 types of Identifier Field in my struct.

*Googled a Bunch

This is probably something very simple, but I don't really know where to look at this point, so any help is appreciated.

A: The id field does not match the field name Identifier.  Fix by using properly formatted JSON field tags.  The field tags used in the question are not recognized by the JSON codec.
type Project struct {
    Identifier int64    `json:"id"`
    Name string         `json:"name"`
    Uri string          `json:"uri"`
}


text:
Q: Parallel Axis Theorem Proof
I've gotten close to proving the theorem.
I began as follows $$ I = \int (n\times(r-a))\cdot(n\times(r-a)) dm $$
$$ = \int (n\times r  - n\times a)\cdot(n\times r  - n\times a) dm$$
$$ = \int (n\times r)\cdot(n\times r) dm\space - 2\int (n\cdot n )(r\cdot a) - (n\cdot r)(n\cdot a)dm \space + \int a^2 - (n\cdot a)^2 dm$$
Where I used Lagrange's Identity in the second and third Integrals, we continue by substituting the first integral and noting that $a_\perp^2 = a^2 - (n\cdot a)^2$ and that $(n\cdot n ) =1$
$$  = I_0 +\int a_\perp^2 dm \space -2\int (r\cdot a) - (n\cdot r)(n\cdot a)dm$$
$$  = I_0 +Ma_\perp^2 -2\int (r\cdot a) - (n\cdot r)(n\cdot a)dm$$
Now it seems to me that the final integral is $0$, but I don't know how to show it.


text:
Q: How to get Row count by dynamically passing the table name create procedure qa_cc
@tablename varchar(500)

AS

BEGIN
    -- Create two integer values
DECLARE @tableOneCount varchar(50), @tableTwoCount varchar(50)

-- Get the number of rows from the first table
SELECT @tableOneCount = 'SELECT COUNT(*) FROM'  + @tablename;
    exec (@tableOneCount);

select      @tableOneCount  ;

END

exec qa_cc @tablename=table1

A: You could use sp_executesql, like:
declare @sql nvarchar(max);
set @sql = N'select @cnt = count(*) from ' + @tablename;
declare @cnt int;
exec sp_executesql @sql, N'@cnt int output', @cnt = @cnt output;
select @cnt;

A: SELECT SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 and ta.name=@tablename
 GROUP BY ta.name

See http://blog.sqlauthority.com/2010/09/08/sql-server-find-row-count-in-table-find-largest-table-in-database-part-2/

A: Looks like you were missing a space after the FROM keyword which was reading FROMTABLE rather than FROM Table
DECLARE @TABLE NVARCHAR(100)
SET @TABLE = 'CLIENT' -- YOUR TABLE NAME

EXEC('SELECT COUNT(*) FROM ' + @TABLE)

A: CREATE PROCEDURE [dbo].[TableRowCount]
@tableName text
AS
EXEC ('SELECT COUNT(*) FROM ' + @tableName)
RETURN @@ROWCOUNT

I hope that helps. Thank you.


text:
Q: Mean amplitude value in EMG signal I have an EMG-signal and would like to get the mean value of the amplitude in a defined frequency space. I tried making FFT, but i don't get a vector with amplitudes and frequencies. I am new to Matlab - please help.

A: Here is how you would get power (i.e., amplitude) and frequency from the fft function in Matlab:
fs = 1024; % sampling rate of signal
time = 1; % time in sec of simulated signal
xn = randn (fs*time,1); % creating random signal
nfft = time*fs; % size of window on which to perform FFT
Y = fft (xn, nfft);
% Convert value to obtain the power of the signal at
% each frequency
Pyy = Y .* conj(Y) / nfft;
% Create a frequency axis for ploting
fy = fs/nfft * (0:(nfft/2) -1);

plot (fy, Pyy(1:nfft/2))
ylabel ('power (AU)^2') % arbitrary units
xlabel ('frequency (Hz)')
xlim ([0 512])

However, keep in mind that EMG is not a stationary signal. When doing spectral analysis on EMG signals we are trying to approximate the true spectrum. This is why EMG is usually seperated into windows of data. FFT is performed on each of these windows and the averaged.
Rather than using the fft function, you might want to consider using the pwelch function in the Matlab Signal Processing Toolbox. It allows you to set the window size, amount of overlap of the windows, etc.
Alternatively you could use the very popular Neurospec Matlab toolbox writen by David Halliday. It has a PDF that describes all the functions and examples you can use. It has additional functionality (e.g., coherence), but you can ignore it if you like and simply extract the spectral data.


text:
Q: Use notification Data in background I am using Firebas mesaging service class. and Its working properly when app is running in foreground but when i clear this application from recent i am not able to access  the push notification data for setting it on textview.
I want to store data in database when app is running in background.
I had Used Database to store the value directly but its not working.
 public void onMessageReceived(RemoteMessage message) {

    database=new SQLiteHelper(getApplicationContext());
    database.open();
    String image = message.getNotification().getIcon();
    String title = message.getNotification().getTitle();
    String text = message.getNotification().getBody();
    String sound = message.getNotification().getSound();
    int id = 0;
    database.addQuotes(text,"Xyz");

}
In MainActivity.java in Oncreate method
  Bundle extras = getIntent().getExtras();
    if (extras != null) {
        final String message = extras.getString("message");
        quote_text.setText(message);
        Toast.makeText(this, "A", Toast.LENGTH_SHORT).show();
    }

But message shows null data.

A: based on this:

I want to store data in database when app is running in background

The service calls which extends FirebaseMessagingService has a method called onMessageReceived which is called when a push notification is received on the front-end (app) add your message to DB there!
@Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
 .....
// parse and add your message to Db here!

A: Normally when your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
But you can refer this answer on stackoverflow if you want to get notification data-messages in your app while in background.
You may also refer this


text:
Q: Multiselect enable option does not work in jQuery

$(document).ready(function() {
  $('#fruits').multiselect({
    name: 'fruits',
    columns: 1,
    placeholder: 'fruits'
  });
  $('#fruits').multiselect('disable');

  $("#changeStatuss").click(function() {
    $("#fruits").multiselect('enable');

  });
});

FRUITS

  <select name="fruits" multiple id="fruits">
    <option value="mango">mango</option>
    <option value="apple">apple</option>
    <option value="orange">orange</option>
  </select>

<input type="button" id="changeStatuss" value="try me" />

When we run the disable option it works fine, the dropdown gets disabled, but enable option on any event trigger is not happening.
I tried other posts with the same problem but still no use.
I also tried refreshing the plugin after the enable option but again no use.

A: You could do this:
$('#fruits option').removeAttr('disabled');

A: Its working fine for me , Here is example:

$(function() {
  $('#fruits').multiselect({
    name: 'fruits',
    columns: 1,
    placeholder: 'fruits'
  });
  $('#fruits').multiselect('disable');

  $("#changeStatuss").click(function() {
    $("#fruits").multiselect('enable');

  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">

FRUITS

  <select name="fruits" id="fruits" multiple="multiple" disabled="disabled">
    <option value="mango">mango</option>
    <option value="apple">apple</option>
    <option value="orange">orange</option>
</select>

<input type="button" id="changeStatuss" value="try me" />


text:
Q: Knowing Privilege rights on a file in Linux i wanted to know the Read / Write Access on to a file , so i did this way
ls -l Denem.sh

This command displayed
-rwxr-xr-x  1 pavan employee 672 DEC 20  2000 pavan.sh

Could anybody please tell me what -rwxr-xr-x  indicates ??
From Wikipedia.com i found that  -rwxr-xr-x  indicates

-rwxr-xr-x
  for a regular file whose user class has full permissions and whose group and others classes have only the read and execute permissions.

Now my  question is Should we take the middle thing (-xr-) into considiration ??

A: Divide it up like this:
- rwx r-x r-x

It's owner, group, others. So the owner (pavan) can read, write, and execute; people in the group employee can read and execute, but not write; anyone else can also read and execute but not write.
The - in front would be d for a directory, l for a symbolic link, etc. man ls.

A: This string:
-rwxr-xr-x

Is separated into four sections:
-    indicates what kind of file it is
rwx  (first 3) owner permissions
r-x  (second 3) group permissions
r-x  (last 3) other permissions

All together, this string is supposed to provide (at a glance) the most important aspects of a file. Namely what it is and who can do what with it.

First Section
The first character in the string is reserved for the file type. Any regular old file will simply have a - in this position. Other include:
d directory
p pipe/fifo
l link
c character device file
b block device file
s local domain socket

So a pipe might look like this:
prwx------ root root filename

Second - Third - Fourth Section
The next 9 bits describe the permissions that everyone has when it comes to this file. There are three types of permissions:
r read (opening the file for reading, can't save changes)
w write (change the contents of file)
x execute (run the file, like a script or binary)

And there are three groups to which these permissions may be applied to:
owner whoever owns the file (as seen by the output of ls -l)
group whoever is part of the group owner of this file
others anyone who doesn't fall in either of the two above categories

For example:
-rwxr-xr-x  1 pavan employee 672 DEC 20  2000 pavan.sh
pavan is the owner
employee is the group owner name
anyone else falls into "others"

Referring to the above example, if we want to make pavan have full control over the file, let anyone in the employee group to read or execute the file and block all permissions to others:
-rwxr-x---

The numbers
The reason permissions are sometimes represented with numbers is that it is generally easier to use an octal representation of the 9 bits (I still prefer straight up rwx).
To understand what the numbers mean you need to build a table (if you've ever done work with binary this will help):
#  r  w  x
0  0  0  0
1  0  0  1
2  0  1  0
3  0  1  1
4  1  0  0
5  1  0  1
6  1  1  0
7  1  1  1

You refer to this chart for each set of three bits. For example, if I decide to give the owner of the file complete control (r,w and x), only read for the group and also only read for others:
rwx owner corresponds to 7 in the table
r-- group corresponds to 4 in the table
r-- other corresponds to 4 in the table
Therefore my file has permissions 744


text:
Q: Getting Values from array - Javascript Trying my best, but still not able to log the result at the end.
var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

function foo(arr) {
    var a = [], b = [], prev;

    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

var result = foo(arr);
var a = result[0]
var b = result[1]
var aa=a.split(",");
var ab=b.split(",");
var a = a.split(",").length;
var b = b.split(",").length;
for (c = 0; c < a; c++){
console.log(aa[c]);
console.log(ab[c]);}

I want to get values from two array result[0] and result[1] one by one in the loop.
Right now I am able to get all the values comma separated but when I split values, nothing shows up.

A: You can create an empty object to track the number of repetitions & an array to hold only unique values.Use indexOf to find if element already exist in uniqArray.

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];
var repCount = {}, // to track number of repetitions
  uniqArray = []; // holds only unique values

arr.forEach(function(item) {
  if (uniqArray.indexOf(item) == -1) {
   // id item is not present push it
    uniqArray.push(item)
  }
  // check if the object already have a key for example 2,4,5,9
  if (!repCount.hasOwnProperty(item)) {
    repCount[item] = 1 // if not then create new key
  } else {
    // if it is there then increase the count
    repCount[item] = repCount[item] + 1
  }
})
console.log(uniqArray, repCount)

A: Looking at your comment...

So basically i want to get the unique no. from array and the no. of repetition of that particular value into another variable

You can achieve this by using reduce function

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];
var a = arr.reduce(function (acc, next) {
  acc[next] = acc[next] ? acc[next] + 1 : 1;
  return acc;
}, {});

console.log(a);

which gives you a hash with unique numbers as keys and their counts as values. From here you can easily break it into two arrays if you really need to..

A: You were almost there:

    var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

    function foo(arr) {
        var a = [], b = [], prev;

        arr.sort();
        for ( var i = 0; i < arr.length; i++ ) {
            if ( arr[i] !== prev ) {
                a.push(arr[i]);
                b.push(1);
            } else {
                b[b.length-1]++;
            }
            prev = arr[i];
        }

        return [a, b];
    }

    var result = foo(arr);
    var a = result[0]
    var b = result[1]
    for (i=0; i<a.length; i++){
      console.log("Number: " + a[i] + "; Time repeated:"+ b[i]); }


text:
Q: listview get distrubed after search. (Data show at bottom)

data get from the local database after searching. i am getting this view.
try{
            DatabaseHandler db=new DatabaseHandler(getApplicationContext());
            retailers=new ArrayList<HashMap<String, String>>();
            String str=str_search[0];
            retailers=db.getRetailers(str);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        // Keys used in Hashmap
        String[] from = {"id","shop_name","address"};

        // Ids of views in listview_layout
        int[] to = {R.id.id,R.id.shopname,R.id.address};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item

        ListAdapter adapter = new SimpleAdapter(RetailersListActivity.this,retailers, R.layout.retailer_list_item, from, to);

        return adapter;

is this problem related to listview or some coading problem
plz help!!!

A: I think in your xml file you are setting ListView above the bottom Layout so try to set you xml layout like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    //here your search layout should be android:layout_alignParentTop="true"

     <ListView
            android:id="@+id/attendanceList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/your_search_layout"
            android:layout_above="@+id/your_bottom_layout" >
     </ListView>

    //here your bottom layout should be android:layout_alignParentBottom="true"

</RelativeLayout>

Hope this scenario whould help you...


text:
Q: How to add a bullet point to the start of sentence text in UITextView? I have one UITextView for which text will change according to the selection by user.
Now I want to add a bullet at the start of every sentence. How would this be achieved?
Thanks a lot in advance.

A: check this code described in this thread Bullet list and Numbered list in UITextView,
NSArray * items = [[NSArray alloc] initWithObjects:@"Mittal",@"Seema",@"Sonal", nil];
NSMutableString * bulletList = [NSMutableString stringWithCapacity:items.count*30];
for (NSString * s in items)
{
    [bulletList appendFormat:@"\u2022 %@\n", s];
}

A: I should you must look into this link. It will contain how to display the numbered list in UITextView .
There is also one more link i want to tell you.


text:
Q: How Can I Recreate the CUPS _lpadmin (Print Administrator) group in MacOS X? I was following this advice to add a user to the _lpadmin group on my system to stop getting a prompt to authenticate when trying to change print options.
Unfortunately, I clicked in the wrong place while using Directory Utility and deleted the entire Print Administrator group.
Now, no users on my system have privileges to change print options or reset the printing system, because none of the users are members of the group that no longer exists.
I tried creating the group "_lpadmin" manually in Directory Services, to no avail. Using the dseditgroup command to add a user to the group returns "Group not found."
Is there a way to reinstall the default CUPS system without reinstalling my entire OS?


text:
Q: Fading in two directions with unshaded middle - Faded rectangles create "lines at boundaries" I'd like to do some fading of my background page from the middle to top and bottom - so far as good. My Problem is that I don't want to start the fading immediatly (e.g. the upper third is faded, the middle third is background color, the lower third is faded).
So my suggestions are two ways:
a) Manipulate somehow the fading speed (I read the corresponding thread but was not able to do the necessary adjustments) and work with "color top", "color bottom", and "color middle".
b) Draw two rectangles at the top and the bottom which are faded in one direction.
My problem: While a) looks "good" but has no extended middle background color part, b) creates some mysterious lines in my output file at the boundaries (the lines are not printed in texmaker but in all of my pdf viewers):

Below a minimal working example for version b:
\documentclass{report}
\usepackage{tikz}
\usetikzlibrary{calc,fadings}
\definecolor{colorBackground}{RGB}{65,110,131}

\begin{document}

\begin{tikzpicture}[remember picture,overlay]
  \fill[color=colorBackground] (current page.north west) rectangle (current page.south east);
  \fill[top color=colorBackground!0, bottom color=colorBackground] (current page.north west) rectangle ($(current page.north west)+(\paperwidth,-10cm)$);
  \fill[top color=colorBackground, bottom color=colorBackground!0] (current page.south west) rectangle ($(current page.south west)+(\paperwidth,+10cm)$);
\end{tikzpicture}

\end{document}

Kind regards!

A: I cannot reproduce the lines you describe and they are likely a viewer artefact. If your document will be printed, that's not a big deal. Otherwise, you might see if this works any better. You will need to adjust the specific points at which the shading changes. I don't know what paper you are using, so I'm not sure what is needed for 10cm. However, I think that you want to change colour at (25bp-(10cm/\paperheight)*50bp) and (75bp-(10cm/\paperheight)*50bp). The shading should total 100bp by 100bp. Only the middle ninth of it will be used i.e. the middle third vertically and the middle third horizontally. So imagine a square divided into thirds horizontally and vertically. Your square needs to be 100bp in length and the middle square will be the bit actually used.
That is, that bit will be used in this case. If you were rotating it or something, it gets more complicated. But you're not rotating it, so it is (relatively!) straightforward.
\documentclass{report}
\usepackage{tikz}
\definecolor{colorBackground}{RGB}{65,110,131}

\begin{document}

\pgfdeclareverticalshading[colorBackground]{pageshade}{100bp}{%
  color(0bp)=(white);
  color(25bp)=(white);
  color(40bp)=(colorBackground);
  color(60bp)=(colorBackground);
  color(75bp)=(white);
  color(100bp)=(white)
}

\begin{tikzpicture}[remember picture, overlay]
  \shade [shading=pageshade] (current page.north east) rectangle (current page.south west);
\end{tikzpicture}

\end{document}


text:
Q: Show that if $3\mid(a^2+1)$ then $3$ does not divide $(a+1)$. Show that if $3\mid(a^2+1)$ then $3$ does not divide $(a+1)$.
using proof of contradiction
can someone prove this using contradiction method please

A: For the original question, if $3 \nmid a$, then $3 \nmid a^2$ since $3$ is prime (consider the factorization of $a$ and $a^2$), but this doesn't imply anything about whether $3$ divides $a^2 + 1$.
Here's a different approach: Suppose $3$ is a divisor of both $a^2 + 1$ and $a + 1$. Can you justify why $$3 \mid \Big( a(a + 1) - (a^2 + 1)\Big) = a$$
and why that's a contradiction?

A: $3\mid \color{blue}{a^2\!+\!1},\,\color{#0a0}{a\!+\!1}\,\Rightarrow\,3\mid\color{blue}{a^2\!+\!1}-\overbrace{(\color{#0a0}{a\!+\!1})(a\!-\!1)}^{\large a^2\,-\,1} = \color{#c00}2,\,$ a contradiction, completing your proof.
Or modly: $\ 3\mid a\!+\!1\,\Rightarrow\, {\rm mod}\ 3\!:\ a\equiv -1\,\Rightarrow\ a^2\!+\!1\equiv \color{#c00}2\,\Rightarrow\,3\nmid a^2\!+\!1$
Remark $\ $ The first proof shows more generally that $\,\gcd(a^2+1,a+1)\mid 2.\,$ Using parity  we see further that the gcd $= 2 \iff a$ is odd; otherwise the gcd $= 1\ \ (\!\iff a\,$ is even$)$.

A: Prove the contrapositive:

If $3\mid a+1$, then $3\nmid a^2+1$.

Which is easy, because then $a=3k-1$ and $a^2+1=9k^2-6k+2$, which isn't divisible by $3$.

A: Hint: just consider the 3 cases
$$a = 3k, a=3k+1, a=3k-1
$$


text:
Q: ViewRef is undefined when component gets initialized on "browser back" action I have a component which contains <ng-template #placeholder></ng-template> in its template to insert components dynamically. In OnInit a "loadComponents" method is called which uses the viewRef, but is unable on the second time it loads:
@ViewChild("placeholder", { read: ViewContainerRef, static: false })
private viewRef: ViewContainerRef;

private loadComponents() {
    if (this.viewRef) {
      this.viewRef.clear();
      this.criteria.forEach((criterion) => {
        if (Object.keys(this.componentMap).includes(criterion.type)) {
          const componentFactory = this.cfr.resolveComponentFactory(
            this.componentMap[criterion.type]
          );
          const componentRef = this.viewRef.createComponent(componentFactory);
        }
      });
    }
  }

This component is a form for a search component which it includes.
After starting the search, the search component shows the data below and has links to the detail views. But when I open the detail view and go back to the search page -- which holds the search criteria in a store -- the viewRef is undefined.
When I check it "later" with the Angular Tools then viewRef is defined. So I guess it is injected after OnInit.
Any ideas how to fix this?

A: I've got a solution. I created a new sub component which wraps the placeholder. I did not need ChangeDetection OnPush in the view ref. But the loadComponents not gets triggered in ngOnChanges.


text:
Q: SQL Server 2012 String splitting I have this table on my database that's filled with big strings, and I'm trying to analyze the text thats in those strings.
I have something like this.
On August the third the pope talked on vatican square.... bla bla

What I want to know is something like this
Word   | Count
ON     | 2
August | 1
the    | 2
third  | 1

and so one, I know I would have to break those string and find the blank spaces " ", ",", ". " and so on so that the function knows that is a word just before that and after is the string < length.
The results should go to a new table, as showned above.
How exactly would I achieve that with a SQL function?

A: You could split and count:
DECLARE @t NVARCHAR(400)='On August the third the pope talked on vatican square.'

;WITH tally AS
(
  SELECT TOP 1000  rn = ROW_NUMBER() OVER(ORDER BY 1/0)
  FROM master..spt_values
), cte AS(
SELECT REPLACE(REPLACE(SUBSTRING(' ' + @t + ' ', rn + 1,
CHARINDEX(' ', ',' + @t + ' ', rn + 1) - rn -1),'.', ''), ',','') AS word
FROM tally
WHERE rn <= LEN(' ' + @t + ' ') - 1
    AND SUBSTRING(' ' + @t + ' ', rn, 1) = ' '
)
SELECT word, COUNT(*) AS total
FROM cte
GROUP BY word;

LiveDemo
Output:
╔═════════╦═══════╗
║  word   ║ total ║
╠═════════╬═══════╣
║ August  ║     1 ║
║ On      ║     2 ║
║ pope    ║     1 ║
║ square  ║     1 ║
║ talked  ║     1 ║
║ the     ║     2 ║
║ third   ║     1 ║
║ vatican ║     1 ║
╚═════════╩═══════╝

A: DECLARE @text NVARCHAR(MAX) = 'On August the third the pope talked on vatican square.... bla bla'

SELECT t.display_term, COUNT(*)
FROM sys.dm_fts_parser('"' + @text + '"', 1049, NULL, 1) t
WHERE t.special_term = 'Exact Match'
GROUP BY t.display_term

Output -
--------------- -----------
august          1
bla             2
on              2
pope            1
square          1
talked          1
the             2
third           1
vatican         1


text:
Q: The system returned: (104) connection reset by peer Facing a squid error. This is the error message we are getting.
Read Error
'The system returned: (104) connection reset by peer.
Our web product is hosted on godaddy. The whole website is working completely alright except this one page on which we are facing the error.
the page times out exactly after the 15 secs.
On testing the same page on localhost it works completely alright, but the same page when tested on server is timed out.
Can anybody suggest us an solution?
Breaking our heads from past many hours.
thanks in advance.
link for the page we are getting the error : http://silicongem.com/rhea/testrd.php
for authentication you can use username: demo
                               password: demo1
Snapshot:

A: Well my servers were not upto the mark. I had to change the server. Since, old servers were not able to compute too many operations in few seconds.

A: Some time a bad Squid config can also cause this. Please check if you have correct memory config defined. These are few important settings to keep your Squid healthy -
max_stale 24 hour
cache_mem 1500 MB
memory_replacement_policy lru
cache_replacement_policy lru
cache_swap_low 93
cache_swap_high 97
positive_dns_ttl 24 hours
negative_dns_ttl 1 minute
quick_abort_min 0 KB
quick_abort_max 0 KB

You may find documentation here by replacing each directive at the end -
http://www.squid-cache.org/Doc/config/cache_swap_low/


text:
Q: What should I fill in for not so urgent field in db? I have a db schema which requires linkedin url of the people signing up. I dont want them to fill the linkedin id on signup itself, they are free to add it at dashboard. Below given is the code for the model
const master = mongoose.model('master', new mongoose.Schema({
  firstName: {type: String, required: true, unique: false},
  lastName: {type: String, required: true, unique: false},
  email:  {type: String, required: true, unique: true },
  linkedinUrl:  {type: String, required: false, unique: false },
  password: {type: String, required: true, unique: false}
},{strict: true}))

When I leave the field empty more than once, the db returns me an error
error: "{"driver":true,"name":"MongoError","index":0,"code":11000,"errmsg":"E11000 duplicate key error collection: maindb.mentors index: linkedinUrl_1 dup key: { : \"\" }"}"

I realise that having multiple null value is an issue. What other value can I use to mask the empty field? Thank you


text:
Q: JSF 2.0 on a J2EE 1.4 compliant Application server Can I use a JSF 2.0 implemntation on a J2ee 1.4 server ( jboss 4.0.5 / 5.0 , Weblogic 9, WebSphere 6.1 )?
Are there any (free) implementation that runs well on all platforms?

A: No, that's not possible, because JSF 2.0 requires version 2.5 of the Servlet API, and J2EE 1.4 only supports Servlet 2.4. However, it is possible that a given concrete J2EE 1.4 implementation may support Servlet 2.5 anyway (but lack other components of Java EE 5).
I'm using Apache MyFaces and have no complaints, however I am not using it cross-platform. But I wouldn't expect issues in that regard; JSF is really just a framework built on top of the Servlet API and doesn't do anything remotely platform-specific.


text:
Q: Conditional sentences using had
Had you read Betty Azar carefully, you were able to persuade your tutor.

Is this sentence correct? or should it be:

Had you read Betty Azar carefully, you would be able to persuade your tutor.

I mean a mixed conditional. If so , can we bring mixed conditionals with had?

A: The first sentence is not grammatically correct.  If you want to use the conditional, you have to use one of the conditional tenses.
Your second sentence is fine. Here, "would" implies the condition of "being able to persuade the tutor". I don't think there is much of a difference in grammar between the structures "If A had (done) B" and "Had A (done) B":

If you had bought the stock back then, you would be rich today.
Had you bought the stock back then, you would be rich today.

so if you are confused about how to start the conditional with "had" just write it starting with "if" and then convert:

If you had got better grades, you would be making more money now.
Had you got better grades, you would be making more money now.

Your example is a little unclear to me because, presumably, you still have time to read Betty Azar if you want to persuade your tutor in the future.

If you read Betty Azar carefully, you will be able to persuade your tutor.

If your chance has already passed, then you should change to the past tense to indicate a missed opportunity:

Had you read Betty Azar carefully, you would have been able to persuade your tutor.


text:
Q: Facebook Graph API Search returning empty data Facebook search API returning empty data set since last couple of days. This worked fine for me till 2-3 days back.
The repro is consistent, even with the sample on Graph API developers page:
https://graph.facebook.com/search?q=watermelon&type=post
{
   "data": [
]
}
Any idea what's going on?
Thanks!

A: This looks like working now. Might be a temp issue.


text:
Q: ffmpeg - How to use all the CPU of the server? I am using this command to run ffmpeg -
ffmpeg -i -  -isync  -threads 16  -vcodec libx264 -acodec aac -ar 22050 -r 25 -s 640x360 -strict experimental  -b:a 32k -b:v 100k -f flv "rtmp://"  -threads 16  -vcodec libx264 -acodec aac -ar 22050 -r 25 -s 640x360 -strict experimental  -b:a 32k -b:v 400k -f flv "rtmp://"

I am running ffmpeg processes on my server. Currently ffmpeg don't use all my CPU, I want to use all my CPU usage.
My server has 24 CPU, 16 GB RAM, and 1 TB HDD. Please tell me the command to use all my CPU usage, and to make my ffmpeg smooth.
Thanks

A: 0% idle and 0% wait. That is using 100% of your CPU. Your computer is just not powerful enough to process 20 videos simultaneously. You can try adding the 'ultrafast' option to use less CPU per encode (at the price of lower quality)


text:
Q: Matching up form post array values after form submission in PHP I have a form:
<form action="index.php" method="post">

with multiple selection inputs
<select class="form-control" id="location" name="location[]" >
<option selected disabled value="">Choose Location</option>
<option value="closing">Closing Station</option>
<option value="device">Device/ROF</option>
<option value="merch1">General Merch 1</option>
<option value="merch2">General Merch 2</option>
</select>
<input type="hidden" name="image_name[]" value="<?php echo $file; ?>" />

I have this array upon form submission:
Array (
    [location] => Array (
    [0] => closing
    [1] => merch1
    [2] => merch2 )

    [image] => Array (
    [0] => AL-AL.jpg
    [1] => AL-AN.jpg
    [2] => AL-AV.jpg
    [3] => AL-CA.jpg
    [4] => AL-CL.jpg
    [5] => AL-CM.jpg )

    [submit] => Submit
)

I want the output in PHP to be like this: location[0] and image[0], etc:
this is my code:
<?php
            if (isset($_POST['submit'])){
                 foreach ($_POST['location'] as $location) {
                foreach ($_POST['image_name'] as $image) {
    echo "you have selected $image to go to this location: $location
";
                            }
                        }
                    }
            }
?>

This is currently outputting:
you have selected AL-AL.jpg to go to this location: closing
you have selected AL-AN.jpg to go to this location: closing
you have selected AL-AV.jpg to go to this location: closing
you have selected AL-CA.jpg to go to this location: closing
you have selected AL-CL.jpg to go to this location: closing
you have selected AL-CM.jpg to go to this location: closing
you have selected AL-AL.jpg to go to this location: merch2
you have selected AL-AN.jpg to go to this location: merch2
you have selected AL-AV.jpg to go to this location: merch2
you have selected AL-CA.jpg to go to this location: merch2
you have selected AL-CL.jpg to go to this location: merch2
you have selected AL-CM.jpg to go to this location: merch2

it just seems to be an eternal loop right now. I know there is a way to match up each array on the []values and then only output where there are matches, but I can't figure it out.

A: no need for the 2 loops, use the key from location to find the image
<?php
$p['location'][0]='closing';
$p['location'][1]='merch1';
$p['location'][2]='merch2';

$p['image'][0]='AL-AL.jpg';
$p['image'][1]='AL-AN.jpg';
$p['image'][2]= 'AL-AV.jpg';

foreach($p['location'] as $k=>$v ){
echo "you have selected ".$p['image'][$k]." to go to this location: $v
";
}

?>

Output:

you have selected AL-AL.jpg to go to this location: closing  you
  have selected AL-AN.jpg to go to this location: merch1  you have
  selected AL-AV.jpg to go to this location: merch2


text:
Q: How to split pdf file by book marks using itext 7 , if pdf contains "Duplicate Bookmarks" I am trying to split pdf by its bookmarks using itext7.
Problem : if Pdf is having same bookmark in other place in the outline tree , it is over ridding and unable to split.
Sample code to reproduce the problem:
public void walkOutlines(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,List<String>titles,List<Integer>pageNum) { //----------loop traversing all paths

    for (PdfOutline child : outline.getAllChildren()){
        if(child.getDestination() != null) {
            prepareIndexFile(child,names,pdfDocument,titles,pageNum,list);
        }
    }
}

//------------Getting pageNumbers from outlines
public void prepareIndexFile(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,List<String>titles,List<Integer>pageNum) {

        String title = outline.getTitle();

        PdfDestination pdfDestination = outline.getDestination();
        String pdfStr = ((PdfString)pdfDestination.getPdfObject()).toUnicodeString();
        PdfArray array = (PdfArray) names.get(pdfStr);
        PdfObject pdfObj = array != null ? array.get(0) : null;

        Integer pageNumber = pdfDocument.getPageNumber((PdfDictionary)pdfObj);

        titles.add(title);
        pageNum.add(pageNumber);

        if(outline.getAllChildren().size() > 0) {

            for (PdfOutline child : outline.getAllChildren()){
                prepareIndexFile(child,names,pdfDocument,titles,pageNum);
            }

        }

}

public boolean splitPdf(String inputFile, final String outputFolder) {

        boolean splitSuccess = true;
        PdfDocument pdfDoc = null;
        try {
            PdfReader pdfReaderNew = new PdfReader(inputFile);
            pdfDoc = new PdfDocument(pdfReaderNew);

            final List<String> titles = new ArrayList<String>();
            List<Integer> pageNum = new ArrayList<Integer>();

            PdfNameTree destsTree = pdfDoc.getCatalog().getNameTree(PdfName.Dests);
            Map<String, PdfObject> names = destsTree.getNames();//--------------------------------------Core logic for getting names
            PdfOutline root = pdfDoc.getOutlines(false);//--------------------------------------Core logic for getting outlines

            walkOutlines(root,names, pdfDoc, titles, pageNum,content);  //------Logic to get bookmarks and pageNumbers

            if (titles == null || titles.size()==0) {
                splitSuccess = false;
            }else {                                                             //------Proceed if it has bookmarks

                for(int i=0;i<titles.size();i++) {

                     String title = titles.get(i);
                     String startPageNmStr =""+pageNum.get(i);
                     int startPage = Integer.parseInt(startPageNmStr);

                     int endPage = startPage;

                     if(i == titles.size() - 1) {
                         endPage = pdfDoc.getNumberOfPages();
                     }else {
                         int nextPage =  pageNum.get(i+1);
                         if(nextPage > startPage) {
                             endPage = nextPage - 1;
                         }else {
                             endPage = nextPage;
                         }
                     }

                     String outFileName = outputFolder + File.separator + getFileName(title) + ".pdf";
                     PdfWriter pdfWriter = new PdfWriter(outFileName);

                     PdfDocument newDocument = new PdfDocument(pdfWriter, new DocumentProperties().setEventCountingMetaInfo(null));
                     pdfDoc.copyPagesTo(startPage, endPage, newDocument);
                     newDocument.close();
                     pdfWriter.close();
                }
            }
        }catch(Exception e){
            //---log
        }
}

Found root cause: In PdfNameTree items.put(name.toUnicodeString(), names.get(k));
How to over come this issue?
Thanks in advance

A: This part of the code:
PdfDestination pdfDestination = outline.getDestination();
String pdfStr = ((PdfString)pdfDestination.getPdfObject()).toUnicodeString();
PdfArray array = (PdfArray) names.get(pdfStr);
PdfObject pdfObj = array != null ? array.get(0) : null;

Integer pageNumber = pdfDocument.getPageNumber((PdfDictionary)pdfObj);

Does not take into account the case that the destination can be non-named and refer to a page explicitly.
So the code needs to be adapted into the following code:
PdfDestination pdfDestination = outline.getDestination();
PdfObject pdfObj = null;
if (pdfDestination.getPdfObject().isString()) {
    String pdfStr = ((PdfString) pdfDestination.getPdfObject()).toUnicodeString();
    PdfArray array = (PdfArray) names.get(pdfStr);
    if (array != null) {
        pdfObj = array.get(0);
    }
} else if (pdfDestination.getPdfObject().isArray() && ((PdfArray)pdfDestination.getPdfObject()).get(0).isDictionary()) {
    pdfObj = ((PdfArray)pdfDestination.getPdfObject()).get(0);
}

Integer pageNumber = pdfDocument.getPageNumber((PdfDictionary)pdfObj);

Additionally, if you want to obtain the full title names including the parent chain, you need to replace String title = outline.getTitle(); with the following piece of code:
String title = outline.getTitle();
PdfOutline parentChain = outline.getParent();
while (parentChain != null) {
    title = parentChain.getTitle() + "." + title;
    parentChain = parentChain.getParent();
}

As a result, I got 6 files in the output directory, with 5 files of 1 page each and one file of 4 pages.

Complete code:
public void walkOutlines(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,
        java.util.List<String>titles,java.util.List<Integer>pageNum) { //----------loop traversing all paths

    for (PdfOutline child : outline.getAllChildren()){
        if(child.getDestination() != null) {
            prepareIndexFile(child,names,pdfDocument,titles,pageNum);
        }
    }
}

//------------Getting pageNumbers from outlines
public void prepareIndexFile(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,
        java.util.List<String>titles,java.util.List<Integer>pageNum) {

    String title = outline.getTitle();
    PdfOutline parentChain = outline.getParent();
    while (parentChain != null) {
        title = parentChain.getTitle() + "." + title;
        parentChain = parentChain.getParent();
    }

    PdfDestination pdfDestination = outline.getDestination();
    PdfObject pdfObj = null;
    if (pdfDestination.getPdfObject().isString()) {
        String pdfStr = ((PdfString) pdfDestination.getPdfObject()).toUnicodeString();
        PdfArray array = (PdfArray) names.get(pdfStr);
        if (array != null) {
            pdfObj = array.get(0);
        }
    } else if (pdfDestination.getPdfObject().isArray() && ((PdfArray)pdfDestination.getPdfObject()).get(0).isDictionary()) {
        pdfObj = ((PdfArray)pdfDestination.getPdfObject()).get(0);
    }

    Integer pageNumber = pdfDocument.getPageNumber((PdfDictionary)pdfObj);

    titles.add(title);
    pageNum.add(pageNumber);

    if(outline.getAllChildren().size() > 0) {

        for (PdfOutline child : outline.getAllChildren()){
            prepareIndexFile(child,names,pdfDocument,titles,pageNum);
        }

    }

}

public void splitPdf(String inputFile, final String outputFolder) {

    boolean splitSuccess = true;
    PdfDocument pdfDoc = null;
    try {
        PdfReader pdfReaderNew = new PdfReader(inputFile);
        pdfDoc = new PdfDocument(pdfReaderNew);

        final java.util.List<String> titles = new ArrayList<String>();
        java.util.List<Integer> pageNum = new ArrayList<Integer>();

        PdfNameTree destsTree = pdfDoc.getCatalog().getNameTree(PdfName.Dests);
        Map<String, PdfObject> names = destsTree.getNames();//--------------------------------------Core logic for getting names
        PdfOutline root = pdfDoc.getOutlines(false);//--------------------------------------Core logic for getting outlines

        walkOutlines(root,names, pdfDoc, titles, pageNum);  //------Logic to get bookmarks and pageNumbers

        if (titles == null || titles.size()==0) {
            splitSuccess = false;
        }else {                                                             //------Proceed if it has bookmarks

            for(int i=0;i<titles.size();i++) {

                String title = titles.get(i);
                String startPageNmStr =""+pageNum.get(i);
                int startPage = Integer.parseInt(startPageNmStr);

                int endPage = startPage;

                if(i == titles.size() - 1) {
                    endPage = pdfDoc.getNumberOfPages();
                }else {
                    int nextPage =  pageNum.get(i+1);
                    if(nextPage > startPage) {
                        endPage = nextPage - 1;
                    }else {
                        endPage = nextPage;
                    }
                }

                String outFileName = outputFolder + File.separator + title + ".pdf";
                PdfWriter pdfWriter = new PdfWriter(outFileName);

                PdfDocument newDocument = new PdfDocument(pdfWriter, new DocumentProperties().setEventCountingMetaInfo(null));
                pdfDoc.copyPagesTo(startPage, endPage, newDocument);
                newDocument.close();
                pdfWriter.close();
            }
        }
    }catch(IOException e){
        System.out.println(e);
    }
}


text:
Q: How to repeat Mono while not empty I have a method which returns like this!
Mono<Integer> getNumberFromSomewhere();

I need to keep calling this until it has no more items to emit. That is I need to make this as Flux<Integer>.
One option is to add repeat. the point is - I want to stop when the above method emits the first empty signal.
Is there any way to do this? I am looking for a clean way.

A: A built-in operator that does that (although it is intended for "deeper" nesting) is expand.
expand naturally stops expansion when the returned Publisher completes empty.
You could apply it to your use-case like this:
//this changes each time one subscribes to it
Mono<Integer> monoWithUnderlyingState;

Flux<Integer> repeated = monoWithUnderlyingState
    .expand(i -> monoWithUnderlyingState);

A: I'm not aware of a built-in operator which would do the job straightaway. However, it can be done using a wrapper class and a mix of operators:
Flux<Integer> repeatUntilEmpty() {
    return getNumberFromSomewhere()
        .map(ResultWrapper::new)
        .defaultIfEmpty(ResultWrapper.EMPTY)
        .repeat()
        .takeWhile(ResultWrapper::isNotEmpty)
}

// helper class, not necessarily needs to be Java record
record ResultWrapper(Integer value) {
    public static final ResultWrapper EMPTY = new ResultWrapper(null);

    public boolean isNotEmpty() {
        return value != null;
    }
}


text:
Q: Remove file from server Summernote v0.8.18 I am trying to delete file from server in summernote, but always getting undefined src error.

Warning: Undefined array key "src" in C:\wamp64\www\

I searched around found this: Summernote - Delete image from server and more but none of them are working.
I tried var src = $(this).attr("src"); and .prop() function no luck to pass url in src to php file.
This is how src url is :<img src="http://localhost/news/uploads/large/6dBUlfZZBW.webp">
Here is my setup :
   $('#summernote').summernote({
      height: 400,
      callbacks: {
         onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
         },
         onMediaDelete : function($target) {
             console.log($target[0].src); //This adds full url of src into console on test.

            deleteFile($target[0].src);
            $target.remove();
         }
      }
   });

And my delete function :
function deleteFile(src) {
   var src = $(this).attr("src");
   $.ajax({
      data:src,
      type: "POST",
      url: "delete_summernote.php",
      cache: false,
      success: function(resp) {
         console.log(resp);
         console.log(src);
      }
   });
}

Simple php example :
if(isset($_FILES['src'])){
$url = $_FILES['src'];

        unlink($url);

} else {
   echo "Src not set.";
}

Solved : Just needed a simple function, no cahce, no attr etc. thanks guys.
   function deleteFile(path) {
      $.ajax({
         url: "delete.php",
         type: "POST",
         data:  {'path':path},
         success: function(resp) {
            alert(resp);
         }
      });
   }

A: Your delete file function has some wrong specifications so that is the reason it is not working.
Correct If I am wrong!
var src = $(this).attr("src"); // you are specifying to select "src" attribute
But here :
deleteFile($target[0].src);
you are selecting source in function then variable src output will be underfined.
This is what I understand.
I hope it will help if I am not wrong But I have tried it on my pc.
But I don't have full code I could help you.


text:
Q: How to creating an application launcher Desktop icon for Android Studio Emulator in Ubuntu? I want to know is it possible for creating a application launcher icon for Emulator(Android Studio) with a specific version of Android Device and OS like Nexus_4_API_27 in Ubuntu 16.04.
If you know please help me. Thanks in Advance.

A: Go to the Android Studio Application menu bar. Go to tools then click Desktop Entry and it will be added on your applications menu.

A: It is possible, yes. You can open the emulator with certain commands from the command line and you can create a script that will run those commands automatically and then link it to your desktp.
To create an executable script with a shortcut on the desktop: https://askubuntu.com/questions/299052/how-to-execute-sh-script-from-a-desktop-shortcut
And in the script you need to set the commands for opening the emulator which you can find here:
https://developer.android.com/studio/run/emulator-commandline.html
I don't have an ubuntu machine right now so i can't help you more but you should be able t get it going from here.

A: Hopefully above solution would be working fine.
Here is another and generic way to create desktop icon for Ubuntu application.
Let take an example of robo-
Run following command from the terminal
sudo nano /usr/share/applications/robo.desktop
and paste the code
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=Robo
Icon=/opt/robo-{robo-version}/bin/robo.png
# Ex- /usr/local/bin/robo3t/robo3t-1.4.3-linux-x86_64-48f7dfd/bin
Exec="/opt/robo-{robo-version}/bin/robo"
# Ex- /usr/local/bin/robo3t/robo3t-1.4.3-linux-x86_64-48f7dfd/bin/robo3t
Comment=Robomongo desktop entry
Categories=Development;
Terminal=false
StartupNotify=true

Note- Icon should be the icon.png path which we want to display and Exec must be the exact executable file path.

Now, we can find the icon in application launcher menu by search for robo.
Similarly we can create desktop icon for any application in Ubuntu.


text:
Q: How to retrieve a specific data from Firebase I am designing a website where when the user comes and enters his email id, a corresponding value gets printed on the website.
I have the below data on my real-time firebase database.
How do I write a javascript function in my JS file so that when a user enters his/her email-id, the value of the total gets printed on the website?

I have tried something like this:
function getdata(){
var email=document.getElementById("email").value;
firebase.database().ref('0/'+email).once('value').then(function(snapshort){
    var total=snapshort.val().total;

    document.getElementById("total").innerHTML=total;
})}

A: I think you're trying to perform a query based on the email property of the node.
In that case, it'd be:
firebase.database().ref()
  .orderByChild("email")
  .equalTo(email)
  .once('value').then((results) => {
    results.forEach((snapshot) => {
      let total = snapshot.val().total;
      document.getElementById("total").innerHTML=total;
    });
  });

I recommend reading the Firebase Realtime Database documentation end-to-end, as it should answer many of the questions you may have about the API. A few hours spent there now, will save you many hours down the line.