问:
Formatting Numbers in Swift 3
I want to format number to this: 123.234.234.234 from 123234234234 depends on what the user types into the text field.
I don't want to manage currency, it's not about currency, it is about the user has to type in a number and this number should be formatted correctly to be easier to read.

Not with a comma, with a dot.

I found only currency stuff in the whole research

答:
Details

Xcode 9.2, Swift 4

Xcode 10.2 (10E125), Swift 5

Solution

```<code>import Foundation

extension String { var toLocale: Locale { return Locale(identifier: self) } }

extension NumberFormatter {
    convenience init(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.init()
        set(numberStyle: numberStyle, groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator)
    }

    convenience init(numberStyle: NumberFormatter.Style, locale: Locale) {
        self.init()
        set(numberStyle: numberStyle, locale: locale)
    }

    func set(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.locale = nil
        self.numberStyle = numberStyle
        self.groupingSeparator = groupingSeparator
        self.decimalSeparator = decimalSeparator
    }

    func set(numberStyle: NumberFormatter.Style, locale: Locale?) {
        self.numberStyle = numberStyle
        self.locale = locale
    }
}

extension Numeric {
    func format(formatter: NumberFormatter) -> String? {
        if let num = self as? NSNumber { return formatter.string(from: num) }
        return nil
    }
}
</code>```

Usage

```<code>let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
print(value.format(formatter: formatter))

formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
print(value.format(formatter: formatter))
</code>```

Full sample

Do not forget to add the solution code here

```<code>func test<T: Numeric>(value: T) {
    print("=========================================================")
    print("\(T.self), value = \(value)")

    let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
    print(value.format(formatter: formatter) ?? "nil")
    formatter.set(numberStyle: .currency, locale: "de_DE".toLocale)
    print(value.format(formatter: formatter)  ?? "nil")
    formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
    print(value.format(formatter: formatter)  ?? "nil")
}

func print(title: String, value: String?) {
    if let value = value { print("\(title) \(value)") }
}

test(value: Int(10000))
test(value: Double(10000.231))
test(value: Float(10000.231))
</code>```

Result

```<code>=========================================================
Int, value = 10000
10 000
10.000,00 €
10 000
=========================================================
Double, value = 10000.231
10 000,231
10.000,23 €
10 000.231
=========================================================
Float, value = 10000.231
10 000,231
10.000,23 €
10 000.231
</code>```

Title: Formatting Numbers in Swift 3

Body:
Details

Xcode 9.2, Swift 4

Xcode 10.2 (10E125), Swift 5

Solution

import Foundation

extension String { var toLocale: Locale { return Locale(identifier: self) } }

extension NumberFormatter {
    convenience init(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.init()
        set(numberStyle: numberStyle, groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator)
    }

    convenience init(numberStyle: NumberFormatter.Style, locale: Locale) {
        self.init()
        set(numberStyle: numberStyle, locale: locale)
    }

    func set(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.locale = nil
        self.numberStyle = numberStyle
        self.groupingSeparator = groupingSeparator
        self.decimalSeparator = decimalSeparator
    }

    func set(numberStyle: NumberFormatter.Style, locale: Locale?) {
        self.numberStyle = numberStyle
        self.locale = locale
    }
}

extension Numeric {
    func format(formatter: NumberFormatter) -> String? {
        if let num = self as? NSNumber { return formatter.string(from: num) }
        return nil
    }
}

Usage

let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
print(value.format(formatter: formatter))

formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
print(value.format(formatter: formatter))

Full sample

Do not forget to add the solution code here

func test<T: Numeric>(value: T) {
    print("=========================================================")
    print("\(T.self), value = \(value)")

    let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
    print(value.format(formatter: formatter) ?? "nil")
    formatter.set(numberStyle: .currency, locale: "de_DE".toLocale)
    print(value.format(formatter: formatter)  ?? "nil")
    formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
    print(value.format(formatter: formatter)  ?? "nil")
}

func print(title: String, value: String?) {
    if let value = value { print("\(title) \(value)") }
}

test(value: Int(10000))
test(value: Double(10000.231))
test(value: Float(10000.231))

Result

=========================================================
Int, value = 10000
10 000
10.000,00 €
10 000
=========================================================
Double, value = 10000.231
10 000,231
10.000,23 €
10 000.231
=========================================================
Float, value = 10000.231
10 000,231
10.000,23 €
10 000.231


来源: stackexchange

