问:
Hive - XML- Serde - Key Value Pair - Create table
Key Value pair combination. We are trying to explode the ID as a column name and VALUE as the corresponding data for each column.

```<code>`<CT> <items> <item> <field> <id>Column1</id> <value>25672</value> </field>
 <field> <id>Column2</id> <value>FGE</value> </field> <field>
 <id>Column3</id> <value>Florence to Venice</value> </field> </item>
 </items>
 </CT>`
</code>```

We are expecting to create a table as below,
Expected Output:

```<code>Column1 Column2 Column3
25672   FGE     Florence to Venice
</code>```

We tried using Map to extract the key value pair but we are not getting the desired result.

```<code>'CREATE EXTERNAL TABLE dev.reference_test(
PM_SubCollection array<map<string,string>>
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES(
"column.xpath.PM_SubCollection"="/CT/items/item/field",
"xml.map.specification.id"="#id->#value"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
LOCATION '/dev/reference_test'
TBLPROPERTIES (
"xmlinput.start"="",
"xmlinput.end"=""
);'

Output:
'[{"field":"Column125672"},{"field":"Column2FGE"},{"field":"Column3Florence to Venice"}]'
</code>```

Any suggestions would be helpful

答:
See https://github.com/dvasilen/Hive-XML-SerDe/issues/42

If you have to capture the message id as well as id and value from the following XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<CT>
   <messageID>11736</messageID>
   <items>
      <item>
         <field>
            <id>Column1</id>
            <value>25672</value>
         </field>
         <field>
            <id>Column2</id>
            <value>FGE</value>
         </field>
         <field>
            <id>Column3</id>
            <value>Florence to Venice</value>
         </field>
      </item>
   </items>
</CT>
</code>```

Then I would go with the DDL which looks like this:

```<code>DROP TABLE IF EXISTS xml_42a;

CREATE  TABLE xml_42a(
message_id string,
fields array<struct<field:struct<id:string,value:string>>>
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES(
  "column.xpath.message_id"="/CT/messageID/text()",
  "column.xpath.fields"="/CT/items/item/field"
  )
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
TBLPROPERTIES (
"xmlinput.start"="<CT>",
"xmlinput.end"="</CT>"
);

load data local inpath '/Users/dvasilen/Misc/XML/42a.xml' OVERWRITE into table xml_42a;

select * from xml_42a;
</code>```

and here is the output:

```<code>hive>
    > select * from xml_42a;
OK
11736   [{"field":{"id":"Column1","value":"25672"}},{"field":{"id":"Column2","value":"FGE"}},{"field":{"id":"Column3","value":"Florence to Venice"}}]
Time taken: 0.08 seconds, Fetched: 1 row(s)
</code>```

Body:
Key Value pair combination. We are trying to explode the ID as a column name and VALUE as the corresponding data for each column.

`<CT> <items> <item> <field> <id>Column1</id> <value>25672</value> </field>
 <field> <id>Column2</id> <value>FGE</value> </field> <field>
 <id>Column3</id> <value>Florence to Venice</value> </field> </item>
 </items>
 </CT>`

We are expecting to create a table as below,
Expected Output:

Column1 Column2 Column3
25672   FGE     Florence to Venice

We tried using Map to extract the key value pair but we are not getting the desired result.

'CREATE EXTERNAL TABLE dev.reference_test(
PM_SubCollection array<map<string,string>>
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES(
"column.xpath.PM_SubCollection"="/CT/items/item/field",
"xml.map.specification.id"="#id->#value"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
LOCATION '/dev/reference_test'
TBLPROPERTIES (
"xmlinput.start"="",
"xmlinput.end"=""
);'

Output:
'[{"field":"Column125672"},{"field":"Column2FGE"},{"field":"Column3Florence to Venice"}]'

Any suggestions would be helpful

Body:
See https://github.com/dvasilen/Hive-XML-SerDe/issues/42

If you have to capture the message id as well as id and value from the following XML

<?xml version="1.0" encoding="UTF-8"?>
<CT>
   <messageID>11736</messageID>
   <items>
      <item>
         <field>
            <id>Column1</id>
            <value>25672</value>
         </field>
         <field>
            <id>Column2</id>
            <value>FGE</value>
         </field>
         <field>
            <id>Column3</id>
            <value>Florence to Venice</value>
         </field>
      </item>
   </items>
</CT>

Then I would go with the DDL which looks like this:

DROP TABLE IF EXISTS xml_42a;

CREATE  TABLE xml_42a(
message_id string,
fields array<struct<field:struct<id:string,value:string>>>
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES(
  "column.xpath.message_id"="/CT/messageID/text()",
  "column.xpath.fields"="/CT/items/item/field"
  )
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
TBLPROPERTIES (
"xmlinput.start"="<CT>",
"xmlinput.end"="</CT>"
);

load data local inpath '/Users/dvasilen/Misc/XML/42a.xml' OVERWRITE into table xml_42a;

select * from xml_42a;

and here is the output:

hive>
    > select * from xml_42a;
OK
11736   [{"field":{"id":"Column1","value":"25672"}},{"field":{"id":"Column2","value":"FGE"}},{"field":{"id":"Column3","value":"Florence to Venice"}}]
Time taken: 0.08 seconds, Fetched: 1 row(s)


来源: stackexchange

问:
How can I get the precision of a decimal in js?
This is probably a super easy thing to solve, but I just can't think of an elegant solution right now.

Given the following numbers, how do I find the precision (.0001) of each number.

```<code>126.01
1.3450
</code>```

Update:
The number of digits after the decimal.

The output from the top two numbers would be.

```<code>.01
.0001
</code>```

答:
Maybe try building a simple function like:</p>

```<code>function acc(num) {
  var splt = num.toString().replace(/\.|$/, '.').split('.');
  return splt[1].length
    ? 1 / Math.pow(10, splt[1].length)
    : Math.pow(10, /0*$/.exec(splt[0])[0].length);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is probably a super easy thing to solve, but I just can't think of an elegant solution right now.

Given the following numbers, how do I find the precision (.0001) of each number.

126.01
1.3450

Update:
The number of digits after the decimal.

The output from the top two numbers would be.

.01
.0001

Body:
Maybe try building a simple function like:

function acc(num) {
  var splt = num.toString().replace(/\.|$/, '.').split('.');
  return splt[1].length
    ? 1 / Math.pow(10, splt[1].length)
    : Math.pow(10, /0*$/.exec(splt[0])[0].length);
}

ContentLicense: CC BY-SA 3.0


问:
'data validation rule limit of 500' error on google script
I'm trying to implement the script to the spreadsheet which will get all folder list and all files list in subfolder of Google drive api with this code,

[I found on this forum]

//GLOBAL VARIABLES

var ss = SpreadsheetApp.getActiveSpreadsheet()
  .getSheets()[0];
var listCell = 'B1';
var idRange = 'A2:B2';
var idCell = 'B2';

function onOpen() {

  SpreadsheetApp.getUi()
    .createMenu('Get Files From Folder')
    .addItem('STEP 1: Get my folders', 'getAllFolders')
    .addItem('STEP 2: Get ID of selected folder', 'getId')
    .addItem('STEP 3: Get all Files', 'getAllFiles')
    .addToUi();
}

function getAllFolders() {
  var arr = [];
  var all = DriveApp.getFolders();
  while (all.hasNext()) {
    var folder = all.next();
    arr.push(folder.getName())
  }
  arr.sort(function(first, next) {
    first.toLowerCase(),
      next.toLowerCase();
    return first < next ? -1 : first > next ? 1 : 0;
  });
  var cell = ss.getRange(listCell);
  cell.setDataValidation(SpreadsheetApp.newDataValidation()
      .requireValueInList(arr, true)
      .build())
    .setVerticalAlignment('middle');
  cell.offset(0, -1)
    .setValue('FOLDERS: ')
    .setBackground('#50803c')
    .setFontColor('White')
    .setFontWeight('Bold')
    .setHorizontalAlignment('center')
    .setVerticalAlignment('middle');
  ss.setRowHeight(1, 50);
}
//STEP2

function getId() {
  ss.getRange(idRange)
    .setValues([
      ["ID: ", DriveApp.getFoldersByName(ss.getRange(listCell)
          .getValue())
        .next()
        .getId()
      ]
    ])
    .setVerticalAlignment('middle')
    .setFontColor('grey');
}

//STEP3

function getAllFiles() {
  var id = ss.getRange(idCell).getValue();
  ss.getRange(4, 1, ss.getLastRow(), ss.getLastColumn()).clear();
  var arr = [
    ["FILENAME", "URL"]
  ];
  var f = DriveApp.getFolderById(id).getFiles()
  while (f.hasNext()) {
    var file = f.next();
    var name = file.getName()
    arr.push([name, '=HYPERLINK("' + file
      .getUrl() + '"; "' + name + '")'
    ]);
  }
  ss.getRange(4, 1, arr.length, arr[0].length).setValues(arr);
}```

but I got an error

The data validation rule has more items than the limit of 500. Use the "List from a range" criteria instead.

I have no clue why I got this error, probably too many subfolders

Is there anyway to edit code to get 3 level of subfolder like

root folder > subfolder1 >subfolder2>subfolder3

or anything that can solve this error ,Thanks

答: It is an issue exactly as the error message says. You may check this documentation. Apps Script services impose daily quotas and hard limitations on some features. If you exceed a quota or limitation, your script will throw an exception and terminate execution.</p>

Body:
I'm trying to implement the script to the spreadsheet which will get all folder list and all files list in subfolder of Google drive api with this code,

[I found on this forum]

//GLOBAL VARIABLES

var ss = SpreadsheetApp.getActiveSpreadsheet()
  .getSheets()[0];
var listCell = 'B1';
var idRange = 'A2:B2';
var idCell = 'B2';

function onOpen() {

  SpreadsheetApp.getUi()
    .createMenu('Get Files From Folder')
    .addItem('STEP 1: Get my folders', 'getAllFolders')
    .addItem('STEP 2: Get ID of selected folder', 'getId')
    .addItem('STEP 3: Get all Files', 'getAllFiles')
    .addToUi();
}

function getAllFolders() {
  var arr = [];
  var all = DriveApp.getFolders();
  while (all.hasNext()) {
    var folder = all.next();
    arr.push(folder.getName())
  }
  arr.sort(function(first, next) {
    first.toLowerCase(),
      next.toLowerCase();
    return first < next ? -1 : first > next ? 1 : 0;
  });
  var cell = ss.getRange(listCell);
  cell.setDataValidation(SpreadsheetApp.newDataValidation()
      .requireValueInList(arr, true)
      .build())
    .setVerticalAlignment('middle');
  cell.offset(0, -1)
    .setValue('FOLDERS: ')
    .setBackground('#50803c')
    .setFontColor('White')
    .setFontWeight('Bold')
    .setHorizontalAlignment('center')
    .setVerticalAlignment('middle');
  ss.setRowHeight(1, 50);
}
//STEP2

function getId() {
  ss.getRange(idRange)
    .setValues([
      ["ID: ", DriveApp.getFoldersByName(ss.getRange(listCell)
          .getValue())
        .next()
        .getId()
      ]
    ])
    .setVerticalAlignment('middle')
    .setFontColor('grey');
}

//STEP3

function getAllFiles() {
  var id = ss.getRange(idCell).getValue();
  ss.getRange(4, 1, ss.getLastRow(), ss.getLastColumn()).clear();
  var arr = [
    ["FILENAME", "URL"]
  ];
  var f = DriveApp.getFolderById(id).getFiles()
  while (f.hasNext()) {
    var file = f.next();
    var name = file.getName()
    arr.push([name, '=HYPERLINK("' + file
      .getUrl() + '"; "' + name + '")'
    ]);
  }
  ss.getRange(4, 1, arr.length, arr[0].length).setValues(arr);
}

but I got an error

The data validation rule has more items than the limit of 500. Use the "List from a range" criteria instead.

I have no clue why I got this error, probably too many subfolders

Is there anyway to edit code to get 3 level of subfolder like

root folder > subfolder1 >subfolder2>subfolder3

or anything that can solve this error ,Thanks


问:
django - why is this custom middleware not working
I am building a website using django 1.10. I have written a middleware class to restrict the number of page views for users that are not logged in. I implemented this functionality into a separate application 'pagerestrict'

settings.py [Relevant Entries]

```<code># Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        'django.contrib.sites',

        'pagerestrict.apps.PagerestrictConfig',
        # ...
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',

        'pagerestrict.middleware.CheckPageAccessMiddleware',
    ]
</code>```

Middleware code (middleware.py):

```<code>from django.http import HttpResponseRedirect
from decouple import config

class CheckPageAccessMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_request(self, request):
        if not request.user.is_authenticated():
            current_page_url = request.path_info.lstrip('/')

            ignore_list = config('PAGE_RESTRICT_PAGE_IGNORES', cast=lambda v: [s.strip() for s in v.split(',')])

            #if not current_page_url or not any(current_page_url != url for url in ignore_list):
            if not current_page_url in ignore_list:
                # first things first ...
                if not has_attr(request, 'pages_visited'):
                    request.pages_visited = set()

                if not has_attr(request, 'page_count'):
                    request.page_count = 0

                if current_page_url not in request.pages_visited:
                    request.pages_visited.add(current_page_url)

                request.page_count += 1

                if request.page_count > config('PAGE_RESTRICT_PAGE_LIMIT'):
                    return HttpResponseRedirect(config('PAGE_RESTRICT_REDIRECT_URL'))
</code>```

I tested this by going to my homepage and refreshing the browser several times - the code never seemed to be triggered. What am I missing?

答:
New-style middleware does not call process_request and process_response by default. This functionally has been replaced with __call__ and the get_response function that is passed to __init__.

You need to call process_request() inside __call__ and process the return value if it is not None. The easiest way to do this is to use the MiddlewareMixin provided by Django. This will define the necessary __init__ and __call__ methods, and __call__ will call process_request() and process_response() if they are defined.

from django.utils.deprecation import MiddlewareMixin

class CheckPageAccessMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if not request.user.is_authenticated():
            current_page_url = request.path_info.lstrip('/')

            ignore_list = config('PAGE_RESTRICT_PAGE_IGNORES', cast=lambda v: [s.strip() for s in v.split(',')])

            #if not current_page_url or not any(current_page_url != url for url in ignore_list):
            if not current_page_url in ignore_list:
                # first things first ...
                if not has_attr(request, 'pages_visited'):
                    request.pages_visited = set()

                if not has_attr(request, 'page_count'):
                    request.page_count = 0

                if current_page_url not in request.pages_visited:
                    request.pages_visited.add(current_page_url)

                request.page_count += 1

                if request.page_count > config('PAGE_RESTRICT_PAGE_LIMIT'):
                    return HttpResponseRedirect(config('PAGE_RESTRICT_REDIRECT_URL'))
```

Body:
I am building a website using django 1.10. I have written a middleware class to restrict the number of page views for users that are not logged in. I implemented this functionality into a separate application 'pagerestrict'

settings.py [Relevant Entries]

# Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        'django.contrib.sites',

        'pagerestrict.apps.PagerestrictConfig',
        # ...
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',

        'pagerestrict.middleware.CheckPageAccessMiddleware',
    ]

