问:
Unable to identify elements using Appium inspector for ios
I am using Appium 1.6.5
Device : iPod
iOS version : 10.3.3

I am unable to identify elements using Appium inspector.
I click on any objects, the whole frame is getting selected.I am not able to identify each element uniquely.Please refer the below image for actual representation of the issue.

Please help me out with the solution

答:
First of all, why don't you try the latest Appium Desktop that uses Appium server v 1.7.1

However, if there are some reason behind not using the latest appium server, you can go to web alternative: Appium-iOS-Inspector


来源: stackexchange

问:
Make buttons appear after a couple of seconds
I'm making a "landing page" for my website where I put all of my exercises.
I would like to make my buttons "fade in" after a couple a seconds. How do I do this?

This is my button class: .fadeButton

I got this far with jquery to make it animate after couple of seconds: $( ".fadeButton" ).delay( 6000 );

But I don't know how to let the buttons fade in instead of showing it directly

答:
Try with this:
When the page is fully loaded, after 2 seconds you fade in (with jquery .fadeIn()) your button

$(window).on('load', function() {
  $('.fadeButton').delay(2000).fadeIn()
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fadeButton {
  display: none;
}</code>```

<button class='fadeButton'>Button</button>```

ContentLicense: CC BY-SA 3.0

Body:
Try with this:
When the page is fully loaded, after 2 seconds you fade in (with jquery .fadeIn()) your button

$(window).on('load', function() {
  $('.fadeButton').delay(2000).fadeIn()
})

.fadeButton {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='fadeButton'>Button</button>


问:
react native TextInput onBlur get unedfined at android
My react-native version is 0.38.0

```<code><TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />
</code>```

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

```<code>nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}
</code>```

The nativeEvent on Android:

```<code>nativeEvent:{
    target: 1046,
}
</code>```

答:
Try with onEndEditing, like

```<code><TextInput onEndEditing={ (event) => this.handleBlurCheck(event.nativeEvent.text,params) } />
</code>```

You may look into the reported issue here

Body:
My react-native version is 0.38.0

<TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}

The nativeEvent on Android:

nativeEvent:{
    target: 1046,
}

Body:
Try with onEndEditing, like

<TextInput onEndEditing={ (event) => this.handleBlurCheck(event.nativeEvent.text,params) } />

You may look into the reported issue here


问:
How can I fill gaps in a binary image in OpenCV?
I have some thresholded images of hand-drawn figures (circuits) but there are some parts where I need to have gaps closed between two points, as I show in the following image:

Binary image

I tried closing (dilation followed by erosion), but it is not working. It doesn't fill the gaps and makes the resistors and other components unrecognizable. I couldn't find a proper value for the morph size and number of iterations that give me a good result without affecting the rest of the picture. It's important not to affect too much the components.
I can't use hough lines because the gaps are not always in lines.

Result after closing:

Result after closing

```<code>int morph_size1 = 2;
Mat element1 = getStructuringElement(MORPH_RECT, Size(2 * morph_size1 + 1, 2 * morph_size1 + 1), Point(morph_size1, morph_size1));
Mat dst1; // result matrix
for (int i = 1; i<3; i++)
{
    morphologyEx(binary, dst1, CV_MOP_CLOSE, element1, Point(-1, -1), i);

}

imshow("closing ", dst1);
</code>```

Any idea?
Thanks in advance.

答:
My proposal:

find the endpoints of the breaks by means of morphological thinning (select the white pixels having only one white neighbor);

in small neighborhoods around every endpoint, find the closest endpoint, by circling* up to a limit radius;

draw a thick segment between them.

*In this step, it is very important to look for neighbors in different connected component, to avoid linking a piece to itself; so you need blob labelling as well.

In this thinning, there are more breaks than in your original picture because I erased the boxes.

Of course, you draw the filling segments in the original image.

This process cannot be perfect, as sometimes endpoints will be missing, and sometimes unwanted endpoints will be considered.

As a refinement, you can try and estimate the direction at endpoints, and only search is an angular sector.

Body:
I have some thresholded images of hand-drawn figures (circuits) but there are some parts where I need to have gaps closed between two points, as I show in the following image:

Binary image

I tried closing (dilation followed by erosion), but it is not working. It doesn't fill the gaps and makes the resistors and other components unrecognizable. I couldn't find a proper value for the morph size and number of iterations that give me a good result without affecting the rest of the picture. It's important not to affect too much the components.
I can't use hough lines because the gaps are not always in lines.

Result after closing:

Result after closing

int morph_size1 = 2;
Mat element1 = getStructuringElement(MORPH_RECT, Size(2 * morph_size1 + 1, 2 * morph_size1 + 1), Point(morph_size1, morph_size1));
Mat dst1; // result matrix
for (int i = 1; i<3; i++)
{
    morphologyEx(binary, dst1, CV_MOP_CLOSE, element1, Point(-1, -1), i);

}

imshow("closing ", dst1);

Any idea?
Thanks in advance.


问:
How to print the numbers separately (comma-seperated) using Python?
I want to print the following numbers in line-by-line in sorted order using Python.

119, 671, 207, 2484, 6, 941, 2138, 806, 1851, 2509, 1264, 701, 2802, 319, 1603, 98, 347, 525, 1521, 269, 1681, 1885, 1731, 2828, 2543, 2011, 720, 2359, 2248, 22, 1637

My code looks likes

```<code>>>> fo = open("cr.txt", "r")
>>> fo1 = fo.readlines()
>>> fo2 = fo1.split(',')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'
</code>```

When I was trying to split the numbers using split, it shows the error as list object has no attribute split.

答:
As the question is to print the numbers in comma-separated line-by-line and in sorted fashion, the following code is one solution:

```<code>f = open("cr.txt", "r")
l = f.read().split(sep = ",")
list1 = sorted(l, key=lambda e: int(e))
for i in list1:
    print(i)
</code>```

And the output is:

```<code>6
22
98
119
207
269
319
347
525
671
701
720
......
</code>```

The code prints the numbers line-by-line in sorted manner and without commas. I have used the lambda expression here for the sorting purpose, which can also otherwise achieved by the sort() function.

Body:
I want to print the following numbers in line-by-line in sorted order using Python.

119, 671, 207, 2484, 6, 941, 2138, 806, 1851, 2509, 1264, 701, 2802, 319, 1603, 98, 347, 525, 1521, 269, 1681, 1885, 1731, 2828, 2543, 2011, 720, 2359, 2248, 22, 1637

My code looks likes

>>> fo = open("cr.txt", "r")
>>> fo1 = fo.readlines()
>>> fo2 = fo1.split(',')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'

When I was trying to split the numbers using split, it shows the error as list object has no attribute split.

Body:
As the question is to print the numbers in comma-separated line-by-line and in sorted fashion, the following code is one solution:

f = open("cr.txt", "r")
l = f.read().split(sep = ",")
list1 = sorted(l, key=lambda e: int(e))
for i in list1:
    print(i)

And the output is:

6
22
98
119
207
269
319
347
525
671
701
720
......

The code prints the numbers line-by-line in sorted manner and without commas. I have used the lambda expression here for the sorting purpose, which can also otherwise achieved by the sort() function.


问:
How to read rtf attached to the document to RichTextBox?
I attached rtf document to my app, and I want its content to be display in RichTextBox, I know how to do that with rtf file from disk, but I can't access file in project.</p>

答: If you added the rtf file as "Embedded Resource" in your project use GetManifestResourceStream etc functions on the executing assembly. Check out a sample here : http://lamahashim.blogspot.com/2009/06/c-reading-embedded-files-at-runtime.html</p>

ContentLicense: CC BY-SA 2.5


答:
In your css file say:

```<code>.fadeButton {
    opacity: 0;
    transition: opacity 0.5s;
}
</code>```

In your onload section of javascript or just somewhere on page say:

```<code>setTimeout(function(){
    $('.fadeButton').css({'opacity':'1'})
}, 2000);
</code>```

There is no need to load another js library and make your website slower

Using jQuery animations takes roughly 10-100 times more processing power than css transitions, this can make your page load jumpy

When you start from "display: none" , the button won't take up any space and there will be jump on design - that's why I prefer animating opacity

Remember, that when loading a page (or starting from "display: none") all animations start from completed state

Title: Make buttons appear after a couple of seconds

Body:
I'm making a "landing page" for my website where I put all of my exercises.
I would like to make my buttons "fade in" after a couple a seconds. How do I do this?

This is my button class: .fadeButton

I got this far with jquery to make it animate after couple of seconds: $( ".fadeButton" ).delay( 6000 );

But I don't know how to let the buttons fade in instead of showing it directly

Body:
In your css file say:

.fadeButton {
    opacity: 0;
    transition: opacity 0.5s;
}

In your onload section of javascript or just somewhere on page say:

setTimeout(function(){
    $('.fadeButton').css({'opacity':'1'})
}, 2000);

There is no need to load another js library and make your website slower

Using jQuery animations takes roughly 10-100 times more processing power than css transitions, this can make your page load jumpy

When you start from "display: none" , the button won't take up any space and there will be jump on design - that's why I prefer animating opacity

Remember, that when loading a page (or starting from "display: none") all animations start from completed state


问:
list remove function on class instance in a list not working properly
here is the code, I'm confused:

```<code>class Button():
    def __init__(self, text):
        self.text = text

bt1 = Button('123')
bt2 = Button('3r5')
bt3 = Button('123')
bt4 = Button('1fe')
bt5 = Button('123')

bts = []

bts.extend((bt1,bt2,bt3,bt4,bt5))
bts.extend((bt1,bt2,bt3,bt4,bt5))

for bt in bts:
    if bt.text == '123':
        bts.remove(bt)

for bt in bts:
    print(bt.text)
</code>```

And here is the results:

```<code>3r5
1fe
123
3r5
1fe
</code>```

My question is, why there is one element with text '123' not been removed?

答:
You're deleting the element in the list while you iterate over it. That means that the first time through the loop, i == 1, so 123 is removed from the list. Then the for loop goes to the second item in the list, which is not 3r5, but 123! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 5. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value of i:

```<code>["123", "3r5", "123", "123", "1fe"]
   ^
That's the state of the list initially; then 1 is removed and the loop goes to the second item in the list:

["3r5", "123", "123", "1fe"]
          ^
[ "3r5", "123", "1fe"]
                  ^
so remaining elements after loop ends [ "3r5", "123"]
</code>```

There's no good way to alter a list's length while iterating over it.

Body:
here is the code, I'm confused:

class Button():
    def __init__(self, text):
        self.text = text

bt1 = Button('123')
bt2 = Button('3r5')
bt3 = Button('123')
bt4 = Button('1fe')
bt5 = Button('123')

bts = []

bts.extend((bt1,bt2,bt3,bt4,bt5))
bts.extend((bt1,bt2,bt3,bt4,bt5))

for bt in bts:
    if bt.text == '123':
        bts.remove(bt)

for bt in bts:
    print(bt.text)

And here is the results:

3r5
1fe
123
3r5
1fe

My question is, why there is one element with text '123' not been removed?

Body:
You're deleting the element in the list while you iterate over it. That means that the first time through the loop, i == 1, so 123 is removed from the list. Then the for loop goes to the second item in the list, which is not 3r5, but 123! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 5. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value of i:

["123", "3r5", "123", "123", "1fe"]
   ^
That's the state of the list initially; then 1 is removed and the loop goes to the second item in the list:

["3r5", "123", "123", "1fe"]
          ^
[ "3r5", "123", "1fe"]
                  ^
so remaining elements after loop ends [ "3r5", "123"]

There's no good way to alter a list's length while iterating over it.


问:
Add spring cloud sleuth to Spring application with Jetty server
I am trying to integrate spring cloud sleuth with an existing spring application which uses jetty server.

I have added

```<code><dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth</artifactId>
            <version>1.2.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

and

```<code><dependencies>
   <dependency>spring-cloud-starter-sleuth</dependency>
</dependencies>
</code>```

How should I pass the logger properties, logging pattern while starting the app? Right now, it does not read the properties file under /resources folder and no traceId or spanId is generated.

Most of the examples have used Spring Boot. Need help to figure out how to integrate this with a Spring application with jetty server.

答: For non Spring Boot applications please use https://github.com/openzipkin/brave . Spring Cloud Sleuth is Boot based.</p>

Body:
I am trying to integrate spring cloud sleuth with an existing spring application which uses jetty server.

I have added

<dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth</artifactId>
            <version>1.2.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

and

<dependencies>
   <dependency>spring-cloud-starter-sleuth</dependency>
</dependencies>

How should I pass the logger properties, logging pattern while starting the app? Right now, it does not read the properties file under /resources folder and no traceId or spanId is generated.

Most of the examples have used Spring Boot. Need help to figure out how to integrate this with a Spring application with jetty server.


问:
How to concatenate two dataframes based on the particular columns?
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

```<code>   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2
</code>```

It's the expected result:

```<code>   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2
</code>```

I can't find a efficient way to concatenate them!!

答:
if output order doesn't matter,

a,b,c are same for each row,

X & Y are distinct for each row.

ls1 = [set(['H','A',8,1]), set(['H','A',8,4])]

      ls1 = set().union(*ls1)

      print ls1

      set(['A', 1, 4, 8, 'H'])

Body:
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2

It's the expected result:

   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2

I can't find a efficient way to concatenate them!!


问:
What does the nuget package MicroBuild.Core do?
In a Visual Studio 2017 project, I came across a nuget package called MicroBuild.Core.  Its nuget page has very little information (see below), and there is currently no content about it here on SO.  I know the pagkage is related to software builds, but what exactly does it do?

答:
What does the nuget package MicroBuild.Core do?

This package is used to load and execute other MicroBuild plugins during the build, which allow for the ability to override the plugin directory via the MicroBuildOverridePluginDirectory property, etc.

For more detail info, you can manual download this package, rename it with .zip, then unzip it, you will find three files in the packages:

Open file "MicroBuild.Plugin.props", there are a lot of detailed comments:

Hope this helps.


问:
How to change the size of a HTML button?
So I have this line of code put into Sublime Text:

```<code><input id="MM" type="button" style="width: 150px" >
</code>```

But how  do I change the length?

答:
If you want to increase the height, give padding propert to input label.
Please check here

<input type="button" value="submit" style="width:150px; padding-top:5px;padding-bottom:5px" />*

Body:
So I have this line of code put into Sublime Text:

<input id="MM" type="button" style="width: 150px" >

But how  do I change the length?


问:
Strategies for Angular Performance in Large Table?
I'm working on a project that's using AngularJS v1.5.11 to display a large table of data -- it is a continuous build system which displays a table of rows for each change that comes in to source control.  The columns are some data that's "static" like the information about the change, and some dynamic columns which show the current state of various automated builders/testers for that change.  The page polls several different REST endpoints from a build server, and updates the page with current results from many different build machines.

I have made quite a few improvements to the page to add additional information, now I'm running in to performance issues due to too many watchers.  Full-page digests happen frequently and the number of watchers is in the thousands, causing some interactive operations to have several seconds of delay.

I use the :: ("one-time-binding") syntax already where applicable, but the heaviest use of watchers is in the columns which show the build/test results and those need to update as new data comes in.  One-time-binding doesn't make sense in those cases.

I have already come up with a solution which involves disabling the watchers on old rows, since after a certain point we can guess that a particular row is not going to go get updated anymore (once all of the builders have moved on to processing a more recent change).   I'm using something similar to this page, having a suspendable directive which can remove the watchers from a row upon an event.

There are a couple problems I'm having with the approach of suspending watchers

Sometimes those old rows do get new data contrary to our heuristic which deactivates the row, e.g. someone goes back and manually re-runs a build on an old change.  Then that row fails to display the up-to-date data

There are some interactive "ng-click" features that fail to work on rows that have been deactivated.

The other issue that I have is that currently the table is restricted to a limited number of rows, but I would like for it to automatically add rows when the user scrolls down ("infinite scrolling") so that they can view old data.  This is going to dramatically increase the number of rows and thereby increase my performance issues with watchers.

My Questions:

Are there any other performance strategies that would help other than what I'm doing (one-time-binding and disabling watchers)?

How do others approach problems like this in Angular, or is Angular just not really well suited to this kind of a high-density information display?  (A previous implementation of a similar page using jQuery runs much faster because once it adds a row, it pretty much leaves it alone, it just sits there in the DOM not incurring any extra cost each time new data comes in)

I realize I'm on an old version of Angular, and that Angular2 is supposed to be better for performance.  What are the specific features in newer versions that might help with these issues?

答:
It's hard to give directed answers without code or examples but here's some suggestions that may help you out

Run NgStats and look at your watcher count and how fast your digest loops take. This will help focus your efforts.

One time binding is a good idea.  If you are still seeing performance problems with this I'd look at your ng-repeat code.

Improve ng-repeat by using track by

Ensure you never bind to a function i.e. ng-repeat="$ctrl.mySortedData()" or
{{$ctrl.getTitle()}}
 as it makes digest cycles slower.

Anecdotally some developers see ng-bind perform better than handle bars

If you are not already, move to one way binding with Angular components, it'll help

It's a bit of a brute force method but I find it helps sometimes: Comment out sections of your page to see what specific sections cause the most slow down (refer to #1). Once you have identified these regions you can focus your time there.

Reducing the number of watchers is key to performance. It can be as simple as using a ng-switch rather than 3 ng-ifs.

Not Angular related, but Tables themselves are slow to render by the browser, if possible consider moving to a div + css styled display.

Personally I am able to render thousands of on screen elements without any noticeable drop in performance using the methods above.  I have never had to suspend watchers and sounds like something that is difficult to maintain. I personally wouldn't recommend that.

Body:
It's hard to give directed answers without code or examples but here's some suggestions that may help you out

Run NgStats and look at your watcher count and how fast your digest loops take. This will help focus your efforts.

One time binding is a good idea.  If you are still seeing performance problems with this I'd look at your ng-repeat code.

Improve ng-repeat by using track by

Ensure you never bind to a function i.e. ng-repeat="$ctrl.mySortedData()" or <div>{{$ctrl.getTitle()}}</div> as it makes digest cycles slower.

Anecdotally some developers see ng-bind perform better than handle bars

If you are not already, move to one way binding with Angular components, it'll help

It's a bit of a brute force method but I find it helps sometimes: Comment out sections of your page to see what specific sections cause the most slow down (refer to #1). Once you have identified these regions you can focus your time there.

Reducing the number of watchers is key to performance. It can be as simple as using a ng-switch rather than 3 ng-ifs.

Not Angular related, but Tables themselves are slow to render by the browser, if possible consider moving to a div + css styled display.

Personally I am able to render thousands of on screen elements without any noticeable drop in performance using the methods above.  I have never had to suspend watchers and sounds like something that is difficult to maintain. I personally wouldn't recommend that.


问:
Using nunjucks with htmlWebpackPlugin using dynamic vars in the template
I'm searching a way of using Nunjucks with the htmlWebpackPlugin to generate some html files on webpack compiling.

What I achieved so far

I managed to actually generate HTML from nunjucks template files through the nunjucks-html-loader but looking a bit closer to the code of said loader, the render method is called without sending vars to the templates.

So, for now with the following plugin config, I generate HTML without dynamically inserted vars

```<code>new HtmlWebpackPlugin({
  filename: path.join(__dirname, '/' + page.filename),
  template: 'nunjucks-html-loader!assets/templates/' + page.name + '.njk'
})
</code>```

What I tried

For a testing purpose, I tried some changes on the node_module itself (I know, I know...) and changed

html = template.render(nunjucksContext);

into

html = template.render(nunjucksContext, { globals: global.globals });

Trying to define global.globals in my webpack.config.js file but this crashes with the following error

ERROR in   Error: Child compilation failed:
  Module build failed: TypeError: parentFrame.push is not a function

which is beyond my comprehension.

What I want

Is to use an extendable template engine like nunjucks which allows me to structure my templates like the following

```<code><html>
<!-- layout structure inherited from every template -->
</html>
</code>```

Every page I make extends the layout and only overrides some blocks

What I try to avoid

Partials like for exemple

header file :

```<code><html>
<!-- header layout -->
</code>```

footer file

```<code><!-- footer layout -->
</html>
</code>```

Every page I make includes partials

So my question is : Is it even possible tu use a template engine supporting inheritance like nunjucks with the htmlWebpackPlugin or is it mandatory to use another one like ejs for exemple and chunking the layout into partials which I do not like?

答:
Alright, so I found a workaround here with the nunjucks-isomorphic-loader which seems not super supported but still. It works for now !

Here's my webPack config

```<code>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const DEV_ENV = process.env.NODE_ENV === 'dev'

const wpConfig = {
  entry: './assets/js/app.js',

  output: {
    path: path.resolve('./dist/js'),
    filename: 'bundle.js'
  },

  module: {
    rules: [
      // Javascript
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader'
        }
      },

      // Nunjucks - HTML
      {
        test: /\.njk$/,
        use: [
          {
            loader: 'nunjucks-isomorphic-loader',
            query: {
              root: [path.resolve(__dirname, 'assets/templates')]
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      DEV_ENV: DEV_ENV
    }),

    new HtmlWebpackPlugin({
      myOptions: { foo: 'bar' },
      filename: path.join(__dirname, '/' + page.filename),
      template: 'assets/templates/index.njk'
    })
  ]
}

module.exports = wpConfig
</code>```

having the following templates

_layout.njk

```<code>{% set vars = htmlWebpackPlugin.options.myOptions %}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ vars.foo }}</title>
  </head>
  <body>
    <header>
    {% block header %}
      <h1 class="header-logo">
        <a href="#">{{ vars.foo }}</a><!-- Outputs bar -->
      </h1>
    {% endblock %}
    </header>

    {% block content %}

    {% endblock %}
  </body>
</html>
</code>```

index.njk

```<code>{% extends "_layout.njk" %}

{% block content %}
here's the content of my `foo` var: {{ vars.foo }}
{% endblock %}
</code>```

Body:
I'm searching a way of using Nunjucks with the htmlWebpackPlugin to generate some html files on webpack compiling.

What I achieved so far

I managed to actually generate HTML from nunjucks template files through the nunjucks-html-loader but looking a bit closer to the code of said loader, the render method is called without sending vars to the templates.

So, for now with the following plugin config, I generate HTML without dynamically inserted vars

new HtmlWebpackPlugin({
  filename: path.join(__dirname, '/' + page.filename),
  template: 'nunjucks-html-loader!assets/templates/' + page.name + '.njk'
})

What I tried

For a testing purpose, I tried some changes on the node_module itself (I know, I know...) and changed

html = template.render(nunjucksContext);

into

html = template.render(nunjucksContext, { globals: global.globals });

Trying to define global.globals in my webpack.config.js file but this crashes with the following error

ERROR in   Error: Child compilation failed:
  Module build failed: TypeError: parentFrame.push is not a function

which is beyond my comprehension.

What I want

Is to use an extendable template engine like nunjucks which allows me to structure my templates like the following

Every page I make extends the layout and only overrides some blocks

What I try to avoid

Partials like for exemple

header file :

footer file

Every page I make includes partials

So my question is : Is it even possible tu use a template engine supporting inheritance like nunjucks with the htmlWebpackPlugin or is it mandatory to use another one like ejs for exemple and chunking the layout into partials which I do not like?

Body:
Alright, so I found a workaround here with the nunjucks-isomorphic-loader which seems not super supported but still. It works for now !

Here's my webPack config

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const DEV_ENV = process.env.NODE_ENV === 'dev'

const wpConfig = {
  entry: './assets/js/app.js',

  output: {
    path: path.resolve('./dist/js'),
    filename: 'bundle.js'
  },

  module: {
    rules: [
      // Javascript
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader'
        }
      },

      // Nunjucks - HTML
      {
        test: /\.njk$/,
        use: [
          {
            loader: 'nunjucks-isomorphic-loader',
            query: {
              root: [path.resolve(__dirname, 'assets/templates')]
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      DEV_ENV: DEV_ENV
    }),

    new HtmlWebpackPlugin({
      myOptions: { foo: 'bar' },
      filename: path.join(__dirname, '/' + page.filename),
      template: 'assets/templates/index.njk'
    })
  ]
}

module.exports = wpConfig

having the following templates

_layout.njk

{% set vars = htmlWebpackPlugin.options.myOptions %}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ vars.foo }}</title>
  </head>
  <body>
    <header>
    {% block header %}
      <h1 class="header-logo">
        <a href="#">{{ vars.foo }}</a><!-- Outputs bar -->
      </h1>
    {% endblock %}
    </header>

    {% block content %}

    {% endblock %}
  </body>
</html>

index.njk

{% extends "_layout.njk" %}

{% block content %}
here's the content of my `foo` var: {{ vars.foo }}
{% endblock %}


答:
Try this.

$("button").click(function() {
  $("#div1").fadeIn();
  $("#div2").fadeIn("slow");
  $("#div3").fadeIn(3000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Demonstrate fadeIn() with different parameters.</p><button>Click to fade in boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div></code>```

Body:
Try this.

$("button").click(function() {
  $("#div1").fadeIn();
  $("#div2").fadeIn("slow");
  $("#div3").fadeIn(3000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Demonstrate fadeIn() with different parameters.</p><button>Click to fade in boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>


问:
Call to undefined method DOMNodeList::getElementsByTagName()
I would like to parse an html table using PHP's DOMDocument, so I use a foreach for every table:   foreach($_POST['comparison'] as $value) {   } in which  i nested the code below. So from the comparison table i want to take each row ($value), the value contains an html table (
 ...
). Here is the table i want to parse:

```<code><table>
    <tbody>
        <tr>
            <td >.....</td>
            <td>....</td>
        </tr>
        <tr>
            <td>....</td>
            <td>.....</td>
        </tr>
    </tbody>
</table>
</code>```

The second code goes like this, i create a foreach for the rows, then an index ($i) for every row and inside every row another foreach with a new index ($j) for the columns, so the purpose is to echo each column of every row like this (first column-first row, second column-first row, first column-second row, second column-second row...

```<code>          foreach($_POST['comparison'] as $value) {

    echo  "<div id='primary' class='content-area'>";

               var_dump($value);  // check the type in the variable value
      $dom = new DOMDocument;

    $dom->loadHTML($value);
    $dom->preserveWhiteSpace = false;

    $tables = $dom->getElementsByTagName('table');

     foreach ($tables->getElementsByTagName('tr') as $element1) {
            for ($i = 0; $i < $element1->length; $i++) {

             echo   $element1->item($i)->nodeValue . "\n";

               foreach ($element1->getElementsByTagName('td') as $element2) {

                  for ($j = 0; $j < $element2->length; $j++) {

               echo $element2->item($j)->nodeValue . "\n";  }

           /* $value_spec[] = $element2->nodeValue + "<br>";  */
        }
     }
  }

    echo " </div><!-- content-area -->";

 }

}
</code>```

I followed the instructions for the error "Call to undefined method DOMNodeList::getElementsByTagName()", which is to add item() to have access to every cell of the table but the error remains. I would appreciate if someone could help.

答:
```<code>    $tables = $dom->getElementsByTagName ('table');

// At this point, if you are sure that you want the first table found,  add
$table = $tables->item(0);
// Below working code, I don't undersatand what you do with that loops
     foreach ($table->getElementsByTagName ('tr') as $tr) {
          foreach ($tr->getElementsByTagName ('td') as $td) {
                 echo $td->nodeValue . "\n";
         }
     }
</code>```

demo

Body:
I would like to parse an html table using PHP's DOMDocument, so I use a foreach for every table:   foreach($_POST['comparison'] as $value) {   } in which  i nested the code below. So from the comparison table i want to take each row ($value), the value contains an html table (
 ...
). Here is the table i want to parse:

            .....
            ....

            ....
            .....

The second code goes like this, i create a foreach for the rows, then an index ($i) for every row and inside every row another foreach with a new index ($j) for the columns, so the purpose is to echo each column of every row like this (first column-first row, second column-first row, first column-second row, second column-second row...

          foreach($_POST['comparison'] as $value) {

    echo  "
";

               var_dump($value);  // check the type in the variable value
      $dom = new DOMDocument;

    $dom->loadHTML($value);
    $dom->preserveWhiteSpace = false;

    $tables = $dom->getElementsByTagName('table');

     foreach ($tables->getElementsByTagName('tr') as $element1) {
            for ($i = 0; $i < $element1->length; $i++) {

             echo   $element1->item($i)->nodeValue . "\n";

               foreach ($element1->getElementsByTagName('td') as $element2) {

                  for ($j = 0; $j < $element2->length; $j++) {

               echo $element2->item($j)->nodeValue . "\n";  }

           /* $value_spec[] = $element2->nodeValue + "
";  */
        }
     }
  }

    echo "
";

 }

}

I followed the instructions for the error "Call to undefined method DOMNodeList::getElementsByTagName()", which is to add item() to have access to every cell of the table but the error remains. I would appreciate if someone could help.

Body:
    $tables = $dom->getElementsByTagName ('table');

// At this point, if you are sure that you want the first table found,  add
$table = $tables->item(0);
// Below working code, I don't undersatand what you do with that loops
     foreach ($table->getElementsByTagName ('tr') as $tr) {
          foreach ($tr->getElementsByTagName ('td') as $td) {
                 echo $td->nodeValue . "\n";
         }
     }

demo


问:
How to GROUP BY eloquent in <select>
I want to have unique mounths in SELECT. I find out i have to use GROUP BY. But it doesnt work this way:

```<code> @foreach($months as $month)
       <option value="{{ $month->id }}">{{ Carbon\Carbon::parse($month
->date)
->format(' F ')
->groupBy('date') }}</option>
 @endforeach
</code>```

How to use groupBy in this way? Because it looks like this right now without GROUP BY:

My Laravel Controller:

```<code>public function index()
{
    $users = User::all(['name', 'id']);
    $months = RouteInfo::all(['date', 'id']);

    return view('admin.index', compact('users', $users, 'months', $months));
}
</code>```

Thank you for your help

答:
You could do something like this, within your controller.

```<code>$months = RouteInfo::all(['date', 'id'])->groupBy(function($month) {
    return Carbon::parse($month->date)->format('F');
});
</code>```

Then within your view

```<code>@foreach($months as $month)
    <option>{{ $month }}</option>
@endforeach
</code>```

This is untested, please let me know if it works for you or if there are any errors.

Title: How to GROUP BY eloquent in <select>

Body:
I want to have unique mounths in SELECT. I find out i have to use GROUP BY. But it doesnt work this way:

 @foreach($months as $month)
       <option value="{{ $month->id }}">{{ Carbon\Carbon::parse($month
->date)
->format(' F ')
->groupBy('date') }}</option>
 @endforeach

How to use groupBy in this way? Because it looks like this right now without GROUP BY:

My Laravel Controller:

public function index()
{
    $users = User::all(['name', 'id']);
    $months = RouteInfo::all(['date', 'id']);

    return view('admin.index', compact('users', $users, 'months', $months));
}

Thank you for your help

Body:
You could do something like this, within your controller.

$months = RouteInfo::all(['date', 'id'])->groupBy(function($month) {
    return Carbon::parse($month->date)->format('F');
});

Then within your view

@foreach($months as $month)
    <option>{{ $month }}</option>
@endforeach

This is untested, please let me know if it works for you or if there are any errors.


问:
Kivy : Run .py file onclick on image

demo.Kv

```<code>AsyncImage:
            canvas:
                Rectangle:
                    texture: CoreImage("add.jpg").texture
                    size: self.width, self.height
                    size: 30, 30
                    pos: self.x - 1, self.y
                    #on_release: os.system("python test.py")
</code>```

Can anyone help me?

 1. This code is in my .kv file. How to run test.py file onclick on add.jpg image.

Any advise or guidance would be greatly appreciated..!!

答:
so somewhere relevant in your main.py probably the root(class) file write a function that will run the test.py like this

```<code>def run_test():
    os.system('python file.py')
</code>```

and do import the os module. Now replace this with what you have in your kv file

```<code>on_release: root.run_test()
</code>```

Title: Kivy : Run .py file onclick on image

Body:
demo.Kv

AsyncImage:
            canvas:
                Rectangle:
                    texture: CoreImage("add.jpg").texture
                    size: self.width, self.height
                    size: 30, 30
                    pos: self.x - 1, self.y
                    #on_release: os.system("python test.py")

Can anyone help me?

 1. This code is in my .kv file. How to run test.py file onclick on add.jpg image.

Any advise or guidance would be greatly appreciated..!!

Body:
so somewhere relevant in your main.py probably the root(class) file write a function that will run the test.py like this

def run_test():
    os.system('python file.py')

and do import the os module. Now replace this with what you have in your kv file

on_release: root.run_test()


问:
Change Validation Summary Text in MVC for a password validation
How do I change the default message on the validation summary when a password does not meet the requirements. The current message the appears is

"Passwords must have at least one digit ('0'-'9'). Passwords must have at least one uppercase ('A'-'Z')."

I want to change that text to something else.

答:
You can also use DataAnnotations

In your example, you can use :

```<code>// ~YourModelFile.cs

[RegularExpression(@"^[A-Z0-9]{6,}$", ErrorMessage = "Password must be at least 6 characters long")]
public string Password { get; set; }
</code>```

Interesting point is the ErrorMessage may be placed in a Resources files, so you can display it in multiple languages.

Plus, you do not have to write a custom AddError method anymore.

Body:
You can also use DataAnnotations

In your example, you can use :

// ~YourModelFile.cs

[RegularExpression(@"^[A-Z0-9]{6,}$", ErrorMessage = "Password must be at least 6 characters long")]
public string Password { get; set; }

Interesting point is the ErrorMessage may be placed in a Resources files, so you can display it in multiple languages.

Plus, you do not have to write a custom AddError method anymore.


问:
angularJs : ng-template inside ng-include
I have lot of small template, so i put them in a single html file.

smallTemlates.html

```<code><script type="text/ng-template" id="template1.html">
...
</script>
<script type="text/ng-template" id="template2.html">
...
</script>
</code>```

then i include smallTemlates.html inside index.html.

index.html

```<code>  <body  ng-app="myapp" id="my-app">
      <div ng-include="'pathTo/smallTemlates.html'"></div>
</body>
</code>```

then i tried to access these templates inside my controller/service using $templateRequest, but it is throwing 404 error.

```<code>  $templateRequest(component.popoverTemplateUrl).then(function(html) {
     var template = html // 404 error
  });
</code>```

but if i added these template direclty into index.html like below it works just fine.

```<code> <body  ng-app="myapp" id="my-app">
<script type="text/ng-template" id="template1.html">
...
</script>
<script type="text/ng-template" id="template2.html">
...
</script>
</body>
</code>```

答:
You should use $templateCache instead of $templateRequest, because you don't need to make another request for template. ng-include already does this by default.

You have to wait for next digest to get the content for template:

```<code>var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,$templateCache,$timeout) {

  $timeout(function(){
    var template = $templateCache.get('smallTemlates.html').then(function(html){
        console.log("smallTemlates");
        console.log(html.data);
       $timeout(function(){
           var template1 = $templateCache.get('template1.html');
             console.log("template1");
             console.log(template1);
       });
    });

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

Html:

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
 <link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

   <div ng-include="'smallTemlates.html'"></div>
</div>

</body>
</code>```

smallTemplates.html

```<code><script type="text/ng-template" id="template1.html">
template1zzasdfasdf
</script>
<script type="text/ng-template" id="template2.html">
template2
</script>
</code>```

Plunker Link here (check console for the results)

Body:
I have lot of small template, so i put them in a single html file.

smallTemlates.html

then i include smallTemlates.html inside index.html.

index.html

then i tried to access these templates inside my controller/service using $templateRequest, but it is throwing 404 error.

  $templateRequest(component.popoverTemplateUrl).then(function(html) {
     var template = html // 404 error
  });

but if i added these template direclty into index.html like below it works just fine.

Body:
You should use $templateCache instead of $templateRequest, because you don't need to make another request for template. ng-include already does this by default.

You have to wait for next digest to get the content for template:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,$templateCache,$timeout) {

  $timeout(function(){
    var template = $templateCache.get('smallTemlates.html').then(function(html){
        console.log("smallTemlates");
        console.log(html.data);
       $timeout(function(){
           var template1 = $templateCache.get('template1.html');
             console.log("template1");
             console.log(template1);
       });
    });

  });
});

Html:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
 <link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

   <div ng-include="'smallTemlates.html'"></div>
</div>

</body>

smallTemplates.html

<script type="text/ng-template" id="template1.html">
template1zzasdfasdf
</script>
<script type="text/ng-template" id="template2.html">
template2
</script>

Plunker Link here (check console for the results)


问:
Excel cell default measure unit
What is the default measurement unit of Excel cell size? Is it Point or Pixel or Millimeter ?

By default, excel cell Row height is 15, what is the meaning of this value? Is it 15 Pixels or 15 Points

By default, excel cell Column Width is 8.43, what is the meaning of this value? Is it 8.43 Pixels or 8.43 Points

If both row and column units are same, then Row height should be smaller than to column width. But the measurement is reverse, row height shows bigger number than column width. In Cell appearance also, row is small than column width.

I need to create box with Height 90 mm (millimeter) and  Width 195 mm (millimeter). Please let me know what are values to be put in Row and Column textboxes.

Thanks in advance.

答:
The default units for column and row are indeed different when accessed through the GUI.

The displayed column width in the GUI refers to the Range.ColumnWidth property, where One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used (source). This means as you change the worksheet style, your column width may change too.

The height, however, displays a normal height in points.

In VBA, you can both get both this font-related unit, and the normal point unit for the width. For the height, you can only get the value in points:

```<code>Debug.Print Range("A1").ColumnWidth '8.43 characters wide by default
Debug.Print Range("A1").Width '48 points wide by default
Debug.Print Range("A1").Height '12.75 points high by default
</code>```

Of course, you can calculate a conversion factor between character width and points: Range("A1").Width / Range("A1").ColumnWidth = 5.69 when using Arial, 10 pt. This means that if you want to have a size of 195mm by 90mm, you need to enter 97.0777 as column width, and 255.118 as column height if you're using Arial, 10 pt as normal style.

Title: Excel cell default measure unit

Body:
The default units for column and row are indeed different when accessed through the GUI.

The displayed column width in the GUI refers to the Range.ColumnWidth property, where One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used (source). This means as you change the worksheet style, your column width may change too.

The height, however, displays a normal height in points.

In VBA, you can both get both this font-related unit, and the normal point unit for the width. For the height, you can only get the value in points:

Debug.Print Range("A1").ColumnWidth '8.43 characters wide by default
Debug.Print Range("A1").Width '48 points wide by default
Debug.Print Range("A1").Height '12.75 points high by default

Of course, you can calculate a conversion factor between character width and points: Range("A1").Width / Range("A1").ColumnWidth = 5.69 when using Arial, 10 pt. This means that if you want to have a size of 195mm by 90mm, you need to enter 97.0777 as column width, and 255.118 as column height if you're using Arial, 10 pt as normal style.


问:
NoClassDefFoundError occurs even if dependency was added to pom.xml
So I would like to build my maven project with

mvn clean package

But once I try to run my built jar file in target folder like

java -jar app-1.0-SNAPSHOT.jar

It shows error:

Error: A JNI error has occurred, please check your installation and
  try again Exception in thread "main" java.lang.NoClassDefFoundError:
  net/sourceforge/jdatepicker/DateModel     at
  java.lang.Class.getDeclaredMethods0(Native Method)    at
  java.lang.Class.privateGetDeclaredMethods(Class.java:2701)    at
  java.lang.Class.privateGetMethodRecursive(Class.java:3048)    at
  java.lang.Class.getMethod0(Class.java:3018)   at
  java.lang.Class.getMethod(Class.java:1784)    at
  sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at
  sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
  Caused by: java.lang.ClassNotFoundException:
  net.sourceforge.jdatepicker.DateModel     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 7 more

Pom DataPicker dependency:

```<code><!-- https://mvnrepository.com/artifact/net.sourceforge.jdatepicker/jdatepicker -->
        <dependency>
            <groupId>net.sourceforge.jdatepicker</groupId>
            <artifactId>jdatepicker</artifactId>
            <version>1.3.2</version>
        </dependency>
</code>```

Why even though dependency was added, exception occurs?

答:
try adding maven plugin so that it copies all your dependencies with the jar file and it does not have to look any further. Do this by adding:</p>

```<code><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.4</version>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>package</phase>
                <goals><goal>copy-dependencies</goal></goals>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
So I would like to build my maven project with

mvn clean package

But once I try to run my built jar file in target folder like

java -jar app-1.0-SNAPSHOT.jar

It shows error:

Error: A JNI error has occurred, please check your installation and
  try again Exception in thread "main" java.lang.NoClassDefFoundError:
  net/sourceforge/jdatepicker/DateModel     at
  java.lang.Class.getDeclaredMethods0(Native Method)    at
  java.lang.Class.privateGetDeclaredMethods(Class.java:2701)    at
  java.lang.Class.privateGetMethodRecursive(Class.java:3048)    at
  java.lang.Class.getMethod0(Class.java:3018)   at
  java.lang.Class.getMethod(Class.java:1784)    at
  sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at
  sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
  Caused by: java.lang.ClassNotFoundException:
  net.sourceforge.jdatepicker.DateModel     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:381)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:424)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:357)     ... 7 more

Pom DataPicker dependency:

        <dependency>
            <groupId>net.sourceforge.jdatepicker</groupId>
            <artifactId>jdatepicker</artifactId>
            <version>1.3.2</version>
        </dependency>

Why even though dependency was added, exception occurs?

Body:
try adding maven plugin so that it copies all your dependencies with the jar file and it does not have to look any further. Do this by adding:

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.4</version>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>package</phase>
                <goals><goal>copy-dependencies</goal></goals>
            </execution>
        </executions>
    </plugin>


问:
SQL MAX COUNT & MIN COUNT
I am trying these two SQL statements on the following two tables:

```<code>SELECT TOP 1
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer.country
    GROUP BY
        country
    ORDER BY
        count(*)
) AS AppointmentCount
</code>```

The SQL above is supposed to give the country with maximum appointments through COUNT (For the MIN I was going to use ORDER BY DESC)

tables' image

Unfortunately the above SQL is giving the following error but I cannot find a way to fix it:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near '1 Country FROM ( SELECT customer.country, count(*)' at line 1

Any help on how I can gix the above SQL statement? Any help would be much appreciated. Thanks in advance.

答:
The issue is the TOP statement, that is for MSSQL. You need to use a LIMIT instead. Try this one:

```<code>SELECT
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer
    GROUP BY
        country
) AS AppointmentCount
ORDER BY
    Appointments DESC