问:
Understanding Windows Phone 7 Development. (.net, c#, silverlight, xna) how do they interact together?
I come from a web development background and am looking into writing applications for the Windows Phone 7 device and am trying to get a better understanding of how things work.

From my online research (and please correct me if i'm wrong in the questions i ask below), this is what I understand so far:

.NET Framework - is a controlled environment that allows you to write in many different types of programming languages like C#

C# is best for wp7 development?

Visual Studio 2010 is best for writing code for the .NET framework?

Are there other programs like Visual Studio 2010 that allow you to write for .NET framework?

C# is the pre-written code in Visual Studio 2010?

Silverlight and XNA - are "libraries" that are made to help you with the development of applications and games.

C# is used to manipulate these libraries into doing what you want them to?

IS Silverlight & XNA libraries embedded in C# similar to how jQuery is embedded in HTML? Do I have the right idea on this or am I completely wrong?

Silverlight is a library that needs to be included into your application in order to run  (a file named silverlight.js perhaps?)

What is the programming language behind silverlight, java? I read somwhere that java is also used in wp7 development? how does java come into play with wp7?

Silverlight is best used for applications and XNA is best used for games.

And the best software write all of these apps in is Visual Studio 2010???  I downloaded the Windows Phone 7 Tools and it installed about 12 things on my computer... I've been watching a few beginner tutorial videos on developing for the wp7, but as you can see I still have some "core" things i need to understand before i proceed.

Any help you guys provide will be gladly appreciated!

答:
Q: C# is best for wp7 development?

A: It's not "best" unless that's the language you prefer and know.  You can use C# or VB.NET and achieve the exact same results, so neither is better in that respect.

Q: Visual Studio 2010 is best for writing code for the .NET framework?

A: For Phone 7, Visual Studio 2010 is your only option for the development environment.  For other, non-Phone 7 development you can use otehr tools. Again, "best" is subjective for those scenarios.

Q: Are there other programs like Visual Studio 2010 that allow you to write for .NET framework?

A: Yes, but not for Phone 7.  Again, only Studio 2010 has Phone 7 integration and is therefore your only tool option.

Q: C# is the pre-written code in Visual Studio 2010?

A: C# is a language.  Like VB, C, C++, Pascal, etc.  You can write it in anything, including a text editor.

Q: C# is used to manipulate these libraries into doing what you want them to?

A: The Silverlight or XNA libraries, for the context of Phone 7, can be consumed by applications written in either C# or VB.NET.

Q: Is Silverlight & XNA libraries embedded in C# similar to how jQuery is embedded in HTML? Do I have the right idea on this or am I completely wrong?

A: No, you don't have the right idea.  Silverlight and XNA are frameworks that you use for creating your application.  The language is either C# or VB.NET.  It's somewhat like jQuery is a framework that can be used to create applications written in Javascript.  So, using your examples, Silverlight is more like jQuery and C# is like Javascript.

Q: Silverlight is a library that needs to be included into your application in order to run (a file named silverlight.js perhaps?)

A: Silverlight and XNA are sets of libraries that already exist on the phone.  You don't build them into your app, nor do you deploy them.  They are guaranteed to already be there.

Q: What is the programming language behind silverlight, java? I read somwhere that java is also used in wp7 development? how does java come into play with wp7?

A: The Silverlight engine on the phone is, at least in part, written in managed code.  It was probably done in C#, but it's actually not relevent as it's compiled down to MSIL in the libraries you directly consume.  They are not Java.  Java is not supported at all on the phone (though one might argue that Javascript is through the browser and browser controls).

Q: Silverlight is best used for applications and XNA is best used for games.

A: That's the general idea and the likely thinking behind the design of both, but it's not always so clear-cut.  You could write a non-game app with XNA, just as you could write a game in Silverlight.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Java design strucutre
If I want to write bunch of sort classes (insertion, merge, etc) with void sort() method common in all of them, then I was hoping to have an interface or abstract class that these classes can implement or extend from.

However, if I plan on using the sort method as static and can not keep static method in abstract super class.

What would be proper way for such implementation?

答:
If I correctly understood your question a solution to use a static method sort(int data [ ]) can be done using Stategy pattern (I used int data to ease comprenhension).

As you said, group all your sort strategies as for example, InsertionSort,MergeSort, Quicksort etc... in an interface SortAlgorithm implement the abstract method sort(int data []).

Then write a class Sorter that owns a reference to the abstract type SortAlgorithm that use  final sort(int data [ ], int choice)where choice in my example is an integer given by the client

```<code>class Client{
   public static void main(String [ ] args){
      Scanner sc = new Scanner(System.in);
      int choice = sc.nextInt();
      int data= new int [5]
      data={3,7,7,1,0};
      Sorter.sort(data,choice);
   }
</code>```

Title: Java design strucutre

Body:
If I correctly understood your question a solution to use a static method sort(int data [ ]) can be done using Stategy pattern (I used int data to ease comprenhension).

As you said, group all your sort strategies as for example, InsertionSort,MergeSort, Quicksort etc... in an interface SortAlgorithm implement the abstract method sort(int data []).

Then write a class Sorter that owns a reference to the abstract type SortAlgorithm that use  final sort(int data [ ], int choice)where choice in my example is an integer given by the client

class Client{
   public static void main(String [ ] args){
      Scanner sc = new Scanner(System.in);
      int choice = sc.nextInt();
      int data= new int [5]
      data={3,7,7,1,0};
      Sorter.sort(data,choice);
   }


问:
Kendo Dropdownlist Cascading: Nothing showing up in child dropdownlist?
I am attempting to manually control a cascading kendo dropdownlist. I bind a 'cascade' event to the parent, and when that triggers, go to my server to get the values of the child dropdownlist that are associated with the parent dropdownlist value, and try to update the child dataSource:

childDropDown.setDataSource(new kendo.data.DataSource({
      data: resultArr.fieldValues
 }));

This does set the dataSource of the child, but nothing shows up in the child dropdownlist.

My dropdownlists are defined as input elements, where the dataSource of the parent is set up with the mvvm method of data-source="[\'option1\',\'option2\',\'option3\']" in the input element (building them dynamically, so construct these as strings and add them to a template).

I believe the issue is because there is no cascadeFromField since my dataSource consists of just the option strings, and not objects, but don't know how to fix that when I am dynamically constructing the HTML, so have to set the dataSource in the dropdownlist element string.

Is it possible to utilize Kendo cascading dropdownlists where I change the child options manually on each parent change like I am attempting to do?

答:
You can simply attach a change event to the main dropdown, so when it changes, it will reload the sub dropdown's dataSource. Here is an example, where SourceID is the main dropdown, and SubSourceID is the sub dropdown:

```<code>function OnChangeSourceID() {
    var kendoSubSourceID = $('#SubSourceID').data('kendoDropDownList');
    var sourceID = $('#SourceID').data('kendoDropDownList').value();

    kendoSubSourceID.setDataSource({
        serverFiltering: true,
        transport: {
            read: {
                contentType: 'application/json',
                type: 'POST',
                url: requestURL + '&source=' + sourceID,

            },
            parameterMap: function(data) {
                return kendo.stringify(data);

            },

        },
        schema: {
            data: 'data',
            total: 'total',

        },

    });

}
</code>```

If you have any question, feel free to ask. I hope, i could be of any help.

Body:
You can simply attach a change event to the main dropdown, so when it changes, it will reload the sub dropdown's dataSource. Here is an example, where SourceID is the main dropdown, and SubSourceID is the sub dropdown:

function OnChangeSourceID() {
    var kendoSubSourceID = $('#SubSourceID').data('kendoDropDownList');
    var sourceID = $('#SourceID').data('kendoDropDownList').value();

    kendoSubSourceID.setDataSource({
        serverFiltering: true,
        transport: {
            read: {
                contentType: 'application/json',
                type: 'POST',
                url: requestURL + '&source=' + sourceID,

            },
            parameterMap: function(data) {
                return kendo.stringify(data);

            },

        },
        schema: {
            data: 'data',
            total: 'total',

        },

    });

}

If you have any question, feel free to ask. I hope, i could be of any help.


问:
301 redirect using query parameter
I am working on a redirect problem. Input link would be like:

http://domain1.com/xyz?targetPCUrl=http://domain2.com/test?q1=val

i.e. one of the query param in the full link (say 1st) is a link itself (say 2nd).

Now I want to write a apache htaccess rewriterule to redirect all such calls to 2nd link. I have this until now:

```<code>RewriteCond %{QUERY_STRING} ^targetPCUrl=([/a-zA-Z_-]*)
</code>```

What should be the RewriteRule with flags [R=301,L] ?

答:
Something like this should do:</p>

```<code>RewriteCond %{QUERY_STRING} targetPCUrl=(.*)$
RewriteRule ^ %1 [R=301,L]
</code>```

Title: 301 redirect using query parameter

Body:
I am working on a redirect problem. Input link would be like:

http://domain1.com/xyz?targetPCUrl=http://domain2.com/test?q1=val

i.e. one of the query param in the full link (say 1st) is a link itself (say 2nd).

Now I want to write a apache htaccess rewriterule to redirect all such calls to 2nd link. I have this until now:

RewriteCond %{QUERY_STRING} ^targetPCUrl=([/a-zA-Z_-]*)

What should be the RewriteRule with flags [R=301,L] ?

Body:
Something like this should do:

RewriteCond %{QUERY_STRING} targetPCUrl=(.*)$
RewriteRule ^ %1 [R=301,L]


问:
GridPane.getColumnIndex() returning null
Trying to add children to a GridPane with row and column indices. They show up in the gui, but using GridPane.getColumnIndex(node) always returns null.

```<code>GridPane grid = new GridPane();
for (int i = 0; i < 20; i++) {
    for (int j = 0; j < 20; j++) {
        grid.setGridLinesVisible(true);

        Button myBtn = new Button("foo");

        GridPane.setColumnIndex(myButton,i);
        GridPane.setRowIndex(myButton,j);

        grid.getChildren().add(myButton);
    }
</code>```

When I try to use this algorithm I got from the answer on javafx GridPane retrive specific Cell content, the program crashes with a NullPointerException.

```<code>private Node getNodeFromGridPane(GridPane gridPane, int col, int row)
{
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
            return node;
        }
    }
    return null;
}
</code>```

Why are GridPane.getRowIndex() and GridPane.getColumnIndex() returning null even after calling setColumnIndex() and setRowIndex()?

答:
So it seems I got it to work if you run it you will see that all the buttons are red white or blue this is because they were found</p>

```<code>import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane grid = new GridPane();
        grid.setGridLinesVisible(true);

        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                grid.add(new Button("foo"),i,j);
                //                Button myBtn = new Button("foo");
                //                GridPane.setColumnIndex(myBtn, i);
                //                GridPane.setRowIndex(myBtn, j);
                //                grid.getChildren().add(myBtn);
            }
        }

        Scene scene = new Scene(grid);

        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        String[] colors = {"-fx-background-color: red;", "-fx-background-color: blue;", "-fx-background-color: white;"};
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                Node node = getNodeFromGridPane(grid,i,j);
                if(node instanceof Button)
                    node.setStyle(colors[(int) (Math.random() * 3)]);
            }
        }
    }

    private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
        for (Node node : gridPane.getChildren())
            if (GridPane.getColumnIndex(node) != null
                    && GridPane.getColumnIndex(node) != null
                    && GridPane.getRowIndex(node) == row
                    && GridPane.getColumnIndex(node) == col)
                return node;
        return null;
    }

    public static void main(String[] args) { launch(args); }
}
</code>```

Body:
Trying to add children to a GridPane with row and column indices. They show up in the gui, but using GridPane.getColumnIndex(node) always returns null.

GridPane grid = new GridPane();
for (int i = 0; i < 20; i++) {
    for (int j = 0; j < 20; j++) {
        grid.setGridLinesVisible(true);

        Button myBtn = new Button("foo");

        GridPane.setColumnIndex(myButton,i);
        GridPane.setRowIndex(myButton,j);

        grid.getChildren().add(myButton);
    }

When I try to use this algorithm I got from the answer on javafx GridPane retrive specific Cell content, the program crashes with a NullPointerException.

private Node getNodeFromGridPane(GridPane gridPane, int col, int row)
{
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
            return node;
        }
    }
    return null;
}

Why are GridPane.getRowIndex() and GridPane.getColumnIndex() returning null even after calling setColumnIndex() and setRowIndex()?

Body:
So it seems I got it to work if you run it you will see that all the buttons are red white or blue this is because they were found

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane grid = new GridPane();
        grid.setGridLinesVisible(true);

        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                grid.add(new Button("foo"),i,j);
                //                Button myBtn = new Button("foo");
                //                GridPane.setColumnIndex(myBtn, i);
                //                GridPane.setRowIndex(myBtn, j);
                //                grid.getChildren().add(myBtn);
            }
        }

        Scene scene = new Scene(grid);

        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        String[] colors = {"-fx-background-color: red;", "-fx-background-color: blue;", "-fx-background-color: white;"};
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                Node node = getNodeFromGridPane(grid,i,j);
                if(node instanceof Button)
                    node.setStyle(colors[(int) (Math.random() * 3)]);
            }
        }
    }

    private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
        for (Node node : gridPane.getChildren())
            if (GridPane.getColumnIndex(node) != null
                    && GridPane.getColumnIndex(node) != null
                    && GridPane.getRowIndex(node) == row
                    && GridPane.getColumnIndex(node) == col)
                return node;
        return null;
    }

    public static void main(String[] args) { launch(args); }
}


