问:
'undefined reference to' when using GTK with CMake
I'm trying to build basic GTK+ code(one of its tutorials) with CMake, but I keep getting 'undefined reference to *' where * is any GTK function that is in the code. I tried to look after guides/tutorials on this, but most of them are mostly similar to what I have.

Regular compilation from terminal works without a problem using command:

```<code>g++ ./test.cpp -o test `pkg-config --cflags --libs gtk+-3.0`
</code>```

When I try using CMake my CMakeLists.txt is:

```<code>cmake_minimum_required(VERSION 3.0.2)
project(gtktest)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)

include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
add_definitions(${GTK3_CFLAGS_OTHER})

add_executable(gtktest test.cpp)
target_link_libraries(gtktest ${GKT3_LIBRARIES})
</code>```

Now cmake . seems to work without problems

```<code>cmake .
-- The C compiler identification is GNU 7.4.0
-- The CXX compiler identification is GNU 7.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'gtk+-3.0'
--   Found gtk+-3.0, version 3.22.30
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dfdark/Desktop/gtk test
</code>```

But make command after that is the problem:

```<code>make
Scanning dependencies of target gtktest
[ 50%] Building CXX object CMakeFiles/gtktest.dir/test.cpp.o
[100%] Linking CXX executable gtktest
CMakeFiles/gtktest.dir/test.cpp.o: In function `activate(_GtkApplication*, void*)':
test.cpp:(.text+0x27): undefined reference to `gtk_application_window_new'
test.cpp:(.text+0x30): undefined reference to `gtk_window_get_type'
test.cpp:(.text+0x42): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x51): undefined reference to `gtk_window_set_title'
test.cpp:(.text+0x56): undefined reference to `gtk_window_get_type'
test.cpp:(.text+0x68): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x7a): undefined reference to `gtk_window_set_default_size'
test.cpp:(.text+0x86): undefined reference to `gtk_widget_show_all'
CMakeFiles/gtktest.dir/test.cpp.o: In function `main':
test.cpp:(.text+0xcc): undefined reference to `gtk_application_new'
test.cpp:(.text+0xfb): undefined reference to `g_signal_connect_data'
test.cpp:(.text+0x100): undefined reference to `g_application_get_type'
test.cpp:(.text+0x112): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x126): undefined reference to `g_application_run'
test.cpp:(.text+0x135): undefined reference to `g_object_unref'
collect2: error: ld returned 1 exit status
CMakeFiles/gtktest.dir/build.make:94: recipe for target 'gtktest' failed
make[2]: *** [gtktest] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/gtktest.dir/all' failed
make[1]: *** [CMakeFiles/gtktest.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

test.cpp code (From GTK+ tutorials)

```<code>#include <gtk/gtk.h>

static void
activate (GtkApplication* app,
          gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}
</code>```

Is the problem messed up order of CMake's commands?

答:
Use GTK in your CMakeLists.txt instead of GTK3: </p>

```<code>cmake_minimum_required(VERSION 3.0.2)
project(gtktest)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED gtk+-3.0)

include_directories(${GTK_INCLUDE_DIRS})
link_directories(${GTK_LIBRARY_DIRS})
add_definitions(${GTK_CFLAGS_OTHER})

add_executable(gtktest test.cpp)
target_link_libraries(gtktest ${GTK_LIBRARIES})
</code>```

Body:
I'm trying to build basic GTK+ code(one of its tutorials) with CMake, but I keep getting 'undefined reference to *' where * is any GTK function that is in the code. I tried to look after guides/tutorials on this, but most of them are mostly similar to what I have.

Regular compilation from terminal works without a problem using command:

g++ ./test.cpp -o test `pkg-config --cflags --libs gtk+-3.0`

When I try using CMake my CMakeLists.txt is:

cmake_minimum_required(VERSION 3.0.2)
project(gtktest)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)

include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
add_definitions(${GTK3_CFLAGS_OTHER})

add_executable(gtktest test.cpp)
target_link_libraries(gtktest ${GKT3_LIBRARIES})

Now cmake . seems to work without problems

cmake .
-- The C compiler identification is GNU 7.4.0
-- The CXX compiler identification is GNU 7.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'gtk+-3.0'
--   Found gtk+-3.0, version 3.22.30
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dfdark/Desktop/gtk test

But make command after that is the problem:

make
Scanning dependencies of target gtktest
[ 50%] Building CXX object CMakeFiles/gtktest.dir/test.cpp.o
[100%] Linking CXX executable gtktest
CMakeFiles/gtktest.dir/test.cpp.o: In function `activate(_GtkApplication*, void*)':
test.cpp:(.text+0x27): undefined reference to `gtk_application_window_new'
test.cpp:(.text+0x30): undefined reference to `gtk_window_get_type'
test.cpp:(.text+0x42): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x51): undefined reference to `gtk_window_set_title'
test.cpp:(.text+0x56): undefined reference to `gtk_window_get_type'
test.cpp:(.text+0x68): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x7a): undefined reference to `gtk_window_set_default_size'
test.cpp:(.text+0x86): undefined reference to `gtk_widget_show_all'
CMakeFiles/gtktest.dir/test.cpp.o: In function `main':
test.cpp:(.text+0xcc): undefined reference to `gtk_application_new'
test.cpp:(.text+0xfb): undefined reference to `g_signal_connect_data'
test.cpp:(.text+0x100): undefined reference to `g_application_get_type'
test.cpp:(.text+0x112): undefined reference to `g_type_check_instance_cast'
test.cpp:(.text+0x126): undefined reference to `g_application_run'
test.cpp:(.text+0x135): undefined reference to `g_object_unref'
collect2: error: ld returned 1 exit status
CMakeFiles/gtktest.dir/build.make:94: recipe for target 'gtktest' failed
make[2]: *** [gtktest] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/gtktest.dir/all' failed
make[1]: *** [CMakeFiles/gtktest.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

test.cpp code (From GTK+ tutorials)

#include <gtk/gtk.h>

static void
activate (GtkApplication* app,
          gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

Is the problem messed up order of CMake's commands?

Body:
Use GTK in your CMakeLists.txt instead of GTK3:

cmake_minimum_required(VERSION 3.0.2)
project(gtktest)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED gtk+-3.0)

include_directories(${GTK_INCLUDE_DIRS})
link_directories(${GTK_LIBRARY_DIRS})
add_definitions(${GTK_CFLAGS_OTHER})

add_executable(gtktest test.cpp)
target_link_libraries(gtktest ${GTK_LIBRARIES})


来源: stackexchange

问:
How to remove the square brackets around a JSON in PHP
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

```<code>[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]
</code>```

What I would like:

```<code>{"id": 1,"name":"Jack","username":"Jack1","age":23}
</code>```

The following is the php script that returns the JSON:

```<code><?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);
</code>```

答:
The square brackets indicate that your variable originated from an array of objects, and is expected for translating it back to the original value.

However, you can use a combination of JSON_* constants for the options argument, such as JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK, to ensure your desired result from json_encode.

JSON_NUMERIC_CHECK will remove the double quotes from the numeric
values in your JSON string.

JSON_FORCE_OBJECT will convert all
arrays into objects.

To remove the square brackets, if your $resultArray variable is an array of objects, you will need to determine which value you want. Such as $resultArray[0] or end($resultArray) or reset($resultArray)

Example: https://3v4l.org/ip6GN

```<code>echo json_encode(reset($resultArray), JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
</code>```

Result:

```<code>{"id":1,"name":"Jack","username":"Jack1","age":23}
</code>```

However in this instance you are looking for a specific record in the database. Assuming there is only one, I suggest updating your query to leverage a prepared statement, to avoid SQL injection attacks.

Additionally I highly recommend hashing your passwords using the built in password_hash functions.

```<code>$sql = 'SELECT `id`, `username`, `name`, `age`
FROM `DriverInfo`
WHERE `username` = ?
AND `password` = ?
LIMIT 1';
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt, $sql)) {
    mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
    $username = $_POST['username'];
    $password = $_POST['password'];
    mysqli_stmt_execute($stmt);
    if ($result = mysqli_stmt_get_result($stmt)) {
       if ($row = mysqli_fetch_object($result)) {
           echo json_encode($row, JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
       }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($con);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]

What I would like:

{"id": 1,"name":"Jack","username":"Jack1","age":23}

The following is the php script that returns the JSON:

<?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);

Body:
The square brackets indicate that your variable originated from an array of objects, and is expected for translating it back to the original value.

However, you can use a combination of JSON_* constants for the options argument, such as JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK, to ensure your desired result from json_encode.

JSON_NUMERIC_CHECK will remove the double quotes from the numeric
values in your JSON string.

JSON_FORCE_OBJECT will convert all
arrays into objects.

To remove the square brackets, if your $resultArray variable is an array of objects, you will need to determine which value you want. Such as $resultArray[0] or end($resultArray) or reset($resultArray)

Example: https://3v4l.org/ip6GN

echo json_encode(reset($resultArray), JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);

Result:

{"id":1,"name":"Jack","username":"Jack1","age":23}

However in this instance you are looking for a specific record in the database. Assuming there is only one, I suggest updating your query to leverage a prepared statement, to avoid SQL injection attacks.

Additionally I highly recommend hashing your passwords using the built in password_hash functions.

$sql = 'SELECT `id`, `username`, `name`, `age`
FROM `DriverInfo`
WHERE `username` = ?
AND `password` = ?
LIMIT 1';
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt, $sql)) {
    mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
    $username = $_POST['username'];
    $password = $_POST['password'];
    mysqli_stmt_execute($stmt);
    if ($result = mysqli_stmt_get_result($stmt)) {
       if ($row = mysqli_fetch_object($result)) {
           echo json_encode($row, JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
       }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($con);


问:
How to remove a specific value from an array in JavaScript?
Suppose, i have an array

```<code>const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
</code>```

If i want to remove the value 3 from anArray but don't know the position of that value in the array, how can i remove that?

Note: I'm a beginner in JavaScript

答:
You can use filter

filter will give you a new array with values except value 3 this will remove all the value 3 if you want only first value 3 to be removed you can use splice as given in other answer

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];

const filtered = anArray.filter(val=> val !== 'value 3')

console.log(filtered)```

Body:
Suppose, i have an array

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];

