问:
How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker
I have following datepicker script: </p>

```<code><script>
 $(function(){
        $("#to").datepicker();
        $("#from").datepicker().bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("mm/dd/yy", minValue);
            minValue.setDate(minValue.getDate()+1);
            $("#to").datepicker( "option", "minDate", minValue );
        })
    });
</script>
</code>```

<p>Now dateformat is MM/DD/YY .how to change the date format to YYYY-MM-DD? </p>

答:
If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date:

<input type="text" data-date-format='yyyy-mm-dd'  id="selectdateadmin" class="form-control" required>```
</div>
</div>
</p>

<p>And in javascript below this page add your date picker code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $('#selectdateadmin').focusin( function()
     {
       $("#selectdateadmin").datepicker();

     });</code>```

Body:
I have following datepicker script:

Now dateformat is MM/DD/YY .how to change the date format to YYYY-MM-DD?

Body:
If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date:

<input type="text" data-date-format='yyyy-mm-dd'  id="selectdateadmin" class="form-control" required>

And in javascript below this page add your date picker code:

 $('#selectdateadmin').focusin( function()
     {
       $("#selectdateadmin").datepicker();

     });


来源: stackexchange

问:
CMake build error: Qt5PrintSupportConfig.cmake missing
I am trying to build build a C++ toolkit called MITK with CMake. But I am getting this Qt5 related error. I am using the open source version of Qt 5.7.1. I can't find any file with the name Qt5PrintSupportConfig.cmake inside the Qt5 folder. The closest thing I found was windowsprintersupport.dll inside the folder printsupport. What could be the probem?

```<code>CMake Error at C:/Qt5.7.1/5.7/winrt_x64_msvc2015/lib/cmake/Qt5/Qt5Config.cmake:26 (find_package):
Could not find a package configuration file provided by "Qt5PrintSupport" with any of the following names:

    Qt5PrintSupportConfig.cmake
    qt5printsupport-config.cmake

Add the installation prefix of "Qt5PrintSupport" to CMAKE_PREFIX_PATH or
set "Qt5PrintSupport_DIR" to a directory containing one of the above files.

If "Qt5PrintSupport" provides a separate development package or SDK, be sure it has been installed.
Call Stack (most recent call first): CMakeLists.txt:211 (find_package)
</code>```

答:
You downloaded the wrong Qt online installer.

The one which you installed is from here: https://www.qt.io/download/

The one which you want is here: https://www.qt.io/download-open-source/ for the latest version or here https://download.qt.io/archive/online_installers/2.0/ for older versions.

I am not sure what the difference is but the one you probably installed is the normal version while the one you need is the unified version, whatever that means. Once you installed it, check this directory: C:\Qt\5.7\msvc2015_64\lib\cmake\Qt5PrintSupport since now it should include the Qt5PrintSupportConfig.cmake file.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to build build a C++ toolkit called MITK with CMake. But I am getting this Qt5 related error. I am using the open source version of Qt 5.7.1. I can't find any file with the name Qt5PrintSupportConfig.cmake inside the Qt5 folder. The closest thing I found was windowsprintersupport.dll inside the folder printsupport. What could be the probem?

CMake Error at C:/Qt5.7.1/5.7/winrt_x64_msvc2015/lib/cmake/Qt5/Qt5Config.cmake:26 (find_package):
Could not find a package configuration file provided by "Qt5PrintSupport" with any of the following names:

    Qt5PrintSupportConfig.cmake
    qt5printsupport-config.cmake

Add the installation prefix of "Qt5PrintSupport" to CMAKE_PREFIX_PATH or
set "Qt5PrintSupport_DIR" to a directory containing one of the above files.

If "Qt5PrintSupport" provides a separate development package or SDK, be sure it has been installed.
Call Stack (most recent call first): CMakeLists.txt:211 (find_package)


问:
How to convert exponential number to decimal numbers in action script 3?
I am facing the problem on multiplying two decimal number in flex.

When i am multiplying two decimal number the result is like a exponential number so i don't know how to get the decimal number as a result instead of getting an exponential number.

I am using the following codes to make a multiplication:

```<code>var num1:Number = 0.00005;
var num2:Number = 0.000007;
var result:Number = num1 * num2;
</code>```

And in result variable i am getting the value as 3.5000000000000003E-10.

So i don't know how to get decimal number as result instead of getting an exponential number as above.

If anybody have knowledge how to resolve this problem please help me to solve.

答:
You need to use the .toPrecision(precision:uint) method available in the Number class. This method takes one parameter which is :

precision:uint — An integer between 1 and 21, inclusive, that
  represents the desired number of digits to represent in the resulting
  string.

So simply do :

```<code>trace(result.toPrecision(2));
</code>```

And you should get an output of 0.00000000035

Official documentation here :

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Number.html#toPrecision()

Hope this helps. Cheers.

Body:
I am facing the problem on multiplying two decimal number in flex.

When i am multiplying two decimal number the result is like a exponential number so i don't know how to get the decimal number as a result instead of getting an exponential number.

I am using the following codes to make a multiplication:

var num1:Number = 0.00005;
var num2:Number = 0.000007;
var result:Number = num1 * num2;

And in result variable i am getting the value as 3.5000000000000003E-10.

So i don't know how to get decimal number as result instead of getting an exponential number as above.

If anybody have knowledge how to resolve this problem please help me to solve.

Body:
You need to use the .toPrecision(precision:uint) method available in the Number class. This method takes one parameter which is :

precision:uint — An integer between 1 and 21, inclusive, that
  represents the desired number of digits to represent in the resulting
  string.

So simply do :

trace(result.toPrecision(2));

And you should get an output of 0.00000000035

Official documentation here :

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Number.html#toPrecision()

Hope this helps. Cheers.


问:
Why does Azure SDK for PHP not working well with Azure General-purpose Storage
Is Azure SDK for PHP Blob Storage method works only on a Blob Storage account? Because whenever I tried to use it on an Azure General-purpose Storage account (which gives you access to Azure Storage services such as Tables, Queues, Files, Blobs and Azure virtual machine disks under a single account), my php program stops at an specific process in an inconsistent manner. At times it processes completely but when I re-run it, it stops again in a random point.

My goal is to get all blobs under my Azure subscription using foreach loop, given that I have an array variable that holds connection strings for each storage accounts. It works well with a Blob Storage account but whenever I include the General-purpose Storage account, the problem starts to occur.

I already tried overriding my php memory limit and still it does not solve the issue.

Any advise guys? Thank you in advance.

答:
```<code>//Here is my code for you to visualize my goal..

<!DOCTYPE html>
<?php
require_once "vendor/autoload.php";
include_once 'Dbcon.php';

use MicrosoftAzure\Storage\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\ServiceException;

if (($handle = fopen("csv/azurestorages.csv", "r")) !== FALSE) {
    fgetcsv($handle);
    $acc_cred = array();
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
            $acc_cred[$data[0]][$c] = $data[$c];
        }
   }
}
fclose($handle);

$all_storage = array();

foreach($acc_cred as $ac){

    $connstr = "DefaultEndpointsProtocol=http;AccountName=$ac[0];AccountKey=$ac[1]";

    // Create blob REST proxy.
    $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connstr);

    // List all containers
    $container = $blobRestProxy->listContainers();
    $containers = $container->getContainers();

    if (count($containers) > 0) {

        $blob_xyzrobot = array();

        foreach($containers as $c){
            $blob_xyzrobot[] = $c->getName();
        }

        foreach($blob_xyzrobot as $bx)
        {
                $uri_segments = array();
                $blobstoragename = array();

                // List blobs.
                $blob_list = $blobRestProxy->listBlobs($bx);

                $blobs = $blob_list->getBlobs();

                if (count($blobs) > 0) {

                    $ctr = 0;
                    $uri_segments = explode('/', $blobs[0]->getUrl());
                    $blobstoragename = explode('.',$uri_segments[2]);

                    foreach($blobs as $blob)
                    {
                        $bprename = $blobstoragename[0];
                        $all_storage[$bprename."|".$bx][$ctr]['storage'] = $blobstoragename[0];
                        $all_storage[$bprename."|".$bx][$ctr]['container'] = $bx;
                        $all_storage[$bprename."|".$bx][$ctr]['whatdate'] = $blob->getProperties()->getLastModified()->format('Y-m-d');
                        $all_storage[$bprename."|".$bx][$ctr]['blob'] = $blob->getName();
                        $all_storage[$bprename."|".$bx][$ctr]['bytesize'] = $blob->getProperties()->getContentLength();
                        $all_storage[$bprename."|".$bx][$ctr]['datecreated'] = date("Y-m-d H:i:s");
                        $ctr++;
                    }
                }
        }
    }
}
if (count($all_storage) > 0){
   print_r($all_storage);
}else{
   echo "No blobs in found...";
}

?>
</code>```


问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答:
Some observations :

You are getting ['0'] because you are calling Object.keys() on an array instead of an object.

Object.keys() will return keys not the values.

As Robby said that the order of an object's properties is not guaranteed in JavaScript, so neither will be the order of your resulting array

DEMO

Using Array map() method.

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

var arr = [];
result.map(function(item) {
    arr.push(item.id, item.employeeDetails.id, item.employeeDetails.version);
});

console.log(arr);```
</div>
</div>
</p>

<ul>
<li>Using <strong>for...in</strong> loop</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

var arr = [];
for (var i in result) {
  arr.push(result[i].id, result[i].employeeDetails.id, result[i].employeeDetails.version);
}

console.log(arr);</code>```

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