LIMIT 1
</code>```

Title: SQL MAX COUNT & MIN COUNT

Body:
I am trying these two SQL statements on the following two tables:

SELECT TOP 1
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer.country
    GROUP BY
        country
    ORDER BY
        count(*)
) AS AppointmentCount

The SQL above is supposed to give the country with maximum appointments through COUNT (For the MIN I was going to use ORDER BY DESC)

tables' image

Unfortunately the above SQL is giving the following error but I cannot find a way to fix it:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near '1 Country FROM ( SELECT customer.country, count(*)' at line 1

Any help on how I can gix the above SQL statement? Any help would be much appreciated. Thanks in advance.

Body:
The issue is the TOP statement, that is for MSSQL. You need to use a LIMIT instead. Try this one:

SELECT
    Country
FROM (
    SELECT
        customer.country,
        count(*) as Appointments
    FROM
       customer
    GROUP BY
        country
) AS AppointmentCount
ORDER BY
    Appointments DESC
LIMIT 1


问:
Integrating Spring cloud sleuth with Spring project
I am trying to integrate spring cloud sleuth with an existing spring application which uses jetty server.

I have added

```<code><dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth</artifactId>
            <version>1.2.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

and

```<code><dependencies>
   <dependency>spring-cloud-starter-sleuth</dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependencies>
</code>```

