问:
ReflectionException in Container.php line 776: Class APPPATH\Http\Controllers\DashboardController does not exist
I know that this error exist in many posts but I tried everything without any solution. After I changed the value model in the auth.php file, to the correct path of the user model, my controllers are not working. All of the controllers throwing the following issue but only the Auth controller is working fine. The error message that I'm getting is:

ReflectionException in Container.php line 776: Class
  APPPATH\Http\Controllers\DashboardController does not exist

I made composer dump-autoload but still the same. My controller is inside App\Http\Controllers\Administrator\Dashboard\DashboardController.php

```<code>namespace APPPATH\Http\Controllers;

    class DashboardController extends Controller {}
</code>```

and inside my route i have this

```<code>get('/', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));

get('/dashboard', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));

get('/dashboard/index', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));
</code>```

Here is the composer of laravel 5

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "APPPATH\": "app/"
    }
},

Does anyone knows why is not working? Thank you

The error message

ReflectionException in Container.php line 776:

Class APPPATH\Http\Controllers\DashboardController does not exist in
  Container.php line 776

at
  ReflectionClass->__construct('APPPATH\Http\Controllers\DashboardController')
  in Container.php line 776

at Container->build('APPPATH\Http\Controllers\DashboardController',
  array()) in Container.php line 656

at Container->make('APPPATH\Http\Controllers\DashboardController',
  array()) in Application.php line 620

at Application->make('APPPATH\Http\Controllers\DashboardController')
  in ControllerDispatcher.php line 83

at
  ControllerDispatcher->makeController('APPPATH\Http\Controllers\DashboardController')
  in ControllerDispatcher.php line 54

at ControllerDispatcher->dispatch(object(Route), object(Request),
  'APPPATH\Http\Controllers\DashboardController', 'index') in Route.php
  line 198

at Route->runWithCustomDispatcher(object(Request)) in Route.php line
  131

at Route->run(object(Request)) in Router.php line 691

at Router->Illuminate\Routing{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  141

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  101

at Pipeline->then(object(Closure)) in Router.php line 693

at Router->runRouteWithinStack(object(Route), object(Request)) in
  Router.php line 660

at Router->dispatchToRoute(object(Request)) in Router.php line 618

at Router->dispatch(object(Request)) in Kernel.php line 214

at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  141

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  VerifyCsrfToken.php line 43

at VerifyCsrfToken->handle(object(Request), object(Closure)) in
  VerifyCsrfToken.php line 17

at VerifyCsrfToken->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  ShareErrorsFromSession.php line 55

at ShareErrorsFromSession->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  StartSession.php line 61

at StartSession->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  AddQueuedCookiesToResponse.php line 36

at AddQueuedCookiesToResponse->handle(object(Request),
  object(Closure)) in Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  EncryptCookies.php line 40

at EncryptCookies->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  CheckForMaintenanceMode.php line 42

at CheckForMaintenanceMode->handle(object(Request), object(Closure))
  in Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  101

at Pipeline->then(object(Closure)) in Kernel.php line 115

at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php
  line 84

at Kernel->handle(object(Request)) in index.php line 53

答:
```<code>get('/', array('as' => 'administrator.dashboard', 'uses' => '\APPPATH\Http\DashboardController@index'));
</code>```

It will try to get it from root namespaces

Body:
I know that this error exist in many posts but I tried everything without any solution. After I changed the value model in the auth.php file, to the correct path of the user model, my controllers are not working. All of the controllers throwing the following issue but only the Auth controller is working fine. The error message that I'm getting is:

ReflectionException in Container.php line 776: Class
  APPPATH\Http\Controllers\DashboardController does not exist

I made composer dump-autoload but still the same. My controller is inside App\Http\Controllers\Administrator\Dashboard\DashboardController.php

namespace APPPATH\Http\Controllers;

    class DashboardController extends Controller {}

and inside my route i have this

get('/', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));

get('/dashboard', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));

get('/dashboard/index', array('as' => 'administrator.dashboard', 'uses' => 'DashboardController@index'));

Here is the composer of laravel 5

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "APPPATH\": "app/"
    }
},

Does anyone knows why is not working? Thank you

The error message

ReflectionException in Container.php line 776:

Class APPPATH\Http\Controllers\DashboardController does not exist in
  Container.php line 776

at
  ReflectionClass->__construct('APPPATH\Http\Controllers\DashboardController')
  in Container.php line 776

at Container->build('APPPATH\Http\Controllers\DashboardController',
  array()) in Container.php line 656

at Container->make('APPPATH\Http\Controllers\DashboardController',
  array()) in Application.php line 620

at Application->make('APPPATH\Http\Controllers\DashboardController')
  in ControllerDispatcher.php line 83

at
  ControllerDispatcher->makeController('APPPATH\Http\Controllers\DashboardController')
  in ControllerDispatcher.php line 54

at ControllerDispatcher->dispatch(object(Route), object(Request),
  'APPPATH\Http\Controllers\DashboardController', 'index') in Route.php
  line 198

at Route->runWithCustomDispatcher(object(Request)) in Route.php line
  131

at Route->run(object(Request)) in Router.php line 691

