问:
Can't import QtMultimedia in PyQt 5 on Windows
I'm trying to learn PyQt5 + qml, and everything I tried so far works fine, however I've ran into a snag when trying to import QtMultimedia into my qml file results in the following error:

plugin cannot be loaded for module "QtMultimedia": Cannot load library
  D:\py35venvQt\lib\site-packages\PyQt5\Qt\qml\QtMultimedia\declarative_multimedia.dll:
  The specified module could not be found.

main.qml:

```<code>import QtQuick 2.8
import QtQuick.Window 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.1
import QtMultimedia 5.6

Window {
  id: root
  visible: true
  title: 'my pyqt app'
  width: 1280
  height: 720

}
</code>```

main.py

```<code>if __name__ == '__main__':
    def handleStatusChange(status):
        if status == QQuickView.Error:
            errors = appLabel.errors()
            if errors:
                print (errors[0].description())

    myApp = QApplication(sys.argv)
    appLabel = QQuickView()
    appLabel.statusChanged.connect(handleStatusChange)
    model = models.ActorModel(DB_PATH)
    ctxt = appLabel.rootContext()
    ctxt.setContextProperty('myModel', model)
    appLabel.setSource(QUrl('./qml/main/main.qml'))

    try:
        sys.exit(myApp.exec_())
    except:
        print("Exiting")
</code>```

Without the QtMultimedia import everything works fine, also I've tried all Possible version of QtMultimedia (5.0,5.1 etc). In addition the dll does exist in the correct path.

When searching for a solution online I found some post saying that QtMultimedia is not supported in PyQt5, though I think those posts are too old.

I would appreciate it if someone would shed some light on this situation,
Thank you.

Edit: Python Version 3.5.2 PyQt Version 5.8.
PyQt installation process: new virtualenv -> pip install pyqt5

Edit2: Tried reinstalling to a completely new virtual environment using pip3 install pyqt5 still getting the same error.

Edit3: According to http://www.dependencywalker.com the following dlls can not be found in the dir where declarative_multimedia.dll is:

QT5MULTIMEDIA.DLL QT5QUICK.DLL QT5GUI.DLL QT5QML.DLL QT5CORE.DLL
  QT5MULTIMEDIAQUICK_P.DLL

With the exception of QT5MULTIMEDIAQUICK_P.DLL they are all present in the \Lib\site-packages\PyQt5\Qt\bin directory

QT5MULTIMEDIAQUICK_P.DLL is not present at all.

I tried copying all the missing files into \Lib\site-packages\PyQt5\Qt\qml\QtMultimedia to see if it would make any difference. It did not.

I also tried to install PyQt 5 into my proper python 3.5 installation (without virtualenv) and running my code. The result is the same.

答:
I had similar issue on Ubuntu and I solved my problem by adding environment variable LD_LIBRARY_PATH=/home/slav/Apps/Qt5.9.2/5.9.2/gcc_64/lib.

"/home/slav/Apps/Qt5.9.2/5.9.2/gcc_64/lib" here I've install Qt with QtInstaller

Body:
I'm trying to learn PyQt5 + qml, and everything I tried so far works fine, however I've ran into a snag when trying to import QtMultimedia into my qml file results in the following error:

plugin cannot be loaded for module "QtMultimedia": Cannot load library
  D:\py35venvQt\lib\site-packages\PyQt5\Qt\qml\QtMultimedia\declarative_multimedia.dll:
  The specified module could not be found.

main.qml:

import QtQuick 2.8
import QtQuick.Window 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.1
import QtMultimedia 5.6

Window {
  id: root
  visible: true
  title: 'my pyqt app'
  width: 1280
  height: 720

}

main.py

if __name__ == '__main__':
    def handleStatusChange(status):
        if status == QQuickView.Error:
            errors = appLabel.errors()
            if errors:
                print (errors[0].description())

    myApp = QApplication(sys.argv)
    appLabel = QQuickView()
    appLabel.statusChanged.connect(handleStatusChange)
    model = models.ActorModel(DB_PATH)
    ctxt = appLabel.rootContext()
    ctxt.setContextProperty('myModel', model)
    appLabel.setSource(QUrl('./qml/main/main.qml'))

    try:
        sys.exit(myApp.exec_())
    except:
        print("Exiting")

Without the QtMultimedia import everything works fine, also I've tried all Possible version of QtMultimedia (5.0,5.1 etc). In addition the dll does exist in the correct path.

When searching for a solution online I found some post saying that QtMultimedia is not supported in PyQt5, though I think those posts are too old.

I would appreciate it if someone would shed some light on this situation,
Thank you.

Edit: Python Version 3.5.2 PyQt Version 5.8.
PyQt installation process: new virtualenv -> pip install pyqt5

Edit2: Tried reinstalling to a completely new virtual environment using pip3 install pyqt5 still getting the same error.

Edit3: According to http://www.dependencywalker.com the following dlls can not be found in the dir where declarative_multimedia.dll is:

QT5MULTIMEDIA.DLL QT5QUICK.DLL QT5GUI.DLL QT5QML.DLL QT5CORE.DLL
  QT5MULTIMEDIAQUICK_P.DLL

With the exception of QT5MULTIMEDIAQUICK_P.DLL they are all present in the \Lib\site-packages\PyQt5\Qt\bin directory

QT5MULTIMEDIAQUICK_P.DLL is not present at all.

I tried copying all the missing files into \Lib\site-packages\PyQt5\Qt\qml\QtMultimedia to see if it would make any difference. It did not.

I also tried to install PyQt 5 into my proper python 3.5 installation (without virtualenv) and running my code. The result is the same.


来源: stackexchange

问:
PowerShell 5 Copy-Item not working
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

```<code>Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf
</code>```

First I used

```<code> $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"
</code>```

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

```<code> PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}
</code>```

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks

答:
You almost have it right, $_ is only grabbing the filename, so you lose the path and it tries to use the path your running the script from.  Use this instead which will keep the full path.

Get-ChildItem -Recurse $source -Filter "*.pdf" | % {Copy-Item $_.FullName -Destination $desti}

ContentLicense: CC BY-SA 3.0

Title: PowerShell 5 Copy-Item not working

Body:
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf

First I used

 $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

 PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks


问:
Modifying font size for pie chart lables
I am using a simple script for a pie chart, but I am unable to change the font size of the pie labels. Is there an easy way to change it?

Below is my plotting code:

```<code>h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly
ax = gca();
set(ax,'fontsize', 18);
view([270, -90])
</code>```

答:
To programmatically set the fontsize or any other property of graphical elements of a certain type you should use the findobj() function to find all elements of this type. Then you can use a single set command to set properties. In your example you have to write:

```<code>set(findobj(h,'type','text'),'fontsize',18)
</code>```

This will change all font sizes of all text elements in the pie chart.

Complete Example

I adapted your example to show the effect:

```<code>h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly

view([270, -90])
set(findobj(h,'type','text'),'fontsize',18);
</code>```

Graphical Output

Body:
I am using a simple script for a pie chart, but I am unable to change the font size of the pie labels. Is there an easy way to change it?

Below is my plotting code:

h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly
ax = gca();
set(ax,'fontsize', 18);
view([270, -90])

Body:
To programmatically set the fontsize or any other property of graphical elements of a certain type you should use the findobj() function to find all elements of this type. Then you can use a single set command to set properties. In your example you have to write:

set(findobj(h,'type','text'),'fontsize',18)

This will change all font sizes of all text elements in the pie chart.

Complete Example

I adapted your example to show the effect:

h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly

view([270, -90])
set(findobj(h,'type','text'),'fontsize',18);

Graphical Output


问:
How to write a bash script to give another program response
I have a bash script that does several tasks, including python manage.py syncdb on a fresh database. This command asks for input, like the login info for the admin. Currently, I just type this into the command line every time. Is there a way I can automatically provide these replies as part of the bash script?

Thanks, I don't really know anything about bash.

I'm using Ubuntu 10.10.

答:
If the program in question cannot read the input from stdin such as:

```<code>echo "some input" | your_progam
</code>```

then you'll need to look to something like expect and/or autoexepect

ContentLicense: CC BY-SA 2.5

Body:
If the program in question cannot read the input from stdin such as:

echo "some input" | your_progam

then you'll need to look to something like expect and/or autoexepect


问:
Match list of substrings and strings and return substring if it matches
I've seen may questions on this topic but most are the opposite of mine. I have a list of strings (column of a data frame) and a list of sub strings. I want to compare each string to the list of sub strings If it contains a sub string then return that sub-string else print 'no match'.

```<code>    subs = [cat, dog, mouse]

    df

      Name       Number     SubMatch
     dogfood      1           dog
     catfood      3           cat
     dogfood      2           dog
     mousehouse   1           mouse
     birdseed     1           no match
</code>```

my current output looks like this though:

```<code>     Name       Number     SubMatch
     dogfood      1           dog
     catfood      3           dog
     dogfood      2           dog
     mousehouse   1           dog
     birdseed     1           dog
</code>```