How should I pass the logger properties, logging pattern while starting the app? Right now, it does not read the properties file under /resources folder and no traceId or spanId is generated.

Most of the examples have used Spring Boot. Need help to figure out how to integrate this with a Spring application with jetty server.

答: Spring Cloud Sleuth is Spring Boot based. Please use https://github.com/openzipkin/brave for non Spring Boot based applications.</p>

Body:
I am trying to integrate spring cloud sleuth with an existing spring application which uses jetty server.

I have added

<dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth</artifactId>
            <version>1.2.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

and

<dependencies>
   <dependency>spring-cloud-starter-sleuth</dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependencies>

How should I pass the logger properties, logging pattern while starting the app? Right now, it does not read the properties file under /resources folder and no traceId or spanId is generated.

Most of the examples have used Spring Boot. Need help to figure out how to integrate this with a Spring application with jetty server.


问:
The module has been successfully installed but then it's not found when imported? - Python
I'm trying to use the graphviz Python module and I've run into this problem:
I pip installed it in my command prompt, but it's not showing up in IPython.  I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython.

I've been recommended to include the sys.path for each of the interpreters.

Anyone have any ideas as to how I'd change it?

答:
Try to list out installed packages in your python:

```<code>$pip freeze
</code>```

Usually it happened because of PYTHONPATH problem.
Did you try to reinstall your iPython? Maybe it was installed using different version of python.