If i want to remove the value 3 from anArray but don't know the position of that value in the array, how can i remove that?

Note: I'm a beginner in JavaScript


问:
How to combine two arrays of integers and return average?
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

```<code>public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }
</code>```

UnitTest:

```<code>[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }
</code>```

答:
You can do it with System.Linq

```<code>var saturday = new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 };
var sunday = new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 };

var average = saturday.Concat(sunday).DefaultIfEmpty(0).Average();
</code>```

Body:
Ok so I have two arrays of integers, and I have to return the average rating of the two days. This is the code that I have come up with thus far, but apparently it does not meet the expectations. Result:

Message:   Expected: 5.0d
    But was:  3.0d

Unit:

public double WeekendAverage(int[] saturday, int[] sunday)
    {
        int[] n = { saturday.Length, sunday.Length };
        int sum = 0;

        for (int i = 0; i < n.Length; i++)
        {
            sum = saturday[i] + sunday[i];
            return sum / n.Length;
        }
        return sum;
        }

UnitTest:

[TestCase(new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 }, new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 }, 7)]

public void WeekendAverage(int[] saturday, int[] sunday, double expected)
    {
        var actual = warmups.WeekendAverage(saturday, sunday);
        Assert.AreEqual(expected, actual);
    }

Body:
You can do it with System.Linq

var saturday = new[] { 1, 2, 3, 4, 5, 7, 8, 5, 10 };
var sunday = new[] { 9, 9, 9, 8, 9, 8, 9, 9, 9, 10, 10 };

var average = saturday.Concat(sunday).DefaultIfEmpty(0).Average();


问:
Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {$$typeof, render})

Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

```<code>class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header />
                    <Alerts />
                    <div className="container">
                        <Dashboard />
                    </div>
                </Fragment>
            </AlertProvider>
        </Provider>
    )
}
</code>```

Here is my Alerts.js component:

```<code>import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);
</code>```

The given error has seen in the console: Error in the console

答:
usually the error,

Uncaught Invariant Violation: Objects are not valid as a React child
  (found: object with keys {$$typeof, render})

throws when you don't,

render multiple nodes inside one single parent node(which is not in this case).

import files properly

if the second condition also passes, maybe should look into the docs of the component your'e using..

Body:
Error handling and alerts in React

When I bring the <Alert /> to the main app component just below the  tag, as soon as the component mounts it throws this error.

While I remove the <Alert /> from the main app component, it works fine.
This is how the browser renders properly before I brought the <Alert /> to the main app component,
 click here.

Here is the snippet of code that works earlier:

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

}

I expect to get the proper alert message snippets in the browser. However, nothing gets rendered in the browser after I tried to use the third party package called react-alert from this Github repository.

Below is the snippet of the code that failed with an error in the console.

