问:
PHP Search File
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

```<code>abc-def.txt
ghi-jkl.txt
</code>```

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

```<code>$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '<br>';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);
</code>```

i need help in it.

答:
This is my teaching example

```<code><?php // demo/find_matching_files.php
/**
 * Put this script in the web root or other high-level directory
 *
 * Traverse this directory and all sub-directories down the tree
 * Show the matching files
 *
 * http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
 */
error_reporting( E_ALL );

// USE THE OUTPUT BUFFER TO COLLECT THE LIST OF FILES
ob_start();

// USE THE REQUEST VARIABLE TO MATCH A SUBSTRING OF THE FILE NAME
$q = !empty($_GET['q']) ? $_GET['q'] : NULL;
if (empty($q)) trigger_error('Missing URL request argument "q=" for file name', E_USER_ERROR);

// CONSTRUCT THE REGEX
$rgx
= '#'         // REGEX DELIMITER
. preg_quote($q)
. '#'         // REGEX DELIMITER
. 'i'         // CASE-INSENSITIVE
;

// START IN THE CURRENT DIRECTORY
$path = realpath(getcwd());

// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    if (preg_match($rgx, $name)) echo PHP_EOL . $name;
}

// IF THERE ARE MATCHES OR NO MATCHES
$out = ob_get_clean();
echo '```';
if (empty($out))
{
    echo PHP_EOL . "No match found for $q.";
}
else
{
    echo PHP_EOL . "Matches for $q.";
}

// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
    $text = explode(DIRECTORY_SEPARATOR, $text);
    $text = array_slice($text, 2);
    $name = implode(DIRECTORY_SEPARATOR, $text);
    echo PHP_EOL . "On Git branch: $name" . PHP_EOL;
}
else
{
    echo PHP_EOL . "On Git branch: UNKNOWN" . PHP_EOL;
}

// SHOW THE MATCHES
echo $out;
```

Title: PHP Search File

Body:
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

abc-def.txt
ghi-jkl.txt

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '
';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);

i need help in it.

Body:
This is my teaching example

<?php // demo/find_matching_files.php
/**
 * Put this script in the web root or other high-level directory
 *
 * Traverse this directory and all sub-directories down the tree
 * Show the matching files
 *
 * http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
 */
error_reporting( E_ALL );

// USE THE OUTPUT BUFFER TO COLLECT THE LIST OF FILES
ob_start();

// USE THE REQUEST VARIABLE TO MATCH A SUBSTRING OF THE FILE NAME
$q = !empty($_GET['q']) ? $_GET['q'] : NULL;
if (empty($q)) trigger_error('Missing URL request argument "q=" for file name', E_USER_ERROR);

// CONSTRUCT THE REGEX
$rgx
= '#'         // REGEX DELIMITER
. preg_quote($q)
. '#'         // REGEX DELIMITER
. 'i'         // CASE-INSENSITIVE
;

// START IN THE CURRENT DIRECTORY
$path = realpath(getcwd());

// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    if (preg_match($rgx, $name)) echo PHP_EOL . $name;
}

// IF THERE ARE MATCHES OR NO MATCHES
$out = ob_get_clean();
echo '<pre>';
if (empty($out))
{
    echo PHP_EOL . "No match found for <b>$q</b>.";
}
else
{
    echo PHP_EOL . "Matches for <b>$q</b>.";
}

// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
    $text = explode(DIRECTORY_SEPARATOR, $text);
    $text = array_slice($text, 2);
    $name = implode(DIRECTORY_SEPARATOR, $text);
    echo PHP_EOL . "On Git branch: $name" . PHP_EOL;
}
else
{
    echo PHP_EOL . "On Git branch: UNKNOWN" . PHP_EOL;
}

// SHOW THE MATCHES
echo $out;


来源: stackexchange

问:
Layer rule for all pages except two in Orchard CMS
I am trying to create a layer rule in the widgets section that shows a widget on all pages except two (or more). I've tried a number of options, in some cases the rule will exclude one page but not the other, in other cases it does not exclude either.

At first I wasn't sure how the exclude would work, I tried true not url("/page-1") which returned the error "The rule is not valid: Syntax error: Unexpected token in primary expression (Token 'Not' at position 5)", so I switched to not url("/page-1") which works (for excluding just one page).

I tried a number of ways to exclude more than one page without any luck, including these:

```<code>not url("/page-1") or not url("/page-2") // not excluded on any pages
not url("/page-1") or (not url("/page-2")) // not excluded on any pages
not url("/page-1") or url("/page-2") // excluded on page-1 only
</code>```

I found this issue which confirmed that url("/foo") or url("/bar") is how you include two URLs, which would suggest that the first example above is at least close.

Is it possible to show a widget on all pages, with a few specific pages excluded? Also, either way, is there a different method recommended for doing something like this, other than using a widget layer rule?

答:
This works:

```<code>not (url("/page-1") or url("/page-2"))
</code>```

I'm chalking this one up to being a little out of practice with logical expressions.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a layer rule in the widgets section that shows a widget on all pages except two (or more). I've tried a number of options, in some cases the rule will exclude one page but not the other, in other cases it does not exclude either.

At first I wasn't sure how the exclude would work, I tried true not url("/page-1") which returned the error "The rule is not valid: Syntax error: Unexpected token in primary expression (Token 'Not' at position 5)", so I switched to not url("/page-1") which works (for excluding just one page).

I tried a number of ways to exclude more than one page without any luck, including these:

not url("/page-1") or not url("/page-2") // not excluded on any pages
not url("/page-1") or (not url("/page-2")) // not excluded on any pages
not url("/page-1") or url("/page-2") // excluded on page-1 only

I found this issue which confirmed that url("/foo") or url("/bar") is how you include two URLs, which would suggest that the first example above is at least close.

Is it possible to show a widget on all pages, with a few specific pages excluded? Also, either way, is there a different method recommended for doing something like this, other than using a widget layer rule?

Body:
This works:

not (url("/page-1") or url("/page-2"))

I'm chalking this one up to being a little out of practice with logical expressions.


问:
Promise chain not executing in expected order - nodejs
I have a chain of 4 promises, and 1 function at the end. The final function is executing before the previous promises in the chain have resolved.

Can someone explain to me why this might be happening?

Here is the promise chain:

updateGdax(db)
  .then(updateBitstamp(db))
  .then(updateBitfinex(db))
  .then(updatePoloniex(db))
  .then(coinMarketData.updateCoinMarketData(db))
  .then(addRates(db)); //this function is executing after the first promise in the chain.```

I would like each function to execute after the one listed before it, so addRates(db) should be executed last.

I can post the code from the promise functions if needed for further analyses, but I really just want to understand WHY this would happen, as my understanding is that functions in a promise chain won't execute unless the previous promise in the chain has resolved.

答:
And have a look at the new async/await, included in nodejs 8. It is much more intuitive:</p>

```<code>async function main() {
  await updateGdax(db)
  await updateBitstamp(db)
  await updateBitfinex(db)
  await updatePoloniex(db)
  await coinMarketData.updateCoinMarketData(db)
  await addRates(db)
}

main().catch(e => console.error(e))
</code>```

Body:
I have a chain of 4 promises, and 1 function at the end. The final function is executing before the previous promises in the chain have resolved.

Can someone explain to me why this might be happening?

Here is the promise chain:

updateGdax(db)
  .then(updateBitstamp(db))
  .then(updateBitfinex(db))
  .then(updatePoloniex(db))
  .then(coinMarketData.updateCoinMarketData(db))
  .then(addRates(db)); //this function is executing after the first promise in the chain.

I would like each function to execute after the one listed before it, so addRates(db) should be executed last.

I can post the code from the promise functions if needed for further analyses, but I really just want to understand WHY this would happen, as my understanding is that functions in a promise chain won't execute unless the previous promise in the chain has resolved.

Body:
And have a look at the new async/await, included in nodejs 8. It is much more intuitive:

async function main() {
  await updateGdax(db)
  await updateBitstamp(db)
  await updateBitfinex(db)
  await updatePoloniex(db)
  await coinMarketData.updateCoinMarketData(db)
  await addRates(db)
}

main().catch(e => console.error(e))


问:
ListView jumping back to drag location when attempting to set keyboard focus
I've added standard drag drop functionality to a Listview. I've also added code to detect when I'm near the top or bottom in order to scroll when dragging.

Unfortunately, if I grab an unselected item, drag up/ down and scroll, on Drop the ListView will jump back to the vertical offset  that it started with when drag began.