```<code>$pip uninstall ipython
$pip install ipython
</code>```

I tried using Python 3.6.3, it works well.
Or you can try;

```<code>$pip3.6 install graphviz
</code>```

Body:
Try to list out installed packages in your python:

$pip freeze

Usually it happened because of PYTHONPATH problem.
Did you try to reinstall your iPython? Maybe it was installed using different version of python.

$pip uninstall ipython
$pip install ipython

I tried using Python 3.6.3, it works well.
Or you can try;

$pip3.6 install graphviz


问:
onNotificationPosted not being called after some time
I use NotificationListenerService to catch notifications and elaborate them in my application. App works great and onNotificationPosted is always called, but after a while (Few hours) it stops being called and the app stops working.

It gets back to work only if I reboot my device or if I revoke and grant again notification access to the application.

Important info

App does have notification access enabled.

App does have service on AndroidManifest.

```<code><service
    android:name=".NotificationService"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
         <intent-filter>
             <action android:name="android.service.notification.NotificationListenerService"/>
         </intent-filter>
</service>
</code>```

App is a release version (Same problem on debug version though).

It has been tested on Android Lollipop, Marshmallow and Nougat, same result.

It has been tested in different devices running the same Android version.

App stops working in both background and activity displayed on screen.

It works again if I reinstall the application, but this is already included in 'revoke and grant notification access again' previously mentioned.