Middleware code (middleware.py):

from django.http import HttpResponseRedirect
from decouple import config

class CheckPageAccessMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_request(self, request):
        if not request.user.is_authenticated():
            current_page_url = request.path_info.lstrip('/')

            ignore_list = config('PAGE_RESTRICT_PAGE_IGNORES', cast=lambda v: [s.strip() for s in v.split(',')])

            #if not current_page_url or not any(current_page_url != url for url in ignore_list):
            if not current_page_url in ignore_list:
                # first things first ...
                if not has_attr(request, 'pages_visited'):
                    request.pages_visited = set()

                if not has_attr(request, 'page_count'):
                    request.page_count = 0

                if current_page_url not in request.pages_visited:
                    request.pages_visited.add(current_page_url)

                request.page_count += 1

                if request.page_count > config('PAGE_RESTRICT_PAGE_LIMIT'):
                    return HttpResponseRedirect(config('PAGE_RESTRICT_REDIRECT_URL'))

I tested this by going to my homepage and refreshing the browser several times - the code never seemed to be triggered. What am I missing?

ContentLicense: CC BY-SA 4.0


问:
What does this mean: "You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement"?
I've found this note in the Swift documentation about initializers:

You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.

What is an "explicit" implementation? What is an "implicit" one then?

What does "satisfy the requirement with an inherited initializer" mean precisely?

Could you give me a code example, in which I don't have to provide an explicit implementation of a required initializer?

答:
It is saying this: If you have initialized all your properties as you declare them, there's no need to write an initializer.

Normally, when you have properties declared and not set, you write an init() method and set them there, and if there's a required initializer in the parent class, you call

```<code>super.init(possible, arg: anotherArg)
</code>```

Since you don't need to set anything, you don't need to write anything, and since there's no init in your class, the super call will happen automatically. (Of course, if the required init needs values passed in, you still need to supply them.) So how is that accomplished? (see below.) The bottom line is that most of the work is done for you.

However, once you write an init(), then you're taking away this automatic behavior, and you have to make sure that those "automatic" calls are explicitly made.

Finally, before I provide an example, I should address this statement:

"if you can satisfy the requirement with an inherited initializer"

If the parent doesn't have an initializer which takes no arguments, how will it get those arguments?  In that case you need initialize your class using that required super's init with the proper arguments.

Here's an example of a view controller which is not set up in IB, I would normally create it using the super's required initializer, since I didn't write an initializer for my derived class:

let vc = MagicController(nibName: nil, bundle: nil)

```<code>import UIKit
import Dotzu

class MagicController: UIViewController, UIGestureRecognizerDelegate {
    let action = #selector(MagicController.buttonTapped(_:))
    let action2 = #selector(MagicController.secondButtonTapped(_:))
    let mainAction = #selector(MagicController.mainButtonTapped(_:))

    let defaultPalette = Palette.randomPalette()
    var questions = [Question]()
    var startTime = TimeInterval()
    var endTime = TimeInterval()
    var selectedTimeIndex = 0
    var selectedTagIndex = 0
    var selectedRatingIndex = 0
    var selectedTag = "swift"
    let timeSpanDropDown = DropDown()
    let ratingDropDown = DropDown()
    let tagDropDown = DropDown()
    var pageNumber = 1
    var savedIndex = 0
    var savedPostId = -1
    var quotaCount = -1
    var isFirstTime = true

    let queryFactory = Queries(client: APIClient())

    var timeSpanButton = UIBarButtonItem()
    var ratingButton = UIBarButtonItem()
    var tagButton = UIBarButtonItem()
    var dbButton = UIBarButtonItem() //

/// start the console log, configure the main view's buttons/actions and present the UI
    override func viewDidLoad() {
        super.viewDidLoad()
        Dotzu.sharedManager.enable()
        self.edgesForExtendedLayout = []
        configureButtons(container: view)
        view.setNeedsLayout()
    }

    ///configure the buttons/actions, prepare and present the UI
    /// The first time this is called it sets up the buttons and drop downs
    /// cleanupDataSource() has no effect the first time it is called
    /// - Parameter animated: passed to super
    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if isFirstTime {
                isFirstTime = false
                initializeButtons()
                setupDropDowns()
            }
            cleanupDataSource()
        }
/// etc.
}
</code>```