at Router->Illuminate\Routing{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  141

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  101

at Pipeline->then(object(Closure)) in Router.php line 693

at Router->runRouteWithinStack(object(Route), object(Request)) in
  Router.php line 660

at Router->dispatchToRoute(object(Request)) in Router.php line 618

at Router->dispatch(object(Request)) in Kernel.php line 214

at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  141

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  VerifyCsrfToken.php line 43

at VerifyCsrfToken->handle(object(Request), object(Closure)) in
  VerifyCsrfToken.php line 17

at VerifyCsrfToken->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  ShareErrorsFromSession.php line 55

at ShareErrorsFromSession->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  StartSession.php line 61

at StartSession->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  AddQueuedCookiesToResponse.php line 36

at AddQueuedCookiesToResponse->handle(object(Request),
  object(Closure)) in Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  EncryptCookies.php line 40

at EncryptCookies->handle(object(Request), object(Closure)) in
  Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in
  CheckForMaintenanceMode.php line 42

at CheckForMaintenanceMode->handle(object(Request), object(Closure))
  in Pipeline.php line 125

at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at
  call_user_func(object(Closure), object(Request)) in Pipeline.php line
  101

at Pipeline->then(object(Closure)) in Kernel.php line 115

at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php
  line 84

at Kernel->handle(object(Request)) in index.php line 53

Body:
get('/', array('as' => 'administrator.dashboard', 'uses' => '\APPPATH\Http\DashboardController@index'));

It will try to get it from root namespaces


来源: stackexchange

问:
Best way to remove = and ? from get method in PHP?
What's the best way to remove the = and ? in a URL from the get method in PHP? I'm working on the pagination structure of my website and currently this is what the URLs look like:

```<code>www.example/test/?page=3
</code>```

I want it to look like this:

```<code>www.example/test/3
</code>```

Can this be addressed directly in the PHP get method with some extra code or does it have to be done through an htaccess file?

This is what my htaccess file looks like right now:

```<code>RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]
</code>```

答:
Here is my try, I compacted some already existing answer from different StackOverflow topics dealing with URL extraction and I came up with this solution :

```<code><?php
    function http_protocol() {
        /**
         * @see https://stackoverflow.com/a/6768831/3753055
         */
        return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://';
    }

    function http_host() {
        return $_SERVER['HTTP_HOST'];
    }

    function http_uri() {
        return parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    }

    function http_refactored_query_strings() {
        $queries = explode('&', $_SERVER['QUERY_STRING']);
        $refactoredQueries = [];

        foreach( $queries as $query ) {
            $refactoredQueries[] = filter_var(explode('=', $query)[1], FILTER_SANITIZE_STRING);
        }

        $queries = implode('/', $refactoredQueries);

        return $queries ?: '';
    }

    function http_refactored_url() {
        return http_protocol() . http_host() . http_uri() . http_refactored_query_strings();
    }

    echo http_refactored_url();
?>
</code>```

Tryied with some examples :

GET http://example.com/test.php : http://example.com/test.php

GET http://example.com/test.php?page=3 : http://example.com/test.php/3

GET https://example.com/test.php?view=page?page=3 : https://example.com/page/3

GET http://example.com/?page=3 : http://example.com/3

For the query string refactoring part, I used $_SERVER['QUERY_STRING] and exploded the value to & character. because the first ? is not contained in $_SERVER['QUERY_STRING']. So you come up with lot of arrays, containing strings like page=3, view=page, ... And foreach one, you split it using = delimiter and get the second element (index : 1) to append it to the solution.

Hope it helps

ContentLicense: CC BY-SA 3.0

Body:
What's the best way to remove the = and ? in a URL from the get method in PHP? I'm working on the pagination structure of my website and currently this is what the URLs look like:

www.example/test/?page=3

I want it to look like this:

www.example/test/3

Can this be addressed directly in the PHP get method with some extra code or does it have to be done through an htaccess file?

This is what my htaccess file looks like right now:

RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]

Body:
Here is my try, I compacted some already existing answer from different StackOverflow topics dealing with URL extraction and I came up with this solution :

<?php
    function http_protocol() {
        /**
         * @see https://stackoverflow.com/a/6768831/3753055
         */
        return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://';
    }

    function http_host() {
        return $_SERVER['HTTP_HOST'];
    }

    function http_uri() {
        return parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    }

    function http_refactored_query_strings() {
        $queries = explode('&', $_SERVER['QUERY_STRING']);
        $refactoredQueries = [];

        foreach( $queries as $query ) {
            $refactoredQueries[] = filter_var(explode('=', $query)[1], FILTER_SANITIZE_STRING);
        }

        $queries = implode('/', $refactoredQueries);

        return $queries ?: '';
    }

    function http_refactored_url() {
        return http_protocol() . http_host() . http_uri() . http_refactored_query_strings();
    }

    echo http_refactored_url();
?>

Tryied with some examples :

GET http://example.com/test.php : http://example.com/test.php

GET http://example.com/test.php?page=3 : http://example.com/test.php/3

GET https://example.com/test.php?view=page?page=3 : https://example.com/page/3

GET http://example.com/?page=3 : http://example.com/3

For the query string refactoring part, I used $_SERVER['QUERY_STRING] and exploded the value to & character. because the first ? is not contained in $_SERVER['QUERY_STRING']. So you come up with lot of arrays, containing strings like page=3, view=page, ... And foreach one, you split it using = delimiter and get the second element (index : 1) to append it to the solution.

Hope it helps


问:
Laravel Auth::user() has no code completion for User model functions
I am using Laravel and PHPStorm.

The auto completion works for all models, just not for the 'User', when I call it with Auth::user().

When I call the Auth::user() I get the right user object, but the return type of Auth::user() is Authenticatable and not User. So I get no code completion for my user object which is very anoying because I use it very often. I think the problem has something to do with the return type of Auth::user() because it is Authenticatable and not User.

In the config/auth.php I already set the model to app/User::class.

Can you tell me how to cast the return value to the User model?

In this example you can see the behaviour.

答:
Add laravel-ide-helper package to your project - https://github.com/barryvdh/laravel-ide-helper.

The package generates a help file for the IDE with all the Facades and their functions.
It fixes the Facades auto-completion so Auth::user() is fixes too


问:
Using .BY, .GRP or other methods to add a multicolumn aggregation with data.table
Say we have this toy data.table example:

```<code>temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))
"V" "GR"
 A   1
 B   1
 C   1
 D   2
 A   2
</code>```

I would like to generate all ordered combinations with combn within each subset defined by GR and create with it a new data.table and with a new column with the grouping factor.

For example, for GR=1 we have (A,B),(A,C),(B,C)

for GR=2 we have (D,A)

If I create the result manually it would be

```<code>cbind(V=c(1,1,1,2),rbind(t(combn(c("A", "B", "C"),2)),t(combn(c( "D","A"),2))))

1  A  B
1  A  C
1  B  C
2  D  A
</code>```

But I would like to do it with data.table easily instead.

This two option don't work:

```<code>temp[,cbind(rep(.GRP,.N),as.data.frame(t(combn(V,2)))),by=GR]
temp[,cbind(rep(.BY,.N),as.data.frame(t(combn(V,2)))),by=GR]
</code>```

This one work, but I don't understand why. I'm afraid it could copy the whole B vector as is instead of the proper value.

```<code>temp[,.(GR,as.list(as.data.frame((combn(V,2))))),by=GR]
</code>```

And I guess it should be a shorter way to write it.

答:
This works:

```<code>> temp[, {v_comb = combn(V,2); .(v_comb[1,], v_comb[2,])}, by=GR]
   GR V1 V2
1:  1  A  B
2:  1  A  C
3:  1  B  C
4:  2  D  A
</code>```

In general, I would avoid when possible all the reshaping operations within the data.table using cbind(), rep(), as.data.frame() or t()... It takes many trials-and-errors to figure out the right way to do it, and produces code that is very hard to maintain.

On the other hand, using code blocks {...} improves the readability of the code.

Body:
Say we have this toy data.table example:

temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))
"V" "GR"
 A   1
 B   1
 C   1
 D   2
 A   2

I would like to generate all ordered combinations with combn within each subset defined by GR and create with it a new data.table and with a new column with the grouping factor.

For example, for GR=1 we have (A,B),(A,C),(B,C)

for GR=2 we have (D,A)

If I create the result manually it would be

cbind(V=c(1,1,1,2),rbind(t(combn(c("A", "B", "C"),2)),t(combn(c( "D","A"),2))))

1  A  B
1  A  C
1  B  C
2  D  A

But I would like to do it with data.table easily instead.

This two option don't work:

temp[,cbind(rep(.GRP,.N),as.data.frame(t(combn(V,2)))),by=GR]
temp[,cbind(rep(.BY,.N),as.data.frame(t(combn(V,2)))),by=GR]

This one work, but I don't understand why. I'm afraid it could copy the whole B vector as is instead of the proper value.

temp[,.(GR,as.list(as.data.frame((combn(V,2))))),by=GR]

And I guess it should be a shorter way to write it.

Body:
This works:

> temp[, {v_comb = combn(V,2); .(v_comb[1,], v_comb[2,])}, by=GR]
   GR V1 V2
1:  1  A  B
2:  1  A  C
3:  1  B  C
4:  2  D  A

In general, I would avoid when possible all the reshaping operations within the data.table using cbind(), rep(), as.data.frame() or t()... It takes many trials-and-errors to figure out the right way to do it, and produces code that is very hard to maintain.

On the other hand, using code blocks {...} improves the readability of the code.


问:
Can't paste Image from Clipboard to RichTextBox
I'm looking to programmatically convert a base64 string into an Image that I then insert into a richTextBox.

Right now I load the string into a stream and convert that into an Image. I then load that onto the Clipboard and attempt to paste. However, when I execute the code, nothing pastes into the richTextBox. After running the code, the image is properly set in my Clipboard and I am able to paste it manually into the richTextBox - it just doesn't seem to work programmatically.

Here's my code:

```<code>byte[] img_bytes = Convert.FromBase64String(imgStr);
using (var ms = new MemoryStream(img_bytes, 0, img_bytes.Length))
{
    Image img = Image.FromStream(ms, true);
    Bitmap imgb = (Bitmap)Bitmap.FromStream(ms);
    Clipboard.SetDataObject(img);
    Console.WriteLine(Clipboard.ContainsImage()); // Prints True
    richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
    Console.WriteLine(richTextBox1.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap))); // Prints True
    richTextBox1.Text += "\n";
}
</code>```

Update: It appears that setting the text field after pasting the image deletes the image. I guess the question now is, how do I have both the image and the text?

答:
It appears that setting a richTextBox's text attribute after pasting was deleting the image. I changed the line

```<code>richTextBox1.Text += "\n";
</code>```

to

```<code>Clipboard.SetText("\n");
richTextBox1.Paste();
</code>```

which is a pretty terrible solution but it works and I'm on a deadline :) I'm open to other suggestions that are less hacky!

Body:
I'm looking to programmatically convert a base64 string into an Image that I then insert into a richTextBox.

Right now I load the string into a stream and convert that into an Image. I then load that onto the Clipboard and attempt to paste. However, when I execute the code, nothing pastes into the richTextBox. After running the code, the image is properly set in my Clipboard and I am able to paste it manually into the richTextBox - it just doesn't seem to work programmatically.

Here's my code:

byte[] img_bytes = Convert.FromBase64String(imgStr);
using (var ms = new MemoryStream(img_bytes, 0, img_bytes.Length))
{
    Image img = Image.FromStream(ms, true);
    Bitmap imgb = (Bitmap)Bitmap.FromStream(ms);
    Clipboard.SetDataObject(img);
    Console.WriteLine(Clipboard.ContainsImage()); // Prints True
    richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
    Console.WriteLine(richTextBox1.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap))); // Prints True
    richTextBox1.Text += "\n";
}

Update: It appears that setting the text field after pasting the image deletes the image. I guess the question now is, how do I have both the image and the text?

Body:
It appears that setting a richTextBox's text attribute after pasting was deleting the image. I changed the line