问:
sublimeREPL - "can't open file '$file_basename'"
When I try to execute more than an operation using SublimeREPL and Python3 I get :
C:/Users/Name/Anaconda3/envs/keras/python.exe: can't open file '$file_basename': [Errno 2] No such file or directory.

Following this answer I have modified the sublime-settings file adding "default_extend_env": {"PATH": "{PATH};C:/Users/Simone/Anaconda3/envs/keras"}.

I have also add the path C:/Users/Name/Anaconda3/envs/keras/python.exe in Main.sublime-menu file, but I'm still getting the same error message.

答:
You do not have to modify you sublime-setttings file. I suppose that you have your subl configured to run with python3 but it doesn't matter.
When you use ctrl + b for running your code, you must be sure that you have something written. Is only that, if you use ctrl + b but you don't have anything in your code file is normal that you were obtaining that error.</p>


问:
Apache Solr - Document is missing mandatory uniqueKey field: id

I'm using Solr7.1 (SolrCloud mode) and I don't have requirement to enforce document uniqueness.
Hence I marked id field (designated as unique key) in schema as required="false".

<field name="id" type="string" indexed="true" stored="false" required="false" multiValued="false" />

<uniqueKey>id</uniqueKey>

And I am trying to index some documents using solr Admin UI and I am trying without specifying 'id' field.

{
 "cat": "books",
 "name": "JayStore"
}

I was expecting it to index successfully but solr is throwing error saying 'mandatory unique key field id is missing'

Could some one guide me what I'm doing wrong.

答:
The uniqueKey field is required internally by Solr for certain features, such as using cursorMark - meaning that the field that is defined as a uniqueKey is required. It's also used for routing etc. inside SolrCloud by default (IIRC), so if it's not present Solr won't be able to shard your documents correctly. Setting it as not required in the schema won't relax that requirement.

But you can work around this by defining an UUID field, and using a UUID Update Processor as described in the old wiki. This will generate a unique UUID for each document when you index it, meaning each document will get a unique identificator attached by default.

UUID is short for Universal Unique IDentifier. The UUID standard RFC-4122 includes several types of UUID with different input formats. There is a UUID field type (called UUIDField) in Solr 1.4 which implements version 4. Fields are defined in the schema.xml file with:

<fieldType name="uuid" class="solr.UUIDField" indexed="true" />

in Solr 4, this field must be populated via solr.UUIDUpdateProcessorFactory.

<field name="id" type="uuid" indexed="true" stored="true" required="true"/>
  <updateRequestProcessorChain name="uuid">
      <processor class="solr.UUIDUpdateProcessorFactory">
        <str name="fieldName">id</str>
      </processor>
      <processor class="solr.RunUpdateProcessorFactory" /
  </updateRequestProcessorChain>


问:
I am using `max()` to get the highest value from n digits?
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

```<code>def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)
</code>```

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

```<code>def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)
</code>```

答:
You can condense the code to a single line:</p>

```<code>def is_divisable(n):
  return max(map(int, str(n)))%3 == 0
</code>```

Body:
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)

Body:
You can condense the code to a single line:

def is_divisable(n):
  return max(map(int, str(n)))%3 == 0


问:
Pagination with BeautifulSoup
I am trying to get some data from the following website. https://www.drugbank.ca/drugs

For every drug in the table, I will need to go deeply and have the name and some other specific features like categories, structured indication (please click on drug name to see the features I will use).

I wrote the following code but the issue that I can't make my code handle pagination (as you see there more than 2000 pages!).

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

def drug_data():
url = 'https://www.drugbank.ca/drugs/'
r = requests.get(url)
soup = BeautifulSoup(r.text ,"lxml")
for link in soup.select('name-head a'):
    href = 'https://www.drugbank.ca/drugs/' + link.get('href')
    pages_data(href)

def pages_data(item_url):
r = requests.get(item_url)
soup = BeautifulSoup(r.text, "lxml")
g_data = soup.select('div.content-container')

for item in g_data:
    print item.contents[1].text
    print item.contents[3].findAll('td')[1].text
    try:
        print item.contents[5].findAll('td',{'class':'col-md-2 col-sm-4'})
    [0].text
    except:
        pass
    print item_url
    drug_data()
</code>```

How can I scrape all of the data and handle pagination properly?

答:
This page uses almost the same url for all pages so you can use for loop to generate them

```<code>def drug_data(page_number):
    url = 'https://www.drugbank.ca/drugs/?page=' + str(page_number)
    #... rest ...

# --- later ---

for x in range(1, 2001):
    drug_data(x)
</code>```

Or using while and try/except to get more then 2000 pages

```<code>def drug_data(page_number):
    url = 'https://www.drugbank.ca/drugs/?page=' + str(page_number)
    #... rest ...

# --- later ---

page = 0

while True:
    try:
        page += 1
        drug_data(page)
    except Exception as ex:
        print(ex)
        print("probably last page:", page)
        break # exit `while` loop
