问:
PHPSESSID security issues?
I've been curious for a while now about the security issues surrounding the PHP session name: PHPSESSID.

I've noticed that some websites rename their session ID cookie, while others just leave it as the default.

Is there any security advantage in using a different name? or is it merely useful for being able to track multiple sessions per user?

答: It doesn't make the slightest bit of difference.</p>

Title: PHPSESSID security issues?


来源: stackexchange

问:
SQL CASE in WHERE clause with parameter
@status is a parameter to stored proc.Based on @Status, if @Status = 'Y' then just get Active records. if @Status = 'N' then fetch the records which have been deactivated less than 30 days back. We do not want to get deactivated records older than 30 days. Therefore, I need to put the logic in WHERE clause as follows. Please guide how to achieve this</p>

```<code>    SELECT * from TableA
WHERE Active =
    ( CASE  @Status WHEN 'N' THEN ('N' AND CONVERT(DATE,ISNULL(DateDeactivated,'01/01/2016'))
    BETWEEN  CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
WHEN 'Y' THEN   'Y' ELSE 'Y' END)
</code>```

答:
Your logic is too complicated.  How about this?

```<code>SELECT a.*
FROM TableA a
WHERE (@Status = 'N' AND DateDeactivated >= CAST(GETDATE() - 30 as DATE) or
      (@Status = 'Y' AND DateDeactivated IS NULL)
</code>```

I assume "active" records are those that have no deactivation date.

ContentLicense: CC BY-SA 3.0

Title: SQL CASE in WHERE clause with parameter

Body:
@status is a parameter to stored proc.Based on @Status, if @Status = 'Y' then just get Active records. if @Status = 'N' then fetch the records which have been deactivated less than 30 days back. We do not want to get deactivated records older than 30 days. Therefore, I need to put the logic in WHERE clause as follows. Please guide how to achieve this

    SELECT * from TableA
WHERE Active =
    ( CASE  @Status WHEN 'N' THEN ('N' AND CONVERT(DATE,ISNULL(DateDeactivated,'01/01/2016'))
    BETWEEN  CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
WHEN 'Y' THEN   'Y' ELSE 'Y' END)

Body:
Your logic is too complicated.  How about this?

SELECT a.*
FROM TableA a
WHERE (@Status = 'N' AND DateDeactivated >= CAST(GETDATE() - 30 as DATE) or
      (@Status = 'Y' AND DateDeactivated IS NULL)

I assume "active" records are those that have no deactivation date.


问:
Short-circuit evaluation evaluating if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
The program is posted below:

```<code>#include <stdio.h>

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}
</code>```

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

```<code>        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496
</code>```

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.

答:
This call of printf

```<code>    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
</code>```

has undefined behavior because variables a, b, c, and d are not initialized and have indeterminate values that can be trap values.

In the condition of the if statement

```<code>if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
</code>```

there is assignment expression

```<code>a = 4
</code>```

According to the C Standard (6.5.16 Assignment operators)

3 An assignment operator stores a value in the object designated by
  the left operand. An assignment expression has the value of the left
  operand after the assignment,111) but is not an lvalue...

And further (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare
  unequal to 0; otherwise, it yields 0. The result has type int.
  4 Unlike the bitwise | operator, the || operator guarantees
  left-to-right evaluation; if the second operand is evaluated, there is
  a sequence point between the evaluations of the first and second
  operands. If the first operand compares unequal to 0, the second
  operand is not evaluated.

Thus only the assignment

```<code>a = 4
</code>```

will be performed in this if statement

```<code>if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
</code>```

all other variables still will be uninitialized.

As the value of the assignment that is 4 is not equal to 0 then the if sub-statement will be executed.

Body:
The program is posted below:

#include <stdio.h>

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.

Body:
This call of printf

    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

has undefined behavior because variables a, b, c, and d are not initialized and have indeterminate values that can be trap values.

In the condition of the if statement

if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )

there is assignment expression

a = 4

According to the C Standard (6.5.16 Assignment operators)

3 An assignment operator stores a value in the object designated by
  the left operand. An assignment expression has the value of the left
  operand after the assignment,111) but is not an lvalue...

And further (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare
  unequal to 0; otherwise, it yields 0. The result has type int.
  4 Unlike the bitwise | operator, the || operator guarantees
  left-to-right evaluation; if the second operand is evaluated, there is
  a sequence point between the evaluations of the first and second
  operands. If the first operand compares unequal to 0, the second
  operand is not evaluated.

Thus only the assignment

a = 4

will be performed in this if statement

if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )

all other variables still will be uninitialized.

As the value of the assignment that is 4 is not equal to 0 then the if sub-statement will be executed.


问:
How to change value of an array in knockout.js?
```<code><div class="row">
    <div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic" style="display:none;">
        <span>Education:</span>
             <!-- ko if: application.candidateMostRecentAcademic != null -->
               <!-- ko with: application.candidateMostRecentAcademic[0] -->
                 <span data-bind="text: $data.degreeTypeName"></span>
                 <span data-bind="text: $data.institutionName"></span>
                 <span data-bind="text: $data.dateToYear"></span>
               <!-- /ko -->
             <!-- /ko -->
    </div>
</div>
</code>```

I was going to make the the column visible only if application.candidateMostRecentAcademic (array) exists.

But I also wanted to add a condition for an array that has 0 length (which is not null).

So when I tried to do,

```<code><div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic.length != 0" style="display:none;">
</code>```

it gave me an error saying that it cannot access the "length" of a null object. So, what I am trying to do is, I want to set an array of length 0 to null so that it can just be invisible just like the null object.

How can I do this with knockout data-binding?

答:
Add another member in viewmodel called isColumnVisible and use this member to show and hide column.</p>

```<code>var viewModel={
    isColumnVisible=true;
    loadData:function(){
        // code to load data;
        // application= something
        if(application.candidateMostRecentAcademic ===null){
            this.isColumnVisible=false;
        }
    }
}
</code>```

Body:
        Education:

I was going to make the the column visible only if application.candidateMostRecentAcademic (array) exists.

But I also wanted to add a condition for an array that has 0 length (which is not null).

So when I tried to do,

it gave me an error saying that it cannot access the "length" of a null object. So, what I am trying to do is, I want to set an array of length 0 to null so that it can just be invisible just like the null object.

How can I do this with knockout data-binding?

Body:
Add another member in viewmodel called isColumnVisible and use this member to show and hide column.

var viewModel={
    isColumnVisible=true;
    loadData:function(){
        // code to load data;
        // application= something
        if(application.candidateMostRecentAcademic ===null){
            this.isColumnVisible=false;
        }
    }
}


问:
Full size popup when address bar is showing and not showing - mobile chrome
My popup is supposed to be full screen height minus the header.

However, when the address bar is not showing up (after scrolling down), the space is left blank.

```<code>var currencyHeight = $(window).innerHeight() - headerHeight;
</code>```

$(window).innerHeight() returns 559 both when the address bar is showing and not showing. When it is showing, the popup works fine, full screen minus the header:

but when it is not showing up you can see the empty space:

How do people usually solve this?

Minimal example:

https://jsfiddle.net/zzuxvg4p/4/

But because jsfiddle uses an iframe, you cannot test it on android properly, so this page has the code from that jsfiddle:

https://annotated-dev.limebuild.net/media/test.html (click on the blue box in the footer. If the address bar isn't showing then the black box is not full screen, but if it is showing then it is full screen).

Here is the issue even after I add the no-scroll class to body with overflow hidden:

答:
Try window.innerHeight for some reason $(window).innerHeight() returns the samevalue on resize event in android portrait mode.

Jquery Issue
https://github.com/jquery/jquery/pull/764

It looks like its not only Mobile Safari.

Body:
My popup is supposed to be full screen height minus the header.

However, when the address bar is not showing up (after scrolling down), the space is left blank.

var currencyHeight = $(window).innerHeight() - headerHeight;

$(window).innerHeight() returns 559 both when the address bar is showing and not showing. When it is showing, the popup works fine, full screen minus the header:

but when it is not showing up you can see the empty space:

How do people usually solve this?

Minimal example:

https://jsfiddle.net/zzuxvg4p/4/

But because jsfiddle uses an iframe, you cannot test it on android properly, so this page has the code from that jsfiddle:

https://annotated-dev.limebuild.net/media/test.html (click on the blue box in the footer. If the address bar isn't showing then the black box is not full screen, but if it is showing then it is full screen).

Here is the issue even after I add the no-scroll class to body with overflow hidden:


问:
Should bcrypted passwords be stored as byte array or as string and why?
I read on some SO answer (which I can't seem to find again) that bcrypted passwords must be stored as byte array in the database. I'm storing them as string. Is there any advantage I gain by storing them as byte array or maybe it's more secure that way?</p>

答: Storing a base64 string?  That's exactly as secure as raw binary.  Treating raw binary as an ASCII string?  That might get messed up during read, write, string processing, table export/backup.  For example binary 0 = \0 = end of string marker in many languages.</p>


问:
Sending variables from two different HTML sources to a single PHP script using HTML/PHP/JScript only
I have a situation in which a page is built off two different sources with HTML by combining with each other in a containter third page. Each section also has a variable they pass through a form using POST to a single PHP file. These variables change in every execution (When they form a page together).

For example:

```<code><!--Start of HTML 3 -->
<html>
<!-- Start of HTML 1 -->
<body>

<a href='process.php' id='php1' name='php1' onclick='document.getElementById("infoForm").submit()'> A link to php file that receives a hidden form's value</a>

<form id='infoForm' action='process.php' method='POST'>
  <input name ="var1" id="var1" value="changing1" hidden />
</form>
<p>Stuff here</p>
<!-- End of HTML 1 -->

<!-- Start of HTML 2 -->
<p>Some more stuff here</p>
<form id='infoForm2' action='process.php' method='POST'>
  <input name ="var2" id="var2" value="changing2" hidden />
</form>

</body>
<!-- End of HTML 2 -->
</html>
<!-- End of HTML 3 -->
</code>```

A few more details:

The forms are independent of each other, joining them would be difficult since they are created using previous processes that work with other variables.

Code can be added inside HTML 1 and 2, but not 3.

This one will only be able to send var1 to process.php (which can invoke it with $_POST). How could I submit both variables to a single PHP file, using a single link, using basic technologies (e.g. Excluding JQuery, AJAX, etc)? Is there a better way than using forms/POST without using the URI?

EDIT: The method I used was @glenn ferns first point: use the form attribute to attach the second one to the first form in the html makeup:

```<code><!-- Start of HTML 2 -->
<p>Some more stuff here</p>

<input form="infoForm" name ="var2" id="var2" value="changing2" hidden />

</body>
<!-- End of HTML 2 -->
</code>```

答:
You could possibly collate the onformation from both forms and send both using ajax and a FormData objec.</p>

```<code>function submitforms(){
    var f2=document.getElementById('infoForm2');
    var data=new FormData( document.getElementById('infoForm') );
    for( i=0; i < f2.elements.length; i++ )data.append( f2.elements[i].name, f2.elements[i].value );
    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if( this.status==200 && this.readyState==4 ){
            alert(this.response)
        }
    };
    xhr.open('POST','process.php',true);
    xhr.send( data );
}
</code>```

Body:
I have a situation in which a page is built off two different sources with HTML by combining with each other in a containter third page. Each section also has a variable they pass through a form using POST to a single PHP file. These variables change in every execution (When they form a page together).

For example:

 A link to php file that receives a hidden form's value

<form id='infoForm' action='process.php' method='POST'>
  <input name ="var1" id="var1" value="changing1" hidden />
</form>

Stuff here

Some more stuff here

<form id='infoForm2' action='process.php' method='POST'>
  <input name ="var2" id="var2" value="changing2" hidden />
</form>

A few more details:

The forms are independent of each other, joining them would be difficult since they are created using previous processes that work with other variables.

Code can be added inside HTML 1 and 2, but not 3.

This one will only be able to send var1 to process.php (which can invoke it with $_POST). How could I submit both variables to a single PHP file, using a single link, using basic technologies (e.g. Excluding JQuery, AJAX, etc)? Is there a better way than using forms/POST without using the URI?

EDIT: The method I used was @glenn ferns first point: use the form attribute to attach the second one to the first form in the html makeup:

Some more stuff here

<input form="infoForm" name ="var2" id="var2" value="changing2" hidden />

Body:
You could possibly collate the onformation from both forms and send both using ajax and a FormData objec.

function submitforms(){
    var f2=document.getElementById('infoForm2');
    var data=new FormData( document.getElementById('infoForm') );
    for( i=0; i < f2.elements.length; i++ )data.append( f2.elements[i].name, f2.elements[i].value );
    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if( this.status==200 && this.readyState==4 ){
            alert(this.response)
        }
    };
    xhr.open('POST','process.php',true);
    xhr.send( data );
}


问:
Limit number of records that can be written to a path (reference other paths in security rules)
Let's say my Firebase collection looks like:

```<code>{
  "max":5
  "things":{}
}
</code>```

How would I use the value of max in my security rules to limit the number of things?

```<code>{
  "rules": {
    "things": {
      ".validate": "newData.val().length <= max"
    }
  }
}
</code>```

答:
While I think there is still no available rule to do such thing, there is a sample cloud function available here that does that:

https://github.com/firebase/functions-samples/tree/master/limit-children

Body:
Let's say my Firebase collection looks like:

{
  "max":5
  "things":{}
}

How would I use the value of max in my security rules to limit the number of things?

{
  "rules": {
    "things": {
      ".validate": "newData.val().length <= max"
    }
  }
}


问:
How to make a rails app "portable"?
I have a rails app that needs a lot of initial data. This data includes default configuration preferences, states information and some company information. This information is not gonna change, but I have it in the database because is huge.

The problem here is that the application won't work without that data. So, how can I make this info easily loaded into the database when I change environments from dev to test/prod and when I deploy the app to the servers?

答:
Don't use the database, maybe is useful to create a .rb file with your initial info or configuration, and add this file to be loaded at the beginning of your config/initializers folder. Everything added here with be loaded by the boot.rb file.

Hope it helps.

PD: I'm supposing you're using rails 2.3 and above. (minus rails 3 and above).

ContentLicense: CC BY-SA 2.5

Title: How to make a rails app "portable"?


问:
Pass in any number of arguments into a Javascript function
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

```<code>function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")
</code>```

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

```<code>function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)
</code>```

答:
Using an array is a good idea, but in the interest of completeness...

The ES6 way!

If you're able to support ES6 features, the spread operator combined with the arguments keyword is a neat way to get around that:

```<code>function anyNumber() {
  console.log(...arguments); // ->  1 2 3 4

  let argsAsArray = [0, ...arguments, 5]; // now they're an array

  argsAsArray.forEach(s => console.log(s)); // -> 0 1 2 3 4 5
};

anyNumber(1,2,3,4);
</code>```

There are a lot of cool things you can do with the spread operator, especially with object and parameter destructuring.

Body:
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)

Body:
Using an array is a good idea, but in the interest of completeness...

The ES6 way!

If you're able to support ES6 features, the spread operator combined with the arguments keyword is a neat way to get around that:

function anyNumber() {
  console.log(...arguments); // ->  1 2 3 4

  let argsAsArray = [0, ...arguments, 5]; // now they're an array

  argsAsArray.forEach(s => console.log(s)); // -> 0 1 2 3 4 5
};

anyNumber(1,2,3,4);

There are a lot of cool things you can do with the spread operator, especially with object and parameter destructuring.