class App extends Component {
render() {
    return (
        <Provider store={store}>
            <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>

                    <Alerts />

                        <Dashboard />

                </Fragment>
            </AlertProvider>
        </Provider>
    )
}

Here is my Alerts.js component:

import React, { Component, Fragment } from 'react';
import { withAlert } from 'react-alert';
export class Alerts extends Component {
    componentDidMount() {
        this.props.alert.show('It Works');
    }
    render() {
        return <Fragment />;
    }
}
export default withAlert(Alerts);

The given error has seen in the console: Error in the console


问:
How to use default csrf-token from AJAX request in Laravel
I'm using Vuejs and I want to make an secure AJAX request (with axios) to my laravel server, but I think that CSRF protections doesn't work because I change the token of the frontend part and even then I can interact with the database.

I read that Laravel come with a file named [bootstrap.js] (https://laravel.com/docs/5.8/csrf#csrf-introduction) it is assumed that this file does this task by default, but it doesn't work for me. I think it's beacuse webpack doens't load the file when I run npm run watch but I don't know how to load it,

I searched for an answer but I only find Bootstrap tutorials :/

答:
You can put the CSRF in the meta as _token. Like this:

<meta name="csrf-token" content="{{ csrf_token() }}">

Visit the laravel documentation for this.
https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token

And then access it in your javascript.


问:
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

```<code>class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};
</code>```

but when I write the derived class:

```<code>#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};
</code>```

I get this error:

```<code>invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’
</code>```

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

答:
You don't have to redefine the struct in TestSon, and you also can't do this. The caller of fatherptr->get_myStructVect statically gets a vector<TestFather::myStruct> back, so the compiler forbids you to override the base class function like that, because the dynamically returned object would potentially be incompatible with vector<TestFather::myStruct> (who knows what you put into TestSon::myStruct and how vector differs in behavior from the base class vector?).

As for the allowed difference, C++ only allows the derived class return type to be a derived class of the base class return type, and only when the return types are pointers or references.

ContentLicense: CC BY-SA 3.0

Body:
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

but when I write the derived class:

#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};

I get this error:

invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?


问:
Is There A Way to Get Notifications When Ambient Light Changes?
OK. I have an app that is designed to allow the user to reduce the screen brightness manually. It works great. I use the standard UIScreen calls to do that, in response to a slider.

I'd like to be able to leverage the ambient light sensor, if possible, but it seems that it is not.

All the feedback that I've seen so far, is that Apple locks up access to the sensor via a private API (meaning no can release apps that use).

I'm wondering if there are any other ways to detect the ambient light level without going directly to the sensor.

I'm thinking of things like key/value binding or notification manager stuff.

I have not seen this kind of thing for ambient light anywhere. I am about to throw in the towel, but figured I'd ask around here, just for the heck of it.

Does anyone know of some (legal) way to find out what the phone believes is the ambient light?

答:
I don't believe that exits some API to ambient light. But what do you think to try get this information by phone's camera ?.

I found this great answer when i was looking for luximenter api for iOS.

https://stackoverflow.com/a/10744323/6273003


问:
Azure hosted blob of type .html intermittently ignoring absolute href and making relative
I have created an html file on Azure blob storage. Accessing the file through a browser works flawlessly, every time. However, for some reason, despite two links being formatted exactly the same (except for the href and the img src), Azure is treating one as a relative link and the other as an absolute link.

I have tried to reformat the links.
I have tried to reposition the failing element within the page.
I have tried to use different links (such as test.com)

```<code><a href="https://linkedin.com/company/xyz" target="_blank"><img src="xyz"></a>
<a href="https://twitter.com/xyz" target="_blank"><img src="abc"></a>
</code>```

The top link works correctly as an absolute URL.
The second link is treated as relative, appending the https:// to the end of my azure blob storage path.

The view source of blob storage pages is infinitely more complex than the page itself. Is it possible that something is running that is interfering with simple html code? Is there a different code structure I should use? Thanks in advance.

答: It turns out that when copying links from Gmail to the Azure editor, it allowed for hidden characters which were saved and preventing links from working properly. </p>

Body:
I have created an html file on Azure blob storage. Accessing the file through a browser works flawlessly, every time. However, for some reason, despite two links being formatted exactly the same (except for the href and the img src), Azure is treating one as a relative link and the other as an absolute link.

I have tried to reformat the links.
I have tried to reposition the failing element within the page.
I have tried to use different links (such as test.com)

The top link works correctly as an absolute URL.
The second link is treated as relative, appending the https:// to the end of my azure blob storage path.

The view source of blob storage pages is infinitely more complex than the page itself. Is it possible that something is running that is interfering with simple html code? Is there a different code structure I should use? Thanks in advance.


问:
How to delete certain k entries that belong to same group in pandas e.g. balance classes?
I currently have the following distribution of labels

```<code>Lbl
0    10451
1     1481
dtype: int64
</code>```

How do I balance labels out? e.g picking only 1481 of 0s?

Given dataframe to be

```<code>index | 1 | 2 | 3 | ... | Lbl
</code>```

Thank you

EDIT:
Adding a picture to address the issue discussed in the answer:

I get the above ^^ for this code

```<code>print(table_train[:5])
table_train = table_train.groupby('Lbl').apply(lambda x : x.sample(1481)).reset_index(level=1, drop=True)
print(table_train[:5])
</code>```

答:
You can try with sample after groupby

```<code>df.groupby('Label').apply(lambda x : x.sample(1481)).reset_index(level=0,drop=True)
</code>```

Body:
I currently have the following distribution of labels

Lbl
0    10451
1     1481
dtype: int64

How do I balance labels out? e.g picking only 1481 of 0s?

Given dataframe to be

index | 1 | 2 | 3 | ... | Lbl

Thank you

EDIT:
Adding a picture to address the issue discussed in the answer:

I get the above ^^ for this code

print(table_train[:5])
table_train = table_train.groupby('Lbl').apply(lambda x : x.sample(1481)).reset_index(level=1, drop=True)
print(table_train[:5])

Body:
You can try with sample after groupby

df.groupby('Label').apply(lambda x : x.sample(1481)).reset_index(level=0,drop=True)


问:
Boto3 ec2 describe_images is too slow
I have this code snippet to get amazon machine images:

```<code>session.client('ec2', region_name=AWS_DEFAULT_REGION).describe_images(ExecutableUsers=[
               'all',
           ],
           Filters=[
               {
                   'Name': 'platform',
                   'Values': [
                       'windows',
                   ]
               },
               {
                   'Name': 'state',
                   'Values': [
                       'available',
                   ]
               },
               {
                   'Name': 'image-type',
                   'Values': [
                       'machine',
                   ]
               },
               {
                   'Name': 'virtualization-type',
                   'Values': [
                       'hvm',
                   ]
               },
               {
                   'Name': 'root-device-type',
                   'Values': [
                       'ebs',
                   ]
               },
           ],
           Owners=[
               '679593333241', # all public ami's from amazon as owner
           ])
</code>```

This works, but the response is too slow, I know that the AMI list is very long, but i don't need all AMIs on the list, i only need the most popular AMI elements (red hat, amazon linux, centos, etc.) if i use Owners=['self'] it returns null, how do i make a sort list of AMI elements like in aws console in quickstart menu when launch a new instance(see the image)? this list has 38 elements.

答:
Rather than using describe_images(), you might want to use a special feature of Amazon EC2 Systems Manager - Parameter Store that can provide the AMI ID of recent Amazon-managed AMIs.

For example:

```<code>aws ssm get-parameters --names /aws/service/ecs/optimized-ami/amazon-linux-2/recommended --region us-east-1
</code>```

Returns:

```<code>{
    "Parameters": [
        {
            "Name": "/aws/service/ecs/optimized-ami/amazon-linux-2/recommended",
            "Type": "String",
            "Value": "{\"schema_version\":1,\"image_name\":\"amzn2-ami-ecs-hvm-2.0.20181017-x86_64-ebs\",\"image_id\":\"ami-0a6be20ed8ce1f055\",\"os\":\"Amazon Linux 2\",\"ecs_runtime_version\":\"Docker version 18.06.1-ce\",\"ecs_agent_version\":\"1.21.0\"}",
            "Version": 1,
            "LastModifiedDate": 1539908415.817,
            "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/ecs/optimized-ami/amazon-linux-2/recommended"
        }
    ],
    "InvalidParameters": []
}
</code>```

See:

Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog

Query for the Latest Windows AMI Using Systems Manager Parameter Store | AWS Management Tools Blog

Working with Public Parameters - AWS Systems Manager

Title: Boto3 ec2 describe_images is too slow

Body:
I have this code snippet to get amazon machine images:

session.client('ec2', region_name=AWS_DEFAULT_REGION).describe_images(ExecutableUsers=[
               'all',
           ],
           Filters=[
               {
                   'Name': 'platform',
                   'Values': [
                       'windows',
                   ]
               },
               {
                   'Name': 'state',
                   'Values': [
                       'available',
                   ]
               },
               {
                   'Name': 'image-type',
                   'Values': [
                       'machine',
                   ]
               },
               {
                   'Name': 'virtualization-type',
                   'Values': [
                       'hvm',
                   ]
               },
               {
                   'Name': 'root-device-type',
                   'Values': [
                       'ebs',
                   ]
               },
           ],
           Owners=[
               '679593333241', # all public ami's from amazon as owner
           ])

This works, but the response is too slow, I know that the AMI list is very long, but i don't need all AMIs on the list, i only need the most popular AMI elements (red hat, amazon linux, centos, etc.) if i use Owners=['self'] it returns null, how do i make a sort list of AMI elements like in aws console in quickstart menu when launch a new instance(see the image)? this list has 38 elements.

Body:
Rather than using describe_images(), you might want to use a special feature of Amazon EC2 Systems Manager - Parameter Store that can provide the AMI ID of recent Amazon-managed AMIs.

For example:

aws ssm get-parameters --names /aws/service/ecs/optimized-ami/amazon-linux-2/recommended --region us-east-1

Returns:

{
    "Parameters": [
        {
            "Name": "/aws/service/ecs/optimized-ami/amazon-linux-2/recommended",
            "Type": "String",
            "Value": "{\"schema_version\":1,\"image_name\":\"amzn2-ami-ecs-hvm-2.0.20181017-x86_64-ebs\",\"image_id\":\"ami-0a6be20ed8ce1f055\",\"os\":\"Amazon Linux 2\",\"ecs_runtime_version\":\"Docker version 18.06.1-ce\",\"ecs_agent_version\":\"1.21.0\"}",
            "Version": 1,
            "LastModifiedDate": 1539908415.817,
            "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/ecs/optimized-ami/amazon-linux-2/recommended"
        }
    ],
    "InvalidParameters": []
}

See:

Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog

Query for the Latest Windows AMI Using Systems Manager Parameter Store | AWS Management Tools Blog

Working with Public Parameters - AWS Systems Manager


问:
Can I use Spring WebFlux to implement REST services which get data through Kafka request/response topics?
I'm developing REST service which, in turn, will query slow legacy system so response time will be measured in seconds. We also expect massive load so I was thinking about asynchronous/non-blocking approaches to avoid hundreds of "servlet" threads blocked on calls to slow system.

As I see this can be implemented using AsyncContext which is present in new servlet API specs. I even developed small prototype and it seems to be working.

On the other hand it looks like I can achieve the same using Spring WebFlux.
Unfortunately I did not find any example where custom "backend" calls are wrapped with Mono/Flux. Most of the examples just reuse already-prepared reactive connectors, like ReactiveCassandraOperations.java, etc.

My data flow is the following:

JS client --> Spring RestController --> send request to Kafka topic --> read response from Kafka reply topic --> return data to client

Can I wrap Kafka steps into Mono/Flux and how to do this?
How my RestController method should look like?

Here is my simple implementation which achieves the same using Servlet 3.1 API

```<code>//took the idea from some Jetty examples
public class AsyncRestServlet extends HttpServlet {
...
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String result = (String) req.getAttribute(RESULTS_ATTR);

    if (result == null) { //data not ready yet: schedule async processing
        final AsyncContext async = req.startAsync();

        //generate some unique request ID
        String uid = "req-" + String.valueOf(req.hashCode());

        //share it to Kafka receive together with AsyncContext
        //when Kafka receiver will get the response it will put it in Servlet request attribute and call async.dispatch()
        //This doGet() method will be called again and it will send the response to client
        receiver.rememberKey(uid, async);

        //send request to Kafka
        sender.send(uid, param);

        //data is not ready yet so we are releasing Servlet thread
        return;
    }

    //return result as html response
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    out.println(result);
    out.close();
}
</code>```

答:
Here's a short example - Not the WebFlux client you probably had in mind, but at least it would enable you to utilize Flux and Mono for asynchronous processing, which I interpreted to be the point of your question. The web objects should work without additional configurations, but of course you will need to configure Kafka as the KafkaTemplate object will not work on its own.

```<code>    @Bean // Using org.springframework.web.reactive.function.server.RouterFunction<ServerResponse>
    public RouterFunction<ServerResponse> sendMessageToTopic(KafkaController kafkaController){
        return RouterFunctions.route(RequestPredicates.POST("/endpoint"), kafkaController::sendMessage);
    }

    @Component
    public class ResponseHandler {
        public getServerResponse() {
            return ServerResponse.ok().body(Mono.just(Status.SUCCESS), String.class);
        }
    }

    @Component
    public class KafkaController {
        public Mono<ServerResponse> auditInvalidTransaction(ServerRequest request) {
            return request.bodyToMono(TopicMsgMap.class)
                // your HTTP call may not return immediately without this
                .subscribeOn(Schedulers.single()) // for a single worker thread
                .flatMap(topicMsgMap -> {
                    MyKafkaPublisher.sendMessages(topicMsgMap);
                }.flatMap(responseHandler::getServerResponse);
        }
    }

    @Data // model class just to easily convert the ServerRequest (from json, for ex.)
    // + ~@constructors
    public class TopicMsgMap() {
        private Map<String, String> topicMsgMap;
    }

    @Service // Using org.springframework.kafka.core.KafkaTemplate<String, String>
    public class MyKafkaPublisher {
        @Autowired
        private KafkaTemplate<String, String> template;

        @Value("${topic1}")
        private String topic1;
        @Value("${topic2}")
        private String topic2;

        public void sendMessages(Map<String, String> topicMsgMap){
            topicMsgMap.forEach((top, msg) -> {
                if (topic.equals("topic1") kafkaTemplate.send(topic1, message);
                if (topic.equals("topic2") kafkaTemplate.send(topic2, message);
            });
        }
    }
</code>```

Guessing this isn't the use-case you had in mind, but hope you find this general structure useful.

Body:
I'm developing REST service which, in turn, will query slow legacy system so response time will be measured in seconds. We also expect massive load so I was thinking about asynchronous/non-blocking approaches to avoid hundreds of "servlet" threads blocked on calls to slow system.

As I see this can be implemented using AsyncContext which is present in new servlet API specs. I even developed small prototype and it seems to be working.

On the other hand it looks like I can achieve the same using Spring WebFlux.
Unfortunately I did not find any example where custom "backend" calls are wrapped with Mono/Flux. Most of the examples just reuse already-prepared reactive connectors, like ReactiveCassandraOperations.java, etc.

My data flow is the following:

JS client --> Spring RestController --> send request to Kafka topic --> read response from Kafka reply topic --> return data to client

Can I wrap Kafka steps into Mono/Flux and how to do this?
How my RestController method should look like?

Here is my simple implementation which achieves the same using Servlet 3.1 API

//took the idea from some Jetty examples
public class AsyncRestServlet extends HttpServlet {
...
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String result = (String) req.getAttribute(RESULTS_ATTR);

    if (result == null) { //data not ready yet: schedule async processing
        final AsyncContext async = req.startAsync();

        //generate some unique request ID
        String uid = "req-" + String.valueOf(req.hashCode());

        //share it to Kafka receive together with AsyncContext
        //when Kafka receiver will get the response it will put it in Servlet request attribute and call async.dispatch()
        //This doGet() method will be called again and it will send the response to client
        receiver.rememberKey(uid, async);

        //send request to Kafka
        sender.send(uid, param);

        //data is not ready yet so we are releasing Servlet thread
        return;
    }

    //return result as html response
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    out.println(result);
    out.close();
}

Body:
Here's a short example - Not the WebFlux client you probably had in mind, but at least it would enable you to utilize Flux and Mono for asynchronous processing, which I interpreted to be the point of your question. The web objects should work without additional configurations, but of course you will need to configure Kafka as the KafkaTemplate object will not work on its own.

    @Bean // Using org.springframework.web.reactive.function.server.RouterFunction<ServerResponse>
    public RouterFunction<ServerResponse> sendMessageToTopic(KafkaController kafkaController){
        return RouterFunctions.route(RequestPredicates.POST("/endpoint"), kafkaController::sendMessage);
    }

    @Component
    public class ResponseHandler {
        public getServerResponse() {
            return ServerResponse.ok().body(Mono.just(Status.SUCCESS), String.class);
        }
    }

    @Component
    public class KafkaController {
        public Mono<ServerResponse> auditInvalidTransaction(ServerRequest request) {
            return request.bodyToMono(TopicMsgMap.class)
                // your HTTP call may not return immediately without this
                .subscribeOn(Schedulers.single()) // for a single worker thread
                .flatMap(topicMsgMap -> {
                    MyKafkaPublisher.sendMessages(topicMsgMap);
                }.flatMap(responseHandler::getServerResponse);
        }
    }

    @Data // model class just to easily convert the ServerRequest (from json, for ex.)
    // + ~@constructors
    public class TopicMsgMap() {
        private Map<String, String> topicMsgMap;
    }

    @Service // Using org.springframework.kafka.core.KafkaTemplate<String, String>
    public class MyKafkaPublisher {
        @Autowired
        private KafkaTemplate<String, String> template;

        @Value("${topic1}")
        private String topic1;
        @Value("${topic2}")
        private String topic2;

        public void sendMessages(Map<String, String> topicMsgMap){
            topicMsgMap.forEach((top, msg) -> {
                if (topic.equals("topic1") kafkaTemplate.send(topic1, message);
                if (topic.equals("topic2") kafkaTemplate.send(topic2, message);
            });
        }
    }

Guessing this isn't the use-case you had in mind, but hope you find this general structure useful.


问:
How do I retain the column name used in my group by with Pandas
I have two data frames. I would like to use group by on the second data frame and then merge the two together on the Company Name column. The issue is that with my group by statement I loose the Company Name column.

```<code>import pandas as pd

df1 = pd.DataFrame(
    {
        'Company Name': ['Google','Google','Microsoft','Microsoft','Amazon','Amazon'],
        'Location': ['Somewhere','Somewhere','Somewhere','Somewhere','Somewhere','Somewhere'],
    }
)

df = pd.DataFrame(
    {
        'Company Name': ['Google','Google','Microsoft','Microsoft','Amazon','Amazon'],
        'Sales': [12345,12345,12345,12345,12345,12345],
        'Company Type': ['Software','Software','Software','Software','Software','Software']
    }
)
df = df.groupby(['Company Name']).sum()

pd.merge(df1,df,how="inner",on="Company Name")

</code>```

I get an error message when merging due to df not having a Company Name column to perform the join.

答:
Replace this line:

```<code>df = df.groupby(['Company Name']).sum()
</code>```

With:

```<code>df = df.groupby('Company Name', as_index=False).sum()
</code>```

Then your code will work as expected, and return:

```<code>  Company Name   Location  Sales
0       Google  Somewhere  24690
1       Google  Somewhere  24690
2    Microsoft  Somewhere  24690
3    Microsoft  Somewhere  24690
4       Amazon  Somewhere  24690
5       Amazon  Somewhere  24690
</code>```

Body:
I have two data frames. I would like to use group by on the second data frame and then merge the two together on the Company Name column. The issue is that with my group by statement I loose the Company Name column.

import pandas as pd

df1 = pd.DataFrame(
    {
        'Company Name': ['Google','Google','Microsoft','Microsoft','Amazon','Amazon'],
        'Location': ['Somewhere','Somewhere','Somewhere','Somewhere','Somewhere','Somewhere'],
    }
)

df = pd.DataFrame(
    {
        'Company Name': ['Google','Google','Microsoft','Microsoft','Amazon','Amazon'],
        'Sales': [12345,12345,12345,12345,12345,12345],
        'Company Type': ['Software','Software','Software','Software','Software','Software']
    }
)
df = df.groupby(['Company Name']).sum()

pd.merge(df1,df,how="inner",on="Company Name")

I get an error message when merging due to df not having a Company Name column to perform the join.

Body:
Replace this line:

df = df.groupby(['Company Name']).sum()

With:

df = df.groupby('Company Name', as_index=False).sum()

Then your code will work as expected, and return:

  Company Name   Location  Sales
0       Google  Somewhere  24690
1       Google  Somewhere  24690
2    Microsoft  Somewhere  24690
3    Microsoft  Somewhere  24690
4       Amazon  Somewhere  24690
5       Amazon  Somewhere  24690


问:
Is Runnable an interface or an object in Java?
While creating threads I see code like:-

```<code>Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}
</code>```

From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.

答: Runnable is an interface. We use it with the "new" operator in order to create an anonymous class object whICH </p>

Body:
While creating threads I see code like:-

Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}

From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.


问:
Table with no primary key due to lots of duplicates, trying to speed up my query to get rid of duplicates etc
I have a table of products from various suppliers all added together, so there are lots of duplicate SKU's (ManuPartNo), there are other elements, Price, Qty etc.  However I want to Choose the Highest Price based on the SKU (ManuPartNo) and also add together all of the Qty's for any matching SKU. I have a working query but was wondering if anyone could suggest how to speed it up, the table I am querying has 1.3 million rows and my query takes about 40 seconds to run.  Its not too slow but I am trying to learn more about optimization and this question is very hard to google so if anyone could give me any tips or point me in the right direction it would be much appreciated.

Here is the structure of the table I'm querying and my query its self.

```<code>CREATE TABLE [dbo].[AllProductsFromAllDistis](
[ProdName] [varchar](max) NULL,
[ManuPartNo] [varchar](150) NULL,
[Manufacturer] [varchar](150) NULL,
[Price] [decimal](10, 2) NOT NULL,
[Qty] [int] NOT NULL,
[Weight] [decimal](10, 2) NULL,
[UpcCode] [varchar](50) NULL,
[Supplier] [varchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code>```

and my query to return only the values with the highest price and to add all qty's of any duplicate sku.

```<code>SELECT ProdName, ManuPartNo, Price, TotalQty, Weight, UPCCode, Supplier,
Manufacturer
FROM
(SELECT dbo.AllProductsFromAllDistis. *,
    ROW_NUMBER() OVER(PARTITION BY ManuPartNo ORDER BY Price ASC) AS RN,
    SUM(Qty) OVER(PARTITION BY ManuPartNo) AS TotalQty
        FROM AllProductsFromAllDistis) AS t
WHERE RN = 1
ORDER BY ManuPartNo
</code>```

As I say this works just fine but I am looking for suggestions on speeding it up.

答:
Although you can’t create a primary key due to the duplicates, you can still create a clustered index which does not require uniqueness but will still improve performance of queries that group or join on the indexes columns. E.g:</p>

```<code>CREATE CLUSTERED INDEX [IX_AllProductsFromAllDistis] ON [dbo].[AllProductsFromAllDistis] ([ManuPartNo])
</code>```

Body:
I have a table of products from various suppliers all added together, so there are lots of duplicate SKU's (ManuPartNo), there are other elements, Price, Qty etc.  However I want to Choose the Highest Price based on the SKU (ManuPartNo) and also add together all of the Qty's for any matching SKU. I have a working query but was wondering if anyone could suggest how to speed it up, the table I am querying has 1.3 million rows and my query takes about 40 seconds to run.  Its not too slow but I am trying to learn more about optimization and this question is very hard to google so if anyone could give me any tips or point me in the right direction it would be much appreciated.

Here is the structure of the table I'm querying and my query its self.

CREATE TABLE [dbo].[AllProductsFromAllDistis](
[ProdName] [varchar](max) NULL,
[ManuPartNo] [varchar](150) NULL,
[Manufacturer] [varchar](150) NULL,
[Price] [decimal](10, 2) NOT NULL,
[Qty] [int] NOT NULL,
[Weight] [decimal](10, 2) NULL,
[UpcCode] [varchar](50) NULL,
[Supplier] [varchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

and my query to return only the values with the highest price and to add all qty's of any duplicate sku.

SELECT ProdName, ManuPartNo, Price, TotalQty, Weight, UPCCode, Supplier,
Manufacturer
FROM
(SELECT dbo.AllProductsFromAllDistis. *,
    ROW_NUMBER() OVER(PARTITION BY ManuPartNo ORDER BY Price ASC) AS RN,
    SUM(Qty) OVER(PARTITION BY ManuPartNo) AS TotalQty
        FROM AllProductsFromAllDistis) AS t
WHERE RN = 1
ORDER BY ManuPartNo

As I say this works just fine but I am looking for suggestions on speeding it up.

Body:
Although you can’t create a primary key due to the duplicates, you can still create a clustered index which does not require uniqueness but will still improve performance of queries that group or join on the indexes columns. E.g:

CREATE CLUSTERED INDEX [IX_AllProductsFromAllDistis] ON [dbo].[AllProductsFromAllDistis] ([ManuPartNo])


问:
How to decorate a Python object with a mutex
I'm new to python and am currently trying to learn threading. I'm weary of using locks to make my resources thread-safe because they aren't inherently tied to the resource, so I'm bound to forget to acquire and/or release them every time my code interacts with the resource. Instead, I'd like to be able to "wrap" (or decorate?) an object so that all of it's methods and attribute getters/setters are atomic. something like this:

```<code>state = atomicObject(dict())

# the following is atomic/thread-safe
state["some key"] = "some value"
</code>```

Is this possible? If so, what's the "best practices" way of implementing it?

EDIT: An good answer to the above question is available in How to make built-in containers (sets, dicts, lists) thread safe?. However; as abarnert and jsbueno have both demonstrated, the solution I proposed (automating locks) is not generally a good idea because determining the proper granularity of atomic operations requires some intelligence and is likely difficult (or impossible) to automate properly.

The problem still remains that locks are not bound in any way to the resources they are meant to protect, so my new question is: What's a good way to associate a lock with an object?

Proposed solution #2:
I imagine there might be a way to bind a lock to an object such that trying to access that object without first acquiring the lock throws an error, but I can see how that could get tricky.

EDIT: The following code is not very relevant to the question. I posted it to demonstrate that I had tried to solve the problem myself and gotten lost before posting this question.

For the record, I wrote the following code, but it doesn't work:

```<code>import threading
import types
import inspect

class atomicObject(object):

    def __init__(self, obj):
        self.lock = threading.RLock()
        self.obj = obj

        # keep track of function handles for lambda functions that will be created
        self.funcs = []

        # loop through all the attributes of the passed in object
        # and create wrapped versions of each attribute
        for name in dir(self.obj):
            value = getattr(self.obj, name)
            if inspect.ismethod(value):
                # this is where things get really ugly as i try to work around the
                # limitations of lambda functions and use eval()... I'm not proud of this code
                eval("self.funcs.append(lambda self, *args, **kwargs: self.obj." + name + "(*args, **kwargs))")
                fidx = str(len(self.funcs) - 1)
                eval("self." + name + " = types.MethodType(lambda self, *args, **kwargs: self.atomize(" + fidx + ", *args, **kwargs), self)")

    def atomize(self, fidx, *args, **kwargs):
        with self.lock:
            return self.functions[fidx](*args, **kwargs)
</code>```

I can create an atomicObject(dict()), but when I try to add a value to the object, I get the error; "atomicObject does not support item assignment".

答:
The wrapt module then contains the @synchronized decorator described there.

https://pypi.python.org/pypi/wrapt

A talk describing the decorator and how it works can be found at:

https://www.youtube.com/watch?v=EB6AH-85zfY

Body:
I'm new to python and am currently trying to learn threading. I'm weary of using locks to make my resources thread-safe because they aren't inherently tied to the resource, so I'm bound to forget to acquire and/or release them every time my code interacts with the resource. Instead, I'd like to be able to "wrap" (or decorate?) an object so that all of it's methods and attribute getters/setters are atomic. something like this:

state = atomicObject(dict())

# the following is atomic/thread-safe
state["some key"] = "some value"

Is this possible? If so, what's the "best practices" way of implementing it?

EDIT: An good answer to the above question is available in How to make built-in containers (sets, dicts, lists) thread safe?. However; as abarnert and jsbueno have both demonstrated, the solution I proposed (automating locks) is not generally a good idea because determining the proper granularity of atomic operations requires some intelligence and is likely difficult (or impossible) to automate properly.

The problem still remains that locks are not bound in any way to the resources they are meant to protect, so my new question is: What's a good way to associate a lock with an object?

Proposed solution #2:
I imagine there might be a way to bind a lock to an object such that trying to access that object without first acquiring the lock throws an error, but I can see how that could get tricky.

EDIT: The following code is not very relevant to the question. I posted it to demonstrate that I had tried to solve the problem myself and gotten lost before posting this question.

For the record, I wrote the following code, but it doesn't work:

import threading
import types
import inspect

class atomicObject(object):

    def __init__(self, obj):
        self.lock = threading.RLock()
        self.obj = obj

        # keep track of function handles for lambda functions that will be created
        self.funcs = []

        # loop through all the attributes of the passed in object
        # and create wrapped versions of each attribute
        for name in dir(self.obj):
            value = getattr(self.obj, name)
            if inspect.ismethod(value):
                # this is where things get really ugly as i try to work around the
                # limitations of lambda functions and use eval()... I'm not proud of this code
                eval("self.funcs.append(lambda self, *args, **kwargs: self.obj." + name + "(*args, **kwargs))")
                fidx = str(len(self.funcs) - 1)
                eval("self." + name + " = types.MethodType(lambda self, *args, **kwargs: self.atomize(" + fidx + ", *args, **kwargs), self)")

    def atomize(self, fidx, *args, **kwargs):
        with self.lock:
            return self.functions[fidx](*args, **kwargs)

I can create an atomicObject(dict()), but when I try to add a value to the object, I get the error; "atomicObject does not support item assignment".


问:
Compare two dataframe columns in same dataframe and return text contained in first column
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

```<code>import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

</code>```

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

答:
The part where you have tried to split using ";" is correct. After that, you need to compare each element in col1_split with each element in col2_split. You can write a simple function to avoid many loops and use pandas apply function to do the rest

Here is the sample code for the same

```<code>import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

def value_check(list1, list2):
    string = ""
    for i in list1:
        if (i in list2) & (len(i)>0):
            string += ";"+i+';'
    return string

df['output'] = df.apply(lambda x: value_check(x.col1_split, x.col2_split), axis=1)
df
</code>```

Output

Body:
I have data loaded into a dataframe but cannot figure out how to compare the parsed data against the other column and return only matches.

This seems like it should be easy but I just don't see it. I've tried splitting the values out to compare but here's where I get stuck.

import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

# output something like...
df['output'] = [null,';c1312;',';d1310;']

I'd expect to see something like -

1st row - return null, as t9010 is not contained in col2_split

2nd row - return c1312, as it is in col2_split

3rd row - return d1310 but not c1512, as only d1310 is in col2_split

lastly, the final text should be returned semicolon delimited and with leading and trailing semicolons i.e. ;t9010; or ;c1312; or ;d1310;c1512; if there is more than one.

Body:
The part where you have tried to split using ";" is correct. After that, you need to compare each element in col1_split with each element in col2_split. You can write a simple function to avoid many loops and use pandas apply function to do the rest

Here is the sample code for the same

import pandas as pd

df = pd.DataFrame({ 'col1': [';t9010;',';c1312;',';d1310;c1512;'],
                    'col2': [';t1010;d1010;c1012;',';t1210;d1210;c1312;',';t1310;d1310;c1412;']})

df['col1_split'] = df['col1'].str.split(';')
df['col2_split'] = df['col2'].str.split(';')

def value_check(list1, list2):
    string = ""
    for i in list1:
        if (i in list2) & (len(i)>0):
            string += ";"+i+';'
    return string

df['output'] = df.apply(lambda x: value_check(x.col1_split, x.col2_split), axis=1)
df

Output


问:
Update Textbox from another class
I need to write into a textbox on Form1 class from another class, but can't get it to work.

I'll use a very simple example of what I want to acheive.  On Form1 I have a combobox with collection of items 1,2,3,4,5. And also a textbox. Based on what is selected in the combobox, a different message will appear in the text box.  For example if I choose 1 in the combobox, textbox1 will say "1 was selected". if I choose 2 in the combobox textbox1 will say "2 was selected", etc.

I'm using a switch statement for this, but I dont want the switch statement to be in Form1.cs but instead in Class1.cs  But i can't get the text into the textbox unless I have the switch statement in Form1.cs. But I really want the switch statement to be in Class1.cs.  I've tried making both my textbox and combobox public but it didn't make a difference.

This is what I have in Form1.cs:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FunctionSelect();
    }
}
</code>```

And this is the other class Class1.cs:

```<code>class Class1
{
    public void FunctionSelect()
    {
        Form1 form1 = new Form1();
        string switcher = form1.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                form1.TextBox1Text = "1 was selected";
                break;
            case "2":
                form1.TextBox1Text = "2 was selected";
                break;
            case "3":
                form1.TextBox1Text = "3 was selected";
                break;
            case "4":
                form1.TextBox1Text = "4 was selected";
                break;
            case "5":
                form1.TextBox1Text = "5 was selected";
                break;
        }
    }
}
</code>```

When I select something in the combobox nothing happens in the text box.  But if I move my switch statement in FunctionSelect() from Class1.cs to Form1.cs it works exactly as I expected.  But really I need FunctionSelect() to be in Class1.cs - Not in Form1.cs.  I believe the problem is due to creating a new instance for Form1 in Class1.cs (Form1 form1 = new Form1()), which means I'm not actually writing to the Form1 displayed on the screen.  But I can't work out how to write to the textbox on Form1.cs from Class1.cs.

I'm sure I'm missing something very simple, but can't work it out, and can't find a post that answers exactly as I need.  Any help is appreciated.

答:
Your suspicion is well funded your problem is exactly that you are making a new form1, there is a number of ways on how to achieve what you are trying to do, one would be to pass the form as a parameter to your other class, another could be using event pattern, and you can find many more.

I will explain how to do the first one:

First you need to update your Class1 to have a constructor that take a Form1 class as a parameter and you save the reference to that class inside the class1. Then you can use that instance to work on your Form1 class. See example above.

NOTE: As a rule of thumb you should use delegates, in this particular case it works fine without one, but you should check whether invoke is required or not when modifying values on the UI thread. Another thing that can be improved there is no need to instanciate many class1, you could have a Class one instansiation and use that class forever, and not going making several classes.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1(this);
        class1.FunctionSelect();
    }
}

public class Class1
{
    private Form1 _instance;

    public Class1(Form1 instance)
    {
        _instance = instance;
    }

    public void FunctionSelect()
    {
        string switcher = _instance.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                _instance.TextBox1Text = "1 was selected";
                break;
            case "2":
                _instance.TextBox1Text = "2 was selected";
                break;
            case "3":
                _instance.TextBox1Text = "3 was selected";
                break;
            case "4":
                _instance.TextBox1Text = "4 was selected";
                break;
            case "5":
                _instance.TextBox1Text = "5 was selected";
                break;
        }
    }
}
</code>```

Title: Update Textbox from another class

Body:
I need to write into a textbox on Form1 class from another class, but can't get it to work.

I'll use a very simple example of what I want to acheive.  On Form1 I have a combobox with collection of items 1,2,3,4,5. And also a textbox. Based on what is selected in the combobox, a different message will appear in the text box.  For example if I choose 1 in the combobox, textbox1 will say "1 was selected". if I choose 2 in the combobox textbox1 will say "2 was selected", etc.

I'm using a switch statement for this, but I dont want the switch statement to be in Form1.cs but instead in Class1.cs  But i can't get the text into the textbox unless I have the switch statement in Form1.cs. But I really want the switch statement to be in Class1.cs.  I've tried making both my textbox and combobox public but it didn't make a difference.

This is what I have in Form1.cs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FunctionSelect();
    }
}

And this is the other class Class1.cs:

class Class1
{
    public void FunctionSelect()
    {
        Form1 form1 = new Form1();
        string switcher = form1.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                form1.TextBox1Text = "1 was selected";
                break;
            case "2":
                form1.TextBox1Text = "2 was selected";
                break;
            case "3":
                form1.TextBox1Text = "3 was selected";
                break;
            case "4":
                form1.TextBox1Text = "4 was selected";
                break;
            case "5":
                form1.TextBox1Text = "5 was selected";
                break;
        }
    }
}