</code>```

You can also find url to next page in HTML

```<code><a rel="next" class="page-link" href="/drugs?approved=1&c=name&d=up&page=2">›</a>
</code>```

so you can use BeautifulSoup to get this link and use it.

It displays current url, finds link to next page (using class="page-link" rel="next") and loads it

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

def drug_data():
    url = 'https://www.drugbank.ca/drugs/'

    while url:
        print(url)
        r = requests.get(url)
        soup = BeautifulSoup(r.text ,"lxml")

        #data = soup.select('name-head a')
        #for link in data:
        #    href = 'https://www.drugbank.ca/drugs/' + link.get('href')
        #    pages_data(href)

        # next page url
        url = soup.findAll('a', {'class': 'page-link', 'rel': 'next'})
        print(url)
        if url:
            url = 'https://www.drugbank.ca' + url[0].get('href')
        else:
            break

drug_data()
</code>```

BTW: never use except:pass because you can have error which you didn't expect and you will not know why it doesn't work. Better display error

```<code> except Exception as ex:
      print('Error:',  ex)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pagination with BeautifulSoup

Body:
I am trying to get some data from the following website. https://www.drugbank.ca/drugs

For every drug in the table, I will need to go deeply and have the name and some other specific features like categories, structured indication (please click on drug name to see the features I will use).

I wrote the following code but the issue that I can't make my code handle pagination (as you see there more than 2000 pages!).

import requests
from bs4 import BeautifulSoup

def drug_data():
url = 'https://www.drugbank.ca/drugs/'
r = requests.get(url)
soup = BeautifulSoup(r.text ,"lxml")
for link in soup.select('name-head a'):
    href = 'https://www.drugbank.ca/drugs/' + link.get('href')
    pages_data(href)

def pages_data(item_url):
r = requests.get(item_url)
soup = BeautifulSoup(r.text, "lxml")
g_data = soup.select('div.content-container')

for item in g_data:
    print item.contents[1].text
    print item.contents[3].findAll('td')[1].text
    try:
        print item.contents[5].findAll('td',{'class':'col-md-2 col-sm-4'})
    [0].text
    except:
        pass
    print item_url
    drug_data()

How can I scrape all of the data and handle pagination properly?

Body:
This page uses almost the same url for all pages so you can use for loop to generate them

def drug_data(page_number):
    url = 'https://www.drugbank.ca/drugs/?page=' + str(page_number)
    #... rest ...

# --- later ---

for x in range(1, 2001):
    drug_data(x)

Or using while and try/except to get more then 2000 pages

def drug_data(page_number):
    url = 'https://www.drugbank.ca/drugs/?page=' + str(page_number)
    #... rest ...

# --- later ---

page = 0

while True:
    try:
        page += 1
        drug_data(page)
    except Exception as ex:
        print(ex)
        print("probably last page:", page)
        break # exit `while` loop

You can also find url to next page in HTML

<a rel="next" class="page-link" href="/drugs?approved=1&amp;c=name&amp;d=up&amp;page=2">›</a>

so you can use BeautifulSoup to get this link and use it.

It displays current url, finds link to next page (using class="page-link" rel="next") and loads it

import requests
from bs4 import BeautifulSoup

def drug_data():
    url = 'https://www.drugbank.ca/drugs/'

    while url:
        print(url)
        r = requests.get(url)
        soup = BeautifulSoup(r.text ,"lxml")

        #data = soup.select('name-head a')
        #for link in data:
        #    href = 'https://www.drugbank.ca/drugs/' + link.get('href')
        #    pages_data(href)

        # next page url
        url = soup.findAll('a', {'class': 'page-link', 'rel': 'next'})
        print(url)
        if url:
            url = 'https://www.drugbank.ca' + url[0].get('href')
        else:
            break

drug_data()

BTW: never use except:pass because you can have error which you didn't expect and you will not know why it doesn't work. Better display error

 except Exception as ex:
      print('Error:',  ex)


问:
Entering data into excel sheet using matlab
I am entering a dynamic data into excel sheet from a textbox. The problem is that it enters letter by letter in every cell.

This is the code I have tried:

```<code> >>function bntEnterData_callback(hObject,eventdata,handles)
 >>val1 = get(handles.txt1,'string'));
 >>val2 = get(handles.txt2,'string'));
 >>val3 = get(handles.txt3,'string'));
 >>values = [ val1 val2 val3]
 >>filename= 'try.xls';
 >>sheet= 1;
 >>xkRange= 'A2';
 >>xlswrite(filename,values,sheet,xlRange);
</code>```

答:
Assuming your handles.txt* are edit uicontrols, the 'String' property is going to be a character vector. Concatenating multiple character vectors just creates a longer vector:

```<code>a = 'foo';
b = 'bar';
values = [a b]
</code>```

Which creates:

```<code>values =

    'foobar'
</code>```

When not explicitly provided a range of cells to write to, xlswrite will interpret the input single cell (or the default A1) as the starting point, and write all elements of the input array using the single cell as the origin. Because 'foobar' is an array of characters, this gives the expected behavior of:

To fix this, concatenate into a cell array:

```<code>a = 'foo';
b = 'bar';
values = {a b};

filename= 'try.xls';
sheet= 1;
xlRange= 'A2';
xlswrite(filename,values,sheet,xlRange);
</code>```

Body:
I am entering a dynamic data into excel sheet from a textbox. The problem is that it enters letter by letter in every cell.

This is the code I have tried:

 >>function bntEnterData_callback(hObject,eventdata,handles)
 >>val1 = get(handles.txt1,'string'));
 >>val2 = get(handles.txt2,'string'));
 >>val3 = get(handles.txt3,'string'));
 >>values = [ val1 val2 val3]
 >>filename= 'try.xls';
 >>sheet= 1;
 >>xkRange= 'A2';
 >>xlswrite(filename,values,sheet,xlRange);

Body:
Assuming your handles.txt* are edit uicontrols, the 'String' property is going to be a character vector. Concatenating multiple character vectors just creates a longer vector:

a = 'foo';
b = 'bar';
values = [a b]

Which creates:

values =

    'foobar'

When not explicitly provided a range of cells to write to, xlswrite will interpret the input single cell (or the default A1) as the starting point, and write all elements of the input array using the single cell as the origin. Because 'foobar' is an array of characters, this gives the expected behavior of:

To fix this, concatenate into a cell array:

a = 'foo';
b = 'bar';
values = {a b};

filename= 'try.xls';
sheet= 1;
xlRange= 'A2';
xlswrite(filename,values,sheet,xlRange);


问:
AWS Lambda python custom response encoding
When you query data with your lambda function from dynamodb and there are binary types or decimal/number types in it my default setup below prompts with an JSONEncoding Error that he cannot deal with Binary or Decimal. I can work around with a small piece of code that I attach to json.dumps(data, indent=2, cls=JSONEncoder)

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(JSONEncoder, self).default(o)
```

<p>But using <code>json.dumps()</code> in front of your <code>return</code> statement double json format the response and that leads to escaped signs. To repeat the problem just <code>return data</code> prompts with the mentioned error.</p>

<p>How can I affect my <code>return</code> statement that converts to json?</p>

<h2>UPDATE:</h2>

<p>The problem is solved dirty by manually change the items with:
</p>

```test = operations['Items'][0]
test['id'] = float(test['id'])
```

But this seems messy.

答:
I'm assuming you are looking to return from the lambda handler function. If so, while not elegant, you can do this:

```<code>json.loads(json.dumps(value, cls=JSONEncoder))
</code>```