I suspect my code is just returning the first thing in the series, how do I change that to the correct thing in the series? Here is the Function:

```<code>    def matchy(col, subs):
        for name in col:
            for s in subs:
                if any(s in name for s in subs):
                    return s
                else:
                    return 'No Match'
</code>```

答:
Unless there is code missing that accounts for it, it would appear that your code returns the result for the very first comparison, and actually does not look at any of the other items in the col list. If you would rather stick with nested loops, I would suggest modifying your code like so:

```<code>def matchy(col, subs):
    subMatch = []
    for name in col:
        subMatch.append('No Match')
        for s in subs:
            if s in name:
                subMatch[-1] = s
                break
    return subMatch
</code>```

This assumes that col is a list of strings containing the column information (dogfood, mousehouse, etc) and that subs is a list of strings containing the substrings you wish to search for. subMatch is a list of strings returned by matchy that contains the search results for each item in col.

For each value in col we examine, we append the 'No Match' string to subMatch, basically assuming we did not find a match. Then we iterate through subs, checking to see if the substring s is contained within name. If there is a match, then subMatch[-1] = s replaces the most recent 'No Match' we appended with the matching substring, then we break to move onto the next item in col since we don't need to search for any more values. Note that subMatch[-1] = s can be replaced with other methods, such as doing subMatch.pop() followed by subMatch.append(s), though at that point I think it is more personal preference. Once all elements in col have been checked, subMatch is returned, at which point you can then process it however you like.

Body:
I've seen may questions on this topic but most are the opposite of mine. I have a list of strings (column of a data frame) and a list of sub strings. I want to compare each string to the list of sub strings If it contains a sub string then return that sub-string else print 'no match'.

    subs = [cat, dog, mouse]

    df

      Name       Number     SubMatch
     dogfood      1           dog
     catfood      3           cat
     dogfood      2           dog
     mousehouse   1           mouse
     birdseed     1           no match

my current output looks like this though:

     Name       Number     SubMatch
     dogfood      1           dog
     catfood      3           dog
     dogfood      2           dog
     mousehouse   1           dog
     birdseed     1           dog

I suspect my code is just returning the first thing in the series, how do I change that to the correct thing in the series? Here is the Function:

    def matchy(col, subs):
        for name in col:
            for s in subs:
                if any(s in name for s in subs):
                    return s
                else:
                    return 'No Match'

Body:
Unless there is code missing that accounts for it, it would appear that your code returns the result for the very first comparison, and actually does not look at any of the other items in the col list. If you would rather stick with nested loops, I would suggest modifying your code like so:

def matchy(col, subs):
    subMatch = []
    for name in col:
        subMatch.append('No Match')
        for s in subs:
            if s in name:
                subMatch[-1] = s
                break
    return subMatch

This assumes that col is a list of strings containing the column information (dogfood, mousehouse, etc) and that subs is a list of strings containing the substrings you wish to search for. subMatch is a list of strings returned by matchy that contains the search results for each item in col.

For each value in col we examine, we append the 'No Match' string to subMatch, basically assuming we did not find a match. Then we iterate through subs, checking to see if the substring s is contained within name. If there is a match, then subMatch[-1] = s replaces the most recent 'No Match' we appended with the matching substring, then we break to move onto the next item in col since we don't need to search for any more values. Note that subMatch[-1] = s can be replaced with other methods, such as doing subMatch.pop() followed by subMatch.append(s), though at that point I think it is more personal preference. Once all elements in col have been checked, subMatch is returned, at which point you can then process it however you like.


问:
Using a CMake cache variable "before" it is defined
CMake cache variables can be set from virtually everywhere (see here @Florian's What's the CMake syntax to set and use variables?). I was under the assumption that the set value is visible everywhere, even to CMake lists parsed before, but this isn't the case.

Use case

Module A uses ${CMAKE_MYDEF}.

Module B sets the cache variable CMAKE_MYDEF.

add_subdirectory(A) is called before add_subdirectory(B).

Short example showing the behavior

```<code>cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_compile_definitions(EXEC PRIVATE MYDEF=${CMAKE_MYDEF})
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
</code>```

Questions

How can I make sure CMAKE_MYDEF has the desired value regardless the order I add module A and module B?

Are there any ways to ensure the CMake configuration step is re-run twice or, if applicable, as long as the cache variables get changed? (This isn't probably a clean solution, but since I'm working with legacy code not everything can be done beautifully.)

Are there alternatives to cache variables to achieve the same result without re-running the CMake configuration by hand?

Is it possible to set compiler definitions in the generation phase (i.e. when all CMake cache variables are known and set)? Using some kind of generator expressions?

Edit: Short example solution

Following @Florian's answer, here the adapted example showing the solution:

```<code>cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_link_libraries(EXEC MyOtherLib)

add_library(MyOtherLib INTERFACE)
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
target_compile_definitions(MyOtherLib INTERFACE MYDEF=${CMAKE_MYDEF})
</code>```

答:
Yes, I'm fully with @Tsyvarev's answer that CMake's parser works sequentially. So variables - even cached ones - or generator expressions - that can't read variables - are no good here.

I just wanted to add the possibilities you have using target and directory properties depending on the dependencies between A and B:

When A depends on B with e.g.

```<code>target_link_libraries(A PUBLIC B)
</code>```

then a simple

```<code>target_compile_definitions(B PUBLIC MYDEF=SOME_DEF)
</code>```

would propagate the necessary define to A.

When B depends an A and A is already known than it would be

```<code>target_link_libraries(B PUBLIC A)
target_compile_definitions(A PUBLIC MYDEF=SOME_OTHER_DEF)
</code>```

If you're working with sub-directories I would recommend putting the definition in the root CMakeLists.txt globally:

```<code>add_definitions(-DMYDEF=GLOBAL_DEF)
</code>```

Finally the full variant with sub-directories letting B decide what to do:

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)

project(test)

add_subdirectory(A)
add_subdirectory(B)
```

<p><strong>A\CMakeLists.txt</strong></p>

<pre class="lang-perl prettyprint-override"><code>file(WRITE a.cpp [=[
#include <iostream>

#ifndef MYDEF
#define MYDEF "Hello from A!"
#endif

void a()
{
    std::cout << MYDEF << std::endl;
}
]=])

add_library(A a.cpp)
</code>```

B\CMakeLists.txt

file(WRITE b.cpp [=[

void a();

void main()
{
    a();
}
]=])

add_executable(B b.cpp)
target_link_libraries(B A)

if (TARGET "A")
    target_compile_definitions(A PRIVATE MYDEF="Hello from B!")
else()
    set_property(
        DIRECTORY ".."
        APPEND PROPERTY
            COMPILE_DEFINITIONS "MYDEF=\"Hello from Global!\""
    )