When I select something in the combobox nothing happens in the text box.  But if I move my switch statement in FunctionSelect() from Class1.cs to Form1.cs it works exactly as I expected.  But really I need FunctionSelect() to be in Class1.cs - Not in Form1.cs.  I believe the problem is due to creating a new instance for Form1 in Class1.cs (Form1 form1 = new Form1()), which means I'm not actually writing to the Form1 displayed on the screen.  But I can't work out how to write to the textbox on Form1.cs from Class1.cs.

I'm sure I'm missing something very simple, but can't work it out, and can't find a post that answers exactly as I need.  Any help is appreciated.

Body:
Your suspicion is well funded your problem is exactly that you are making a new form1, there is a number of ways on how to achieve what you are trying to do, one would be to pass the form as a parameter to your other class, another could be using event pattern, and you can find many more.

I will explain how to do the first one:

First you need to update your Class1 to have a constructor that take a Form1 class as a parameter and you save the reference to that class inside the class1. Then you can use that instance to work on your Form1 class. See example above.

NOTE: As a rule of thumb you should use delegates, in this particular case it works fine without one, but you should check whether invoke is required or not when modifying values on the UI thread. Another thing that can be improved there is no need to instanciate many class1, you could have a Class one instansiation and use that class forever, and not going making several classes.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string ComboBox1Text
    {
        get { return comboBox1.Text; }
    }

    public string TextBox1Text
    {
        get { return textBox1.Text; }
        set { textBox1.Text = value; }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        Class1 class1 = new Class1(this);
        class1.FunctionSelect();
    }
}