Not awesome because eventually Lambda will convert that structure back into a string (not sure if there's a way to just skip the intermediate step of converting to a python structure).

Body:
When you query data with your lambda function from dynamodb and there are binary types or decimal/number types in it my default setup below prompts with an JSONEncoding Error that he cannot deal with Binary or Decimal. I can work around with a small piece of code that I attach to json.dumps(data, indent=2, cls=JSONEncoder)

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(JSONEncoder, self).default(o)

But using json.dumps() in front of your return statement double json format the response and that leads to escaped signs. To repeat the problem just return data prompts with the mentioned error.

How can I affect my return statement that converts to json?

UPDATE:

The problem is solved dirty by manually change the items with:

test = operations['Items'][0]
test['id'] = float(test['id'])

But this seems messy.

Body:
I'm assuming you are looking to return from the lambda handler function. If so, while not elegant, you can do this:

json.loads(json.dumps(value, cls=JSONEncoder))

Not awesome because eventually Lambda will convert that structure back into a string (not sure if there's a way to just skip the intermediate step of converting to a python structure).


问:
sending \X0D0A\ in OBX TX field in hl7 message
In the final report the findings are printed as paragraph.

For ex:
'FINDINGS:
Right: Peak systolic velocities are given below. Right proximal common carotid artery: 100 cm/sec Right mid common carotid artery: 100 cm/sec Right distal common carotid artery: 100 cm/sec Right proximal internal carotid artery: 100 cm/sec Right distal internal carotid artery: 100 cm/sec Right internal carotid artery plaque: None. Internal carotid artery wave forms are normal'.

I want it to be printed like below line by line.

Findings:
Right:
Peak systolic velocities are given below.
Right proximal common carotid artery: 100 cm/sec
Right mid common carotid artery: 100 cm/sec
Right distal common carotid artery: 100 cm/sec
Right proximal internal carotid artery: 100 cm/sec
Right distal internal carotid artery: 100 cm/sec
Right internal carotid artery plaque: None.
Internal carotid artery waveforms are normal.

Is it possible to achieve this by sending \x0D0A\ at the end in hl7 message like below

OBX|1|TX|93880^US DUPLEX CAROTID||Peak systolic velocities are given below.\X0D0A\||||||F|||||| (it is in single line)

OBX|1|TX|93880^US DUPLEX CAROTID||Right proximal common carotid artery: 99 cm/sec\X0D0A\||||||F||||||

OBX|1|TX|93880^US DUPLEX CAROTID||Right mid common carotid artery: 70 cm/sec\X0D0A\||||||F||||||

OBX|1|TX|93880^US DUPLEX CAROTID||Right distal common carotid artery: 74 cm/sec\X0D0A\||||||F||||||

I am new to Mirth. I apologize if i asked wrong question.

答:
Dale M posted a comment that's part of the complete answer:

The system that you send this to is going to determine how the report looks.

I've seen systems that use:

Hexadecimal escape sequences like you have, with one OBX segment

.br like Dale suggests with one OBX segment (should use the FT data type instead of TX)

Just having multiple OBX segments, line breaks get inserted by the receiver

Repetition of OBX-5

If #1 or #2 are supported, you have a little bit more control over the formatting. With #3 and #4 you're at the mercy of the receiver - they may add a line break, or they may add a paragraph break.

Other options if you need more control over formatting are RTF or any kind of Binary format like PDF. Support on the receiving system side is going to be lower for those than plain text, but it can help to present the information more clearly.

Finally, you have discrete values. I would try to integrate those as numerical values in addition to textual values.


问:
What's the best way to select multiple M:N relationships in SQL?
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

```<code>books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)
</code>```

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

答:
You can return multiple result sets with MS SQL Server.
SELECT * FROM books;
SELECT * FROM book_authors;
SELECT * FROM authors;
SELECT * FROM book_subjects;
SELECT * FROM subjects;

Then use the information to either load a .NET DataSet with relationships or create Entity Objects that encapsulate the relationships if not using .NET or DataSets.

If you are using .NET 3.5 then look at LINQ to SQL or LINQ to Entities to simplify the effort in creating the required code.

OwnerDisplayName: Ben Blank

Body:
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

LastEditorDisplayName: Ben Blank

OwnerDisplayName: Matthew


问:
Return request HttpModules as quickly as possible
In a web site I capture the http POST request with a HttpModule as in this answer.

After reading the body of the POST in the context's BeginRequest event I would like to return as quickly as possible an "OK" response to the client.

What would be the best way to prevent further processing in IIS (7.5 integrated mode)?

答:
I believe this one is the fastest:</p>

```<code>Response.Clear();
Response.ClearHeaders();

Response.StatusCode = 200;
Response.StatusDescription = "OK";

Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
</code>```

Body:
I believe this one is the fastest:

Response.Clear();
Response.ClearHeaders();

Response.StatusCode = 200;
Response.StatusDescription = "OK";

Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();


问:
group and filter and array of objects using VanillaJS
I have the following table which contains some objects :

```<code>var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];
</code>```

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

```<code>var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});
</code>```

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

```<code>[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]
</code>```

So I did the following, which works and I get the expected result :

```<code>var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

console.log(organizations);
</code>```

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.

答:
You can use array#reduce to club all your information.

var data = [ { "userRoleId": 1, "userId": 1, "roleId": 1, "organizationId": "ORG_01", "roleTitle": "Admin", "organizationTitle": "Organization 01", "startDate": "2017-11-15", "endDate": "2017-11-15", "automatic": false, "useDate": "2017-11-15" }, { "userRoleId":2, "userId": 1, "roleId": 2, "organizationId": "ORG_01", "roleTitle": "Agent", "organizationTitle": "Organization 01", "startDate": "2017-11-15", "endDate": "2017-11-15", "automatic": true, "useDate": "2017-11-15" }, { "userRoleId": 4, "userId": 1, "roleId":4, "organizationId": "ORG_02", "roleTitle": "Referent", "organizationTitle": "Organization 02", "startDate": "2017-11-15", "endDate": "2017-11-15", "automatic": true, "useDate": "2017-11-15" }, { "userRoleId": 5, "userId": 1, "roleId": 2, "organizationId":"ORG_02", "roleTitle": "Agent", "organizationTitle": "Organization 02", "startDate": "2017-11-15", "endDate": "2017-11-15", "automatic": true, "useDate": "2017-11-15" } ];

var result = data.reduce(function(r, o){
  r[o.organizationId] = r[o.organizationId] || {id : o.organizationId, lib : o.organizationTitle, roles : []};
  r[o.organizationId].roles.push({id : o.roleId, title: o.roleTitle});
  return r;
},{});
var output = Object.values(result);
console.log(output);```

Body:
I have the following table which contains some objects :

var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]

So I did the following, which works and I get the expected result :

var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

console.log(organizations);

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.


问:
How to change devise views model in an existing app
So, I have actually generated the views for devise but recently i want to change it back to another name, how will i?

Initially it was rails g devise 'Writer'...
now, i want rails g devise 'User'

Thanks.

答:
if you cannot destroy your devise model then one method is to

rename occurrences of user_signed_in?,  current_user, user_session
(see devise helpers)

Rename your db table name (migration), modify your tests files, model and route to devise_for :users.


问:
Haskell: app build troubleshooting (docker primer)
How am I supposed to go about troubleshooting if an imported library won't build?

```<code>$ stack new any-tool simple
$ cd any-tool/
$ stack build
</code>```

The boilerplate builds.

Adding import Turtle to Main.hs:

```<code>{-# LANGUAGE OverloadedStrings #-}
module Main where

import Turtle

main :: IO ()
main = do
  putStrLn "hello world"
</code>```

Adding turtle to any-tool.cabal:

```<code>....
executable any-tool
  hs-source-dirs:      src
  main-is:             Main.hs
  default-language:    Haskell2010
  build-depends:       base >= 4.7 && < 5
                     , turtle
</code>```

Won't build:

```<code>$ stack build
clock-0.7.2: configure
clock-0.7.2: build
hashable-1.2.6.1: download
hashable-1.2.6.1: configure
hashable-1.2.6.1: build
hashable-1.2.6.1: copy/register
Progress: 2/30
--  While building custom Setup.hs for package clock-0.7.2 using:
      /home/alexey/.stack/setup-exe-cache/x86_64-linux-tinfo6-nopie/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-tinfo6-nopie/Cabal-1.24.2.0 build --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Logs have been written to: /home/alexey/spaces/haskell/any-tool/.stack-work/logs/clock-0.7.2.log

...
</code>```

Looks like no particular surprise: turtle has a couple of dozen dependencies, any incompatibility and there she goes. The question is, what is my next step?

答:
You'd better drain the swamp.

https://www.fpcomplete.com/blog/2015/08/stack-docker

https://docs.haskellstack.org/en/stable/docker_integration

https://hub.docker.com/r/fpco/stack-build

It took me just installing docker from the reps,

```<code>$  docker pull fpco/stack-build
...
$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED SIZE
...
fpco/stack-build    latest              4e3c147fca48        4 months ago        4.3GB
...
</code>```

and adding three lines to stack.yaml of my project:

```<code>docker:
  enable: true
  image: 4e3c147fca48
</code>```

The image is not quite lightweight, but well worth it.

You can probably put the image name right into stack.yaml with impunity:

```<code>docker:
  enable: true
  repo: "fpco/stack-build"
</code>```

Body:
How am I supposed to go about troubleshooting if an imported library won't build?

$ stack new any-tool simple
$ cd any-tool/
$ stack build

The boilerplate builds.

Adding import Turtle to Main.hs:

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Turtle

main :: IO ()
main = do
  putStrLn "hello world"

Adding turtle to any-tool.cabal:

....
executable any-tool
  hs-source-dirs:      src
  main-is:             Main.hs
  default-language:    Haskell2010
  build-depends:       base >= 4.7 && < 5
                     , turtle

Won't build:

$ stack build
clock-0.7.2: configure
clock-0.7.2: build
hashable-1.2.6.1: download
hashable-1.2.6.1: configure
hashable-1.2.6.1: build
hashable-1.2.6.1: copy/register
Progress: 2/30
--  While building custom Setup.hs for package clock-0.7.2 using:
      /home/alexey/.stack/setup-exe-cache/x86_64-linux-tinfo6-nopie/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux-tinfo6-nopie/Cabal-1.24.2.0 build --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Logs have been written to: /home/alexey/spaces/haskell/any-tool/.stack-work/logs/clock-0.7.2.log

...

Looks like no particular surprise: turtle has a couple of dozen dependencies, any incompatibility and there she goes. The question is, what is my next step?

Body:
You'd better drain the swamp.

https://www.fpcomplete.com/blog/2015/08/stack-docker

https://docs.haskellstack.org/en/stable/docker_integration

https://hub.docker.com/r/fpco/stack-build

It took me just installing docker from the reps,

$  docker pull fpco/stack-build
...
$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED SIZE
...
fpco/stack-build    latest              4e3c147fca48        4 months ago        4.3GB
...

and adding three lines to stack.yaml of my project:

docker:
  enable: true
  image: 4e3c147fca48

The image is not quite lightweight, but well worth it.

You can probably put the image name right into stack.yaml with impunity:

docker:
  enable: true
  repo: "fpco/stack-build"


问:
How to use specific custom objectMapper/JsonSerializer for specific requestMapping
I know thar Jackson allow us to use custom serializer for specific domain/entity/modle, like this:

```<code>@JsonSerialize(using = CustomSerializer.class)
public class SimpleDomain {

}
</code>```

And, is there any idea to specify custom serializer for some requestMapping,
(only for the specific requestMapping(that method), not to set global objectMapper.) like this:

```<code>@RequestMapping(method = RequestMethod.GET, value = "hello")
@JsonSerialize(nullsUsing = NullToEmptyStrSerializer.class)
public @ResponseBody
Object get() {
    return new HashMap<String, Object>() {{
        put("aa", null);
        put("bb", "");
    }};
}
</code>```

I execute the code above, it returns:

```<code>{
    "aa": null,
    "bb": ""
}
</code>```

instead of:

```<code>{
    "aa": "",
    "bb": ""
}
</code>```

which exactly i wanted.

NullToEmptyStrSerializer :

```<code>public class NullToEmptyStrSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString("");
    }
}
</code>```

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.

答:
It may be a known limitation (@JsonSerialize with nullUsing option not working for String properties) and reported in this github issue.

It is scheduled to be released in jackson 2.9.3 and 2.8.11.

Fix will be in 2.9.3 but I also back-ported it in 2.8 branch in case
  2.8.11 might be released at some point.

Body:
I know thar Jackson allow us to use custom serializer for specific domain/entity/modle, like this:

@JsonSerialize(using = CustomSerializer.class)
public class SimpleDomain {

}

And, is there any idea to specify custom serializer for some requestMapping,
(only for the specific requestMapping(that method), not to set global objectMapper.) like this:

@RequestMapping(method = RequestMethod.GET, value = "hello")
@JsonSerialize(nullsUsing = NullToEmptyStrSerializer.class)
public @ResponseBody
Object get() {
    return new HashMap<String, Object>() {{
        put("aa", null);
        put("bb", "");
    }};
}

I execute the code above, it returns:

{
    "aa": null,
    "bb": ""
}

instead of:

{
    "aa": "",
    "bb": ""
}

which exactly i wanted.

NullToEmptyStrSerializer :

public class NullToEmptyStrSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString("");
    }
}

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.


问:
Switch Teradata Accounts
I want to be able to switch between 2 Teradata accounts if the password has expired for one user in SAS.
e.g. connect to teradata (user="&terauser" password="&terapwd" account="&teraacct" server="&tdserver" mode=teradata);

terauser : Password expired
terauser1 : Password valid

Couple of questions:

How do I pre-warn the user to change password. Do I use the DBC.Users table.

How do I swicth accounts, as I will know the status only in the logs.

答:
If you get connected you can ask Teradata when the password was last changed by querying DBC.USERSV.  Then if you know what your expiration rules are you can send a message to the user in the SAS log.  So if you passwords expire after 120 days your query and report might look like this:

```<code>select catx(' ','%put'
   , case when (days_left < 2) then 'ERROR:'
          when (days_left < 10) then 'WARNING:'
          else 'NOTE:'
     end
   ,'Your Teradata password expires in',days_left,'days.')
 into :tdpassword_message trimmed
from connection to teradata
 (select ((PasswordChgDate+ 120) - date) days_left from dbc.usersV )
;
*----------------------------------------------------------------------------;
* Write message to SAS log ;
*----------------------------------------------------------------------------;
&tdpassword_message;
</code>```

Title: Switch Teradata Accounts

Body:
If you get connected you can ask Teradata when the password was last changed by querying DBC.USERSV.  Then if you know what your expiration rules are you can send a message to the user in the SAS log.  So if you passwords expire after 120 days your query and report might look like this:

select catx(' ','%put'
   , case when (days_left < 2) then 'ERROR:'
          when (days_left < 10) then 'WARNING:'
          else 'NOTE:'
     end
   ,'Your Teradata password expires in',days_left,'days.')
 into :tdpassword_message trimmed
from connection to teradata
 (select ((PasswordChgDate+ 120) - date) days_left from dbc.usersV )
;
*----------------------------------------------------------------------------;
* Write message to SAS log ;
*----------------------------------------------------------------------------;
&tdpassword_message;


问:
Vertical Blue, Green, or Gray lines in Android Studio
I am seeing these vertical blue and green lines on the right border of the Android Studio:

What do these lines mean? Is there a way to remove them as they are a little annoying. I don't remember seeing them in previous versions of Android Studio.

答:
The tool is showing you lines which have changed as far as VCS (rev control, in your case git) is concerned.  This gives you a quick look at what has changed within the file compared to the last commit on your current branch.

There is no way to disable this in the UI AFAIK.  You may try looking in Settings -> Editor -> Colors & Fonts to see if you can find a setting to disable this.


问:
Socket read and unknown length data
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

```<code>static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}
</code>```

fd in this case is FILENO_STDIN

答:
Pass SOCK_NONBLOCK in call to socket() (or call fcntl() with O_NONBLOCK later on) to make socket operations non-blocking. This will result in read() call failing with either EAGAIN or EWOULDBLOCK (those are effectively the same) if there's no data to read (yet).

Alternatively, you may use select() to determine if there's any data ready to be read on a specific socket before the actual read() call.

Title: Socket read and unknown length data

Body:
I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}

fd in this case is FILENO_STDIN


问:
Ordering and binding in for loop r
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

```<code>##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories
</code>```

Hope you guys can help me out!

答:
If you nest another for loop, and put that for loop's assigner inside the dataframe indices you want to modify that should solve your problem. Obviously without data this answer is just guidance rather than concrete code...</p>

```<code>    ##for loop for all competitor average prices accross all categories
        for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
      PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
      PriceX <- transpose(PriceX)
      PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
      PriceX <- transpose(PriceX)
      PriceX <- sapply(PriceX, as.numeric)
      PriceX <- data.frame(PriceX)
      CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
      CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
      CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
      CompPriceXa <- as.matrix(CompPriceXa)
      CompPriceXb <- PriceX[-c(1, 3), ]
       CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
      CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
      CompPriceXb <- as.matrix(CompPriceXb)
      CompPriceXc <- PriceX[-c(1, 4), ]
      CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
      CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
      CompPriceXc <- as.matrix(CompPriceXc)
      StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
      StackedCompPrice <- as.data.frame(StackedCompPrice)