I've attempted to reset the vertical offset, but so far I am unable to prevent this jump. Is there a way to prevent this behavior?

EDIT:
This code is executed before the drag (used to give focus to a textbox). Although, if I prevent this code from being called then the jump will not occur.

```<code>private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var element = Keyboard.FocusedElement;
        if (element is ListViewItem)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
            {
                (element as ListViewItem).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }));
        }
    }
</code>```

The issue may be with the way I begin my drag operation. Given the invocation.

```<code>    protected void BeginDrag(object sender, MouseEventArgs e, Action<object> action)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            Point position = e.GetPosition(this);
            this.ListView.ReleaseMouseCapture();

            if ((Math.Abs(position.X - _startPoint.X) > 10
                || Math.Abs(position.Y - _startPoint.Y) > 10)
                && !IsDragging)
            {
                try
                {
                    IsDragging = true;
                    Application.Current.Dispatcher.Invoke(
                        DispatcherPriority.Normal,
                        new System.Threading.ParameterizedThreadStart(action),
                        e);
                }
                catch (InvalidOperationException) { }
                finally
                {
                    IsDragging = false;
                }
            }
        }
    }
</code>```

答:
There was an issue if the BeginInvoke in SelectionChanged was called before the Invoke in the Drop. For one reason or another the BeginInvoke did not finish before the Invoke was called.

The Solution to this issue was to simply assure that the BeginInvoke for setting the focus was not called until AFTER the Invoke.

A fix is to attach the code to a different event, in this case I used MouseUp.

```<code>private void ListView_MouseUp(object sender, MouseButtonEventArgs e)
    {
        var element = Keyboard.FocusedElement;
        if (element is ListViewItem)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, new Action(delegate ()
            {
                (element as ListViewItem).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }));
        }
    }
</code>```

Not 100% perfect. When I drag and drop, the event for mouse up is not called. This means that the focus will not be set when I drag and drop; which may or may not be an issue.

Body:
I've added standard drag drop functionality to a Listview. I've also added code to detect when I'm near the top or bottom in order to scroll when dragging.

Unfortunately, if I grab an unselected item, drag up/ down and scroll, on Drop the ListView will jump back to the vertical offset  that it started with when drag began.

I've attempted to reset the vertical offset, but so far I am unable to prevent this jump. Is there a way to prevent this behavior?

EDIT:
This code is executed before the drag (used to give focus to a textbox). Although, if I prevent this code from being called then the jump will not occur.

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var element = Keyboard.FocusedElement;
        if (element is ListViewItem)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
            {
                (element as ListViewItem).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }));
        }
    }

The issue may be with the way I begin my drag operation. Given the invocation.

    protected void BeginDrag(object sender, MouseEventArgs e, Action<object> action)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            Point position = e.GetPosition(this);
            this.ListView.ReleaseMouseCapture();

            if ((Math.Abs(position.X - _startPoint.X) > 10
                || Math.Abs(position.Y - _startPoint.Y) > 10)
                && !IsDragging)
            {
                try
                {
                    IsDragging = true;
                    Application.Current.Dispatcher.Invoke(
                        DispatcherPriority.Normal,
                        new System.Threading.ParameterizedThreadStart(action),
                        e);
                }
                catch (InvalidOperationException) { }
                finally
                {
                    IsDragging = false;
                }
            }
        }
    }

Body:
There was an issue if the BeginInvoke in SelectionChanged was called before the Invoke in the Drop. For one reason or another the BeginInvoke did not finish before the Invoke was called.

The Solution to this issue was to simply assure that the BeginInvoke for setting the focus was not called until AFTER the Invoke.

A fix is to attach the code to a different event, in this case I used MouseUp.

private void ListView_MouseUp(object sender, MouseButtonEventArgs e)
    {
        var element = Keyboard.FocusedElement;
        if (element is ListViewItem)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, new Action(delegate ()
            {
                (element as ListViewItem).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }));
        }
    }

Not 100% perfect. When I drag and drop, the event for mouse up is not called. This means that the focus will not be set when I drag and drop; which may or may not be an issue.


问:
vnode and file descriptor in xnu, where does the file operation vector is stored
In xnu we have the vnode_t entity which represent the file globally.

Each process can access the file (assuming it has right permissions) by setting new file descriptor and set the vnode under fg_data

```<code>fp->f_fglob->fg_data = vp;
</code>```

the vnode contain a list of basic actions for all relevant operations and is set in according to the file's FS. i.e. HFS+ driver implement such vector and set its vnode accordingly.

```<code>int     (**v_op)(void *);       /* vnode operations vector */
</code>```

this is a vector for function pointers for all actions that may operate on the vnode.

In addition, we have the fileops struct that is part of the file descriptor (fg_global) which describe a minimal subset of these functions:

Here is a typical definition :

```<code>const struct fileops vnops = {
 .fo_type = DTYPE_VNODE,
 .fo_read = vn_read,
 .fo_write = vn_write,
 .fo_ioctl = vn_ioctl,
 .fo_select = vn_select,
 .fo_close = vn_closefile,
 .fo_kqfilter = vn_kqfilt_add,
 .fo_drain = NULL,
};
</code>```

and we set it here :

```<code>fp->f_fglob->fg_ops = &vnops;
</code>```

I saw that when reading regular file under local filesystem (HFS+), it works through the file_descriptor and not the vnode ...

```<code> * frame #0: 0xffffff801313c67c kernel`vn_read(fp=0xffffff801f004d98, uio=0xffffff807240be70, flags=0, ctx=0xffffff807240bf10) at vfs_vnops.c:978 [opt]
frame #1: 0xffffff801339cc1a kernel`dofileread [inlined] fo_read(fp=0xffffff801f004d98, uio=0xffffff807240be70, flags=0, ctx=0xffffff807240bf10) at kern_descrip.c:5832 [opt]
frame #2: 0xffffff801339cbff kernel`dofileread(ctx=0xffffff807240bf10, fp=0xffffff801f004d98, bufp=140222138463456, nbyte=282, offset=<unavailable>, flags=<unavailable>, retval=<unavailable>) at sys_generic.c:365 [opt]
frame #3: 0xffffff801339c983 kernel`read_nocancel(p=0xffffff801a597658, uap=0xffffff801a553cc0, retval=<unavailable>) at sys_generic.c:215 [opt]
frame #4: 0xffffff8013425695 kernel`unix_syscall64(state=<unavailable>) at systemcalls.c:376 [opt]
frame #5: 0xffffff8012e9dd46 kernel`hndl_unix_scall64 + 22
</code>```

My question is why does this duality needed, and in which cases the operation works through the file_descriptor vector (fg_ops) and which cases the operation works through the vnode vector (vp->v_op).

thanks

答:
[…] in which cases the
  operation works through the file_descriptor vector (fg_ops) and which
  cases the operation works through the vnode vector (vp->v_op).

I'm going to start by answering this second part of the question first: if you trace through your call stack further, and look inside the vn_read function, you'll find that it contains this line:

```<code>    error = VNOP_READ(vp, uio, ioflag, ctx);
</code>```

The VNOP_READ function (kpi_vfs.c) in turn has this:

```<code>_err = (*vp->v_op[vnop_read_desc.vdesc_offset])(&a);
</code>```

So the answer to your question is that for your typical file, both tables are used for dispatching operations.

With that out of the way,

My question is why does this duality needed […]

Not everything to which a process can hold a file descriptor is also represented in the file system. For example, pipes don't necessarily have to be named. A vnode doesn't make any sense in that context. So in sys_pipe.c, you'll see a different fileops table:

```<code>static const struct fileops pipeops = {
    .fo_type = DTYPE_PIPE,
    .fo_read = pipe_read,
    .fo_write = pipe_write,
    .fo_ioctl = pipe_ioctl,
    .fo_select = pipe_select,
    .fo_close = pipe_close,
    .fo_kqfilter = pipe_kqfilter,
    .fo_drain = pipe_drain,
};
</code>```

Similar deal for sockets.

File descriptors track the state of a process's view of a file or object that allows file-like operations. Things like position in the file, etc. - different processes can have the same file open, and they must each have their own read/write position - so vnode:fileglob is a 1:many relationship.

Meanwhile, using vnode objects to track things other than objects within a file system doesn't make any sense either. Additionally, the v_op table is file system specific, whereas vn_read/VNOP_READ contain code that applies to any file that's represented in a file system.

So in summary they're really just different layers in the I/O stack.

Body:
In xnu we have the vnode_t entity which represent the file globally.

Each process can access the file (assuming it has right permissions) by setting new file descriptor and set the vnode under fg_data

fp->f_fglob->fg_data = vp;

the vnode contain a list of basic actions for all relevant operations and is set in according to the file's FS. i.e. HFS+ driver implement such vector and set its vnode accordingly.

int     (**v_op)(void *);       /* vnode operations vector */

this is a vector for function pointers for all actions that may operate on the vnode.

In addition, we have the fileops struct that is part of the file descriptor (fg_global) which describe a minimal subset of these functions:

Here is a typical definition :

const struct fileops vnops = {
 .fo_type = DTYPE_VNODE,
 .fo_read = vn_read,
 .fo_write = vn_write,
 .fo_ioctl = vn_ioctl,
 .fo_select = vn_select,
 .fo_close = vn_closefile,
 .fo_kqfilter = vn_kqfilt_add,
 .fo_drain = NULL,
};

and we set it here :

fp->f_fglob->fg_ops = &vnops;

I saw that when reading regular file under local filesystem (HFS+), it works through the file_descriptor and not the vnode ...

 * frame #0: 0xffffff801313c67c kernel`vn_read(fp=0xffffff801f004d98, uio=0xffffff807240be70, flags=0, ctx=0xffffff807240bf10) at vfs_vnops.c:978 [opt]