endif()
```

Reference

Is Cmake set variable recursive?

Body:
CMake cache variables can be set from virtually everywhere (see here @Florian's What's the CMake syntax to set and use variables?). I was under the assumption that the set value is visible everywhere, even to CMake lists parsed before, but this isn't the case.

Use case

Module A uses ${CMAKE_MYDEF}.

Module B sets the cache variable CMAKE_MYDEF.

add_subdirectory(A) is called before add_subdirectory(B).

Short example showing the behavior

cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_compile_definitions(EXEC PRIVATE MYDEF=${CMAKE_MYDEF})
set(CMAKE_MYDEF "MyValue" CACHE STRING "")

Questions

How can I make sure CMAKE_MYDEF has the desired value regardless the order I add module A and module B?

Are there any ways to ensure the CMake configuration step is re-run twice or, if applicable, as long as the cache variables get changed? (This isn't probably a clean solution, but since I'm working with legacy code not everything can be done beautifully.)

Are there alternatives to cache variables to achieve the same result without re-running the CMake configuration by hand?

Is it possible to set compiler definitions in the generation phase (i.e. when all CMake cache variables are known and set)? Using some kind of generator expressions?

Edit: Short example solution

Following @Florian's answer, here the adapted example showing the solution:

cmake_minimum_required(VERSION 3.7)
project(test)
add_executable(EXEC test.cpp)
target_link_libraries(EXEC MyOtherLib)

add_library(MyOtherLib INTERFACE)
set(CMAKE_MYDEF "MyValue" CACHE STRING "")
target_compile_definitions(MyOtherLib INTERFACE MYDEF=${CMAKE_MYDEF})

Body:
Yes, I'm fully with @Tsyvarev's answer that CMake's parser works sequentially. So variables - even cached ones - or generator expressions - that can't read variables - are no good here.

I just wanted to add the possibilities you have using target and directory properties depending on the dependencies between A and B:

When A depends on B with e.g.

target_link_libraries(A PUBLIC B)

then a simple

target_compile_definitions(B PUBLIC MYDEF=SOME_DEF)

would propagate the necessary define to A.

When B depends an A and A is already known than it would be

target_link_libraries(B PUBLIC A)
target_compile_definitions(A PUBLIC MYDEF=SOME_OTHER_DEF)

If you're working with sub-directories I would recommend putting the definition in the root CMakeLists.txt globally:

add_definitions(-DMYDEF=GLOBAL_DEF)

Finally the full variant with sub-directories letting B decide what to do:

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)

project(test)

add_subdirectory(A)
add_subdirectory(B)

A\CMakeLists.txt

file(WRITE a.cpp [=[
#include <iostream>

#ifndef MYDEF
#define MYDEF "Hello from A!"
#endif

void a()
{
    std::cout << MYDEF << std::endl;
}
]=])

add_library(A a.cpp)

B\CMakeLists.txt

file(WRITE b.cpp [=[

void a();

void main()
{
    a();
}
]=])

add_executable(B b.cpp)
target_link_libraries(B A)

if (TARGET "A")
    target_compile_definitions(A PRIVATE MYDEF="Hello from B!")
else()
    set_property(
        DIRECTORY ".."
        APPEND PROPERTY
            COMPILE_DEFINITIONS "MYDEF=\"Hello from Global!\""
    )
endif()

Reference

Is Cmake set variable recursive?


问:
A global method that finds the average, and the highest speed of cars
I created the Car class with attributes and properties. In the main part of the program, I created a series of cars and initialized the values.

My program should use the global method to find the fastest car and average speed of all cars, the method must also return two results.

I tried to make This method, I made for a loop that will pass through every speed individually and  split it with the total number of cars in a row, then added to the variable average, does this make sense?

To find the fastest car in a row, I'm not sure how to do it, so I asked myself the question.

Can anyone explain to me about this speed finding algorithm in the global method and also generally about the whole task if I made a mistake in the definition of the same method?

```<code>class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }
}
</code>```

This is main program

```<code>class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}
</code>```

答:
Unless performance is critical, doing it multiple steps is fine:

```<code>a) find the maximum speed (hint: you can use .Select(..) and .Max( ) from System.Linq)
b) then find the car (s) that have that speed (.Where(...))
c) calculating the average can likewise been done using .Select( ) and .Average( )
</code>```

Yes, in principle you could do it all in a single hand-written loop but at the cost of readability/maintainability.

Body:
I created the Car class with attributes and properties. In the main part of the program, I created a series of cars and initialized the values.

My program should use the global method to find the fastest car and average speed of all cars, the method must also return two results.

I tried to make This method, I made for a loop that will pass through every speed individually and  split it with the total number of cars in a row, then added to the variable average, does this make sense?

To find the fastest car in a row, I'm not sure how to do it, so I asked myself the question.

Can anyone explain to me about this speed finding algorithm in the global method and also generally about the whole task if I made a mistake in the definition of the same method?

class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }
}

This is main program

class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}

Body:
Unless performance is critical, doing it multiple steps is fine:

a) find the maximum speed (hint: you can use .Select(..) and .Max( ) from System.Linq)
b) then find the car (s) that have that speed (.Where(...))
c) calculating the average can likewise been done using .Select( ) and .Average( )

Yes, in principle you could do it all in a single hand-written loop but at the cost of readability/maintainability.


问:
iOS 11 navigation bar transparent with large titles
I have default preferences for uinavigationbar:

```<code>UINavigationBar.appearance().barTintColor = .red
        UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        if #available(iOS 11.0, *) {
            UINavigationBar.appearance().largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        }
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().tintColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)
</code>```

Structure: UINaviagtionController -> PostsTableViewController -> PostTableViewController.

I want to have large navigation bar on PostsViewController (with opaque background color) and transparent navigation bar on PostViewController.

In PostTableViewController i add:

```<code>self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.barTintColor = .clear

        self.automaticallyAdjustsScrollViewInsets = false
        //self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        //self.navigationController?.navigationBar.shadowImage = UIImage()
        if #available(iOS 11.0, *) {
            print("asd")
            self.tableView.insetsContentViewsToSafeArea = false
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
</code>```

Navigation bar is BLACK. I dont understand how make it transparent...

UPDATE:

git hub repository: https://github.com/Mazorati/testnavbar

i set isTranslucent = true, but large navigation becomes also transparent. Only default navigation is ok.

But i want navigationbar color to be opaque, so:

```<code>self.navigationController?.view.backgroundColor = .red
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic
</code>```

As the result:

3D layers:

答:
have you tried changing it to translucent?

```<code>self.navigationController?.navigationBar.isTranslucent = true
</code>```

UPDATE:

You must remember that the navigation bar belongs to the UINavigationController which holds the views inside it, so that when you change it in one it changes for all.

The solution would be to change it to translucent in the second view controller's viewWillAppear method and change it to not translucent in the viewDidDissapear method. Play with the viewWill and viewDid appear methods until you find the right one for your needs.

Body:
I have default preferences for uinavigationbar:

UINavigationBar.appearance().barTintColor = .red
        UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        if #available(iOS 11.0, *) {
            UINavigationBar.appearance().largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        }
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().tintColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)

Structure: UINaviagtionController -> PostsTableViewController -> PostTableViewController.

I want to have large navigation bar on PostsViewController (with opaque background color) and transparent navigation bar on PostViewController.

In PostTableViewController i add:

self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.barTintColor = .clear

        self.automaticallyAdjustsScrollViewInsets = false
        //self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        //self.navigationController?.navigationBar.shadowImage = UIImage()
        if #available(iOS 11.0, *) {
            print("asd")
            self.tableView.insetsContentViewsToSafeArea = false
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }

Navigation bar is BLACK. I dont understand how make it transparent...

UPDATE:

git hub repository: https://github.com/Mazorati/testnavbar

i set isTranslucent = true, but large navigation becomes also transparent. Only default navigation is ok.

But i want navigationbar color to be opaque, so:

self.navigationController?.view.backgroundColor = .red
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic

As the result:

3D layers:

Body:
have you tried changing it to translucent?

self.navigationController?.navigationBar.isTranslucent = true

UPDATE:

You must remember that the navigation bar belongs to the UINavigationController which holds the views inside it, so that when you change it in one it changes for all.

The solution would be to change it to translucent in the second view controller's viewWillAppear method and change it to not translucent in the viewDidDissapear method. Play with the viewWill and viewDid appear methods until you find the right one for your needs.


问:
In Ruby, is there a way to remove only 1 match in an Array easily?
In Ruby, the array subtraction or reject

```<code>>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]
</code>```

will remove all entries in the array.  Is there an easy to remove just 1 occurrence?

答:
The best I can think of is:

```<code>found = false
[1,3,5,7,7].reject{|i| found = true if !found && i == 7}
</code>```

Or destructively:

```<code>arr = [1, 2, 3, 5, 7, 7]
arr.delete_at( arr.index(7))
arr #=> [1, 2, 3, 5, 7]
</code>```

Body:
In Ruby, the array subtraction or reject

>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]

will remove all entries in the array.  Is there an easy to remove just 1 occurrence?

Body:
The best I can think of is:

found = false
[1,3,5,7,7].reject{|i| found = true if !found && i == 7}

Or destructively:

arr = [1, 2, 3, 5, 7, 7]
arr.delete_at( arr.index(7))
arr #=> [1, 2, 3, 5, 7]


问:
input javascript checked - unchecked
I have input in body of my html page:

```<code><input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked"/>
</code>```

And in script there is:

```<code>  function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked" />
</code>```

But, for some reason, it doesn't work ... My input should be clicked by default, and user can unclick it if he chooses to.

Perhaps, there is some mistake in my code, so, im asking for help. Thanks

答:
oninput event will not work in checkbox or radio use onchange event.

```<code><input id="showElement" type="checkbox" onchange="onShowElementChange()" checked="checked"/>
</code>```

And you can also try like below will work.

```<code><input id="showElement" type="checkbox" onchange="onShowElementChange(this.checked)" checked="checked"/>
</code>```

JavaScript

```<code>function onShowElementChange(checked) {
  console.log(checked);
}
</code>```

Title: input javascript checked - unchecked

Body:
I have input in body of my html page:

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked"/>

And in script there is:

  function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked" />

But, for some reason, it doesn't work ... My input should be clicked by default, and user can unclick it if he chooses to.

Perhaps, there is some mistake in my code, so, im asking for help. Thanks

Body:
oninput event will not work in checkbox or radio use onchange event.

<input id="showElement" type="checkbox" onchange="onShowElementChange()" checked="checked"/>

And you can also try like below will work.

<input id="showElement" type="checkbox" onchange="onShowElementChange(this.checked)" checked="checked"/>

JavaScript

function onShowElementChange(checked) {
  console.log(checked);
}


问:
Line up label with fa icon in my navbar with css
I may be being a bit of a perfectionist but I want my text to line up with the centre of the icon...

I would like to move the compass down a few pixels but using padding and margin just changes the size of the menubar they reside in. Also position relative and bottom moves both.

My code is

```<code><p class="nav navbar-nav navbar-left" id="townlabel">
<i class="fa fa-compass fa-2x" id="compassicon"></i>Glastonbury
</p>
</code>```

Css

```<code>#townlabel {
display: inline-block;
}
#compassicon {
display: inline-block;
margin: 5px;
}
</code>```

答:
You can use vertical-align: middle to fix this.

```<code>#townlabel * {
  display: inline-block;
  vertical-align: middle;
}
</code>```

https://jsfiddle.net/tudrLv03/

Body:
I may be being a bit of a perfectionist but I want my text to line up with the centre of the icon...

I would like to move the compass down a few pixels but using padding and margin just changes the size of the menubar they reside in. Also position relative and bottom moves both.

My code is

Glastonbury

Css

#townlabel {
display: inline-block;
}
#compassicon {
display: inline-block;
margin: 5px;
}

Body:
You can use vertical-align: middle to fix this.

#townlabel * {
  display: inline-block;
  vertical-align: middle;
}

https://jsfiddle.net/tudrLv03/


答:
Try:

```<code>#compassicon {
    display: inline-block;
    margin: 0 5px 0 0;
    vertical-align: middle;
}
</code>```

If that doesn't work, then this will, although it's the less "correct" way to do it:

```<code>#compassicon {
    display: inline-block;
    position: relative;
    top: 5px;
    margin: 0 5px 0 0;
}
</code>```

You may need to adjust the top value to get it exactly how you want it.

Title: Line up label with fa icon in my navbar with css

Body:
Try:

#compassicon {
    display: inline-block;
    margin: 0 5px 0 0;
    vertical-align: middle;
}

If that doesn't work, then this will, although it's the less "correct" way to do it:

#compassicon {
    display: inline-block;
    position: relative;
    top: 5px;
    margin: 0 5px 0 0;
}

You may need to adjust the top value to get it exactly how you want it.


问:
How do I use NSSecureCoding to guarantee the content of collection classes?
I have an object of class SGBContainer which has an array named objects that contains objects of class SGBObject.  Currently, they each implement NSCoding but not NSSecureCoding.  The -initWithCoder: for SGBContainer looks like this:

```<code>- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [self init];
    if (self)
    {
        _objects = [aCoder decodeObjectForKey:@"objects"];
    }
}
</code>```

I want to switch to using NSSecureCoding, and from what I can tell, it would mean changing the above to this:

```<code>- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [self init];
    if (self)
    {
        _objects = [aCoder decodeObjectOfClass:[NSArray class] forKey:@"objects"];
    }
}
</code>```

...which isn't much of an improvement, as the contents of the array will be instantiated whatever their class.  How do I make sure that the array only contains objects of class SGBObject without instantiating them?

答:
Sean D.'s answer is correct to unblock the code, but there is one caveat: the foundation does not guarantee the class types inside of the array, IF they are foundation classes. E.g. the following code demonstrates the problem:</p>

```<code>@implementation Serializable
- (id)initWithCoder:(NSCoder *)aDecoder {
  return [super init];
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
}
+ (BOOL)supportsSecureCoding {
  return YES;
}
@end