Body:
Some observations :

You are getting ['0'] because you are calling Object.keys() on an array instead of an object.

Object.keys() will return keys not the values.

As Robby said that the order of an object's properties is not guaranteed in JavaScript, so neither will be the order of your resulting array

DEMO

Using Array map() method.

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

var arr = [];
result.map(function(item) {
    arr.push(item.id, item.employeeDetails.id, item.employeeDetails.version);
});

console.log(arr);

Using for...in loop

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

var arr = [];
for (var i in result) {
  arr.push(result[i].id, result[i].employeeDetails.id, result[i].employeeDetails.version);
}

console.log(arr);


问:
What's the difference between Virtual-8086 Mode and Real-Address Mode in x86 processor
In wikipedia, the explanation of virtual 8086 mode is said that

In the 80386 microprocessor and later, virtual 8086 mode (also called
      virtual real mode, V86-mode or VM86) allows the execution of real mode
      applications that are incapable of running directly in protected mode while
      the processor is running a protected mode operating system

I think this means that virtual 8086 mode can access to system memory and hardware devices.

And the explanation of real-address mode

Real mode, also called real address mode, is an operating mode of all
      x86-compatible CPUs. Real mode is characterized by a 20-bit segmented
      memory address space (giving exactly 1 MiB of addressable memory) and
      unlimited direct software access to all addressable memory, I/O addresses
      and peripheral hardware. Real mode provides no support for memory
      protection, multitasking, or code privilege levels

I think there is no difference between them.
anybody knows it??

答: Virtual-x86 is Real-address mode that is working in protected mode.</p>


问:
ORA-00979: not a GROUP BY expression when I execute my sql
When I execute my SQL, I get the below error:

My exception is:

```<code>[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression
</code>```

My SQL is below:

```<code>select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)
</code>```

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

答:
The issue is that you are ordering by something that is not in your group by clause.

For example, this works

```<code>SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by one;

       ONE
----------
         1
</code>```

If you order by a column that is not in your group by clause:

```<code>SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by two;
select one
       *
ERROR at line 2:
ORA-00979: not a GROUP BY expression
</code>```

If you edit the group by clause to handle the column you need in the order by:

```<code>SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by one, two;

       ONE
----------
         1

SQL>
</code>```

Body:
When I execute my SQL, I get the below error:

My exception is:

[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression

My SQL is below:

select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

Body:
The issue is that you are ordering by something that is not in your group by clause.

For example, this works

SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by one;

       ONE
----------
         1

If you order by a column that is not in your group by clause:

SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by two;
select one
       *
ERROR at line 2:
ORA-00979: not a GROUP BY expression

If you edit the group by clause to handle the column you need in the order by:

SQL> with testGroup as ( select 1 as one, 2 as two from dual)
  2  select one
  3  from testGroup
  4  group by one, two;

       ONE
----------
         1

SQL>


问:
How to set a Image Button's image xcode aplescript OBJC
I am trying to change an Image Button's image object with this code using applescript.

I have tried this:

property theButton : missing Value

on button_(sender)
set newImage to "example.png"
changeImage(newImage)
end button_

on changeImage(newImage)
set theImage to current application's NSImage's imageNamed_(newImage)
theButton's setImage_(theImage)
end changeImage

答:
```<code>on changeSomeImage_(newImage, targetObjectOutlet, newText, targetLableOutlet)

set newImage1 to current application's NSImage's imageNamed_(newImage)
targetObjectOutlet's setImage_(newImage1)
targetLableOutlet's setStringValue_(newText)

end changeSomeImage_
</code>```


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
When I was first learning, I think arrays for sure. Before that I really just thought in terms of single variables. When I learned about arrays, I was able to do a lot lot more with my qbasic :).

Now I have all sorts of data structures available, not just arrays :)

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: Doug T.


问:
Who sent you?
I have a series of input forms, all of them take a different form action. Each of those validates input. If ok, they go to different success pages. If fail, I want the form action/validation pages to set $_SESSION['error_messages'] and go to a common page which displays the errors and has a "resubmit" button.

Question ... how to get error form the resubmit button back to one of many possible input forms?

Edit: I don't see how $_SERVER['HTTP_REFERER'] is going to work. Again: form --> validation --> error_page

So, I guess that validation has to set  a session variable from $_SERVER['HTTP_REFERER']

答:
USing HTTP_REFERER is an option, but possibly not the most viable one, as the referrer header is easily spoofable (and not all the browsers will send it). This may or may not interfere with your process.

The easiest thing to do, as you are already setting error messages in $_SESSION is to also add a $_SESSION['redirect_url'] value.

Title: Who sent you?


问:
Difference between an object in Java versus an object in Scala
I have started learning Scala.Is there any difference between an object in Java versus an object in Scala. As per my understanding the object created in Scala is singleton. Any other pointers please. </p>

答:
In Java, Object (upper case) is the top class. All classes extend Object. Primitive types (int, long, etc) don't extend Object because they are not a class

In Scala, there's a a different hierarchy. Everything extends class Any: reference types extend AnyRef, and value types extend AnyVal, unlike Java, there are no primitives. (check docs: http://docs.scala-lang.org/tutorials/tour/unified-types)

But the object you are referring in Scala is a singleton yes. It's very common to have a class that you want to be a singleton. In java there's a pattern to achieve that (for instance http://www.javaworld.com/article/2073352/core-java/simply-singleton.html), in scala they created the object keyword as a shorthand.

there is also a special case: when there's a class and an object with the same name defined in the same compilation unit, the object is called a companion object, and basically you can think of it as holding the static methods you would have in Java

More on the subject at http://docs.scala-lang.org/tutorials/tour/singleton-objects.html


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
This is because your are giving padding and border-radius to the image itself. Instead, add a SPAN tag give it border properties and inset img tag inside it. It will give you the desired output.

.icon_circle {
  overflow: hidden;
}

span {
  display: block;
  border-radius: 50%;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <table>
    <tr>
      <td><span>
        <img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt="">
        </span></td>
      <td><span><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></span></td>
      <td><span><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></span></td>
    </tr>
  </table>
  <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
</div></code>```

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
This is because your are giving padding and border-radius to the image itself. Instead, add a SPAN tag give it border properties and inset img tag inside it. It will give you the desired output.

.icon_circle {
  overflow: hidden;
}

span {
  display: block;
  border-radius: 50%;
  padding: 30px;
  border: #000 5px solid;
}

<div class="slideshow">
  <table>
    <tr>
      <td><span>
        <img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt="">
        </span></td>
      <td><span><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></span></td>
      <td><span><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></span></td>
    </tr>
  </table>
  <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
</div>


问:
Passing a shell variable into an awk command
I have a loop that processes a bunch of files within a dir. I would like to input the filename into the file it processes, but I'm getting an error. It works perfectly with the myvar syntax but I need that for obvious reasons.

Error

```<code>awk: cmd. line:1: RS=
awk: cmd. line:1:    ^ unexpected newline or end of string
</code>```

Command

```<code>for filename in $files
do
    awk -v "myvar=${filename}"
      RS= '/-- Ticket/{++i; print "PROMPT myvar Line ",
      i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done
</code>```

答:
If you could avoid a batch loop, it's better (performance mainly for subshell fork, ...)</p>

```<code># assume TXT_files is the list of $files with .txt extension (not purpose of this OP)
awk RS='' '
   /-- Ticket/{
     # get the file name without extension
     myvar = FILENAME;sub( /\.txt$/,"",myvar)

     print "PROMPT " myvar " Line " ++i ORS $0 ORS

     i += split( $0, a, /\n/) + 1
     }
   ' ${TXT_files}
</code>```

Body:
I have a loop that processes a bunch of files within a dir. I would like to input the filename into the file it processes, but I'm getting an error. It works perfectly with the myvar syntax but I need that for obvious reasons.

Error

awk: cmd. line:1: RS=
awk: cmd. line:1:    ^ unexpected newline or end of string

Command

for filename in $files
do
    awk -v "myvar=${filename}"
      RS= '/-- Ticket/{++i; print "PROMPT myvar Line ",
      i ORS $0 ORS; i+=split($0, a, /\n/)+1}' ${filename}.txt
done

Body:
If you could avoid a batch loop, it's better (performance mainly for subshell fork, ...)

# assume TXT_files is the list of $files with .txt extension (not purpose of this OP)
awk RS='' '
   /-- Ticket/{
     # get the file name without extension
     myvar = FILENAME;sub( /\.txt$/,"",myvar)

     print "PROMPT " myvar " Line " ++i ORS $0 ORS

     i += split( $0, a, /\n/) + 1
     }
   ' ${TXT_files}


问:
getElementsByName in opera, ie etc
this is my code to fix compability getElementById in ie,ff,opera etc

```<code>    function getId(item) {
        if( window.mmIsOpera ) return(document.getElementById(item));
        if (document.all) return(document.all[item]);
        if (document.getElementById) return(document.getElementById(item));
    return(false);
    }
</code>```

my question is, how about getElementsByName in ie,ff, opera..

答:
i got the solution last night...

and to get value from text field, just add an atribut "name" in form..
like David Dorward said : document.nameOfForm.nameOfTextfield.value

Title: getElementsByName in opera, ie etc

Body:
this is my code to fix compability getElementById in ie,ff,opera etc

    function getId(item) {
        if( window.mmIsOpera ) return(document.getElementById(item));
        if (document.all) return(document.all[item]);
        if (document.getElementById) return(document.getElementById(item));
    return(false);
    }

my question is, how about getElementsByName in ie,ff, opera..


问:
Watch DOM for new elements (VanillaJS)
I'm working on a Chrome extension, which parses the DOM and transforms some text nodes based on certain criteria. I am using pure Javascript, i.e. no jQuery or another framework, and I want to keep it that way.

How can I watch the DOM for new dynamically inserted elements, so I can run my parser on them too?

Again, please don't suggest any jQuery solutions, or solutions using anything but pure Javascript.

答:
The accepted answer actually doesn't work, for a couple of reasons (explained below).

Instead, I would suggest this:

```<code>var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(function(addedNode) {
      // Do things to `addedNode` here
    });
  });
});