richTextBox1.Text += "\n";

to

Clipboard.SetText("\n");
richTextBox1.Paste();

which is a pretty terrible solution but it works and I'm on a deadline :) I'm open to other suggestions that are less hacky!


问:
Shortening Really long Client ids
I'mm getting really long client ids one such example is below. Some of them are about 100 characters long which is ridiculous.
Is there anything or any tool i can use that will shorten the pages ids?

id="ctl00_ctl00_MainContent_MemberMain_Abc_asdsad...._DlSAdasdasdasd_ctl00_PnsadasdasdnsHF"

EDIT:
I am nesting a lot which is the cause of the problem.
I am using  .net 3.5. and collisions are not ok as some of the ids are being used by javascript funcitons

答: The INamingContainer interface is probably what you are looking for. Implement it on surrounding controls.

ContentLicense: CC BY-SA 2.5

Title: Shortening Really long Client ids


问:
How to create message box when a value changes in a range based off a formula on a different worksheet
I am trying to create a message box automatically when a cell on a separate worksheet equals 0 in column J.

The values in column J are calculated using a formula based off input values.

I tried using the intersection function and cannot get it to work when operating in a range that is not a specific cell.

答: Worksheet_Change events only fire when a value is entered into a cell, not when a formula recalculates the value of a cell. You will need to hook the event to the data entry cell, then use code to check the values in column J for zeros.</p>


问:
C# Update or insert from a List by some criteria
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}
```

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?

答:
```<code>var comparators = prodcrm.Select(i => i.VEHI_SERIE).ToList();
foreach (var rep in prodrep)
{
  if (comparators.Contains(rep.VEHI_SERIE)
    // do something
  else
    // do something else
}
</code>```

Body:
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?


问:
GDB: redirect target stdout temporarly
When I launch GDB the targeted process prints a lot of data so I want to redirect it to NULL until a certain point in time.

the only two methods i've found so far are:

run > filename

tty filename

the problem is i cannot find a way to restore the stdout of the inferior back to normal.

there is no "tty default", or "default tty"

Thanks,

Itay

答:
Elaborating on Employed Russian's solution, I have written a standalone GDB-python script which will toggle redirection to and from stdout and the active terminal (TTY). As it stands, the script is ineffective if the program output isn't redirected to begin with (run > /dev/null).

To activate the script, use the source command:

```<code>(gdb) b 10
Breakpoint 1 at 0x5555555547a8: file gdbtest.c, line 10.
(gdb) run > /dev/null
Starting program: /home/gdbtest > /dev/null

Breakpoint 1, main () at gdbtest.c:10
10    printf("An important line\n");
(gdb) list
5
6     setbuf(stdout, NULL);
7     for (i = 0; i < 1000; ++i) {
8       printf("A line we don't care about: %d\n", i);
9     }
10    printf("An important line\n");
11    for (i = 0; i < 1000; ++i) {
12      printf("A line we don't care about: %d\n", i);
13    }
14    //fflush(stdout);
(gdb) source redir-stdout.py
(gdb) redir-stdout
Inferior PID: 20749
Redirecting stdout (fd:4) to TTY (fd:3)
(gdb) n
An important line
11    for (i = 0; i < 1000; ++i) {
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb) n
A line we don't care about: 0
11    for (i = 0; i < 1000; ++i) {
(gdb) redir-stdout
Inferior PID: 20749
Redirecting TTY (fd:3) back to stdout (fd:4)
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb) n
11    for (i = 0; i < 1000; ++i) {
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb)
</code>```

Here is the script (which I named redir-stdout.py):

import gdb

class RedirectStdout(gdb.Command):
    def __init__(self):
        super(RedirectStdout, self).__init__("redir-stdout", gdb.COMMAND_USER)
        self.tty = None
        self.stdout = None
        self.redir = False
        gdb.events.exited.connect(self.exit_handler)

    def invoke(self, arg, from_tty):
        print("Inferior PID: %s" % gdb.selected_inferior().pid)
        if(gdb.selected_inferior().pid == 0):
            raise gdb.GdbError ("Error: must have an active debuggee")

        out = gdb.execute("call fflush(0)", to_string=True)
        if(self.tty is None):
            # or just /dev/tty, as shown (the 1 means WRONLY)
            out = gdb.execute("p open(\"/dev/tty\", 1)", to_string=True)
            self.tty = out.split('=')[-1].strip()

        if(self.stdout is None):
            out = gdb.execute("p open(\"/proc/self/fd/1\", 1)", to_string=True)
            self.stdout = out.split('=')[-1].strip()

        if(not self.redir):
            print("Redirecting stdout (fd:{}) to TTY (fd:{})".format(self.stdout, self.tty))
            out = gdb.execute("call dup2({}, 1)".format(self.tty), to_string=True)
            ret = out.split('=')[-1].strip()
            #print("dup2 returns: " + ret)
            self.redir = True
        else:
            print("Redirecting TTY (fd:{}) back to stdout (fd:{})".format(self.tty, self.stdout))
            out = gdb.execute("call dup2({}, 1)".format(self.stdout), to_string=True)
            ret = out.split('=')[-1].strip()
            #print("dup2 returns: " + ret)
            self.redir = False

    def exit_handler(self, event):
        self.tty = None
        self.stdout = None
        self.redir = False

instance = RedirectStdout()

def exit_handler (event):
    print("Exit event received")
    instance.exit_handler(event)
```

Note: the script is easily sourced from your local .gdbinit in either the current working directory or your home directory.

Title: GDB: redirect target stdout temporarly

Body:
Elaborating on Employed Russian's solution, I have written a standalone GDB-python script which will toggle redirection to and from stdout and the active terminal (TTY). As it stands, the script is ineffective if the program output isn't redirected to begin with (run > /dev/null).

To activate the script, use the source command:

(gdb) b 10
Breakpoint 1 at 0x5555555547a8: file gdbtest.c, line 10.
(gdb) run > /dev/null
Starting program: /home/gdbtest > /dev/null

Breakpoint 1, main () at gdbtest.c:10
10    printf("An important line\n");
(gdb) list
5
6     setbuf(stdout, NULL);
7     for (i = 0; i < 1000; ++i) {
8       printf("A line we don't care about: %d\n", i);
9     }
10    printf("An important line\n");
11    for (i = 0; i < 1000; ++i) {
12      printf("A line we don't care about: %d\n", i);
13    }
14    //fflush(stdout);
(gdb) source redir-stdout.py
(gdb) redir-stdout
Inferior PID: 20749
Redirecting stdout (fd:4) to TTY (fd:3)
(gdb) n
An important line
11    for (i = 0; i < 1000; ++i) {
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb) n
A line we don't care about: 0
11    for (i = 0; i < 1000; ++i) {
(gdb) redir-stdout
Inferior PID: 20749
Redirecting TTY (fd:3) back to stdout (fd:4)
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb) n
11    for (i = 0; i < 1000; ++i) {
(gdb) n
12      printf("A line we don't care about: %d\n", i);
(gdb)

Here is the script (which I named redir-stdout.py):

import gdb

class RedirectStdout(gdb.Command):
    def __init__(self):
        super(RedirectStdout, self).__init__("redir-stdout", gdb.COMMAND_USER)
        self.tty = None
        self.stdout = None
        self.redir = False
        gdb.events.exited.connect(self.exit_handler)

    def invoke(self, arg, from_tty):
        print("Inferior PID: %s" % gdb.selected_inferior().pid)
        if(gdb.selected_inferior().pid == 0):
            raise gdb.GdbError ("Error: must have an active debuggee")

        out = gdb.execute("call fflush(0)", to_string=True)
        if(self.tty is None):
            # or just /dev/tty, as shown (the 1 means WRONLY)
            out = gdb.execute("p open(\"/dev/tty\", 1)", to_string=True)
            self.tty = out.split('=')[-1].strip()

        if(self.stdout is None):
            out = gdb.execute("p open(\"/proc/self/fd/1\", 1)", to_string=True)
            self.stdout = out.split('=')[-1].strip()

        if(not self.redir):
            print("Redirecting stdout (fd:{}) to TTY (fd:{})".format(self.stdout, self.tty))
            out = gdb.execute("call dup2({}, 1)".format(self.tty), to_string=True)
            ret = out.split('=')[-1].strip()
            #print("dup2 returns: " + ret)
            self.redir = True
        else:
            print("Redirecting TTY (fd:{}) back to stdout (fd:{})".format(self.tty, self.stdout))
            out = gdb.execute("call dup2({}, 1)".format(self.stdout), to_string=True)
            ret = out.split('=')[-1].strip()
            #print("dup2 returns: " + ret)
            self.redir = False

    def exit_handler(self, event):
        self.tty = None
        self.stdout = None
        self.redir = False

instance = RedirectStdout()

def exit_handler (event):
    print("Exit event received")
    instance.exit_handler(event)

Note: the script is easily sourced from your local .gdbinit in either the current working directory or your home directory.

ContentLicense: CC BY-SA 4.0


问:
What damage can still be done via a reflected XSS through a POST request when cookies are secure and HttpOnly?
I'm looking at a web site that has a verified reflected XSS vulnerability in a POST operation.  I'm not sure what kind of exploit an attacker could do here.

Cookies are all marked as secure and HttpOnly, so malicious JavaScript can't steal them.

The vulnerability only shows when a POST request is done, not a GET, so the vulnerability couldn't easily be used for phishing by making a URL that starts with a legit domain.

Using it to hijack the web browser to forward it to a malicious site seems unnecessary you'd have to visit a malicious site that had HTML or JavaScript code to make the browser submit the POST to the website.

What am I missing?  Could this vulnerability still be used for nefarious purposes?

答:
XSS is when an attacker can craft a request from outside of your site, GET or POST, and inject his own content into your page.  XSS is possible whenever data from a request is used in a response unescaped.

What can the attacker do once XSS is achieved?  You should consider the answer to be 'anything'.

My go-to example is often this:

The attacker injects code to replace whatever the page is with your login page, and they got it perfect, your user cannot tell the difference.  But the 'fake' login page sends the user's username and password to the attacker, and also logs the user in so they wouldn't even realise it was fake.


答: If using ASP .NET 4, you can set ClientIDMode to Static. Then you just have to make sure yourself that control ids in the hierarchy is unique. See this.</p>

Title: Shortening Really long Client ids

Body:
I'mm getting really long client ids one such example is below. Some of them are about 100 characters long which is ridiculous.
Is there anything or any tool i can use that will shorten the pages ids?

id="ctl00_ctl00_MainContent_MemberMain_Abc_asdsad...._DlSAdasdasdasd_ctl00_PnsadasdasdnsHF"

EDIT:
I am nesting a lot which is the cause of the problem.
I am using  .net 3.5. and collisions are not ok as some of the ids are being used by javascript funcitons


问:
conditional evaluation in TensorFlow graph
This can be done with tf.cond, however it will update both branches of the graph, from the manual:

Note that the conditional execution applies only to the operations
  defined in true_fn and false_fn. Consider the following simple
  program:

```<code>z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
</code>```

If x < y, the tf.add operation will be executed and tf.square
  operation will not be executed. Since z is needed for at least one
  branch of the cond, the tf.multiply operation is always executed,
  unconditionally.

How can I implement this such that tf.multiply is executed conditionally (i.e. only when x > Y)?

More specifically, what I'm trying to do:

```<code>var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
update_var1 = tf.assign(var1,var1 +1)
training = tf.placeholder(tf.bool)

def f1():
  with tf.control_dependencies([update_var1]):
    return var1*1.1

def f2():
  return var1 * 1.1

final = tf.cond(training, f1, f2)
sess.run(final, feed_dict={training:False})
</code>```

This will increase var1 with 1 each time you evaluate final, regardless the value of training, and the problem lays in tf.cond, because manually it works:

```<code>var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
update_var1 = tf.assign(var1,var1 +1)
training = tf.placeholder(tf.bool)

with tf.control_dependencies([update_var1]):
  f1 = var1 * 1.1

f2 = var1 * 1.1

sess.run(f1)
>> array([1.1,1.1,1.1,1.1])
sess.run(f1)
>> array([2.2,2.2,2.2,2.2])
# var1 gets updated every call
sess.run(f2)
>> array([2.2,2.2,2.2,2.2])
sess.run(f2)
>> array([2.2,2.2,2.2,2.2])
# var1 does not get updated
</code>```

答:
The general solution is as follows: move the code that you want to execute conditionally into the body of the lambda (or—in general—the callable object) for the appropriate branch of the tf.cond(). For example, to ensure that tf.multiply(a, b) only executes when x < y, you move it into the true_fn lambda:

```<code>result = tf.cond(x < y, lambda: tf.add(x, tf.multiply(a, b)), lambda: tf.square(y))
</code>```

The same principle can be applied to variable update ops, such as tf.assign(). The important detail is that you must create the tf.assign() op inside the body of the function used for one of the branches. Here's how you'd modify your second example:

```<code>var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
training = tf.placeholder(tf.bool)

def f1():
  with tf.control_dependencies([tf.assign(var1, var1 + 1)]):
    return var1 * 1.1

def f2():
  return var1 * 1.1

final = tf.cond(training, f1, f2)
sess.run(final, feed_dict={training: False})
</code>```

The control dependencies for the assignment are a little fiddly, so alternatively you could write f1() as:

```<code>def f1():
  return tf.assign(var1, var1 + 1) * 1.1
</code>```

...or put the whole thing on one line as:

```<code>final = tf.cond(training, lambda: tf.assign(var1, var1 + 1) * 1.1, lambda: var1 * 1.1)
</code>```

Body:
This can be done with tf.cond, however it will update both branches of the graph, from the manual:

Note that the conditional execution applies only to the operations
  defined in true_fn and false_fn. Consider the following simple
  program:

z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))