frame #1: 0xffffff801339cc1a kernel`dofileread [inlined] fo_read(fp=0xffffff801f004d98, uio=0xffffff807240be70, flags=0, ctx=0xffffff807240bf10) at kern_descrip.c:5832 [opt]
frame #2: 0xffffff801339cbff kernel`dofileread(ctx=0xffffff807240bf10, fp=0xffffff801f004d98, bufp=140222138463456, nbyte=282, offset=<unavailable>, flags=<unavailable>, retval=<unavailable>) at sys_generic.c:365 [opt]
frame #3: 0xffffff801339c983 kernel`read_nocancel(p=0xffffff801a597658, uap=0xffffff801a553cc0, retval=<unavailable>) at sys_generic.c:215 [opt]
frame #4: 0xffffff8013425695 kernel`unix_syscall64(state=<unavailable>) at systemcalls.c:376 [opt]
frame #5: 0xffffff8012e9dd46 kernel`hndl_unix_scall64 + 22

My question is why does this duality needed, and in which cases the operation works through the file_descriptor vector (fg_ops) and which cases the operation works through the vnode vector (vp->v_op).

thanks

Body:
[…] in which cases the
  operation works through the file_descriptor vector (fg_ops) and which
  cases the operation works through the vnode vector (vp->v_op).

I'm going to start by answering this second part of the question first: if you trace through your call stack further, and look inside the vn_read function, you'll find that it contains this line:

    error = VNOP_READ(vp, uio, ioflag, ctx);

The VNOP_READ function (kpi_vfs.c) in turn has this:

_err = (*vp->v_op[vnop_read_desc.vdesc_offset])(&a);

So the answer to your question is that for your typical file, both tables are used for dispatching operations.

With that out of the way,

My question is why does this duality needed […]

Not everything to which a process can hold a file descriptor is also represented in the file system. For example, pipes don't necessarily have to be named. A vnode doesn't make any sense in that context. So in sys_pipe.c, you'll see a different fileops table:

static const struct fileops pipeops = {
    .fo_type = DTYPE_PIPE,
    .fo_read = pipe_read,
    .fo_write = pipe_write,
    .fo_ioctl = pipe_ioctl,
    .fo_select = pipe_select,
    .fo_close = pipe_close,
    .fo_kqfilter = pipe_kqfilter,
    .fo_drain = pipe_drain,
};

Similar deal for sockets.

File descriptors track the state of a process's view of a file or object that allows file-like operations. Things like position in the file, etc. - different processes can have the same file open, and they must each have their own read/write position - so vnode:fileglob is a 1:many relationship.

Meanwhile, using vnode objects to track things other than objects within a file system doesn't make any sense either. Additionally, the v_op table is file system specific, whereas vn_read/VNOP_READ contain code that applies to any file that's represented in a file system.

So in summary they're really just different layers in the I/O stack.


问:
Adobe Analytics- Email campaign tracking
My organization sends out various emails to users and we want to track " How many users clicked on the links in that particular email sent out by our team?".
How do we track this in Adobe Analytics & Reporting?
Right now I am only able to see, how many people clicked on the links in  all the emails combined  but I am not able to differentiate among various emails sent by our team

-Arjun Patil

答:
Append a query parameter to your Email landing page URL, which user will click on.
For example: www.mysite.com/landingpage?cmp=my_email_campaign_name

Then set up Adobe Analytics tracking code to capture this code and pass it to s.campaign variable or any other eVar used for campaign tracking.

```<code>s.campaign=s.Util.getQueryParam("cmp")
</code>```

Body:
Append a query parameter to your Email landing page URL, which user will click on.
For example: www.mysite.com/landingpage?cmp=my_email_campaign_name

Then set up Adobe Analytics tracking code to capture this code and pass it to s.campaign variable or any other eVar used for campaign tracking.

s.campaign=s.Util.getQueryParam("cmp")

ContentLicense: CC BY-SA 4.0


问:
Filter a Subform with a ComboBox - ACCESS 2013
How do I filter a Subform with a ComboBox. I have a ComboBox called FETextbox, it is populated with names from [tblMatterList]![Lead_FE]. I also have a subform called SubFormPF which when I select a name from FETextbox I want to filter to only show the rows with that name.

Here's what I have so far, this worked with a TextBox but doesn't with a combo box.

```<code>Private Sub FETextbox_Change()
Me.Filter = (Me.FETextbox = qryPlannedHours.Lead_FE)
Me.FilterOn = True
End Sub
</code>```

Any help is much appreciated!
If I've missed anything to help you let me know.

答:
The filter property needs to be set to a string that is the where part of a select statement (without the word "where").

https://msdn.microsoft.com/en-us/library/office/ff194672.aspx

Body:
How do I filter a Subform with a ComboBox. I have a ComboBox called FETextbox, it is populated with names from [tblMatterList]![Lead_FE]. I also have a subform called SubFormPF which when I select a name from FETextbox I want to filter to only show the rows with that name.

Here's what I have so far, this worked with a TextBox but doesn't with a combo box.

Private Sub FETextbox_Change()
Me.Filter = (Me.FETextbox = qryPlannedHours.Lead_FE)
Me.FilterOn = True
End Sub

Any help is much appreciated!
If I've missed anything to help you let me know.


问:
w3c markup validator ampersand (&) error
Is there any workaround for the w3c validation error for an & present in urls or some other place in HTML markup?

It says:

& did not start a character reference. (& probably should have been escaped as &.)

The ampersand in my case is a part of a url for gravatar thumbnail. This is the problematic part of a url:

c91588793296e2?s=50&d=http%3A%2F%.

答:
for each & sign you got write &
in your example it would be:

```<code>c91588793296e2?s=50&d=http%3A%2F%
</code>```

Body:
for each & sign you got write &amp;
in your example it would be:

c91588793296e2?s=50&amp;d=http%3A%2F%

ContentLicense: CC BY-SA 2.5


问:
Command line error D8016: '/O2' and '/RTC1' command-line options are incompatible
I'm trying to use the /O2 optimization for my project. I checked that the release configuration was enabled (Solution->Properties->Configuration Properties->Configuration->Release) and set Debug Information Format to /Zi but now I don't know what to do for this error.

答:
The optimization setting Maximize Speed (/O2) is incompatible to the Basic Runtime Checks setting of Code Generation.

To change the settings for Basic Runtime Checks:

Solution -> Properties -> Configuration Properties -> C/C++ -> Code Generation -> Basic Runtime Checks

Set it to "Default", and it should work.


问:
Use gdal.Open to open an in-memory GDAL Dataset
I have a GDAL dataset that exists only in memory (inmem_ds):