for(i in 1:5{
      ALLStackedCompPrice[,i]<- rbind(StackedCompPrice, ALLStackedCompPrice)
}}

    ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories
</code>```

Title: Ordering and binding in for loop r

Body:
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories

Hope you guys can help me out!

Body:
If you nest another for loop, and put that for loop's assigner inside the dataframe indices you want to modify that should solve your problem. Obviously without data this answer is just guidance rather than concrete code...

    ##for loop for all competitor average prices accross all categories
        for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
      PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
      PriceX <- transpose(PriceX)
      PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
      PriceX <- transpose(PriceX)
      PriceX <- sapply(PriceX, as.numeric)
      PriceX <- data.frame(PriceX)
      CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
      CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
      CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
      CompPriceXa <- as.matrix(CompPriceXa)
      CompPriceXb <- PriceX[-c(1, 3), ]
       CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
      CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
      CompPriceXb <- as.matrix(CompPriceXb)
      CompPriceXc <- PriceX[-c(1, 4), ]
      CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
      CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
      CompPriceXc <- as.matrix(CompPriceXc)
      StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
      StackedCompPrice <- as.data.frame(StackedCompPrice)
for(i in 1:5{
      ALLStackedCompPrice[,i]<- rbind(StackedCompPrice, ALLStackedCompPrice)
}}

    ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories


问:
How to track down log4net problems
I use log4net all the time, but one thing I've never figured out is how to tell what's going on on the inside. For example, I've got a console appender and a database appender in my project. I made a few changes to the database and the code, and now the database appender doesn't work anymore. I'll figure out why eventually, but it would help a lot if I could see what's going on inside log4net.

Does log4net generate any kind of output that I can view to try to determine the source of my problem?

答:
Make sure the root application where your entry point is logs something to log4net. Give it one of these:

```<code>private static ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
    logger.InfoFormat("{0} v.{1} started.", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString());