If x < y, the tf.add operation will be executed and tf.square
  operation will not be executed. Since z is needed for at least one
  branch of the cond, the tf.multiply operation is always executed,
  unconditionally.

How can I implement this such that tf.multiply is executed conditionally (i.e. only when x > Y)?

More specifically, what I'm trying to do:

var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
update_var1 = tf.assign(var1,var1 +1)
training = tf.placeholder(tf.bool)

def f1():
  with tf.control_dependencies([update_var1]):
    return var1*1.1

def f2():
  return var1 * 1.1

final = tf.cond(training, f1, f2)
sess.run(final, feed_dict={training:False})

This will increase var1 with 1 each time you evaluate final, regardless the value of training, and the problem lays in tf.cond, because manually it works:

var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
update_var1 = tf.assign(var1,var1 +1)
training = tf.placeholder(tf.bool)

with tf.control_dependencies([update_var1]):
  f1 = var1 * 1.1

f2 = var1 * 1.1

sess.run(f1)
>> array([1.1,1.1,1.1,1.1])
sess.run(f1)
>> array([2.2,2.2,2.2,2.2])
# var1 gets updated every call
sess.run(f2)
>> array([2.2,2.2,2.2,2.2])
sess.run(f2)
>> array([2.2,2.2,2.2,2.2])
# var1 does not get updated

Body:
The general solution is as follows: move the code that you want to execute conditionally into the body of the lambda (or—in general—the callable object) for the appropriate branch of the tf.cond(). For example, to ensure that tf.multiply(a, b) only executes when x < y, you move it into the true_fn lambda:

result = tf.cond(x < y, lambda: tf.add(x, tf.multiply(a, b)), lambda: tf.square(y))

The same principle can be applied to variable update ops, such as tf.assign(). The important detail is that you must create the tf.assign() op inside the body of the function used for one of the branches. Here's how you'd modify your second example:

var1 = tf.Variable(tf.zeros(4), trainable=False, name='var1')
training = tf.placeholder(tf.bool)

def f1():
  with tf.control_dependencies([tf.assign(var1, var1 + 1)]):
    return var1 * 1.1

def f2():
  return var1 * 1.1

final = tf.cond(training, f1, f2)
sess.run(final, feed_dict={training: False})

The control dependencies for the assignment are a little fiddly, so alternatively you could write f1() as:

def f1():
  return tf.assign(var1, var1 + 1) * 1.1

...or put the whole thing on one line as:

final = tf.cond(training, lambda: tf.assign(var1, var1 + 1) * 1.1, lambda: var1 * 1.1)


问:
Access private members of a class instantiated using interface
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:

Interface:

```<code>class AInterface
{
public:
   virtual ~AInterface() = default;
   virtual void set(int a) = 0;
};
</code>```

Derived class A with friend class B:

```<code>class B;
class A : public AInterface
{
public:
   ~A() override {}
   void set(int a) override
   {
      mem = a;
   }
private:
   friend class B;

   int mem = 0;
};
</code>```

class B:

```<code>class B
{
public:
   B()
   {
     a = new A();
     a->set(3);
   }

   int get_a()
   {
      // Access mem since it's a friend class
      return a->mem;
   }

private:
    AInterface *a;
}
</code>```

main:

```<code>int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}
</code>```

The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?

答:
Now work