int main(int argc, const char * argv[]) {

  NSArray *foo = @[ @1, @"Gotcha", [Serializable new] ];
  NSMutableData *archive = [NSMutableData data];
  NSKeyedArchiver *archiver =
      [[NSKeyedArchiver alloc] initForWritingWithMutableData:archive];
  archiver.requiresSecureCoding = YES;
  [archiver encodeObject:foo forKey:@"root"];
  [archiver finishEncoding];

  NSKeyedUnarchiver *unarchiver =
     [[NSKeyedUnarchiver alloc] initForReadingWithData:archive];
  unarchiver.requiresSecureCoding = YES;
  NSSet *classes = [NSSet setWithArray:@[ [NSArray class], [Serializable class] ]];
  // Should throw, but it does not.
  NSArray *loaded = [unarchiver decodeObjectOfClasses:classes forKey:NSKeyedArchiveRootObjectKey];
  if (loaded.count > 2 && ![loaded[0] isKindOfClass:[Serializable class]]) {
    NSLog(@"Successfully performed object substitution attack.");
    NSLog(@"Class: %@", [loaded[0] class]);  // All 3 objects are
    return 1;
  }
  return 0;
}
</code>```

Body:
I have an object of class SGBContainer which has an array named objects that contains objects of class SGBObject.  Currently, they each implement NSCoding but not NSSecureCoding.  The -initWithCoder: for SGBContainer looks like this:

- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [self init];
    if (self)
    {
        _objects = [aCoder decodeObjectForKey:@"objects"];
    }
}

I want to switch to using NSSecureCoding, and from what I can tell, it would mean changing the above to this:

- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [self init];
    if (self)
    {
        _objects = [aCoder decodeObjectOfClass:[NSArray class] forKey:@"objects"];
    }
}

...which isn't much of an improvement, as the contents of the array will be instantiated whatever their class.  How do I make sure that the array only contains objects of class SGBObject without instantiating them?

Body:
Sean D.'s answer is correct to unblock the code, but there is one caveat: the foundation does not guarantee the class types inside of the array, IF they are foundation classes. E.g. the following code demonstrates the problem:

@implementation Serializable
- (id)initWithCoder:(NSCoder *)aDecoder {
  return [super init];
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
}
+ (BOOL)supportsSecureCoding {
  return YES;
}
@end

int main(int argc, const char * argv[]) {

  NSArray *foo = @[ @1, @"Gotcha", [Serializable new] ];
  NSMutableData *archive = [NSMutableData data];
  NSKeyedArchiver *archiver =
      [[NSKeyedArchiver alloc] initForWritingWithMutableData:archive];
  archiver.requiresSecureCoding = YES;
  [archiver encodeObject:foo forKey:@"root"];
  [archiver finishEncoding];

  NSKeyedUnarchiver *unarchiver =
     [[NSKeyedUnarchiver alloc] initForReadingWithData:archive];
  unarchiver.requiresSecureCoding = YES;
  NSSet *classes = [NSSet setWithArray:@[ [NSArray class], [Serializable class] ]];
  // Should throw, but it does not.
  NSArray *loaded = [unarchiver decodeObjectOfClasses:classes forKey:NSKeyedArchiveRootObjectKey];
  if (loaded.count > 2 && ![loaded[0] isKindOfClass:[Serializable class]]) {
    NSLog(@"Successfully performed object substitution attack.");
    NSLog(@"Class: %@", [loaded[0] class]);  // All 3 objects are
    return 1;
  }
  return 0;
}


问:
Datediff on one Date Field. Issues with grouping by
I have a data set like: https://i.stack.imgur.com/pYiMr.png

I want to calculate the difference it takes to go from max of processing to min of received.

Here is the desired output table: https://i.stack.imgur.com/2juJH.png

Here is the Calculated field I have written so:

```<code>{

INCLUDE [Tracking Item status]:

MIN([Created Date])- MAX([Created Date])

}
</code>```

答:
I think this should work:</p>

```<code>{fixed [tracking_item], [tracking_item_status] : Max([created_date])} - {fixed [tracking_item], [tracking_item_status] : Min([created_date])}
</code>```

Body:
I have a data set like: https://i.stack.imgur.com/pYiMr.png

I want to calculate the difference it takes to go from max of processing to min of received.

Here is the desired output table: https://i.stack.imgur.com/2juJH.png

Here is the Calculated field I have written so:

{

INCLUDE [Tracking Item status]:

MIN([Created Date])- MAX([Created Date])

}

Body:
I think this should work:

{fixed [tracking_item], [tracking_item_status] : Max([created_date])} - {fixed [tracking_item], [tracking_item_status] : Min([created_date])}


问:
What's the time to release the image of the imageView?
I create a UIImage and set to the property of the imageView, then I release the currentImg,
whether there is a problem in these code ?

```<code>self.currentContentImv = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 1024, 768)];
UIImage *currentImg = [[UIImage alloc] initWithContentsOfFile: @"whatever..."]];
self.currentContentImv.image = currentImg;
[currentImg release];
</code>```

Sometimes it will be crash, so in this situation how could I write it?

Thanks very much!

答:
It looks like you are releasing the currentImg properly.  In this circumstance, you may want to create the UIImage using the static +imageWithContentsOfFile: method.  This will automatically add currentImg to the autorelease pool.

```<code>UIImage *currentImg = [UIImage imageWithContentsOfFile: @"whatever..."];
</code>```

Body:
I create a UIImage and set to the property of the imageView, then I release the currentImg,
whether there is a problem in these code ?

self.currentContentImv = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 1024, 768)];
UIImage *currentImg = [[UIImage alloc] initWithContentsOfFile: @"whatever..."]];
self.currentContentImv.image = currentImg;
[currentImg release];

Sometimes it will be crash, so in this situation how could I write it?

Thanks very much!

Body:
It looks like you are releasing the currentImg properly.  In this circumstance, you may want to create the UIImage using the static +imageWithContentsOfFile: method.  This will automatically add currentImg to the autorelease pool.

UIImage *currentImg = [UIImage imageWithContentsOfFile: @"whatever..."];


问:
How to refresh a List View in admin on rest
I am trying to get a list to refresh after a custom action was successfully executed.

i used the saga from the admin on rest tutorial

```<code>function * actionApproveSuccess () {
  yield put(showNotification('Executed'))
  yield put(push('/comments'))
  // does not refresh, because the route does not change
  // react-redux-router also has no refresh() method, like react-router has...
}
</code>```

the other idea i had was to somehow trigger the refresh action of the list component, but i have no idea how to access that or how to hook that up to the ACTION_SUCCESS event.

答:
using refreshView action via redux works well.  </p>

<p>see example....  </p>

```<code>import { refreshView as refreshViewAction } from 'admin-on-rest';
import { connect } from 'react-redux';