问:
How to get file extension from a uri of Drupal 7
I have file uri {s3://video-seven-test/file_name.mp4} how do I get the extension from this uri?</p>

答:
```<code>$file = file_load($fid);
$path = drupal_realpath($file->uri);
$parts = pathinfo($path);
$extension = $parts['extension'];
</code>```

thanks to nmc

Body:
$file = file_load($fid);
$path = drupal_realpath($file->uri);
$parts = pathinfo($path);
$extension = $parts['extension'];

thanks to nmc


问:
Looping over all model indexes and their children causes stack overflow error
I created following functions to loop over all indexes in a table or a tree and find the one that contains required string:

```<code>#include <QModelIndex>
#include <QAbstractItemModel>
#include <QAbstractItemView>

QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent = QModelIndex());
QModelIndex findIndexByString(const QModelIndex& index, const QString& text) {
    // First check this particular index
    if(index.data().toString() == text)
        return index;
    // Check if it has children and loop
    const QAbstractItemModel* model = index.model();
    if(model==nullptr)
        return QModelIndex();
    if (!model->hasChildren(index))
        return QModelIndex();
    // STACK OVERFLOW HERE (model and index keep repeating)
    return findIndexByString(model, text, index);
}
QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent) {
    int rows = model->rowCount(parent);
    int cols = model->columnCount(parent);
    for (int i = 0; i < rows; ++i)
      for (int j = 0; j < cols; ++j) {
        QModelIndex index_child = findIndexByString(model->index(i, j, parent), text);
        if(index_child.isValid())
            return index_child;
      }
    return QModelIndex();
}
QModelIndex findIndexByString(const QAbstractItemView* view, const QString& text) {
    //const QModelIndex root = view->rootIndex();
    const QAbstractItemModel* model = view->model();
    return findIndexByString(model, text);
}
</code>```

This code is self contained and doesn't have any dependencies outside Qt library.

I encountered stack overflow error when looping over some model in foreign code.

I am trying to create generic correct algorithm to do this. Is the algorithm above correct?

答:
The code looks fine. It's a classic depth-first search. It runs out of stack because your model is not a tree, but a cyclic graph and/or it has infinite depth.

We can reformulate the search with an explicit stack and add tests that ensure a reasonable behavior in face of ill-formed model.

If your model has infinite depth or cycles by design, the code below will act appropriately and won't run out of stack.

```<code>// https://github.com/KubaO/stackoverflown/tree/master/questions/model-find-diagnostic-44416637
#include <QtGui>
</code>```

First, we'll need a set of indexes, since QSet will only work with persistent indexes that we don't use:

```<code>class IndexSet : public QMap<QModelIndex, bool> {
public:
   void insert(const QModelIndex & key) { QMap::insert(key, true); }
};
</code>```

The state of the finder, that we'll keep on an explicit stack:

```<code>struct FindState {
   QModelIndex index;
   int rows;
   int cols;
   int i = 0;
   int j = 0;
   FindState() = default;
   FindState(const QAbstractItemModel* model, const QModelIndex & index) :
      index(index),
      rows(model->rowCount(index)),
      cols(model->columnCount(index)) {}
   bool isInitial() const { return i == 0 && j == 0; }
   bool equalTo(const QVariant & value) const {
      return index.isValid() && index.data() == value;
   }
   bool operator==(const FindState & o) const {
      return index == o.index;
   }
};

QDebug operator<<(QDebug dbg, const FindState & s) {
   return dbg << "{" << s.index << "," << s.i << "," << s.j << "}";
}
</code>```

Then, a find utility that verifies that things are sane and that the model doesn't misbehave:

```<code>QModelIndex findIndexByValue(const QAbstractItemModel* model, const QVariant& needle,
                             const QModelIndex& parent = {}) {
   int iterations = {};
   int maxDepth = {};
   const auto depthLimit = 100;
   IndexSet indexes;
   QStack<FindState> states;
   states.push({model, parent});
   for (; !states.isEmpty(); iterations++) {
      auto valid = true;
      auto & top = states.top();
      if (top.isInitial()) {
         if (states.size() > 1) {
            if (!top.index.isValid()) {
               qWarning() << "the index isn't valid, stack:" << states;
               valid = false;
            }
            if (!model->hasIndex(top.index.row(), top.index.column(), top.index.parent())) {
               qWarning() << "the index doesn't exist, stack:" << states;
               valid = false;
            }
         }
         if (indexes.contains(top.index)) {
            qWarning() << "skipping already seen index" << top.index;
            valid = false;
         }
         if (valid) {
            indexes.insert(top.index);
            if (top.equalTo(needle))
               break;
         }
      }
      if (valid && model->hasChildren(top.index) && top.i < top.rows && top.j < top.cols) {
         FindState state(model, model->index(top.i, top.j, top.index));
         top.i ++;
         if (top.i == top.rows) {
            top.i = 0;
            top.j ++;
         }
         if (states.contains(state))
            qWarning() << "skipping duplicate index" << state.index;
         else if (states.size() == depthLimit)
            qWarning() << "stack is full, skipping index" << state.index;
         else {
            states.push(state);
            maxDepth = std::max(maxDepth, states.size());
         }
      } else
         states.pop();
   }
   qDebug() << "max depth" << maxDepth << "iterations" << iterations;
   return states.isEmpty() ? QModelIndex() : states.top().index;
}

QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& needle, const QModelIndex& parent = {}) {
   return findIndexByValue(model, QVariant::fromValue(needle), parent);
}
</code>```

For comparison, we can include the original implementations from the question:

```<code>QModelIndex findIndexByString2(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent = QModelIndex());
QModelIndex findIndexByString2(const QModelIndex& index, const QString& text) {
   if (index.data().toString() == text)
      return index;
   auto model = index.model();
   if (!model || !model->hasChildren(index))
      return {};
   return findIndexByString2(model, text, index);
}

QModelIndex findIndexByString2(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent) {
   int rows = model->rowCount(parent);
   int cols = model->columnCount(parent);
   for (int i = 0; i < rows; ++i)
      for (int j = 0; j < cols; ++j) {
         auto child = findIndexByString2(model->index(i, j, parent), text);
         if (child.isValid())
            return child;
      }
   return {};
}
</code>```

Finally, we need a rudimentary test harness. A path into the model is represented by a vector of positions within an item. Each position has a string representation.

```<code>struct Pos {
   int row, col;
   QString toString() const { return QStringLiteral("(%1,%2)").arg(row).arg(col); }
};
Q_DECLARE_TYPEINFO(Pos, Q_PRIMITIVE_TYPE);
using Path = QVector<Pos>;
</code>```

The builder adds items to the model to ensure that a given path is valid. Each item's value is a string representing its path as a concatenation of positions that make up the path (row,col)(row,col).... As the builder builds up the model, it also retains the paths of all the items it created.

```<code>struct Builder {
   QStandardItemModel * model;
   QStringList paths;
   Path add(Path path, const Pos & pos) {
      auto item = model->invisibleRootItem();
      path.push_back(pos);
      QString pathString;
      for (auto p : path) {
         pathString += p.toString();
         auto child = item->child(p.row, p.col);
         if (!child) {
            item->setChild(p.row, p.col, child = new QStandardItem(pathString));
            paths << pathString;
         }
         item = child;
      }
      return path;
   }
   explicit Builder(QStandardItemModel * model) : model(model) {}
};
</code>```

Finally, we can create a model, and ensure that both methods of finding items provide the same results:

```<code>int main() {
   QStandardItemModel model;
   Builder b(&model);
   Path path, ____;
   path = b.add({}, {1, 0});     // *(1,0)
   ____ = b.add(path, {1, 1});   //  (1,0)-(1,1)
   ____ = b.add(path, {0, 0});   //  (1,0)-(0,0)
   path = b.add({}, {1, 1});     // *(1,1)
   path = b.add(path, {3, 3});   // *(1,1)-(3,3)
   ____ = b.add(path, {0, 0});   //  (1,1)-(3,3)-(0,0)
   path.pop_back();              // -(1,1)
   path = b.add(path, {2, 2});   // *(1,1)-(2,2)
   ____ = b.add(path, {0, 1});   //  (1,1)-(2,2)-(0,1)
   path = b.add({}, {2, 1});     // *(2,1)

   IndexSet indexes;
   for (auto path : b.paths) {
      auto index = findIndexByString(b.model, path);
      auto index2 = findIndexByString2(b.model, path);
      Q_ASSERT(index.isValid());
      Q_ASSERT(!indexes.contains(index));
      Q_ASSERT(index2 == index);
      indexes.insert(index);
   }
}
</code>```

This concludes the example.

Body:
I created following functions to loop over all indexes in a table or a tree and find the one that contains required string:

#include <QModelIndex>
#include <QAbstractItemModel>
#include <QAbstractItemView>

QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent = QModelIndex());
QModelIndex findIndexByString(const QModelIndex& index, const QString& text) {
    // First check this particular index
    if(index.data().toString() == text)
        return index;
    // Check if it has children and loop
    const QAbstractItemModel* model = index.model();
    if(model==nullptr)
        return QModelIndex();
    if (!model->hasChildren(index))
        return QModelIndex();
    // STACK OVERFLOW HERE (model and index keep repeating)
    return findIndexByString(model, text, index);
}
QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent) {
    int rows = model->rowCount(parent);
    int cols = model->columnCount(parent);
    for (int i = 0; i < rows; ++i)
      for (int j = 0; j < cols; ++j) {
        QModelIndex index_child = findIndexByString(model->index(i, j, parent), text);
        if(index_child.isValid())
            return index_child;
      }
    return QModelIndex();
}
QModelIndex findIndexByString(const QAbstractItemView* view, const QString& text) {
    //const QModelIndex root = view->rootIndex();
    const QAbstractItemModel* model = view->model();
    return findIndexByString(model, text);
}

This code is self contained and doesn't have any dependencies outside Qt library.

I encountered stack overflow error when looping over some model in foreign code.

I am trying to create generic correct algorithm to do this. Is the algorithm above correct?

Body:
The code looks fine. It's a classic depth-first search. It runs out of stack because your model is not a tree, but a cyclic graph and/or it has infinite depth.

We can reformulate the search with an explicit stack and add tests that ensure a reasonable behavior in face of ill-formed model.

If your model has infinite depth or cycles by design, the code below will act appropriately and won't run out of stack.

// https://github.com/KubaO/stackoverflown/tree/master/questions/model-find-diagnostic-44416637
#include <QtGui>

First, we'll need a set of indexes, since QSet will only work with persistent indexes that we don't use:

class IndexSet : public QMap<QModelIndex, bool> {
public:
   void insert(const QModelIndex & key) { QMap::insert(key, true); }
};

The state of the finder, that we'll keep on an explicit stack:

struct FindState {
   QModelIndex index;
   int rows;
   int cols;
   int i = 0;
   int j = 0;
   FindState() = default;
   FindState(const QAbstractItemModel* model, const QModelIndex & index) :
      index(index),
      rows(model->rowCount(index)),
      cols(model->columnCount(index)) {}
   bool isInitial() const { return i == 0 && j == 0; }
   bool equalTo(const QVariant & value) const {
      return index.isValid() && index.data() == value;
   }
   bool operator==(const FindState & o) const {
      return index == o.index;
   }
};

QDebug operator<<(QDebug dbg, const FindState & s) {
   return dbg << "{" << s.index << "," << s.i << "," << s.j << "}";
}

Then, a find utility that verifies that things are sane and that the model doesn't misbehave:

QModelIndex findIndexByValue(const QAbstractItemModel* model, const QVariant& needle,
                             const QModelIndex& parent = {}) {
   int iterations = {};
   int maxDepth = {};
   const auto depthLimit = 100;
   IndexSet indexes;
   QStack<FindState> states;
   states.push({model, parent});
   for (; !states.isEmpty(); iterations++) {
      auto valid = true;
      auto & top = states.top();
      if (top.isInitial()) {
         if (states.size() > 1) {
            if (!top.index.isValid()) {
               qWarning() << "the index isn't valid, stack:" << states;
               valid = false;
            }
            if (!model->hasIndex(top.index.row(), top.index.column(), top.index.parent())) {
               qWarning() << "the index doesn't exist, stack:" << states;
               valid = false;
            }
         }
         if (indexes.contains(top.index)) {
            qWarning() << "skipping already seen index" << top.index;
            valid = false;
         }
         if (valid) {
            indexes.insert(top.index);
            if (top.equalTo(needle))
               break;
         }
      }
      if (valid && model->hasChildren(top.index) && top.i < top.rows && top.j < top.cols) {
         FindState state(model, model->index(top.i, top.j, top.index));
         top.i ++;
         if (top.i == top.rows) {
            top.i = 0;
            top.j ++;
         }
         if (states.contains(state))
            qWarning() << "skipping duplicate index" << state.index;
         else if (states.size() == depthLimit)
            qWarning() << "stack is full, skipping index" << state.index;
         else {
            states.push(state);
            maxDepth = std::max(maxDepth, states.size());
         }
      } else
         states.pop();
   }
   qDebug() << "max depth" << maxDepth << "iterations" << iterations;
   return states.isEmpty() ? QModelIndex() : states.top().index;
}

QModelIndex findIndexByString(const QAbstractItemModel* model, const QString& needle, const QModelIndex& parent = {}) {
   return findIndexByValue(model, QVariant::fromValue(needle), parent);
}

For comparison, we can include the original implementations from the question:

QModelIndex findIndexByString2(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent = QModelIndex());
QModelIndex findIndexByString2(const QModelIndex& index, const QString& text) {
   if (index.data().toString() == text)
      return index;
   auto model = index.model();
   if (!model || !model->hasChildren(index))
      return {};
   return findIndexByString2(model, text, index);
}

QModelIndex findIndexByString2(const QAbstractItemModel* model, const QString& text,  const QModelIndex& parent) {
   int rows = model->rowCount(parent);
   int cols = model->columnCount(parent);
   for (int i = 0; i < rows; ++i)
      for (int j = 0; j < cols; ++j) {
         auto child = findIndexByString2(model->index(i, j, parent), text);
         if (child.isValid())
            return child;
      }
   return {};
}

