问:
Export a class from a CoffeeScript file
If I have a CoffeeScript class defined in a separate file, which I'm calling from my main script, I can make the functions within the file globally visible, but not the class.

The included file is:

```<code>root = exports ? this

root.add = (a, b) ->

      return a + b

class root.userModel
      username: 'Aaaa'
      name: 'Bbbb'
</code>```

I can access the function from my main code. How can I create the class?

答:
Just define your class with a '@' before its name:</p>
```<code>class @ClassName
  blablabla: -> blablalblablabla
</code>```

Title: Export a class from a CoffeeScript file

Body:
If I have a CoffeeScript class defined in a separate file, which I'm calling from my main script, I can make the functions within the file globally visible, but not the class.

The included file is:

root = exports ? this

root.add = (a, b) ->

      return a + b

class root.userModel
      username: 'Aaaa'
      name: 'Bbbb'

I can access the function from my main code. How can I create the class?

Body:
Just define your class with a '@' before its name:

class @ClassName
  blablabla: -> blablalblablabla


来源: stackexchange

问:
Display properties from state using React
I have a simple React component which pulls in some data via the Monzo API and then I simply want to print it out on the screen. I can see I'm getting back the correct data via the React dev tools and it's setting the state however nothing gets printed in my HTML.

Here is my component:

```<code>import React, {Component} from "react";
import "./App.css";
import axios from "axios";

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            account: [{
                id: '',
                description: '',
                created: '',
                type: ''
            }]
        }
    }

    componentDidMount() {
        let config = {
            headers: {
                'Authorization': 'Bearer sampleToken'
            }
        };

        axios.get('https://api.monzo.com/accounts', config).then((response) => {
            this.setState({'account': response.data.accounts});
        });
    }

    render() {
        return (
            <div className="App">
                <div className="App-header">
                    <h2>Hello {this.state.account.map(account =>
                        console.log(account),
                        <p>account.description</p>
                    )}</h2>
                </div>
                <p className="App-intro">
                    Monzo API app
                    {this.state.account.id}
                </p>
            </div>
        );
    }
}

export default App;
</code>```

My console log within my map function first displays an empty account object and then a filled correct account object, could this be the reason why?

答:
```<code>  <p>{account.description}</p>
</code>```

<p>instead of </p>

```<code> <p>account.description</p>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple React component which pulls in some data via the Monzo API and then I simply want to print it out on the screen. I can see I'm getting back the correct data via the React dev tools and it's setting the state however nothing gets printed in my HTML.

Here is my component:

import React, {Component} from "react";
import "./App.css";
import axios from "axios";

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            account: [{
                id: '',
                description: '',
                created: '',
                type: ''
            }]
        }
    }

    componentDidMount() {
        let config = {
            headers: {
                'Authorization': 'Bearer sampleToken'
            }
        };

        axios.get('https://api.monzo.com/accounts', config).then((response) => {
            this.setState({'account': response.data.accounts});
        });
    }

    render() {
        return (

Hello {this.state.account.map(account =>
                        console.log(account),

account.description

                    )}

                    Monzo API app
                    {this.state.account.id}

        );
    }
}

export default App;

My console log within my map function first displays an empty account object and then a filled correct account object, could this be the reason why?

Body:
  <p>{account.description}</p>

instead of

 <p>account.description</p>


问:
angularjs 1.2 - validation directive update on $watch
I have the following directive that I'm using for validation on a multi-select to allow for (dynamic) length validation of the number of selected items.

```<code>(function() {
    'use strict';

    angular
        .module('myModule')
        .directive('listLength', listLength);

    listLength.$inject = ['$parse'];

    function listLength($parse) {
        var directive = {
            require: 'ngModel',
            restrict: 'A',
            link: link
        };

        function link(scope, elem, attr, ngModel) {
            var length = 0;
            var exp = $parse(attr.listLength);
            if (exp.constant) {
                // Single value, no need to watch
                length = exp(scope);
            } else {
                // We have an expression, need to watch for changes
                scope.$watch(attr.listLength, function(newVal, oldVal) {
                    length = newVal;
                });
            }

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                    return valid ? value : undefined;
                }
                return value;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                }
                return value;
            });
        }

        return directive;
    }
})();
</code>```

In order to have it update properly, I need to trigger the validation to be run when the expression (attr.listLength) updates, but it's not obvious to me how to achieve this. I tried setting ngModel.$dirty to true but it still does not update.

答:
Try change the watch parameter like that:</p>

```<code>scope.$watch("listLength", function(newVal, oldVal) {
       length = newVal;
});
</code>```

Body:
I have the following directive that I'm using for validation on a multi-select to allow for (dynamic) length validation of the number of selected items.

(function() {
    'use strict';

    angular
        .module('myModule')
        .directive('listLength', listLength);

    listLength.$inject = ['$parse'];

    function listLength($parse) {
        var directive = {
            require: 'ngModel',
            restrict: 'A',
            link: link
        };

        function link(scope, elem, attr, ngModel) {
            var length = 0;
            var exp = $parse(attr.listLength);
            if (exp.constant) {
                // Single value, no need to watch
                length = exp(scope);
            } else {
                // We have an expression, need to watch for changes
                scope.$watch(attr.listLength, function(newVal, oldVal) {
                    length = newVal;
                });
            }

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                    return valid ? value : undefined;
                }
                return value;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                }
                return value;
            });
        }

        return directive;
    }
})();

In order to have it update properly, I need to trigger the validation to be run when the expression (attr.listLength) updates, but it's not obvious to me how to achieve this. I tried setting ngModel.$dirty to true but it still does not update.

Body:
Try change the watch parameter like that:

scope.$watch("listLength", function(newVal, oldVal) {
       length = newVal;
});


问:
How to implement the Gentelella Bootstrap Admin theme in ASP.NET MVC?
I'm starting now with web development in Visual Studio. I have already understood MVC, I have some knowledge of HTML and I started to study the bootstrap.
Then, I discovered the beautiful template Free Bootstrap 3 Admin Template on the web, which has an example online here: https://colorlib.com/polygon/gentelella/index.html

I downloaded the files like custom.css and custom.min.css as they are shown in the following image:

But now I don't know how to put it in my project, so I created a new clean project in Visual Studio Community 2015. I did some tests, and I created some controllers and views.

How can I change the default bootstrap theme that came with ASP.NET MVC project to the downloaded one?

I imagine I should replace the _Layout in the shared folder. But what else should I bring?

I do not want all those example pages, etc. Just Bootstrap and the base layout to create my view's.

答:
I have found everything I needed from a YouTube video, entitled "Plantilla Bootstrap en Proyecto ASP.NET MVC" (obviously in Spanish).

There are many steps:

Adding files to the project

setting the _Layout

set scripts references

bundles

Etc.

Ultimately, it worked.


问:
Delete duplicate rows based on a condition
I have a table that has ID and EventDate. It has duplicate rows as I used Union of two tables. Now I got to have the rows with the minimum Eventdate and remove the other duplicates.

the table for eg

ID  | Date

--- | ---

1     | 10/27/1993

1      | 10/27/1994

2      | 10/17/1993

2      | 08/15/1993

Delete duplicate rows based on condition

答:
Use this!</p>

```<code>    delete A
    (
       SELECT *,
              RN = ROW_NUMBER() OVER(PARTITION BY [COLUMN] ORDER BY EventDate ASC),*
       FROM dbo.Your_Table
    ) AS A
where rn > 1
</code>```

Body:
Use this!

    delete A
    (
       SELECT *,
              RN = ROW_NUMBER() OVER(PARTITION BY [COLUMN] ORDER BY EventDate ASC),*
       FROM dbo.Your_Table
    ) AS A
where rn > 1


问:
Pandas df.values does not return index values
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

```<code>                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent
</code>```

Input:

```<code>df.values
</code>```

Output:

```<code>array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)
</code>```

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?

答: Various methods to do so. The one obvious one being that you create a columns copying the index data, and then calling df.values.

Body:
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent

Input:

df.values

Output:

array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?


问:
Remember cell selected before double click
I have an Excel sheet that has a doubleclick event in cell "P1" (runs a macro).

I may have cell "J30" (or any other cell) selected before I doubleclick "P1"
How can I remember, and return to the cell "J30" after the "P1" doubleclick?

Storing the active cell doesn't work because the first click in the doubleclick sequence, selects "P1".

I also tried rightclick on "P1", but it also selects "P1" before running the event.

答:
Well, it's a bit more complicated than the "duplicate thread" because the SelectionChange event is invoked prior to the BeforeDoubleClick event, so the former will update the last selection to the new one before the latter gets hand.

What you need is to go "one step further" in saving the selections, by actually saving both:

The current selection

The previous selection

Something like this should work

```<code>' Code module of your worksheet
Option Explicit
Private lastSelection As Range, beforeLastSelection As Range

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  ' Your Code for this event, i.e.
  If Target.Address = "$P$1" Then
    ' Some code ...
     Cancel = True
     If Not beforeLastSelection Is Nothing Then beforeLastSelection.Select
  End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set beforeLastSelection = lastSelection
  Set lastSelection = Target