```<code>In: gdal.Info(inmem_ds)
Out:
('Driver: NUMPY/Numeric Python Array\n'
 'Files: none associated\n'
 'Size is 500, 500\n'
 'Coordinate System is:\n'
 'PROJCS["WGS 84 / UTM zone 19N",\n'
 '    GEOGCS["WGS 84",\n'
 '        DATUM["WGS_1984",\n'
 '            SPHEROID["WGS 84",6378137,298.257223563,\n'
 '                AUTHORITY["EPSG","7030"]],\n'
 '            AUTHORITY["EPSG","6326"]],\n'
 '        PRIMEM["Greenwich",0,\n'
 '            AUTHORITY["EPSG","8901"]],\n'
 '        UNIT["degree",0.0174532925199433,\n'
 '            AUTHORITY["EPSG","9122"]],\n'
 '        AUTHORITY["EPSG","4326"]],\n'
 '    PROJECTION["Transverse_Mercator"],\n'
 '    PARAMETER["latitude_of_origin",0],\n'
 '    PARAMETER["central_meridian",-69],\n'
 '    PARAMETER["scale_factor",0.9996],\n'
 '    PARAMETER["false_easting",500000],\n'
 '    PARAMETER["false_northing",0],\n'
 '    UNIT["metre",1,\n'
 '        AUTHORITY["EPSG","9001"]],\n'
 '    AXIS["Easting",EAST],\n'
 '    AXIS["Northing",NORTH],\n'
 '    AUTHORITY["EPSG","32619"]]\n'
 'Origin = (617085.000000000000000,-1512585.000000000000000)\n'
 'Pixel Size = (30.000000000000000,-30.000000000000000)\n'
 'Corner Coordinates:\n'
 'Upper Left  (  617085.000,-1512585.000) ( 67d55\' 2.38"W, 13d40\'47.58"S)\n'
 'Lower Left  (  617085.000,-1527585.000) ( 67d55\' 0.13"W, 13d48\'55.77"S)\n'
 'Upper Right (  632085.000,-1512585.000) ( 67d46\'43.12"W, 13d40\'45.26"S)\n'
 'Lower Right (  632085.000,-1527585.000) ( 67d46\'40.59"W, 13d48\'53.42"S)\n'
 'Center      (  624585.000,-1520085.000) ( 67d50\'51.55"W, 13d44\'50.54"S)\n'
 'Band 1 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 2 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 3 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 4 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 5 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 6 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 7 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 8 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n')
</code>```

Now I want to pass this dataset directly to an external Python library that uses gdal.Open() to open its input datasets. So I need a physical file path that I can pass to gdal.Open(). But I don´t want to write the in-memory GDAL dataset to disk in order to save IO time.

Is there any way to pass an in-memory dataset to gdal.Open()?

I tried to use a VRT dataset but it does not work:

```<code>drv = gdal.GetDriverByName("VRT")
vrt = drv.CreateCopy("/mypath/test.vrt", inmem_ds)
type(vrt.ReadAsArray()) # numpy.ndarray -> works

gdal.Open('/mypath/test.vrt') # None, last GDAL error: Exception: Error reading file:  Missing <SourceFilename> element in VRTRasterBand.
</code>```

The saved VRT file (mypath/test.vrt) looks like this:

```<code><VRTDataset rasterXSize="500" rasterYSize="500">
  <SRS>PROJCS["WGS 84 / UTM zone 19N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-69],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32619"]]</SRS>
  <GeoTransform>  6.1708500000000000e+05,  3.0000000000000000e+01,  0.0000000000000000e+00, -1.5125850000000000e+06,  0.0000000000000000e+00, -3.0000000000000000e+01</GeoTransform>
  <VRTRasterBand dataType="Int16" band="1">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>1</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="2">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>2</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="3">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>3</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="4">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>4</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="5">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>5</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="6">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>6</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="7">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>7</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="8">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>8</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
</VRTDataset>
</code>```

答: As you have seen, gdal.Open takes a filepath and in-memory datasets don't have filepaths. Data coercion techniques like VRT still require filepaths (<SourceFilename>). From my experience and the research for this question, I don't think there is a way to pass a dataset (in-memory or file-based) into gdal.Open. You might have to write to disk or try to modify the external library...

Body:
I have a GDAL dataset that exists only in memory (inmem_ds):

In: gdal.Info(inmem_ds)
Out:
('Driver: NUMPY/Numeric Python Array\n'
 'Files: none associated\n'
 'Size is 500, 500\n'
 'Coordinate System is:\n'
 'PROJCS["WGS 84 / UTM zone 19N",\n'
 '    GEOGCS["WGS 84",\n'
 '        DATUM["WGS_1984",\n'
 '            SPHEROID["WGS 84",6378137,298.257223563,\n'
 '                AUTHORITY["EPSG","7030"]],\n'
 '            AUTHORITY["EPSG","6326"]],\n'
 '        PRIMEM["Greenwich",0,\n'
 '            AUTHORITY["EPSG","8901"]],\n'
 '        UNIT["degree",0.0174532925199433,\n'
 '            AUTHORITY["EPSG","9122"]],\n'
 '        AUTHORITY["EPSG","4326"]],\n'
 '    PROJECTION["Transverse_Mercator"],\n'
 '    PARAMETER["latitude_of_origin",0],\n'
 '    PARAMETER["central_meridian",-69],\n'
 '    PARAMETER["scale_factor",0.9996],\n'
 '    PARAMETER["false_easting",500000],\n'
 '    PARAMETER["false_northing",0],\n'
 '    UNIT["metre",1,\n'
 '        AUTHORITY["EPSG","9001"]],\n'
 '    AXIS["Easting",EAST],\n'
 '    AXIS["Northing",NORTH],\n'
 '    AUTHORITY["EPSG","32619"]]\n'
 'Origin = (617085.000000000000000,-1512585.000000000000000)\n'
 'Pixel Size = (30.000000000000000,-30.000000000000000)\n'
 'Corner Coordinates:\n'
 'Upper Left  (  617085.000,-1512585.000) ( 67d55\' 2.38"W, 13d40\'47.58"S)\n'
 'Lower Left  (  617085.000,-1527585.000) ( 67d55\' 0.13"W, 13d48\'55.77"S)\n'
 'Upper Right (  632085.000,-1512585.000) ( 67d46\'43.12"W, 13d40\'45.26"S)\n'
 'Lower Right (  632085.000,-1527585.000) ( 67d46\'40.59"W, 13d48\'53.42"S)\n'
 'Center      (  624585.000,-1520085.000) ( 67d50\'51.55"W, 13d44\'50.54"S)\n'
 'Band 1 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 2 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 3 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 4 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 5 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 6 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 7 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n'
 'Band 8 Block=500x1 Type=Int16, ColorInterp=Undefined\n'
 '  NoData Value=-9999\n')

Now I want to pass this dataset directly to an external Python library that uses gdal.Open() to open its input datasets. So I need a physical file path that I can pass to gdal.Open(). But I don´t want to write the in-memory GDAL dataset to disk in order to save IO time.

Is there any way to pass an in-memory dataset to gdal.Open()?

I tried to use a VRT dataset but it does not work:

drv = gdal.GetDriverByName("VRT")
vrt = drv.CreateCopy("/mypath/test.vrt", inmem_ds)
type(vrt.ReadAsArray()) # numpy.ndarray -> works

gdal.Open('/mypath/test.vrt') # None, last GDAL error: Exception: Error reading file:  Missing <SourceFilename> element in VRTRasterBand.

The saved VRT file (mypath/test.vrt) looks like this:

<VRTDataset rasterXSize="500" rasterYSize="500">
  <SRS>PROJCS["WGS 84 / UTM zone 19N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-69],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32619"]]</SRS>
  <GeoTransform>  6.1708500000000000e+05,  3.0000000000000000e+01,  0.0000000000000000e+00, -1.5125850000000000e+06,  0.0000000000000000e+00, -3.0000000000000000e+01</GeoTransform>
  <VRTRasterBand dataType="Int16" band="1">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>1</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="2">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>2</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="3">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>3</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="4">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>4</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="5">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>5</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="6">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>6</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="7">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>7</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
  <VRTRasterBand dataType="Int16" band="8">
    <NoDataValue>-9999</NoDataValue>
    <SimpleSource>
      <SourceFilename relativeToVRT="0"></SourceFilename>
      <SourceBand>8</SourceBand>
      <SourceProperties RasterXSize="500" RasterYSize="500" DataType="Int16" BlockXSize="500" BlockYSize="1" />
      <SrcRect xOff="0" yOff="0" xSize="500" ySize="500" />
      <DstRect xOff="0" yOff="0" xSize="500" ySize="500" />
    </SimpleSource>
  </VRTRasterBand>
</VRTDataset>


问:
Error in Math.random() for arrayList
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

```<code>private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
</code>```

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!

答:
There are a couple of errors here.

First: If your method is not void is because you're gonna return something, in your method you should return a String.

Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double

Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.

So, the easier fix would be just changing the string and int for double and return it like this:

```<code>    private static double setQuestions(){

        double match = Math.floor(Math.random()*cities.length);

        return match;
    }
</code>```

Remember if you want to use the double returned you should store it when you call it, like this:

```<code>double result = setQuestions();
</code>```

Hope it helps!

Title: Error in Math.random() for arrayList

Body:
I'm sure this is a small, stupid error that I just can't see.

I'm getting a compiling error in this code:

private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }

in my length.

Compiling error is:

"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList  "

How can I fix this?  I do want to use Math.random();

Also not sure if this makes a difference, but this is is being done within a String method.

Thanks in advance!

Body:
There are a couple of errors here.

First: If your method is not void is because you're gonna return something, in your method you should return a String.

Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double

Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.

So, the easier fix would be just changing the string and int for double and return it like this:

    private static double setQuestions(){

        double match = Math.floor(Math.random()*cities.length);

        return match;
    }

Remember if you want to use the double returned you should store it when you call it, like this:

double result = setQuestions();

Hope it helps!


问:
PHP find max between variables
I'm trying to find out wich variable is bigger (those are all integers):

```<code><?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
</code>```

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

```<code>  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;
</code>```

I want endoA and endoB to be identified...

答:
I would definitely recommend using an array.  Then you can do something like this:

```<code>$my_array = array(3, 5, 0, 4, 11, 11);

$maxIndex = 0;

for($i = 1; $i < count($my_array); $i++) {
    if($my_array[$i] > $my_array[$maxIndex])
        $maxIndex = $i;
}
</code>```

Another option with array keys would be:

```<code>$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);

$maxIndex = "ectoA";

while($c = current($my_array)) {
    $key = key($my_array);
    if($my_array[$key] > $my_array[$maxIndex])
        $maxIndex = $key;

    next($my_array);
}
</code>```

Note: Code not tested, but should be the gist of what needs to be done

Title: PHP find max between variables

Body:
I'm trying to find out wich variable is bigger (those are all integers):

<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;

I want endoA and endoB to be identified...

Body:
I would definitely recommend using an array.  Then you can do something like this:

$my_array = array(3, 5, 0, 4, 11, 11);

$maxIndex = 0;

for($i = 1; $i < count($my_array); $i++) {
    if($my_array[$i] > $my_array[$maxIndex])
        $maxIndex = $i;
}

Another option with array keys would be:

$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);

$maxIndex = "ectoA";

while($c = current($my_array)) {
    $key = key($my_array);
    if($my_array[$key] > $my_array[$maxIndex])
        $maxIndex = $key;

    next($my_array);
}

Note: Code not tested, but should be the gist of what needs to be done


问:
Mapping this json to java object (pojo)
I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?

This is the json:

```<code>    {
"group": [
            {
                "name": "Beheerders",
                "desc": "Beheerders",
                "children" : [
                    "group" : [
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                            "children": [
                                "group" : [
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                },
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                }
                        }

            }
        ]
    }
</code>```

And i have these 4 pojo's:

Group.java

```<code>        private String name;
        private String desc;
        private Children children;

//getters & Setters & toString
</code>```

GroupList.java

```<code> private ArrayList<Group> group;

    public void setGroup(ArrayList<Group> group) {
        this.group = group;
    }

    public ArrayList<Group> getGroup() {
        return this.group;
    }
</code>```

Children.java

```<code>   private ArrayList<ChildrenGroup> group;

    public ArrayList<ChildrenGroup> getGroup() {
        return this.group;
    }

    public void setGroup(ArrayList<ChildrenGroup> group) {
        this.group = group;
    }
</code>```

childrengroup.java

```<code>    private String name;
    private String desc;
    private Children Children;

//Getters & Setters & toString
</code>```

This is not working for me, i always get this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

答:
Your JSON is not valid and your objects aren't correctly using object vs List. Please validate your example JSON. "children" : [ "group" : [ is invalid.