As you can see, I did not write an init for this view controller, even though a view controller has a required init. I initialized my view controller using an init() that isn't even in my code.

Body:
It is saying this: If you have initialized all your properties as you declare them, there's no need to write an initializer.

Normally, when you have properties declared and not set, you write an init() method and set them there, and if there's a required initializer in the parent class, you call

super.init(possible, arg: anotherArg)

Since you don't need to set anything, you don't need to write anything, and since there's no init in your class, the super call will happen automatically. (Of course, if the required init needs values passed in, you still need to supply them.) So how is that accomplished? (see below.) The bottom line is that most of the work is done for you.

However, once you write an init(), then you're taking away this automatic behavior, and you have to make sure that those "automatic" calls are explicitly made.

Finally, before I provide an example, I should address this statement:

"if you can satisfy the requirement with an inherited initializer"

If the parent doesn't have an initializer which takes no arguments, how will it get those arguments?  In that case you need initialize your class using that required super's init with the proper arguments.

Here's an example of a view controller which is not set up in IB, I would normally create it using the super's required initializer, since I didn't write an initializer for my derived class:

let vc = MagicController(nibName: nil, bundle: nil)

import UIKit
import Dotzu

class MagicController: UIViewController, UIGestureRecognizerDelegate {
    let action = #selector(MagicController.buttonTapped(_:))
    let action2 = #selector(MagicController.secondButtonTapped(_:))
    let mainAction = #selector(MagicController.mainButtonTapped(_:))

    let defaultPalette = Palette.randomPalette()
    var questions = [Question]()
    var startTime = TimeInterval()
    var endTime = TimeInterval()
    var selectedTimeIndex = 0
    var selectedTagIndex = 0
    var selectedRatingIndex = 0
    var selectedTag = "swift"
    let timeSpanDropDown = DropDown()
    let ratingDropDown = DropDown()
    let tagDropDown = DropDown()
    var pageNumber = 1
    var savedIndex = 0
    var savedPostId = -1
    var quotaCount = -1
    var isFirstTime = true

    let queryFactory = Queries(client: APIClient())

    var timeSpanButton = UIBarButtonItem()
    var ratingButton = UIBarButtonItem()
    var tagButton = UIBarButtonItem()
    var dbButton = UIBarButtonItem() //

/// start the console log, configure the main view's buttons/actions and present the UI
    override func viewDidLoad() {
        super.viewDidLoad()
        Dotzu.sharedManager.enable()
        self.edgesForExtendedLayout = []
        configureButtons(container: view)
        view.setNeedsLayout()
    }

    ///configure the buttons/actions, prepare and present the UI
    /// The first time this is called it sets up the buttons and drop downs
    /// cleanupDataSource() has no effect the first time it is called
    /// - Parameter animated: passed to super
    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if isFirstTime {
                isFirstTime = false
                initializeButtons()
                setupDropDowns()
            }
            cleanupDataSource()
        }
/// etc.
}

As you can see, I did not write an init for this view controller, even though a view controller has a required init. I initialized my view controller using an init() that isn't even in my code.


问:
Canvas height and width
When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions.
Why is this happening and how can I fix this?</p>

答:
I've found the problem. I was setting the dimensions of the  using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.

```<code>var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');
</code>```

http://jsfiddle.net/h2yJn/66/

Title: Canvas height and width

Body:
I've found the problem. I was setting the dimensions of the  using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.

var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');

http://jsfiddle.net/h2yJn/66/


问:
javac current file code in vim file?
I want to source a vim file in vimrc file.
I wrote code in vim file.

```<code>set makeprg=javac %
</code>```

and vim said he doesn't know that option.
how do i write code that javac current file?

what I want to do is compiling current file in vim while coding..

答:
On the command-line a space is used to separate 2 arguments. So, when you execute:

```<code>set makeprg=javac %
</code>```

The :set command assigns the value javac to the option 'makeprg', then it tries to enable the option '%', which doesn't exist, hence the error.

If you want the space to be included inside the value of the 'makeprg' option, you need to escape it:

```<code>set makeprg=javac\ %
</code>```

Title: javac current file code in vim file?

Body:
I want to source a vim file in vimrc file.
I wrote code in vim file.

set makeprg=javac %

and vim said he doesn't know that option.
how do i write code that javac current file?

what I want to do is compiling current file in vim while coding..

Body:
On the command-line a space is used to separate 2 arguments. So, when you execute:

set makeprg=javac %

The :set command assigns the value javac to the option 'makeprg', then it tries to enable the option '%', which doesn't exist, hence the error.

If you want the space to be included inside the value of the 'makeprg' option, you need to escape it:

set makeprg=javac\ %


问:
Async operation freezing UI
I'm working on a small application that displays a lists of people in a DataGrid. I've dipped my toe in the async thread-pool (punny, eh?) and most of it has worked well. However, I am now running into a problem. I understand the origins of the problem, but I'm stumped for a solution.

In my DataGrid, I have a Style with DataTriggers to update the Visibility of my rows based on a property of my view model. I use the property during a Levenshtein distance search to determine if the rows will be displayed. When I clear the search, I set the property IsResult to true on all objects in the collection to re-display the full list.

I am aware that the problem is the rapid Layout updates of the UI, rather than the iteration process itself. I have confirmed this with performance profiling. I know async/await isn't a magic solution to all UI issues, so I just need some direction on how to manage this operation more gracefully.

The project isn't large enough to warrant the complexity of running the DataGrid in Virtual mode, so I'm hoping there is another solution, whether in how I'm executing the search or how to corral DataGrid.

DataGrid

```<code>    <Style x:Key="EditableDataGrid" TargetType="DataGrid">
        <Setter Property="IsReadOnly" Value="True"/>
        <Setter Property="AutoGenerateColumns" Value="False"/>
        <Setter Property="RowBackground" Value="WhiteSmoke"/>
        <Setter Property="AlternatingRowBackground" Value="AntiqueWhite"/>
        <EventSetter Event="MouseDoubleClick" Handler="GridDoubleClick"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=Editing}" Value="True">
                <Setter Property="IsReadOnly" Value="False"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=Adding}" Value="True">
                <Setter Property="IsReadOnly" Value="False"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <DataGrid Name="FlaggedPersonDataGrid"
              Grid.Column="0"
              ItemsSource="{Binding FlaggedPeople}"
              Style="{StaticResource EditableDataGrid}">

        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=IsResult}" Value="False">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>

        <DataGrid.Columns>
            <DataGridTextColumn Width="*" Header="Last Name"
                                Binding="{Binding LastName, UpdateSourceTrigger=LostFocus}"/>
            <DataGridTextColumn Width="*" Header="First Name"
                                Binding="{Binding FirstName, UpdateSourceTrigger=LostFocus}"/>
        </DataGrid.Columns>

        <DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
                             Color="#FF3399FF"/>
        </DataGrid.Resources>

    </DataGrid>
</code>```

Search Function

```<code>    private async Task ExecuteSearchAsync()
    {

        string searchTerm = SearchText.Text;
        double lastNameScore, firstNameScore, distanceScore, searchSensitivity;

        ObservableCollection<FlaggedPersonViewModel> searchBase = contextViewModel.FlaggedPeople;

        searchSensitivity = SensitivitySlider.Value / 100;

        await Task.Run
            (() =>
            {
                foreach (FlaggedPersonViewModel person in searchBase)
                {
                    lastNameScore = GetLevenshteinDistance(searchTerm, person.LastName, false);
                    lastNameScore = (person.LastName.Length - lastNameScore) / person.LastName.Length;

                    firstNameScore = GetLevenshteinDistance(searchTerm, person.FirstName, false);
                    firstNameScore = (person.FirstName.Length - firstNameScore) / person.FirstName.Length;

                    distanceScore = System.Math.Max(firstNameScore, lastNameScore);

                    if (distanceScore > searchSensitivity)
                        person.IsResult = true;
                    else
                        person.IsResult = false;
                }
            });
    }
</code>```

Clear Search Function

```<code>    private async Task ClearSearchAsync()
    {
        ObservableCollection<FlaggedPersonViewModel> searchBase = contextViewModel.FlaggedPeople;

        await Task.Run
            (() =>
            {
                foreach (FlaggedPersonViewModel person in searchBase)
                    person.IsResult = true;
            });
    }
</code>```

Handler Calling Search Operations