public class Class1
{
    private Form1 _instance;

    public Class1(Form1 instance)
    {
        _instance = instance;
    }

    public void FunctionSelect()
    {
        string switcher = _instance.ComboBox1Text;
        switch (switcher)
        {
            case "1":
                _instance.TextBox1Text = "1 was selected";
                break;
            case "2":
                _instance.TextBox1Text = "2 was selected";
                break;
            case "3":
                _instance.TextBox1Text = "3 was selected";
                break;
            case "4":
                _instance.TextBox1Text = "4 was selected";
                break;
            case "5":
                _instance.TextBox1Text = "5 was selected";
                break;
        }
    }
}


问:
lxml returned me a list but it's empty
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

```<code>market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')
</code>```

then I also tried lxml.html.

```<code>tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')
</code>```

furthermore, I tried this xpath:

```<code>s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')
</code>```

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

答:
Here is a more lightweight way of getting just that column using nth-of-type. You should find this faster.</p>

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://hypeauditor.com/top-instagram/')
soup = bs(r.content, 'lxml')
accounts = [item.text.strip().split('\n') for item in soup.select('#bloggers-top-table td:nth-of-type(4)')][1:]
print(accounts)
</code>```

Title: lxml returned me a list but it's empty

Body:
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')

then I also tried lxml.html.

tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')

furthermore, I tried this xpath:

s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

Body:
Here is a more lightweight way of getting just that column using nth-of-type. You should find this faster.

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://hypeauditor.com/top-instagram/')
soup = bs(r.content, 'lxml')
accounts = [item.text.strip().split('\n') for item in soup.select('#bloggers-top-table td:nth-of-type(4)')][1:]
print(accounts)


问:
Resize div according to background image size
I have a div that loads a background image. The height of this div cannot go beyond 60px but the width can be expanded upto any number depending on the image width.

I want all my images that are getting loaded to have original dimensions without getting blurred. Infact, my div should resize according to the image size but should not go beyond 60px.

Currently, I have this css in place for the div.
Using background-size: contain works really well for images greater that 60px height but when the image is smaller it stretches the image and background-size: auto works well for smaller images but larger images expands out of the div.

```<code>.div{
  background-image: url("../assets/images/example.gif");
  background-size: contain;
  background-repeat: no-repeat;
  height: 60px!important;
  width: 500px!important;
}
</code>```

I am looking for some css that will show the original image everytime having the div height intact to 60px

Thanks

答:
The backgroundImage doesn't size the element. It's not how backgroundImage was designed.

The contents of the element or any set attributes do. So what you can do is, via JavaScript, create a  tag with the same source as the backgroundImage. In its onload event get the size of the image and set the div's width to that value.

Along these lines:

const toResize = document.querySelectorAll('.bg-resize');
[...toResize].forEach(elem => {
  const img = document.createElement('img');
  img.src = elem.style.backgroundImage.slice(4, -1).replace(/"/g, "");
  img.onload = event => {
    elem.style.width = `${event.path[0].width}px`;
  };
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bg-resize {
  height: 60px;
  margin: 0 auto;
  background: transparent no-repeat center /cover;
}</code>```