</code>```

With 2.0.8, I had an interesting situation. I created a library project and a test exe project that would demo it's capabilities. The library project was set up to use Log4net as was the exe project. The exe project used the assemblyinfo attribute to register the config, yet I was getting no logging output to either the console or the log file. When I turned on log4net internal debug logging, I got some internal messages written to the console, but still none of my normal logs. No errors were being reported. It all started working when I added the above code to my program. Log4net was otherwise setup correctly.

Title: How to track down log4net problems

Body:
Make sure the root application where your entry point is logs something to log4net. Give it one of these:

private static ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
    logger.InfoFormat("{0} v.{1} started.", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString());

With 2.0.8, I had an interesting situation. I created a library project and a test exe project that would demo it's capabilities. The library project was set up to use Log4net as was the exe project. The exe project used the assemblyinfo attribute to register the config, yet I was getting no logging output to either the console or the log file. When I turned on log4net internal debug logging, I got some internal messages written to the console, but still none of my normal logs. No errors were being reported. It all started working when I added the above code to my program. Log4net was otherwise setup correctly.


问:
lists match with dataframe
I want to match lists with dataframe

```<code>> lists
    [[1]]
    [1] "SURFSKINTEMP=6" "MODIS_LST=1"

    [[2]]
    [1] "TOTCO=13"    "MODIS_LST=1"

    [[3]]
    [1] "TOTCO=6"     "MODIS_LST=1"

    [[4]]
    [1] "TOTO3=15"    "MODIS_LST=1"

    [[5]]
    [1] "TOTH2OVAP=6" "MODIS_LST=1"

    [[6]]
    [1] "TOTH2OVAP=1" "MODIS_LST=1"
</code>```

and the test dataframe

```<code> > test
      LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
    1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1
</code>```

in above example. data.frame match 3 lists

```<code>[1] "SURFSKINTEMP=6" "MODIS_LST=1"
[1] "TOTCO=13"    "MODIS_LST=1"
[1] "TOTH2OVAP=6" "MODIS_LST=1"
</code>```

so the match count is 3, matching ratio is 3/6 = 50%.

my expect will add two columns(MATCH_COUNT  MATCH_RATIO), like:

```<code>  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4  OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST  MATCH_COUNT  MATCH_RATIO
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13        10          10       10         1            3          0.5
</code>```

the list and test dataframe I used is:

```<code>lists <- list(c("SURFSKINTEMP=6", "MODIS_LST=1"), c("TOTCO=13", "MODIS_LST=1"
), c("TOTCO=6", "MODIS_LST=1"), c("TOTO3=15", "MODIS_LST=1"),
    c("TOTH2OVAP=6", "MODIS_LST=1"), c("TOTH2OVAP=1", "MODIS_LST=1"
    ))