```<code>    private async void Search_Click(object sender, RoutedEventArgs e)
    {
        if (contextViewModel.Searching)
        {
            contextViewModel.Processing = true;

            //Already searching, revert to clear state
            contextViewModel.Searching = false;
            await ClearSearchAsync();

            contextViewModel.Processing = false;
        }
        else
        {
            contextViewModel.Processing = true;

            contextViewModel.Searching = true;
            await ExecuteSearchAsync();

            contextViewModel.Processing = false;
        }
    }
</code>```

Performance Profile

EDIT

I removed await Task.Run from the ClearSearchAsync function, to run the process on the main thread. It seems to have decreased performance further.

1.42s in the async run, 2.39 in the synchronous run

Update 07/14/2017
For the time being, I've just resorted to re-running the query and throwing a fresh collection into the grid. I'm not really satisfied with this, as it seems like using a sledgehammer for a detail job.

答:
Alot of moving parts especially on the UI tends to slow down updates when many action/events try to execute at the same time.

I see no immediate issues with the above code but advise refactoring some of the method calls to use explicit dependencies, especially given the async nature of the calls so as to identify how UI dependent components are being interacted with.

ExecuteSearchAsync Refactored

```<code>private async Task ExecuteSearchAsync(string searchTerm, ObservableCollection<FlaggedPersonViewModel> searchBase, double searchSensitivity) {
    double lastNameScore, firstNameScore, distanceScore;
    await Task.Run
    (() => {
        foreach (FlaggedPersonViewModel person in searchBase) {
            lastNameScore = GetLevenshteinDistance(searchTerm, person.LastName, false);
            lastNameScore = (person.LastName.Length - lastNameScore) / person.LastName.Length;

            firstNameScore = GetLevenshteinDistance(searchTerm, person.FirstName, false);
            firstNameScore = (person.FirstName.Length - firstNameScore) / person.FirstName.Length;

            distanceScore = System.Math.Max(firstNameScore, lastNameScore);

            if (distanceScore > searchSensitivity)
                person.IsResult = true;
            else
                person.IsResult = false;
        }
    });
}
</code>```

ClearSearchAsync Refactored

```<code>private async Task ClearSearchAsync(ObservableCollection<FlaggedPersonViewModel> searchBase) {

    await Task.Run
        (() => {
            foreach (FlaggedPersonViewModel person in searchBase)
                person.IsResult = true;
        });
}
</code>```

Event handler refactored.

```<code>private async void Search_Click(object sender, RoutedEventArgs e) {
    if (contextViewModel.Searching) {
        contextViewModel.Processing = true;

        //Already searching, revert to clear state
        contextViewModel.Searching = false;
        await ClearSearchAsync(contextViewModel.FlaggedPeople);

        contextViewModel.Processing = false;
    } else {
        contextViewModel.Processing = true;

        contextViewModel.Searching = true;
        await ExecuteSearchAsync(SearchText.Text, contextViewModel.FlaggedPeople, SensitivitySlider.Value / 100);

        contextViewModel.Processing = false;
    }
}
</code>```

Title: Async operation freezing UI

Body:
I'm working on a small application that displays a lists of people in a DataGrid. I've dipped my toe in the async thread-pool (punny, eh?) and most of it has worked well. However, I am now running into a problem. I understand the origins of the problem, but I'm stumped for a solution.

In my DataGrid, I have a Style with DataTriggers to update the Visibility of my rows based on a property of my view model. I use the property during a Levenshtein distance search to determine if the rows will be displayed. When I clear the search, I set the property IsResult to true on all objects in the collection to re-display the full list.

I am aware that the problem is the rapid Layout updates of the UI, rather than the iteration process itself. I have confirmed this with performance profiling. I know async/await isn't a magic solution to all UI issues, so I just need some direction on how to manage this operation more gracefully.

The project isn't large enough to warrant the complexity of running the DataGrid in Virtual mode, so I'm hoping there is another solution, whether in how I'm executing the search or how to corral DataGrid.

DataGrid

    </Style>

    <DataGrid Name="FlaggedPersonDataGrid"
              Grid.Column="0"
              ItemsSource="{Binding FlaggedPeople}"
              Style="{StaticResource EditableDataGrid}">

        <DataGrid.RowStyle>

            </Style>
        </DataGrid.RowStyle>

        <DataGrid.Columns>
            <DataGridTextColumn Width="*" Header="Last Name"
                                Binding="{Binding LastName, UpdateSourceTrigger=LostFocus}"/>
            <DataGridTextColumn Width="*" Header="First Name"
                                Binding="{Binding FirstName, UpdateSourceTrigger=LostFocus}"/>
        </DataGrid.Columns>

        <DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
                             Color="#FF3399FF"/>
        </DataGrid.Resources>

    </DataGrid>

Search Function

    private async Task ExecuteSearchAsync()
    {

        string searchTerm = SearchText.Text;
        double lastNameScore, firstNameScore, distanceScore, searchSensitivity;

        ObservableCollection<FlaggedPersonViewModel> searchBase = contextViewModel.FlaggedPeople;

        searchSensitivity = SensitivitySlider.Value / 100;

        await Task.Run
            (() =>
            {
                foreach (FlaggedPersonViewModel person in searchBase)
                {
                    lastNameScore = GetLevenshteinDistance(searchTerm, person.LastName, false);
                    lastNameScore = (person.LastName.Length - lastNameScore) / person.LastName.Length;

                    firstNameScore = GetLevenshteinDistance(searchTerm, person.FirstName, false);
                    firstNameScore = (person.FirstName.Length - firstNameScore) / person.FirstName.Length;

                    distanceScore = System.Math.Max(firstNameScore, lastNameScore);

                    if (distanceScore > searchSensitivity)
                        person.IsResult = true;
                    else
                        person.IsResult = false;
                }
            });
    }

Clear Search Function

    private async Task ClearSearchAsync()
    {
        ObservableCollection<FlaggedPersonViewModel> searchBase = contextViewModel.FlaggedPeople;

        await Task.Run
            (() =>
            {
                foreach (FlaggedPersonViewModel person in searchBase)
                    person.IsResult = true;
            });
    }

Handler Calling Search Operations

    private async void Search_Click(object sender, RoutedEventArgs e)
    {
        if (contextViewModel.Searching)
        {
            contextViewModel.Processing = true;

            //Already searching, revert to clear state
            contextViewModel.Searching = false;
            await ClearSearchAsync();

            contextViewModel.Processing = false;
        }
        else
        {
            contextViewModel.Processing = true;

            contextViewModel.Searching = true;
            await ExecuteSearchAsync();

            contextViewModel.Processing = false;
        }
    }

Performance Profile

EDIT

I removed await Task.Run from the ClearSearchAsync function, to run the process on the main thread. It seems to have decreased performance further.

1.42s in the async run, 2.39 in the synchronous run

Update 07/14/2017
For the time being, I've just resorted to re-running the query and throwing a fresh collection into the grid. I'm not really satisfied with this, as it seems like using a sledgehammer for a detail job.

Body:
Alot of moving parts especially on the UI tends to slow down updates when many action/events try to execute at the same time.

I see no immediate issues with the above code but advise refactoring some of the method calls to use explicit dependencies, especially given the async nature of the calls so as to identify how UI dependent components are being interacted with.

ExecuteSearchAsync Refactored

private async Task ExecuteSearchAsync(string searchTerm, ObservableCollection<FlaggedPersonViewModel> searchBase, double searchSensitivity) {
    double lastNameScore, firstNameScore, distanceScore;
    await Task.Run
    (() => {
        foreach (FlaggedPersonViewModel person in searchBase) {
            lastNameScore = GetLevenshteinDistance(searchTerm, person.LastName, false);
            lastNameScore = (person.LastName.Length - lastNameScore) / person.LastName.Length;

            firstNameScore = GetLevenshteinDistance(searchTerm, person.FirstName, false);
            firstNameScore = (person.FirstName.Length - firstNameScore) / person.FirstName.Length;

            distanceScore = System.Math.Max(firstNameScore, lastNameScore);

            if (distanceScore > searchSensitivity)
                person.IsResult = true;
            else
                person.IsResult = false;
        }
    });
}

ClearSearchAsync Refactored

private async Task ClearSearchAsync(ObservableCollection<FlaggedPersonViewModel> searchBase) {

    await Task.Run
        (() => {
            foreach (FlaggedPersonViewModel person in searchBase)
                person.IsResult = true;
        });
}

Event handler refactored.

private async void Search_Click(object sender, RoutedEventArgs e) {
    if (contextViewModel.Searching) {
        contextViewModel.Processing = true;

        //Already searching, revert to clear state
        contextViewModel.Searching = false;
        await ClearSearchAsync(contextViewModel.FlaggedPeople);

        contextViewModel.Processing = false;
    } else {
        contextViewModel.Processing = true;

        contextViewModel.Searching = true;
        await ExecuteSearchAsync(SearchText.Text, contextViewModel.FlaggedPeople, SensitivitySlider.Value / 100);

        contextViewModel.Processing = false;
    }
}


问:
Numba python3 get error [GPU ufunc requires array arguments to have the exact types.]
I'm trying to use numba to do np.diff on my GPU.

Here is the script I use ;

```<code>import numpy as np
import numba

@numba.vectorize(["float32(float32, float32)"], target='cuda')
def vector_diff_axis0(a, b):
    return a + b

def my_diff(A, axis=0):
    if (axis == 0):
        return vector_diff_axis0(A[1:], A[:-1])
    if (axis == 1):
        return vector_diff_axis0(A[:,1:], A[:,:-1])

A = np.matrix([
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [9, 8, 7, 6, 5],
    [4, 3, 2, 1, 0],
    [0, 2, 4, 6, 8]
    ], dtype='float32')

C = my_diff(A, axis=1)
print (str(C))
</code>```