App includes AdMob banner on bottom, is it a possible problem?

I read Android has a cache problem or something like that. Is this the problem? Is there any permanent solution that I couldn't find anywhere?

答:
I found the answer myself here:
https://gist.github.com/xinghui/b2ddd8cffe55c4b62f5d8846d5545bf9

Just create a new class as in the link above, then put in onCreate:

```<code>startService(new Intent(this, NotificationCollectorMonitorService.class));
</code>```

And in AndroidManifest:

```<code><service android:name=".NotificationCollectorMonitorService"/>
</code>```

This will restart your NotificationListenerService whenever Android kills it.

Body:
I use NotificationListenerService to catch notifications and elaborate them in my application. App works great and onNotificationPosted is always called, but after a while (Few hours) it stops being called and the app stops working.

It gets back to work only if I reboot my device or if I revoke and grant again notification access to the application.

Important info

App does have notification access enabled.

App does have service on AndroidManifest.

<service
    android:name=".NotificationService"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
         <intent-filter>
             <action android:name="android.service.notification.NotificationListenerService"/>
         </intent-filter>
</service>

App is a release version (Same problem on debug version though).

It has been tested on Android Lollipop, Marshmallow and Nougat, same result.

It has been tested in different devices running the same Android version.

App stops working in both background and activity displayed on screen.