observer.observe(document.body, {childList: true, subtree: true});
</code>```

...because, as miniml correctly points out, subtree: true is required to receive events for elements added that aren't direct children, and the arguments passed to the listener callback is an array of MutationRecords.

Also, I've chosen document.body as my observation root since I don't think listening for elements dynamically inserted into  is something most people are interested in. (But if that is desired, then just replace document.body with document.documentElement or just document.)

Fun side note: in the accepted answer, the only time that listener would ever actually fire at all would be if someone literally removed the  element and/or re-created it afterward. That's it. (Because the document object is only allowed to have one Element child.)

Title: Watch DOM for new elements (VanillaJS)

Body:
The accepted answer actually doesn't work, for a couple of reasons (explained below).

Instead, I would suggest this:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(function(addedNode) {
      // Do things to `addedNode` here
    });
  });
});

observer.observe(document.body, {childList: true, subtree: true});

...because, as miniml correctly points out, subtree: true is required to receive events for elements added that aren't direct children, and the arguments passed to the listener callback is an array of MutationRecords.

Also, I've chosen document.body as my observation root since I don't think listening for elements dynamically inserted into <head> is something most people are interested in. (But if that is desired, then just replace document.body with document.documentElement or just document.)

Fun side note: in the accepted answer, the only time that listener would ever actually fire at all would be if someone literally removed the <html> element and/or re-created it afterward. That's it. (Because the document object is only allowed to have one Element child.)


问:
how to make phone number clickable in classifield wordpress
I tried everything to make the phone number clickable but for some reason it didn't work

```<code>    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>
    <li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><?php echo $post_phone; ?></li>
</code>```

I added this and it still didn't work :

```<code><a href="tel:$post_phone"> $post_phone</a>
</code>```

and this

```<code><li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a></li>
                        <?php }?>
</code>```

Thank you so much for your help

答:
This should work</p>

```<code><a href="tel:<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a>
</code>```

Body:
I tried everything to make the phone number clickable but for some reason it didn't work

    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>

<?php esc_html_e( 'Phone', 'classiera' ); ?><?php echo $post_phone; ?>

I added this and it still didn't work :

 $post_phone

and this

<?php esc_html_e( 'Phone', 'classiera' ); ?><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?>

                        <?php }?>

Thank you so much for your help

Body:
This should work

<a href="tel:<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a>


问:
PHP - passing values to mysqli_connect
I have a legacy project, where I have a file with a class that in its construct method makes a connection with a database.

```<code>public $mysqli;

public function __construct(){
    $this->mysqli = mysqli_connect( "192.168.10.10", "homestead", "secret", "myDatabase" );
}
</code>```

For now, I would like to make this somewhat flexible and make a config file with an array of values that I would pass to mysqli_connect method.  Something like this:

Config file:

```<code>$mysqliConfig = [
  '192.168.10.10',
  'homestead',
  'secret',
  'myDatabase'
];
</code>```

And then just require that in the other file and use it in the class constructor of that file:

```<code>require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct(){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }
</code>```

But that is not working, how should I do that?

答:
You can use ... token to unpack the config into the argument list:</p>

```<code>$this->mysqli = mysqli_connect(...$mysqliConfig);
</code>```

Title: PHP - passing values to mysqli_connect

Body:
I have a legacy project, where I have a file with a class that in its construct method makes a connection with a database.

public $mysqli;

public function __construct(){
    $this->mysqli = mysqli_connect( "192.168.10.10", "homestead", "secret", "myDatabase" );
}

For now, I would like to make this somewhat flexible and make a config file with an array of values that I would pass to mysqli_connect method.  Something like this:

Config file:

$mysqliConfig = [
  '192.168.10.10',
  'homestead',
  'secret',
  'myDatabase'
];

And then just require that in the other file and use it in the class constructor of that file:

require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct(){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }

But that is not working, how should I do that?

Body:
You can use ... token to unpack the config into the argument list:

$this->mysqli = mysqli_connect(...$mysqliConfig);


问:
How to find the average colour of an image in Python with OpenCV?
I tried this code:

```<code>import cv2
image = cv2.imread("sample.jpg")
pixel = image[200, 550]
print pixel
</code>```

But I am getting error as:

'Nonetype' no attributes error getitem

This error is getting displayed after executing the third line of code.

答:
I was able to get the average color by using the following:

```<code>import cv2
import numpy
myimg = cv2.imread('image.jpg')
avg_color_per_row = numpy.average(myimg, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)
</code>```

Result:

```<code>[ 197.53434769  217.88439451  209.63799938]
</code>```

Great Resource which I referenced

Body:
I tried this code:

import cv2
image = cv2.imread("sample.jpg")
pixel = image[200, 550]
print pixel

But I am getting error as:

'Nonetype' no attributes error getitem

This error is getting displayed after executing the third line of code.

Body:
I was able to get the average color by using the following:

import cv2
import numpy
myimg = cv2.imread('image.jpg')
avg_color_per_row = numpy.average(myimg, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)

Result:

[ 197.53434769  217.88439451  209.63799938]

Great Resource which I referenced


问:
Javascript - create text file on website
So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.

e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt

Is there a way to do this with HTML/Javascript?

EDIT:
I am on Github

答:
You can achieve this in IE browser using the following code.

```<code><SCRIPT LANGUAGE="JavaScript">
</code>```

function WriteToFile(passForm) {

```<code>set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
</code>```

}

if you are looking for a goos reliable solution then better to use PHP and other server scripts.

Body:
You can achieve this in IE browser using the following code.

<SCRIPT LANGUAGE="JavaScript">

function WriteToFile(passForm) {

set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();

}

if you are looking for a goos reliable solution then better to use PHP and other server scripts.


问:
jquery hover div and show another div then keep that div open
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}</code>```

home

about

contact

```

https://jsfiddle.net/7okx2Lrx/7/

答:
You need make some changes in the code.
One of the variant would be:

```<code>$(function(){
  $('.navigation li').hover(
    function(){
      $('.navigation-dropdown').addClass('visible');
    }
  );
  $('.navigation-dropdown').hover(function(){}, function(){
    $(this).removeClass('visible');
  })
});
</code>```

https://jsfiddle.net/7okx2Lrx/11/

Body:
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});

.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}

home

about

contact

https://jsfiddle.net/7okx2Lrx/7/

Body:
You need make some changes in the code.
One of the variant would be:

$(function(){
  $('.navigation li').hover(
    function(){
      $('.navigation-dropdown').addClass('visible');
    }
  );
  $('.navigation-dropdown').hover(function(){}, function(){
    $(this).removeClass('visible');
  })
});

https://jsfiddle.net/7okx2Lrx/11/


问:
HttpEndpoint and Proxy Options in Vert.x
I am working on Vert.x Service Discovery registering HttpEndPoints. Is there a way to specify ProxyOptions when publishing HttpEndPoint to service discovery?

Thanks,
-Rajani

答:
You don't provide the options when creating the record but when retrieving the service reference.

```<code>ServiceReference reference = discovery.getReferenceWithConfiguration(record, new HttpClientOptions()
        .setProxyOptions(proxyOptions)
        .toJson());
</code>```

This explained in the retrieving a service reference section of the documentation:

When retrieving a service reference you can pass a JsonObject used to
  configure the service object.

Body:
You don't provide the options when creating the record but when retrieving the service reference.

ServiceReference reference = discovery.getReferenceWithConfiguration(record, new HttpClientOptions()
        .setProxyOptions(proxyOptions)
        .toJson());

This explained in the retrieving a service reference section of the documentation:

When retrieving a service reference you can pass a JsonObject used to
  configure the service object.


答:
You need to make the variables from the config file available to the class.

```<code>require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct($mysqliConfig){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }

}

$cal = new Calculator($mysqliConfig);
</code>```

As an aside, I would use an associative array for the config to make it more readable.

```<code>$mysqliConfig = [
  'host' => '192.168.10.10',
  'database' => 'homestead',
  'user' => 'secret',
  'password' => 'myDatabase'
];