Your errors are occurring because it is encountering [ when your java objects are specifying {.

You can remove Children and ChildrenGroup and just nest GroupList inside Group as well.

Title: Mapping this json to java object (pojo)

Body:
I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?

This is the json:

    {
"group": [
            {
                "name": "Beheerders",
                "desc": "Beheerders",
                "children" : [
                    "group" : [
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                        },
                        {
                            "name": "Beheerders",
                            "desc": "Beheerders"
                            "children": [
                                "group" : [
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                },
                                {
                                    "name": "Beheerders",
                                    "desc": "Beheerders"
                                }
                        }

            }
        ]
    }

And i have these 4 pojo's:

Group.java

        private String name;
        private String desc;
        private Children children;

//getters & Setters & toString

GroupList.java

 private ArrayList<Group> group;

    public void setGroup(ArrayList<Group> group) {
        this.group = group;
    }

    public ArrayList<Group> getGroup() {
        return this.group;
    }

Children.java

   private ArrayList<ChildrenGroup> group;

    public ArrayList<ChildrenGroup> getGroup() {
        return this.group;
    }

    public void setGroup(ArrayList<ChildrenGroup> group) {
        this.group = group;
    }

childrengroup.java

    private String name;
    private String desc;
    private Children Children;

//Getters & Setters & toString

This is not working for me, i always get this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token


问:
Safely Removing DataRow In ForEach
I don't understand why this code does not work.</p>

```<code>foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}
</code>```

答:
Where items have a Count, this is what I have done:

```<code>int Count = myTable.Rows.Count;

while (Count > 0) // replace condition with myTable.Rows.Count if unconditionally performed on all rows
{
    DataRow row = myTable.Rows[0] // or however you want to find your index

    // do some work
    myTable.Rows.Remove(row);

    // if you want to perform a check to break out of while
    if (someCondition)
        Count = 0;
    else
        Count = myTable.Rows.Count;
}
</code>```

Note, that where objects have a .GetXXXX() collection, like FileInfo (IIRC),
deleting item contents in a foreach is acceptable. One solution I have considered is creating an extension method that provides a .GetItems() method.

Title: Safely Removing DataRow In ForEach

Body:
I don't understand why this code does not work.

foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}

Body:
Where items have a Count, this is what I have done:

int Count = myTable.Rows.Count;

while (Count > 0) // replace condition with myTable.Rows.Count if unconditionally performed on all rows
{
    DataRow row = myTable.Rows[0] // or however you want to find your index

    // do some work
    myTable.Rows.Remove(row);

    // if you want to perform a check to break out of while
    if (someCondition)
        Count = 0;
    else
        Count = myTable.Rows.Count;
}

Note, that where objects have a .GetXXXX() collection, like FileInfo (IIRC),
deleting item contents in a foreach is acceptable. One solution I have considered is creating an extension method that provides a .GetItems() method.


问:
How to get the output of a maxpool layer in a pre-trained model in TensorFlow?

I have a model that I trained. I wish to extract from the model the output of an intermediate maxpool layer.
I tried the following

saver = tf.train.import_meta_graph(BASE_DIR + LOG_DIR + '/model.ckpt.meta')
saver.restore(sess,tf.train.latest_checkpoint(BASE_DIR + LOG_DIR))
sess.run("maxpool/maxpool",feed_dict=feed_dict)
```

<p>here, <code>feed_dict</code> contains the placeholders and their contents for this run in a dictionary. </p>

<p>I keep getting the following error</p>

<pre class="lang-py prettyprint-override"><code>InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_1_1' with dtype float and shape...
</code>```

what can be the cause of this? I generated all of the placeholders and input them in the feed dictionary.

答:
I ran in to a similar issue and it was frustrating. What got me around it was filling out the name field for every variable and operation that I wanted to call later. You also may need to add your maxpool/maxpool op to a collection with tf.add_to_collection('name_for_maxpool_op', maxpool_op_handle). You can then restore the ops and named tensors with:

# Restore from metagraph.
saver = tf.train.import_meta_graph(...)
sess = tf.Session()
saver = restore(sess, ...)
graph = sess.graph

# Restore your ops and tensors.
maxpool_op = tf.get_collection('name_for_maxpool_op')[0]  # returns a list, you want the first element
a_tensor = graph.get_tensor_by_name('tensor_name:0')  # need the :0 added to your name
```

<p>Then you would build your <code>feed_dict</code> using your restored tensors. More information can be found here. Also, as you mentioned in your comment, you need to pass the op itself to <code>sess.run</code>, not it's name:</p>

<pre class="lang-py prettyprint-override"><code>sess.run(maxpool_op, feed_dict=feed_dict)
</code>```

You can access your tensors and ops from a restored metagraph even if you did not name them (to avoid retraining the model with new fancy tensor names, for instance), but it can be a bit of a pain. The names given to the tensors automatically are not always the most transparent. You can list the names of all variables in your graph with:

print([v.name for v in tf.all_variables()])
```

You can hopefully find the name that you are looking for there and then restore that tensor using graph.get_tensor_by_name as described above.

Body:
I have a model that I trained. I wish to extract from the model the output of an intermediate maxpool layer.
I tried the following

saver = tf.train.import_meta_graph(BASE_DIR + LOG_DIR + '/model.ckpt.meta')
saver.restore(sess,tf.train.latest_checkpoint(BASE_DIR + LOG_DIR))
sess.run("maxpool/maxpool",feed_dict=feed_dict)

here, feed_dict contains the placeholders and their contents for this run in a dictionary.

I keep getting the following error

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_1_1' with dtype float and shape...

what can be the cause of this? I generated all of the placeholders and input them in the feed dictionary.

Body:
I ran in to a similar issue and it was frustrating. What got me around it was filling out the name field for every variable and operation that I wanted to call later. You also may need to add your maxpool/maxpool op to a collection with tf.add_to_collection('name_for_maxpool_op', maxpool_op_handle). You can then restore the ops and named tensors with:

# Restore from metagraph.
saver = tf.train.import_meta_graph(...)
sess = tf.Session()
saver = restore(sess, ...)
graph = sess.graph

# Restore your ops and tensors.
maxpool_op = tf.get_collection('name_for_maxpool_op')[0]  # returns a list, you want the first element
a_tensor = graph.get_tensor_by_name('tensor_name:0')  # need the :0 added to your name

Then you would build your feed_dict using your restored tensors. More information can be found here. Also, as you mentioned in your comment, you need to pass the op itself to sess.run, not it's name:

sess.run(maxpool_op, feed_dict=feed_dict)

You can access your tensors and ops from a restored metagraph even if you did not name them (to avoid retraining the model with new fancy tensor names, for instance), but it can be a bit of a pain. The names given to the tensors automatically are not always the most transparent. You can list the names of all variables in your graph with:

print([v.name for v in tf.all_variables()])

You can hopefully find the name that you are looking for there and then restore that tensor using graph.get_tensor_by_name as described above.


问:
ruby-on-rails - Problem with Nested Resources
I have a Problem with Nested Resources.

2 Models

```<code>User => has_many :stuffs

Stuff => belongs_to :user
</code>```

routes.rb

```<code>map.resources :stuffs

map.resources :users, :has_many => [:stuffs]
</code>```

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

```<code>MySQL Query from Server
SELECT * FROM `stuffs`
</code>```

rake routes

```<code>stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}
</code>```

gem list

```<code>actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)
</code>```

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

答:
In your Stuffs controller's index method, how are you collecting your stuffs? If you used a scaffold to create the controller it will default to something like

```<code>@stuffs = Stuff.all
</code>```

but should be something along the lines of

```<code>@user = User.find(params[:user_id])
@stuffs = @user.stuffs
</code>```

or something to that effect--basically, you're collecting the user's stuff, not all stuff.

Body:
I have a Problem with Nested Resources.

2 Models

User => has_many :stuffs

Stuff => belongs_to :user

routes.rb

map.resources :stuffs

map.resources :users, :has_many => [:stuffs]

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

MySQL Query from Server
SELECT * FROM `stuffs`

rake routes

stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}

gem list

actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

Body:
In your Stuffs controller's index method, how are you collecting your stuffs? If you used a scaffold to create the controller it will default to something like

@stuffs = Stuff.all

but should be something along the lines of

@user = User.find(params[:user_id])
@stuffs = @user.stuffs

or something to that effect--basically, you're collecting the user's stuff, not all stuff.


问:
tensorflow using tf.train.string_input_producer
I'm using tf.train.string_input_producer to read data from tfRecord file. I suppose it create a queue and pipeline and the data will automatically loaded and feed into my model. However, it stuck at the first batch, and show this exception:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value input_producer/limit_epochs/epochs

my tfrecord was made by tf.train.SequenceExample, instead of tf.train.Example, which don't have clear documentation in the official guide.

here is code snapshot to reproduce my problem. (I believe my problem come from the queue initializing or sth. because it seems that the whole pipeline is hang up)

```<code>from config.config import get_config

init = tf.global_variables_initializer()
config = get_config()

filename_queue = tf.train.string_input_producer(['data0.tfrecord,data1.tfrecord'], 5, capacity=16384)
reader = tf.TFRecordReader()

(keys, values) = reader.read_up_to(filename_queue, config.batch_size)

context_features = {
    "seq_len": tf.FixedLenFeature([1], dtype=tf.int64),
}
audio_features = {
    "audio": tf.FixedLenSequenceFeature([config.num_features], dtype=tf.float32),
    "label": tf.FixedLenSequenceFeature([config.num_classes], dtype=tf.float32)
}
audio_list = []
label_list = []
len_list = []

for i in range(config.batch_size):
    print(i)
    context, sequence = tf.parse_single_sequence_example(
        serialized=values[i],
        context_features=context_features,
        sequence_features=audio_features
    )
    audio = sequence['audio']
    label = sequence['label']
    # seq_len = context['seq_len'][0]
    seq_len = tf.shape(audio)[0]
    audio_list.append(audio)
    label_list.append(label)
    len_list.append(seq_len)

audio_tensor = tf.stack(audio_list)
label_tenor = tf.stack(label_list)
len_tensor = tf.stack(len_list)

with tf.Session() as sess:
    sess.run(init)

    threads = tf.train.start_queue_runners(sess=sess)
    for i in range(3):
        x, y, z = sess.run([audio_tensor, label_tenor, len_tensor])
        print(z)
</code>```

答:
Try

```<code>init2 = tf.local_variables_initializer()
sess.run(init2)
</code>```

Variabes (num_epochs or capacity) inside tf.train.string_input_producer() are local variables. You have to initialize them with local variable initializer as shown above.

Let me know if this helped.

Body:
I'm using tf.train.string_input_producer to read data from tfRecord file. I suppose it create a queue and pipeline and the data will automatically loaded and feed into my model. However, it stuck at the first batch, and show this exception:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value input_producer/limit_epochs/epochs

my tfrecord was made by tf.train.SequenceExample, instead of tf.train.Example, which don't have clear documentation in the official guide.

here is code snapshot to reproduce my problem. (I believe my problem come from the queue initializing or sth. because it seems that the whole pipeline is hang up)

from config.config import get_config

init = tf.global_variables_initializer()
config = get_config()

filename_queue = tf.train.string_input_producer(['data0.tfrecord,data1.tfrecord'], 5, capacity=16384)
reader = tf.TFRecordReader()

(keys, values) = reader.read_up_to(filename_queue, config.batch_size)

context_features = {
    "seq_len": tf.FixedLenFeature([1], dtype=tf.int64),
}
audio_features = {
    "audio": tf.FixedLenSequenceFeature([config.num_features], dtype=tf.float32),
    "label": tf.FixedLenSequenceFeature([config.num_classes], dtype=tf.float32)
}
audio_list = []
label_list = []
len_list = []

for i in range(config.batch_size):
    print(i)
    context, sequence = tf.parse_single_sequence_example(
        serialized=values[i],
        context_features=context_features,
        sequence_features=audio_features
    )
    audio = sequence['audio']
    label = sequence['label']
    # seq_len = context['seq_len'][0]
    seq_len = tf.shape(audio)[0]
    audio_list.append(audio)
    label_list.append(label)
    len_list.append(seq_len)

audio_tensor = tf.stack(audio_list)
label_tenor = tf.stack(label_list)
len_tensor = tf.stack(len_list)

with tf.Session() as sess:
    sess.run(init)

    threads = tf.train.start_queue_runners(sess=sess)
    for i in range(3):
        x, y, z = sess.run([audio_tensor, label_tenor, len_tensor])
        print(z)

Body:
Try

init2 = tf.local_variables_initializer()
sess.run(init2)

Variabes (num_epochs or capacity) inside tf.train.string_input_producer() are local variables. You have to initialize them with local variable initializer as shown above.

Let me know if this helped.


问:
SQL Server Database Vesion
I have a problem regarding a SQL Server database.

The error message is

Cannot be opened because it is version 852. This server supports version 782 and earlier. A downgrade path is not supported.

I tried everything, updating via Visual Studio 2015, downloading SQL Server 2016, installing SSMS, but nothing changed the server's version.

I need to somehow change the server's version so it will attach the the database successfully.

Please help!

答:
You are attempting to attach SQL Server 2016 database files to SQL Server 2014.  This is not supported.

Your only solution is to upgrade SQL Server from 2014 to 2016.  Note, this is the database engine, not management studio.

Here is a list of all SQL Server internal database version numbers: http://sqlserverbuilds.blogspot.com/2014/01/sql-server-internal-database-versions.html

Title: SQL Server Database Vesion


问:
Pandas: Filter by values within multiple columns
I'm trying to filter a dataframe based on the values within the multiple columns, based on a single condition, but keep other columns to which I don't want to apply the filter at all.

I've reviewed these answers, with the third being the closest, but still no luck:

how do you filter pandas dataframes by multiple columns

Filtering multiple columns Pandas

Python Pandas - How to filter multiple columns by one value

Setup:

```<code>import pandas as pd

df = pd.DataFrame({
        'month':[1,1,1,2,2],
        'a':['A','A','A','A','NONE'],
        'b':['B','B','B','B','B'],
        'c':['C','C','C','NONE','NONE']
    }, columns = ['month','a','b','c'])

l = ['month','a','c']
df = df.loc[df['month'] == df['month'].max(), df.columns.isin(l)].reset_index(drop = True)
</code>```

Current Output:

```<code>   month     a     c
0      2     A  NONE
1      2  NONE  NONE
</code>```

Desired Output:

```<code>   month     a
0      2     A
1      2  NONE
</code>```

I've tried:

```<code>sub = l[1:]
df = df[(df.loc[:, sub] != 'NONE').any(axis = 1)]
</code>```

and many other variations (.all(), [sub, :], ~df.loc[...], (axis = 0)), but all with no luck.

Basically I want to drop any column (within the sub list) that has all 'NONE' values in it.

Any help is much appreciated.

答:
You first want to substitute your 'NONE' with np.nan so that it is recognized as a null value by dropna.  Then use loc with your boolean series and column subset.  Then use dropna with axis=1 and how='all'

```<code>df.replace('NONE', np.nan) \
    .loc[df.month == df.month.max(), l].dropna(axis=1, how='all')

   month     a
3      2     A
4      2  NONE
</code>```

Body:
I'm trying to filter a dataframe based on the values within the multiple columns, based on a single condition, but keep other columns to which I don't want to apply the filter at all.

I've reviewed these answers, with the third being the closest, but still no luck:

how do you filter pandas dataframes by multiple columns

Filtering multiple columns Pandas

Python Pandas - How to filter multiple columns by one value

Setup:

import pandas as pd

df = pd.DataFrame({
        'month':[1,1,1,2,2],
        'a':['A','A','A','A','NONE'],
        'b':['B','B','B','B','B'],
        'c':['C','C','C','NONE','NONE']
    }, columns = ['month','a','b','c'])

l = ['month','a','c']
df = df.loc[df['month'] == df['month'].max(), df.columns.isin(l)].reset_index(drop = True)

Current Output:

   month     a     c
0      2     A  NONE
1      2  NONE  NONE

Desired Output:

   month     a
0      2     A
1      2  NONE

I've tried:

sub = l[1:]
df = df[(df.loc[:, sub] != 'NONE').any(axis = 1)]

and many other variations (.all(), [sub, :], ~df.loc[...], (axis = 0)), but all with no luck.

Basically I want to drop any column (within the sub list) that has all 'NONE' values in it.

Any help is much appreciated.

Body:
You first want to substitute your 'NONE' with np.nan so that it is recognized as a null value by dropna.  Then use loc with your boolean series and column subset.  Then use dropna with axis=1 and how='all'

df.replace('NONE', np.nan) \
    .loc[df.month == df.month.max(), l].dropna(axis=1, how='all')

   month     a
3      2     A
4      2  NONE


问:
creating functions by conditons
I want to create functions if they doesn't exists and update when they exists.

But mssql says that is wrong syntax near function.

```<code> IF NOT EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin
Create function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
    return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
end

end
IF EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin

Alter function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL

)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
     return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
       end