It works again if I reinstall the application, but this is already included in 'revoke and grant notification access again' previously mentioned.

App includes AdMob banner on bottom, is it a possible problem?

I read Android has a cache problem or something like that. Is this the problem? Is there any permanent solution that I couldn't find anywhere?

Body:
I found the answer myself here:
https://gist.github.com/xinghui/b2ddd8cffe55c4b62f5d8846d5545bf9

Just create a new class as in the link above, then put in onCreate:

startService(new Intent(this, NotificationCollectorMonitorService.class));

And in AndroidManifest:

<service android:name=".NotificationCollectorMonitorService"/>

This will restart your NotificationListenerService whenever Android kills it.


问:
Anonymous Functions on Event Handlers not activating Styling
I have been experimenting with a technique for using event listeners which I found here on the Stack Overflow.

My own problem is that I am trying to retrieve the element ids of a couple of elements (retrieved by testing for id name) and isolate any styling/changes to just those elements (there are multiple elements that may have events occur on them).

Because I don't know which elements could have events occur on them I found the biggest issue was gathering and passing the id of the elements I wanted to pass to the listener. I believe I have found a way to overcome that using an array and an if else statement. Then I found a new problem...

I narrowed the issue using this example down to choice A or B. Choice A needs to modify an element with styling and choice B doesn't. In this example I've been able to gather an id and pass it to the listening function but for some reason the anonymous functions in the listener are not firing to modify choice A despite the event seemingly being passed successfully to the listening function and I am asking for help to find out why. If I explicitly hard code an id to the listener the program works!

Any help anyone could provide would be great and very much appreciated.

function listen(elem, evnt, func) {
  if (elem.addEventListener) { //W3C DOMS.
    elem.addEventListener(evnt, func, false);
  } else if (elem.attachEvent) { //IE DOM 7
    var r = elem.attachEvent("on" + evnt, func);
    return r;
  }
}

function attachListeners() {

  var selectors = document.querySelectorAll("div");

  for (var i = 0; i < selectors.length; i++) {
    selectors[i].addEventListener("focus", function(event) {
      var id_of_clicked_element = event.target.id
    });

    // var id_of_clicked_element = document.activeElement.id;
    if (id_of_clicked_element = 'touch_me') {
      var touch_div = id_of_clicked_element;
    } else if (id_of_clicked_element = 'What_about_me') {
      touch_div = id_of_clicked_element;
    }
  }

  //var touch_div = document.getElementById('touch_me');
  //  If you uncomment the line above and comment out the bit
  //   above the program works

  listen(touch_div, 'touchmove', function(event) {
    touch_div.innerHTML = "Being Touched" + event.targetTouches.length;
    touch_div.style.background = 'green';
  }, false);

  listen(touch_div, 'touchstart', function(event) {
    event.preventDefault();
    touch_div.innerHTML = "touchstart";
    touch_div.style.background = 'green';
  }, false);

  listen(touch_div, 'touchend', function(event) {
    touch_div.innerHTML = "Thanks";
    touch_div.style.background = '#CCFF66';
  }, false);

  listen(touch_div, 'click', function(event) {
    touch_div.innerHTML = "Hey - touch not Click!";
    touch_div.style.background = 'red';
  }, false);

  listen(touch_div, 'onmouseup', function(event) {
    touch_div.innerHTML = "Hey - that was a Click!";
    touch_div.style.background = '';
  }, false);
}

window.onload = attachListeners;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="touch_me"> Touch Me!</div>
<div id="What_about_me"> What About Me!</div></code>```

答:
The problem is in your if statement you are just getting ID of the element not the whole element. You should change it to:</p>

```<code>    if (id_of_clicked_element === 'touch_me') {
      var touch_div = document.getElementById(id_of_clicked_element);
    } else if (id_of_clicked_element === 'What_about_me') {
      touch_div = document.getElementById(id_of_clicked_element);
    }
</code>```

Body:
I have been experimenting with a technique for using event listeners which I found here on the Stack Overflow.

My own problem is that I am trying to retrieve the element ids of a couple of elements (retrieved by testing for id name) and isolate any styling/changes to just those elements (there are multiple elements that may have events occur on them).

Because I don't know which elements could have events occur on them I found the biggest issue was gathering and passing the id of the elements I wanted to pass to the listener. I believe I have found a way to overcome that using an array and an if else statement. Then I found a new problem...

I narrowed the issue using this example down to choice A or B. Choice A needs to modify an element with styling and choice B doesn't. In this example I've been able to gather an id and pass it to the listening function but for some reason the anonymous functions in the listener are not firing to modify choice A despite the event seemingly being passed successfully to the listening function and I am asking for help to find out why. If I explicitly hard code an id to the listener the program works!

Any help anyone could provide would be great and very much appreciated.

function listen(elem, evnt, func) {
  if (elem.addEventListener) { //W3C DOMS.
    elem.addEventListener(evnt, func, false);
  } else if (elem.attachEvent) { //IE DOM 7
    var r = elem.attachEvent("on" + evnt, func);
    return r;
  }
}

function attachListeners() {

  var selectors = document.querySelectorAll("div");

  for (var i = 0; i < selectors.length; i++) {
    selectors[i].addEventListener("focus", function(event) {
      var id_of_clicked_element = event.target.id
    });

    // var id_of_clicked_element = document.activeElement.id;
    if (id_of_clicked_element = 'touch_me') {
      var touch_div = id_of_clicked_element;
    } else if (id_of_clicked_element = 'What_about_me') {
      touch_div = id_of_clicked_element;
    }
  }

  //var touch_div = document.getElementById('touch_me');
  //  If you uncomment the line above and comment out the bit
  //   above the program works

  listen(touch_div, 'touchmove', function(event) {
    touch_div.innerHTML = "Being Touched" + event.targetTouches.length;
    touch_div.style.background = 'green';
  }, false);

  listen(touch_div, 'touchstart', function(event) {
    event.preventDefault();
    touch_div.innerHTML = "touchstart";
    touch_div.style.background = 'green';
  }, false);

  listen(touch_div, 'touchend', function(event) {
    touch_div.innerHTML = "Thanks";
    touch_div.style.background = '#CCFF66';
  }, false);

  listen(touch_div, 'click', function(event) {
    touch_div.innerHTML = "Hey - touch not Click!";
    touch_div.style.background = 'red';
  }, false);

  listen(touch_div, 'onmouseup', function(event) {
    touch_div.innerHTML = "Hey - that was a Click!";
    touch_div.style.background = '';
  }, false);
}

window.onload = attachListeners;

 Touch Me!

 What About Me!

Body:
The problem is in your if statement you are just getting ID of the element not the whole element. You should change it to:

    if (id_of_clicked_element === 'touch_me') {
      var touch_div = document.getElementById(id_of_clicked_element);
    } else if (id_of_clicked_element === 'What_about_me') {
      touch_div = document.getElementById(id_of_clicked_element);
    }


问:
Is there a list of all available extensions for Jupyterlab?
I am looking for a webpage or some manner to see a list of the existing extensions for Jupyterlab. I have been manually browsing through the www.npmjs.com with the search keyword @jupyterlab. Any other suggestions?

Thanks

答:
Found in Jupyterlab tutorial Documentation -> Release 0.1 ->
Chapter 2.2 -> Installation extension.

The currently installed extensions can be listed by running
the command: jupyter labextension list.


问:
dojo.require issues
I'm having trouble configuring my initial installation of dojo to include the widget framework correctly.

Following most of the code I see, including dijit should look like this:

```<code>dojo.require("dijit");
</code>```

and that's that. Unfortunately, that doesn't seem to work.

Using this initializes the widgets correctly, but there's some weird behavior from the standard dijit methods that makes me think that I'm doing it wrong:

```<code>dojo.require("dijit.dijit");
</code>```

Is there an element of configuring dojo that I'm missing? The files are all placed as they are in the 1.2.3 distribution, underneath another javascript folder.

答:
You don't actually have to include dijit, just point directly to widgets you want to use: dojo.require("dijit.Dialog");. Weird widget behavior could be explained also by:

missing theme css files: check with FireBug that everything gets loaded

missing theme class attribute: add class="tundra" to the body element

missing djConfig="parseOnLoad: true"

OwnerDisplayName: Dan Monego

Title: dojo.require issues

Body:
I'm having trouble configuring my initial installation of dojo to include the widget framework correctly.

Following most of the code I see, including dijit should look like this:

dojo.require("dijit");

and that's that. Unfortunately, that doesn't seem to work.

Using this initializes the widgets correctly, but there's some weird behavior from the standard dijit methods that makes me think that I'm doing it wrong:

dojo.require("dijit.dijit");

Is there an element of configuring dojo that I'm missing? The files are all placed as they are in the 1.2.3 distribution, underneath another javascript folder.

OwnerDisplayName: Maine


问:
Showing data from pickerview
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }
</code>```