test <- structure(list(LONGITUDE = 118.5, LATITUDE = -11.5, DATE_START = structure(1419897600, class = c("POSIXct",
"POSIXt")), DATE_END = structure(1420502400, class = c("POSIXct",
"POSIXt")), FLAG = 2, SURFSKINTEMP = 6L, SURFAIRTEMP = 6L, TOTH2OVAP = 6L,
    TOTO3 = 16L, TOTCO = 13L, TOTCH4 = 13L, OLR_ARIS = 10L, CLROLR_ARIS = 10L,
    OLR_NOAA = 10L, MODIS_LST = 1L), .Names = c("LONGITUDE",
"LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
"SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
"CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = 1L, class = "data.frame")
</code>```

How to implement it, thanks

and for multi-rows

```<code>> test1
  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1
2     118.5    -11.5 2014-12-31 2015-01-07    2            1           6         1    16     6     14        4           4       10         1
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4           4       10         2
</code>```

my expect is

```<code>  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST  MATCH_COUNT  MATCH_RATIO
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1            3          0.5
2     118.5    -11.5 2014-12-31 2015-01-07    2            1           6         1    16     6     14        4           4       10         1            2        0.333
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4           4       10         2            0            0
</code>```

used data here is

```<code>test1 <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5), LATITUDE = c(-11.5,
-11.5, -11.5), DATE_START = structure(c(1419897600, 1419984000,
1420070400), class = c("POSIXct", "POSIXt")), DATE_END = structure(c(1420502400,
1420588800, 1420675200), class = c("POSIXct", "POSIXt")), FLAG = c(2,
2, 2), SURFSKINTEMP = c(6L, 1L, 16L), SURFAIRTEMP = c(6L, 6L,
6L), TOTH2OVAP = c(6L, 1L, 17L), TOTO3 = c(16L, 16L, 16L), TOTCO = c(13L,
6L, 8L), TOTCH4 = c(13L, 14L, 6L), OLR_ARIS = c(10L, 4L, 4L),
    CLROLR_ARIS = c(10L, 4L, 4L), OLR_NOAA = c(10L, 10L, 10L),
    MODIS_LST = c(1L, 1L, 2L)), .Names = c("LONGITUDE", "LATITUDE",
"DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP", "SURFAIRTEMP",
"TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS", "CLROLR_ARIS",
"OLR_NOAA", "MODIS_LST"), row.names = c(NA, 3L), class = "data.frame")
</code>```

答:
We could paste the column names of 'test' with the single row of 'test', check whether all the elements in each list element are there in the pasted vector to get a logical vector.  Create the column by getting the sum and mean of the logical vector

```<code>v1 <- paste(names(test), unlist(test), sep="=")
i1 <- sapply(lists, function(x) all(x %in% v1))
test[c('MATCH_COUNT', 'MATCH_RATIO')] <- list(sum(i1), mean(i1))
test
#  LONGITUDE LATITUDE          DATE_START            DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
#1     118.5    -11.5 2014-12-30 05:30:00 2015-01-06 05:30:00    2            6           6         6    16    13     13       10          10       10         1
#  MATCH_COUNT MATCH_RATIO
#1           3         0.5
</code>```

If the dataset 'test' have greater than 1 row, then

```<code>m1 <- matrix(paste(names(test1)[col(test1)], unlist(test1), sep="="), ncol = ncol(test1))
i2 <- sapply(lists, function(x) apply(m1, 1, function(y) all(x %in% y)))
test1[c('MATCH_COUNT', 'MATCH_RATIO')] <- list(rowSums(i2), rowMeans(i2))
</code>```

Title: lists match with dataframe

Body:
I want to match lists with dataframe

> lists
    [[1]]
    [1] "SURFSKINTEMP=6" "MODIS_LST=1"

    [[2]]
    [1] "TOTCO=13"    "MODIS_LST=1"

    [[3]]
    [1] "TOTCO=6"     "MODIS_LST=1"

    [[4]]
    [1] "TOTO3=15"    "MODIS_LST=1"

    [[5]]
    [1] "TOTH2OVAP=6" "MODIS_LST=1"

    [[6]]
    [1] "TOTH2OVAP=1" "MODIS_LST=1"

and the test dataframe

 > test
      LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
    1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1

in above example. data.frame match 3 lists

[1] "SURFSKINTEMP=6" "MODIS_LST=1"
[1] "TOTCO=13"    "MODIS_LST=1"
[1] "TOTH2OVAP=6" "MODIS_LST=1"

so the match count is 3, matching ratio is 3/6 = 50%.

my expect will add two columns(MATCH_COUNT  MATCH_RATIO), like:

  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4  OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST  MATCH_COUNT  MATCH_RATIO
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13        10          10       10         1            3          0.5

the list and test dataframe I used is:

lists <- list(c("SURFSKINTEMP=6", "MODIS_LST=1"), c("TOTCO=13", "MODIS_LST=1"
), c("TOTCO=6", "MODIS_LST=1"), c("TOTO3=15", "MODIS_LST=1"),
    c("TOTH2OVAP=6", "MODIS_LST=1"), c("TOTH2OVAP=1", "MODIS_LST=1"
    ))

test <- structure(list(LONGITUDE = 118.5, LATITUDE = -11.5, DATE_START = structure(1419897600, class = c("POSIXct",
"POSIXt")), DATE_END = structure(1420502400, class = c("POSIXct",
"POSIXt")), FLAG = 2, SURFSKINTEMP = 6L, SURFAIRTEMP = 6L, TOTH2OVAP = 6L,
    TOTO3 = 16L, TOTCO = 13L, TOTCH4 = 13L, OLR_ARIS = 10L, CLROLR_ARIS = 10L,
    OLR_NOAA = 10L, MODIS_LST = 1L), .Names = c("LONGITUDE",
"LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
"SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
"CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = 1L, class = "data.frame")

How to implement it, thanks

and for multi-rows

> test1
  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1
2     118.5    -11.5 2014-12-31 2015-01-07    2            1           6         1    16     6     14        4           4       10         1
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4           4       10         2

my expect is

  LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST  MATCH_COUNT  MATCH_RATIO
1     118.5    -11.5 2014-12-30 2015-01-06    2            6           6         6    16    13     13       10          10       10         1            3          0.5
2     118.5    -11.5 2014-12-31 2015-01-07    2            1           6         1    16     6     14        4           4       10         1            2        0.333
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4           4       10         2            0            0

used data here is

test1 <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5), LATITUDE = c(-11.5,
-11.5, -11.5), DATE_START = structure(c(1419897600, 1419984000,
1420070400), class = c("POSIXct", "POSIXt")), DATE_END = structure(c(1420502400,
1420588800, 1420675200), class = c("POSIXct", "POSIXt")), FLAG = c(2,
2, 2), SURFSKINTEMP = c(6L, 1L, 16L), SURFAIRTEMP = c(6L, 6L,
6L), TOTH2OVAP = c(6L, 1L, 17L), TOTO3 = c(16L, 16L, 16L), TOTCO = c(13L,
6L, 8L), TOTCH4 = c(13L, 14L, 6L), OLR_ARIS = c(10L, 4L, 4L),
    CLROLR_ARIS = c(10L, 4L, 4L), OLR_NOAA = c(10L, 10L, 10L),
    MODIS_LST = c(1L, 1L, 2L)), .Names = c("LONGITUDE", "LATITUDE",
"DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP", "SURFAIRTEMP",
"TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS", "CLROLR_ARIS",
"OLR_NOAA", "MODIS_LST"), row.names = c(NA, 3L), class = "data.frame")

Body:
We could paste the column names of 'test' with the single row of 'test', check whether all the elements in each list element are there in the pasted vector to get a logical vector.  Create the column by getting the sum and mean of the logical vector

v1 <- paste(names(test), unlist(test), sep="=")
i1 <- sapply(lists, function(x) all(x %in% v1))
test[c('MATCH_COUNT', 'MATCH_RATIO')] <- list(sum(i1), mean(i1))
test
#  LONGITUDE LATITUDE          DATE_START            DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS CLROLR_ARIS OLR_NOAA MODIS_LST
#1     118.5    -11.5 2014-12-30 05:30:00 2015-01-06 05:30:00    2            6           6         6    16    13     13       10          10       10         1
#  MATCH_COUNT MATCH_RATIO
#1           3         0.5

If the dataset 'test' have greater than 1 row, then

m1 <- matrix(paste(names(test1)[col(test1)], unlist(test1), sep="="), ncol = ncol(test1))
i2 <- sapply(lists, function(x) apply(m1, 1, function(y) all(x %in% y)))
test1[c('MATCH_COUNT', 'MATCH_RATIO')] <- list(rowSums(i2), rowMeans(i2))


问:
Can I use an HTML input type "date" to collect only a year?
I have a field that is required to collect a year from the user (i.e. a date with a year resolution - for ease of storage I'd prefer to store an actual date value and not a number).

I would like to use the date input UI supported by modern browsers or webshims because its nice and plays well with modern platforms. I couldn't figure out how to get the UI to display only the year. Any ideas?

If there is no platform support, ideally I would like to have a UI something like you can see here if you click "Preview" and then click the top of the widget a couple of times, except in reverse: when you first click the input you get a widget with a list of decades, then you drill down to choose the year, then the UI closes.

答:
There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

```<code><!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>
</code>```

Body:
There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>