End
Go
</code>```

How I can make update/create functions by condition?

答:
It might be easier to conditionally drop it:
(like Sql Server equivalent to Oracle's CREATE OR REPLACE VIEW)</p>

```<code>IF OBJECT_ID('[dbo].[CreateJson]') IS NOT NULL
DROP FUNCTION [dbo].[CreateJson]
GO
CREATE FUNCTION [dbo].[CreateJson]
AS
--
</code>```

Title: creating functions by conditons

Body:
I want to create functions if they doesn't exists and update when they exists.

But mssql says that is wrong syntax near function.

 IF NOT EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin
Create function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL
)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
    return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
end

end
IF EXISTS(SELECT 1 FROM sys.objects where name='CreateJson' AND type='U' )
Begin

Alter function [dbo].CreateJson
(
    @String  nvarchar(4000),
    @Param0  SQL_VARIANT = NULL

)
returns nvarchar(4000)
as
begin
    declare @Null nvarchar(4) = N'NULL';
     return  replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));
       end
End
Go

How I can make update/create functions by condition?

Body:
It might be easier to conditionally drop it:
(like Sql Server equivalent to Oracle's CREATE OR REPLACE VIEW)

IF OBJECT_ID('[dbo].[CreateJson]') IS NOT NULL
DROP FUNCTION [dbo].[CreateJson]
GO
CREATE FUNCTION [dbo].[CreateJson]
AS
--


问:
Can i remove schema.rb in production
Is this file for informational purposes ?

Can it be removed in production ?

答:
The schema.rb is used when you execute rake db:schema:load. If you are absolutely sure you are not going to execute this Rake task in production, then yes, you could remove it.

I'm unsure why you'd want to take the time to remove it explicitly, though.

Title: Can i remove schema.rb in production


问:
Tensorflow: Computing gradients w.r.t. sub-tensor
Let v be a Tensor. If I compute the gradient of another Tensor w.r.t to v everything works fine, i.e.

```<code>grads = tf.gradients(loss_func, v)
</code>```

works fine.

However, when I want to compute the gradient w.r.t to just a single element or any subtensor of v, I get an error, i.e.

```<code>grads = tf.gradients(loss_func, v[0,0])
grads = tf.gradients(loss_func, v[:,1:])
</code>```

produces the following error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/henning/anaconda/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/Users/henning/pflow/testing.py", line 89, in <module>
    theta = sess.run(grads, feed_dict={P:P_inp, Q:Q_inp})
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 952, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 230, in for_fetch
    return _ListFetchMapper(fetch)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 337, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 337, in <listcomp>
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 227, in for_fetch
    (fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <class 'NoneType'>
</code>```

What am I doing wrong?

答:
I found a solution to the problem.

The most elegant way of doing it that I found was to 'construct' v from constants and Variables and then compute the gradient w.r.t. the Variables, i.e.

```<code>v_free = tf.Variable(shape)
v_notfree = tf.constant(other_shape)
v = tf.concat([v_notfree, v_free])
loss_func = some function of v
grads = tf.gradients(loss_func, v_free)
</code>```

Body:
Let v be a Tensor. If I compute the gradient of another Tensor w.r.t to v everything works fine, i.e.

grads = tf.gradients(loss_func, v)

works fine.

However, when I want to compute the gradient w.r.t to just a single element or any subtensor of v, I get an error, i.e.

grads = tf.gradients(loss_func, v[0,0])
grads = tf.gradients(loss_func, v[:,1:])