// E.g. $mysqliConfig['host']
</code>```

Title: PHP - passing values to mysqli_connect

Body:
You need to make the variables from the config file available to the class.

require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct($mysqliConfig){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }

}

$cal = new Calculator($mysqliConfig);

As an aside, I would use an associative array for the config to make it more readable.

$mysqliConfig = [
  'host' => '192.168.10.10',
  'database' => 'homestead',
  'user' => 'secret',
  'password' => 'myDatabase'
];

// E.g. $mysqliConfig['host']


问:
Pass xml string as input to MySQL stored procedure
We are using the following code sample to send data from my application to an external DB via stored procedure (SQL Server).

Here I need to support MySQL also. So based on DB selection by end user, we need to send the data to the either MySQL or SQL Server

The c# code will be running on a different machine and the DB server will be different server.

C# Code

```<code>using (SqlConnection sqlConnection = new SqlConnection(<<MyConnectionString>>))
{
 using (SqlCommand sqlCommand = new SqlCommand(<<StoredProcedureName>>, sqlConnection))
 {
   sqlCommand.CommandType = CommandType.StoredProcedure;
   sqlCommand.Parameters.Add("tblStudent", SqlDbType.Xml).Value = students.ToList().ToXML();
   sqlConnection.Open();
   sqlCommand.ExecuteNonQuery();
 }
}
</code>```

Stored Procedure

```<code>CREATE PROCEDURE `usp_UpdateStudent` (@tblStudent  XML)
BEGIN
  SET NOCOUNT ON;
  INSERT INTO Student(StudentId,StudentName)
  SELECT    Student.value('(StudentId)[1]', 'nvarchar(100)') as StudentId,
    Student.value('(StudentName)[1]',  'nvarchar(100)') as StudentName
  FROM
  @tblStudent.nodes('/ArrayOfStudent/Student')AS TEMPTABLE(Student)
END
</code>```

I searched on the web on how to pass xml string as input parameter from c# to a stored procedure. But I don't get any concrete answer.

Please advice on how to create a stored procedure with XML as input parameter and also how to pass the XML string from c# to the same.

Note: The above code works as expected in SQL Server. When I tried to implement the same with MySQL, I found that MySQL do not support xml as input type parameter in Stored Procedure. It looks like I need to pass the xml as normal text and parse the text in stored procedure.

Please let me know if there is more efficient way to do this.

答:
Using Load_File() imports the xml data into a local variable, while ExtractValue() then queries the XML data using XPath.  For instance, in the code below, it retrieves a count of students from the xml_content variable:

```<code>declare xml_content text;
 declare v_row_count int unsigned;
 set xml_content = load_file(path);
 set v_row_count = extractValue(xml_content, concat('count(', node, ')'))
</code>```

path: 'C:\students1.xml', node: '/student_list/student'

Body:
We are using the following code sample to send data from my application to an external DB via stored procedure (SQL Server).

Here I need to support MySQL also. So based on DB selection by end user, we need to send the data to the either MySQL or SQL Server

The c# code will be running on a different machine and the DB server will be different server.

C# Code

using (SqlConnection sqlConnection = new SqlConnection(<<MyConnectionString>>))
{
 using (SqlCommand sqlCommand = new SqlCommand(<<StoredProcedureName>>, sqlConnection))
 {
   sqlCommand.CommandType = CommandType.StoredProcedure;
   sqlCommand.Parameters.Add("tblStudent", SqlDbType.Xml).Value = students.ToList().ToXML();
   sqlConnection.Open();
   sqlCommand.ExecuteNonQuery();
 }
}

Stored Procedure

CREATE PROCEDURE `usp_UpdateStudent` (@tblStudent  XML)
BEGIN
  SET NOCOUNT ON;
  INSERT INTO Student(StudentId,StudentName)
  SELECT    Student.value('(StudentId)[1]', 'nvarchar(100)') as StudentId,
    Student.value('(StudentName)[1]',  'nvarchar(100)') as StudentName
  FROM
  @tblStudent.nodes('/ArrayOfStudent/Student')AS TEMPTABLE(Student)
END

I searched on the web on how to pass xml string as input parameter from c# to a stored procedure. But I don't get any concrete answer.

Please advice on how to create a stored procedure with XML as input parameter and also how to pass the XML string from c# to the same.

Note: The above code works as expected in SQL Server. When I tried to implement the same with MySQL, I found that MySQL do not support xml as input type parameter in Stored Procedure. It looks like I need to pass the xml as normal text and parse the text in stored procedure.

Please let me know if there is more efficient way to do this.

Body:
Using Load_File() imports the xml data into a local variable, while ExtractValue() then queries the XML data using XPath.  For instance, in the code below, it retrieves a count of students from the xml_content variable:

declare xml_content text;
 declare v_row_count int unsigned;
 set xml_content = load_file(path);
 set v_row_count = extractValue(xml_content, concat('count(', node, ')'))

path: 'C:\students1.xml', node: '/student_list/student'


问:
How to calculate time duration in sql server 2014?

This is My First Condition. suppose CheckIn Time is Greater Than Check Out Time so How Can I calculate Time Duration

```<code>StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
---------------------------------------------------------------------------------------------
Kiran A Veri  |   2017-03-28   |5146  |1  | Night  | 34584   |18:00:00| 03:00:00  | 09:00:00
</code>```

This is my second condition. If check in time is less than checkout time so how to manage both condition in this Query?

```<code> StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
    ---------------------------------------------------------------------------------------------
    Ritesh B Patel  |   2017-03-28   |5146  |1  | General | 34584   |10:06:06| 19:35:46  | 09:29:00
</code>```

答:
For the first part:

Use a CASE WHEN CheckIn > CheckOut in conjunction with DATEDIFF.

For the second part:

Build a datetime or time field and convert it using Style=108 (hh.mm.ss)

```<code>CREATE TABLE TEST(ID int, CheckIn time, CheckOut time);
INSERT INTO TEST VALUES(1, '03:00:00', '10:00:00'),(2, '10:26:13', '03:12:15'),(3, '18:00:00', '03:00:00');

-- Below SQL-Server 2012
SELECT CASE WHEN CheckIn > CheckOut
            THEN CONVERT(VARCHAR(20), 86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 108)
            ELSE CONVERT(VARCHAR(20),DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 108)
            END Elapsed_Time
FROM   TEST

-- SQL-Server 2012 or above
SELECT CASE WHEN CheckIn > CheckOut
            THEN FORMAT(86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 'hh\:mm\:ss')
            ELSE FORMAT(DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 'hh\:mm\:ss')
            END Elapsed_Time
FROM   TEST

GO
</code>```
```
| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 16:46:02     |
| 09:00:00     |

| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 04:46:02     |
| 09:00:00     |
```

dbfiddle here

Body:
This is My First Condition. suppose CheckIn Time is Greater Than Check Out Time so How Can I calculate Time Duration

StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
---------------------------------------------------------------------------------------------
Kiran A Veri  |   2017-03-28   |5146  |1  | Night  | 34584   |18:00:00| 03:00:00  | 09:00:00

This is my second condition. If check in time is less than checkout time so how to manage both condition in this Query?

 StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
    ---------------------------------------------------------------------------------------------
    Ritesh B Patel  |   2017-03-28   |5146  |1  | General | 34584   |10:06:06| 19:35:46  | 09:29:00

Body:
For the first part:

Use a CASE WHEN CheckIn > CheckOut in conjunction with DATEDIFF.

For the second part:

Build a datetime or time field and convert it using Style=108 (hh.mm.ss)

CREATE TABLE TEST(ID int, CheckIn time, CheckOut time);
INSERT INTO TEST VALUES(1, '03:00:00', '10:00:00'),(2, '10:26:13', '03:12:15'),(3, '18:00:00', '03:00:00');

-- Below SQL-Server 2012
SELECT CASE WHEN CheckIn > CheckOut
            THEN CONVERT(VARCHAR(20), 86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 108)
            ELSE CONVERT(VARCHAR(20),DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 108)
            END Elapsed_Time
FROM   TEST

-- SQL-Server 2012 or above
SELECT CASE WHEN CheckIn > CheckOut
            THEN FORMAT(86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 'hh\:mm\:ss')
            ELSE FORMAT(DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 'hh\:mm\:ss')
            END Elapsed_Time
FROM   TEST

GO

| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 16:46:02     |
| 09:00:00     |

| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 04:46:02     |
| 09:00:00     |

dbfiddle here


问:
PHP key value pair array to strings
Let's say I have an array that looks like this:

```<code>$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);
</code>```

To get the values from the array keys I need to do this:

```<code>echo $args['format'];
echo $args['type'];
echo $args['name'];
echo $args['template'];
</code>```

While it works, it feels more messy than needed. Is there a proper way to somehow convert it to this?

```<code>echo $format;
echo $type;
echo $name;
echo $template;
</code>```

I'm aware of list but that only uses values and not keys.

答:
Are you looking for http://php.net/manual/en/function.extract.php ?

```<code>$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);
extract($args);

echo "$format, $type, $name, $template";
</code>```

Output:

file, page, Projects, default

Title: PHP key value pair array to strings

Body:
Let's say I have an array that looks like this:

$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);

To get the values from the array keys I need to do this:

echo $args['format'];
echo $args['type'];
echo $args['name'];
echo $args['template'];

While it works, it feels more messy than needed. Is there a proper way to somehow convert it to this?

echo $format;
echo $type;
echo $name;
echo $template;

I'm aware of list but that only uses values and not keys.

Body:
Are you looking for http://php.net/manual/en/function.extract.php ?

$args = array(
  'format' => 'file',
  'type' => 'page',
  'name' => 'Projects',
  'template' => 'default'
);
extract($args);

echo "$format, $type, $name, $template";

Output:

file, page, Projects, default


问:
How to put sql result into single cell
I'm coding sql in a simplified platform and can't access the platform code so I need some workaround every now and then (not always the best practise code).

I would need to store result of select clause to single cell for further use.

For example:
Table products has productID, productName, packages.

Table variants has productID, packageID.

Example data of variants:

```<code>productID - packageID
1001 - K1001
1001 - K1002
1001 - K1003
</code>```

I would need to save the result to cell packages in form of (K1001, K1002, K1003) or similar.

Is this possible to do just using sql?

I'm using ms sql server xpress, platform/RDBMS is custom coded and not widely known.

答:
Starting on SQL Server vNext you can do:

```<code>SELECT
    STRING_AGG(productId + ' - ' + packageId, ',')