```

Notice you don't actually have to append the  elements. They get loaded once you create them.

Body:
I have a div that loads a background image. The height of this div cannot go beyond 60px but the width can be expanded upto any number depending on the image width.

I want all my images that are getting loaded to have original dimensions without getting blurred. Infact, my div should resize according to the image size but should not go beyond 60px.

Currently, I have this css in place for the div.
Using background-size: contain works really well for images greater that 60px height but when the image is smaller it stretches the image and background-size: auto works well for smaller images but larger images expands out of the div.

.div{
  background-image: url("../assets/images/example.gif");
  background-size: contain;
  background-repeat: no-repeat;
  height: 60px!important;
  width: 500px!important;
}

I am looking for some css that will show the original image everytime having the div height intact to 60px

Thanks

Body:
The backgroundImage doesn't size the element. It's not how backgroundImage was designed.

The contents of the element or any set attributes do. So what you can do is, via JavaScript, create a <img> tag with the same source as the backgroundImage. In its onload event get the size of the image and set the div's width to that value.

Along these lines:

const toResize = document.querySelectorAll('.bg-resize');
[...toResize].forEach(elem => {
  const img = document.createElement('img');
  img.src = elem.style.backgroundImage.slice(4, -1).replace(/"/g, "");
  img.onload = event => {
    elem.style.width = `${event.path[0].width}px`;
  };
})

.bg-resize {
  height: 60px;
  margin: 0 auto;
  background: transparent no-repeat center /cover;
}

<div class="bg-resize" style="background-image: url(https://via.placeholder.com/150)"></div>
<div class="bg-resize" style="background-image: url(https://via.placeholder.com/600x60)"></div>
<div class="bg-resize" style="background-image: url(https://via.placeholder.com/300x200)"></div>

Notice you don't actually have to append the <img> elements. They get loaded once you create them.


问:
google app engine favicon.ico does not update
I'm developing GAE App.

I have a favicon.ico in my static folder, as recommended and explained everywhere.

Now I changed the picture in the favicon.ico. In the local host I can see the new favicon.ico, but when I try to open the webpage with the url (on the server) I see the old favicon.ico.

It even persist when I uploaded a newer version of the app to GAE.

答: Try looking at the favicon directly, e.g., go to http://mysite.com/favicon.ico.  If it looks right there, then it is just a caching issue that will resolve itself soon.</p>


答: Runnable is interface, you are creating an anonymous class which implements the Runnable interface.

Title: Is Runnable an interface or an object in Java?


问:
Is there anything to generically invert a C++ Comparator type?
For example, if I passed in std::less, I would want it to create a new comparator with behavior equal to std::greater. For use in templates.

Something that would enable a syntax like std::map<int, int, std::invert<std::less>> (except if the thing I'm looking for exists, that's not what it's called). Does this exist?

答:
There is std::not_fn, which:

Creates a forwarding call wrapper that returns the negation of the callable object it holds.

However, in this case, it would result in a comparator with functionality of std::greater_equal, not std::greater. Furthermore, the type is not the same as std::greater_equal.

Example:

```<code>auto greater_eq = std::not_fn(std::less<>());
</code>```

For getting equivalent of std::greater, you get that by flipping the arguments. I don't think there's a function for that in the standard library, but it's simple to write yourself:

```<code>auto flip = [](auto fun) {
    return [fun = std::move(fun)]
           (const auto& arg1, const auto& arg2)
    {
        return fun(arg2, arg1);
    };
};