Finally, we need a rudimentary test harness. A path into the model is represented by a vector of positions within an item. Each position has a string representation.

struct Pos {
   int row, col;
   QString toString() const { return QStringLiteral("(%1,%2)").arg(row).arg(col); }
};
Q_DECLARE_TYPEINFO(Pos, Q_PRIMITIVE_TYPE);
using Path = QVector<Pos>;

The builder adds items to the model to ensure that a given path is valid. Each item's value is a string representing its path as a concatenation of positions that make up the path (row,col)(row,col).... As the builder builds up the model, it also retains the paths of all the items it created.

struct Builder {
   QStandardItemModel * model;
   QStringList paths;
   Path add(Path path, const Pos & pos) {
      auto item = model->invisibleRootItem();
      path.push_back(pos);
      QString pathString;
      for (auto p : path) {
         pathString += p.toString();
         auto child = item->child(p.row, p.col);
         if (!child) {
            item->setChild(p.row, p.col, child = new QStandardItem(pathString));
            paths << pathString;
         }
         item = child;
      }
      return path;
   }
   explicit Builder(QStandardItemModel * model) : model(model) {}
};

Finally, we can create a model, and ensure that both methods of finding items provide the same results:

int main() {
   QStandardItemModel model;
   Builder b(&model);
   Path path, ____;
   path = b.add({}, {1, 0});     // *(1,0)
   ____ = b.add(path, {1, 1});   //  (1,0)-(1,1)
   ____ = b.add(path, {0, 0});   //  (1,0)-(0,0)
   path = b.add({}, {1, 1});     // *(1,1)
   path = b.add(path, {3, 3});   // *(1,1)-(3,3)
   ____ = b.add(path, {0, 0});   //  (1,1)-(3,3)-(0,0)
   path.pop_back();              // -(1,1)
   path = b.add(path, {2, 2});   // *(1,1)-(2,2)
   ____ = b.add(path, {0, 1});   //  (1,1)-(2,2)-(0,1)
   path = b.add({}, {2, 1});     // *(2,1)

   IndexSet indexes;
   for (auto path : b.paths) {
      auto index = findIndexByString(b.model, path);
      auto index2 = findIndexByString2(b.model, path);
      Q_ASSERT(index.isValid());
      Q_ASSERT(!indexes.contains(index));
      Q_ASSERT(index2 == index);
      indexes.insert(index);
   }
}

This concludes the example.


问:
Can not execute hexagon_graph_execution on hexagon-sim
I have followed the build_and_run_inception_hexagon.sh and generated the hexagon_graph_execution executable. Now instead of using a real device I would like to test inception model with hexagon-sim available at SDK 3.0. So there is no need to use adb push commands as the SDK can simulate HVX device with hexagon-sim.
I have put the run-time libraries and the inception model plus the image at the same folder. After execution It gives me this error:

```<code>~/Qualcomm/HEXAGON_Tools/7.2.12/Tools/bin/hexagon-sim ./hexagon_graph_execution "/home/aashouri/Qualcomm/Hexagon_SDK/3.0/test/common/inception"
Error: Unsupported machine type 0x0 in ELF image "./hexagon_graph_execution" - exiting.
</code>```

Can anyone comment on this?

Hexagon-readelf:

```<code>ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0xc8c9c
  Start of program headers:          52 (bytes into file)
  Start of section headers:          39944896 (bytes into file)
  Flags:                             0x5000000, Version5 EABI
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         8
  Size of section headers:           40 (bytes)
  Number of section headers:         36
  Section header string table index: 35
</code>```

XXD info:

```<code>0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0300 2800 0100 0000 9c8c 0c00 3400 0000  ..(.........4...
0000020: c082 6102 0000 0005 3400 2000 0800 2800  ..a.....4. ...(.
0000030: 2400 2300 0600 0000 3400 0000 3400 0000  $.#.....4...4...
0000040: 3400 0000 0001 0000 0001 0000 0400 0000  4...............
0000050: 0400 0000 0300 0000 3401 0000 3401 0000  ........4...4...
0000060: 3401 0000 1300 0000 1300 0000 0400 0000  4...............
0000070: 0100 0000 0100 0000 0000 0000 0000 0000  ................
0000080: 0000 0000 ece6 2a01 ece6 2a01 0500 0000  ......*...*.....
0000090: 0010 0000 0100 0000 20eb 2a01 20fb 2a01  ........ .*. .*.
</code>```

答:
```<code>ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           ARM
  Version:                           0x1
</code>```

This binary was not built by hexagon-clang. You must have accidentally built it with the ARM toolchain -- the "Machine" field would say "Qualcomm Hexagon" if it had been built for the hexagon DSP.

Body:
I have followed the build_and_run_inception_hexagon.sh and generated the hexagon_graph_execution executable. Now instead of using a real device I would like to test inception model with hexagon-sim available at SDK 3.0. So there is no need to use adb push commands as the SDK can simulate HVX device with hexagon-sim.
I have put the run-time libraries and the inception model plus the image at the same folder. After execution It gives me this error:

~/Qualcomm/HEXAGON_Tools/7.2.12/Tools/bin/hexagon-sim ./hexagon_graph_execution "/home/aashouri/Qualcomm/Hexagon_SDK/3.0/test/common/inception"
Error: Unsupported machine type 0x0 in ELF image "./hexagon_graph_execution" - exiting.

Can anyone comment on this?

Hexagon-readelf:

ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0xc8c9c
  Start of program headers:          52 (bytes into file)
  Start of section headers:          39944896 (bytes into file)
  Flags:                             0x5000000, Version5 EABI
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         8
  Size of section headers:           40 (bytes)
  Number of section headers:         36
  Section header string table index: 35

XXD info:

0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0300 2800 0100 0000 9c8c 0c00 3400 0000  ..(.........4...
0000020: c082 6102 0000 0005 3400 2000 0800 2800  ..a.....4. ...(.
0000030: 2400 2300 0600 0000 3400 0000 3400 0000  $.#.....4...4...
0000040: 3400 0000 0001 0000 0001 0000 0400 0000  4...............
0000050: 0400 0000 0300 0000 3401 0000 3401 0000  ........4...4...
0000060: 3401 0000 1300 0000 1300 0000 0400 0000  4...............
0000070: 0100 0000 0100 0000 0000 0000 0000 0000  ................
0000080: 0000 0000 ece6 2a01 ece6 2a01 0500 0000  ......*...*.....
0000090: 0010 0000 0100 0000 20eb 2a01 20fb 2a01  ........ .*. .*.

Body:
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           ARM
  Version:                           0x1

This binary was not built by hexagon-clang. You must have accidentally built it with the ARM toolchain -- the "Machine" field would say "Qualcomm Hexagon" if it had been built for the hexagon DSP.


答:
Given javascript at updated Question, you can define default parameters within () following function name.

function test(a = 2, b = 3) {
  let c;
  if (a > b) {
    c = a + b
  } else {
    c = 0
  }
  console.log(c);
}

test(); // 0

test(4); // 7```

See also Can we set persistent default parameters which remain set until explicitly changed?

Title: Pass in any number of arguments into a Javascript function

Body:
Given javascript at updated Question, you can define default parameters within () following function name.

function test(a = 2, b = 3) {
  let c;
  if (a > b) {
    c = a + b
  } else {
    c = 0
  }
  console.log(c);
}

test(); // 0

test(4); // 7

See also Can we set persistent default parameters which remain set until explicitly changed?


问:
What does using something::something::something mean (c++)?
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

```<code>using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;
</code>```

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.

答:
If there really just random naming, than it's very-very bad. BUT I hope it's just yours personally vision, as beginner in C++, and in reality there is a good code, but kinda complex.

I don't know yours background, what languages you know, so I would say that namespaces are kinda boxes. They can build very good, hierarchically structured, modules\subsystems. I suggest you to not panic, take paper and try to wrote out all namespaces, their relations, what is in them (classes, structures, maybe functions) and your own understanding them purposes.

P. S. sorry for bad English. This topic very  close for me, but my writing skills in English are not very good for a free conversation about this. I hope moderators will fix  typos.

Body:
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.


问:
Java. Consumer - Producer with BlockingQueue. Search tool
I was trying to implement some Consumer-Producer problem with BlockingQueue. To do it with some purpose, I decided to write file searching tool.

I decided that search mechanism is working recursively, and every new directory is going to have new thread pool to increase speed of searching.

My problem is, that I have no idea how can I implement mechanism that stops printing threads (consumers) at the end - when searching threads get job done.

I was trying to do that with some ideas like POISON PILLS, but it doesn't works well (threads stops before print any results). Any ideas how can I do that?

Here is some code:

Searching mechanism:

```<code>public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue) {
    this.file = fileName;
    this.queue = queue;
    this.executor = Executors.newWorkStealingPool();
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue));
            } else {
                this.queue.add(fil);
            }
        }
    }
}
</code>```

}

Printer:

```<code>public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
// private ExecutorService executor;
private String keyWord;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord) {
    this.queue = queue;
    this.keyWord = keyWord;
    // executor = Executors.newFixedThreadPool(2);
}

@Override
public void run() {
    try {
        printFile();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    while (true) {
        File takeFile = queue.take();
        String fileName = takeFile.getAbsolutePath()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}
</code>```

}

Main test class:

```<code>public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot");
    executor.submit(ca);

    executor.shutdown();
}
</code>```

}

答:
Split the whole work in 2 stages. At the first stage, SearchingAlgorithm's work and ContainingCheckAlgorithm waits for new jobs if the queue is empty. At second stage, all SearchingAlgorithm instances finished, and ContainingCheckAlgorithm quits if finds the queue empty. To discover if the queue is empty, ContainingCheckAlgorithm uses queue.poll(timeout) instead of queue.take().

And you need not to create new thread pool for each SearchingAlgorithm.

Body:
I was trying to implement some Consumer-Producer problem with BlockingQueue. To do it with some purpose, I decided to write file searching tool.