class MyReactComponent extends Component {
  //... etc etc standard react stuff...

 doSomething() {
    // etc etc do smt then trigger refreshView like below
    this.props.refreshView();
 }
 render() {
   return <div>etc etc your stuff</div>
 }
}

export default connect(undefined, { refreshView: refreshViewAction })(
  MyReactComponent
);
</code>```

Body:
I am trying to get a list to refresh after a custom action was successfully executed.

i used the saga from the admin on rest tutorial

function * actionApproveSuccess () {
  yield put(showNotification('Executed'))
  yield put(push('/comments'))
  // does not refresh, because the route does not change
  // react-redux-router also has no refresh() method, like react-router has...
}

the other idea i had was to somehow trigger the refresh action of the list component, but i have no idea how to access that or how to hook that up to the ACTION_SUCCESS event.

Body:
using refreshView action via redux works well.

see example....

import { refreshView as refreshViewAction } from 'admin-on-rest';
import { connect } from 'react-redux';

class MyReactComponent extends Component {
  //... etc etc standard react stuff...

 doSomething() {
    // etc etc do smt then trigger refreshView like below
    this.props.refreshView();
 }
 render() {
   return <div>etc etc your stuff</div>
 }
}

export default connect(undefined, { refreshView: refreshViewAction })(
  MyReactComponent
);


问:
fade in/out highlight to zebra striped table
I have a table with a number of data rows, which is zebra striped using the following CSS:

```<code>#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}
</code>```

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

```<code>$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}
</code>```

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

答:
Just put the transition on a rule that is not removed from the element.

setTimeout(function() {
  $('#row_id').addClass("temphighlight");
  setTimeout(clearHighlighting, 3000);
}, 2000);

function clearHighlighting() {
  $("#row_id").removeClass("temphighlight");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#datatable tr {
  transition: background 2.0s ease;
}

#datatable tr:nth-child(odd) {
  background-color: #fff;
}

#datatable tr:nth-child(even) {
  background-color: #fafafa;
}

#datatable tr.temphighlight {
  background-color: #c6efce;
}</code>```

    One

    Two

    Three

    Four

```

Body:
I have a table with a number of data rows, which is zebra striped using the following CSS:

#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

Body:
Just put the transition on a rule that is not removed from the element.

setTimeout(function() {
  $('#row_id').addClass("temphighlight");
  setTimeout(clearHighlighting, 3000);
}, 2000);

function clearHighlighting() {
  $("#row_id").removeClass("temphighlight");
}

#datatable tr {
  transition: background 2.0s ease;
}

#datatable tr:nth-child(odd) {
  background-color: #fff;
}

#datatable tr:nth-child(even) {
  background-color: #fafafa;
}

#datatable tr.temphighlight {
  background-color: #c6efce;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
  <tr>
    <td>One</td>
  </tr>
  <tr>
    <td>Two</td>
  </tr>
  <tr id="row_id">
    <td>Three</td>
  </tr>
  <tr>
    <td>Four</td>
  </tr>
</table>


问:
Authenticate against Active Directory in .NET Core 1.0 application?
With the recent release of .NET Core 1.0, we're in the process of migrating our RC1 applications to the final release. The only piece we can't seem to figure out is how to integrate Active Directory authentication.

Previously in the RC1 applications, we had used the System.DirectoryServices.AccountManagement library to handle the LDAP authorization queries. However, we can no longer mix this library with .NET Core v1.

Generally, what is the best way to integrate Active Directory authentication into our applications using the libraries available for use in the .NET Core framework? IdentityServer, some other third party service like Auth0 or something else?

答:
Just want to say that they just issued a pre-release of the Microsoft.Windows.Compatibility  which contains the System.DirectoryServices components needed to integrating with Active Directory

https://www.nuget.org/packages/Microsoft.Windows.Compatibility/2.0.0-preview1-25914-04


答:
Though taking each speed and dividing by 10 works in this case, you may consider dividing by the length of the Car array instead of 10 (done in code sample below). To find the max speed, simply assign the speed of the first car in the array to the max speed, and update it if another Car turns out to be faster.</p>

```<code>    public static void MaxSpeedCarAverage(Car[] arraycar, float maxspeed, float average)
    {
        maxspeed = arraycar[0].Speed;
        for(int i=0;i<10;i++)
        {
            if(arraycar[i].Speed > maxspeed) {
                maxspeed = arraycar[i].Speed;
            }
            average+= arraycar[i].Speed / arraycar.Length;
        }
    }
</code>```

Title: A global method that finds the average, and the highest speed of cars

Body:
I created the Car class with attributes and properties. In the main part of the program, I created a series of cars and initialized the values.

My program should use the global method to find the fastest car and average speed of all cars, the method must also return two results.

I tried to make This method, I made for a loop that will pass through every speed individually and  split it with the total number of cars in a row, then added to the variable average, does this make sense?

To find the fastest car in a row, I'm not sure how to do it, so I asked myself the question.

Can anyone explain to me about this speed finding algorithm in the global method and also generally about the whole task if I made a mistake in the definition of the same method?

class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }
}

This is main program

class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}

Body:
Though taking each speed and dividing by 10 works in this case, you may consider dividing by the length of the Car array instead of 10 (done in code sample below). To find the max speed, simply assign the speed of the first car in the array to the max speed, and update it if another Car turns out to be faster.

    public static void MaxSpeedCarAverage(Car[] arraycar, float maxspeed, float average)
    {
        maxspeed = arraycar[0].Speed;
        for(int i=0;i<10;i++)
        {
            if(arraycar[i].Speed > maxspeed) {
                maxspeed = arraycar[i].Speed;
            }
            average+= arraycar[i].Speed / arraycar.Length;
        }
    }


问:
Assets path : absolute vs generated
I'm currently making a "fromAssets" function that provide a path to the assets folder where ever the program is execute.

The function come from the following part of code.

Header file :

```<code>#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

namespace path {
    static fs::path BUILD_PATH;
    const void initialiseBuildPath(const char *argv);
    const char * fromAssets(const char * path);
}
</code>```

Source file :

```<code>using namespace path;

const void path::initialiseBuildPath(const char *argv0) {
    BUILD_PATH = fs::initial_path<fs::path>();
    BUILD_PATH = fs::system_complete(fs::path(argv0))
                            .parent_path()
                            .parent_path();
}

const char * path::fromAssets(const char * path) {
    std::string strPath = std::string(path);
    return (BUILD_PATH.string() + "/assets/" + strPath).c_str();
}
</code>```

Use :

```<code>const char * absolute = "/Users/thomaspetillot/CLionProjects/glDiscoverProject/build/assets/shader/basic.vert.glsl";
const char * generated = path::fromAssets("shader/basic.vert.glsl");
cout << strcmp(absolute, generated) << endl; // show 0

// Work
auto * shader = new Shader(absolute,
                           path::fromAssets("shader/basic.frag.glsl"));

// Doesn't work
auto * shader = new Shader(generated,
                           path::fromAssets("shader/basic.frag.glsl"));
</code>```

Folder structure :

```<code>build
├── assets
│   ├── img
│   │   ├── pepe.jpg
│   │   └── snoop.jpg
│   └── shader
│       ├── basic.frag.glsl
│       └── basic.vert.glsl
└── bin
    └── program