produces the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/henning/anaconda/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/Users/henning/pflow/testing.py", line 89, in <module>
    theta = sess.run(grads, feed_dict={P:P_inp, Q:Q_inp})
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 952, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 230, in for_fetch
    return _ListFetchMapper(fetch)
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 337, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 337, in <listcomp>
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/Users/henning/anaconda/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 227, in for_fetch
    (fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <class 'NoneType'>

What am I doing wrong?

Body:
I found a solution to the problem.

The most elegant way of doing it that I found was to 'construct' v from constants and Variables and then compute the gradient w.r.t. the Variables, i.e.

v_free = tf.Variable(shape)
v_notfree = tf.constant(other_shape)
v = tf.concat([v_notfree, v_free])
loss_func = some function of v
grads = tf.gradients(loss_func, v_free)


问:
JSONDecodeError: Expecting value: line 1 column 1 (char 0) on Iris dataset
I'm a trying to create a machine learning model using the Iris data set (doing this by watching tutorial, complete newbie to machine learning and data science), so far I have classified it using Random Forest Classifier, but now I wish to check my predictions against custom input, my main code for classification looks like this:

```<code>X= iris.data
y= iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y)
rfc = RandomForestClassifier(n_estimators=100, n_jobs=2)
rfc.fit(X_train, y_train)
print ("Accuracy = %0.2f" % accuracy_score(y_test, rfc.predict(X_test)))
print (classification_report(y_test, rfc.predict(X_test)))
pickle.dump(rfc, open("iris_rfc1.pkl", "wb"))
my_random_forest = pickle.load(open("iris_rfc1.pkl","rb"))
url= "http://localhost:9000/api"
data = json.dumps({'sl':5.8,'sw':4,'pl':2,'pw':9})
r = requests.post(url, data)

print (r.json())
</code>```

The Flask file I use to make connection:

```<code>my_random_forest = pickle.load(open('iris_rfc1.pkl','rb'))
app = Flask(__name__)

@app.route('/api', methods=['POST'])
def make_predict():
    data = request.get_json(force = True)
    predict_request = [data['sl'],data['sw'], data['pl'], data['pw']]
    predict_request = np.array(predict_request)
    y_hat = my_random_forest.predict(predict_request)
    output = [y_hat[0]]
    return jsonify(results = output)

if __name__ == '__main__':
    app.run(port=9000, debug = True)
</code>```

But when I run the program I get error "JSONDecodeError: Expecting value: line 1 column 1 (char 0)"

Additional details: I'm using Jupyter Notebook for making prediction and atom for creating the flask file, Pyhton Version 3

答:
The result delivered by the function make_predict() is where the error occurs.

JSON(Java Script Object Notation) can only represent/serialize a limited group of data types and Numpy objects do not belong to that group.

Looking at the error message, the number 0 must be the prediction generated by the Random Forest Classifier and RFCs only operate on Numpy arrays. Their outputs too are of the same data type. The .json() method doesn't know how to serialize a numpy object.

```<code>>>>a = rfc.predict(np.array([1,2,3,4]).reshape(1,-1))
>>>a, type(a)
(array([1]), numpy.ndarray)

>>>b = a[0]
>>>b, type(b)
(1, numpy.int32)

>>>c = np.asscalar(b)
>>>c, type(c)
(1, int)
</code>```

The y_hat is a numpy array, the first element of y_hat(output variable) is of the type np.int32. Cast it as an int using the np.asscalar() method, json() will be able to identify it.

Body:
I'm a trying to create a machine learning model using the Iris data set (doing this by watching tutorial, complete newbie to machine learning and data science), so far I have classified it using Random Forest Classifier, but now I wish to check my predictions against custom input, my main code for classification looks like this:

X= iris.data
y= iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y)
rfc = RandomForestClassifier(n_estimators=100, n_jobs=2)
rfc.fit(X_train, y_train)
print ("Accuracy = %0.2f" % accuracy_score(y_test, rfc.predict(X_test)))
print (classification_report(y_test, rfc.predict(X_test)))
pickle.dump(rfc, open("iris_rfc1.pkl", "wb"))
my_random_forest = pickle.load(open("iris_rfc1.pkl","rb"))
url= "http://localhost:9000/api"
data = json.dumps({'sl':5.8,'sw':4,'pl':2,'pw':9})
r = requests.post(url, data)

print (r.json())

The Flask file I use to make connection:

my_random_forest = pickle.load(open('iris_rfc1.pkl','rb'))
app = Flask(__name__)

@app.route('/api', methods=['POST'])
def make_predict():
    data = request.get_json(force = True)
    predict_request = [data['sl'],data['sw'], data['pl'], data['pw']]
    predict_request = np.array(predict_request)
    y_hat = my_random_forest.predict(predict_request)
    output = [y_hat[0]]
    return jsonify(results = output)

if __name__ == '__main__':
    app.run(port=9000, debug = True)

But when I run the program I get error "JSONDecodeError: Expecting value: line 1 column 1 (char 0)"

Additional details: I'm using Jupyter Notebook for making prediction and atom for creating the flask file, Pyhton Version 3

Body:
The result delivered by the function make_predict() is where the error occurs.

JSON(Java Script Object Notation) can only represent/serialize a limited group of data types and Numpy objects do not belong to that group.

Looking at the error message, the number 0 must be the prediction generated by the Random Forest Classifier and RFCs only operate on Numpy arrays. Their outputs too are of the same data type. The .json() method doesn't know how to serialize a numpy object.

>>>a = rfc.predict(np.array([1,2,3,4]).reshape(1,-1))
>>>a, type(a)
(array([1]), numpy.ndarray)

>>>b = a[0]
>>>b, type(b)
(1, numpy.int32)

>>>c = np.asscalar(b)
>>>c, type(c)
(1, int)

The y_hat is a numpy array, the first element of y_hat(output variable) is of the type np.int32. Cast it as an int using the np.asscalar() method, json() will be able to identify it.


问:
Xslt transform types declared in xs:import schema
I need to transform a xsd, which represents Java dtos into html.
The main goal is the allowed to fill the object even in production if the regular input fails. (i.e., it doesn't need to be pretty)

I found https://github.com/MichielCM/xsd2html2xml which should do exactly what I want, but unfortunately doesn't.

My problem is the following: If I have a source schema like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:c="http://www.trivia/commonTypes/v1_0"
       targetNamespace="http://www.trivia/v1_0" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0">

<xs:import schemaLocation="comm.xsd" namespace="http://www.trivia/commonTypes/v1_0" />

<xs:element name="common" type="c:typeAddress"/>
<xs:element name="local" type="typeAddress"/>
<xs:element name="simple" type="xs:string"/>

<xs:complexType name="typeAddress">
    <xs:sequence>
        <xs:element name="city" minOccurs="0">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:maxLength value="40" />
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
    </xs:sequence>
</xs:complexType>
</code>```

the simple and local elements are transformed as expected, but the common element is not. The comm.xsd contains a copy of typeAdress for the sake of the example.

The question is how can I reference a type declared with an import statement in a xsl transformation?

答: Doing any kind of processing that starts from source XSD documents is a tough undertaking, because there are so many ways of expressing things: do you need to handle named attribute groups or model groups, for example? What about xs:redefines? You can always extend a bit of software like this to handle one more case, but you're on an uphill escalator: there's always going to be a lot more to do before you're finished. My advice is, don't do it this way. Use an API that gives you access to the internal schema component model built by a schema processor. The Xerces processor exposes this via a Java API, the Saxon processor exposes it as an XML document (called an SCM file). Either way all the surface stuff like xs:import is taken care of and you only need worry about the underlying data model.</p>

Body:
I need to transform a xsd, which represents Java dtos into html.
The main goal is the allowed to fill the object even in production if the regular input fails. (i.e., it doesn't need to be pretty)

I found https://github.com/MichielCM/xsd2html2xml which should do exactly what I want, but unfortunately doesn't.

My problem is the following: If I have a source schema like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:c="http://www.trivia/commonTypes/v1_0"
       targetNamespace="http://www.trivia/v1_0" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0">

<xs:import schemaLocation="comm.xsd" namespace="http://www.trivia/commonTypes/v1_0" />

<xs:element name="common" type="c:typeAddress"/>
<xs:element name="local" type="typeAddress"/>
<xs:element name="simple" type="xs:string"/>

<xs:complexType name="typeAddress">
    <xs:sequence>
        <xs:element name="city" minOccurs="0">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:maxLength value="40" />
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
    </xs:sequence>
</xs:complexType>

the simple and local elements are transformed as expected, but the common element is not. The comm.xsd contains a copy of typeAdress for the sake of the example.

The question is how can I reference a type declared with an import statement in a xsl transformation?


问:
Summing the Non-Null results in a matrix
I have a report that looks like the picture below. It is a matrix with person name on the rows and weeknum on the columns. What I need to calculate is the number of weeks that have data in the calls taken column. In the picture below it is the consistency column with the red numbers. I can't seem to get those red numbers to appear. Is there an expression that can count the number of columns that aren't null in a particular matrix. This report will be dynamically generated and the number of weeks will be totally different each time.

I would rather solve this in SSRS because I don't want to mess with my SQL too much but if no SSRS solution is possible I can post my SQL and perhaps solve it that way.

答:
You need to create a column group outside of the last group. So in your example, Right click on the column tab above your efficiency column in the 23rd week. After you create this column, you can use a simple Count(Fields!CallsTaken.Value) in an expression to count the times there are values listed.

Reference SO question on Horizontal Totals.