auto greater = flip(std::less<>());
</code>```

This could also be extended to support any number of arguments, flipping only the first two (making it analoguous to flip from Haskell), as well as to support perfect forwarding of arguments, but those features may complicate the neat example quite a bit and are not needed for comparators.

Body:
There is std::not_fn, which:

Creates a forwarding call wrapper that returns the negation of the callable object it holds.

However, in this case, it would result in a comparator with functionality of std::greater_equal, not std::greater. Furthermore, the type is not the same as std::greater_equal.

Example:

auto greater_eq = std::not_fn(std::less<>());

For getting equivalent of std::greater, you get that by flipping the arguments. I don't think there's a function for that in the standard library, but it's simple to write yourself:

auto flip = [](auto fun) {
    return [fun = std::move(fun)]
           (const auto& arg1, const auto& arg2)
    {
        return fun(arg2, arg1);
    };
};

auto greater = flip(std::less<>());

This could also be extended to support any number of arguments, flipping only the first two (making it analoguous to flip from Haskell), as well as to support perfect forwarding of arguments, but those features may complicate the neat example quite a bit and are not needed for comparators.


问:
How to hide / disable Ionic inapp browser top address bar?
I have implemented ionic inapp browser in my app. I want to hide the top bar from it. I am trying using the below code but it does not seem to work.

page.ts code

```<code>  openWebpage(url: string) {
    const browser = this.inAppBrowser.create('http://sco7.com/filemanager/sapphire/','_self','toolbar=no');
    const options: InAppBrowserOptions = {
      zoom: 'no',
      location: 'no',
      toolbar: 'no'
    }

  }
</code>```

I have added toolbar=no  but still top address bar is visible.

答:
```<code>openWebpage(url: string) {
    const options: InAppBrowserOptions = {
      zoom: 'no',
      fullscreen: "yes",
      hidenavigationbuttons: "no",
      toolbar:'no',
      hideurlbar: 'yes',
    }

    // Opening a URL and returning an InAppBrowserObject
    const browser = this.inAppBrowser.create(url, '_blank',{ toolbar: 'no',  hideurlbar: 'yes',
    fullscreen: "yes",location:"no", options});

    browser.on('loadstop').subscribe(event => {
      browser.insertCSS({ code: "toolbar{display: none;" });
    });

   // Inject scripts, css and more with browser.X
    }