And here is the error I get ;

```<code>TypeError: No matching version.  GPU ufunc requires array arguments
to have the exact types.  This behaves like regular ufunc with casting='no'.
</code>```

Does anybody knows the reason for this?

PS : I used this video to do my script ;
https://youtu.be/jKV1m8APttU?t=388

EDIT :
Thanks for the fast answers!

I added the dtype='float32' in np.matrix but now I have this error ;
    Known signatures:
     * (float32, float32) -> float32
    File "", line 5
    [1] During: resolving callee type: Function(
    signature=(float32, float32) -> float32>)
    [2] During: typing of call at  (5)

I also tried to use float32[:] into the signature but it doesn't work and in the video I followed they don't do that

答: The dtype of your matrix will be int32, which does not match the signature of vector_diff_axis0 since it requires float32. You need to make the matrix float32, i.e. pass the argument dtype='float32' when you call np.matrix.

Body:
I'm trying to use numba to do np.diff on my GPU.

Here is the script I use ;

import numpy as np
import numba

@numba.vectorize(["float32(float32, float32)"], target='cuda')
def vector_diff_axis0(a, b):
    return a + b

def my_diff(A, axis=0):
    if (axis == 0):
        return vector_diff_axis0(A[1:], A[:-1])
    if (axis == 1):
        return vector_diff_axis0(A[:,1:], A[:,:-1])

A = np.matrix([
    [0, 1, 2, 3, 4],
    [5, 6, 7, 8, 9],
    [9, 8, 7, 6, 5],
    [4, 3, 2, 1, 0],
    [0, 2, 4, 6, 8]
    ], dtype='float32')

C = my_diff(A, axis=1)
print (str(C))

And here is the error I get ;

TypeError: No matching version.  GPU ufunc requires array arguments
to have the exact types.  This behaves like regular ufunc with casting='no'.

Does anybody knows the reason for this?

PS : I used this video to do my script ;
https://youtu.be/jKV1m8APttU?t=388

EDIT :
Thanks for the fast answers!

I added the dtype='float32' in np.matrix but now I have this error ;
    Known signatures:
     * (float32, float32) -> float32
    File "", line 5
    [1] During: resolving callee type: Function(
    signature=(float32, float32) -> float32>)
    [2] During: typing of call at  (5)

I also tried to use float32[:] into the signature but it doesn't work and in the video I followed they don't do that


问:
how to print the content in android string XML file
i need way to read xml string file Because i am trying to make program read the strings and translate the content to another language to make another xml String file with new language</p>

答:
For accessing strings.xml through java use</p>

```<code>getResources().getString(R.string.yourStringId)
</code>```

Body:
For accessing strings.xml through java use

getResources().getString(R.string.yourStringId)


问:
Why the remote branches are not shown in the ".git\refs\remotes\origin\" folder?
In my test github repo, all my remote branches are shown in the .git\refs\remotes\origin\ folder. Like this:

But I just checked another non-toy repo, all the remote branches cannot be seen in that folder. Like this:

But the git remote show origin does show a lot of remote branches. And I still can create new local branch to track those remote branches.

Why?

答:
Git has a feature where it will pack the seperate ref files into a single file to improve performance and lower the storage cost. When a ref is packed, it will no longer exist as a seperate file in the refs  folder.

When a ref is missing from the traditional $GIT_DIR/refs directory hierarchy, it is looked up in this file and used if found.

You can pack the ref files using the git pack-refs command.


问:
facets in elastic 5.5
I'm trying to build a feceted search with elastic 5.5 (With elastic 2.* I found information on how to do this but in 5.5 I can't)

Not something unusual, store-like items that i want to show hint of the amount if the user will choose to filter using some property. Image for visualisation

Data set example:

```<code>[
  {
    "id" : "978-0641723445",
    "cat" : ["book","hardcover"],
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 12.50,
    "pages_i" : 384
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 2,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 6.49,
    "pages_i" : 304
  }
,
  {
    "id" : "978-1857995879",
    "cat" : ["book","paperback"],
    "name" : "Sophie's World : The Greek Philosophers",
    "author" : "Jostein Gaarder",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 3.07,
    "pages_i" : 64
  }
,
  {
    "id" : "978-1933988177",
    "cat" : ["book","paperback"],
    "name" : "Lucene in Action, Second Edition",
    "author" : "Michael McCandless",
    "sequence_i" : 1,
    "genre_s" : "IT",
    "inStock" : true,
    "price" : 30.50,
    "pages_i" : 475
  }
]
</code>```

Thanks!

答:
You just have to use aggs instead of facets. Aggregations are much more powerful than facets.

For example:

```<code>GET index/_search
{
    "aggs" : {
        "countries" : {
            "terms" : { "field" : "country" }
        },
        "types" : {
            "terms" : { "field" : "type" }
        }
    }
}
</code>```

Then if a user click on a "facet", just add a filter clause within a bool query (this will update all facet counts) or add a post_filter to just filter the results (does not affect aggregations).

Title: facets in elastic 5.5

Body:
I'm trying to build a feceted search with elastic 5.5 (With elastic 2.* I found information on how to do this but in 5.5 I can't)

Not something unusual, store-like items that i want to show hint of the amount if the user will choose to filter using some property. Image for visualisation

Data set example:

[
  {
    "id" : "978-0641723445",
    "cat" : ["book","hardcover"],
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 12.50,
    "pages_i" : 384
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 2,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 6.49,
    "pages_i" : 304
  }
,
  {
    "id" : "978-1857995879",
    "cat" : ["book","paperback"],
    "name" : "Sophie's World : The Greek Philosophers",
    "author" : "Jostein Gaarder",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 3.07,
    "pages_i" : 64
  }
,
  {
    "id" : "978-1933988177",
    "cat" : ["book","paperback"],
    "name" : "Lucene in Action, Second Edition",
    "author" : "Michael McCandless",
    "sequence_i" : 1,
    "genre_s" : "IT",
    "inStock" : true,
    "price" : 30.50,
    "pages_i" : 475
  }
]

Thanks!

Body:
You just have to use aggs instead of facets. Aggregations are much more powerful than facets.

For example:

GET index/_search
{
    "aggs" : {
        "countries" : {
            "terms" : { "field" : "country" }
        },
        "types" : {
            "terms" : { "field" : "type" }
        }
    }
}

Then if a user click on a "facet", just add a filter clause within a bool query (this will update all facet counts) or add a post_filter to just filter the results (does not affect aggregations).


问:
Maven+JDK9 modules: Failed to parse module-info
Using 9-ea+171, Maven 3.5.0

I am compiling a project with this module-info.java:

```<code>module org.project {
}
</code>```

But it fails with a mysterious error:

```<code>[ERROR] Failed to parse module-info:
[ERROR] With qdox: null
(...)
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project rli-stubs: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project rli-stubs: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:563)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
... 20 more
Caused by: java.lang.RuntimeException: Failed to parse module-info
at org.apache.maven.plugin.compiler.TestCompilerMojo.preparePaths(TestCompilerMojo.java:322)
at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:742)
at org.apache.maven.plugin.compiler.TestCompilerMojo.execute(TestCompilerMojo.java:170)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
... 21 more
</code>```

I recreated the simplest form of the project here:
https://github.com/benji/jdk9-mvn5-withqdoxnull

It seems to have something to do with src/test/java/ . If I remove that folder then the build passes.

答: You need to put module-info.java to src/main/java. Now it is located in src/main/java/com/test which is wrong. module-info.java must be a top level file.

Body:
Using 9-ea+171, Maven 3.5.0

I am compiling a project with this module-info.java:

module org.project {
}

But it fails with a mysterious error:

[ERROR] Failed to parse module-info:
[ERROR] With qdox: null
(...)
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project rli-stubs: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project rli-stubs: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:563)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile failed: Failed to parse module-info
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
... 20 more
Caused by: java.lang.RuntimeException: Failed to parse module-info
at org.apache.maven.plugin.compiler.TestCompilerMojo.preparePaths(TestCompilerMojo.java:322)
at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:742)
at org.apache.maven.plugin.compiler.TestCompilerMojo.execute(TestCompilerMojo.java:170)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
... 21 more

I recreated the simplest form of the project here:
https://github.com/benji/jdk9-mvn5-withqdoxnull

It seems to have something to do with src/test/java/ . If I remove that folder then the build passes.


问:
Multiple selection with checkbox multi level by jquery
Currently I want to implement drop-down list with multiple group selection checkbox but could not find the exactly one. It is something similar to this : multiple select. But unfortunately, mine has multi level parent and child as this image :

This is the structure of the code :

```<code> <select id="ms" multiple="multiple">
        <option value="1">Parent 1</option>
            <option value="2">    > Child 1</option>
            <option value="2">    > Child 2</option>
        <option value="4">Parent 2</option>
        <option value="5">Parent 3</option>
            <option value="2">  > Child 1</option>
            <option value="2">  > Child 2</option>
            <option value="2">  > Sub Parent 3</option>
                <option value="2">  >-> Child 1</option>
                <option value="2">  >-> Child 2</option>
 </select>
</code>```

I don't use <optgroup> because I don't want to modify the structure of the code since all the code of the dropdown list is the structure that received from server side.