FROM yourTable
</code>```

In previous versions you are going to either hack your way through with cursors/xml or use a CLR aggregation function.

Title: How to put sql result into single cell

Body:
I'm coding sql in a simplified platform and can't access the platform code so I need some workaround every now and then (not always the best practise code).

I would need to store result of select clause to single cell for further use.

For example:
Table products has productID, productName, packages.

Table variants has productID, packageID.

Example data of variants:

productID - packageID
1001 - K1001
1001 - K1002
1001 - K1003

I would need to save the result to cell packages in form of (K1001, K1002, K1003) or similar.

Is this possible to do just using sql?

I'm using ms sql server xpress, platform/RDBMS is custom coded and not widely known.

Body:
Starting on SQL Server vNext you can do:

SELECT
    STRING_AGG(productId + ' - ' + packageId, ',')
FROM yourTable

In previous versions you are going to either hack your way through with cursors/xml or use a CLR aggregation function.


问:
ORA-00979: not a GROUP BY expression when I execute my sql
When I execute my SQL, I get the below error:

My exception is:

```<code>[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression
</code>```

My SQL is below:

```<code>select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)
</code>```

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

答:
Use select distinct instead:</p>

```<code>select distinct bd.name aaa ,
       substr(m.code,0,4) -- see below code comment, either include this or remove the order by
from bd_material_v m
inner join bd_marbasclass bd
      on bd.code=substr(m.code,0,4)
where m.creator='1001A210000000000IIQ'
order by substr(m.code,0,4) -- As this is oracle, you can only order by selected columns/expressions :D
</code>```

Body:
When I execute my SQL, I get the below error:

My exception is:

[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression

My SQL is below:

select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

Body:
Use select distinct instead:

select distinct bd.name aaa ,
       substr(m.code,0,4) -- see below code comment, either include this or remove the order by
from bd_material_v m
inner join bd_marbasclass bd
      on bd.code=substr(m.code,0,4)
where m.creator='1001A210000000000IIQ'
order by substr(m.code,0,4) -- As this is oracle, you can only order by selected columns/expressions :D


问:
Is it possible to require at least one field from a set of defined fields?
Given a definition like this:

```<code>const querySchema = joi.object({
  one: joi.string().min(1).max(255),
  two: joi.string().min(1).max(255),
  three: joi.string().min(1).max(255),
});
</code>```

Is there a way to require at least one of those fields? I don't care which one.

Note: the solution provided for this SO question doesn't serve me as I have 7 fields and they may grow, so doing all the possible combinations is a no-go.

Couldn't find any methods in Joi API Reference that may be useful for this use case.

Any help is greatly appreciated.

答:
If you really don't care which one is required then you could just ensure there is at least one key in the object by using object().min(1).

```<code>const querySchema = joi.object({
    one: joi.string().min(1).max(255),
    two: joi.string().min(1).max(255),
    three: joi.string().min(1).max(255),
}).min(1);
</code>```

At least one key (one, two, three) must be required. Keys with names different to those three will be rejected.

Body:
Given a definition like this:

const querySchema = joi.object({
  one: joi.string().min(1).max(255),
  two: joi.string().min(1).max(255),
  three: joi.string().min(1).max(255),
});

Is there a way to require at least one of those fields? I don't care which one.

Note: the solution provided for this SO question doesn't serve me as I have 7 fields and they may grow, so doing all the possible combinations is a no-go.

Couldn't find any methods in Joi API Reference that may be useful for this use case.

Any help is greatly appreciated.

Body:
If you really don't care which one is required then you could just ensure there is at least one key in the object by using object().min(1).

const querySchema = joi.object({
    one: joi.string().min(1).max(255),
    two: joi.string().min(1).max(255),
    three: joi.string().min(1).max(255),
}).min(1);

At least one key (one, two, three) must be required. Keys with names different to those three will be rejected.


问:
Tomcat7 serving blank pages
I am using Java with Tomcat7 to develop a web application.
I'm a trying to test my services in local using Eclipse built-in environment.
My servlets are working fine but I get blank pages when loading HTML file.

My home page is configured like so in my web.xml:

```<code><welcome-file-list>
    <welcome-file>/index.html</welcome-file>
</welcome-file-list>
</code>```

My ports 8005, 8080 and 8009 are not in used by another application.
I tried switching Tomcat's location in Eclipse properties but nothing changed.

Why is Tomcat serving blank HTML pages?

答:
Problem solved: I simply moved all my HTML files under the WebContent directory.

WebContent appears to be the root directory of Java EE web applications under Eclipse.

Title: Tomcat7 serving blank pages

Body:
I am using Java with Tomcat7 to develop a web application.
I'm a trying to test my services in local using Eclipse built-in environment.
My servlets are working fine but I get blank pages when loading HTML file.

My home page is configured like so in my web.xml:

<welcome-file-list>
    <welcome-file>/index.html</welcome-file>
</welcome-file-list>

My ports 8005, 8080 and 8009 are not in used by another application.
I tried switching Tomcat's location in Eclipse properties but nothing changed.

Why is Tomcat serving blank HTML pages?


问:
jquery onchange event for radio button now instantaneous
I am trying to make an ID active only when a certain type of radio button is selected.  Below is my jQuery code:

```<code>$(document).ready(function() {
   $('#Type').attr('disabled', 'disabled');
   $('input[@name=action]').change(function() {
     if ($("input[@name=action]:checked").val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
    });
});
</code>```

This works as intended but with one flaw.  When I click on the radio button SomeKind it does not make Type active instantaneously, instead I have to click again (anywhere on the page) for Type to be active.

I am on IE7

答:
if action is a name of your checkbox, then use click event instead of change,</p>

```<code>$('input[@name=action]').click(function() {
     if (this.checked && $(this).val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
});
</code>```

Body:
I am trying to make an ID active only when a certain type of radio button is selected.  Below is my jQuery code:

$(document).ready(function() {
   $('#Type').attr('disabled', 'disabled');
   $('input[@name=action]').change(function() {
     if ($("input[@name=action]:checked").val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
    });
});

This works as intended but with one flaw.  When I click on the radio button SomeKind it does not make Type active instantaneously, instead I have to click again (anywhere on the page) for Type to be active.

I am on IE7

Body:
if action is a name of your checkbox, then use click event instead of change,

$('input[@name=action]').click(function() {
     if (this.checked && $(this).val() == 'SomeKind')
        $('#Type').removeAttr('disabled');
     else
        $('#Type').attr('disabled', 'disabled');
});


问:
Is there anyway to merge cobertura coverage xml reports together?
I have c++/c application with a lots of unit tests. I would like to get overall coverage and also individual coverage of each test with condition that each test can be run only once.
Format of coverage must be xml (cobertura xml) for jenkins cobertura plugin to process.

So far I generate gcno files upon compilation and gcda files when source is used. Then call gcovr to get xml file.

I would like to create coverage of each unit test (thus creating coverage xml for every unit test) and then merge these xml files into one xml file.

Thanks!

答:
I was looking at solution as well, but in my case there was about 1000 of Cobertura XML files and all above scripts were really slow in processing such amount.

In the end I've come up with merge-cobertura.py a Python script which does the merge. However it's quite limited in what it supports as all I needed was to merge reports from OpenCppCoverage to be used at Codecov. So it just merges line hits ignoring any branch information (there is none coming from OpenCppCoverage) and assuming all coverage reports are for same path. It also merges all packages into one.

Maybe somebody will find this useful as well, there are some more details in my blog.


问:
iOS - UITableView Delete All Rows Within A Section
I have a UITableView with expandable sections. When a user goes to another view, I need all the expanded sections to collapse, which I'll need to put in the viewWillDisappear method.

I've found solutions only on how to delete all rows from a table view at once, but is there a way to delete all the rows from a specific section?

EDIT:

I have figured out a solution, but I'm not sure if it's optimal or can lead to inefficiencies in the future. Whenever a cell is expanded, it gets added to an NSMutableIndexSet. So in my viewWillDisappear method, I iterate over the expanded sections like so:

```<code>-(void)viewWillDisappear:(BOOL)animated
{
    if (expandedSections.count != 0) {
        NSLog(@"COLLAPSING CALLED");
        [self.tableView beginUpdates];

        NSUInteger section = [expandedSections firstIndex];

        do
        {
            NSInteger rows;
            NSMutableArray *tmpArray = [NSMutableArray array];
            rows = [self tableView:self.tableView numberOfRowsInSection:section];
            [expandedSections removeIndex:section];
            for (int i=1; i<rows; i++) {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }
            [self.tableView deleteRowsAtIndexPaths:tmpArray withRowAnimation:UITableViewRowAnimationTop];
            NSIndexPath *expandableCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:expandableCellIndexPath];
            cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[self.colorHolder objectAtIndex:section] type:DTCustomColoredAccessoryTypeRight];

            section = [expandedSections indexGreaterThanIndex:section];
        } while (section != NSNotFound);

        [self.tableView endUpdates];
    }
}
</code>```

Please let me know if this is a good solution or, if I'm suspecting correctly, if this will lead to slower transitions between views in the future when there are more rows in each expanded section. Any help or advice would be appreciated. Thanks.

答:
I did not read this in detail but surely the for loop should start at zero.

```<code>    for (int i=0; i<rows; i++) {
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
        [tmpArray addObject:tmpIndexPath];
    }