</code>```

<p>like this way shall appear what you wanna hidden or control! </p>

Body:
I have implemented ionic inapp browser in my app. I want to hide the top bar from it. I am trying using the below code but it does not seem to work.

page.ts code

  openWebpage(url: string) {
    const browser = this.inAppBrowser.create('http://sco7.com/filemanager/sapphire/','_self','toolbar=no');
    const options: InAppBrowserOptions = {
      zoom: 'no',
      location: 'no',
      toolbar: 'no'
    }

  }

I have added toolbar=no  but still top address bar is visible.

Body:
openWebpage(url: string) {
    const options: InAppBrowserOptions = {
      zoom: 'no',
      fullscreen: "yes",
      hidenavigationbuttons: "no",
      toolbar:'no',
      hideurlbar: 'yes',
    }

    // Opening a URL and returning an InAppBrowserObject
    const browser = this.inAppBrowser.create(url, '_blank',{ toolbar: 'no',  hideurlbar: 'yes',
    fullscreen: "yes",location:"no", options});

    browser.on('loadstop').subscribe(event => {
      browser.insertCSS({ code: "toolbar{display: none;" });
    });

   // Inject scripts, css and more with browser.X
    }

like this way shall appear what you wanna hidden or control!


问:
Java Collections - Effienct search for DateTime ranges
I have a case where I have a table (t1) which contains items like

```<code> | id | timestamp | att1 | att2 |
</code>```

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!

答:
Yes. Use TreeMap which is basically a sorted map of key=>value pairs and its method TreeMap::subMap(fromKey, toKey).

In your case you would use timestamps as keys to the map and for values att1 attribute or id or whatever else would be most convenient for you.

Body:
I have a case where I have a table (t1) which contains items like

 | id | timestamp | att1 | att2 |

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!


问:
Trying to get ID from multidimensional array PHP
I have an array, which has been created from getting the pages from user levels. When I use print_r to print out the array you can see that there are arrays nested within arrays.

I am trying to access the 'ID' and 'name' values, which exists in each nested array. I have tried using a foreach and for loop, but have had no luck. Any help would be greatly appreciated.

```<code>   Array ( [0] => Array ( [0] => Array ( [ID] => 2487 [name] => Student Analytics [_more_] => /levels/1531756603/pages/2487 )
[1] => Array ( [ID] => 1048 [name] => Member Profile [_more_] => /levels/1531756603/pages/1048 )
[2] => Array ( [ID] => 864 [name] => i.4 Course Practicum – Your Live Campaign [_more_] => /levels/1531756603/pages/864 )
[3] => Array ( [ID] => 817 [name] => i.5 Course Expectations – Contact Us If Needed [_more_] => /levels/1531756603/pages/817 )
[4] => Array ( [ID] => 815 [name] => i.3 Course Assessments – Why There Are Level Assessments [_more_] => /levels/1531756603/pages/815 )
[5] => Array ( [ID] => 813 [name] => i.2 Course Structure – How to Navigate the Web Platform [_more_] => /levels/1531756603/pages/813 )
[6] => Array ( [ID] => 807 [name] => Introduction to the Course [_more_] => /levels/1531756603/pages/807 )
[7] => Array ( [ID] => 659 [name] => INTRO LEVEL ASSESSMENT [_more_] => /levels/1531756603/pages/659 )
[8] => Array ( [ID] => 378 [name] => How This Course Will be Taught [_more_] => /levels/1531756603/pages/378 )
[9] => Array ( [ID] => 376 [name] => SCourse [_more_] => /levels/1531756603/pages/376 )
[10] => Array ( [ID] => 372 [name] => Dashboard [_more_] => /levels/1531756603/pages/372 ) )
[1] => Array ( [0] => Array ( [ID] => 2372 [name] => Profile Assignment [_more_] => /levels/1531866216/pages/2372 )
[1] => Array ( [ID] => 2110 [name] => Instructions [_more_] => /levels/1531866216/pages/2110 )
[2] => Array ( [ID] => 1619 [name] => Practicum [_more_] => /levels/1531866216/pages/1619 )
[3] => Array ( [ID] => 1048 [name] => Member Profile [_more_] => /levels/1531866216/pages/1048 )
[4] => Array ( [ID] => 571 [name] => LEVEL 1 [_more_] => /levels/1531866216/pages/571 )
[5] => Array ( [ID] => 506 [name] => 2.A ASSIGNMENTS [_more_] => /levels/1531866216/pages/506 )
[6] => Array ( [ID] => 504 [name] => 2.7 SUMMARY AND REVIEW [_more_] => /levels/1531866216/pages/504 )
[7] => Array ( [ID] => 502 [name] => 2.6 Your Brand is the Balancing Force [_more_] => /levels/1531866216/pages/502 )
[8] => Array ( [ID] => 497 [name] => 2.5 Brand Trust [_more_] => /levels/1531866216/pages/497 )
[9] => Array ( [ID] => 494 [name] => 2.4 Brand Beliefs [_more_] => /levels/1531866216/pages/494 )
[10] => Array ( [ID] => 491 [name] => 2.3 Brand Promise [_more_] => /levels/1531866216/pages/491 )
[11] => Array ( [ID] => 487 [name] => 2.2 Brand Story [_more_] => /levels/1531866216/pages/487 )
[12] => Array ( [ID] => 484 [name] => 2.1 Branding [_more_] => /levels/1531866216/pages/484 )
[13] => Array ( [ID] => 478 [name] => CHAPTER 2 CREATING THE BRAND HUB: FOUR KEY BRAND ELEMENTS [_more_] => /levels/1531866216/pages/478 )
[14] => Array ( [ID] => 473 [name] => LEVEL 1 ASSESSMENT [_more_] => /levels/1531866216/pages/473 )
[15] => Array ( [ID] => 464 [name] => 2.A-1 Brand Strategy Assignment [_more_] => /levels/1531866216/pages/464 )
[16] => Array ( [ID] => 461 [name] => 2.A-4 Student Instructions [_more_] => /levels/1531866216/pages/461 )
[17] => Array ( [ID] => 459 [name] => 2.A-3 Project Submission Form [_more_] => /levels/1531866216/pages/459 )
[18] => Array ( [ID] => 448 [name] => 1.A PRACTICUM ASSIGNMENTS [_more_] => /levels/1531866216/pages/448 )
[19] => Array ( [ID] => 445 [name] => 1.A-2 Topical Brainstorm Assignment [_more_] => /levels/1531866216/pages/445 )
[20] => Array ( [ID] => 432 [name] => 1.5 SUMMARY AND REVIEW [_more_] => /levels/1531866216/pages/432 )
[21] => Array ( [ID] => 427 [name] => 1.4 A New Inbound Model [_more_] => /levels/1531866216/pages/427 )
[22] => Array ( [ID] => 423 [name] => 1.3 The New Social Era of Marketing [_more_] => /levels/1531866216/pages/423 )
[23] => Array ( [ID] => 410 [name] => 1.2 Traditional Outbound Marketing vs. Digital Inbound Marketing [_more_] => /levels/1531866216/pages/410 )
[24] => Array ( [ID] => 394 [name] => 1.1 Consumer Acquisition from the Digital Landscape [_more_] => /levels/1531866216/pages/394 )
[25] => Array ( [ID] => 392 [name] => CHAPTER 1 INTRODUCING [_more_] => /levels/1531866216/pages/392 )
[26] => Array ( [ID] => 318 [name] => Project Submission Thank You [_more_] => /levels/1531866216/pages/318 ) ) )
</code>```

答:
Loop through the array like so. </p>

```<code>foreach($pages_array_name['0'] as $index => $sub_array) {
   echo "index is " . $index . "\n<br/>";
   echo "name is " . $sub_array['name'] . "\n<br/>";
   echo "_more_ is " . $sub_array['_more_'] . "\n<br/>";
   echo "\n<br/>"; // extra space
}
</code>```

Body:
I have an array, which has been created from getting the pages from user levels. When I use print_r to print out the array you can see that there are arrays nested within arrays.

I am trying to access the 'ID' and 'name' values, which exists in each nested array. I have tried using a foreach and for loop, but have had no luck. Any help would be greatly appreciated.

   Array ( [0] => Array ( [0] => Array ( [ID] => 2487 [name] => Student Analytics [_more_] => /levels/1531756603/pages/2487 )
[1] => Array ( [ID] => 1048 [name] => Member Profile [_more_] => /levels/1531756603/pages/1048 )
[2] => Array ( [ID] => 864 [name] => i.4 Course Practicum – Your Live Campaign [_more_] => /levels/1531756603/pages/864 )
[3] => Array ( [ID] => 817 [name] => i.5 Course Expectations – Contact Us If Needed [_more_] => /levels/1531756603/pages/817 )
[4] => Array ( [ID] => 815 [name] => i.3 Course Assessments – Why There Are Level Assessments [_more_] => /levels/1531756603/pages/815 )
[5] => Array ( [ID] => 813 [name] => i.2 Course Structure – How to Navigate the Web Platform [_more_] => /levels/1531756603/pages/813 )
[6] => Array ( [ID] => 807 [name] => Introduction to the Course [_more_] => /levels/1531756603/pages/807 )
[7] => Array ( [ID] => 659 [name] => INTRO LEVEL ASSESSMENT [_more_] => /levels/1531756603/pages/659 )
[8] => Array ( [ID] => 378 [name] => How This Course Will be Taught [_more_] => /levels/1531756603/pages/378 )
[9] => Array ( [ID] => 376 [name] => SCourse [_more_] => /levels/1531756603/pages/376 )
[10] => Array ( [ID] => 372 [name] => Dashboard [_more_] => /levels/1531756603/pages/372 ) )
[1] => Array ( [0] => Array ( [ID] => 2372 [name] => Profile Assignment [_more_] => /levels/1531866216/pages/2372 )
[1] => Array ( [ID] => 2110 [name] => Instructions [_more_] => /levels/1531866216/pages/2110 )
[2] => Array ( [ID] => 1619 [name] => Practicum [_more_] => /levels/1531866216/pages/1619 )
[3] => Array ( [ID] => 1048 [name] => Member Profile [_more_] => /levels/1531866216/pages/1048 )
[4] => Array ( [ID] => 571 [name] => LEVEL 1 [_more_] => /levels/1531866216/pages/571 )
[5] => Array ( [ID] => 506 [name] => 2.A ASSIGNMENTS [_more_] => /levels/1531866216/pages/506 )
[6] => Array ( [ID] => 504 [name] => 2.7 SUMMARY AND REVIEW [_more_] => /levels/1531866216/pages/504 )
[7] => Array ( [ID] => 502 [name] => 2.6 Your Brand is the Balancing Force [_more_] => /levels/1531866216/pages/502 )
[8] => Array ( [ID] => 497 [name] => 2.5 Brand Trust [_more_] => /levels/1531866216/pages/497 )
[9] => Array ( [ID] => 494 [name] => 2.4 Brand Beliefs [_more_] => /levels/1531866216/pages/494 )
[10] => Array ( [ID] => 491 [name] => 2.3 Brand Promise [_more_] => /levels/1531866216/pages/491 )
[11] => Array ( [ID] => 487 [name] => 2.2 Brand Story [_more_] => /levels/1531866216/pages/487 )
[12] => Array ( [ID] => 484 [name] => 2.1 Branding [_more_] => /levels/1531866216/pages/484 )
[13] => Array ( [ID] => 478 [name] => CHAPTER 2 CREATING THE BRAND HUB: FOUR KEY BRAND ELEMENTS [_more_] => /levels/1531866216/pages/478 )
[14] => Array ( [ID] => 473 [name] => LEVEL 1 ASSESSMENT [_more_] => /levels/1531866216/pages/473 )
[15] => Array ( [ID] => 464 [name] => 2.A-1 Brand Strategy Assignment [_more_] => /levels/1531866216/pages/464 )
[16] => Array ( [ID] => 461 [name] => 2.A-4 Student Instructions [_more_] => /levels/1531866216/pages/461 )
[17] => Array ( [ID] => 459 [name] => 2.A-3 Project Submission Form [_more_] => /levels/1531866216/pages/459 )
[18] => Array ( [ID] => 448 [name] => 1.A PRACTICUM ASSIGNMENTS [_more_] => /levels/1531866216/pages/448 )
[19] => Array ( [ID] => 445 [name] => 1.A-2 Topical Brainstorm Assignment [_more_] => /levels/1531866216/pages/445 )
[20] => Array ( [ID] => 432 [name] => 1.5 SUMMARY AND REVIEW [_more_] => /levels/1531866216/pages/432 )
[21] => Array ( [ID] => 427 [name] => 1.4 A New Inbound Model [_more_] => /levels/1531866216/pages/427 )
[22] => Array ( [ID] => 423 [name] => 1.3 The New Social Era of Marketing [_more_] => /levels/1531866216/pages/423 )
[23] => Array ( [ID] => 410 [name] => 1.2 Traditional Outbound Marketing vs. Digital Inbound Marketing [_more_] => /levels/1531866216/pages/410 )
[24] => Array ( [ID] => 394 [name] => 1.1 Consumer Acquisition from the Digital Landscape [_more_] => /levels/1531866216/pages/394 )
[25] => Array ( [ID] => 392 [name] => CHAPTER 1 INTRODUCING [_more_] => /levels/1531866216/pages/392 )
[26] => Array ( [ID] => 318 [name] => Project Submission Thank You [_more_] => /levels/1531866216/pages/318 ) ) )

Body:
Loop through the array like so.

foreach($pages_array_name['0'] as $index => $sub_array) {
   echo "index is " . $index . "\n<br/>";
   echo "name is " . $sub_array['name'] . "\n<br/>";
   echo "_more_ is " . $sub_array['_more_'] . "\n<br/>";
   echo "\n<br/>"; // extra space
}