```<code>#include <iostream>
using namespace std;

class AInterface
{
public:
    virtual ~AInterface() = default;
    int getMem() { return mem; }
    virtual void set(int a) = 0;
protected:
    int mem = 0;
};

class A : public AInterface
{
public:
    ~A() override {}
    void set(int a) override
    {
        mem = a;
    }

};

class B
{
public:
    B()
    {
         a = new A{};
        a->set(3);
    }

    int get_a()
    {
        // Access mem since it's a friend class
        return a->getMem();
    }

private:
    AInterface *a;
};
int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}
</code>```

Method which is override by child and is pure, should be virtual.

If each class (child) Interface, variable int mem should be protected in interface.
Now works fine, like you want.

Add getter getMem()

Version with friend

```<code>#include <iostream>
using namespace std;

class AInterface
{
public:
    virtual ~AInterface() = default;
    virtual void set(int a) = 0;
protected:
    friend class B;
    int mem = 0;
};

class A : public AInterface
{
public:
    ~A() override {}
    void set(int a) override
    {
        mem = a;
    }

};

class B
{
public:
    B()
    {
         a = new A{};
        a->set(3);
    }

    int get_a()
    {
        // Access mem since it's a friend class
        return a->mem;
    }

private:
    AInterface *a;
};
int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}
</code>```

Body:
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:

Interface:

class AInterface
{
public:
   virtual ~AInterface() = default;
   virtual void set(int a) = 0;
};

Derived class A with friend class B:

class B;
class A : public AInterface
{
public:
   ~A() override {}
   void set(int a) override
   {
      mem = a;
   }
private:
   friend class B;

   int mem = 0;
};

class B:

class B
{
public:
   B()
   {
     a = new A();
     a->set(3);
   }

   int get_a()
   {
      // Access mem since it's a friend class
      return a->mem;
   }

private:
    AInterface *a;
}

main:

int main()
{
    B *b = new B();
    std::cout <get_a() << std::endl;
    return 0;
}

The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?

Body:
Now work

#include <iostream>
using namespace std;

class AInterface
{
public:
    virtual ~AInterface() = default;
    int getMem() { return mem; }
    virtual void set(int a) = 0;
protected:
    int mem = 0;
};

class A : public AInterface
{
public:
    ~A() override {}
    void set(int a) override
    {
        mem = a;
    }

};

class B
{
public:
    B()
    {
         a = new A{};
        a->set(3);
    }

    int get_a()
    {
        // Access mem since it's a friend class
        return a->getMem();
    }

private:
    AInterface *a;
};
int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}

Method which is override by child and is pure, should be virtual.

If each class (child) Interface, variable int mem should be protected in interface.
Now works fine, like you want.

Add getter getMem()

Version with friend

#include <iostream>
using namespace std;

class AInterface
{
public:
    virtual ~AInterface() = default;
    virtual void set(int a) = 0;
protected:
    friend class B;
    int mem = 0;
};

class A : public AInterface
{
public:
    ~A() override {}
    void set(int a) override
    {
        mem = a;
    }

};

class B
{
public:
    B()
    {
         a = new A{};
        a->set(3);
    }

    int get_a()
    {
        // Access mem since it's a friend class
        return a->mem;
    }

private:
    AInterface *a;
};
int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}


问:
Why isn't the map fragment shown?
So I'm trying to do a simple Application with a Google Maps Fragment in it. I started from a preset out of Android-Studio. Since newly, the toolbar is shown but not the map fragment. Following, you will see my code and the Stack Trace:

activity_maps.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="1080dp"
    android:layout_height="1920dp"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="1720dp"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"

        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</RelativeLayout>
</code>```

MapsActivity.java

```<code>package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    }

}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingmapingmarker23">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=" AIz...." />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Stack Trace

```<code>/com.example.testingmapingmarker23 W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000023/n/armeabi-v7a
07-05 23:22:08.294 21301-21845/com.example.testingmapingmarker23 W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000023/n/armeabi
07-05 23:22:08.296 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.298 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.298 21301-21849/com.example.testingmapingmarker23 E/GLConsumer: [SurfaceTexture-0-21301-0] bindTextureImage: error binding external image: 0x501
07-05 23:22:08.343 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.345 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
</code>```

And this repeats over and over. I'm using a OnePlus One with Android 6.0.1 and shown API 23. The App runs, but it doesn't show the map fragment.

答:
For Layout:

If you are using your custom Toolbar, better change your style to
NoActionBar.

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

Using relative layout,
 for toolbar, keep

```<code>android:layout_alignParentTop="true"
</code>```

and for that map fragment

```<code> android:layout_below="@+id/toolbar"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
</code>```

This will simply place  your toolbar at the top and below part as map fragment.

Now for the Map not showing:

Have you put the Google Play Services dependency in your app??

Also add this to your manifest file just above your permissions.

```<code> <permission
        android:name="your_package_name.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
</code>```

Sorry, I couldn't comment so posted an answer.

Hope it helps !!

Title: Why isn't the map fragment shown?

Body:
So I'm trying to do a simple Application with a Google Maps Fragment in it. I started from a preset out of Android-Studio. Since newly, the toolbar is shown but not the map fragment. Following, you will see my code and the Stack Trace:

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="1080dp"
    android:layout_height="1920dp"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="1720dp"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"

        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</RelativeLayout>

MapsActivity.java

package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingmapingmarker23">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=" AIz...." />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Stack Trace

/com.example.testingmapingmarker23 W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000023/n/armeabi-v7a
07-05 23:22:08.294 21301-21845/com.example.testingmapingmarker23 W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000023/n/armeabi
07-05 23:22:08.296 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.298 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.298 21301-21849/com.example.testingmapingmarker23 E/GLConsumer: [SurfaceTexture-0-21301-0] bindTextureImage: error binding external image: 0x501
07-05 23:22:08.343 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE
07-05 23:22:08.345 21301-21849/com.example.testingmapingmarker23 W/Adreno-ES20: <core_glEGLImageTargetTexture2DOES:4548>: GL_INVALID_VALUE

And this repeats over and over. I'm using a OnePlus One with Android 6.0.1 and shown API 23. The App runs, but it doesn't show the map fragment.

Body:
For Layout:

If you are using your custom Toolbar, better change your style to
NoActionBar.

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

Using relative layout,
 for toolbar, keep

android:layout_alignParentTop="true"

and for that map fragment

 android:layout_below="@+id/toolbar"
 android:layout_width="match_parent"
 android:layout_height="match_parent"

This will simply place  your toolbar at the top and below part as map fragment.

Now for the Map not showing:

Have you put the Google Play Services dependency in your app??

Also add this to your manifest file just above your permissions.

 <permission
        android:name="your_package_name.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

Sorry, I couldn't comment so posted an answer.

Hope it helps !!


问:
Android Studios: Is it possible to filter json data based on user location?
I am trying to develop an app which suggests places to eat based on the users location and the price of individual meals within those restaurants. I'm not quite sure how to go about doing this - I've considered using the Google Places API but that does not contain price information on individual meals. The other option is to construct my own database.

What is easiest method to filter data based on both location and my own fields (eg meal prices)?

答:
first of all you can't filter json, you will filter where you will save data. you can do it by two ways :

you retrieve all the data from your database(advice use firebase easy to use) and filter the list or array or the RecyclerView where you save the data.

you send the conditions and retrieve the data to show them directly to your user


问:
sumif not adding up correctly

My SUMIF formula in B20 is returning a total value of $7.00 but it should be $13.00 because I am trying to add up the values in B14, B15, B16 and B17. It only seems to be capturing the value in B14. B13 is a drop down with two options, New Form and Old Form.

答:
This doesn't work like that.

In first argument you need to provide range of cells to provide value for criteria in second argument to check if value in cell from range in third argument had to be added to sum.

So, given data:

```<code>A       B
---------
a       7
a       2
a       2
</code>```

and formula in cell B4:

```<code>=SUMIF(A1:A3;"a";B1:B3)
</code>```

you'll get 11 in result.

given data:

```<code>A       B
---------
a       7
b       2
a       2
</code>```

you'll get 9 in result.

Title: sumif not adding up correctly

Body:
This doesn't work like that.

In first argument you need to provide range of cells to provide value for criteria in second argument to check if value in cell from range in third argument had to be added to sum.

So, given data:

A       B
---------
a       7
a       2
a       2

and formula in cell B4:

=SUMIF(A1:A3;"a";B1:B3)

you'll get 11 in result.

given data:

A       B
---------
a       7
b       2
a       2

you'll get 9 in result.


问:
Curl, Kerberos authenticated file copy on hadoop
We need to establish a filecopy at HDFS location, between HDFS folders. We currently have used curl command, as shown below, in a shell script loop.