And the picker view methods I have given like this...

```<code>func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}
</code>```

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}
</code>```

This is the picker view methods...

```<code>        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}
</code>```

EDIT 2 . code of pickerview didSelectRow

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}
</code>```

答:
Problem :

As somebody mentioned in answer above

myCell = cell //The issue seems to be here.

is the culprit. Because every time cellForRowAtIndexPath finishes your myCell will have reference to the last cell returned and not to the cell which is responsible for showing the pickerView.

First delete myCell = cell from cellForRowAtIndexPath

Solution :

Now all that you have to do is to figure out which cell which holds the textField which is responsible for presenting the pickerView.

Now there can be multiple solutions. Here is one

step 1: Create a subclass of PickerView

```<code>class MyPickerView : UIPickerView {
    weak var cell : MyTableViewCell? = nil
}
</code>```

Use this pickerView in your code than UIPickerView.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = MyPickerView()
        pickerView.cell = cell //pass cells reference
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        //other code
}
</code>```

Finally

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView is MyPickerView {
            if let cell = (pickerView as! MyPickerView).cell {
                cell.textField?.text = myData[row]
                let indexPath = self.tableView.indexPath(for: cell)
                if let index  = indexPath {
                    //now go ahead and update your data
                }

            }

        }
    }
</code>```

Edit:

There can be multiple variants to this solution. Some will agree that passing a cell reference to picker view is fine because cell will anyway hold a strong ref to picker and picker only holds weak ref to cell.

I personally feel passing indexPath as a param to picker makes more sense.  Finally when user picks something you will use the indexPath passed to picker to get the reference to cell and finally update the cell's textField.

O/P:

EDIT 2:

As OP is still confused I decided to modify his edit 2 and add it as part of answer

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView is MyPickerView {

            if let cell = (pickerView as! MyPickerView).cell {

                cell.qtyPickerField.text = myData[row]
                let indexPath = self.tableview.indexPath(for: cell)
                if let index = indexPath {
                    //this is only to show you how you can access indexPath
                    //and in future if you need to update your data source you can use it
                    //for now ignore this :)
                }
            }

        }
    }
</code>```

Should be good enough :) Hope it helps :)

Title: Showing data from pickerview

Body:
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }

And the picker view methods I have given like this...

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}

This is the picker view methods...

        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}

EDIT 2 . code of pickerview didSelectRow

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}

Body:
Problem :

As somebody mentioned in answer above

myCell = cell //The issue seems to be here.

is the culprit. Because every time cellForRowAtIndexPath finishes your myCell will have reference to the last cell returned and not to the cell which is responsible for showing the pickerView.

First delete myCell = cell from cellForRowAtIndexPath

Solution :

Now all that you have to do is to figure out which cell which holds the textField which is responsible for presenting the pickerView.

Now there can be multiple solutions. Here is one

step 1: Create a subclass of PickerView

class MyPickerView : UIPickerView {
    weak var cell : MyTableViewCell? = nil
}

Use this pickerView in your code than UIPickerView.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = MyPickerView()
        pickerView.cell = cell //pass cells reference
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        //other code
}

Finally

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView is MyPickerView {
            if let cell = (pickerView as! MyPickerView).cell {
                cell.textField?.text = myData[row]
                let indexPath = self.tableView.indexPath(for: cell)
                if let index  = indexPath {
                    //now go ahead and update your data
                }

            }

        }
    }

Edit:

There can be multiple variants to this solution. Some will agree that passing a cell reference to picker view is fine because cell will anyway hold a strong ref to picker and picker only holds weak ref to cell.

I personally feel passing indexPath as a param to picker makes more sense.  Finally when user picks something you will use the indexPath passed to picker to get the reference to cell and finally update the cell's textField.

O/P:

EDIT 2:

As OP is still confused I decided to modify his edit 2 and add it as part of answer

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView is MyPickerView {

            if let cell = (pickerView as! MyPickerView).cell {

                cell.qtyPickerField.text = myData[row]
                let indexPath = self.tableview.indexPath(for: cell)
                if let index = indexPath {
                    //this is only to show you how you can access indexPath
                    //and in future if you need to update your data source you can use it
                    //for now ignore this :)
                }
            }

        }
    }

Should be good enough :) Hope it helps :)


问:
How to make active particular toggle
This is my toogle code .Iam getting this HTML from backend . Iam using it in ng-repeat.When I click on a switch and make activate ,all switches become active and my expectation is only that switch become active that is clicked </p>

```<code><td class="">
  <label class="switch switch custom-switch" aria-hidden="false">
    <input type="checkbox" ng-model="agent_approve" ng-click="agent_status(agent_approve,id)" class="ng-pristine ng-untouched ng-valid" aria-checked="true" aria-invalid="false">
    <span></span>
  </label>
</td>
</code>```

<p>as i have mentioned that all data is coming from backend . we only save it in tables  and render it on html page
controller data is </p>

```<code>$scope.dtInstance = $('#all_driver_datatable').dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "order": [[0, "desc"]],
                "iDisplayLength": 25,
                "bDestroy": true,
                "bSearchable": true,
                "bPagination": true,
                "bPaginate": true,
                "sDom": '<"top"f>rt<"bottom"ipl><"clear">',
                language: {
                    paginate: {
                        next: '<i class="tf right-chevron"></i>',
                        previous: '<i class="tf left-chevron"></i>'
                    }
                },
                aoColumns: [
                    {"sTitle": "{{'more.agents.AGENTS_ID' | translate}}", "sClass": "ng-cloak", "sWidth": "7%"},
                    {
                        "sTitle": "{{'more.agents.IMAGE' | translate}}",
                        "sClass": "ng-cloak",
                        "sWidth": "7%",
                        orderable: false
                    },
                    {"sTitle": "{{'more.agents.USERNAME' | translate}}", "sClass": "ng-cloak", "sWidth": "10%"},
                    {"sTitle": "{{'more.agents.NAME' | translate}}", "sClass": "ng-cloak", "sWidth": "10%"},
                    {"sTitle": "{{'more.agents.EMAIL' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.PHONE' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.DEVICE_TYPE' | translate}}", "sClass": "ng-cloak", "sWidth": "6%"},
                    {
                        "sTitle": "{{'more.agents.DEVICE_VERSION' | translate}}",
                        "sClass": "ng-cloak",
                        "sWidth": "6%"
                    },
                    {"sTitle": "{{'more.agents.TEAM' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.STATUS' | translate}}", "sClass": "ng-cloak", "sWidth": "12%"},
                    {
                        "sTitle": "{{'more.agents.ACTIONS' | translate}}",
                        "sClass": "ng-cloak",
                        orderable: false,
                        "sWidth": "14%"
                    },
                ],
                // "columnDefs": [
                //     {targets: 'no-sort', orderable: false},
                //     {"type": "date-de", targets: 7}
                // ],
                "headerCallback": function (thead, data, start, end, display) {
                    $compile(thead)($scope);
                    $('.dataTables_wrapper .dataTables_filter input[type="search"]', '.fancy-table-outer').attr('placeholder', 'Search '+$scope.driverNamedAs).attr('onkeyup', 'showLoader()').focus().after('<div class="tf search"></div>');
                },
                "sAjaxSource": api,
                "createdRow": function (row, data, dataIndex) {
                    $compile(row)($scope);
                    $compile($('#all_driver_datatable thead tr')[0])($scope);
                    hideLoader();
                },
                "fnDrawCallback": function() {
                    hideLoader();
                },
                "columnDefs": [ {
                "targets": arr,
                "visible": false
            }
            ]

            }).fnSetFilteringDelay(2000);

            $timeout(function () {
                $compile($('#all_driver_datatable thead tr')[0])($scope);
                $("#all_driver_datatable").show();
                $('table th').css('opacity', '1');
                hideLoader();
            }, 2000);

        }