When all the children are selected, the parent would be selected too.

When all the children are selected, there should be only parent's name that showed in the selected filed.

If one of children is deselected , then the parent would be deselected too.

The sub level should work as the 1st level as well.

Is there any recommend plugin jquery for this?

Any answer would be appreciated.

答:
This is totally messed up, but you can always try to do this way:

Find the posision of check option by getting its position on a list like in this post

Make all if/else statments which requires:

Get the possition of my parent

and if all my siblings are checked: check my parent and get rig of all other scopes

Body:
Currently I want to implement drop-down list with multiple group selection checkbox but could not find the exactly one. It is something similar to this : multiple select. But unfortunately, mine has multi level parent and child as this image :

This is the structure of the code :

 <select id="ms" multiple="multiple">
        <option value="1">Parent 1</option>
            <option value="2">    > Child 1</option>
            <option value="2">    > Child 2</option>
        <option value="4">Parent 2</option>
        <option value="5">Parent 3</option>
            <option value="2">  > Child 1</option>
            <option value="2">  > Child 2</option>
            <option value="2">  > Sub Parent 3</option>
                <option value="2">  >-> Child 1</option>
                <option value="2">  >-> Child 2</option>
 </select>

I don't use <optgroup> because I don't want to modify the structure of the code since all the code of the dropdown list is the structure that received from server side.

When all the children are selected, the parent would be selected too.

When all the children are selected, there should be only parent's name that showed in the selected filed.

If one of children is deselected , then the parent would be deselected too.

The sub level should work as the 1st level as well.

Is there any recommend plugin jquery for this?

Any answer would be appreciated.


问:
PHP Type Annotation for functions?
In PHP it's common to type annotate variables like this:

```<code>  /**
   * @var boolean
   */
  protected $isLoaded;
</code>```

But what about the return types in functions? Does PHP Type Annotation support the return type of a function?

If so, how can I annotate the return type of the function in class diagram

-getName(): String

?

I would expect something like:

```<code>  /**
   * @return String
   */
  private function getName() {}
</code>```

But it's ignored.

答:
That would just be:

```<code>/**
 * @return string
 */
private function getName(): string {}
</code>```

The annotation is optional at this point.

Title: PHP Type Annotation for functions?

Body:
In PHP it's common to type annotate variables like this:

  /**
   * @var boolean
   */
  protected $isLoaded;

But what about the return types in functions? Does PHP Type Annotation support the return type of a function?

If so, how can I annotate the return type of the function in class diagram

-getName(): String

?

I would expect something like:

  /**
   * @return String
   */
  private function getName() {}

But it's ignored.

Body:
That would just be:

/**
 * @return string
 */
private function getName(): string {}

The annotation is optional at this point.


问:
Laravel 5.4 - Paginate from array collection products
i'm trying to paginate a collection's products, like this:

```<code>$products_array = array();

        for ($i=0; $i < count($t); $i++) {

            $p = Product::where('category_id',$t[$i]->category_default)->where('project_id',$t[$i]->id)->first();
            array_push($products_array, $p);
        }

        $paginate = new Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

        dd($paginate);
</code>```

But i get this error:

FatalThrowableError in HomeController.php line 75: Class
  'Shop\Http\Controllers\Illuminate\Pagination\LengthAwarePaginator' not
  found

i don't know if this is the best way to do this, I would appreciate your help.

答:
The error is really self explaining. You are trying to use Illuminate\Pagination\LengthAwarePaginator from current namespace and this is Shop\Http\Controllers.

To fix this, either add leading backslash like so:

```<code>$paginate = new \Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);
</code>```

or at the beginning of this PHP file (after opening PHP tag) add new line:

```<code>use Illuminate\Pagination\LengthAwarePaginator;
</code>```

and then you can write above line like so:

```<code>$paginate = new LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);
</code>```

To read more about namespace in PHP you can look here: https://stackoverflow.com/a/24607087/3593996

Body:
i'm trying to paginate a collection's products, like this:

$products_array = array();

        for ($i=0; $i < count($t); $i++) {

            $p = Product::where('category_id',$t[$i]->category_default)->where('project_id',$t[$i]->id)->first();
            array_push($products_array, $p);
        }

        $paginate = new Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

        dd($paginate);

But i get this error:

FatalThrowableError in HomeController.php line 75: Class
  'Shop\Http\Controllers\Illuminate\Pagination\LengthAwarePaginator' not
  found

i don't know if this is the best way to do this, I would appreciate your help.

Body:
The error is really self explaining. You are trying to use Illuminate\Pagination\LengthAwarePaginator from current namespace and this is Shop\Http\Controllers.

To fix this, either add leading backslash like so:

$paginate = new \Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

or at the beginning of this PHP file (after opening PHP tag) add new line:

use Illuminate\Pagination\LengthAwarePaginator;

and then you can write above line like so:

$paginate = new LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

To read more about namespace in PHP you can look here: https://stackoverflow.com/a/24607087/3593996


问:
Why I am advised to use pointer in Quick Sort?
I wrote Quick Sort in CPP,  it is working fine. But when I checked with Google Coding standards it is advising this. I am not able to decipher this message, can you please explain what is wrong with my code.</p>

```<code>qs.cpp:8:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:9:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:25:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:34:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
Done processing qs.cpp
Total errors found: 4

#include <iostream>
#include <vector>
#include <iomanip>
#include <utility>

void quickSort(std::vector<int> &A, int p, int r);
int partition(std::vector<int> &A, int p, int r);

int main() {
  std::vector<int> a = {2, 8, 7, 1, 3, 5, 6, 4};
  std::cout << std::setw(10) << "UnSorted Array:\n"
  for (int ele : a) {
    std::cout << ele << std::setw(5);
  }
  std::cout << std::endl << std::setw(10) << "Sorted Array:\n";
  quickSort(a, 0, a.size()-1);
  for (int ele : a) {
    std::cout << ele << std::setw(5);
  }
  std::cout << std::endl;
}

void quickSort(std::vector<int> &A, int p, int r) {
  int q;
  if ( p  < r ) {
    q = partition(A, p, r);
    quickSort(A, p, q-1);
    quickSort(A, q+1, r);
  }
}

int partition(std::vector<int> &A, int p, int r) {
  int x = A[r];
  int i = p-1;
  for (int j = p; j < r; j++) {
    if (A[j] <= x) {
      i = i+1;
      std::swap(A[i], A[j]);
    }
  }
  std::swap(A[i+1], A[r]);
  return i+1;
}
</code>```

答: There is an opinion, apparently shared by Google, that non-const references are bad because they make it non-obvious at the call site that the argument is going to be modified by the call.</p>

Body:
I wrote Quick Sort in CPP,  it is working fine. But when I checked with Google Coding standards it is advising this. I am not able to decipher this message, can you please explain what is wrong with my code.

qs.cpp:8:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:9:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:25:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
qs.cpp:34:  Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A  [runtime/references] [2]
Done processing qs.cpp
Total errors found: 4

#include <iostream>
#include <vector>
#include <iomanip>
#include <utility>

void quickSort(std::vector<int> &A, int p, int r);
int partition(std::vector<int> &A, int p, int r);

int main() {
  std::vector<int> a = {2, 8, 7, 1, 3, 5, 6, 4};
  std::cout << std::setw(10) << "UnSorted Array:\n"
  for (int ele : a) {
    std::cout << ele << std::setw(5);
  }
  std::cout << std::endl << std::setw(10) << "Sorted Array:\n";
  quickSort(a, 0, a.size()-1);
  for (int ele : a) {
    std::cout << ele << std::setw(5);
  }
  std::cout << std::endl;
}

void quickSort(std::vector<int> &A, int p, int r) {
  int q;
  if ( p  < r ) {
    q = partition(A, p, r);
    quickSort(A, p, q-1);
    quickSort(A, q+1, r);
  }
}

int partition(std::vector<int> &A, int p, int r) {
  int x = A[r];
  int i = p-1;
  for (int j = p; j < r; j++) {
    if (A[j] <= x) {
      i = i+1;
      std::swap(A[i], A[j]);
    }
  }
  std::swap(A[i+1], A[r]);
  return i+1;
}


问:
how to make my own map into openstreetmap tiles standard for iphone
i have my own map , now how to cut my map into openstreetmap standrad (their folder strucure)??

so that i can load those tiles into server and can access from there???

kindly suggest

答:
OpenStreetMap consists of 256 pixel by 256 pixel tiles in png format.

There's a set of tiles for each zoom level.  The zoom level is the first level of folders in the directory structure.

The next level of folders is the tile x coordinate, based on the Mercator projection.  The name of the image file is tile y coordinate, followed by .png.

As an example, at zoom level 6, tile x coordinate 10, the 24.png image is California, near San Francisco.  That tile is referred to as the 10, 24 tile at zoom level 6.


问:
performance improvement in elixir when using lists
How can I improve the performance in, for example, a mergesort. In the merge step of the mergesort 2 smaller lists of size n/2 are combined into an list of size n. Because this is happening recursively the next tiem merge is called to merge 2 arrays, these lists have size n and the new list has size 2n. In Elixir lists are immutable I can't modify the values of the initial list, the list that I am trying to sort. Instead it creates new lists at each step of the merge. How can I improve this? Would one use ets?</p>