```<code>/usr/bin/curl -v --negotiate -u : -X PUT "<hnode>:<port>/webhdfs/v1/busy/rg/stg/"$1"/"$table"/"$table"_"$3".dsv?op=RENAME&destination=/busy/rg/data/"$1"/"$table"/"$table"_$date1.dsv"
</code>```

However this achieves the file move. We need to establish a filecopy, such that file is maintained at the original staging location.

I Wanted to know if there is a corresponding curl operation? op=RENAME&destination instead of Rename, what else could work?

答:
WebHDFS alone does not offer a copy operation in its interface.  The WebHDFS interface provides lower-level file system primitives.  A copy operation is a higher-level application that uses those primitive operations to accomplish its work.

The implementation of hdfs dfs -cp against a webhdfs: URL essentially combines op=OPEN and op=CREATE calls to complete the copy.  You could potentially re-implement a subset of that logic in your script.  If you want to pursue that direction, the CopyCommands class is a good starting point in the Apache Hadoop codebase for seeing how that works.

Here is a starting point for how this could work.  There is an existing file at /hello1 that we want to copy to /hello2.  This script calls curl to open /hello1 and pipes the output to another curl command, which creates /hello2, using stdin as the input source.

```<code>> hdfs dfs -ls /hello*
-rw-r--r--   3 cnauroth supergroup          6 2017-07-06 09:15 /hello1

> curl -sS -L 'http://localhost:9870/webhdfs/v1/hello1?op=OPEN' |
>     curl -sS -L -X PUT -d @- 'http://localhost:9870/webhdfs/v1/hello2?op=CREATE&user.name=cnauroth'

> hdfs dfs -ls /hello*
-rw-r--r--   3 cnauroth supergroup          6 2017-07-06 09:15 /hello1
-rw-r--r--   3 cnauroth supergroup          5 2017-07-06 09:20 /hello2
</code>```

But my requirement is to connect from an external unix box, automated kerberos login into hdfs and then move the files within hdfs, hence the curl.

Another option could be a client-only Hadoop installation on your external host.  You would have an installation of the Hadoop software and the same configuration files from the Hadoop cluster, and then you could issue the hdfs dfs -cp commands instead of running curl commands against HDFS.

Body:
We need to establish a filecopy at HDFS location, between HDFS folders. We currently have used curl command, as shown below, in a shell script loop.

/usr/bin/curl -v --negotiate -u : -X PUT "<hnode>:<port>/webhdfs/v1/busy/rg/stg/"$1"/"$table"/"$table"_"$3".dsv?op=RENAME&destination=/busy/rg/data/"$1"/"$table"/"$table"_$date1.dsv"

However this achieves the file move. We need to establish a filecopy, such that file is maintained at the original staging location.

I Wanted to know if there is a corresponding curl operation? op=RENAME&destination instead of Rename, what else could work?

Body:
WebHDFS alone does not offer a copy operation in its interface.  The WebHDFS interface provides lower-level file system primitives.  A copy operation is a higher-level application that uses those primitive operations to accomplish its work.

The implementation of hdfs dfs -cp against a webhdfs: URL essentially combines op=OPEN and op=CREATE calls to complete the copy.  You could potentially re-implement a subset of that logic in your script.  If you want to pursue that direction, the CopyCommands class is a good starting point in the Apache Hadoop codebase for seeing how that works.

Here is a starting point for how this could work.  There is an existing file at /hello1 that we want to copy to /hello2.  This script calls curl to open /hello1 and pipes the output to another curl command, which creates /hello2, using stdin as the input source.

> hdfs dfs -ls /hello*
-rw-r--r--   3 cnauroth supergroup          6 2017-07-06 09:15 /hello1

> curl -sS -L 'http://localhost:9870/webhdfs/v1/hello1?op=OPEN' |
>     curl -sS -L -X PUT -d @- 'http://localhost:9870/webhdfs/v1/hello2?op=CREATE&user.name=cnauroth'

> hdfs dfs -ls /hello*
-rw-r--r--   3 cnauroth supergroup          6 2017-07-06 09:15 /hello1
-rw-r--r--   3 cnauroth supergroup          5 2017-07-06 09:20 /hello2

But my requirement is to connect from an external unix box, automated kerberos login into hdfs and then move the files within hdfs, hence the curl.

Another option could be a client-only Hadoop installation on your external host.  You would have an installation of the Hadoop software and the same configuration files from the Hadoop cluster, and then you could issue the hdfs dfs -cp commands instead of running curl commands against HDFS.


问:
Security Issue: How do I prevent firebase signInWithEmailAndPassword () usage?
The way I set up my signin, I am using firebase auth custom tokens. After 5 tries the account is locked. However there still exists a security flaw.

Suppose a hacker comes along an implements his own javascript file. All he has to do is implement firebase signInWithEmailAndPassword function and try as many email/password combination as he likes and eventually he will be able to get both the username and password. Then from there, sign into my normal system and I would never be able to detect that I was hacked.

I believe I have to implement some sort of firebase security rules for this issue, but I do not know where to start and how to guard the firebase users. Is there a way to stop someone from implementing that function?

I looked at firebase security rules and it shows how to protect the firebase database. But that doesnt work for my purpose. I need it to protect the firebase authentication users.

答:
The easiest and best solution is simply to disable all sign-in providers in the Firebase Console for your project. Custom auth is always enabled and can't be disabled.
You need to go to the "Authentication" section -> "SIGN-IN METHOD" -> "Sign-in provider".
https://firebase.corp.google.com/u/0/project/$PROJECT_ID/authentication/providers

If the user tries to create a password account, they will get an error operation-not-allowed.


问:
should an applet or an application catch Error exceptions?
should an applet or an application catch Error exceptions?

I think both can do it.

any help?

答:
No. Errors are runtime errors that are outside of your control (eg, OutOfMemoryError).

Errors are unchecked. You don't need to catch them or declare them, because they can happen at literally any point in your application. And, when they happen, it means that the sky is falling, and nothing you do will fix them.

In fact, in certain cases, you can't do anything safely at all. If the computer is out of memory, you likely can't even log it.

So, it's best not to worry about them.


问:
ListView replaces first object instead of adding a new one
I created a test project, and in that project I am trying to create a listview that the user can add to when they click a button. The button opens an new activity with an editText and another button to go back to the listview activity and an item should have been added. It works the first time, but when I add another Item it replaces the old one. I have search for a while now, and all the other answer don't seem to help me. Thanks in advance.

```<code>public class MainActivity extends Activity {

ListView simpleList;
String input;
ArrayList<Item> listItems =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    simpleList = (ListView) findViewById(R.id.listView);
    addData();
    MyAdapter myAdapter=new MyAdapter(this,R.layout.row, listItems);
    simpleList.setAdapter(myAdapter);
}

public void addData(){
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        input = extras.getString("Homework");
        listItems.add(new Item(input, input, input));
    }
}

public void toInput(View view){
    Intent intent = new Intent(this, inputScreen.class);
    startActivity(intent);
}}
</code>```

This is my main activity, the adapter is a custom adapter that is made in this class.

```<code>public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> listItems = new ArrayList<>();

public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
    super(context, textViewResourceId, objects);
    listItems = objects;
}

public int getCount(){
    return super.getCount();
}

public View getView(int position, View convertView, ViewGroup parent){
    View v = convertView;
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.row, null);
    TextView textView = (TextView) v.findViewById(R.id.homeworkDisplay);
    TextView textView2 = (TextView) v.findViewById(R.id.dueDisplay);
    TextView textView3 = (TextView) v.findViewById(R.id.classDisplay);
    textView.setText(listItems.get(position).getHomework());
    textView2.setText(listItems.get(position).getDate());
    textView3.setText(listItems.get(position).getClasses());
    return v;
}}
</code>```

The string that is added to the listview is sent from the another activity that gets it from an editText, here is it's class

```<code>public class inputScreen extends Activity{

EditText userInput;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input_screen);
    userInput = (EditText) findViewById(R.id.editText);

}

public void sendInfo(View view){
    Intent goingBack = new Intent(this,MainActivity.class);
    goingBack.putExtra("Homework", userInput.getText().toString());
    startActivity(goingBack);

}}
</code>```

I know there is alot of code there, you don't need to go through it all as I am sure the problem is in MainActivity. I have another class called items that returns homework. Thank you!

答:
Written by: https://stackoverflow.com/users/2936153/rohit5k2

Source: Listview replaces first item instead of creating new items

Every time you call changeText() your adapter is reset so only one
  item will be displayed

Change your fragment like this