</code>```

otherwise you will only delete all but the first cells in the section.

Body:
I have a UITableView with expandable sections. When a user goes to another view, I need all the expanded sections to collapse, which I'll need to put in the viewWillDisappear method.

I've found solutions only on how to delete all rows from a table view at once, but is there a way to delete all the rows from a specific section?

EDIT:

I have figured out a solution, but I'm not sure if it's optimal or can lead to inefficiencies in the future. Whenever a cell is expanded, it gets added to an NSMutableIndexSet. So in my viewWillDisappear method, I iterate over the expanded sections like so:

-(void)viewWillDisappear:(BOOL)animated
{
    if (expandedSections.count != 0) {
        NSLog(@"COLLAPSING CALLED");
        [self.tableView beginUpdates];

        NSUInteger section = [expandedSections firstIndex];

        do
        {
            NSInteger rows;
            NSMutableArray *tmpArray = [NSMutableArray array];
            rows = [self tableView:self.tableView numberOfRowsInSection:section];
            [expandedSections removeIndex:section];
            for (int i=1; i<rows; i++) {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }
            [self.tableView deleteRowsAtIndexPaths:tmpArray withRowAnimation:UITableViewRowAnimationTop];
            NSIndexPath *expandableCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:expandableCellIndexPath];
            cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[self.colorHolder objectAtIndex:section] type:DTCustomColoredAccessoryTypeRight];

            section = [expandedSections indexGreaterThanIndex:section];
        } while (section != NSNotFound);

        [self.tableView endUpdates];
    }
}

Please let me know if this is a good solution or, if I'm suspecting correctly, if this will lead to slower transitions between views in the future when there are more rows in each expanded section. Any help or advice would be appreciated. Thanks.

Body:
I did not read this in detail but surely the for loop should start at zero.

    for (int i=0; i<rows; i++) {
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
        [tmpArray addObject:tmpIndexPath];
    }

otherwise you will only delete all but the first cells in the section.


问:
C++: Singleton Class Design (Error: unresolved external symbol)
I'm implementing a singleton class design for a C++ project on Visual Studio. It was based on this GitHub code sample. Logic-wise, my code seems correct, but there's an error from my compiler. Does anyone know what's wrong?

I have several singleton classes. Here's a code sample for one of them.

AccountBG.h

```<code>#ifndef ACCOUNTBG_H
#define ACCOUNTBG_H

#include "Lecturer.h"
#include "Student.h"
#include "Type.h"

class AccountBG
{
public:
   static AccountBG* getInstance();
   // GET Methods
   Lecturer* getLecturer();
   Student* getStudent();
   // SET Methods
   void setLecturer(int, string);
   void setStudent(int, string);
private:
   // Singleton class instance
   static AccountBG* instance;
   AccountBG(); // Private constructor to prevent instancing.
   Lecturer *lecturer;
   Student *student;
};

#endif // !ACCOUNTBG_H
</code>```

AccountBG.cpp

```<code>#include "AccountBG.h"
// Null, because instance will be initialized on demand.
AccountBG* AccountBG::instance = 0;

AccountBG* AccountBG::getInstance() {
    if (instance == 0) {
        instance = new AccountBG();
    }
    return instance;
}

// GET Methods
Lecturer* AccountBG::getLecturer() {
    return this->lecturer;
}

Student* AccountBG::getStudent() {
    return this->student;
}

// SET Methods
void AccountBG::setLecturer(int id, string username) {
    this->lecturer = new Lecturer();
    this->lecturer->setID(id);
    this->lecturer->setUsername(username);
    this->lecturer->setType("Lecturer");
}