</code>```

How can it work for the frag shader but not for the other ?

答:
The fromAssets method returns a pointer to an invalid memory address. That happens because you return the c_str() pointer of a std::string object that is a local variable of that function. When the function returns, all local variables, including the std::string, get deleted and the pointer returned points to a no longer existing memory address.

The best (and most modern) fix would be to return the std::string object itself instead of a const char* pointer. You can than either pass the c_str pointer to the Shader constructor or even better adjust the constructor to take const std::string& as parameters.

Title: Assets path : absolute vs generated

Body:
I'm currently making a "fromAssets" function that provide a path to the assets folder where ever the program is execute.

The function come from the following part of code.

Header file :

#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

namespace path {
    static fs::path BUILD_PATH;
    const void initialiseBuildPath(const char *argv);
    const char * fromAssets(const char * path);
}

Source file :

using namespace path;

const void path::initialiseBuildPath(const char *argv0) {
    BUILD_PATH = fs::initial_path<fs::path>();
    BUILD_PATH = fs::system_complete(fs::path(argv0))
                            .parent_path()
                            .parent_path();
}

const char * path::fromAssets(const char * path) {
    std::string strPath = std::string(path);
    return (BUILD_PATH.string() + "/assets/" + strPath).c_str();
}

Use :

const char * absolute = "/Users/thomaspetillot/CLionProjects/glDiscoverProject/build/assets/shader/basic.vert.glsl";
const char * generated = path::fromAssets("shader/basic.vert.glsl");
cout << strcmp(absolute, generated) << endl; // show 0

// Work
auto * shader = new Shader(absolute,
                           path::fromAssets("shader/basic.frag.glsl"));

// Doesn't work
auto * shader = new Shader(generated,
                           path::fromAssets("shader/basic.frag.glsl"));

Folder structure :

build
├── assets
│   ├── img
│   │   ├── pepe.jpg
│   │   └── snoop.jpg
│   └── shader
│       ├── basic.frag.glsl
│       └── basic.vert.glsl
└── bin
    └── program

How can it work for the frag shader but not for the other ?


问:
Video conversion with ffmpeg to target Android and iOS mobile devices
I'm building a react native app for both Android and IOS, the back-end API is written with NodeJS.

Users may upload video from their phones, once uploaded the user and their friends will be able to view the video - so the videos need to be stored in a format which is playable on both Android & IOS.

My question relates to the conversion of video, uploaded by the user. I developed a similar app a couple of years ago; I used the repo node-fluent-ffmpeg which provides a nice API to interact with FFmpeg.

In the previous project (which was a web app), I converted the uploaded videos into two files, one .mp4 and one .webm - if a user uploaded an mp4, then I would skip the mp4 step, likewise if they uploaded a .webm.

This was kind of slow. Now I've come across the same requirement years later, after some research I think I was wrong to convert the videos to the last project.

I've read that I can simply use FFmpeg to change the container format of the videos, which is a much faster process than converting them from scratch.

The video conversion code I used last time went something along the lines of:

```<code>var convertVideo = function (source, format, output, success, failure, progress) {

    var converter = ffmpeg(source);

    var audioCodec = "libvorbis";

    if (format.indexOf("mp4") != -1) {
        audioCodec = "aac";
    }

    converter.format(format)
        .withVideoBitrate(1024)
        .withAudioCodec(audioCodec)
        .on('end', success)
        .on('progress', progress)
        .on('error', failure);

    converter.save(output);
};
</code>```

Usage:

Convert to mp4:

```<code>convertVideo("PATH_TO_VIDEO", "mp4", "foo.mp4", () => {console.log("success");});
</code>```

Convert to webm:

```<code>convertVideo("PATH_TO_VIDEO", "webm", "foo.webm", () => {console.log("success");});
</code>```

Can anyone point out a code smell here regarding the performance of this operation? Is this code doing a lot more than it should achieve cross-platform compatibility between IOS and Android?

Might be worth mentioning that support for older OS versions is not such a big deal in this project.

答:
Thats easy, you just go for the same that the big vendors like youtube do, which is currently mp4/h.264/aac

As you target Android or better "any" OS or device, to get out the max. you have additionally to take care about the detailed settings of the codecs. Hardware decoders that are built in to devices tend to be pretty picky about what they want to decode.

Youtube defines the video codec settings this way

for the h264:

Progressive scan (no interlacing)

High Profile

2 consecutive B frames

Closed GOP. GOP of half the frame rate.

CABAC

Variable bitrate. No bitrate limit required, though we offer recommended bit rates below for reference

Chroma subsampling: 4:2:0

The only thing i can add: actually you should care about the bitrate, if you go too high (e.g. more than 15MBit/s for Full-HD video), hardware decoders might cause troubles.

For the AAC:

Channels: Stereo or Stereo + 5.1

Sample rate 96khz or 48khz

Container: MP4

No Edit Lists (or the video might not get processed correctly)

moov atom at the front of the file (Fast Start)

Furthermore, h264 is definitely the codec that has been worked on most which is why it can be encoded much faster than VP8/9 and co. So in my opinion there is no good reason (besides "ethic" ones) to go for h264 ONLY - not to mention that "x264" is even faster than h264 and should guarantee the same compatibility

Conclusio:

Can anyone point out a code smell here regarding performance of this
  operation? Is this code doing a lot more than it should to achieve
  cross platform compatibility between IOS and Android?

Unfortunately no, it all depends on what kind of videos you get as input. Your code does definitely not too much, but far to less in terms of "try to save computing time". You could check if the input video matches all the listed parameters before you send it to encoding but to be honest, from experience most compatible results you will get is when you re-encode all your inputs to the settings above.

Body:
I'm building a react native app for both Android and IOS, the back-end API is written with NodeJS.

Users may upload video from their phones, once uploaded the user and their friends will be able to view the video - so the videos need to be stored in a format which is playable on both Android & IOS.

My question relates to the conversion of video, uploaded by the user. I developed a similar app a couple of years ago; I used the repo node-fluent-ffmpeg which provides a nice API to interact with FFmpeg.

In the previous project (which was a web app), I converted the uploaded videos into two files, one .mp4 and one .webm - if a user uploaded an mp4, then I would skip the mp4 step, likewise if they uploaded a .webm.

This was kind of slow. Now I've come across the same requirement years later, after some research I think I was wrong to convert the videos to the last project.

I've read that I can simply use FFmpeg to change the container format of the videos, which is a much faster process than converting them from scratch.

The video conversion code I used last time went something along the lines of:

var convertVideo = function (source, format, output, success, failure, progress) {

    var converter = ffmpeg(source);

    var audioCodec = "libvorbis";

    if (format.indexOf("mp4") != -1) {
        audioCodec = "aac";
    }

    converter.format(format)
        .withVideoBitrate(1024)
        .withAudioCodec(audioCodec)
        .on('end', success)
        .on('progress', progress)
        .on('error', failure);

    converter.save(output);
};

Usage:

Convert to mp4:

convertVideo("PATH_TO_VIDEO", "mp4", "foo.mp4", () => {console.log("success");});

Convert to webm:

convertVideo("PATH_TO_VIDEO", "webm", "foo.webm", () => {console.log("success");});

Can anyone point out a code smell here regarding the performance of this operation? Is this code doing a lot more than it should achieve cross-platform compatibility between IOS and Android?

Might be worth mentioning that support for older OS versions is not such a big deal in this project.


问:
Diamond shorthand syntax not working javac
When I compile this:

```<code>LinkedBlockingDeque<Integer> q = new LinkedBlockingDeque<>();
</code>```

in Eclipse Java EE Kepler version, everything works fine, but once I try to compile the same program in in the terminal with

javac myProgram.java

in the command line, I receive a "illegal start of type" error, on the <>

I know the Diamond Shorthand came with java 7, so why would the terminal use the javac of java 6 and not 7? And how do I correct this permanently? I'm on Linux, Mint 15.

Running javac -version revealed this

```<code>~ $ javac -version
    javac 1.6.0_27
</code>```

答: In eclipse.. Go to project properties -> Java Compiler and select the required java compiler version.</p>

Body:
When I compile this:

LinkedBlockingDeque<Integer> q = new LinkedBlockingDeque<>();

in Eclipse Java EE Kepler version, everything works fine, but once I try to compile the same program in in the terminal with

javac myProgram.java

in the command line, I receive a "illegal start of type" error, on the <>

I know the Diamond Shorthand came with java 7, so why would the terminal use the javac of java 6 and not 7? And how do I correct this permanently? I'm on Linux, Mint 15.

Running javac -version revealed this

~ $ javac -version
    javac 1.6.0_27


问:
About VBA Code returns multiple values
I need help here to understand how and from where the variable Ret has the value "2".

I am not able to understand this code, can someone help me please.

```<code>Function Test(ByVal Input1 As Integer, ByVal Input2 As Integer, _
    ByRef Output1 As Integer, ByRef Output2 As Integer) As Integer

      Output1 = Input1 + Input2
      Output2 = Input1 - Input2
      Test = Output1 + Output2

End Function

Sub Test2()

    Dim Ret As Integer, Input1 As Integer, Input2 As Integer, _
    Output1 As Integer, Output2 As Integer
    Input1 = 1
    Input2 = 2
    Ret = Test(Input1, Input2, Output1, Output2)
    Sheet1.Range("A1") = Ret     ' 2
    Sheet1.Range("A2") = Output1 ' 3
    Sheet1.Range("A3") = Output2 '-1

End Sub
</code>```

答:
Return value

Return values in VBA are done by setting the name of the function equal to a value. Example:

```<code>Function myFunction()
    myFunction = 123