```<code>public class ListViewFragment1 extends Fragment {

protected ArrayAdapter<String> adapter1;
ListView list1;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.list_view_fragment1, container, false);
    adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);
    list1 = (ListView) view.findViewById(R.id.listview1);
    list1.setAdapter(adapter1);
    return view;
}

public void changeText(String data){
    adapter1.add(data);
    adapter1.notifyDataSetChanged();
}
}
</code>```

Body:
I created a test project, and in that project I am trying to create a listview that the user can add to when they click a button. The button opens an new activity with an editText and another button to go back to the listview activity and an item should have been added. It works the first time, but when I add another Item it replaces the old one. I have search for a while now, and all the other answer don't seem to help me. Thanks in advance.

public class MainActivity extends Activity {

ListView simpleList;
String input;
ArrayList<Item> listItems =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    simpleList = (ListView) findViewById(R.id.listView);
    addData();
    MyAdapter myAdapter=new MyAdapter(this,R.layout.row, listItems);
    simpleList.setAdapter(myAdapter);
}

public void addData(){
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        input = extras.getString("Homework");
        listItems.add(new Item(input, input, input));
    }
}

public void toInput(View view){
    Intent intent = new Intent(this, inputScreen.class);
    startActivity(intent);
}}

This is my main activity, the adapter is a custom adapter that is made in this class.

public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> listItems = new ArrayList<>();

public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
    super(context, textViewResourceId, objects);
    listItems = objects;
}

public int getCount(){
    return super.getCount();
}

public View getView(int position, View convertView, ViewGroup parent){
    View v = convertView;
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.row, null);
    TextView textView = (TextView) v.findViewById(R.id.homeworkDisplay);
    TextView textView2 = (TextView) v.findViewById(R.id.dueDisplay);
    TextView textView3 = (TextView) v.findViewById(R.id.classDisplay);
    textView.setText(listItems.get(position).getHomework());
    textView2.setText(listItems.get(position).getDate());
    textView3.setText(listItems.get(position).getClasses());
    return v;
}}

The string that is added to the listview is sent from the another activity that gets it from an editText, here is it's class

public class inputScreen extends Activity{

EditText userInput;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input_screen);
    userInput = (EditText) findViewById(R.id.editText);

}

public void sendInfo(View view){
    Intent goingBack = new Intent(this,MainActivity.class);
    goingBack.putExtra("Homework", userInput.getText().toString());
    startActivity(goingBack);

}}

I know there is alot of code there, you don't need to go through it all as I am sure the problem is in MainActivity. I have another class called items that returns homework. Thank you!

Body:
Written by: https://stackoverflow.com/users/2936153/rohit5k2

Source: Listview replaces first item instead of creating new items

Every time you call changeText() your adapter is reset so only one
  item will be displayed

Change your fragment like this

public class ListViewFragment1 extends Fragment {

protected ArrayAdapter<String> adapter1;
ListView list1;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.list_view_fragment1, container, false);
    adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);
    list1 = (ListView) view.findViewById(R.id.listview1);
    list1.setAdapter(adapter1);
    return view;
}

public void changeText(String data){
    adapter1.add(data);
    adapter1.notifyDataSetChanged();
}
}


问:
Is there a way to stop/disable a Google Cloud Function?
I have running multiple Google Cloud functions. One is not operating well, so I want to stop them until I've fixed the situation.

I have seen that I can remove the function, but is there a way to disable and later; enable the function?

答: I am not sure if this is late but what I did is that I deleted/commented the function I don't need and deployed again using firebase deploy --only functions . Once run, it shows that the function is being deleted. Hope this helpsGCF Deployment</p>


问:
SQL join subquery where condition
How can I effectively subquery a LEFT OUTER JOIN so that only rows that meet a specific condition in the join are included?

I'd like to only count PPPD's where converted_at IS NULL. However when I add PPPD.converted_at IS NULL, then the result is more limited than I'd like it to be because it only includes patient_profiles that do have a row with null in converted_at. Instead I'd like a count of all PPPD records that have converted_at = null

```<code>SELECT P.id, P.gender, P.dob,
count(distinct recommendations.id) AS recommendation_count,
count(distinct PPPD.id) AS community_submissions,
FROM patient_profiles AS P
LEFT OUTER JOIN recommendations ON recommendations.patient_profile_id = P.id
LEFT OUTER JOIN patient_profile_potential_doctors AS PPPD ON PPPD.patient_profile_id = P.id
WHERE P.is_test = FALSE
GROUP BY P.id
</code>```

答:
You need to add the condition in the ON clause:

```<code>SELECT P.id, P.gender, P.dob,
       count(distinct r.id) AS recommendation_count,
       count(distinct PPPD.id) AS community_submissions,
FROM patient_profiles  P LEFT OUTER JOIN
     recommendations r
     ON r.patient_profile_id = P.id LEFT OUTER JOIN
     patient_profile_potential_doctors PPPD
     ON PPPD.patient_profile_id = P.id AND PPPD.converted_at IS NULL
WHERE P.is_test = FALSE;
GROUP BY P.id
</code>```

Title: SQL join subquery where condition

Body:
How can I effectively subquery a LEFT OUTER JOIN so that only rows that meet a specific condition in the join are included?

I'd like to only count PPPD's where converted_at IS NULL. However when I add PPPD.converted_at IS NULL, then the result is more limited than I'd like it to be because it only includes patient_profiles that do have a row with null in converted_at. Instead I'd like a count of all PPPD records that have converted_at = null

SELECT P.id, P.gender, P.dob,
count(distinct recommendations.id) AS recommendation_count,
count(distinct PPPD.id) AS community_submissions,
FROM patient_profiles AS P
LEFT OUTER JOIN recommendations ON recommendations.patient_profile_id = P.id
LEFT OUTER JOIN patient_profile_potential_doctors AS PPPD ON PPPD.patient_profile_id = P.id
WHERE P.is_test = FALSE
GROUP BY P.id

Body:
You need to add the condition in the ON clause:

SELECT P.id, P.gender, P.dob,
       count(distinct r.id) AS recommendation_count,
       count(distinct PPPD.id) AS community_submissions,
FROM patient_profiles  P LEFT OUTER JOIN
     recommendations r
     ON r.patient_profile_id = P.id LEFT OUTER JOIN
     patient_profile_potential_doctors PPPD
     ON PPPD.patient_profile_id = P.id AND PPPD.converted_at IS NULL
WHERE P.is_test = FALSE;
GROUP BY P.id


问:
Server action never invoked - JSON deserialization failure?
I have simple action in my controller:

```<code>[HttpPost]
public JsonResult Action(MenuSet menuSet)
{
   //...
}
</code>```

where MenuSet is:

```<code>public class MenuSet
{
    private IEnumerable<MenuEntry> _menuEntries;

    public IEnumerable<MenuEntry> MenuEntries
    {
        get { return _menuEntries; }
        set { _menuEntries = value; }
    }
}

public class MenuEntry
{
    private string _parentPageName;
    private IEnumerable<string> _orderedPages;

    public string ParentPageName
    {
        get { return _parentPageName; }
        set { _parentPageName = value; }
    }
    public IEnumerable<string> OrderedPages
    {
        get { return _orderedPages; }
        set { _orderedPages = value; }
    }
}
</code>```

From the client side, I'm invoking this action in the way below:

```<code>$.post("Controller/Action",
       $.param({ MenuEntries: prepareData() }, true),
       null,
       "json");
</code>```

where prepareData() function returns MenuEntries collection:

```<code>function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: null,
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    return menuEntries;
}

function getPagesOrder() {
    var values = new Array();
    values.push('samplePageName')
    return values;
}
</code>```

But the JSON object appears to be not deserialized to the model at the server side - the controller action is never invoked. How to make this work ?

答:
Jarek,

it works fine if you use $ajax, rather than $post. I've added a button to a my index.aspx page as so:

```<code><input type="button" id="btnGo" value="Go" />
</code>```

also, add a new javascript file and paste the following into it (save it as /scripts/toJson.js):

```<code>//Source: http://www.overset.com/2008/04/11/mark-gibsons-json-jquery-updated/
(function($) {
  m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"': '\\"',
    '\\': '\\\\'
},
$.toJSON = function(value, whitelist) {
    var a,          // The array holding the partial texts.
        i,          // The loop counter.
        k,          // The member key.
        l,          // Length.
        r = /["\\\x00-\x1f\x7f-\x9f]/g,
        v;          // The member value.

    switch (typeof value) {
        case 'string':
            return r.test(value) ?
            '"' + value.replace(r, function(a) {
                var c = m[a];
                if (c) {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"' :
            '"' + value + '"';

        case 'number':
            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':
            return String(value);

        case 'object':
            if (!value) {
                return 'null';
            }
            if (typeof value.toJSON === 'function') {
                return $.toJSON(value.toJSON());
            }
            a = [];
            if (typeof value.length === 'number' &&
                !(value.propertyIsEnumerable('length'))) {
                l = value.length;
                for (i = 0; i < l; i += 1) {
                    a.push($.toJSON(value[i], whitelist) || 'null');
                }
                return '[' + a.join(',') + ']';
            }
            if (whitelist) {
                l = whitelist.length;
                for (i = 0; i < l; i += 1) {
                    k = whitelist[i];
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            }
            return '{' + a.join(',') + '}';
    }
};

})(jQuery);
</code>```