</code>```

答:
You have the same ng-model assigned to all of your checkboxes. So, if one becomes true, it makes all the checkboxes as checked.

Change the value of your ng-model, for example, use an array instead.

```<code><tr ng-repeat="item in items track by $index">
  <td class="">
    <label class="switch switch custom-switch" aria-hidden="false">
      <input type="checkbox" ng-model="agent_approve[$index]" ng-click="agent_status(agent_approve,id)" class="ng-pristine ng-untouched ng-valid" aria-checked="true" aria-invalid="false">
      <span></span>
    </label>
  </td>
</tr>
</code>```

This way, agent_approve will be an array of boolean values, each representing the checked state of the corresponding checkbox.

Title: How to make active particular toggle

Body:
This is my toogle code .Iam getting this HTML from backend . Iam using it in ng-repeat.When I click on a switch and make activate ,all switches become active and my expectation is only that switch become active that is clicked

    <input type="checkbox" ng-model="agent_approve" ng-click="agent_status(agent_approve,id)" class="ng-pristine ng-untouched ng-valid" aria-checked="true" aria-invalid="false">

as i have mentioned that all data is coming from backend . we only save it in tables  and render it on html page
controller data is

$scope.dtInstance = $('#all_driver_datatable').dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "order": [[0, "desc"]],
                "iDisplayLength": 25,
                "bDestroy": true,
                "bSearchable": true,
                "bPagination": true,
                "bPaginate": true,
                "sDom": '<"top"f>rt<"bottom"ipl><"clear">',
                language: {
                    paginate: {
                        next: '',
                        previous: ''
                    }
                },
                aoColumns: [
                    {"sTitle": "{{'more.agents.AGENTS_ID' | translate}}", "sClass": "ng-cloak", "sWidth": "7%"},
                    {
                        "sTitle": "{{'more.agents.IMAGE' | translate}}",
                        "sClass": "ng-cloak",
                        "sWidth": "7%",
                        orderable: false
                    },
                    {"sTitle": "{{'more.agents.USERNAME' | translate}}", "sClass": "ng-cloak", "sWidth": "10%"},
                    {"sTitle": "{{'more.agents.NAME' | translate}}", "sClass": "ng-cloak", "sWidth": "10%"},
                    {"sTitle": "{{'more.agents.EMAIL' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.PHONE' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.DEVICE_TYPE' | translate}}", "sClass": "ng-cloak", "sWidth": "6%"},
                    {
                        "sTitle": "{{'more.agents.DEVICE_VERSION' | translate}}",
                        "sClass": "ng-cloak",
                        "sWidth": "6%"
                    },
                    {"sTitle": "{{'more.agents.TEAM' | translate}}", "sClass": "ng-cloak", "sWidth": "9%"},
                    {"sTitle": "{{'more.agents.STATUS' | translate}}", "sClass": "ng-cloak", "sWidth": "12%"},
                    {
                        "sTitle": "{{'more.agents.ACTIONS' | translate}}",
                        "sClass": "ng-cloak",
                        orderable: false,
                        "sWidth": "14%"
                    },
                ],
                // "columnDefs": [
                //     {targets: 'no-sort', orderable: false},
                //     {"type": "date-de", targets: 7}
                // ],
                "headerCallback": function (thead, data, start, end, display) {
                    $compile(thead)($scope);
                    $('.dataTables_wrapper .dataTables_filter input[type="search"]', '.fancy-table-outer').attr('placeholder', 'Search '+$scope.driverNamedAs).attr('onkeyup', 'showLoader()').focus().after('

');
                },
                "sAjaxSource": api,
                "createdRow": function (row, data, dataIndex) {
                    $compile(row)($scope);
                    $compile($('#all_driver_datatable thead tr')[0])($scope);
                    hideLoader();
                },
                "fnDrawCallback": function() {
                    hideLoader();
                },
                "columnDefs": [ {
                "targets": arr,
                "visible": false
            }
            ]

            }).fnSetFilteringDelay(2000);

            $timeout(function () {
                $compile($('#all_driver_datatable thead tr')[0])($scope);
                $("#all_driver_datatable").show();
                $('table th').css('opacity', '1');
                hideLoader();
            }, 2000);

        }

Body:
You have the same ng-model assigned to all of your checkboxes. So, if one becomes true, it makes all the checkboxes as checked.

Change the value of your ng-model, for example, use an array instead.

<tr ng-repeat="item in items track by $index">
  <td class="">
    <label class="switch switch custom-switch" aria-hidden="false">
      <input type="checkbox" ng-model="agent_approve[$index]" ng-click="agent_status(agent_approve,id)" class="ng-pristine ng-untouched ng-valid" aria-checked="true" aria-invalid="false">
      <span></span>
    </label>
  </td>
</tr>

This way, agent_approve will be an array of boolean values, each representing the checked state of the corresponding checkbox.


问:
Remove Leaflet minicharts
I've created piecharts with the Leaflet.minicharts.js plugin.
It works fine to add the charts.
But I can't remove them anymore.
I tried to remove each chart separately with map.removeLayer(chart[i]).
And I also tried to put all charts together in a LayerGroup and then use the function map.removeLayer(LayerGroup) and with layergorup.clearLayers(). When I call the function map.hasLayer(layer), it returns false. So, everything as expected. But the charts are still visible on the map.
Here a simple example with a barchart, which I try to remove with a button-click.

```<code><html>
<head>
    <title>Leaflet Test</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css"
   integrity="sha512-wcw6ts8Anuw10Mzh9Ytw4pylW8+NAD4ch3lqm9lzAsTxg0GFeJgoAtxuCLREZSC5lUXdVyo/7yfsqFjQ4S+aKw=="
   crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.1.0/dist/leaflet.js"
   integrity="sha512-mNqn2Wg7tSToJhvHcqfzLMU6J4mkOImSPTxVZAdo+lcPlk+GhZmYgACEe0x35K7YzW1zJ7XyJV/TT1MrdXvMcA=="
   crossorigin=""></script>
   <script src="https://unpkg.com/leaflet.minichart/dist/leaflet.minichart.min.js" charset="utf-8"></script>
</head>
<body>
    <!-- CSS -->
    <style type="text/css">
        #mapid { height: 480px; }
        #butt {color:black;position: absolute;padding:2em;top:50%; left:50%;}
    </style>

    <div id="mapid"></div>
    <button id="butt" onclick="vanish();">Remove Chart!</button>
    <script type="text/javascript">
        var map = L.map('mapid').setView([50, 9], 14);
        var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
        }).addTo( map );

        var center = [50, 9];
        function fakeData() {
          return [Math.random(), Math.random(), Math.random()];
        }

        var myBarChart = L.minichart(center, {data: fakeData()});
        map.addLayer(myBarChart);

        function vanish(e) {
            console.log(map.hasLayer(myBarChart));
            map.removeLayer(myBarChart);
            console.log(map.hasLayer(myBarChart));
        }

    </script>

</body>
</html>
</code>```

答:
i had the same problem. What i did is I wrote a function where i can loop through the layer-group to find if the Layer-group contains a layer with the property "_chart". If so, remove that layer. The loop continues till it removes all the layers with that property. Here is the code what i wrote.

```<code>for(var i = 0; i<Object.keys(lyrGrp._layers).length;i++){

    if(lyrGrp._layers[Object.keys(lyrGrp._layers)[i]]._chart)
      {
       lyrGrp._layers[Object.keys(lyrGrp._layers)[i]]._chart.remove()
      }

 }
</code>```

Hope it is useful.

Title: Remove Leaflet minicharts

Body:
I've created piecharts with the Leaflet.minicharts.js plugin.
It works fine to add the charts.
But I can't remove them anymore.
I tried to remove each chart separately with map.removeLayer(chart[i]).
And I also tried to put all charts together in a LayerGroup and then use the function map.removeLayer(LayerGroup) and with layergorup.clearLayers(). When I call the function map.hasLayer(layer), it returns false. So, everything as expected. But the charts are still visible on the map.
Here a simple example with a barchart, which I try to remove with a button-click.

    <title>Leaflet Test</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css"
   integrity="sha512-wcw6ts8Anuw10Mzh9Ytw4pylW8+NAD4ch3lqm9lzAsTxg0GFeJgoAtxuCLREZSC5lUXdVyo/7yfsqFjQ4S+aKw=="
   crossorigin=""/>

    <button id="butt" onclick="vanish();">Remove Chart!</button>

Body:
i had the same problem. What i did is I wrote a function where i can loop through the layer-group to find if the Layer-group contains a layer with the property "_chart". If so, remove that layer. The loop continues till it removes all the layers with that property. Here is the code what i wrote.

for(var i = 0; i<Object.keys(lyrGrp._layers).length;i++){

    if(lyrGrp._layers[Object.keys(lyrGrp._layers)[i]]._chart)
      {
       lyrGrp._layers[Object.keys(lyrGrp._layers)[i]]._chart.remove()
      }

 }

Hope it is useful.