End Sub
</code>```

Body:
Well, it's a bit more complicated than the "duplicate thread" because the SelectionChange event is invoked prior to the BeforeDoubleClick event, so the former will update the last selection to the new one before the latter gets hand.

What you need is to go "one step further" in saving the selections, by actually saving both:

The current selection

The previous selection

Something like this should work

' Code module of your worksheet
Option Explicit
Private lastSelection As Range, beforeLastSelection As Range

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  ' Your Code for this event, i.e.
  If Target.Address = "$P$1" Then
    ' Some code ...
     Cancel = True
     If Not beforeLastSelection Is Nothing Then beforeLastSelection.Select
  End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set beforeLastSelection = lastSelection
  Set lastSelection = Target
End Sub


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答:
Scrap my previous answer.

The reason this eval() is here is shown in the php eval docs

This is what's happening:

```<code>$text_including_tax = '$tax <a href="...">...</a>';

...

$tax = 10;

...

eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

At the end of this $text_including_tax is equal to:

```<code>"10 <a href="...">...</a>"
</code>```

The single quotes prevents $tax being included in the original definition of the string. By using eval() it forces it to re-evaluate the string and include the value for $tax in the string.

I'm not a fan of this particular method, but it is correct. An alternative could be to use sprintf()

OwnerDisplayName: mk

ContentLicense: CC BY-SA 2.5

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

Body:
Scrap my previous answer.

The reason this eval() is here is shown in the php eval docs

This is what's happening:

$text_including_tax = '$tax <a href="...">...</a>';

...

$tax = 10;

...

eval ("\$text_including_tax = \"$text_including_tax\";");

At the end of this $text_including_tax is equal to:

"10 <a href="...">...</a>"

The single quotes prevents $tax being included in the original definition of the string. By using eval() it forces it to re-evaluate the string and include the value for $tax in the string.

I'm not a fan of this particular method, but it is correct. An alternative could be to use sprintf()

OwnerDisplayName: calebbrown


问:
phpunit no tests executed
I have a 'No tests executed' with phpunit..

This line works

```<code>$ phpunit install/InstallDbTest.php
...
<result expected>
...

$ cat suites/installtests.xml
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.

Time: 130 ms, Memory: 11.25Mb

No tests executed!
</code>```

Does anyone can tell me what I am doing wrong ?

Thanks in advance!

答:
For those of you who you use a different bootstrap file than the Composer's autoload file, make sure you don't use one of your test case classes.

Indeed, PHPUnit (version 6.2 in my case) add to the running TestSuite all PHP files for which no class is loaded yet (see how it's done in the code). From the TestSuite::addTestFile($filename) method:

```<code>$classes = get_declared_classes();
$filename   = Fileloader::checkAndLoad($filename);
$newClasses = \array_diff(\get_declared_classes(), $classes);
</code>```

So if your class already belong to the get_declared_classes it will be ignored.

To summarize: don't use your test class before ;)

Title: phpunit no tests executed

Body:
I have a 'No tests executed' with phpunit..

This line works

$ phpunit install/InstallDbTest.php
...
<result expected>
...

$ cat suites/installtests.xml
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.

Time: 130 ms, Memory: 11.25Mb

No tests executed!

Does anyone can tell me what I am doing wrong ?

Thanks in advance!

Body:
For those of you who you use a different bootstrap file than the Composer's autoload file, make sure you don't use one of your test case classes.

Indeed, PHPUnit (version 6.2 in my case) add to the running TestSuite all PHP files for which no class is loaded yet (see how it's done in the code). From the TestSuite::addTestFile($filename) method:

$classes = get_declared_classes();
$filename   = Fileloader::checkAndLoad($filename);
$newClasses = \array_diff(\get_declared_classes(), $classes);

So if your class already belong to the get_declared_classes it will be ignored.

To summarize: don't use your test class before ;)


问:
ESP32 - UDP broadcaster/ receiver with native LwIP library
I'm building a distributed application with the ESP32 (a great platform btw) where all participants should communicate over UDP in it's simplest form: sending messages via broadcast and listening to all messages floating around. Each participant filters the relevant messages by itself.

So far, I have the following initialization routine:

```<code>int lavor_wifi_openUDPsocket(){
    // Create a socket
    int sckt = socket(AF_INET, SOCK_DGRAM, 0);
    if ( sckt < 0 ){
        printf("socket call failed");
        exit(0);
    }

    // Prepare binding to port
    struct sockaddr_in sLocalAddr;
    // Initialize the address
    memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));

    sLocalAddr.sin_family = AF_INET;
    sLocalAddr.sin_len = sizeof(sLocalAddr);
    sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    sLocalAddr.sin_port = UDP_SOCKET_PORT;

    bind(sckt, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr));

    return sckt;
}
</code>```

Then, a message would be send with:

```<code>void lavor_wifi_sendUDPmsg(int sckt, char* msg, int len){
    // Prepare the address to sent to via BROADCAST
    struct sockaddr_in sDestAddr;
    // Initialize the address
    // memset((char *)&sDestAddr, 0, sizeof(sDestAddr));

    sDestAddr.sin_family = AF_INET;
    sDestAddr.sin_len = sizeof(sDestAddr);
    sDestAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    sDestAddr.sin_port = UDP_SOCKET_PORT;

    if(sendto(sckt, msg, len, 0, (struct sockaddr *)&sDestAddr, sizeof(sDestAddr)) < len){
         printf("UDP message couldn't be sent.");
    }
}
</code>```

And finally, receiving messages would work like this:

```<code>void lavor_wifi_processor(void* sckt){
    int nbytes;
    char buffer[UDP_BUFF_LEN];
    // Listen for incoming messages as long as the socket is open
    while(1){   // TO DO: Test if socket open
        // Try to read new data arrived at the socket
        nbytes = recv(*((int *)sckt), buffer, sizeof(buffer), 0);
    ...
</code>```

But even if I just try to call the above initialization function, the ESP goes wild and throws one Guru Meditation error after another.

Does anyone has experience with UDP communication in the descripted way?

答:
I got UDP with ESP32/UDP/LWIP to work with this example:

https://github.com/Ebiroll/qemu_esp32/blob/master/examples/19_udp

Note that send_thread() is not started until we have received an ip address.

However it also might also be that you need v2.0 of esp-idf. I also got Guru Meditation errors with latest version.

Body:
I'm building a distributed application with the ESP32 (a great platform btw) where all participants should communicate over UDP in it's simplest form: sending messages via broadcast and listening to all messages floating around. Each participant filters the relevant messages by itself.

So far, I have the following initialization routine:

int lavor_wifi_openUDPsocket(){
    // Create a socket
    int sckt = socket(AF_INET, SOCK_DGRAM, 0);
    if ( sckt < 0 ){
        printf("socket call failed");
        exit(0);
    }

    // Prepare binding to port
    struct sockaddr_in sLocalAddr;
    // Initialize the address
    memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));

    sLocalAddr.sin_family = AF_INET;
    sLocalAddr.sin_len = sizeof(sLocalAddr);
    sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    sLocalAddr.sin_port = UDP_SOCKET_PORT;

    bind(sckt, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr));

    return sckt;
}

Then, a message would be send with:

void lavor_wifi_sendUDPmsg(int sckt, char* msg, int len){
    // Prepare the address to sent to via BROADCAST
    struct sockaddr_in sDestAddr;
    // Initialize the address
    // memset((char *)&sDestAddr, 0, sizeof(sDestAddr));

    sDestAddr.sin_family = AF_INET;
    sDestAddr.sin_len = sizeof(sDestAddr);
    sDestAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    sDestAddr.sin_port = UDP_SOCKET_PORT;

    if(sendto(sckt, msg, len, 0, (struct sockaddr *)&sDestAddr, sizeof(sDestAddr)) < len){
         printf("UDP message couldn't be sent.");
    }
}

And finally, receiving messages would work like this:

void lavor_wifi_processor(void* sckt){
    int nbytes;
    char buffer[UDP_BUFF_LEN];
    // Listen for incoming messages as long as the socket is open
    while(1){   // TO DO: Test if socket open
        // Try to read new data arrived at the socket
        nbytes = recv(*((int *)sckt), buffer, sizeof(buffer), 0);
    ...

But even if I just try to call the above initialization function, the ESP goes wild and throws one Guru Meditation error after another.

Does anyone has experience with UDP communication in the descripted way?


问:
Extra underscored name in a c++ function
I understand what c++ functions need: type name (parameters) {statements}. What is it called when a function has an extra name like this:

```<code>_API8810AFUNC int API8810A_GetAPI8810AUSBDeviceCnt(int *pnUSBDeviceCnt);?
</code>```

_API8810AFUNC is defined as:

```<code>#ifdef _BUILD_API8810ADLL
#define _API8810AFUNC  __declspec(dllexport )
#else
</code>```

Does the "_API8810AFUNC" mean the function needs to be called differently? And does this have a name in c++?

答:
It depends.

In this case, it's a macro — and one with an illegal name, to boot* — that expands to __declspec(dllexport). We can easily Google this to find that it's a Microsoft attribute for use with DLLs.

It could also have expanded [conditionally] to nothing, or it could have expanded to a different attribute, or it could expand to a storage class specifier (like static or extern).

To directly answer your question, the actual syntax of a function definition, per C++14, is as follows:

function-definition:

   attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt function-body

function-body:

   ctor-initializeropt compound-statement

   function-try-block

   = default ;

   = delete ;

So it's a little more complicated than "type name (parameters) {statements}", but you're not far off.

* [C++14: 17.6.4.3.2]: [..] Each name that [..] begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use. [..]

Body:
I understand what c++ functions need: type name (parameters) {statements}. What is it called when a function has an extra name like this:

_API8810AFUNC int API8810A_GetAPI8810AUSBDeviceCnt(int *pnUSBDeviceCnt);?

_API8810AFUNC is defined as:

#ifdef _BUILD_API8810ADLL
#define _API8810AFUNC  __declspec(dllexport )
#else

Does the "_API8810AFUNC" mean the function needs to be called differently? And does this have a name in c++?


问:
Sort items by name in template instead of controller
Here is my runable Plunker

I want to sort items by name. This is the bug, for the top one, "Please select a student name", it displays as an empty field.

```<code><select ng-options="student as student.name for student in students | orderBy: sortNameExcludeTopOne"
        ng-model = "student">
</select>

$scope.sortNameExcludeTopOne = function(student) {
        if (student.id === 0) {
          return -1;
        }
        return student.name;
      }
</code>```

What I want:

Now I sort items by its name by using a custom function in the controller, can we do sort items by its name in the template? instead of in controller?

What UI I want for select is:
"Please select a student name" -> "Bar" -> "Foo"

Update: I want the "Please select a student name" at the top of select

答:
You want the options available to them sorted by the name:

```<code><select ng-options="student as student.name for student in students | orderBy: 'name'" ng-model="student">
</select>
</code>```

That should sort the students by their 'name' property.

Edit:
If you want to add the extra option at the top, then, use your controller to sort the 'students' first:

```<code>students() {
  const studentList = someStudents();
  studentList.sort((a, b) => {
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
  });
  studentList.unshift({ new: option, goes: here });
}
</code>```

Then you can sort it there, and insert one more option at the beginning with the option you want visible.

Incidentally you could use orderBy: 'name' still, assuming your options are based on 'value'; you'd have to have one more default entry with a numeric value like so:

```<code><select ng-options="student as student.name for student in students | orderBy: 'name'"
  ng-model="student">
  <option value="-1">Please select a student name:</option>
</select>
</code>```

Body:
Here is my runable Plunker

I want to sort items by name. This is the bug, for the top one, "Please select a student name", it displays as an empty field.

<select ng-options="student as student.name for student in students | orderBy: sortNameExcludeTopOne"
        ng-model = "student">
</select>

$scope.sortNameExcludeTopOne = function(student) {
        if (student.id === 0) {
          return -1;
        }
        return student.name;
      }

What I want:

Now I sort items by its name by using a custom function in the controller, can we do sort items by its name in the template? instead of in controller?

What UI I want for select is:
"Please select a student name" -> "Bar" -> "Foo"

Update: I want the "Please select a student name" at the top of select

Body:
You want the options available to them sorted by the name:

<select ng-options="student as student.name for student in students | orderBy: 'name'" ng-model="student">
</select>

That should sort the students by their 'name' property.

Edit:
If you want to add the extra option at the top, then, use your controller to sort the 'students' first:

students() {
  const studentList = someStudents();
  studentList.sort((a, b) => {
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
  });
  studentList.unshift({ new: option, goes: here });
}

Then you can sort it there, and insert one more option at the beginning with the option you want visible.

Incidentally you could use orderBy: 'name' still, assuming your options are based on 'value'; you'd have to have one more default entry with a numeric value like so:

<select ng-options="student as student.name for student in students | orderBy: 'name'"
  ng-model="student">
  <option value="-1">Please select a student name:</option>
</select>


问:
Record audio/video in skype for business online - skype web sdk
I did not find any information available online on how to record a meeting(audio or video) scheduled using skype for business online (skype web sdk).

All I see is information only on skype for business onpremises which full clients to record and store meeting in local storage.

It will be very grateful if someone can provide references on recording audio/video using skype for business - online.

答:
Now Skype for Business Online Plan 2 supports Audio and Video Recordings.  You can find the detailed feature comparision here

After a lot of research, i have decided to use Skype Media bot along with Skype Web SDK to record audio and video conversations.

Create a Skype Media Bot and add Skype for Business as channel.

Register this bot with Skype for Business online ( Only Tenant Administrator can do that)

Make sure in each conference, this Skype Bot is also invited by default. So this bot is a participant in each conference call. It records audio and video.

Skype Bot has simple interface to Record, Respond, Convert audio to text and many more features.

Github samples can be found here


问:
Error in ocrFile function in AbbyyR package
While I was using Abbyy cloud SDK for OCR, I keep on getting the error below when I try to use the ocrFile function which is inside the AbbyyR package.

" Error in curl_download(finishedlist$resultUrl[res$id == finishedlist$id],  :
  Argument 'url' must be string. "

When I send the files to the cloud and process them everything works fine but when the cloud returns the files there is a problem in downloading them. I thought that it might be a network or certificate problem but I can't solve the problem.

Thanks in advance

答:
There is a problem in source code, it needs as.character() function for url.
I updated ocrFile function as follows:

```<code>    install.packages("curl")
    library(curl)

    new_ocrFile<-function (file_path = "", output_dir = "./", exportFormat = c("txt",
                                                                  "txtUnstructured", "rtf", "docx", "xlsx", "pptx", "pdfSearchable",
                                                                  "pdfTextAndImages", "pdfa", "xml", "xmlForCorrectedImage",
                                                                  "alto"), save_to_file = TRUE)
    {
      exportFormat <- match.arg(exportFormat)
      res <- processImage(file_path = file_path, exportFormat = exportFormat)
      while (!(any(as.character(res$id) == as.character(listFinishedTasks()$id)))) {
        Sys.sleep(1)
      }
      finishedlist <- listFinishedTasks()
      res$id <- as.character(res$id)
      finishedlist$id <- as.character(finishedlist$id)
      if (identical(save_to_file, FALSE)) {
        res <- curl_fetch_memory(as.character(finishedlist$resultUrl[res$id ==
                                                          finishedlist$id]))
        return(rawToChar(res$content))
      }
      curl_download(as.character(finishedlist$resultUrl[res$id == finishedlist$id]),
                    destfile = paste0(output_dir, unlist(strsplit(basename(file_path),
                                                                  "[.]"))[1], ".", exportFormat))
    }
</code>```

I hope, it helps.

Body:
There is a problem in source code, it needs as.character() function for url.
I updated ocrFile function as follows:

    install.packages("curl")
    library(curl)

    new_ocrFile<-function (file_path = "", output_dir = "./", exportFormat = c("txt",
                                                                  "txtUnstructured", "rtf", "docx", "xlsx", "pptx", "pdfSearchable",
                                                                  "pdfTextAndImages", "pdfa", "xml", "xmlForCorrectedImage",
                                                                  "alto"), save_to_file = TRUE)
    {
      exportFormat <- match.arg(exportFormat)
      res <- processImage(file_path = file_path, exportFormat = exportFormat)
      while (!(any(as.character(res$id) == as.character(listFinishedTasks()$id)))) {
        Sys.sleep(1)
      }
      finishedlist <- listFinishedTasks()
      res$id <- as.character(res$id)
      finishedlist$id <- as.character(finishedlist$id)
      if (identical(save_to_file, FALSE)) {
        res <- curl_fetch_memory(as.character(finishedlist$resultUrl[res$id ==
                                                          finishedlist$id]))
        return(rawToChar(res$content))
      }
      curl_download(as.character(finishedlist$resultUrl[res$id == finishedlist$id]),
                    destfile = paste0(output_dir, unlist(strsplit(basename(file_path),
                                                                  "[.]"))[1], ".", exportFormat))
    }

I hope, it helps.


问:
How to quickly build a two dimensional array from two arrays using FP or 3rd party library
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

```<code> double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }
</code>```

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

答:
The quickest way will be either what you have written, or this:

```<code>    double xy[][] = new double[x.length][];
    for (int i = 0; i< x.length; i++) {
        xy[i] = new double[]{x[i], y[i]};
    }
</code>```

Now you could also do this:

```<code>    double xy[][] = {x, y};
</code>```

However that is creating an N x 2 array rather than a 2 x N array.  Furthermore, the x and y arrays have now been incorporated into the xy array.  That is semantically different to your version (and mine) where the arrays x and y will be distinct from xy.

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

Well, there probably is a way to code this using streams, but it is unlikely to be quicker / more efficient than a simple loop.  Or at least, not in Java 8.

Here's one possible solution (not tested!):

```<code>   double[][] xy = IntStream.range(0, x.length - 1)
         .map(lambda i: new double[]{x[i], y[i]})
         .collect(Collectors.toList())
         .toArray(new double[0][0]);
</code>```

Body:
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

 double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

Body:
The quickest way will be either what you have written, or this:

    double xy[][] = new double[x.length][];
    for (int i = 0; i< x.length; i++) {
        xy[i] = new double[]{x[i], y[i]};
    }

Now you could also do this:

    double xy[][] = {x, y};

However that is creating an N x 2 array rather than a 2 x N array.  Furthermore, the x and y arrays have now been incorporated into the xy array.  That is semantically different to your version (and mine) where the arrays x and y will be distinct from xy.

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

Well, there probably is a way to code this using streams, but it is unlikely to be quicker / more efficient than a simple loop.  Or at least, not in Java 8.

Here's one possible solution (not tested!):

   double[][] xy = IntStream.range(0, x.length - 1)
         .map(lambda i: new double[]{x[i], y[i]})
         .collect(Collectors.toList())
         .toArray(new double[0][0]);


问:
SQL Server HASHBYTES conversion inconsistency?
When I execute this hardcoded, I get the correct result:

```<code>Declare @result nvarchar(32)

Set @result = convert(varchar(32), hashbytes('MD5', '1' + 'One' + 'Two' + 'Three'), 2)

select @result
</code>```

Result: 4173AB4C6EE66BC1FF7B7E5D44A872CA (correct)

But when I call/execute this stored procedure, giving it the same parameters, it's a different result

```<code>ALTER Procedure [db_owner].[CheckTheTransaction]
    @DataID nvarchar(50),
    @Data1 nvarchar(50),
    @Data2 nvarchar(50),
    @Data3 nvarchar(50)
as
    Declare @result nvarchar(32)
    Set @result = convert(varchar(32), hashbytes('MD5', @DataID + @Data1 + @Data2 + @Data3), 2)

    Select @result
</code>```

My execution:

```<code>DECLARE @result int

EXEC    @result = [db_owner].[CheckTheTransaction]
        @DataID = '1',
        @Data1 = 'One',
        @Data2 = 'Two',
        @Data3 = 'Three'

SELECT  'Result' = @result

GO
</code>```

Result: 5BD42777932EE959AD5A4C9FEE142F00 (wrong)

Where did I go wrong?

答:
That is a data type issue. You will see it match by changing the T-SQ script to followings.

Declare @result nvarchar(32)

Set @result = convert(varchar(32), hashbytes('MD5', N'1' + N'One' + N'Two' + N'Three'), 2)

select @result

Body:
When I execute this hardcoded, I get the correct result:

Declare @result nvarchar(32)

Set @result = convert(varchar(32), hashbytes('MD5', '1' + 'One' + 'Two' + 'Three'), 2)

select @result

Result: 4173AB4C6EE66BC1FF7B7E5D44A872CA (correct)

But when I call/execute this stored procedure, giving it the same parameters, it's a different result

ALTER Procedure [db_owner].[CheckTheTransaction]
    @DataID nvarchar(50),
    @Data1 nvarchar(50),
    @Data2 nvarchar(50),
    @Data3 nvarchar(50)
as
    Declare @result nvarchar(32)
    Set @result = convert(varchar(32), hashbytes('MD5', @DataID + @Data1 + @Data2 + @Data3), 2)

    Select @result

My execution:

DECLARE @result int

EXEC    @result = [db_owner].[CheckTheTransaction]
        @DataID = '1',
        @Data1 = 'One',
        @Data2 = 'Two',
        @Data3 = 'Three'

SELECT  'Result' = @result

GO

Result: 5BD42777932EE959AD5A4C9FEE142F00 (wrong)

Where did I go wrong?


问:
plot multiple Y values against a single X values
I have four lists with data:

[RED_LIST], [GRE_LIST], [REG_LIST], [NIR_LIST]

Each list has data like this ...

```<code> 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
</code>```

I have already plotted each one as Y values against X :

I want now to plot the four lists in one figure against the same X values.

How can I do it?

WHAT I HAVE TRIED:

```<code># Create a list of 4 X vales
X =[[X1],[X2],[X3],[X4]]
# Create one list of Y valeus containing the foue lists
Y = [[RED_LIST],[GRE_LIST],[REG_LIST],[NIR_LIST]]

plt.figure()
plt.plot(X,Y),plt.title("Bande Passante vs Reflectance Capteur:"),plt.xlabel("Bande Passante"),plt.ylabel("log1/Reflectance")
</code>```

EDIT & SOLUTION

So the question was solved by @Paul H and here is the solution:

```<code>fig, ax = plt.subplots()
for Y in [RED_LIST , GRE_LIST , REG_LIST , NIR_LIST]:
    ax.plot(X, Y)
</code>```

答:
I suggest</p>

```<code>fig, ax = plt.subplots()
for Y in [YY_RED, YY_REG, YY_NIR, YY_GRE]:
    ax.plot(X, Y)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have four lists with data:

[RED_LIST], [GRE_LIST], [REG_LIST], [NIR_LIST]

Each list has data like this ...

 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,
 1.6044503709230613,

I have already plotted each one as Y values against X :

I want now to plot the four lists in one figure against the same X values.

How can I do it?

WHAT I HAVE TRIED:

# Create a list of 4 X vales
X =[[X1],[X2],[X3],[X4]]
# Create one list of Y valeus containing the foue lists
Y = [[RED_LIST],[GRE_LIST],[REG_LIST],[NIR_LIST]]

plt.figure()
plt.plot(X,Y),plt.title("Bande Passante vs Reflectance Capteur:"),plt.xlabel("Bande Passante"),plt.ylabel("log1/Reflectance")

EDIT & SOLUTION

So the question was solved by @Paul H and here is the solution:

fig, ax = plt.subplots()
for Y in [RED_LIST , GRE_LIST , REG_LIST , NIR_LIST]:
    ax.plot(X, Y)

Body:
I suggest

fig, ax = plt.subplots()
for Y in [YY_RED, YY_REG, YY_NIR, YY_GRE]:
    ax.plot(X, Y)


问:
How to limit table search to specific rows that contain specific text in a column
I am searching in my table with a function:

```<code>//search field for table
$("#search_field").keyup(function() {
var value = this.value;

$("#menu_table").find("tr").each(function(index) {
    if (index === 0) return;
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);

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

Fourth coulmn of data is Type i.e. Chicken, Kebabs etc.
I want to search only in those rows whose 4th column contains ('Chicken'). It should not search in rows whose Type is 'Kebabs'. The code above is searching in all rows.

答:
Use jQuery :contains(text) selector.

```<code>$("#menu_table").find("tr:contains('Chicken')").each(function(index) {
    if($(this).children('td').eq(3).text() == "Chicken"){
        /* Do something */
    }
});
</code>```

Working example: https://jsfiddle.net/kvvnjmup/4/

$('#menu_table').find('tr:contains("Chicken")').each(function(){
    if($(this).children('td').eq(3).text() == "Chicken"){
        alert($(this).prop('id'));
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="menu_table">
<tbody><tr id="1">
  <td></td>
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td></td>
</tr>
<tr id="2">
  <td></td>
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td></td>
</tr>
<tr id="3">
  <td></td>
  <td></td>
  <td></td>
  <td>pasta</td>
  <td></td>
</tr>
 <tr id="4">
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td>pasta</td>
  <td></td>
</tr>
</tbody>
</table></code>```

Body:
I am searching in my table with a function:

//search field for table
$("#search_field").keyup(function() {
var value = this.value;

$("#menu_table").find("tr").each(function(index) {
    if (index === 0) return;
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);

});});

Fourth coulmn of data is Type i.e. Chicken, Kebabs etc.
I want to search only in those rows whose 4th column contains ('Chicken'). It should not search in rows whose Type is 'Kebabs'. The code above is searching in all rows.

Body:
Use jQuery :contains(text) selector.

$("#menu_table").find("tr:contains('Chicken')").each(function(index) {
    if($(this).children('td').eq(3).text() == "Chicken"){
        /* Do something */
    }
});

Working example: https://jsfiddle.net/kvvnjmup/4/

$('#menu_table').find('tr:contains("Chicken")').each(function(){
    if($(this).children('td').eq(3).text() == "Chicken"){
        alert($(this).prop('id'));
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="menu_table">
<tbody><tr id="1">
  <td></td>
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td></td>
</tr>
<tr id="2">
  <td></td>
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td></td>
</tr>
<tr id="3">
  <td></td>
  <td></td>
  <td></td>
  <td>pasta</td>
  <td></td>
</tr>
 <tr id="4">
  <td></td>
  <td></td>
  <td>Chicken</td>
  <td>pasta</td>
  <td></td>
</tr>
</tbody>
</table>


问:
Does an additional "AND `columnname` LIKE '%'" hurt performance?

simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

```<code>AND `name` LIKE '%'
</code>```

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?

答:
I agree with the previous answers: LIKE is pretty expensive. If your table is properly indexed, a small result-set can be additionally queried using LIKE.

In conjunction with OR the query is going to be brutally expensive again, though.

Also, solely using LIKE to query an indexed VARCHAR field should present minimal performance gain at best.

Body:
simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

AND `name` LIKE '%'

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?


问:
Curl execution in python failed
I wanted to download files for around 300 item. An example is below:

```<code>curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml
</code>```

This opens the page and downloads the content and stores it as xml file in my end

I tried to do a batch script in perl with system command, like

```<code>system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1'
-b cookies > Absrep1.xml');
</code>```

But, it did not work. There was syntax error, which I guess is due to single quotes.

I tried with python,

```<code>import subprocess
bash_com = 'curl "http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1" '
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])
</code>```

It did not work. I get the error, File does not exist. Even if it works, how can I include the

-b cookies > Absrep1.xml'

part in it?

Please help. Thanks in Advance,

AP

答:
The syntax error is almost certainly down to the quotes in the system call:

system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml');

The single quotes either need to be escaped or alternative parentheses can be used such as double quotes or custom parentheses with q or qq, eg:

system(q{curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml});

It's hard to tell from the context given, but wrapping the curl call in perl or python would likely be a less than optimal approach. Perl has LWP, Python has requests, and the bash shell is already well equipped to run simple batch jobs. It might be best to stick to a single interpreter unless there's a good reason not to.

Title: Curl execution in python failed

Body:
I wanted to download files for around 300 item. An example is below:

curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml

This opens the page and downloads the content and stores it as xml file in my end

I tried to do a batch script in perl with system command, like

system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1'
-b cookies > Absrep1.xml');

But, it did not work. There was syntax error, which I guess is due to single quotes.

I tried with python,

import subprocess
bash_com = 'curl "http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1" '
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])

It did not work. I get the error, File does not exist. Even if it works, how can I include the

-b cookies > Absrep1.xml'

part in it?

Please help. Thanks in Advance,

AP


问:
Array reclassification with numpy
I have a large (50000 x 50000) 64-bit integer NumPy array containing 10-digit numbers.  There are about 250,000 unique numbers in the array.

I have a second reclassification table which maps each unique value from the first array to an integer between 1 and 100.  My hope would be to reclassify the values from the first array to the corresponding values in the second.

I've tried two methods of doing this, and while they work, they are quite slow. In both methods I create a blank (zeros) array of the same dimensions.

```<code>new_array = np.zeros(old_array.shape)
</code>```

First method:

```<code>for old_value, new_value in lookup_array:
    new_array[old_array == old_value] = new_value
</code>```

Second method, where lookup_array is in a pandas dataframe with the headings "Old" and "New:

```<code>for new_value, old_values in lookup_table.groupby("New"):
    new_array[np.in1d(old_array, old_values)] = new_value
</code>```

Is there a faster way to reclassify values

答:
Store the lookup table as a 250,000 element array where for each index you have the mapped value. For example, if you have something like:

```<code>lookups = [(old_value_1, new_value_1), (old_value_2, new_value_2), ...]
</code>```

Then you can do:

```<code>idx, val = np.asarray(lookups).T
lookup_array = np.zeros(idx.max() + 1)
lookup_array[idx] = val
</code>```

When you get that, you can get your transformed array simply as:

```<code>new_array = lookup_array[old_array]
</code>```

Title: Array reclassification with numpy

Body:
I have a large (50000 x 50000) 64-bit integer NumPy array containing 10-digit numbers.  There are about 250,000 unique numbers in the array.

I have a second reclassification table which maps each unique value from the first array to an integer between 1 and 100.  My hope would be to reclassify the values from the first array to the corresponding values in the second.

I've tried two methods of doing this, and while they work, they are quite slow. In both methods I create a blank (zeros) array of the same dimensions.

new_array = np.zeros(old_array.shape)

First method:

for old_value, new_value in lookup_array:
    new_array[old_array == old_value] = new_value

Second method, where lookup_array is in a pandas dataframe with the headings "Old" and "New:

for new_value, old_values in lookup_table.groupby("New"):
    new_array[np.in1d(old_array, old_values)] = new_value

Is there a faster way to reclassify values

Body:
Store the lookup table as a 250,000 element array where for each index you have the mapped value. For example, if you have something like:

lookups = [(old_value_1, new_value_1), (old_value_2, new_value_2), ...]

Then you can do:

idx, val = np.asarray(lookups).T
lookup_array = np.zeros(idx.max() + 1)
lookup_array[idx] = val

When you get that, you can get your transformed array simply as:

new_array = lookup_array[old_array]


问:
inner use of cursor outside declare block
I have to use a cursor inside a particular block which contains query with WHERE clause getting parameters dynamically...

Therefore how to use a cursor without declaring in DECLARE block.

(I can't use nested cursors - am looking for examples).

答:
You could use an Implicit Cursor that uses a local parameter to your procedure. Here is how it looks like:

```<code>declare
  v_parm varchar2(3) := 'Z';
begin
-- FIRST LOOP will display all objects owned by Z
  for x in ( select * from all_objects where owner=v_parm) loop
    dbms_output.put_line(x.object_name);
  end loop;
-- SECOND LOOP will display all objects owned by SYS until 100 is reached
--     (that would be a huge bunch otherwise!)
  v_parm := 'SYS';
  for x in ( select * from all_objects where owner=v_parm and rowid < 100) loop
    dbms_output.put_line(x.object_name);
  end loop;
end;
/
</code>```

Body:
You could use an Implicit Cursor that uses a local parameter to your procedure. Here is how it looks like:

declare
  v_parm varchar2(3) := 'Z';
begin
-- FIRST LOOP will display all objects owned by Z
  for x in ( select * from all_objects where owner=v_parm) loop
    dbms_output.put_line(x.object_name);
  end loop;
-- SECOND LOOP will display all objects owned by SYS until 100 is reached
--     (that would be a huge bunch otherwise!)
  v_parm := 'SYS';
  for x in ( select * from all_objects where owner=v_parm and rowid < 100) loop
    dbms_output.put_line(x.object_name);
  end loop;
end;
/


问:
Sorting collection of posts in latest version of Assemble
I’m trying to migrate an old site I have from grunt-assemble over to assemble (with gulp).

I’ve managed to work out a lot of the differences but I’m not really sure how collections now work and how to make a collection of posts and then sort them.

The old config I had in grunt-assemble was like this:

```<code>grunt.initConfig({
  assemble: {
    posts: {
      options: {
        collections: [{
          name: 'post',
          sortby: 'posted',
          sortorder: 'descending'
        }],
        permalinks: {
          structure: ':url.html'
        }
      },
      files: [{
        cwd: './src/templates/pages/blog/',
        dest: '<%= site.destination %>/blog',
        expand: true,
        src: ['**/*.hbs', '**/*.md']
      }]
    }
  }
});
</code>```

How can I convert this to work in the latest version of Assemble?

答:
You can use a combination of the {{items}} helper from assemble-helpers and the withSort helper from handlebars-helpers to accomplish your goal:

```<code>{{#withSort "data.posted" (items "posts") reverse=true}}
  {{this.data.title}}
{{/withSort}}
</code>```

This also assumes that you've created a "posts" view collection and you're loading your "posts" into it:

```<code>// create the "posts" view collection (usually done outside of a task)
app.create('posts');

// load markdown posts into the "posts" view collection (usually done in a "load" task
app.posts('path/to/posts/*.md');
</code>```

Body:
I’m trying to migrate an old site I have from grunt-assemble over to assemble (with gulp).

I’ve managed to work out a lot of the differences but I’m not really sure how collections now work and how to make a collection of posts and then sort them.

The old config I had in grunt-assemble was like this:

grunt.initConfig({
  assemble: {
    posts: {
      options: {
        collections: [{
          name: 'post',
          sortby: 'posted',
          sortorder: 'descending'
        }],
        permalinks: {
          structure: ':url.html'
        }
      },
      files: [{
        cwd: './src/templates/pages/blog/',
        dest: '<%= site.destination %>/blog',
        expand: true,
        src: ['**/*.hbs', '**/*.md']
      }]
    }
  }
});

How can I convert this to work in the latest version of Assemble?

Body:
You can use a combination of the {{items}} helper from assemble-helpers and the withSort helper from handlebars-helpers to accomplish your goal:

{{#withSort "data.posted" (items "posts") reverse=true}}
  {{this.data.title}}
{{/withSort}}

This also assumes that you've created a "posts" view collection and you're loading your "posts" into it:

// create the "posts" view collection (usually done outside of a task)
app.create('posts');

// load markdown posts into the "posts" view collection (usually done in a "load" task
app.posts('path/to/posts/*.md');


问:
IF EXISTS then Update else do Nothing - SQL SERVER 2012
I have a table which assigns roles to particular users. I am doing mass update to this table where in I am end dating some users previous roles and after that is completed assigning them new roles by inserting into this table.

I am doing both these actions separately. For my first action my code goes like this.

```<code>UPDATE userrolelist
SET effectiveend = '2016-01-20 00:00:00.000'
where userid IN ('150920','160847','160848','160849')
and roleid = '1037' and effectiveend IS NULL
</code>```

This works if there is no end date assigned to that role but if there is an end date for even 1 user the whole update statement terminates. I want to use an IF EXISTS statement to first check if an end date for this user and this role exists if not then do the update else do nothing.

Inserting is similar. I am running a 100 inserts based on the user that need to have new roles. Now again when i run these insert statements if it finds any duplicates it errors out.

```<code>Insert into userrolelist (Userid, Roleid, IsDefault, EffectiveStart,
EffectiveEnd, Clientid, LastmodifiedUserId, LastmodifiedTimestamp)
Values
(161514,1011,1,'2016-01-21 00:00:00.001',Null,16785,0,'2016-01-21
00:00:00.001')
</code>```

Table structure:

答:
I am not sure I understood correctly your question, but maybe you can try this:

```<code>UPDATE A SET EFFECTIVEEND = '2016-01-20 00:00:00.000'
FROM USERROLELIST A
WHERE A.USERID IN ('150920','160847','160848','160849')
AND A.ROLEID = '1037' AND A.EFFECTIVEEND IS NULL
AND NOT EXISTS(SELECT 1 FROM USERROLELIST B WHERE B.USERID IN ('150920','160847','160848','160849') AND B.effectiveend IS NOT NULL) ;
</code>```

Sample data:

```<code>CREATE TABLE USERROLELIST  (USERID INT, ROLEID INT, EFFECTIVEEND DATETIME);
INSERT INTO USERROLELIST VALUES (150920, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160847, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160848, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160849, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160850, 1037,NULL);
</code>```

Output:

```<code>USERID  ROLEID  EFFECTIVEEND
150920  1037    2016-01-20 00:00:00.000
160847  1037    2016-01-20 00:00:00.000
160848  1037    2016-01-20 00:00:00.000
160849  1037    2016-01-20 00:00:00.000
160850  1037    NULL
</code>```

Sample2:

```<code>TRUNCATE TABLE USERROLELIST
INSERT INTO USERROLELIST VALUES (150920, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160847, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160848, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160849, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160850, 1037,NULL);
UPDATE USERROLELIST SET EFFECTIVEEND='20160119' WHERE USERID=150920;
</code>```

Output:

```<code>USERID  ROLEID  EFFECTIVEEND
150920  1037    2016-01-19 00:00:00.000
160847  1037    NULL
160848  1037    NULL
160849  1037    NULL
160850  1037    NULL
</code>```

Body:
I have a table which assigns roles to particular users. I am doing mass update to this table where in I am end dating some users previous roles and after that is completed assigning them new roles by inserting into this table.

I am doing both these actions separately. For my first action my code goes like this.

UPDATE userrolelist
SET effectiveend = '2016-01-20 00:00:00.000'
where userid IN ('150920','160847','160848','160849')
and roleid = '1037' and effectiveend IS NULL

This works if there is no end date assigned to that role but if there is an end date for even 1 user the whole update statement terminates. I want to use an IF EXISTS statement to first check if an end date for this user and this role exists if not then do the update else do nothing.

Inserting is similar. I am running a 100 inserts based on the user that need to have new roles. Now again when i run these insert statements if it finds any duplicates it errors out.

Insert into userrolelist (Userid, Roleid, IsDefault, EffectiveStart,
EffectiveEnd, Clientid, LastmodifiedUserId, LastmodifiedTimestamp)
Values
(161514,1011,1,'2016-01-21 00:00:00.001',Null,16785,0,'2016-01-21
00:00:00.001')

Table structure:

Body:
I am not sure I understood correctly your question, but maybe you can try this:

UPDATE A SET EFFECTIVEEND = '2016-01-20 00:00:00.000'
FROM USERROLELIST A
WHERE A.USERID IN ('150920','160847','160848','160849')
AND A.ROLEID = '1037' AND A.EFFECTIVEEND IS NULL
AND NOT EXISTS(SELECT 1 FROM USERROLELIST B WHERE B.USERID IN ('150920','160847','160848','160849') AND B.effectiveend IS NOT NULL) ;

Sample data:

CREATE TABLE USERROLELIST  (USERID INT, ROLEID INT, EFFECTIVEEND DATETIME);
INSERT INTO USERROLELIST VALUES (150920, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160847, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160848, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160849, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160850, 1037,NULL);

Output:

USERID  ROLEID  EFFECTIVEEND
150920  1037    2016-01-20 00:00:00.000
160847  1037    2016-01-20 00:00:00.000
160848  1037    2016-01-20 00:00:00.000
160849  1037    2016-01-20 00:00:00.000
160850  1037    NULL

Sample2:

TRUNCATE TABLE USERROLELIST
INSERT INTO USERROLELIST VALUES (150920, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160847, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160848, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160849, 1037,NULL);
INSERT INTO USERROLELIST VALUES (160850, 1037,NULL);
UPDATE USERROLELIST SET EFFECTIVEEND='20160119' WHERE USERID=150920;

Output:

USERID  ROLEID  EFFECTIVEEND
150920  1037    2016-01-19 00:00:00.000
160847  1037    NULL
160848  1037    NULL
160849  1037    NULL
160850  1037    NULL


问:
How do you use the Contentful Middleman preview API in different build environment?
Here's what I'm trying to achieve in principle, which obviously doesn't work since the contentful data needs to be retrieved before the build:

```<code># Build command
bundle exec middleman contentful && bundle exec middleman build -e <ENV>
</code>```

# config.rb

configure :prod do
  set :build_dir, 'build/prod'
  set :ENV, 'prod'

  activate :contentful do |f|
    f.space         = { hs: 'SPACE' }
    f.access_token  = 'TOKEN'
    f.cda_query     = { include: 2 }
    f.all_entries   = true
    f.content_types = { #... }
  end
end

configure :testSite do
  set :build_dir, 'build/test-site'
  set :ENV, 'test'

  activate :contentful do |f|
    use_preview_api = true
    #...
  end
end
```

答:
You can use environment variables to switch on that.

```<code># Build command
CONTENTFUL_ENV=<env> bundle exec middleman contentful && bundle exec middleman build -e <env>

# config.rb
access_token = nil
use_preview = false
case ENV['CONTENTFUL_ENV']
when 'prod'
  access_token = ENV['CONTENTFUL_PROD_TOKEN']
when 'testSite'
  access_token = ENV['CONTENTFUL_TEST_TOKEN']
  use_preview = true
end

activate :contentful do |f|
  f.space = {space_alias: ENV['CONTENTFUL_SPACE']}
  f.use_preview_api = use_preview
  f.access_token = access_token
  # ...
end
</code>```

This way you can have multiple environments working together

Body:
Here's what I'm trying to achieve in principle, which obviously doesn't work since the contentful data needs to be retrieved before the build:

# Build command
bundle exec middleman contentful && bundle exec middleman build -e <ENV>

# config.rb

configure :prod do
  set :build_dir, 'build/prod'
  set :ENV, 'prod'

  activate :contentful do |f|
    f.space         = { hs: 'SPACE' }
    f.access_token  = 'TOKEN'
    f.cda_query     = { include: 2 }
    f.all_entries   = true
    f.content_types = { #... }
  end
end

configure :testSite do
  set :build_dir, 'build/test-site'
  set :ENV, 'test'

  activate :contentful do |f|
    use_preview_api = true
    #...
  end
end

Body:
You can use environment variables to switch on that.

# Build command
CONTENTFUL_ENV=<env> bundle exec middleman contentful && bundle exec middleman build -e <env>

# config.rb
access_token = nil
use_preview = false
case ENV['CONTENTFUL_ENV']
when 'prod'
  access_token = ENV['CONTENTFUL_PROD_TOKEN']
when 'testSite'
  access_token = ENV['CONTENTFUL_TEST_TOKEN']
  use_preview = true
end

activate :contentful do |f|
  f.space = {space_alias: ENV['CONTENTFUL_SPACE']}
  f.use_preview_api = use_preview
  f.access_token = access_token
  # ...
end

This way you can have multiple environments working together


问:
Retrieve the headers in excel using Python

I want to retrieve headers of this excel file (Only A,B,C)and store it in a list using Python. I opened my file but I am unable to retrieve it.

```<code>import xlrd
file_location= "C:/Users/Desktop/Book1.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
</code>```

Can anyone please help me with that? I am new to Python.

Thank you for your help.

答:
```<code>iterheaders = iter(sheet.row(1))
headers = [str(cell.value) for cell in iterheaders[1:] if cell is not None and cell.value != '']
</code>```

Hope that helps...

Body:
I want to retrieve headers of this excel file (Only A,B,C)and store it in a list using Python. I opened my file but I am unable to retrieve it.

import xlrd
file_location= "C:/Users/Desktop/Book1.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)

Can anyone please help me with that? I am new to Python.

Thank you for your help.

Body:
iterheaders = iter(sheet.row(1))
headers = [str(cell.value) for cell in iterheaders[1:] if cell is not None and cell.value != '']

Hope that helps...


问:
Stax considers Text+CDATA+Text to be a single CHARACTERS section
Using Stax, I'm surprised to find that an XML block such as:

```<code><badger>
    <![CDATA[Text about a badger]]>
</badger>
</code>```

is treated as if it were:

```<code>START_ELEMENT (badger)
CHARACTERS (        Text about a badger    )
END_ELEMENT (badger)
</code>```

That is, the CDATA and the surrounding text are flattened into one text element. There is no CDATA element detected.

Is this correct behaviour? How can I separate the whitespace from the CDATA?

I am using the woodstox implementation.

答:
I suspect you have property 'XMLInputFactory.IS_COALESCING' set to true (or, are using Woodstox 3.2 that had it enabled by default -- which is not the default stax specs suggest, i.e. was a minor bug). This forces both conversion of CDATA into CHARACTERS, and coalesces adjacent text segments if any.

Other than this, Woodstox does report CDATA sections as distinct; but Stax specification has some 'interesting' requirements for convesion -- members of the expert group seemed to dislike idea of CDATA being handled any different from CHARACTERS.

So: if you do want to get them reported separate, make sure to disable IS_COALESCING:

```<code>inputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
</code>```

Body:
Using Stax, I'm surprised to find that an XML block such as:

<badger>
    <![CDATA[Text about a badger]]>
</badger>

is treated as if it were:

START_ELEMENT (badger)
CHARACTERS (        Text about a badger    )
END_ELEMENT (badger)

That is, the CDATA and the surrounding text are flattened into one text element. There is no CDATA element detected.

Is this correct behaviour? How can I separate the whitespace from the CDATA?

I am using the woodstox implementation.

Body:
I suspect you have property 'XMLInputFactory.IS_COALESCING' set to true (or, are using Woodstox 3.2 that had it enabled by default -- which is not the default stax specs suggest, i.e. was a minor bug). This forces both conversion of CDATA into CHARACTERS, and coalesces adjacent text segments if any.

Other than this, Woodstox does report CDATA sections as distinct; but Stax specification has some 'interesting' requirements for convesion -- members of the expert group seemed to dislike idea of CDATA being handled any different from CHARACTERS.

So: if you do want to get them reported separate, make sure to disable IS_COALESCING:

inputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);


问:
displaying the next hidden div with same class name
i created an array of similar elements in mvc razor which are hidden

```<code>  <button type="button" class="btn btn-primary addit" id="add"><i class="fa
  fa-plus"></i> Add Branch</button>
 <div id="parnt">
    @for (int w = 0; w < 10; ++w)
       {
         ViewBag.Branch = "branchform" + w;

         <div class="col-md-6 formBranch" id="@ViewBag.Branch" hidden="hidden" >
            <div class="jarviswidget Widget_margin col-md-10" data-widget-
    editbutton="false" data-widget-colorbutton="false" data-widget-
 deletebutton="true" data-widget-fullscreenbutton="false">

                <header>
                    <div class="jarviswidget-ctrls" role="menu" id="deleteButton" onclick="Remove('@ViewBag.Branch')"><a href="javascript:void(0);" class="button-icon jarviswidget-delete-btn" rel="tooltip" title=""><i class="fa fa-times"></i></a></div>

                    @*<span class="widget-icon"> <i class="fa fa-arrows-v"></i> </span>*@
                    <h2 class="font-md">Branch <span id="branchTitle">@w</span></h2>
                </header>

                <!-- widget div-->
                <div>

                    <!-- widget edit box -->
                    <div class="jarviswidget-editbox">
                        <!-- This area used as dropdown edit box -->

                    </div>
                    <!-- end widget edit box -->
                    <!-- widget content -->
                    <div class="widget-body form-horizontal" style="min-height:30px;">

                        <div class="form-group">
                            @Html.Label("Branch Type", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <select class="form-control" name="BranchId[]" id="BranchId1"><option>Head Office</option></select>
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("Branch Name", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Branch[]" id="Branch1" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("Address", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Address[]" id="Address1" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("Address 2", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Address2[]" id="Address21" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("City", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="City[]" id="City1" />
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("State", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <select class="form-control" name="State[]" id="State1"><option>Lagos</option></select>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>

    }
</div>
</code>```

how do i show the next hidden div in the array of div. i.e if first div is shown display the next available hidden div on button click using jquery.

i tried...

```<code>    jQuery(document).on("click", ".addit", function (e) {
        e.preventDefault();

        $("#parnt").next('.formBranch').show();

    })
</code>```

答:
Here's a simple solution which looks for the first element matching the .formBranch class with hidden="hidden" and displays it.

$(document).on("click", ".addit", function(e) {
  e.preventDefault();
  $("#parnt").children('.formBranch[hidden="hidden"]').first().attr("hidden", false);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parnt">
  <div class="formBranch" hidden="hidden">Hidden 1</div>
  <div class="formBranch" hidden="hidden">Hidden 2</div>
  <div class="formBranch" hidden="hidden">Hidden 3</div>
  <div class="formBranch" hidden="hidden">Hidden 4</div>
  <div class="formBranch" hidden="hidden">Hidden 5</div>
</div>
<button class="addit">Show it</button></code>```

Body:
i created an array of similar elements in mvc razor which are hidden

  <button type="button" class="btn btn-primary addit" id="add"> Add Branch</button>

    @for (int w = 0; w < 10; ++w)
       {
         ViewBag.Branch = "branchform" + w;

                    @*  *@

Branch @w

                            @Html.Label("Branch Type", new { @class = "col-md-2 control-label" })

                                <select class="form-control" name="BranchId[]" id="BranchId1"><option>Head Office</option></select>

                            @Html.Label("Branch Name", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Branch[]" id="Branch1" />

                            @Html.Label("Address", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Address[]" id="Address1" />

                            @Html.Label("Address 2", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Address2[]" id="Address21" />

                            @Html.Label("City", new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="City[]" id="City1" />

                            @Html.Label("State", new { @class = "col-md-2 control-label" })

                                <select class="form-control" name="State[]" id="State1"><option>Lagos</option></select>

    }

how do i show the next hidden div in the array of div. i.e if first div is shown display the next available hidden div on button click using jquery.

i tried...

    jQuery(document).on("click", ".addit", function (e) {
        e.preventDefault();

        $("#parnt").next('.formBranch').show();

    })

Body:
Here's a simple solution which looks for the first element matching the .formBranch class with hidden="hidden" and displays it.

$(document).on("click", ".addit", function(e) {
  e.preventDefault();
  $("#parnt").children('.formBranch[hidden="hidden"]').first().attr("hidden", false);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parnt">
  <div class="formBranch" hidden="hidden">Hidden 1</div>
  <div class="formBranch" hidden="hidden">Hidden 2</div>
  <div class="formBranch" hidden="hidden">Hidden 3</div>
  <div class="formBranch" hidden="hidden">Hidden 4</div>
  <div class="formBranch" hidden="hidden">Hidden 5</div>
</div>
<button class="addit">Show it</button>


问:
How to skip first few elements from array?
I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further.

for that I have tried following solution.

```<code>//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();
</code>```

This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line.

I have to use Array only due to carried on legacy. and very frequent ToArray() doesn't seem to be good for performance.

there is also possible solution,

```<code>//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements)
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);
</code>```

but this is even worse in time complexity.

Is there any better solution for this, which doesn't need casting from List to Array ?

答: you can use Skip(Provide number which you want to exclude).ToArray();</p>

Body:
I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further.

for that I have tried following solution.

//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();

This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line.

I have to use Array only due to carried on legacy. and very frequent ToArray() doesn't seem to be good for performance.

there is also possible solution,

//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements)
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);

but this is even worse in time complexity.

Is there any better solution for this, which doesn't need casting from List to Array ?


问:
spread operator in react throwing error of Unexpected token
Here is the code where I have included spread operator

```<code>style={{ ...styles.detailsRow.icon, alignSelf: 'centre' }}
</code>```

What things do I need to install or add to make it run?

And also what is its equivalent in es2015?

答:
You are missing one babel preset, stage-0

```<code>npm install --save-dev babel-preset-stage-0
</code>```

if you have .bablerc file add following to it.

```<code>{
  "presets":[
    "es2015", "react", "stage-0"
  ]
}
</code>```

Or added to webpack config in loader.

Body:
Here is the code where I have included spread operator

style={{ ...styles.detailsRow.icon, alignSelf: 'centre' }}

What things do I need to install or add to make it run?

And also what is its equivalent in es2015?

Body:
You are missing one babel preset, stage-0

npm install --save-dev babel-preset-stage-0

if you have .bablerc file add following to it.

{
  "presets":[
    "es2015", "react", "stage-0"
  ]
}

Or added to webpack config in loader.


问:
Draw polygons around clusters from hclust
I did clustering by using function hclust, now I want to draw polygons around each cluster!

How I can do it? I only have a group of point with the cluster id!

for example this image has two classes and 4 distinct areas! How I can get the number of these areas?

答:
You can do this using the convex hull function chull.

```<code>## First part sets up problem
library(cluster)        ## For Ruspinin data
Rusp_HC = hclust(dist(ruspini))
Cluster4 = cutree(Rusp_HC, 4)
plot(ruspini, pch=20, col=rainbow(4)[Cluster4])

##  Now get the polygons
for(i in 1:4) {
    ConvexHull = chull(ruspini[Cluster4 == i, ])
    polygon(ruspini[Cluster4 == i, ][ConvexHull,],
        border=rainbow(4)[i], col=rainbow(4, alpha=0.1)[i])
}
</code>```

Body:
You can do this using the convex hull function chull.

## First part sets up problem
library(cluster)        ## For Ruspinin data
Rusp_HC = hclust(dist(ruspini))
Cluster4 = cutree(Rusp_HC, 4)
plot(ruspini, pch=20, col=rainbow(4)[Cluster4])

##  Now get the polygons
for(i in 1:4) {
    ConvexHull = chull(ruspini[Cluster4 == i, ])
    polygon(ruspini[Cluster4 == i, ][ConvexHull,],
        border=rainbow(4)[i], col=rainbow(4, alpha=0.1)[i])
}


答:
You could also try using the numpy method loadtxt:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html
Which gives you arrays for each column (you can also skip specified columns so that you only get the A,B,C as you desire). You can write a for loop to get the first entry of each column and put them in a list.</p>

```<code>data = loadtxt("Book1.xlsx")
headers = []
for c in range(1,data.shape[0]):
    if data[c, 0] != "":
        headers.append(data[c, 0])
</code>```

Title: Retrieve the headers in excel using Python

Body:
You could also try using the numpy method loadtxt:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html
Which gives you arrays for each column (you can also skip specified columns so that you only get the A,B,C as you desire). You can write a for loop to get the first entry of each column and put them in a list.

data = loadtxt("Book1.xlsx")
headers = []
for c in range(1,data.shape[0]):
    if data[c, 0] != "":
        headers.append(data[c, 0])


问:
How do I iterate through a child's private fields?
After reading this question
One idea for my problem was to implement the method in the child classes like:

```<code>class Child {
    private $childField = "Want to see";
    public $pubChildField = "Will see";

    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
var_dump((new Child())->jsonSerialize());
</code>```

But for this I'd have to copycat the code in each child class. For readability, I want to refactor it into an (already existing) parentClass similar to:

```<code>abstract class parentClass {
    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
class Child extends parentClass {
    private $childField;
    public $pubChildField;
}
var_dump((new Child())->jsonSerialize());
</code>```

Both foreach ($this as $k=>$v) and get_object_vars() will get the public fields from the instance. I need to get it's private fields thou, for serialization.

Edit 1: Typo abstract method - what was i thinking

Edit 2: Clarified the example

Edit 3: Reformulated the question since there seemed to be misconception

答:
Abstract class is about abstract methods, not inherited. I assume these
are not relevant to the problem (otherwise make it ordinary default/base class).

private limits visibility to concrete class - use protected
instead.

It seems to me that you need only code reuse. You might reach for traits in this casse - traits becoming part of a class, and you can iterate private fields.

```<code>interface ArrayData {
    public function toArray(): array;
}

trait ToArray {
    public function toArray(): array {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = $value;
        }
        return $assoc;
    }
}

class Foo implements ArrayData {
    use ToArray;

    private $childField = "Want to see";
    public $pubChildField = "Will see";
}

$foo = new Foo();

var_dump($foo->toArray());
</code>```

Body:
After reading this question
One idea for my problem was to implement the method in the child classes like:

class Child {
    private $childField = "Want to see";
    public $pubChildField = "Will see";

    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
var_dump((new Child())->jsonSerialize());

But for this I'd have to copycat the code in each child class. For readability, I want to refactor it into an (already existing) parentClass similar to:

abstract class parentClass {
    public function method()
    {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = doStuff($value);
        }
        return $assoc;
    }
}
class Child extends parentClass {
    private $childField;
    public $pubChildField;
}
var_dump((new Child())->jsonSerialize());

Both foreach ($this as $k=>$v) and get_object_vars() will get the public fields from the instance. I need to get it's private fields thou, for serialization.

Edit 1: Typo abstract method - what was i thinking

Edit 2: Clarified the example

Edit 3: Reformulated the question since there seemed to be misconception

Body:
Abstract class is about abstract methods, not inherited. I assume these
are not relevant to the problem (otherwise make it ordinary default/base class).

private limits visibility to concrete class - use protected
instead.

It seems to me that you need only code reuse. You might reach for traits in this casse - traits becoming part of a class, and you can iterate private fields.

interface ArrayData {
    public function toArray(): array;
}

trait ToArray {
    public function toArray(): array {
        $assoc = []; // a associative array
        foreach ($this as $field => $value) {
            $assoc[$field] = $value;
        }
        return $assoc;
    }
}

class Foo implements ArrayData {
    use ToArray;

    private $childField = "Want to see";
    public $pubChildField = "Will see";
}

$foo = new Foo();

var_dump($foo->toArray());


问:
IBM Domino Designer stuck on 'Sync with ODP...'
I am using GitLab in combination with Sourcetree. Every time I want to commit something, I would go to my Domino Designer and right click the database, click Team Development and use 'Sync with ODP...'.

Most of the time everything works perfectly fine but sometimes the synchronization dialog pops up and just wont go away. In my Sourcetree I can see that some files are waiting to be commited but those files are not all.

So the dialog shows up, wont go away and says "Progress information" "Exporting..." and thats it.

There is no "use in background" button there and the 'cancel' button is disabled.

At this point the only thing I can do is to shut down the Designer using the task manager but the problem still wont go away even after restarting my computer and VirtualBox which I am working on (The designer runs on the VM). The only thing that changes: It sometimes gets stuck "later" in the progress.

I have read the designer hangs often due to automatic synchronization. In my case this feature is disabled.

Is there someone who can tell me what causes this problem and how I can fix it?
- Thank you in advance

(The synchronization is in progress for roughly four hours now, with no change)

答: Are you able to track it down to a specific design element? If there is a corruption in the DXL, the export to the ODP will probably fail. In Package Explorer you can use the "Open With..." right-click menu option to open as XML. Similarly, using the menu options to export as DXL might also highlight any corruption in DXL. Also, is the NSF local or on a server. If it's on a remote server, that may impact the performance of syncing to an ODP (which will be local).</p>


问:
Tensorflow installation
Upon trying to install Tensorflow for conda environment, I encountered with the following error message, without any progress:

tensorflow-1.1.0-cp35-cp35mwin_amd64.whl is not a supported wheel on this platform

答: Make sure that the Python version installed in the Environment is 3.5 not 3.6. Since 3.6 was released Conda automatically sets that version as default for python 3. However, it is still not supported by Tensorflow. </p>

Title: Tensorflow installation


问:
How can I find out more about my classic ASP environment?
I'm trying to make some modifications to some old ASP pages running VBScript on a server that I don't have a lot of information about. The people who would have that information are off in another department/hard to track down/probably wouldn't be able to provide complete information anyway.

I would like to run an ASP script that would get the server to tell me about itself. Information I would like to know is stuff like:

the version number of the server

version of Windows it is running on

the version of VBScript am I using

what dll's and COM objects are available for me to use

Bearing in mind that I know very little about ASP, what is some code that I could put into an ASP file I could run on the server so that it would provide me this information?

Based on the ServerVariables clue provided in the comment by JB King, below, I wrote this code and put it in an ASP:

```<code><%
    dim x
    for each x in Request.ServerVariables
      response.write("<p>" & x & ": " & Request.ServerVariables(x) &"</p>")
    next
%>
</code>```

This provided a lot of the information I needed - such as telling me that I'm actually running under something called Chili!Soft on a Solaris server, not Windows, which probably explains why the stuff I want to use from the Microsoft library doesn't work.

I still would like a good way of figuring out what COM objects are available in this environment...

答:
So, you've found out that the server is running Chili!Soft.  You can probably assume that the COM objects will mostly be limited to the basics like the ASP Built-in (intrinsic) objects,  and some form of data access like ADO.  I don't know of an easy way to blindly list the registered COM classes for a server with VBScript.  My guess is that this wouldn't work so well on a Solaris platform anyways since COM registers classes in the Windows registry... does Solaris have a Windows registry? ;)

Here are some links to the official Chili!Soft reference pages (aka Sun ONE ASP):

ASP Built-in Objects Reference
- covers: Application, ASPError, Request, Response, Server & Session objects

Sun ONE ASP Installed Components - Note that these may not be available on your installation since you might be on an older version of the platform (add-on components such as: Ad Rotator, Browser Capabilities, Counters, etc)

Sun ONE ASP XML Control - Supposed to correspond to the COM interfaces in MSXML 1.0

Also, if the server has Chili!Beans installed and enabled you can access Java components in VBScript as if they were COM components.  More info on that here.

Lastly, you may want to try and access the Administration Console for Sun ONE ASP via either http://[HOSTNAME]:5100 or http://[HOSTNAME]/caspsamp.  Detailed instructions for accessing the admin console can be found here.  If you can manage to get in I am sure there is a lot more information to discover about the server in the admin console.

Good Luck!

Body:
I'm trying to make some modifications to some old ASP pages running VBScript on a server that I don't have a lot of information about. The people who would have that information are off in another department/hard to track down/probably wouldn't be able to provide complete information anyway.

I would like to run an ASP script that would get the server to tell me about itself. Information I would like to know is stuff like:

the version number of the server

version of Windows it is running on

the version of VBScript am I using

what dll's and COM objects are available for me to use

Bearing in mind that I know very little about ASP, what is some code that I could put into an ASP file I could run on the server so that it would provide me this information?

Based on the ServerVariables clue provided in the comment by JB King, below, I wrote this code and put it in an ASP:

<%
    dim x
    for each x in Request.ServerVariables
      response.write("
" & x & ": " & Request.ServerVariables(x) &"
")
    next
%>

This provided a lot of the information I needed - such as telling me that I'm actually running under something called Chili!Soft on a Solaris server, not Windows, which probably explains why the stuff I want to use from the Microsoft library doesn't work.

I still would like a good way of figuring out what COM objects are available in this environment...


问:
Create js function from string without eval and new Function()
Is there any alternative solution to create js-function from string var, except eval() and Function constructor
I'm not allowed to use this both methods for security reason.

I know solution when you create DOM element with js code and add to page, but it's absolutely dirty hack.
Thank you very much for help.

====

ADD

I received json-data with string like "a === b", "!a", "(a && b) || c" and so on... (hundreds of combinations). Need to create and return function which can do this compare function.

Something

```<code>var test = function ('a === b') {
  //some code without eval and new Function()
}
// in console
test('aa', 'bb') // return false
</code>```

答:
Thanks all of you for interesting answers.

So, I had read and tried to use all methods, that you suggested me.
All of them it’s eval() even you wont be used eval in your code.
In my project I fixed problem using WebWorkers. This technologi has a lot benefits, please read article in MDN https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

But, I have to use "new Function" for this method.

So correct answer is:

You cannot create function from string without eval and new Function().

The only way it’s to write your own simple parser for that.

Thanks @brianxautumn

Body:
Is there any alternative solution to create js-function from string var, except eval() and Function constructor
I'm not allowed to use this both methods for security reason.

I know solution when you create DOM element with js code and add to page, but it's absolutely dirty hack.
Thank you very much for help.

====

ADD

I received json-data with string like "a === b", "!a", "(a && b) || c" and so on... (hundreds of combinations). Need to create and return function which can do this compare function.

Something

var test = function ('a === b') {
  //some code without eval and new Function()
}
// in console
test('aa', 'bb') // return false


问:
React.js + Webpack won't recognize @media expressions
I'm currently working on site that runs on React.js (15.6.1) and Webpack 1. I'm using a SASS-compatible version of the popular Flexbox Grid. For some reason however it doesn't seem to compile @media expressions like it normally would.

In this example @include viewport($key); works as intended but it completely skips the media query.

```<code>@media screen and (min-width: 48em) {
    @include viewport($key);
}
</code>```

For some reason I don't get any errors. I've tried using sass-loader as well as fast-sass-loader but neither seem to resolve my issue.

I'd be thankful for any helpful advice!

答:
You could use react-media npm

https://github.com/ReactTraining/react-media

Body:
I'm currently working on site that runs on React.js (15.6.1) and Webpack 1. I'm using a SASS-compatible version of the popular Flexbox Grid. For some reason however it doesn't seem to compile @media expressions like it normally would.

In this example @include viewport($key); works as intended but it completely skips the media query.

@media screen and (min-width: 48em) {
    @include viewport($key);
}

For some reason I don't get any errors. I've tried using sass-loader as well as fast-sass-loader but neither seem to resolve my issue.

I'd be thankful for any helpful advice!