I decided that search mechanism is working recursively, and every new directory is going to have new thread pool to increase speed of searching.

My problem is, that I have no idea how can I implement mechanism that stops printing threads (consumers) at the end - when searching threads get job done.

I was trying to do that with some ideas like POISON PILLS, but it doesn't works well (threads stops before print any results). Any ideas how can I do that?

Here is some code:

Searching mechanism:

public class SearchingAlgorithm implements Runnable {

private final File file;
private BlockingQueue<File> queue;
private ExecutorService executor;

public SearchingAlgorithm(File fileName, BlockingQueue<File> queue) {
    this.file = fileName;
    this.queue = queue;
    this.executor = Executors.newWorkStealingPool();
}

@Override
public void run() {
    try {
        searchDeep();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void searchDeep() throws InterruptedException {
    File[] files = file.listFiles();
    if (files != null) {
        for (File fil : files) {
            if (fil.isDirectory()) {
                executor.submit(new SearchingAlgorithm(fil, this.queue));
            } else {
                this.queue.add(fil);
            }
        }
    }
}

}

Printer:

public class ContainingCheckAlgorithm implements Runnable {

private BlockingQueue<File> queue;
// private ExecutorService executor;
private String keyWord;

public ContainingCheckAlgorithm(BlockingQueue<File> queue, String keyWord) {
    this.queue = queue;
    this.keyWord = keyWord;
    // executor = Executors.newFixedThreadPool(2);
}

@Override
public void run() {
    try {
        printFile();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void printFile() throws InterruptedException {
    while (true) {
        File takeFile = queue.take();
        String fileName = takeFile.getAbsolutePath()
                .toLowerCase();
        boolean isContainingKeyWord = fileName.contains(keyWord.toLowerCase());

        if (isContainingKeyWord) {
            System.out.println(takeFile.getAbsolutePath());
        }
    }
}

}

Main test class:

public class MainClass {

public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    BlockingQueue<File> queue = new LinkedBlockingQueue<>();

    File fileName = new File("C:/");

    SearchingAlgorithm sa = new SearchingAlgorithm(fileName, queue);
    executor.submit(sa);

    ContainingCheckAlgorithm ca = new ContainingCheckAlgorithm(queue, "Slipknot");
    executor.submit(ca);

    executor.shutdown();
}

}


问:
Powershell create file on file server and open on desktop
I want to be able to create a file on a file server and then open this file on my PC right after the file creation. I have the following script (edited to hide confident info.)

```<code>Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path E:\foo\bar\'test test'\ $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName
</code>```

This script creates the file on the file server successfully, but does not open the file anywhere. Ive tried removing the if statement and that didn't seem to be the problem.
Can anyone help me?

答:
Not a very elegant solution as the$NewFilevariable isn't being used to open the file, but at least the script creates and opens a file at once.

```<code>Invoke-Command -ComputerName FileServer -ScriptBlock {
$NewFile = "Test.txt"
$path = Join-Path E:\folder1\'folder2'\'folder3 with spaces'\ $NewFile
New-Item $path -type file
} -Credential userName
Invoke-Item \\FileServer\folder1\'folder2'\'folder3 with spaces'\Test.txt
</code>```

Can anyone help improve the efficiency of this script by showing how to use the$NewFilevariable to open the file?

Body:
I want to be able to create a file on a file server and then open this file on my PC right after the file creation. I have the following script (edited to hide confident info.)

Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path E:\foo\bar\'test test'\ $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName

This script creates the file on the file server successfully, but does not open the file anywhere. Ive tried removing the if statement and that didn't seem to be the problem.
Can anyone help me?

Body:
Not a very elegant solution as the$NewFilevariable isn't being used to open the file, but at least the script creates and opens a file at once.

Invoke-Command -ComputerName FileServer -ScriptBlock {
$NewFile = "Test.txt"
$path = Join-Path E:\folder1\'folder2'\'folder3 with spaces'\ $NewFile
New-Item $path -type file
} -Credential userName
Invoke-Item \\FileServer\folder1\'folder2'\'folder3 with spaces'\Test.txt

Can anyone help improve the efficiency of this script by showing how to use the$NewFilevariable to open the file?


问:
acumatica fastfilter (inventory item search within sales order entry grid)
Looking to 'exclude' the inventory item description but 'add' a custom field against the inventory item master (called model).
I thought I found where this is stored in the aspx of the screen but any changes I make don't seem to make a difference.
Does anyone know if fastfilters can be edited/altered to exclude/include different fields?  Thanks in advance.</p>

答:
FastFilter fields in Form/Detail inquiry grid are inclusive, you pick only the one you need, the others are excluded by default.

For an Inquiry Grid, modify the property FastFilterFields of the Grid element. The value is a comma separated list of the field names you want to use as fast filters:

For an Inquiry Grid inside a Selector popup window, select the RowTemplate Editor for the Selector and look for the FastFilterFields in the collapsible GridProperties section. If required, expirement with the FilterByAllFields property.


问:
How can I get the value in this array?
I cannot figure out getting the string 'foo' printed from an array. How can I just print the value in 'tags'?</p>

```<code>print_r(array_values($res));

Array
(
    [0] => Array
        (
            [tags] => foo
        )

)
</code>```

答:
Arrays work in depth. You can have array that store arrays and so on. If:

```<code>$res = array ( 0 => array ( ['tags'] => 'foo' ) );
echo $res[0]['tags']; // foo
</code>```

does that make sense?

Also, be careful when using Array and array

Array
 vs array

Title: How can I get the value in this array?

Body:
I cannot figure out getting the string 'foo' printed from an array. How can I just print the value in 'tags'?

print_r(array_values($res));

Array
(
    [0] => Array
        (
            [tags] => foo
        )

)

Body:
Arrays work in depth. You can have array that store arrays and so on. If:

$res = array ( 0 => array ( ['tags'] => 'foo' ) );
echo $res[0]['tags']; // foo

does that make sense?

Also, be careful when using Array and array

Array
 vs array


问:
How do I right justify numbers with decimal points using Python 3.6
I am looking for a way to right justify the numbers in the output so all the decimal points line up, Using Python 3.6.1.

The general format I am using is:

```<code>print('Bonus: $',format(bonus, ',.2f'),sep='')
</code>```

but I cannot figure out how to get the numbers to right justify and keep the currency format.  Here's a pic of output:

答:
You could use: </p>

```<code>print('{:<15}: {:>10.2f}'.format('Bonus', bonus),sep='')
</code>```

<p>The > takes care of right alignment while the .2f takes care of the decimal points. </p>

Body:
I am looking for a way to right justify the numbers in the output so all the decimal points line up, Using Python 3.6.1.

The general format I am using is:

print('Bonus: $',format(bonus, ',.2f'),sep='')

but I cannot figure out how to get the numbers to right justify and keep the currency format.  Here's a pic of output:

Body:
You could use:

print('{:<15}: {:>10.2f}'.format('Bonus', bonus),sep='')

The > takes care of right alignment while the .2f takes care of the decimal points.


问:
RxJava2 that acts like AsyncTask in Android
Hi I just start learning Reactive programming using RxJava2.
How do I create a task that runs in the background thread and then complete on main thread using RxJava2.

Example in Android we use AsyncTask just like example below

```<code>private class MyTask extends AsyncTask<String, Integer, Boolean>
{
    @Override
    protected Boolean doInBackground(String... paths)
    {
        for (int index = 0; index < paths.length; index++)
        {
            boolean result = copyFileToExternal(paths[index]);

            if (result == true)
            {
                // update UI
                publishProgress(index);
            }
            else
            {
                // stop the background process
                return false;
            }
        }

        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values)
    {
        super.onProgressUpdate(values);
        int count = values[0];
        // this will update my textview to show the number of files copied
        myTextView.setText("Total files: " + count);
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        super.onPostExecute(result);
        if (result)
        {
            // display a success dialog
            ShowSuccessAlertDialog();
        }
        else
        {
            // display a fail dialog
            ShowFailAlertDialog();
        }
    }
}
</code>```

For this example I want to pass in a Array / ArrayList of Strings and it is use to execute some method in the background thread. Then every success result will update my TextView (UI thread). If one of the process fail, I want it to stop directly. Lastly I want to update my Views when the process has completed.

I only manage to get this far

```<code>Observable.just(paths).subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<ArrayList<String>>()
            {
                private boolean result;

                @Override
                public void onSubscribe(Disposable d)
                {
                }

                @Override
                public void onNext(ArrayList<String> paths)
                {
                    for (int index = 0; index < paths.size(); index++)
                    {
                        result = copyFileToExternal(paths[index]);

                        if (result == true)
                        {
                            // cant update UI because is in background thread
                            myTextView.setText("Total files: " + index);
                        }
                        else
                        {
                            // end the loop
                            break;
                        }
                    }
                }

                @Override
                public void onError(Throwable e)
                {
                }

                @Override
                public void onComplete()
                {
                    if (result)
                    {
                        // cant display because it is still in background thread
                        ShowSuccessAlertDialog();
                    }
                    else
                    {
                        // cant display because it is still in background thread
                        ShowFailAlertDialog();
                    }
                }
            });
</code>```

I looked at a few tutorials but can't seem to find the answer.

Thanks in advance for the help

答:
I'm new at this, but I got a working example..

```<code>//Observable
Observable.just("input_parameter")
            .subscribeOn(Schedulers.io())//creation of secondary thread
            .map(new Function<String, String>() {//<input obj,return obj>
                @Override
                public String apply(String cad){//input obj
                    Log.d(TAG,"thread :"+Thread.currentThread().getName());
                    //runs in a secondary thread
                    return "result text: "+doLongNetworkOperation();
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(MyObserver);//now this runs in main thread
</code>```

And MyObserver:

```<code>//Observer
Observer MyObserver = new Observer() {
    @Override
    public void onSubscribe(Disposable d) {
        Log.d(TAG,"onSubscribe thread:"+Thread.currentThread().getName());
    }

    @Override
    public void onNext(Object value) {
        Log.d(TAG,"on next, valor:<<"+value.toString()+">> \n nombre hilo:"+Thread.currentThread().getName());
    }

    @Override
    public void onError(Throwable e) {
        Log.d(TAG,"error "+e.toString());
    }

    @Override
    public void onComplete() {
        Log.d(TAG,"onCompleted thread:"+Thread.currentThread().getName());
    }
};
</code>```

Plz, let me know if this works for you.

Body:
Hi I just start learning Reactive programming using RxJava2.
How do I create a task that runs in the background thread and then complete on main thread using RxJava2.

Example in Android we use AsyncTask just like example below

private class MyTask extends AsyncTask<String, Integer, Boolean>
{
    @Override
    protected Boolean doInBackground(String... paths)
    {
        for (int index = 0; index < paths.length; index++)
        {
            boolean result = copyFileToExternal(paths[index]);

            if (result == true)
            {
                // update UI
                publishProgress(index);
            }
            else
            {
                // stop the background process
                return false;
            }
        }

        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values)
    {
        super.onProgressUpdate(values);
        int count = values[0];
        // this will update my textview to show the number of files copied
        myTextView.setText("Total files: " + count);
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        super.onPostExecute(result);
        if (result)
        {
            // display a success dialog
            ShowSuccessAlertDialog();
        }
        else
        {
            // display a fail dialog
            ShowFailAlertDialog();
        }
    }
}

For this example I want to pass in a Array / ArrayList of Strings and it is use to execute some method in the background thread. Then every success result will update my TextView (UI thread). If one of the process fail, I want it to stop directly. Lastly I want to update my Views when the process has completed.

I only manage to get this far

Observable.just(paths).subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<ArrayList<String>>()
            {
                private boolean result;

                @Override
                public void onSubscribe(Disposable d)
                {
                }

                @Override
                public void onNext(ArrayList<String> paths)
                {
                    for (int index = 0; index < paths.size(); index++)
                    {
                        result = copyFileToExternal(paths[index]);

                        if (result == true)
                        {
                            // cant update UI because is in background thread
                            myTextView.setText("Total files: " + index);
                        }
                        else
                        {
                            // end the loop
                            break;
                        }
                    }
                }

                @Override
                public void onError(Throwable e)
                {
                }

                @Override
                public void onComplete()
                {
                    if (result)
                    {
                        // cant display because it is still in background thread
                        ShowSuccessAlertDialog();
                    }
                    else
                    {
                        // cant display because it is still in background thread
                        ShowFailAlertDialog();
                    }
                }
            });

I looked at a few tutorials but can't seem to find the answer.

Thanks in advance for the help

Body:
I'm new at this, but I got a working example..

//Observable
Observable.just("input_parameter")
            .subscribeOn(Schedulers.io())//creation of secondary thread
            .map(new Function<String, String>() {//<input obj,return obj>
                @Override
                public String apply(String cad){//input obj
                    Log.d(TAG,"thread :"+Thread.currentThread().getName());
                    //runs in a secondary thread
                    return "result text: "+doLongNetworkOperation();
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(MyObserver);//now this runs in main thread

And MyObserver:

//Observer
Observer MyObserver = new Observer() {
    @Override
    public void onSubscribe(Disposable d) {
        Log.d(TAG,"onSubscribe thread:"+Thread.currentThread().getName());
    }

    @Override
    public void onNext(Object value) {
        Log.d(TAG,"on next, valor:<<"+value.toString()+">> \n nombre hilo:"+Thread.currentThread().getName());
    }

    @Override
    public void onError(Throwable e) {
        Log.d(TAG,"error "+e.toString());
    }

    @Override
    public void onComplete() {
        Log.d(TAG,"onCompleted thread:"+Thread.currentThread().getName());
    }
};

Plz, let me know if this works for you.


问:
scatter plot between two different datasets
I have two different datasets. Two different data frames. I would like to generate scatterplot for this.

```<code>Dataset1:

MT  NUM
D   103
M   67
D   90
W   456
MM  78
M   434

Dataset2:

MT  NUM
M   13
M   6
MM  9
W   45
D   7
</code>```

Scatterplot should look something like following:

I don't have any idea how to generate the plot. Can anyone tell me how to do this? Thank you

I used following code: But the plot looks completely different from what I want.

```<code>library(reshape)
hh <- melt(list(p1 = Dataset1, p2 = Dataset2), id.vars = "MT")

ggplot(hh, aes(MT, value, colour = L1)) + geom_point() +
  scale_colour_manual("Dataset", values = c("p1" = "blue", "p2" = "red"))
</code>```

答:
Not sure that's what you want, as the graph you show differs a lot from what you obtain from the code you wrote.

```<code>library(ggplot2)
df <- merge(df1, df2, by = 'MT')
ggplot(df) +
  geom_point(aes(NUM.x, NUM.y), color = '#0087E9', size = 5) +
  theme_minimal() +
  theme(axis.text = element_text(color = 'black', size = 16),
        axis.line = element_line(color = 'black'))
</code>```

Data

```<code>df1 <- structure(list(MT = structure(c(1L, 2L, 1L, 4L, 3L, 2L), .Label = c("D",
"M", "MM", "W"), class = "factor"), NUM = c(103L, 67L, 90L, 456L,
78L, 434L)), .Names = c("MT", "NUM"), class = "data.frame", row.names = c(NA,
-6L))

df2 <- structure(list(MT = structure(c(2L, 2L, 3L, 4L, 1L), .Label = c("D",
"M", "MM", "W"), class = "factor"), NUM = c(13L, 6L, 9L, 45L,
7L)), .Names = c("MT", "NUM"), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
I have two different datasets. Two different data frames. I would like to generate scatterplot for this.

Dataset1:

MT  NUM
D   103
M   67
D   90
W   456
MM  78
M   434

Dataset2:

MT  NUM
M   13
M   6
MM  9
W   45
D   7

Scatterplot should look something like following:

I don't have any idea how to generate the plot. Can anyone tell me how to do this? Thank you

I used following code: But the plot looks completely different from what I want.

library(reshape)
hh <- melt(list(p1 = Dataset1, p2 = Dataset2), id.vars = "MT")

ggplot(hh, aes(MT, value, colour = L1)) + geom_point() +
  scale_colour_manual("Dataset", values = c("p1" = "blue", "p2" = "red"))

Body:
Not sure that's what you want, as the graph you show differs a lot from what you obtain from the code you wrote.

library(ggplot2)
df <- merge(df1, df2, by = 'MT')
ggplot(df) +
  geom_point(aes(NUM.x, NUM.y), color = '#0087E9', size = 5) +
  theme_minimal() +
  theme(axis.text = element_text(color = 'black', size = 16),
        axis.line = element_line(color = 'black'))

Data

df1 <- structure(list(MT = structure(c(1L, 2L, 1L, 4L, 3L, 2L), .Label = c("D",
"M", "MM", "W"), class = "factor"), NUM = c(103L, 67L, 90L, 456L,
78L, 434L)), .Names = c("MT", "NUM"), class = "data.frame", row.names = c(NA,
-6L))

df2 <- structure(list(MT = structure(c(2L, 2L, 3L, 4L, 1L), .Label = c("D",
"M", "MM", "W"), class = "factor"), NUM = c(13L, 6L, 9L, 45L,
7L)), .Names = c("MT", "NUM"), class = "data.frame", row.names = c(NA,
-5L))


问:
How can I fade in the updated characters from an ng-model input?
My website uses an input  <input type="text" ng-model="name"> and a header
Hello {{name}}
. As it should, updated text appears as the user types in the input. Is it possible to have the individual characters fade in instead of just appear as the user types?

答: I think its best you use the NgModelController in your advantage here. With that you can read the users input and control what is outputted in the expression. I'm referring to the $viewValue and $modelValue. With this I assume you can create what you want to achieve...</p>


问:
MySQL - Foreign Key does not work even when InnoDB is on (Ubuntu 16.04)(Error code: 1215)
I am having a problem with an text-book example of MySQL table.
The trick is, it works on Windows OS but for some strange reason , it does not work for Linux. I tried configuring the default engine and it is InnoDB for sure, bot for some strange reason it still isn't working.

```<code>CREATE TABLE radnik(
     Mbr integer NOT NULL,
     Ime varchar(20) NOT NULL,
     Prz varchar(25) NOT NULL,
     Sef integer,
     Plt decimal(10, 2),
     Pre decimal(6, 2),
     God date NOT NULL,
     CONSTRAINT radnik_PK PRIMARY KEY (Mbr),
     CONSTRAINT radnik_FK FOREIGN KEY (Sef) REFERENCES radnik (Mbr),
     CONSTRAINT radnik_CH CHECK (Plt>500)
)engine=innodb;

CREATE TABLE projekat(
     Spr integer NOT NULL,
     Ruk integer NOT NULL,
     Nap varchar(50),
     Nar varchar(50),
     CONSTRAINT projekat_PK PRIMARY KEY (Spr),
     CONSTRAINT projekat_FK FOREIGN KEY (Ruk) REFERENCES radnik (Mbr),
     CONSTRAINT projekat_UK UNIQUE (Nap)
)engine=innodb;
CREATE TABLE radproj(
     Spr integer NOT NULL,
     Mbr integer NOT NULL,
     Brc integer NOT NULL,
     CONSTRAINT radproj_PK PRIMARY KEY (Spr, Mbr),
     CONSTRAINT radproj_rad_FK FOREIGN KEY (Mbr) REFERENCES radnik(Mbr),
     CONSTRAINT radproj_prj_FK FOREIGN KEY (Spr) REFERENCES projekat(Spr)
);
</code>```

答:
For a self-referencing foreign key, I don't think you can put the foreign key constraint in the CREATE TABLE statement. You have to create the table first, then add the constraint with ALTER TABLE.

This works for me.

```<code>CREATE TABLE radnik(
     Mbr integer NOT NULL,
     Ime varchar(20) NOT NULL,
     Prz varchar(25) NOT NULL,
     Sef integer,
     Plt decimal(10, 2),
     Pre decimal(6, 2),
     God date NOT NULL,
     CONSTRAINT radnik_PK PRIMARY KEY (Mbr)
)engine=innodb;

ALTER TABLE radnik ADD CONSTRAINT radnik_FK FOREIGN KEY (Sef) REFERENCES radnik (Mbr);
</code>```

BTW, MySQL ignores CHECK constraints.

Body:
I am having a problem with an text-book example of MySQL table.
The trick is, it works on Windows OS but for some strange reason , it does not work for Linux. I tried configuring the default engine and it is InnoDB for sure, bot for some strange reason it still isn't working.

CREATE TABLE radnik(
     Mbr integer NOT NULL,
     Ime varchar(20) NOT NULL,
     Prz varchar(25) NOT NULL,
     Sef integer,
     Plt decimal(10, 2),
     Pre decimal(6, 2),
     God date NOT NULL,
     CONSTRAINT radnik_PK PRIMARY KEY (Mbr),
     CONSTRAINT radnik_FK FOREIGN KEY (Sef) REFERENCES radnik (Mbr),
     CONSTRAINT radnik_CH CHECK (Plt>500)
)engine=innodb;

CREATE TABLE projekat(
     Spr integer NOT NULL,
     Ruk integer NOT NULL,
     Nap varchar(50),
     Nar varchar(50),
     CONSTRAINT projekat_PK PRIMARY KEY (Spr),
     CONSTRAINT projekat_FK FOREIGN KEY (Ruk) REFERENCES radnik (Mbr),
     CONSTRAINT projekat_UK UNIQUE (Nap)
)engine=innodb;
CREATE TABLE radproj(
     Spr integer NOT NULL,
     Mbr integer NOT NULL,
     Brc integer NOT NULL,
     CONSTRAINT radproj_PK PRIMARY KEY (Spr, Mbr),
     CONSTRAINT radproj_rad_FK FOREIGN KEY (Mbr) REFERENCES radnik(Mbr),
     CONSTRAINT radproj_prj_FK FOREIGN KEY (Spr) REFERENCES projekat(Spr)
);

Body:
For a self-referencing foreign key, I don't think you can put the foreign key constraint in the CREATE TABLE statement. You have to create the table first, then add the constraint with ALTER TABLE.

This works for me.

CREATE TABLE radnik(
     Mbr integer NOT NULL,
     Ime varchar(20) NOT NULL,
     Prz varchar(25) NOT NULL,
     Sef integer,
     Plt decimal(10, 2),
     Pre decimal(6, 2),
     God date NOT NULL,
     CONSTRAINT radnik_PK PRIMARY KEY (Mbr)
)engine=innodb;

ALTER TABLE radnik ADD CONSTRAINT radnik_FK FOREIGN KEY (Sef) REFERENCES radnik (Mbr);

BTW, MySQL ignores CHECK constraints.


问:
To fault or not to fault
I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.

One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:

ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)

GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found

The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.

What do you think?

答:
In the old days we used to have a rule that exceptions were only for exceptional and unexpected things. One of the reasons you did not want to use them too much was that they "cost" alot of computing power.

But if you use exceptions you can reduce the amount of code, no need for alot of if else statements, just let the exception bubble up.

It depends on your project. The most important thing is that there is a project standard and everyone does it the same way.

Title: To fault or not to fault


问:
Adding Global Password to Jenkins with init.groovy
How can I add a global passwords to Jenkins through the init.groovy that runs at startup?

To be clear, in the Manage Jenkins -> Configure Jenkins page, there is a section titled "Global Passwords". I would like to add entries in that section via Groovy code during the startup of Jenkins.

I am trying to provision my jenkins environment through groovy code by using the init.groovy. I need to add global passwords through the EnvInject plugin. I can successfully add path to a file for the same plugin using this code:

```<code>def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties =
    instance.getGlobalNodeProperties();

globalNodeProperties.add(
    new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties")
);
</code>```

However, I am failing to understand the mechanics needed to programmatically add global passwords.

答:
Here is the code example that should work. It seems that save() method also adds it to GlobalNodeProperties, so you don't have to add to that collection manually. </p>

```<code>import jenkins.model.*
import hudson.util.*
import hudson.slaves.NodeProperty
import hudson.slaves.NodePropertyDescriptor
import org.jenkinsci.plugins.envinject.*

def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties
                 = instance.getGlobalNodeProperties();

envInjectNodeProperty= new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties"
propDescriptor = envInjectNodeProperty.getDescriptor()

//password entry
def passEntry = new EnvInjectGlobalPasswordEntry("some_username", "password")
//password entries list, add you global password here
List<EnvInjectGlobalPasswordEntry> envInjectGlobalPasswordEntriesList= [passEntry];
propDescriptor.envInjectGlobalPasswordEntries =
          envInjectGlobalPasswordEntriesList.toArray(
          new EnvInjectGlobalPasswordEntry[envInjectGlobalPasswordEntriesList.size()]
         );
propDescriptor.save();
</code>```

Body:
How can I add a global passwords to Jenkins through the init.groovy that runs at startup?

To be clear, in the Manage Jenkins -> Configure Jenkins page, there is a section titled "Global Passwords". I would like to add entries in that section via Groovy code during the startup of Jenkins.

I am trying to provision my jenkins environment through groovy code by using the init.groovy. I need to add global passwords through the EnvInject plugin. I can successfully add path to a file for the same plugin using this code:

def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties =
    instance.getGlobalNodeProperties();

globalNodeProperties.add(
    new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties")
);

However, I am failing to understand the mechanics needed to programmatically add global passwords.

Body:
Here is the code example that should work. It seems that save() method also adds it to GlobalNodeProperties, so you don't have to add to that collection manually.

import jenkins.model.*
import hudson.util.*
import hudson.slaves.NodeProperty
import hudson.slaves.NodePropertyDescriptor
import org.jenkinsci.plugins.envinject.*

def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties
                 = instance.getGlobalNodeProperties();

envInjectNodeProperty= new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties"
propDescriptor = envInjectNodeProperty.getDescriptor()

//password entry
def passEntry = new EnvInjectGlobalPasswordEntry("some_username", "password")
//password entries list, add you global password here
List<EnvInjectGlobalPasswordEntry> envInjectGlobalPasswordEntriesList= [passEntry];
propDescriptor.envInjectGlobalPasswordEntries =
          envInjectGlobalPasswordEntriesList.toArray(
          new EnvInjectGlobalPasswordEntry[envInjectGlobalPasswordEntriesList.size()]
         );
propDescriptor.save();


问:
SimpleXML Dynamic Attributes
I'm trying to figure out how to generate the code for this.

```<code>$revImages = $revXML->addChild('images');
$revImage = $revImages->addChild('image');
$revImage->addAttribute('src', '001.jpg');
</code>```

the last line is the static entry for what I need. Is there a foreach statement I can use to auto generate that last line based on the images from a directory so it outputs as such:

```<code><images>
    <image src = "001.jpg"/>
    <image src = "002.jpg"/>
    <image src = "003.jpg"/>
    <image src = "004.jpg"/>
    <image src = "005.jpg"/>
    <image src = "006.jpg"/>
    <image src = "007.jpg"/>
    <image src = "008.jpg"/>
    <image src = "009.jpg"/>
    <image src = "010.jpg"/>
</images>
</code>```

答:
This is it:

```<code>$revImages = $revXML->addChild('images');
foreach ($some_data as $value) {
    // yes, everytime you need to create new `$revImage`
    $revImage = $revImages->addChild('image');
    $revImage->addAttribute('src', $value);
}
</code>```

where $some_data is array of values that you have.

Update:

```<code>if ($handle = opendir($path)) {
    // create parent node before while-loop
    $revImages = $revXML->addChild('images');
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            // yes, everytime you need to create new $revImage
            $revImage = $revImages->addChild('image');

            // `$entry` is already a filename, there's no need to iterate over it
            $revImage->addAttribute('src', $entry);
        }
    }
    closedir($handle);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: SimpleXML Dynamic Attributes

Body:
I'm trying to figure out how to generate the code for this.

$revImages = $revXML->addChild('images');
$revImage = $revImages->addChild('image');
$revImage->addAttribute('src', '001.jpg');

the last line is the static entry for what I need. Is there a foreach statement I can use to auto generate that last line based on the images from a directory so it outputs as such:

<images>
    <image src = "001.jpg"/>
    <image src = "002.jpg"/>
    <image src = "003.jpg"/>
    <image src = "004.jpg"/>
    <image src = "005.jpg"/>
    <image src = "006.jpg"/>
    <image src = "007.jpg"/>
    <image src = "008.jpg"/>
    <image src = "009.jpg"/>
    <image src = "010.jpg"/>
</images>

Body:
This is it:

$revImages = $revXML->addChild('images');
foreach ($some_data as $value) {
    // yes, everytime you need to create new `$revImage`
    $revImage = $revImages->addChild('image');
    $revImage->addAttribute('src', $value);
}

where $some_data is array of values that you have.

Update:

if ($handle = opendir($path)) {
    // create parent node before while-loop
    $revImages = $revXML->addChild('images');
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            // yes, everytime you need to create new $revImage
            $revImage = $revImages->addChild('image');

            // `$entry` is already a filename, there's no need to iterate over it
            $revImage->addAttribute('src', $entry);
        }
    }
    closedir($handle);
}


问:
VBA Excel - Access Query not updateable
I am getting an error trying to run a query through VBA in Excel.

Error:

Run-time error '3073':
  Operation must use an updateable query.

I have a query that is fetching data from one table in Excel.

qryAllData:

```<code>SELECT ID, Field1 AS [Date], Field9 AS [Alarm Init], Field5 AS [Alarm End], CVDate(Field2) AS [Time]
FROM [Jet Info]
WHERE (Field3 LIKE 'ALARM' OR Field8 LIKE 'ALARM:') AND Field5 NOT LIKE 'Program' AND (Field9 NOT LIKE 'Program' OR ISNULL(Field9));
</code>```

I originally had been directly referencing this query in Excel but was still getting the above error, so I tried referencing the query instead.

qrySelData:

```<code>SELECT DISTINCTROW TOP 1 a.*
FROM [Process Info] AS a, [Complete Data] AS b
WHERE (((a.Date) Not In (SELECT [Date] FROM [Complete Data])) AND ((a.[Start Time]) Not In (SELECT [Start Time] FROM [Complete Data])));
</code>```

Here is my VBA code:

```<code> Private Sub CommandButton1_Click()
     Refresh_Data
     Dim objAccess As Object

     Set objAccess = GetObject("C:\Users\******\Documents\Database21.accdb")

     objAccess.Visible = False

     objAccess.DoCmd.OpenQuery ("qrySelData")

     objAccess.Quit
     Set objAccess = Nothing
 End Sub
</code>```

Running the sub in VBA throws error 3072 on the objAccess.DoCmd.OpenQuery ("qrySelData") line.

Any help would be appreciated - if you need more info let me know.

答:
The first query is not updatable because you are using function (cvdate) in select column list. Remove this column or function and it should work.

Second query (seems to be completly different) have missing join condition between [Process Info] and [Complete Data]. This means Access tries to produce carthesian product and simply have not enough memory...

On first look I would say in second query you should remove [Complete Data] from FROM clause (if you anyway don't join those tables).

Title: VBA Excel - Access Query not updateable

Body:
I am getting an error trying to run a query through VBA in Excel.

Error:

Run-time error '3073':
  Operation must use an updateable query.

I have a query that is fetching data from one table in Excel.

qryAllData:

SELECT ID, Field1 AS [Date], Field9 AS [Alarm Init], Field5 AS [Alarm End], CVDate(Field2) AS [Time]
FROM [Jet Info]
WHERE (Field3 LIKE 'ALARM' OR Field8 LIKE 'ALARM:') AND Field5 NOT LIKE 'Program' AND (Field9 NOT LIKE 'Program' OR ISNULL(Field9));

I originally had been directly referencing this query in Excel but was still getting the above error, so I tried referencing the query instead.

qrySelData:

SELECT DISTINCTROW TOP 1 a.*
FROM [Process Info] AS a, [Complete Data] AS b
WHERE (((a.Date) Not In (SELECT [Date] FROM [Complete Data])) AND ((a.[Start Time]) Not In (SELECT [Start Time] FROM [Complete Data])));

Here is my VBA code:

 Private Sub CommandButton1_Click()
     Refresh_Data
     Dim objAccess As Object

     Set objAccess = GetObject("C:\Users\******\Documents\Database21.accdb")

     objAccess.Visible = False

     objAccess.DoCmd.OpenQuery ("qrySelData")

     objAccess.Quit
     Set objAccess = Nothing
 End Sub

Running the sub in VBA throws error 3072 on the objAccess.DoCmd.OpenQuery ("qrySelData") line.

Any help would be appreciated - if you need more info let me know.


问:
Gulp Error: Cannot find module 'jshint/src/cli'
So I've got a fresh install of El Capitan and I'm giving these task runners another go.

I'm following sitepoint's An introduction to Gulp.js, but I'm stuck on step four, when I try to run gulp jshint I get "Error: Cannot find module 'jshint/src/cli'"

I've no idea what's causing this, which is why I'm asking here. Below are a couple of screen grabs to help with the issue.

As always, I'm eternally grateful for any advice.

答:
Here you target jshint, which you probably didn't install. (You do this in gulp.task('jshint', function() {.)

Try this:

```<code>gulp.task('gulp-jshint', function() {
</code>```

This matches the way you required it.

```<code>var jshint = require('gulp-jshint');
</code>```

Body:
Here you target jshint, which you probably didn't install. (You do this in gulp.task('jshint', function() {.)

Try this:

gulp.task('gulp-jshint', function() {

This matches the way you required it.

var jshint = require('gulp-jshint');


问:
ElasticSearch 5.x Context Suggester - single context multiple value
I am trying to use completion context with multiple value.
Context accept only one value.

```<code>string contextValue = "10";
List<string> listOfContextValues = new List<string> {"10", "20","30"};
var a = Client.Search<Post>(s => s
            .Suggest(su => su
                .Completion("categories", cs => cs
                    .Field(f => f.CSuggest)
                    .Prefix(query)
                    .Contexts(co => co
                        .Context("sourceid",
                            cd => cd.Context(contextValue)
                    )
                )
            )
        ));
</code>```

I don't know how to filter my suggest field with listOfContextValues.

Update

When i using a for loop and passing single context as filter and storing result in a list.

And also using Russ suggested code and storing result in a list.
But Some result are missing in second list.

As you can see in below:

```<code>var socialNetworks = srvUser.GetUserSocialNetworks(userId);

List<string> tags = new List<string>();
foreach (var socialNetwork in socialNetworks)
{
    var result = Client.Search<Post>(s => s
        .Suggest(su => su
            .Completion("categories", cs => cs
                .Field(f => f.CSuggest)
                .Prefix(query)
                .Contexts(co => co
                    .Context("sourceid",
                        cd => cd.Context(socialNetwork)
                    )
                )
            )
        ));
    List<string> br = result.Suggest["categories"].SelectMany(x => x.Options)
        .Select(y => y.Text).Distinct().ToList();
    tags.AddRange(br);
}

var searchResponse = Client.Search<Post>(s => s
    .Suggest(su => su
        .Completion("categories", cs => cs
            .Field(f => f.CSuggest)
            .Prefix(query)
            .Contexts(co => co
                .Context("sourceid", socialNetworks
                    .Select<string, Func<SuggestContextQueryDescriptor<Post>, ISuggestContextQuery>>(v => cd => cd.Context(v))
                    .ToArray()

                )
            )
        )
    )
);
List<string> sa = searchResponse.Suggest["categories"].SelectMany(x => x.Options).Select(y => y.Text).Distinct().ToList();
if (sa.Count != tags.Count)
{
    // >>>>> counts are not the same
}
</code>```

答:
.Context(...) takes a params Func<SuggestContextQueryDescriptor<T>, ISuggestContextQuery>[] as the second argument, so for a collection of context values you can do

```<code>void Main()
{
    var client = new ElasticClient();
    var listOfContextValues = new List<string> { "10", "20", "30" };
    var query = "query";

    var searchResponse = client.Search<Post>(s => s
                .Suggest(su => su
                    .Completion("categories", cs => cs
                        .Field(f => f.CSuggest)
                        .Prefix(query)
                        .Contexts(co => co
                            .Context("sourceid",
                                listOfContextValues
                                    .Select<string, Func<SuggestContextQueryDescriptor<Post>, ISuggestContextQuery>>(v => cd => cd.Context(v))
                                    .ToArray()
                            )
                        )
                    )
                )
            );
}

public class Post
{
    public CompletionField CSuggest { get; set; }
}
</code>```

Body:
I am trying to use completion context with multiple value.
Context accept only one value.

string contextValue = "10";
List<string> listOfContextValues = new List<string> {"10", "20","30"};
var a = Client.Search<Post>(s => s
            .Suggest(su => su
                .Completion("categories", cs => cs
                    .Field(f => f.CSuggest)
                    .Prefix(query)
                    .Contexts(co => co
                        .Context("sourceid",
                            cd => cd.Context(contextValue)
                    )
                )
            )
        ));

I don't know how to filter my suggest field with listOfContextValues.

Update

When i using a for loop and passing single context as filter and storing result in a list.

And also using Russ suggested code and storing result in a list.
But Some result are missing in second list.

As you can see in below:

var socialNetworks = srvUser.GetUserSocialNetworks(userId);

List<string> tags = new List<string>();
foreach (var socialNetwork in socialNetworks)
{
    var result = Client.Search<Post>(s => s
        .Suggest(su => su
            .Completion("categories", cs => cs
                .Field(f => f.CSuggest)
                .Prefix(query)
                .Contexts(co => co
                    .Context("sourceid",
                        cd => cd.Context(socialNetwork)
                    )
                )
            )
        ));
    List<string> br = result.Suggest["categories"].SelectMany(x => x.Options)
        .Select(y => y.Text).Distinct().ToList();
    tags.AddRange(br);
}

var searchResponse = Client.Search<Post>(s => s
    .Suggest(su => su
        .Completion("categories", cs => cs
            .Field(f => f.CSuggest)
            .Prefix(query)
            .Contexts(co => co
                .Context("sourceid", socialNetworks
                    .Select<string, Func<SuggestContextQueryDescriptor<Post>, ISuggestContextQuery>>(v => cd => cd.Context(v))
                    .ToArray()

                )
            )
        )
    )
);
List<string> sa = searchResponse.Suggest["categories"].SelectMany(x => x.Options).Select(y => y.Text).Distinct().ToList();
if (sa.Count != tags.Count)
{
    // >>>>> counts are not the same
}

Body:
.Context(...) takes a params Func<SuggestContextQueryDescriptor<T>, ISuggestContextQuery>[] as the second argument, so for a collection of context values you can do

void Main()
{
    var client = new ElasticClient();
    var listOfContextValues = new List<string> { "10", "20", "30" };
    var query = "query";

    var searchResponse = client.Search<Post>(s => s
                .Suggest(su => su
                    .Completion("categories", cs => cs
                        .Field(f => f.CSuggest)
                        .Prefix(query)
                        .Contexts(co => co
                            .Context("sourceid",
                                listOfContextValues
                                    .Select<string, Func<SuggestContextQueryDescriptor<Post>, ISuggestContextQuery>>(v => cd => cd.Context(v))
                                    .ToArray()
                            )
                        )
                    )
                )
            );
}

public class Post
{
    public CompletionField CSuggest { get; set; }
}