End Function
</code>```

When I call myFunction, I can assign the function's return value to a variable, e.g. like:

```<code>returnValue = myFunction
</code>```

returnValue will now have the value 123

In your example, the function Test returns the result of Output1 + Output2:

```<code>Output1 + Output2 = 3 + (-1) = 2
</code>```

Therefore, the function Test returns the value 2

ByRef/ByVal Parameters

The other thing that's going on here, are the two different types of parameters.

Passing a parameter ByVal (by value) creates a copy of the variable and passes that copy into the function. Therefore, if I adjust the variable inside the function, its value in the caller function doesn't change. Example:

```<code>Function MyFunction(ByVal num)
    num = 2
End Function
</code>```

and then I call the function like so:

```<code>count = 1
Call MyFunction(count)
MsgBox count
</code>```

The MsgBox will display the number 1. The variable count was copied to a different variable (num inside MyFunction) and when num was assigned the value 2, count remained unchanged.

Passing a parameter ByRef is the opposite: The parameter isn't copied, but passed directly (as a reference ~ as a "link") to the function.

Let's look at the above MyFunction again, but imagine changing the parameter to ByRef instead of ByVal. In that case, MsgBox count will display the value 2. When we pass count ByRef to MyFunction, num becomes an alias of the same variable as count and when num is assigned the value 2, count is the same variable, so it also now has the value 2.

Title: About VBA Code returns multiple values

Body:
I need help here to understand how and from where the variable Ret has the value "2".

I am not able to understand this code, can someone help me please.

Function Test(ByVal Input1 As Integer, ByVal Input2 As Integer, _
    ByRef Output1 As Integer, ByRef Output2 As Integer) As Integer

      Output1 = Input1 + Input2
      Output2 = Input1 - Input2
      Test = Output1 + Output2

End Function

Sub Test2()

    Dim Ret As Integer, Input1 As Integer, Input2 As Integer, _
    Output1 As Integer, Output2 As Integer
    Input1 = 1
    Input2 = 2
    Ret = Test(Input1, Input2, Output1, Output2)
    Sheet1.Range("A1") = Ret     ' 2
    Sheet1.Range("A2") = Output1 ' 3
    Sheet1.Range("A3") = Output2 '-1

End Sub

Body:
Return value

Return values in VBA are done by setting the name of the function equal to a value. Example:

Function myFunction()
    myFunction = 123
End Function

When I call myFunction, I can assign the function's return value to a variable, e.g. like:

returnValue = myFunction

returnValue will now have the value 123

In your example, the function Test returns the result of Output1 + Output2:

Output1 + Output2 = 3 + (-1) = 2

Therefore, the function Test returns the value 2

ByRef/ByVal Parameters

The other thing that's going on here, are the two different types of parameters.

Passing a parameter ByVal (by value) creates a copy of the variable and passes that copy into the function. Therefore, if I adjust the variable inside the function, its value in the caller function doesn't change. Example:

Function MyFunction(ByVal num)
    num = 2
End Function

and then I call the function like so:

count = 1
Call MyFunction(count)
MsgBox count

The MsgBox will display the number 1. The variable count was copied to a different variable (num inside MyFunction) and when num was assigned the value 2, count remained unchanged.

Passing a parameter ByRef is the opposite: The parameter isn't copied, but passed directly (as a reference ~ as a "link") to the function.

Let's look at the above MyFunction again, but imagine changing the parameter to ByRef instead of ByVal. In that case, MsgBox count will display the value 2. When we pass count ByRef to MyFunction, num becomes an alias of the same variable as count and when num is assigned the value 2, count is the same variable, so it also now has the value 2.


问:
Outlook Add-In: Detect when any of the CC or TO email addresses are selected
Basically I have an Outlook Add-In that when a new mail item is selected in the Explorer a callback is fired. In this callback, based on if the mail item is sent or received, I select the external email address (meaning the email address that does not belong the outlook account. If the mail item is of type received then I select the FROM address, otherwise I select the first TO address) and make an HTTP call to a RESTful API to obtain more info about the person based on that email address.

The point is that if the mail item has multiple CC's or multiple TO's, I need to be able to detect when any of this email address are selected, so I can make another call to the API with the selected email address.

答: Recipient selection in emails is not exposed at all.</p>


问:
Convert job control number (%1) to pid so that I can kill sudo'ed background job
I often end up in this situation:

```<code>$ sudo something &
[1] 21838
$# Oh, shoot, it's hung, and assume the pid has scrolled off the screen
$ kill %1
-bash: kill: (21838) - Operation not permitted
$# Ah, rats.  I forgot I sudo'ed that.
$# Wishful thinking:
$ sudo kill %1
kill: cannot find process "%1"
$# Now I have to use ps and find the pid I want.
$ ps -elf | grep something
$ ps -elf | grep sleep
4 S root     21838  1928  0  80   0 - 53969 poll_s 11:28 pts/2    00:00:00 sudo sleep 100
4 S root     21840 21838  0  80   0 - 26974 hrtime 11:28 pts/2    00:00:00 sleep 100
$ sudo kill -9 21838
[1]+  Killed                  sudo something
</code>```

I would really like to know if there is a better workflow for this.  I'm really surprised there isn't a bash expression to turn %1 into a pid number.

Is there a bash trick for converting %1 to it's underlying pid?  (Yes, I know I could have saved it at launch with $!)

答:
To get the PID of a job, use: jobs -p N, where N is the job number:

```<code>$ yes >/dev/null &
[1] 2189
$ jobs -p 1
2189
$ sudo kill $(jobs -p 1)
[1]+  Terminated              yes > /dev/null
</code>```

Alternatively, and more strictly answering your question, you might find -x useful: it runs a command, replacing a job spec with the corresponding PID:

```<code>$ yes >/dev/null &
[1] 2458
$ jobs -x sudo kill %1
[1]+  Terminated              yes > /dev/null
</code>```

I find -p more intuitive, personally, but I get the appeal of -x.

Body:
I often end up in this situation:

$ sudo something &
[1] 21838
$# Oh, shoot, it's hung, and assume the pid has scrolled off the screen
$ kill %1
-bash: kill: (21838) - Operation not permitted
$# Ah, rats.  I forgot I sudo'ed that.
$# Wishful thinking:
$ sudo kill %1
kill: cannot find process "%1"
$# Now I have to use ps and find the pid I want.
$ ps -elf | grep something
$ ps -elf | grep sleep
4 S root     21838  1928  0  80   0 - 53969 poll_s 11:28 pts/2    00:00:00 sudo sleep 100
4 S root     21840 21838  0  80   0 - 26974 hrtime 11:28 pts/2    00:00:00 sleep 100
$ sudo kill -9 21838
[1]+  Killed                  sudo something

I would really like to know if there is a better workflow for this.  I'm really surprised there isn't a bash expression to turn %1 into a pid number.

Is there a bash trick for converting %1 to it's underlying pid?  (Yes, I know I could have saved it at launch with $!)

Body:
To get the PID of a job, use: jobs -p N, where N is the job number:

$ yes >/dev/null &
[1] 2189
$ jobs -p 1
2189
$ sudo kill $(jobs -p 1)
[1]+  Terminated              yes > /dev/null

Alternatively, and more strictly answering your question, you might find -x useful: it runs a command, replacing a job spec with the corresponding PID:

$ yes >/dev/null &
[1] 2458
$ jobs -x sudo kill %1
[1]+  Terminated              yes > /dev/null

I find -p more intuitive, personally, but I get the appeal of -x.


问:
Can you query a HANA analytical view as if it's the orginal table?
Suppose you have a HANA analytical view, but you have no access to the table that was the origin of the analytical view.

The analytical view has pre-aggregated columns, but you need the columns without the pre-aggregation, otherwise the query will get the wrong result.

For example if there are the integer columns Price and Profit, and your query has SELECT SUM(PRICE*PROFIT). With the regular table on each row there would be a PRICE*PROFIT calculation, and then the result would aggregate that to SUM(PRICE*PROFIT) from each row. But with the analytical view's pre-aggregation, you end up getting SUM(PRICE)*SUM(PROFIT), which is not the same as SUM(PRICE*PROFIT).

Yes, if there's another column with a unique value per row, that can be added to the query, and you can get multiple rows from the analytical view that will aggregate as I need. And you can do a SELECT * to get all rows without pre-aggregation, but that doesn't allow including the SUM(PRICE*PROFIT).

In my case, my program has no idea which columns would have the unique value to do the aggregated calculation correctly.

Is there any way to query an analytical view as if it was its original table?

答:
I have a solution: do a SELECT * as a subquery, then you have the original table to query from:

```<code>SELECT "State", SUM("Price" * "Profit") AS PxP FROM
(
    SELECT * FROM AVTable
)
GROUP BY "State"
</code>```

Body:
I have a solution: do a SELECT * as a subquery, then you have the original table to query from:

SELECT "State", SUM("Price" * "Profit") AS PxP FROM
(
    SELECT * FROM AVTable
)
GROUP BY "State"


问:
Git clone works in AWS CodeCommit but pushing fails with 403
I can clone my CodeCommit repository successfully, but when I try to push to it, I get 403. Fetching and pulling works, however. It's as if I have read-only access.

I have setup my .gitconfig to use AWS CLI for credential manager:

```<code>[credential]
        helper = !aws --profile builder codecommit credential-helper $@
        UseHttpPath = true