void AccountBG::setStudent(int id, string username) {
    this->student = new Student();
    this->student->setID(id);
    this->student->setUsername(username);
    this->student->setType("Student");
}
</code>```

Screenshot of Compiler Errors

Errors as seen on VS2015

答:
unresolved external symbol usually caused by calling a declared, but un-implemented function.

In your case, you don't implement constructor for AccountBG, only declared.

Possible same problem for other functions:

```<code>MarkingData::instance()
Quiz::Quiz()
QuizTracker::QuizTracker()
</code>```

Add implementation to these functions may solve your problem.

Body:
I'm implementing a singleton class design for a C++ project on Visual Studio. It was based on this GitHub code sample. Logic-wise, my code seems correct, but there's an error from my compiler. Does anyone know what's wrong?

I have several singleton classes. Here's a code sample for one of them.

AccountBG.h

#ifndef ACCOUNTBG_H
#define ACCOUNTBG_H

#include "Lecturer.h"
#include "Student.h"
#include "Type.h"

class AccountBG
{
public:
   static AccountBG* getInstance();
   // GET Methods
   Lecturer* getLecturer();
   Student* getStudent();
   // SET Methods
   void setLecturer(int, string);
   void setStudent(int, string);
private:
   // Singleton class instance
   static AccountBG* instance;
   AccountBG(); // Private constructor to prevent instancing.
   Lecturer *lecturer;
   Student *student;
};

#endif // !ACCOUNTBG_H

AccountBG.cpp

#include "AccountBG.h"
// Null, because instance will be initialized on demand.
AccountBG* AccountBG::instance = 0;

AccountBG* AccountBG::getInstance() {
    if (instance == 0) {
        instance = new AccountBG();
    }
    return instance;
}

// GET Methods
Lecturer* AccountBG::getLecturer() {
    return this->lecturer;
}

Student* AccountBG::getStudent() {
    return this->student;
}

// SET Methods
void AccountBG::setLecturer(int id, string username) {
    this->lecturer = new Lecturer();
    this->lecturer->setID(id);
    this->lecturer->setUsername(username);
    this->lecturer->setType("Lecturer");
}

void AccountBG::setStudent(int id, string username) {
    this->student = new Student();
    this->student->setID(id);
    this->student->setUsername(username);
    this->student->setType("Student");
}

Screenshot of Compiler Errors

Errors as seen on VS2015

Body:
unresolved external symbol usually caused by calling a declared, but un-implemented function.

In your case, you don't implement constructor for AccountBG, only declared.

Possible same problem for other functions:

MarkingData::instance()
Quiz::Quiz()
QuizTracker::QuizTracker()

Add implementation to these functions may solve your problem.


问:
iOS: isMultipleTouchEnabled does not work on table
I have a controller that has a UITableView property:

```<code>class OrdersViewController: UIViewController {
  @IBOutlet weak var ordersTable: UITableView!

  override func viewDidLoad() {
    self.ordersTable.isMultipleTouchEnabled = false;
  }
</code>```

However, it's not working. When I try swiping two cells at the same time (using this library https://github.com/alikaragoz/MCSwipeTableViewCell) it still swipes both of them:

答:
According to Apple's documentation about isMultipleTouchEnabled:

When set to true, the receiver receives all touches associated with a multi-touch sequence. When set to false, the receiver receives only the first touch event in a multi-touch sequence. The default value of this property is false.
  Other views in the same window can still receive touch events when this property is false. If you want this view to handle multi-touch events exclusively, set the values of both this property and the isExclusiveTouch property to true.

So, even though the table itself won't handle multi-touch, it's child views handle single touches independently.
To achieve what you want you probably have to set isExclusiveTouch on all cells.

Body:
I have a controller that has a UITableView property:

class OrdersViewController: UIViewController {
  @IBOutlet weak var ordersTable: UITableView!

  override func viewDidLoad() {
    self.ordersTable.isMultipleTouchEnabled = false;
  }

However, it's not working. When I try swiping two cells at the same time (using this library https://github.com/alikaragoz/MCSwipeTableViewCell) it still swipes both of them:


问:
Android Gps Tracker not getting timely updates
I have an open source gps tracking application that has been around for many years. Recently, I have been getting complaints that in android nougat, instead of getting updates once a minute, people are getting updates from the phone once every five minutes when the phone is unplugged.

There is something going on with the power saver mode even though we tried turning it off.

Is there a way to force a phone to get gps updates at a specified time when unplugged?

Here is the code if anyone wants to see it but I don't think it's a problem with the code. It has been very stable for years.

https://github.com/nickfox/GpsTracker/blob/master/phoneClients/android/app/src/main/java/com/websmithing/gpstracker/LocationService.java

thanks.

答:
One change in Android 7/Nougat was that the Doze is now "more aggressive". In Android 6/Marshmallow the doze mode kicked in when the screen was off, the device was running on battery and it was stationary.

(This is documented in Optimizing for Doze and App Standby)

Now in Android 7 the conditions are just screen off and running on battery.

(This is documented in Android 7.0 Behavior Changes)

Apps can be white-listed to be exempt of the restrictions if they break the core functionalility of it. In your case they do as the GPS tracker needs to record coordinates in real time.

There's a list of Acceptable Use Cases for Whitelisting

This includes:

Task automation app | App's core function is scheduling automated
  actions, such as for instant messaging, voice calling, new photo
  management, or location actions.

Users can white list an app manually on their own in the device settings or whitelisting can be requested by the app and approved or rejected by the user.

This is covered in Support for Other Use Cases

Quoting:

An app can fire the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent
  to take the user directly to the Battery Optimization, where they can
  add the app.

An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can
  trigger a system dialog to let the user add the app to the whitelist
  directly, without going to settings. The app fires a
  ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the
  dialog.

The user can manually remove apps from the whitelist as needed.

The last point is important of course, but luckily the whitelisting status can be checked programmatically:

An app can check whether it is currently on the exemption whitelist by
  calling isIgnoringBatteryOptimizations().

So, dealing with the Doze mode is one thing to study at least.

Another issue is keeping the Service running in general. But the Service getting killed by the system might result in more random time intervals. There are of course the classic things like using START_STICKY or running as a foreground service.


问:
Apache2 return php source code
I installed Apache2 in my Xubunt, but I have a problem, When I see a Html file it works but when I see a Php file, Apache shows my sources code and I don't see my site and my script don't works.

See my desktop:

答: try on sudo apt-get install php-pear php5-suhosin

Title: Apache2 return php source code


问:
Detect a Missing file based on its Date
I need to manually monitor a random windows-based backup program for failures and the only way to do this is via checking for the daily backup file it makes.

A batch file would be simplest for me to implement.  It would need to scan a directory for a certain file type and then do X if a file doesn't exist that was created/modified yesterday.

```<code>C:\backups\random-named-file.tib 27/03/2017
C:\backups\random-named-file.tib 28/03/2017
C:\backups\random-named-file.tib 29/03/2017
</code>```

So if a random-named-file.tib wasnt created or modified yesterday, it means the backup failed and I would write output to the console saying "Backup Failed"

Does anyone please have any ideas ?

EDIT :
To clarify, the backup files are coming from a custom application that has no way to check for missed backups.  The batch file solution I'm looking for will be integrated into our RMM platform, which will take the results of the batch file and raise a support desk ticket for our Service desk to action.

The backup application will apply its own retention policies and delete any backups older then 4 days.
I'm just trying to detect if a backup was missed the previous day.  The filenames are variable, the only constant is the file extension ( *.tib)

This backup app doesn't write eventlogs, nor does it create its own log files I can parse for Failure messages.

答:
1) I would suggest you, go through this article

four-ways-to-manage-windows-server-2008-backup-on-multiple-servers

2) There is a windows scheduler which can act according to your situation

Window scheduler Wiki

3) You can write scripts which alert you whenever it  fails

4) I have found a Solution for your similar kind of problem

make-windows-task-scheduler-alert-on-fail

TL:Dr --> see step 4

Title: Detect a Missing file based on its Date

Body:
I need to manually monitor a random windows-based backup program for failures and the only way to do this is via checking for the daily backup file it makes.

A batch file would be simplest for me to implement.  It would need to scan a directory for a certain file type and then do X if a file doesn't exist that was created/modified yesterday.

C:\backups\random-named-file.tib 27/03/2017
C:\backups\random-named-file.tib 28/03/2017
C:\backups\random-named-file.tib 29/03/2017

So if a random-named-file.tib wasnt created or modified yesterday, it means the backup failed and I would write output to the console saying "Backup Failed"

Does anyone please have any ideas ?

EDIT :
To clarify, the backup files are coming from a custom application that has no way to check for missed backups.  The batch file solution I'm looking for will be integrated into our RMM platform, which will take the results of the batch file and raise a support desk ticket for our Service desk to action.

The backup application will apply its own retention policies and delete any backups older then 4 days.
I'm just trying to detect if a backup was missed the previous day.  The filenames are variable, the only constant is the file extension ( *.tib)

This backup app doesn't write eventlogs, nor does it create its own log files I can parse for Failure messages.


问:
Move UI element with keyboard nativescript (IOS)
On my nativescript app - I have a button at the bottom of a screen. On the screen there is a Text area. When the user taps in the Text Area, a virtual keyboard appears. At this point, I want the button at the bottom to move up and appear just on top of the virtual keyboard. Any suggestions on how I can achieve this in both android and iOS?

Code

```<code><GridLayout>
<ActionBar title="" backgroundColor="#f82462" top="0" left="0">
    <NavigationButton (tap)="goBack()"></NavigationButton>
</ActionBar>
<GridLayout rows="*, auto">
    <GridLayout row ='0' rows="auto *" columns="">
        <GridLayout row="0" rows="" columns="">
            <Button text="Top Button" (tap)="goNext()"></Button>
        </GridLayout>
        <GridLayout row="1" backgroundColor="#f82462">
            <TextView [(ngModel)]="xyz" class="input" hint="Write your question as a complete sentence.Click on camera to add images if required." returnkeyType="done" id="questionText"></TextView>
        </GridLayout>
</GridLayout>
<StackLayout row='1'>
    <Button text="Next" (tap)="goNext()"></Button>
</StackLayout>
</GridLayout>
</code>```

答: I am not able to test this right now, but have you tried to wrap everything inside the main GridLayout in <ScrollView> ... </ScrollView>

Body:
On my nativescript app - I have a button at the bottom of a screen. On the screen there is a Text area. When the user taps in the Text Area, a virtual keyboard appears. At this point, I want the button at the bottom to move up and appear just on top of the virtual keyboard. Any suggestions on how I can achieve this in both android and iOS?

Code

<GridLayout>
<ActionBar title="" backgroundColor="#f82462" top="0" left="0">
    <NavigationButton (tap)="goBack()"></NavigationButton>
</ActionBar>
<GridLayout rows="*, auto">
    <GridLayout row ='0' rows="auto *" columns="">
        <GridLayout row="0" rows="" columns="">
            <Button text="Top Button" (tap)="goNext()"></Button>
        </GridLayout>
        <GridLayout row="1" backgroundColor="#f82462">
            <TextView [(ngModel)]="xyz" class="input" hint="Write your question as a complete sentence.Click on camera to add images if required." returnkeyType="done" id="questionText"></TextView>
        </GridLayout>
</GridLayout>
<StackLayout row='1'>
    <Button text="Next" (tap)="goNext()"></Button>
</StackLayout>
</GridLayout>


问:
Avoiding Google Drive Java REST API prompting for user account everytime on devices with multiple accounts
I have a working solution where I search for files in Google Drive and ask for Google Drive to open them using the getWebViewLink, this generates a link like this:

```<code>https://drive.google.com/file/d/0B6cgfp1Py-7SAF&SAFgASFGZGlQWEU/view?usp=drivesdk
</code>```

Then I parse the link and generate an intent like this:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);
</code>```

This works great on devices configured with one gmail account, but if the device happens to have 2 or more gmail accounts configured then Google Drive keeps always asking which account the user wants to use to open the file.

Is there anyway to suggest in the link which account to use to Google Drive?

P.S: I tried adding the following to the link to no avail

```<code>&approval_prompt=auto
</code>```

or

```<code>&user_id=myemail@gmail.com
</code>```

答:
You may refer with this related thread. It stated that the redirect loop happens to users that have both a Gmail account and a Google Apps account. There are only one set of active Docs cookies at any given time. The workarounds are to either log out of the account that you are not currently trying to use for Docs access or use different browsers for each account.

Here's another reference which might help: How can I enforce GoogleApiClient to prompt account chooser UI each time I call connect?

...you must manage the account selection yourself as you can see here (for REST) or here (for GDAA)

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I have a working solution where I search for files in Google Drive and ask for Google Drive to open them using the getWebViewLink, this generates a link like this:

https://drive.google.com/file/d/0B6cgfp1Py-7SAF&SAFgASFGZGlQWEU/view?usp=drivesdk

Then I parse the link and generate an intent like this:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);

This works great on devices configured with one gmail account, but if the device happens to have 2 or more gmail accounts configured then Google Drive keeps always asking which account the user wants to use to open the file.

Is there anyway to suggest in the link which account to use to Google Drive?

P.S: I tried adding the following to the link to no avail

&approval_prompt=auto

or

&user_id=myemail@gmail.com


问:
What is the use of "bash -c" command?
What is the use of bash -c command, while surfing on the internet I came across the command

```<code>ssh -t "${SSH_USER}@${SERVER_IP}" bash -c
</code>```

First part here is doing ssh obviously to a server but what exactly bash -c is responsible for?

答:
bash -c option with ssh is one such method to execute multi line commands on the ssh server with variable expansion.

Say you have

```<code>VAR1="Variable 1"
ssh app@HOSTNAME '
ls
pwd
if true; then
    echo "True"
    echo $VAR1      # <-- it won't work
else
    echo "False"
fi
'
</code>```

But with bash -c

```<code>VAR1="Variable 1"
 ssh -t "${SSH_USER}@${SERVER_IP}" bash -c "'
ls
pwd
if true; then
    echo $VAR1     <-- This works
else
    echo "False"
fi
'"
</code>```

Title: What is the use of "bash -c" command?

Body:
What is the use of bash -c command, while surfing on the internet I came across the command

ssh -t "${SSH_USER}@${SERVER_IP}" bash -c

First part here is doing ssh obviously to a server but what exactly bash -c is responsible for?

Body:
bash -c option with ssh is one such method to execute multi line commands on the ssh server with variable expansion.

Say you have

VAR1="Variable 1"
ssh app@HOSTNAME '
ls
pwd
if true; then
    echo "True"
    echo $VAR1      # <-- it won't work
else
    echo "False"
fi
'

But with bash -c

VAR1="Variable 1"
 ssh -t "${SSH_USER}@${SERVER_IP}" bash -c "'
ls
pwd
if true; then
    echo $VAR1     <-- This works
else
    echo "False"
fi
'"


问:
ui-router child view of an angularjs component not showing
I have an angularjs component(almost empty markup) acting as a shell/parent to its child views(markups with different columns/formats).  I am able to see the component but no child views are loaded.

ui-router config code:

```<code>.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

$urlRouterProvider.otherwise('/');

$stateProvider
  .state('parent', {
    url: '',
    views: {
      'parentComponent': {
        component: 'parentComponent'
      }
    }
  })
  .state('parent.child', {
    url: '/child',
    templateUrl: 'child.html'
  });
</code>```