答:
Elixir has a lot of such performance issues aready solved. Taking for example this problem with merging in mergesort, we aready have :lists.merge that is taking presorted arrays, and returns one sorted array. Complete merge sort could look like this:

```<code>defmodule Sort do
  def merge_sort(input) when length(input) <= 1 do
    input
  end

  def merge_sort(input) do
    splitting_point = length(input) |> div(2)
    { left, right } = Enum.split(input, splitting_point)
    :lists.merge(merge_sort(left), merge_sort(right))
  end
end
</code>```

I wrote Elixir has a lot of things sorted, right? The mergesort is no exception. You can just use Enum.sort that uses mergesort under the hood, and call it a day.

Body:
Elixir has a lot of such performance issues aready solved. Taking for example this problem with merging in mergesort, we aready have :lists.merge that is taking presorted arrays, and returns one sorted array. Complete merge sort could look like this:

defmodule Sort do
  def merge_sort(input) when length(input) <= 1 do
    input
  end

  def merge_sort(input) do
    splitting_point = length(input) |> div(2)
    { left, right } = Enum.split(input, splitting_point)
    :lists.merge(merge_sort(left), merge_sort(right))
  end
end

I wrote Elixir has a lot of things sorted, right? The mergesort is no exception. You can just use Enum.sort that uses mergesort under the hood, and call it a day.


问:
Not ablet to pass Parcelable object as putExtra from IntentService to another Activity
Reivewed all the similar question, and yet no result.
I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project.
Code is given below(Dont have right to publish whole code,and whole code is working except these lines)
CODE:
IntentService:

```<code>    Intent action = new Intent(this, QuizActivity.class);
    intent.putParcelableArrayListExtra("userList",name);
    Random position = new Random();
    int randomPosition =position.nextInt(3);
    intent.putExtra("selectedUser",name.get(randomPosition));
    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

SecondActivity:

```<code>List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");
</code>```

答:
Try below and when you get getParcelableArrayListExtra use same name.you have to implement User class with Parcelable.

```<code>Intent action = new Intent(this, QuizActivity.class);
intent.putParcelableArrayListExtra("userList",name);
Random position = new Random();
int randomPosition =position.nextInt(3);
intent.putExtra("selectedUser",name.get(randomPosition));
action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code>```

In SecondActivity :

```<code>ArrayList<User> userList = getIntent().getParcelableArrayListExtra("userList");
for(User user : post){
    Log.d("user", user.getString());
}
</code>```

Body:
Reivewed all the similar question, and yet no result.
I cannot pass one ojbect that implements parcelable from an intentService to an Activity. The Same code works fine when passing data from an activity to another activity. Even can pass ParcelableArrayListExtra also but not the parcelable Object. Its a requirment to pass the object in my project.
Code is given below(Dont have right to publish whole code,and whole code is working except these lines)
CODE:
IntentService:

    Intent action = new Intent(this, QuizActivity.class);
    intent.putParcelableArrayListExtra("userList",name);
    Random position = new Random();
    int randomPosition =position.nextInt(3);
    intent.putExtra("selectedUser",name.get(randomPosition));
    action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

SecondActivity:

List<User> userList= getIntent().getParcelableArrayListExtra(EXTRA_INSECTS);
Insect selected = getIntent().getExtras().getParcelable("selectedUser");

Body:
Try below and when you get getParcelableArrayListExtra use same name.you have to implement User class with Parcelable.

Intent action = new Intent(this, QuizActivity.class);
intent.putParcelableArrayListExtra("userList",name);
Random position = new Random();
int randomPosition =position.nextInt(3);
intent.putExtra("selectedUser",name.get(randomPosition));
action.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

In SecondActivity :

ArrayList<User> userList = getIntent().getParcelableArrayListExtra("userList");
for(User user : post){
    Log.d("user", user.getString());
}


问:
replace all word occurrence in list with index of items in another list
I have a list -

```<code>A=["hi how are you","have good day","where are you going ","do you like the place"]
</code>```

and another list -

```<code>B=["how","good","where","going","like","place"]
</code>```

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

```<code>["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]
</code>```

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

```<code>for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)
</code>```

答:
What you could do is create a dictionary that maps each word in list B to it's index. Then you only have to iterate through the first list once.

Something like

```<code>B = ["how","yes"]
BDict = {}
index = 0
for x in B:
    Bdict[x] = index
    index += 1

for sentence in A:
     for word in sentence:
         if word in BDict:
              #BDict[word] has the index of the current word in B
         else:
              #Word does not exist in B