</code>```

The problem is that the error doesn't tell me why pushing is failing:

```<code>$ git push origin test-branch
fatal: unable to access 'https://git-codecommit.us-east-1.amazonaws.com/v1/repos/my-example-repo/': The requested URL returned error: 403
</code>```

Most questions on the internet about his error are when cloning fails, but cloning works for me. I found this question where cloning succeeds and pushing fails, but his error is different - aws codecommit cannot push.

Edit:: After looking at my CodeCommit policy, it has Full: Read Limited: List, Write:

There is also a ResourceSpecifier = foo-*, but that holds for GitPull permission and pulling works, so I doubt it's the resource specifier.

答:
I imagine you're right about the read-only permissions. As the docs state, you need the codecommit:GitPush permission in your IAM policy to be allowed to push commits from your local repository to the CodeCommit repository.

Being able to pull the repository means your credentials are set up correctly, if they weren't you wouldn't be able to git pull / git fetch at all.

Body:
I can clone my CodeCommit repository successfully, but when I try to push to it, I get 403. Fetching and pulling works, however. It's as if I have read-only access.

I have setup my .gitconfig to use AWS CLI for credential manager:

[credential]
        helper = !aws --profile builder codecommit credential-helper $@
        UseHttpPath = true

The problem is that the error doesn't tell me why pushing is failing:

$ git push origin test-branch
fatal: unable to access 'https://git-codecommit.us-east-1.amazonaws.com/v1/repos/my-example-repo/': The requested URL returned error: 403

Most questions on the internet about his error are when cloning fails, but cloning works for me. I found this question where cloning succeeds and pushing fails, but his error is different - aws codecommit cannot push.

Edit:: After looking at my CodeCommit policy, it has Full: Read Limited: List, Write:

There is also a ResourceSpecifier = foo-*, but that holds for GitPull permission and pulling works, so I doubt it's the resource specifier.


问:
Working with DirectoryServices in ASP.NET Core
I am upgrading my ASP.NET Core RC1 application to RC2. I have some references to System.DirectoryServices and System.DirectoryServices.AccountManagement in some *.cs files so that I can query LDAP. But I have no idea how to add references to it in RC2 in the Project.json file. Everything that I try just gives me more errors. Any help is appreciated.

```<code>{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "default"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview1-final",
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview1-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Newtonsoft.Json": "8.0.3",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
    "System.Linq": "4.0.1-beta-23516",
    "System.Linq.Queryable": "4.0.1-beta-23516"
  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    },
    "Microsoft.Extensions.SecretManager.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}
</code>```

答:
Just want to say that they just issued a pre-release of the Microsoft.Windows.Compatibility which contains the System.DirectoryServices components needed to work directory with active directory. its beta, but its finally out there.

NuGet Microsoft.Windows.Compatibility

ContentLicense: CC BY-SA 4.0

Body:
I am upgrading my ASP.NET Core RC1 application to RC2. I have some references to System.DirectoryServices and System.DirectoryServices.AccountManagement in some *.cs files so that I can query LDAP. But I have no idea how to add references to it in RC2 in the Project.json file. Everything that I try just gives me more errors. Any help is appreciated.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "default"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview1-final",
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview1-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Newtonsoft.Json": "8.0.3",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
    "System.Linq": "4.0.1-beta-23516",
    "System.Linq.Queryable": "4.0.1-beta-23516"
  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    },
    "Microsoft.Extensions.SecretManager.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}


问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答: If you haven't read Joel's article on Architecture Astronauts (the Live Mesh one), I recommend it - it's a good read about this subject.</p>

OwnerDisplayName: Nick Pierpoint

LastEditorDisplayName: Nick Pierpoint


问:
Unable to cast page as page class
I'm attempting to access data on a parent page from a user control. I understand this is not the best way to go about it and I do not want to get into that debate. This is HOW I have to go about it due to constraints beyond my control and pay grade.

I should be able to do this:

```<code>myWebBase myPage = (myWebBase) Parent.Page;
int x = myPage.getX();
</code>```

But the class name myWebBase is not recognized. Anyone have any ideas why?

答: Is the content page in a namespace that hasn't been imported?</p>

Title: Unable to cast page as page class

Body:
I'm attempting to access data on a parent page from a user control. I understand this is not the best way to go about it and I do not want to get into that debate. This is HOW I have to go about it due to constraints beyond my control and pay grade.

I should be able to do this:

myWebBase myPage = (myWebBase) Parent.Page;
int x = myPage.getX();

But the class name myWebBase is not recognized. Anyone have any ideas why?


问:
Group repeated elements of a list
I am trying to create a function that receives a list and return another list with the repeated elements.

For example for the input A = [2,2,1,1,3,2] (the list is not sorted) and the function would return result = [[1,1], [2,2,2]]. The result doesn't need to be sorted.

I already did it in Wolfram Mathematica but now I have to translate it to python3, Mathematica has some functions like Select, Map and Split that makes it very simple without using long loops with a lot of instructions.

答:
```<code>result = [[x] * A.count(x) for x in set(A) if A.count(x) > 1]
</code>```

Title: Group repeated elements of a list


问:
Find folder of specific file
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

```<code>find 2>/dev/null / -name libgfortran.so
</code>```

... which will output something like the following to stdout (redirecting stderr to /dev/null):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

From this I want to extract just the folder (without a trailing /):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8
</code>```

I've got as far as trying something like:

```<code>find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'
</code>```

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

How do I achieve what I want?

答:
If you really want to use sed:

```<code>find 2>/dev/null / -name libgfortran.so | sed -E 's#(/.*)/(.*)#\1#g'
</code>```

where -E tells sed to use a regular expression, so you don't have to escape the paratheses. The group \1 is your path and \2 would be the filename.

Title: Find folder of specific file

Body:
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

find 2>/dev/null / -name libgfortran.so

... which will output something like the following to stdout (redirecting stderr to /dev/null):

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

From this I want to extract just the folder (without a trailing /):

/usr/lib/gcc/x86_64-linux-gnu/4.8

I've got as far as trying something like:

find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

How do I achieve what I want?

Body:
If you really want to use sed:

find 2>/dev/null / -name libgfortran.so | sed -E 's#(/.*)/(.*)#\1#g'

where -E tells sed to use a regular expression, so you don't have to escape the paratheses. The group \1 is your path and \2 would be the filename.


问:
Javascript prototypical inheritence with object.create and call gives not function error
I am moving my head around JavaScript prototypical Inheritance. I am taking the help of following link: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

I have a person object:

```<code>function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};
</code>```

I have inherited it to teacher object:

```<code>function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}
</code>```

Now, I defined a function on Person prototype:

```<code>Person.prototype.sayHello = function (){
   console.log("hello");
}
</code>```

Now, I want to call it via teacher:

```<code>var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.prototype.sayHello();
</code>```

It gives:

Uncaught TypeError: Cannot read property 'sayHello' of undefined
      at :1:19

Calling it directly yields the same result:

```<code>teacher.sayHello();
</code>```

Let me make constructor right:

```<code>Teacher.prototype = Object.create(Person.prototype);

teacher.sayHello();
</code>```

VM203:1 Uncaught TypeError: teacher.sayHello is not a function
          at :1:9

Same result. What am I missing?

答:
You are just calling the Person function and pass to him the context which uses that to initialize the properties. You call it like if you call another function inside it. Person is not in the prototype chain of the Teacher. You also need to explicitly add it into the chain.

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

// Set the prototype an empty object which prototype is the Person.prototype
Teacher.prototype = Object.create(Person.prototype);
// Preserve the constructor
Teacher.constructor = Teacher;

Person.prototype.sayHello = function (){
   console.log("hello");
}

var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.sayHello();```

Body:
I am moving my head around JavaScript prototypical Inheritance. I am taking the help of following link: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

I have a person object:

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

I have inherited it to teacher object:

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

Now, I defined a function on Person prototype:

Person.prototype.sayHello = function (){
   console.log("hello");
}

Now, I want to call it via teacher:

var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.prototype.sayHello();

It gives:

Uncaught TypeError: Cannot read property 'sayHello' of undefined
      at :1:19

Calling it directly yields the same result:

teacher.sayHello();

Let me make constructor right:

Teacher.prototype = Object.create(Person.prototype);

teacher.sayHello();

VM203:1 Uncaught TypeError: teacher.sayHello is not a function
          at :1:9

Same result. What am I missing?


答:
Ret gets the value of the result of the Test Function

```<code>Ret = Test(Input1, Input2, Output1, Output2)
</code>```

Title: About VBA Code returns multiple values

Body:
Ret gets the value of the result of the Test Function

Ret = Test(Input1, Input2, Output1, Output2)