index.html:

```<code><body ng-app="app" >
 <div ng-controller='RoutingCtrl'>
   <parent-component></parent-component>
 </div>
</body>
</code>```

The parent, which is a component:

```<code><!DOCTYPE html>
<div>
    <br />
    <br />
    <div>I am the parent, a angularjs component.</div>
    <div>There sould be the nested/child view right below:</div>
    <div ui-view></div>
</div>
</code>```

child:

```<code><div>Hi! I am the child!</div>
</code>```

My controller tells ui-router to go to child view:

```<code>$state.go('parent.child');
</code>```

I don't want to declare parent as abstract because, in my real app, I have views parallel to the parent component view(together, they form a multiple named view) here and these other high level views(except the parent component) must be visible regardless of the child views.

I am using angularjs 1.5.8 and ui-router version 0.4.2

Plunker:
http://plnkr.co/edit/tBhVTjttMagaJzHQNvro?p=preview

答:
You haven't provided any details what you are trying to accomplish, so based on what it looks right now, you have two options: either go with the ui-view template throughout your app and use the parent-child relationship of ui-router or go with hybrid approach of loading your component, and inside it, a state you want to show.

Example with parent-child relationship - This example uses ui-view throughout the app. parent-component is loaded with it's own state and it's not abstract. This approach is good if you want to load different templates for different states in the same place.

Example with hybrid approach. This example follows your current app structure with parent-component loaded in index.html and a state loaded in your parent-component. You can see that you really don't need a parent state here as you have put your parent-component directly in index.html file. State child is loaded in inside your parent-component and it doesn't need a parent state.

Body:
I have an angularjs component(almost empty markup) acting as a shell/parent to its child views(markups with different columns/formats).  I am able to see the component but no child views are loaded.

ui-router config code:

.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

$urlRouterProvider.otherwise('/');

$stateProvider
  .state('parent', {
    url: '',
    views: {
      'parentComponent': {
        component: 'parentComponent'
      }
    }
  })
  .state('parent.child', {
    url: '/child',
    templateUrl: 'child.html'
  });

index.html:

   <parent-component></parent-component>

The parent, which is a component:

<!DOCTYPE html>

I am the parent, a angularjs component.

There sould be the nested/child view right below:

child:

Hi! I am the child!

My controller tells ui-router to go to child view:

$state.go('parent.child');

I don't want to declare parent as abstract because, in my real app, I have views parallel to the parent component view(together, they form a multiple named view) here and these other high level views(except the parent component) must be visible regardless of the child views.

I am using angularjs 1.5.8 and ui-router version 0.4.2

Plunker:
http://plnkr.co/edit/tBhVTjttMagaJzHQNvro?p=preview


问:
Use multiply shaders in Android open GL
I have two different fragment shaders:

First static

Second depend on value that a change every onDrawFrame event

How can I use both of this shaders? I need change image with first and than result with second?

I tried place all code in one shader, but it works slowly

答:
If you can join the 2 shaders into a single one then that is usually the fastest way. The situations where it is slower happen when you have many fragment redraws. For instance a normal 3D scene may have for instance in average 5 redraws per pixel which means that the fragment shader will be called 5 more times then optimal. In this case it makes sense to keep this shader as basic as possible and use a post processing.

In your case it might help if you added some shader code and explain what exactly you are doing. But looking at your question it seems what you are looking for is FBO (frame buffer object) with attached texture.

To achieve this you need to create a new frame buffer (glGenFramebuffers) and bind it. Then you need to create a new empty texture glTexImage2D with NULL data should do. The attach the 2 together with color using glFramebufferTexture2D. After you succeed in doing this the rest of the code should be more or less the same and the result is you are now drawing directly to a texture instead of your main buffer.

Some things to watch out: Unless enabled your texture size must be POT. Remember to set an appropriate viewport.

So now you have 2 frame buffers, the FBO and your main. You received the ID of your FBO while I believe that the main buffer should have the ID of 0. So now you need to bind your FBO and draw to it with the first shader. Once that is done you need to bind your main frame buffer and redraw the texture from the FBO to the main buffer using the second shader.

Redrawing to the main buffer simply means you need to draw a 2d textured rectangle which fills the whole screen. Using the texture from the FBO that is.

Title: Use multiply shaders in Android open GL


问:
Return Custom HTTP Status Code from WebAPI?
You can return the http status code along with the response object using:

```<code> return Ok(responseObject);
 return BadRequest(responseObject);
 return NotFound(responseObject);
</code>```

But what about you want to return your own custom http status code? 402, 429, 500, 501 etc

答:
```<code>Response.StatusCode = 500; // HttpStatusCode.
return responseObject;
</code>```

OR

```<code>Response.StatusCode = StatusCodes.Status500InternalServerError; // HttpStatusCode.
return responseObject;
</code>```

Body:
You can return the http status code along with the response object using:

 return Ok(responseObject);
 return BadRequest(responseObject);
 return NotFound(responseObject);

But what about you want to return your own custom http status code? 402, 429, 500, 501 etc

Body:
Response.StatusCode = 500; // HttpStatusCode.
return responseObject;

OR

Response.StatusCode = StatusCodes.Status500InternalServerError; // HttpStatusCode.
return responseObject;


问:
Tutorials about javaagents
I'd like to learn something about javaagents, but researching is not easy. Most of result refers to JADE. I know java agent can mean two things:

An agent programmed in Java being an incarnation of the agent
concept of distributed systems.

A low-level software component to augment the working of a JVM, such
as profilers, code-coverage tools, etc

I've found similar question here, but unfortunately it also refers to version 1.

Do you know any articles, tutorials for beginners, sample project about javaagent in version 2?
I've found one here, but I'm looking for more.

答:
Few useful resources for the javaagent as described in point #2.

How-to guide to writing a javaagent

Taming Javaagents - presentation at BCN JUG
2015

API documentation for
java.lang.instrument

Title: Tutorials about javaagents


问:
Paper Input elements doesn't work in Polymer 2
I'm working with polymer 2, I download polymer paper input elements, then i add the link tag:

```<code><link rel="import" href="../bower_components/paper-input/paper-input.html">
</code>```

then:

```<code><paper-input  label="Floating label"></paper-input>
</code>```

And the browser not showing the input text element

I'm working with the last version of chrome 56.0

Thanks for the help

答:
Look at Polymer 2.0 installation Documentation.

Have you installed paper-input with bower correctly?

```<code>bower install --save PolymerElements/paper-input#2.0-preview
</code>```

Body:
I'm working with polymer 2, I download polymer paper input elements, then i add the link tag:

<link rel="import" href="../bower_components/paper-input/paper-input.html">

then:

<paper-input  label="Floating label"></paper-input>

And the browser not showing the input text element

I'm working with the last version of chrome 56.0

Thanks for the help

Body:
Look at Polymer 2.0 installation Documentation.

Have you installed paper-input with bower correctly?

bower install --save PolymerElements/paper-input#2.0-preview


问:
PHP - passing values to mysqli_connect
I have a legacy project, where I have a file with a class that in its construct method makes a connection with a database.

```<code>public $mysqli;

public function __construct(){
    $this->mysqli = mysqli_connect( "192.168.10.10", "homestead", "secret", "myDatabase" );
}
</code>```

For now, I would like to make this somewhat flexible and make a config file with an array of values that I would pass to mysqli_connect method.  Something like this:

Config file:

```<code>$mysqliConfig = [
  '192.168.10.10',
  'homestead',
  'secret',
  'myDatabase'
];
</code>```

And then just require that in the other file and use it in the class constructor of that file:

```<code>require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct(){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }
</code>```

But that is not working, how should I do that?

答:
What i do is to have a .ini file Advantage is that it returns as a key value association.

save your config details in the .ini file(path/to/config.ini)
In config.ini file,

```<code>database_name = mydatabase_name
password = my_password
host = host
system_root = system_root
other_details = other_details
</code>```

Then on your calculator class, do

```<code>    <?php
    $currentConfig = parse_ini_file(path/to/config/config.ini);

    print_r($currentConfig); # prints the entire parsed .ini file

    print($currentConfig ['database_name ']); #prints "mydatabase_name"

?>
</code>```

Title: PHP - passing values to mysqli_connect

Body:
I have a legacy project, where I have a file with a class that in its construct method makes a connection with a database.

public $mysqli;

public function __construct(){
    $this->mysqli = mysqli_connect( "192.168.10.10", "homestead", "secret", "myDatabase" );
}

For now, I would like to make this somewhat flexible and make a config file with an array of values that I would pass to mysqli_connect method.  Something like this:

Config file:

$mysqliConfig = [
  '192.168.10.10',
  'homestead',
  'secret',
  'myDatabase'
];

And then just require that in the other file and use it in the class constructor of that file:

require_once 'includes/config.php';

class Calculator{

    private $mysqli;

    public function __construct(){
        $this->mysqli = mysqli_connect($mysqliConfig);
    }

But that is not working, how should I do that?

Body:
What i do is to have a .ini file Advantage is that it returns as a key value association.

save your config details in the .ini file(path/to/config.ini)
In config.ini file,

database_name = mydatabase_name
password = my_password
host = host
system_root = system_root
other_details = other_details

Then on your calculator class, do

    <?php
    $currentConfig = parse_ini_file(path/to/config/config.ini);

    print_r($currentConfig); # prints the entire parsed .ini file

    print($currentConfig ['database_name ']); #prints "mydatabase_name"

?>