reference this new file in your index.aspx

```<code><script src= "/scripts/toJson.js" type="text/javascript"></script>
</code>```

and replaced the $post javascript with:

```<code>$(document).ready(function() {
    $('#btnGo').click(function() {
        $.ajax({
            type: "POST",
            url: '<%=Url.Content("~/Home/Action") %>',
            dataType: "json",
            data: { MenuEntries: prepareData() },
            success: function(msg) {
                alert(msg);
            },
            error: function(xhr) { alert(xhr.statusText); }
        });

    });
});

function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: "myPageName",
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    // this serialises the javascript array correctly
    return $.toJSON(menuEntries);
}
</code>```

try changing the action to the code below and try playing about with that (this gives you two options to examine the posted data):

```<code>[HttpPost]
public JsonResult Action(FormCollection formCollection)
{
    NameValueCollection test = HttpContext.Request.Form;
    // return Json(test[0]);
    return Json(formCollection[0]);
}
</code>```

it correctly deserialises inside the 'Action' action in the controller.

give it a try. i'm sure it's 'fixed'

[edit] - halfaway fixed... you'll need to work on how you play with the object. i.e. either via the formCollection or via the test varibale. both give the object in different guises.!!

Body:
I have simple action in my controller:

[HttpPost]
public JsonResult Action(MenuSet menuSet)
{
   //...
}

where MenuSet is:

public class MenuSet
{
    private IEnumerable<MenuEntry> _menuEntries;

    public IEnumerable<MenuEntry> MenuEntries
    {
        get { return _menuEntries; }
        set { _menuEntries = value; }
    }
}

public class MenuEntry
{
    private string _parentPageName;
    private IEnumerable<string> _orderedPages;

    public string ParentPageName
    {
        get { return _parentPageName; }
        set { _parentPageName = value; }
    }
    public IEnumerable<string> OrderedPages
    {
        get { return _orderedPages; }
        set { _orderedPages = value; }
    }
}

From the client side, I'm invoking this action in the way below:

$.post("Controller/Action",
       $.param({ MenuEntries: prepareData() }, true),
       null,
       "json");

where prepareData() function returns MenuEntries collection:

function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: null,
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    return menuEntries;
}

function getPagesOrder() {
    var values = new Array();
    values.push('samplePageName')
    return values;
}

But the JSON object appears to be not deserialized to the model at the server side - the controller action is never invoked. How to make this work ?

Body:
Jarek,

it works fine if you use $ajax, rather than $post. I've added a button to a my index.aspx page as so:

<input type="button" id="btnGo" value="Go" />

also, add a new javascript file and paste the following into it (save it as /scripts/toJson.js):

//Source: http://www.overset.com/2008/04/11/mark-gibsons-json-jquery-updated/
(function($) {
  m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"': '\\"',
    '\\': '\\\\'
},
$.toJSON = function(value, whitelist) {
    var a,          // The array holding the partial texts.
        i,          // The loop counter.
        k,          // The member key.
        l,          // Length.
        r = /["\\\x00-\x1f\x7f-\x9f]/g,
        v;          // The member value.

    switch (typeof value) {
        case 'string':
            return r.test(value) ?
            '"' + value.replace(r, function(a) {
                var c = m[a];
                if (c) {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"' :
            '"' + value + '"';

        case 'number':
            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':
            return String(value);

        case 'object':
            if (!value) {
                return 'null';
            }
            if (typeof value.toJSON === 'function') {
                return $.toJSON(value.toJSON());
            }
            a = [];
            if (typeof value.length === 'number' &&
                !(value.propertyIsEnumerable('length'))) {
                l = value.length;
                for (i = 0; i < l; i += 1) {
                    a.push($.toJSON(value[i], whitelist) || 'null');
                }
                return '[' + a.join(',') + ']';
            }
            if (whitelist) {
                l = whitelist.length;
                for (i = 0; i < l; i += 1) {
                    k = whitelist[i];
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (typeof k === 'string') {
                        v = $.toJSON(value[k], whitelist);
                        if (v) {
                            a.push($.toJSON(k) + ':' + v);
                        }
                    }
                }
            }
            return '{' + a.join(',') + '}';
    }
};

})(jQuery);

reference this new file in your index.aspx

<script src= "/scripts/toJson.js" type="text/javascript"></script>

and replaced the $post javascript with:

$(document).ready(function() {
    $('#btnGo').click(function() {
        $.ajax({
            type: "POST",
            url: '<%=Url.Content("~/Home/Action") %>',
            dataType: "json",
            data: { MenuEntries: prepareData() },
            success: function(msg) {
                alert(msg);
            },
            error: function(xhr) { alert(xhr.statusText); }
        });

    });
});

function prepareData() {
    var menuEntries = new Array();
    var menuEntry = {
        ParentPageName: "myPageName",
        OrderedPages: getPagesOrder()
    }
    menuEntries.push(menuEntry);
    // this serialises the javascript array correctly
    return $.toJSON(menuEntries);
}

try changing the action to the code below and try playing about with that (this gives you two options to examine the posted data):

[HttpPost]
public JsonResult Action(FormCollection formCollection)
{
    NameValueCollection test = HttpContext.Request.Form;
    // return Json(test[0]);
    return Json(formCollection[0]);
}

it correctly deserialises inside the 'Action' action in the controller.

give it a try. i'm sure it's 'fixed'

[edit] - halfaway fixed... you'll need to work on how you play with the object. i.e. either via the formCollection or via the test varibale. both give the object in different guises.!!


问:
How to check whether a string contains a substring in JavaScript?
Usually I would expect a String.contains() method, but there doesn't seem to be one.

What is a reasonable way to check for this?

答:
Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n⋅m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

```<code>// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
</code>```

function kmpSearch(pattern, text) {
  if (pattern.length == 0)
    return 0; // Immediate match

  // Compute longest suffix-prefix table
  var lsp = [0]; // Base case
  for (var i = 1; i < pattern.length; i++) {
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
    while (j > 0 && pattern[i] !== pattern[j])
      j = lsp[j - 1];
    if (pattern[i] === pattern[j])
      j++;
    lsp.push(j);
  }

  // Walk through text string
  var j = 0; // Number of chars matched in pattern
  for (var i = 0; i < text.length; i++) {
    while (j > 0 && text[i] != pattern[j])
      j = lsp[j - 1]; // Fall back in the pattern
    if (text[i]  == pattern[j]) {
      j++; // Next char matched, increment position
      if (j == pattern.length)
        return i - (j - 1);
    }
  }
  return -1; // Not found
}

console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false```

Body:
Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n⋅m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

function kmpSearch(pattern, text) {
  if (pattern.length == 0)
    return 0; // Immediate match

  // Compute longest suffix-prefix table
  var lsp = [0]; // Base case
  for (var i = 1; i < pattern.length; i++) {
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
    while (j > 0 && pattern[i] !== pattern[j])
      j = lsp[j - 1];
    if (pattern[i] === pattern[j])
      j++;
    lsp.push(j);
  }

  // Walk through text string
  var j = 0; // Number of chars matched in pattern
  for (var i = 0; i < text.length; i++) {
    while (j > 0 && text[i] != pattern[j])
      j = lsp[j - 1]; // Fall back in the pattern
    if (text[i]  == pattern[j]) {
      j++; // Next char matched, increment position
      if (j == pattern.length)
        return i - (j - 1);
    }
  }
  return -1; // Not found
}

console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false


问:
Listbox Microsoft Access 2016
How can I change the color of the selected item in the properties of the control? Currently, I have a listbox object which displays data from a query. When I click on a row it is highlighted black and the text becomes white. How can I change this black to another color.</p>

答: Not possible... directly. The selected color for the default ListBox control is the inverse of the Back Color property. This is true of the text color also. For example, try setting the Fore Color to Yellow and the Back Color to Blue. The resultant selected (a.k.a. highlighted) colors will be bluish text and yellow/orange backcolor.</p>

Title: Listbox Microsoft Access 2016