</code>```

This should significantly decrease runtime since dictionary has O(1) access time. However, depending on the size of B the dictionary could become quite large

EDIT:
Your code works, the reason it is slow is that the in and index operator have to perform a linear search when you are using a list. So if B gets large this can be a big slow down. A dictionary however has a constant time required to see if a key exists in the dictionary and for retrieving the value. By using the dictionary you would replace 2 O(n) operations with O(1) operations.

Body:
I have a list -

A=["hi how are you","have good day","where are you going ","do you like the place"]

and another list -

B=["how","good","where","going","like","place"]

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)

Body:
What you could do is create a dictionary that maps each word in list B to it's index. Then you only have to iterate through the first list once.

Something like

B = ["how","yes"]
BDict = {}
index = 0
for x in B:
    Bdict[x] = index
    index += 1

for sentence in A:
     for word in sentence:
         if word in BDict:
              #BDict[word] has the index of the current word in B
         else:
              #Word does not exist in B

This should significantly decrease runtime since dictionary has O(1) access time. However, depending on the size of B the dictionary could become quite large

EDIT:
Your code works, the reason it is slow is that the in and index operator have to perform a linear search when you are using a list. So if B gets large this can be a big slow down. A dictionary however has a constant time required to see if a key exists in the dictionary and for retrieving the value. By using the dictionary you would replace 2 O(n) operations with O(1) operations.


问:
Creating a NodeJS based web server to take advantage of HTTP2 on windows platform
I am using windows 2012 server and want to host some static HTML/CSS/JS/image files on a nodejs based web server. I do not want to use IIS as I want to take advantages of HTTP2 & want to push files from server to client. I looked at Using node.js as a simple web server which talks about how to create a node based webserver. Another option is to use  http-server node package.

My question is:

These solutions are over two year old. Do we have a better option available now?

Does any of these two options supports HTTP2?

I would prefer using a existing node module rather then reinventing the wheel.

答:
You could try NGINX, it can support HTTP/2. http://nginx.org/en/docs/windows.html

Run your node applications by using default node, nodemon, pm2...
Then use NGINX as a static web server and you can reverse proxy your node apps.


问:
Exclude subpackages from Spring autowiring?
Is there a simple way to exclude a package / sub-package from autowiring in Spring 3.1?

E.g., if I wanted to include a component scan with a base package of com.example is there a simple way to exclude com.example.ignore?

(Why?  I'd like to exclude some components from my integration tests)

答:
You can also use @SpringBootApplication, which according to Spring documentation does the same functionality as the following three annotations:
@Configuration, @EnableAutoConfiguration @ComponentScan
in one annotation.

```<code>@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}
</code>```

Body:
You can also use @SpringBootApplication, which according to Spring documentation does the same functionality as the following three annotations:
@Configuration, @EnableAutoConfiguration @ComponentScan
in one annotation.

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}


问:
Regular Expression that matchis something or nothing
I am trying to find a value between two HTML tags i.e:

There can either be a word character \w or nothing (not even a space between the >< closing an opening bracket.

So I am trying this /[\w{1,}|]<\/td>/ but it is not working.

This is for php, and yes, I am well aware of some people warning against parsing HTML with regular expressions ;) ...

Any help would be appreciated.

Thank you

答:
```<code>/<td>\w*<\/td>/
</code>```

If you are trying to have matching groups, you need parentheses not brackets:

```<code>/<td>(\w*)<\/td>/
</code>```

To match "nothing", just make the term optional with an *

Body:
/<td>\w*<\/td>/

If you are trying to have matching groups, you need parentheses not brackets:

/<td>(\w*)<\/td>/

To match "nothing", just make the term optional with an *


问:
Unique values in PyTorch tensor
I'm tying to find distinct values in a PyTorch tensor. Is there an efficient analogue of Tensorflow's unique op?</p>

答:
You can convert to a numpy array and make use of numpy's built-in unique function:

def unique(tensor1d):
    t, idx = np.unique(tensor1d.numpy(), return_inverse=True)
    return torch.from_numpy(t), torch.from_numpy(idx)
```
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>t, idx = unique(torch.LongTensor([1, 1, 2, 4, 4, 4, 7, 8, 8]))
# t --> [1, 2, 4, 7, 8]
# idx --> [0, 0, 1, 2, 2, 2, 3, 4, 4]
</code>```

Title: Unique values in PyTorch tensor

Body:
You can convert to a numpy array and make use of numpy's built-in unique function:

def unique(tensor1d):
    t, idx = np.unique(tensor1d.numpy(), return_inverse=True)
    return torch.from_numpy(t), torch.from_numpy(idx)

Example:

t, idx = unique(torch.LongTensor([1, 1, 2, 4, 4, 4, 7, 8, 8]))
# t --> [1, 2, 4, 7, 8]
# idx --> [0, 0, 1, 2, 2, 2, 3, 4, 4]


问:
CloudKit/Firebase: is it possible to send not only push when a record changes but also mail?
In my app I do need synchronization/communication between devices, therefore I need a serverside database. Whenever some special record changes, I need to send a push notification and/or an email.

It's an iOS-only app, so Cloudkit would be fine, but I don't think that it's possible to send an e-mail. Same fore Firebase. Am I overlooking something or are there very similar alternatives which are capable of both, sending push and mail?

答:
Since March 2017 there's an integration between Google Cloud Functions and Firebase. This allows you to run JavaScript code on Google's servers in response to events that happen in Firebase. A node being written to the database is one such event, but there are many more use-cases.

Your use-case seems closest to this sample, which sends a welcome email when a user subscribes to some fictional newsletter.


问:
Preferred value to encode 96 DPI within PNG
PNG files may contain chunks of optional informations. One of these optional information blocks is the physical resolution of the image (chunk-signature pHYs).[1] [2] It contains separate values for horizontal and vertical resolution as pixels per unit, and a unit specifier, that can be 0 for unit unspecified, or 1 for meter ← that's quite confusing, because resolutions are traditionally expressed in DPIs.

The Inch is defined as 25.4 mm in the metric system.
So, if I calculate this correctly, 96 DPIs means 3779.527559... dots per metre. For the pHYs chunk, this has to be rounded. I'd say 3780 is the right value, but I found also 3779 suggested on the web. Images of both kind also coexist on my machine.

The difference may not be important in most cases,

```<code>3779 * 0.054 = 95.9866
3780 * 0.054 = 96.012
</code>```

but I try to avoid tricky layout problems when mixing images of both kind in processes that are DPI-aware like creating PDF files using LaTeX.

[1] Portable Network Graphics (PNG) Specification (Second Edition), section11.3.5.3 pHYs Physical pixel dimensions

[2] PNG Specification: Chunk Specifications, section 4.2.4.2. pHYs Physical pixel dimensions

答:
The relative difference is less that 0.03% (2.65/10000), it's hardly relevant.

Anyway, I'd go with 3780. Not only it's the nearest value, but it would give the correct value if some (sloppy) conversor rounds the value down (instead of rounding to the nearest).

Also, if you google "72.009 DPI PNG" you'll see a similar (non) issue with 72 DPI (example), and it seems that most people rounded the value up (which is also the nearest) 2834.645 -> 2835

Body:
PNG files may contain chunks of optional informations. One of these optional information blocks is the physical resolution of the image (chunk-signature pHYs).[1] [2] It contains separate values for horizontal and vertical resolution as pixels per unit, and a unit specifier, that can be 0 for unit unspecified, or 1 for meter ← that's quite confusing, because resolutions are traditionally expressed in DPIs.

The Inch is defined as 25.4 mm in the metric system.
So, if I calculate this correctly, 96 DPIs means 3779.527559... dots per metre. For the pHYs chunk, this has to be rounded. I'd say 3780 is the right value, but I found also 3779 suggested on the web. Images of both kind also coexist on my machine.

The difference may not be important in most cases,

3779 * 0.054 = 95.9866
3780 * 0.054 = 96.012

but I try to avoid tricky layout problems when mixing images of both kind in processes that are DPI-aware like creating PDF files using LaTeX.

[1] Portable Network Graphics (PNG) Specification (Second Edition), section11.3.5.3 pHYs Physical pixel dimensions

[2] PNG Specification: Chunk Specifications, section 4.2.4.2. pHYs Physical pixel dimensions


问:
How to update session values in joomla?
I have a form.Now I want to save it's value to session, So I have set the session value when the form submitted like below.

```<code>if(JRequest::getVar('from')=='watches'){
    $session = JFactory::getSession();
    $post = JRequest::get('post');
    $session->set('wt_postdata',$post);
}
</code>```

So the value are set to session variable wt_postdata. That's fine. Now I want that if user again visit the same form ,even if the current session not destroyed, user again submitted the same form with the new value ,so the new value will override the old value which stored previously. I want to know that is it possible to update/modify the session value?

If not is there any alternative by that I can temporarily stored the post data for later uses?

Please help.

答:
I understand it is an old post but I thought to share the answer in case someone is looking for it.

In Joomla to Update the Session value you need to set the same variable name with the new value for example:

```<code>$session=JFactory::getSession();
$session->set('var1','x');
$session->set('var1','y');
</code>```

Now, Var 1 is : y

Title: How to update session values in joomla?

Body:
I have a form.Now I want to save it's value to session, So I have set the session value when the form submitted like below.

if(JRequest::getVar('from')=='watches'){
    $session = JFactory::getSession();
    $post = JRequest::get('post');
    $session->set('wt_postdata',$post);
}

So the value are set to session variable wt_postdata. That's fine. Now I want that if user again visit the same form ,even if the current session not destroyed, user again submitted the same form with the new value ,so the new value will override the old value which stored previously. I want to know that is it possible to update/modify the session value?

If not is there any alternative by that I can temporarily stored the post data for later uses?

Please help.

Body:
I understand it is an old post but I thought to share the answer in case someone is looking for it.

In Joomla to Update the Session value you need to set the same variable name with the new value for example:

$session=JFactory::getSession();
$session->set('var1','x');
$session->set('var1','y');

Now, Var 1 is : y


问:
Python bug: null byte in input prompt
I've found that

```<code>input('some\x00 text')
</code>```

will prompt for some instead of some text.

From sources, I've figured out that this function uses C function PyOS_Readline, which ignores everything in prompt after NULL byte.

From PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt):

```<code>fprintf(stderr, "%s", prompt);
</code>```

https://github.com/python/cpython/blob/3.6/Python/bltinmodule.c#L1989
https://github.com/python/cpython/blob/3.6/Parser/myreadline.c#L251

Is this a bug or there is a reason for that?

Issue: http://bugs.python.org/issue30431

答: The function signature pretty much requires a NUL terminated C-string, PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt), so there isn't much than can be done about this without changing the API and breaking interoperability with GNU readline.

Title: Python bug: null byte in input prompt

Body:
I've found that

input('some\x00 text')

will prompt for some instead of some text.

From sources, I've figured out that this function uses C function PyOS_Readline, which ignores everything in prompt after NULL byte.

From PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt):

fprintf(stderr, "%s", prompt);

https://github.com/python/cpython/blob/3.6/Python/bltinmodule.c#L1989
https://github.com/python/cpython/blob/3.6/Parser/myreadline.c#L251

Is this a bug or there is a reason for that?

Issue: http://bugs.python.org/issue30431


问:
DynamoDB query by contains one of the values from array for Node.js
Is it possible to query with an array [apple, orange] on category (also an array. showing below) and get data contains values of either apple or orange?

```<code>row1 | "category": [apple, orange, banana, watermelon]
row2 | "category": [banana, watermelon]
row3 | "category": [orange, watermelon]
</code>```

I expect to get row1, row3 as a result that contains either apple or orange.

答:
You can use CONTAINS function to check for values in the list. However, if you want to check multiple values, you need to use logical OR condition for each value.

CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
  can be a list; however, "b" cannot be a set, a map, or a list.

Example:-

```<code>var params = {
    TableName : 'tableName',
    FilterExpression: "contains (category, :category1) OR contains (category, :category2)",
    ExpressionAttributeValues : {
        ':category1' : "apple",
        ':category2' : "orange"
    }
};
</code>```

Note:-

I assumed you are going to use Scan API. If you are using Query API, please include the KeyConditionExpression.

Body:
Is it possible to query with an array [apple, orange] on category (also an array. showing below) and get data contains values of either apple or orange?

row1 | "category": [apple, orange, banana, watermelon]
row2 | "category": [banana, watermelon]
row3 | "category": [orange, watermelon]

I expect to get row1, row3 as a result that contains either apple or orange.

Body:
You can use CONTAINS function to check for values in the list. However, if you want to check multiple values, you need to use logical OR condition for each value.

CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
  can be a list; however, "b" cannot be a set, a map, or a list.

Example:-

var params = {
    TableName : 'tableName',
    FilterExpression: "contains (category, :category1) OR contains (category, :category2)",
    ExpressionAttributeValues : {
        ':category1' : "apple",
        ':category2' : "orange"
    }
};

Note:-

I assumed you are going to use Scan API. If you are using Query API, please include the KeyConditionExpression.


问:
Saving multiple params in a single array with ajax and rails
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

```<code>$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});
</code>```

This sends params which look something like this

```<code>Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}
</code>```

I'm then updating each affected card's position attribute in my controller action like this:

```<code>def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end
</code>```

The view looks like this:

```<code><ul class="js-CardsContainer js-Sortable">
  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <span><%= card.title %></span>
      <% end %>
    </li>
  <% end %>
</ul>
</code>```

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?

答:
Sorry I was late to respond.  To build on @uzaif's answer you can also set key value pairs inside of the data hash itself like so:

```<code> var data = {$(this).sortable('serialize'), list_id: $(this).attr("data-list-id")}
</code>```

Like @uzaif said, make sure to adjust your controller to accept the list_id in the parameters hash.

Body:
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});

This sends params which look something like this

Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}

I'm then updating each affected card's position attribute in my controller action like this:

def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end

The view looks like this:

  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <%= card.title %>
      <% end %>

  <% end %>

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?

Body:
Sorry I was late to respond.  To build on @uzaif's answer you can also set key value pairs inside of the data hash itself like so:

 var data = {$(this).sortable('serialize'), list_id: $(this).attr("data-list-id")}

Like @uzaif said, make sure to adjust your controller to accept the list_id in the parameters hash.