问:
Pass a range as an argument in a formula using VBA
I'm really REALLY new using VBA, so I apologize for this question in advance:

Basically, I'm trying to write a sub that will calculate IRR on a range of numbers that is dynamic. So I tried to create a variable which would select the range of numbers, and then using a named range for the output cell(IRR), have the result of the formula show. Below is the code I have:

```<code>Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range("B55").End(xlToRight).Select

Range("IRR").Formula = "IRR(calcrange)"

End Sub
</code>```

The error I'm getting is 'Object required', and its pointing to the center line of code "Set calcrange".

I have been looking for an answer but I can't seem to find (or understand) what the problem is...Again I know this is probably ridiculously easy but I'm a bit stumped. Thanks in advance

答:
```<code>Range("IRR").Formula = "IRR(calcrange)"
</code>```

-You are putting a formula into the cell requesting it to run a named range through a subroutine called "IRR".

Setting the range in a module does not make it a named range.  You need the following code to do that:

```<code>Set rng1 = Range("B55:B200") ' How many columns need to be calculated
ActiveWorkbook.Names.Add Name:="calcrange", RefersTo:=Rng1
</code>```

Now you have a named range to work with.

Do you have a subroutine "IRR" to work with?  It looks like you are referring to a single cell named "IRR."  It's confusing and probably erroneous to use the same name for different things like ranges and functions or subroutines.  Can you post your subroutine "IRR?"

Body:
I'm really REALLY new using VBA, so I apologize for this question in advance:

Basically, I'm trying to write a sub that will calculate IRR on a range of numbers that is dynamic. So I tried to create a variable which would select the range of numbers, and then using a named range for the output cell(IRR), have the result of the formula show. Below is the code I have:

Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range("B55").End(xlToRight).Select

Range("IRR").Formula = "IRR(calcrange)"

End Sub

The error I'm getting is 'Object required', and its pointing to the center line of code "Set calcrange".

I have been looking for an answer but I can't seem to find (or understand) what the problem is...Again I know this is probably ridiculously easy but I'm a bit stumped. Thanks in advance

Body:
Range("IRR").Formula = "IRR(calcrange)"

-You are putting a formula into the cell requesting it to run a named range through a subroutine called "IRR".

Setting the range in a module does not make it a named range.  You need the following code to do that:

Set rng1 = Range("B55:B200") ' How many columns need to be calculated
ActiveWorkbook.Names.Add Name:="calcrange", RefersTo:=Rng1

Now you have a named range to work with.

Do you have a subroutine "IRR" to work with?  It looks like you are referring to a single cell named "IRR."  It's confusing and probably erroneous to use the same name for different things like ranges and functions or subroutines.  Can you post your subroutine "IRR?"


来源: stackexchange

问:
How to make number auto to step 1, 2, 3 in ListView, Not connection Database
Photo Example:

For Form_load Click

```<code>private void Form6_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < itm.Length; i++)
            {
                listView1.Columns.Add(itm[i], size[i], HorizontalAlignment.Left);

            }
            listView1.GridLines = true;
            listView1.View = View.Details;
            listView1.FullRowSelect = true;
        }
</code>```

Code in Button Add_Click

```<code> private void btnadd_Click(object sender, EventArgs e)
        {
            ListViewItem data = new ListViewItem();
            data.SubItems.Add(txtname.Text);
            data.SubItems.Add(txtsur.Text);
            data.SubItems.Add(txtage.Text);
            listView1.Items.Add(data);
            clear();
        }
</code>```

答:
You need to set the Text property of new ListViewItem which will be displayed in the first column of the ListView.

```<code> private void btnadd_Click(object sender, EventArgs e)
 {
     ListViewItem data = new ListViewItem();
     data.Text = (listView1.Items.Count + 1).ToString();
     data.SubItems.Add(txtname.Text);
     data.SubItems.Add(txtsur.Text);
     data.SubItems.Add(txtage.Text);
     listView1.Items.Add(data);
     clear();
 }
</code>```

This should resolve your issue.

ContentLicense: CC BY-SA 3.0

Body:
Photo Example:

For Form_load Click

private void Form6_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < itm.Length; i++)
            {
                listView1.Columns.Add(itm[i], size[i], HorizontalAlignment.Left);

            }
            listView1.GridLines = true;
            listView1.View = View.Details;
            listView1.FullRowSelect = true;
        }

Code in Button Add_Click

 private void btnadd_Click(object sender, EventArgs e)
        {
            ListViewItem data = new ListViewItem();
            data.SubItems.Add(txtname.Text);
            data.SubItems.Add(txtsur.Text);
            data.SubItems.Add(txtage.Text);
            listView1.Items.Add(data);
            clear();
        }

Body:
You need to set the Text property of new ListViewItem which will be displayed in the first column of the ListView.

 private void btnadd_Click(object sender, EventArgs e)
 {
     ListViewItem data = new ListViewItem();
     data.Text = (listView1.Items.Count + 1).ToString();
     data.SubItems.Add(txtname.Text);
     data.SubItems.Add(txtsur.Text);
     data.SubItems.Add(txtage.Text);
     listView1.Items.Add(data);
     clear();
 }

This should resolve your issue.


问:
PHP regex for admin, admin/ and admin/more/ etc
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

```<code>'admin(.*)'
</code>```

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias

答:
Another approach:

```<code>$sample_string="admin/foo/bar";

if(in_array("admin", explode("/",$sample_string))){
 //true
}else{
 //false
}
</code>```

Or you could even replace the explode "/" with explode by "admin".....

ContentLicense: CC BY-SA 2.5

Body:
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

'admin(.*)'

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias

Body:
Another approach:

$sample_string="admin/foo/bar";

if(in_array("admin", explode("/",$sample_string))){
 //true
}else{
 //false
}

Or you could even replace the explode "/" with explode by "admin".....


问:
Visual Studio keeps adding IIS Express back into my launchsettings.json
I am trying to remove the IIS Express profile from my .NET Core launch settings but every time i repoen the solution, Visual Studio adds it back in again. For example, in a new project my launch settings looks like this

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:55735/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyProject": {
      "commandName": "Project",
      "launchUrl": "http://localhost:5010",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

I remove the IIS sections

```<code>{
  "profiles": {
    "MyProject": {
      "commandName": "Project",
      "launchUrl": "http://localhost:5010",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

The solution runs fine. But as soon as I close and reopen the solution the IIS sections reappear.

Any ideas?

答:
UPDATE:

The issue should be fixed with the latest release (update) of Visual Studio 2017 (version 15.3.0).

Initial answer:

This is not a solution, but an ugly workaround. I figured that if I would just deny permissions to change the launchsettings.json file this will prevent Visual Studio from overwriting it every time. Since this file doesn't change much, it is more or less a satisfying solution for me.

So:

Update your launchsettings.json for the last time.

Close Visual Studio.

Open security settings (right-click on launchsettings.json in Explorer -> Properties -> Security)

Click Advanced -> Change Permissions

Select "Authenticated Users" (or other user group under which Visual Studio is running on your machine) from the "Permissions entries" list and click Edit ->

Check Deny for "Create files / write data" permission.

Click OK in all open dialogs and warnings to save changes.

Reopen Visual Studio and see it fail to do it's update.

Hope it helps.

Body:
I am trying to remove the IIS Express profile from my .NET Core launch settings but every time i repoen the solution, Visual Studio adds it back in again. For example, in a new project my launch settings looks like this

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:55735/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyProject": {
      "commandName": "Project",
      "launchUrl": "http://localhost:5010",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

I remove the IIS sections

{
  "profiles": {
    "MyProject": {
      "commandName": "Project",
      "launchUrl": "http://localhost:5010",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

The solution runs fine. But as soon as I close and reopen the solution the IIS sections reappear.

Any ideas?


问:
How can you use a returned result in a new function without using global variables?
How can you use a returned variable in a new function without using global variables?</p>

```<code>def f():
  var1 = 5
  var2 = 10
  return var1, var2

def g():
  var3 = var1*var2
  return var3
</code>```

答:
You need to store the return value of f() in a variable (or variables) defined in function g.
See an example:

```<code>def f():
    var1 = 5
    var2 = 10
    return var1, var2

def g():
    var1, var2 = f()
    var3 = var1*var2
    return var3
</code>```

Edit: oops it seems the user mknull has responded just before.

Body:
How can you use a returned variable in a new function without using global variables?

def f():
  var1 = 5
  var2 = 10
  return var1, var2

def g():
  var3 = var1*var2
  return var3

Body:
You need to store the return value of f() in a variable (or variables) defined in function g.
See an example:

def f():
    var1 = 5
    var2 = 10
    return var1, var2

def g():
    var1, var2 = f()
    var3 = var1*var2
    return var3

Edit: oops it seems the user mknull has responded just before.


问:
Deploy Angular4 (Angular) created using angular-cli to Google App Engine
I have created a Angular4 or simply "Angular" application using Angular-CLI. Now i could run it locally using "ng serve" and it works fine. Now i want to deploy it to Google App Engine, ng build --prod builds all files to dist folder.

Now how should i deploy them to google app engine?

EDIT:

I forgot to mention this, i want to deploy using maven. is there any dependency i can add to pom.xml. so that i can do everything from mvn?

答:
you can use maven in this way as a wrapper to create the build and to create a zip to upload. This is an implementation using yarn
and npm.

    ${project.artifactId}

```<code><plugins>

  <!-- ############################## -->
  <!-- npm scripts                    -->
  <!-- ############################## -->

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <executions>
      <execution>
        <id>exec-yarn-install</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>npm</executable>
          <arguments>
            <argument>install</argument>
            <argument>--global</argument>
            <argument>yarn</argument>
          </arguments>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
      <execution>
        <id>exec-project-dependencies-install</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>yarn</executable>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>

      <!-- run `ng build -prod -aot` -->
      <!-- * clean dist/ before generating distribution files -->
      <execution>
        <id>exec-compile</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>yarn</executable>
          <arguments>
            <argument>run</argument>
            <argument>build</argument>
          </arguments>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <!-- generate zip -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.3</version>
    <configuration>
      <descriptors>
        <descriptor>src/assembly/static.xml</descriptor>
      </descriptors>
    </configuration>
    <executions>
      <execution>
        <id>make-assembly</id>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>
</code>```

Body:
you can use maven in this way as a wrapper to create the build and to create a zip to upload. This is an implementation using yarn
and npm.

    ${project.artifactId}

<plugins>

  <!-- ############################## -->
  <!-- npm scripts                    -->
  <!-- ############################## -->

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <executions>
      <execution>
        <id>exec-yarn-install</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>npm</executable>
          <arguments>
            <argument>install</argument>
            <argument>--global</argument>
            <argument>yarn</argument>
          </arguments>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
      <execution>
        <id>exec-project-dependencies-install</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>yarn</executable>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>

      <!-- run `ng build -prod -aot` -->
      <!-- * clean dist/ before generating distribution files -->
      <execution>
        <id>exec-compile</id>
        <phase>generate-sources</phase>
        <configuration>
          <executable>yarn</executable>
          <arguments>
            <argument>run</argument>
            <argument>build</argument>
          </arguments>
        </configuration>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <!-- generate zip -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.3</version>
    <configuration>
      <descriptors>
        <descriptor>src/assembly/static.xml</descriptor>
      </descriptors>
    </configuration>
    <executions>
      <execution>
        <id>make-assembly</id>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>


问:
How to pass additional parameters to WordPress wp_mail() function?
I want to pass some additional data (i.e. the admin email address) every a mail is sent from WordPress.

If my web site was based on pure PHP, I would have to set parameter additional_parameters to -f me@domain.com. More info here.

However, my web site is based on WordPress and so I have to find another way to pass the additional parameter (i.e. the admin email address) to wp_mail() function.

How can I do that in Wordpress?

答:
wp_mail allows you to provide headers to the email. If you use the From header, you can specify who the email is from.

```<code>$headers = array('From: ' . get_option('admin_email'));

wp_mail('recipient@example.com', 'Email subject', 'Email Body', $headers);
</code>```

Body:
wp_mail allows you to provide headers to the email. If you use the From header, you can specify who the email is from.

$headers = array('From: ' . get_option('admin_email'));

wp_mail('recipient@example.com', 'Email subject', 'Email Body', $headers);


问:
SQL - execute query from table cells
I have a database with one table, Queries. This table has two columns, name and Query. In column named Query I'm recording some SQL statements.

I'm trying to execute these statements after selecting them from the table.

This is my code, but output is incorrect, only the statements listed, without execution:

```<code>DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'

EXECUTE SP_EXECUTESQL @STR_QUERY
</code>```

答:
This should help you go through all scripts in that table. With what you are doing, only one script will be run so if the table has 100 Scripts, only one will be executed. Hope this helps</p>

```<code>DECLARE @Queries TABLE (ID INT IDENTITY(1,1),SQLScript VARCHAR(MAX))
DECLARE @STR_QUERY VARCHAR(MAX);
DECLARE @StartLoop INT
DECLARE @EndLoop INT

INSERT INTO @Queries
SELECT Query
FROM [AccHelper].[dbo].[Queries]

SELECT @EndLoop = MAX(ID), @StartLoop = MIN(ID)
FROM @Queries

WHILE @StartLoop < = @EndLoop
BEGIN
    SELECT @STR_QUERY = SQLScript
    FROM @Queries
    WHERE ID = @StartLoop

    EXEC (@STR_QUERY)

    SET @StartLoop = @StartLoop + 1
END
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL - execute query from table cells

Body:
I have a database with one table, Queries. This table has two columns, name and Query. In column named Query I'm recording some SQL statements.

I'm trying to execute these statements after selecting them from the table.

This is my code, but output is incorrect, only the statements listed, without execution:

DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'

EXECUTE SP_EXECUTESQL @STR_QUERY

Body:
This should help you go through all scripts in that table. With what you are doing, only one script will be run so if the table has 100 Scripts, only one will be executed. Hope this helps

DECLARE @Queries TABLE (ID INT IDENTITY(1,1),SQLScript VARCHAR(MAX))
DECLARE @STR_QUERY VARCHAR(MAX);
DECLARE @StartLoop INT
DECLARE @EndLoop INT

INSERT INTO @Queries
SELECT Query
FROM [AccHelper].[dbo].[Queries]

SELECT @EndLoop = MAX(ID), @StartLoop = MIN(ID)
FROM @Queries

WHILE @StartLoop < = @EndLoop
BEGIN
    SELECT @STR_QUERY = SQLScript
    FROM @Queries
    WHERE ID = @StartLoop

    EXEC (@STR_QUERY)

    SET @StartLoop = @StartLoop + 1
END


问:
How to show notification bar for a short time when the window is full screen by default?
```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setting fullscreen
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.repository_list);
</code>```

One can see that the window is fullscreen by default.

In an async task,notification is to be shown

```<code>@Override
    protected void onPreExecute() {
        Toast.makeText(this_context,"Downloading",Toast.LENGTH_LONG).show();
        mNotifyManager =
                (NotificationManager) this_context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this_context);
        mBuilder.setContentTitle("Repository")
                .setContentText("Download in progress")
                .setSmallIcon(android.R.drawable.stat_sys_download);
        mBuilder.setProgress(0, 0, false);
        // Displays the progress bar for the first time.
        mNotifyManager.notify(1, mBuilder.build());
        //dialog = ProgressDialog.show(this_context, "Wait", "Downloading...", true);
    }
</code>```

But the window being fullscreen, the notification cant be seen.
How can the notification be seen and then again will be hidden when the onPostExecute method will be called.
Thanks for your time.

答:
Ok have found an answer.

Have written this code.

On preExecute method

```<code>@Override
    protected void onPreExecute() {
        Toast.makeText(this_context,"Downloading",Toast.LENGTH_LONG).show();
        ((Activity)this_context).getWindow().addFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));

        mNotifyManager =
                (NotificationManager) this_context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this_context);
        mBuilder.setContentTitle("Repository")
                .setContentText("Download in progress")
                .setSmallIcon(android.R.drawable.stat_sys_download);
        mBuilder.setProgress(0, 0, false);
        // Displays the progress bar for the first time.
        mNotifyManager.notify(1, mBuilder.build());
        //dialog = ProgressDialog.show(this_context, "Wait", "Downloading...", true);
    }
</code>```

And on postExecute method

```<code>@Override
    protected void onPostExecute(String s) {
        ((Activity)this_context).getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
        mBuilder.setContentText("Download complete")
                .setSmallIcon(android.R.drawable.stat_sys_download_done)
                // Removes the progress bar
                .setProgress(0,0,false);
        mNotifyManager.notify(1, mBuilder.build());
        mNotifyManager.cancel(1);
</code>```

So long story short.

1.When activity is started the window was set to flag fullscreen

2.When asyntask starts,on the preexecute method, added the flag to force not fullscreen.Now can see the downloading notification as planned.

3.When asynctask completed downloading,the window flag to force not fullscreen is cleared.And again the window implements the default flag automatically i.e flag fullscreen which was set at the start of the activity.

Thanks for your time.

Body:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setting fullscreen
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.repository_list);

One can see that the window is fullscreen by default.

In an async task,notification is to be shown

@Override
    protected void onPreExecute() {
        Toast.makeText(this_context,"Downloading",Toast.LENGTH_LONG).show();
        mNotifyManager =
                (NotificationManager) this_context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this_context);
        mBuilder.setContentTitle("Repository")
                .setContentText("Download in progress")
                .setSmallIcon(android.R.drawable.stat_sys_download);
        mBuilder.setProgress(0, 0, false);
        // Displays the progress bar for the first time.
        mNotifyManager.notify(1, mBuilder.build());
        //dialog = ProgressDialog.show(this_context, "Wait", "Downloading...", true);
    }

But the window being fullscreen, the notification cant be seen.
How can the notification be seen and then again will be hidden when the onPostExecute method will be called.
Thanks for your time.

Body:
Ok have found an answer.

Have written this code.

On preExecute method

@Override
    protected void onPreExecute() {
        Toast.makeText(this_context,"Downloading",Toast.LENGTH_LONG).show();
        ((Activity)this_context).getWindow().addFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));

        mNotifyManager =
                (NotificationManager) this_context.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this_context);
        mBuilder.setContentTitle("Repository")
                .setContentText("Download in progress")
                .setSmallIcon(android.R.drawable.stat_sys_download);
        mBuilder.setProgress(0, 0, false);
        // Displays the progress bar for the first time.
        mNotifyManager.notify(1, mBuilder.build());
        //dialog = ProgressDialog.show(this_context, "Wait", "Downloading...", true);
    }

And on postExecute method

@Override
    protected void onPostExecute(String s) {
        ((Activity)this_context).getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
        mBuilder.setContentText("Download complete")
                .setSmallIcon(android.R.drawable.stat_sys_download_done)
                // Removes the progress bar
                .setProgress(0,0,false);
        mNotifyManager.notify(1, mBuilder.build());
        mNotifyManager.cancel(1);

So long story short.

1.When activity is started the window was set to flag fullscreen

2.When asyntask starts,on the preexecute method, added the flag to force not fullscreen.Now can see the downloading notification as planned.

3.When asynctask completed downloading,the window flag to force not fullscreen is cleared.And again the window implements the default flag automatically i.e flag fullscreen which was set at the start of the activity.

Thanks for your time.


问:
Rotate Apple Map as per user movement

Apple Map

Core Location

I implemented Apple Map with Core Location and its delegate to add pin and its working perfectly but now i am stuck with the issue to :

Rotate Map as per user movement ( as user travelling with car moves the different direction , the apple map should move )

I found Apple Map native does same work . Here is gif :

I did find solution yet . Kindly suggest me how to do it ?

Note ->

Don't want to use Google Map

Don't want to move Pin (annotation view)

If you want me to update my existing code , i can update again .

答:
Simply add the MKUserTrackingBarButtonItem to your toolbar, it behaves exactly as the button in Maps app and handles all of the magic.

```<code>    let trackingButton = MKUserTrackingBarButtonItem(mapView: mapView)
    toolbarItems = [trackingButton]
</code>```

Alternatively you could set the MKUserTrackingMode but then you're going to run into some handling issues, and a few caveats of doing it this way. Such as resetting the view after user scrolls the map, and not being able to control the zoom level among other things.

```<code>    mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)
</code>```

Title: Rotate Apple Map as per user movement

Body:
Simply add the MKUserTrackingBarButtonItem to your toolbar, it behaves exactly as the button in Maps app and handles all of the magic.

    let trackingButton = MKUserTrackingBarButtonItem(mapView: mapView)
    toolbarItems = [trackingButton]

Alternatively you could set the MKUserTrackingMode but then you're going to run into some handling issues, and a few caveats of doing it this way. Such as resetting the view after user scrolls the map, and not being able to control the zoom level among other things.

    mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)


问:
Node.js with websocket and cloudflare not working
I have two node scripts connected with PHO site.
Domain is under Cloudflare protection.

I using node.js and socekt.io to update content live to all connected users, but when I using CF protection, node script not working well.

Could someone tell me what I should do?
My ports: 8880 and 8080.

答:
You need allow CORS from your node script add the following to your node script for socket.io.

io.set('origins', 'http://sampledomain.com:8880');


问:
Python inserts both a carriage return and a line feed after variable, instead of just line feed
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

```<code>import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')
</code>```

the problem here is the line

```<code>print("{}\r".format(k), file=text_file, end='')
</code>```

答:
Try:</p>

```<code>with open("Output.txt", "bw") as text_file:
</code>```

Body:
I've created a python script to output every 1-4 character letter combinations from AAAA-ZZZZ etc.

It works perfectly, however I require only a line feed to be inserted at the end of the printed variable, since I am using this as a word list to be used in another script.

I have attempted to use both \r and \n, however using \n inserts both a Carriage Return and a Line Feed at the end (e.g AAAA CR LF), using \r inserts only a Carriage Return (e.g AAAA CR).

My question is would it be possible to insert just a line feed at the end, or is this impossible due to a limitation in python? i've tried using notepad to manually replace each character, and this works, however this is just patching up the problem and is impractical for use.

Many thanks for any help!

import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
    for k in i:
        print("{}\r".format(k), file=text_file, end='')

the problem here is the line

print("{}\r".format(k), file=text_file, end='')

Body:
Try:

with open("Output.txt", "bw") as text_file:


问:
Swift - Cascade on delete in SharkORM
I'm using SharkORM in Swift to create an SQLite database, the issue is that I have two tables with one-to-many relationship using foreign key, I need to know if there is a way to implement cascading on delete on these two tables,

When I delete a record from the primary table, all the records with its foreign key in the details table should be deleted automatically, I don't want to implement this manually.

So is there a way to implement cascading on delete using SharkORM? I already went through documentations and couldn't find anything,

Thanks in advance for your help.

答:
So if you take the example of Person -> Department, where person contains a .department property. Then you cascade these deletes via the entityWillDelete method.

An example is 'something' like this.

```<code>class Department: SRKObject {

   ...

   override func entityWillDelete() -> BOOL {
       Person.query()
             .whereWithFormat("department = %@", parameters:[self])
             .fetch()
             .removeAll()
       return true
   }

}
</code>```

With relationships, always look to the inverse.

The documentation for entityWillDelete mentions this here.

```<code>/**
 * Before SharkORM attempts an operation it will ask the
 * persitable class if it would like to continue with this operation.
 *
 * @return BOOL if YES is returned then SharkORM WILL complete the operation
 * and it is guaranteed to complete.  All pre-requisite checks have been made
 * and the statement compiled before getting to this point.
 * It is safe to use this method to cascade operations to other classes.
 * In the case of delete, you might wish to delete related records, or
 * indeed remove this object from related tables.
 */
- (BOOL)entityWillDelete;
</code>```

This is all done within a transaction, including all the cascades and event trigger changes.  Which can then all be rolled back in the case of a failure/error/abort.

Title: Swift - Cascade on delete in SharkORM

Body:
So if you take the example of Person -> Department, where person contains a .department property. Then you cascade these deletes via the entityWillDelete method.

An example is 'something' like this.

class Department: SRKObject {

   ...

   override func entityWillDelete() -> BOOL {
       Person.query()
             .whereWithFormat("department = %@", parameters:[self])
             .fetch()
             .removeAll()
       return true
   }

}

With relationships, always look to the inverse.

The documentation for entityWillDelete mentions this here.

/**
 * Before SharkORM attempts an operation it will ask the
 * persitable class if it would like to continue with this operation.
 *
 * @return BOOL if YES is returned then SharkORM WILL complete the operation
 * and it is guaranteed to complete.  All pre-requisite checks have been made
 * and the statement compiled before getting to this point.
 * It is safe to use this method to cascade operations to other classes.
 * In the case of delete, you might wish to delete related records, or
 * indeed remove this object from related tables.
 */
- (BOOL)entityWillDelete;

This is all done within a transaction, including all the cascades and event trigger changes.  Which can then all be rolled back in the case of a failure/error/abort.


问:
Can I install Xcode 8.3 on ElCapitan
Can I install xcode 8.3 without updating my Mac's OS i.e. "OS X El Capitan" (Version 10.11.6)

I was not able to find any reference on Apple's site, However, this link says I can't.

Right now, I've Xcode 8.2.1 installed.

答: No, the latest version of Xcode (Version 8.3) requires macOS Sierra 10.12. I found this information on the App Store page under the compatibility section on the left side.</p>

Title: Can I install Xcode 8.3 on ElCapitan


问:
DB2 SELECT FOR UPDATE with INNER JOIN
I am trying to work out a DB2 Issue. I make an update based on a previous Select and occasionally encounter Deadlocks when two transactions run the select in parallel and none of them is able to update afterwards.

So I am trying to solve this using Select For Update, but apparently, Select For Update does not work with inner join, is that correct? And is there a way around it?

Here's my Select Statement

```<code>SELECT s.ID FROM DATA.TABLE_A s
    INNER JOIN DATA.TABLE_B n ON s.ID = n.ID
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
        AND s.P_ID = ?
        AND s.C_ID = ?
FOR UPDATE
</code>```

答:
If you are only updating one table, you could try using a subselect instead of a join. Say, if you target TABLE_A for update, this might work:

```<code>SELECT s.ID FROM DATA.TABLE_A s
WHERE s.ID IN (
  SELECT n.ID
  FROM DATA.TABLE_B n
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
)
AND s.P_ID = ?
AND s.C_ID = ?
FOR UPDATE
</code>```

Title: DB2 SELECT FOR UPDATE with INNER JOIN

Body:
I am trying to work out a DB2 Issue. I make an update based on a previous Select and occasionally encounter Deadlocks when two transactions run the select in parallel and none of them is able to update afterwards.

So I am trying to solve this using Select For Update, but apparently, Select For Update does not work with inner join, is that correct? And is there a way around it?

Here's my Select Statement

SELECT s.ID FROM DATA.TABLE_A s
    INNER JOIN DATA.TABLE_B n ON s.ID = n.ID
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
        AND s.P_ID = ?
        AND s.C_ID = ?
FOR UPDATE

Body:
If you are only updating one table, you could try using a subselect instead of a join. Say, if you target TABLE_A for update, this might work:

SELECT s.ID FROM DATA.TABLE_A s
WHERE s.ID IN (
  SELECT n.ID
  FROM DATA.TABLE_B n
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
)
AND s.P_ID = ?
AND s.C_ID = ?
FOR UPDATE


问:
Binding gives UnsetValue on multiple binding
I have a datagrid which gets its data out of a datatable like
Inside if there is a textbox with a contextmenu and this contextmenu has a converter (with multibinding)
The problem is i datatable the binded data has 1 or 0 as data but in the converter i get UnsetValue.
This is the xaml code: </p>

```<code><DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch"  VirtualizingStackPanel.VirtualizationMode="Recycling" VirtualizingStackPanel.IsVirtualizing="True"  Margin="0,1,0,0" x:Name="TrackingDataGrid" IsReadOnly="True" CanUserAddRows="False"  CanUserDeleteRows="False"  IsManipulationEnabled="True"  CanUserResizeColumns="False" ItemsSource="{Binding TrackingTable}" ColumnHeaderStyle="{DynamicResource dataGridColumnStyle}"  Style="{DynamicResource dataGridStyle}"  EnableColumnVirtualization="True"  IsEnabled="True" BorderThickness="0" CellStyle="{DynamicResource CellStyleBase}" VerticalGridLinesBrush="#FFA0A7AD"  RowHeight="30" MinRowHeight="20" GridLinesVisibility="None" SelectionMode="Single" Grid.Row="1" Grid.ColumnSpan="10" Panel.ZIndex="4" MinHeight="30" Loaded="TrackingDataGrid_Loaded" CanUserReorderColumns="False" VerticalScrollBarVisibility="Disabled" ScrollViewer.CanContentScroll="True">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Process Time" IsReadOnly="True"  Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock   Text="{Binding DeliveryDate}" TextTrimming="CharacterEllipsis" >
                        <TextBlock.ContextMenu>
                            <ContextMenu>
                                <MenuItem x:Name="StandbyProcessMenuITem" Header="StandBy Process" Click="StandbyProcessMenuITem_Click" >
                                    <!--<MenuItem.Visibility>
                                            <MultiBinding Converter="{StaticResource RowUndoButtonVisibility}">
                                                <Binding Path="ProductIsStandby" />
                                                <Binding Path="ProductIsDone" />
                                            </MultiBinding>
                                        </MenuItem.Visibility>-->
                                </MenuItem>
                                <MenuItem x:Name="UndoProcessMenuITem" Header="Undo Process" Click="UndoProcessMenuITem_Click" >
                                    <MenuItem.Visibility>
                                        <MultiBinding Converter="{StaticResource RowUndoButtonVisibility}">
                                            <Binding Path="{Binding ProductIsStandby}" />
                                            <Binding Path="{Binding ProductIsDone}" />
                                        </MultiBinding>
                                    </MenuItem.Visibility>
                                </MenuItem>
                                <MenuItem x:Name="FinishProcessMenuITem" Header="Finish Process" Click="FinishProcessMenuITem_Click">
                                </MenuItem>
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

答:
The DataContext of a MenuItem is not the same as the DataContext of the CellTemplate but you could use a RelativeSource to bind to the PlacementTarget of the ContextMenu:

```<code><MenuItem x:Name="UndoProcessMenuITem" Header="Undo Process" Click="UndoProcessMenuITem_Click" >
    <MenuItem.Visibility>
        <MultiBinding Converter="{StaticResource RowUndoButtonVisibility}">
            <Binding Path="{Binding PlacementTarget.DataContext.ProductIsStandby, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
            <Binding Path="{Binding PlacementTarget.DataContext.ProductIsDone, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
        </MultiBinding>
    </MenuItem.Visibility>
</MenuItem>
</code>```

Body:
I have a datagrid which gets its data out of a datatable like
Inside if there is a textbox with a contextmenu and this contextmenu has a converter (with multibinding)
The problem is i datatable the binded data has 1 or 0 as data but in the converter i get UnsetValue.
This is the xaml code:

<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch"  VirtualizingStackPanel.VirtualizationMode="Recycling" VirtualizingStackPanel.IsVirtualizing="True"  Margin="0,1,0,0" x:Name="TrackingDataGrid" IsReadOnly="True" CanUserAddRows="False"  CanUserDeleteRows="False"  IsManipulationEnabled="True"  CanUserResizeColumns="False" ItemsSource="{Binding TrackingTable}" ColumnHeaderStyle="{DynamicResource dataGridColumnStyle}"  Style="{DynamicResource dataGridStyle}"  EnableColumnVirtualization="True"  IsEnabled="True" BorderThickness="0" CellStyle="{DynamicResource CellStyleBase}" VerticalGridLinesBrush="#FFA0A7AD"  RowHeight="30" MinRowHeight="20" GridLinesVisibility="None" SelectionMode="Single" Grid.Row="1" Grid.ColumnSpan="10" Panel.ZIndex="4" MinHeight="30" Loaded="TrackingDataGrid_Loaded" CanUserReorderColumns="False" VerticalScrollBarVisibility="Disabled" ScrollViewer.CanContentScroll="True">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Process Time" IsReadOnly="True"  Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock   Text="{Binding DeliveryDate}" TextTrimming="CharacterEllipsis" >
                        <TextBlock.ContextMenu>
                            <ContextMenu>
                                <MenuItem x:Name="StandbyProcessMenuITem" Header="StandBy Process" Click="StandbyProcessMenuITem_Click" >

                                </MenuItem>
                                <MenuItem x:Name="UndoProcessMenuITem" Header="Undo Process" Click="UndoProcessMenuITem_Click" >
                                    <MenuItem.Visibility>
                                        <MultiBinding Converter="{StaticResource RowUndoButtonVisibility}">
                                            <Binding Path="{Binding ProductIsStandby}" />
                                            <Binding Path="{Binding ProductIsDone}" />
                                        </MultiBinding>
                                    </MenuItem.Visibility>
                                </MenuItem>
                                <MenuItem x:Name="FinishProcessMenuITem" Header="Finish Process" Click="FinishProcessMenuITem_Click">
                                </MenuItem>
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Body:
The DataContext of a MenuItem is not the same as the DataContext of the CellTemplate but you could use a RelativeSource to bind to the PlacementTarget of the ContextMenu:

<MenuItem x:Name="UndoProcessMenuITem" Header="Undo Process" Click="UndoProcessMenuITem_Click" >
    <MenuItem.Visibility>
        <MultiBinding Converter="{StaticResource RowUndoButtonVisibility}">
            <Binding Path="{Binding PlacementTarget.DataContext.ProductIsStandby, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
            <Binding Path="{Binding PlacementTarget.DataContext.ProductIsDone, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
        </MultiBinding>
    </MenuItem.Visibility>
</MenuItem>


问:
How to listen to when elements with a certain are show() or hide() in jquery?
I have a number of elements on the a page which are hidden by default. Depending on a user behaviour, one might be shown (using jquery's show()). Similar, one might be hidden (using jquery's hide()).

All these elements have the same css class. Is there a way to create a listener for elements with a specific class to see if any of them have changed between hide/show?

Thanks!

答:
To directly answer your question, no there is no built in way, but we can achieve this through custom .on's and .trigger's.

isVisibleList = [];
setInterval(function() {
  for (var i = 0, len = isVisibleList.length; i < len; i++) {
    if (isVisibleList[i].is(":visible") != isVisibleList[i].data("wasVisible")) {
      isVisibleList[i].data("wasVisible", !isVisibleList[i].data("wasVisible"));
      if (isVisibleList[i].is(":visible")) {
        isVisibleList[i].trigger("show");
      } else {
        isVisibleList[i].trigger("hide");
      }
    }
  }
}, 500);

$("#test").hide();
$("#test").data("wasVisible", false);
isVisibleList.push($("#test"));

$("#toggle").click(function() {
  $("#test").toggle();
});

$("#test").on("show", function() {
  console.log("shown");
});

$("#test").on("hide", function() {
  console.log("hidden");
});```
<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>
<button id="toggle">Test toggle</button>
<div id="test">test</div></code>```

Body:
To directly answer your question, no there is no built in way, but we can achieve this through custom .on's and .trigger's.

isVisibleList = [];
setInterval(function() {
  for (var i = 0, len = isVisibleList.length; i < len; i++) {
    if (isVisibleList[i].is(":visible") != isVisibleList[i].data("wasVisible")) {
      isVisibleList[i].data("wasVisible", !isVisibleList[i].data("wasVisible"));
      if (isVisibleList[i].is(":visible")) {
        isVisibleList[i].trigger("show");
      } else {
        isVisibleList[i].trigger("hide");
      }
    }
  }
}, 500);

$("#test").hide();
$("#test").data("wasVisible", false);
isVisibleList.push($("#test"));

$("#toggle").click(function() {
  $("#test").toggle();
});

$("#test").on("show", function() {
  console.log("shown");
});

$("#test").on("hide", function() {
  console.log("hidden");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">Test toggle</button>
<div id="test">test</div>


问:
Amazon EC2, elastic beanstalk, need static outbound IP's
I need to integrate with a service, that needs to know my IP's in advance to whitelist them, my app is hosted on EBS amazon with autoscaling.

Is this possible?

Here is what my current config file looks like.

```<code>Resources:
  # LB SG
  AWSEBLoadBalancerSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "443", ToPort: "443"}

  # CONFIGURE LB Health Check different port

  # EB SG
  AWSEBSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "443", ToPort: "443"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "22", ToPort: "22"}

option_settings:
  aws:elb:listener:80:
    ListenerProtocol: HTTP
    InstancePort: 80
    InstanceProtocol: HTTP
  aws:elb:listener:443:
    ListenerProtocol: TCP
    InstancePort: 443
    InstanceProtocol: TCP
</code>```

To make this easy, can i somehow reserve a range of IP's and make EBS prefer them when launching a new instance ?

答:
Since your instances are subject to being created or destroyed dynamically, you can't depend on their IPs remaining the same, whether you use Elastic IPs or not.

The right solution is to route your outgoing traffic through a NAT. You can find more information about how to design and implement a NAT at http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat.html.

Body:
I need to integrate with a service, that needs to know my IP's in advance to whitelist them, my app is hosted on EBS amazon with autoscaling.

Is this possible?

Here is what my current config file looks like.

Resources:
  # LB SG
  AWSEBLoadBalancerSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "443", ToPort: "443"}

  # CONFIGURE LB Health Check different port

  # EB SG
  AWSEBSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "443", ToPort: "443"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "22", ToPort: "22"}

option_settings:
  aws:elb:listener:80:
    ListenerProtocol: HTTP
    InstancePort: 80
    InstanceProtocol: HTTP
  aws:elb:listener:443:
    ListenerProtocol: TCP
    InstancePort: 443
    InstanceProtocol: TCP

To make this easy, can i somehow reserve a range of IP's and make EBS prefer them when launching a new instance ?


问:
How to access (copy) specific elements of Mat in OpenCV?
Let's say I have a matrix of single row x. In MATLAB, I can access specific elements of x via

```<code>x=[10 6 9 12 15 20 22];
index=[1 3 7];
y=x(index)
y =
    10     9    22
</code>```

How can I do the same in OpenCV (without for loop)?

I know there are ways to access rows or columns of the matrix, but I couldn't find a way to access only specific elements in OpenCV.

Edit:

I am using C++. What if x is NxM matrix and I want to access some elements in the 5th column. In MATLAB, I can do it as x(index,5). I can sure do it with for loops in OpenCV. My question is, is there any ready OpenCV function that returns me the specific elements of x?

答:
You can retrieve a cv::Mat containing the values by index by using the same mechanism as cv::sortIdx  see Sorting cv::Mat in OpenCv

ie if you have a cv::Mat containing the indices you can pass this to the cv::Mat containing the data and get back that subset.

Body:
Let's say I have a matrix of single row x. In MATLAB, I can access specific elements of x via

x=[10 6 9 12 15 20 22];
index=[1 3 7];
y=x(index)
y =
    10     9    22

How can I do the same in OpenCV (without for loop)?

I know there are ways to access rows or columns of the matrix, but I couldn't find a way to access only specific elements in OpenCV.

Edit:

I am using C++. What if x is NxM matrix and I want to access some elements in the 5th column. In MATLAB, I can do it as x(index,5). I can sure do it with for loops in OpenCV. My question is, is there any ready OpenCV function that returns me the specific elements of x?


问:
Building an app made with Intel-xdk with Cordova Cli
I'm evaluating Intel-xdk, the idea is using this tool in my IT classes (people from 15 to 18 y.o.), I'm on Ubuntu 16.04 and installed XDK 3759 Linux 32.
A couple of days ago, as I installed an update I also installed nodejs, npm and cordova because as far as june Xdk will no more provide the cloud build service, anyway, after installing android sdk tools, build tools and platform tools, when I try to compile a simple project I've got this error

Error: /home/prof/prova-xdk/platforms/android/gradlew: Command failed with exit code 1 Error output:
/home/prof/android-sdk/build-tools/25.0.2/aapt: 3: /home/prof/android-sdk/build-tools/25.0.2/aapt: Syntax error: Unterminated quoted string

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':CordovaLib:processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

Can someone please explain me the error? May I check my code? But which file? Thanks everybody! Alessandro

答: I recommend you update to 3900 (hotfix coming very soon to address login and several other issues) and use the "Cordova export" feature to build apps. The ZIP that is generated by that export can be provided directly to PhoneGap Build, using the one free private slot. This will be a much simpler build process than having your students install node, Cordova CLI and the Android build tools.</p>


问:
Radio button onchange function not working if radio is checked directly by link parameter
A Radio Button runs a onchange jQuery function when we click on it. But if we directly check this same radio button by a link parameter, the function is not called. Please, how to solve this? I've tried changing onchange to onclick without success.

Page I'm working on: Once any Store is manually selected, the onchange function will hide the Store DIV and show the Category DIV, simulating a step filter. http://www.hotsales.com.br/procurar/

This is the direct link parameter to automatically select some Store. But this way, the onchange function doesn't run, so the Store DIV is still visible and the Category DIV still hidden. http://www.hotsales.com.br/procurar/?offer_store=852

This is the first function that should run when Store is selected (both manually or by direct link).

```<code>/* AJAX SEARCH*/
$(document).on( 'change', '.advanced-search input', function(){

start_ajax_search3();

    $.ajax({
        url: $('.advanced-search').attr('action'),
        data: $('.advanced-search').serialize(),
        success: function( response ){
            handle_ajax_search_response( response ); /*this function hide/show desired DIV*/
        },
        complete: function(){
            end_ajax_search();
        }
    });
});
</code>```

This is how the DIVs are hidden/showed:

```<code>function handle_ajax_search_response( response ){
    var $response = $('<div>'+response+'</div>');
    $('.ajax-results').html( $response.find('.ajax-results').html() );
    $('.ajax-sidebar').html( $response.find('.ajax-sidebar').html() );
    $('.category-filter').show();
    $('.store-filter').hide();
    $('.offer-type-filter').show();}
</code>```

答:
You could call your function on change and on document ready, ex:

function test(chk){
  console.log("called by" + $(chk).attr("id"));
}

$(document).ready(function(){
  if($("#chkTest2").is(":checked")){
    test($("#chkTest2"));
  }
});

$(".chkboxes").on( 'change', function(){
  test(this);
 });```
<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>
<input class="chkboxes" type="checkbox" id="chkTest1">Test 1
<input class="chkboxes" type="checkbox" id="chkTest2" checked="checked"> Test 2</code>```

I hope it helps you, bye.

Body:
A Radio Button runs a onchange jQuery function when we click on it. But if we directly check this same radio button by a link parameter, the function is not called. Please, how to solve this? I've tried changing onchange to onclick without success.

Page I'm working on: Once any Store is manually selected, the onchange function will hide the Store DIV and show the Category DIV, simulating a step filter. http://www.hotsales.com.br/procurar/

This is the direct link parameter to automatically select some Store. But this way, the onchange function doesn't run, so the Store DIV is still visible and the Category DIV still hidden. http://www.hotsales.com.br/procurar/?offer_store=852

This is the first function that should run when Store is selected (both manually or by direct link).

/* AJAX SEARCH*/
$(document).on( 'change', '.advanced-search input', function(){

start_ajax_search3();

    $.ajax({
        url: $('.advanced-search').attr('action'),
        data: $('.advanced-search').serialize(),
        success: function( response ){
            handle_ajax_search_response( response ); /*this function hide/show desired DIV*/
        },
        complete: function(){
            end_ajax_search();
        }
    });
});

This is how the DIVs are hidden/showed:

function handle_ajax_search_response( response ){
    var $response = $('
'+response+'
');
    $('.ajax-results').html( $response.find('.ajax-results').html() );
    $('.ajax-sidebar').html( $response.find('.ajax-sidebar').html() );
    $('.category-filter').show();
    $('.store-filter').hide();
    $('.offer-type-filter').show();}

Body:
You could call your function on change and on document ready, ex:

function test(chk){
  console.log("called by" + $(chk).attr("id"));
}

$(document).ready(function(){
  if($("#chkTest2").is(":checked")){
    test($("#chkTest2"));
  }
});

$(".chkboxes").on( 'change', function(){
  test(this);
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="chkboxes" type="checkbox" id="chkTest1">Test 1
<input class="chkboxes" type="checkbox" id="chkTest2" checked="checked"> Test 2

I hope it helps you, bye.


问:
Swift equivalent of C#'s IsAssignableFrom
In C#, given two types, I can say something like

```<code>var stringType = typeof(string)
var intType = typeof(int)
var assignable = stringType.IsAssignableFrom(intType)
</code>```

The value of assignable would be false since an int cannot be assigned to a string.

Is there any way to do this in Swift?

```<code>func isAssignable<T1, T2>(_ type1: T1.Type, from type2: T2.Type) -> Bool {
    // What's the implementation here?
}

let assignable = isAssignable(String.self, from: Int.self)
</code>```

My suspicion is that this is not currently possible.

Why do I need this?

Some have asked why I need this. I've written a dependency resolution framework called Guise. Each registration returns a unique Key. While it's actually unusual to use the Key for resolution—there are more elegant ways—there are times when it is useful, such as when resolving multiple registrations.

In the code below, look at the line that says if type != key.type { continue }. This just compares the reflected string representations of the registered types. It would be a lot more useful if instead I could test assignability directly, so that the generic parameter T would not have to be the specific type under which the registration was made. Something like if !key.typeIsAssignableTo(type: T.self) { continue }. Where typeIsAssignableTo is a thunk over the type in Key.

At this point I don't have an instance and don't want one. In fact, that's the whole point. Any good DR framework should resolve lazily, and this one does. I don't want to have to create an instance first before testing type compatibility.

```<code>public static func resolve<T, K: Sequence>(keys: K, parameter: Any = (), cached: Bool? = nil) -> [T] where K.Iterator.Element == Key {
    return lock.read {
        let type = String(reflecting: T.self)
        var resolutions = [T]()
        for (key, dependency) in registrations {
            if type != key.type { continue }
            if !keys.contains(key) { continue }
            resolutions.append(dependency.resolve(parameter: parameter, cached: cached))
        }
        return resolutions
    }
}
</code>```

Probably clear as mud, but that's the best explanation I can give.

答:
Not exactly, if you tried to construct an object from another and it was not compatible the Swift way would be to return nil.
So you could have your scenario like so:

let assignable = Int(text: stringElement)

In this case, you would have an optional Int, because there is a chance that a string may not be convertible to an int.

Body:
In C#, given two types, I can say something like

var stringType = typeof(string)
var intType = typeof(int)
var assignable = stringType.IsAssignableFrom(intType)

The value of assignable would be false since an int cannot be assigned to a string.

Is there any way to do this in Swift?

func isAssignable<T1, T2>(_ type1: T1.Type, from type2: T2.Type) -> Bool {
    // What's the implementation here?
}

let assignable = isAssignable(String.self, from: Int.self)

My suspicion is that this is not currently possible.

Why do I need this?

Some have asked why I need this. I've written a dependency resolution framework called Guise. Each registration returns a unique Key. While it's actually unusual to use the Key for resolution—there are more elegant ways—there are times when it is useful, such as when resolving multiple registrations.

In the code below, look at the line that says if type != key.type { continue }. This just compares the reflected string representations of the registered types. It would be a lot more useful if instead I could test assignability directly, so that the generic parameter T would not have to be the specific type under which the registration was made. Something like if !key.typeIsAssignableTo(type: T.self) { continue }. Where typeIsAssignableTo is a thunk over the type in Key.

At this point I don't have an instance and don't want one. In fact, that's the whole point. Any good DR framework should resolve lazily, and this one does. I don't want to have to create an instance first before testing type compatibility.

public static func resolve<T, K: Sequence>(keys: K, parameter: Any = (), cached: Bool? = nil) -> [T] where K.Iterator.Element == Key {
    return lock.read {
        let type = String(reflecting: T.self)
        var resolutions = [T]()
        for (key, dependency) in registrations {
            if type != key.type { continue }
            if !keys.contains(key) { continue }
            resolutions.append(dependency.resolve(parameter: parameter, cached: cached))
        }
        return resolutions
    }
}

Probably clear as mud, but that's the best explanation I can give.


问:
Purpose of "with" methods in class
I'm looking at class called Product which includes the following:

```<code>@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}
</code>```

what is the purpose of the withName method and how is it used? Why not just do:

```<code>Product p = new Product();
p.setName("foo");
</code>```

答:
It is used to get a reference to an object by its name so that method call can be chained with other calls on same object.

Example: withName(String name)

Title: Purpose of "with" methods in class

Body:
I'm looking at class called Product which includes the following:

@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}

what is the purpose of the withName method and how is it used? Why not just do:

Product p = new Product();
p.setName("foo");


问:
How to export sql to PDF in php, I have generate an error
How to fix this error to export sql to PDF. I have generated an error. Can someone provide me with the example code

<?php
define('path','fpdf/font/');
require('fpdf/fpdf.php');
include 'connection.php';
$pdf=new FPDF();
$pdf->Open();
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();
$y_axis_initial = 25;
$pdf->SetFillColor(232, 232, 232);
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetY($y_axis_initial);
$pdf->SetX(25);
$pdf->Cell(30,6,'Complaint',1,0,'L',1);
$pdf->Cell(30,6,'Date',1,0,'L',1);
$pdf->Cell(30,6,'Text',1,0,'L',1);
$pdf->Cell(30,6,'Polar words',1,0,'L',1);
$pdf->Cell(30,6,'Source',1,0,'L',1);
$pdf->Cell(30,6,'Company id',1,0,'R',1);
$y_axis = $y_axis + $row_height;
$fromdate=$_REQUEST['i_name'];
$todate=$_REQUEST['s_name'];
$fromdate=$_REQUEST['address'];
$todate=$_REQUEST['city'];
$fromdate=$_REQUEST['contact'];
$result=mysqli_query($con,"SELECT i_name,s_name,address,city,contact FROM s_reg WHERE limit='1'") or die(mysql_error());
$i = 0;
$max = 25;
$row_height = 6;
while($row = mysqli_fetch_array($result))
{
  if ($i == $max)
  {
    $pdf->AddPage();
    $pdf->SetY($y_axis_initial);
    $pdf->SetX(25);
    $pdf->Cell(30,6,'i_name',1,0,'L',1);
    $pdf->Cell(30,6,'s_name',1,0,'L',1);
    $pdf->Cell(30,6,'address',1,0,'L',1);
    $pdf->Cell(30,6,'city',1,0,'L',1);
    $pdf->Cell(30,6,'contact',1,0,'L',1);
    $y_axis = $y_axis + $row_height;
    $i = 0;
  }
  $complainant = $row['i_name'];
  $date = $row['s_name'];
  $complainttext = $row['address'];
  $complainttitle = $row['city'];
  $polarwords = $row['contact'];
  $pdf->SetY($y_axis);
  $pdf->SetX(25);
  $pdf->Cell(30, 6, $i_name, 1, 0, 'L', 1);
  $pdf->Cell(30, 6, $s_name, 1, 0, 'L', 1);
  $pdf->Cell(30, 6, $address, 1, 0, 'L', 1);
  $pdf->Cell(30, 6, $city, 1, 0, 'L', 1);
  $pdf->Cell(30, 6, $contact, 1, 0, 'L', 1);
  $y_axis = $y_axis + $row_height;
  $i = $i + 1;
}

$pdf->Output('report.pdf','F');

if($pdf->Output('report.pdf','F'))
{
  echo "Report Created Successfyully CLick to view";
}
else
{
  echo "failed to create Report";
}

$pdf->Output();
?>
```

答:
You need to tell us what the error is. One thing I can see, though, is that at the end of the code you've got

```<code>$pdf->Output('report.pdf','F');

if($pdf->Output('report.pdf','F'))
{
   ...
</code>```

So you're calling the Output function twice.

If I were you I'd go to the fpdf documentation and work through the examples slowly, adapting them until you get what you want.

Body:
You need to tell us what the error is. One thing I can see, though, is that at the end of the code you've got

$pdf->Output('report.pdf','F');

if($pdf->Output('report.pdf','F'))
{
   ...

So you're calling the Output function twice.

If I were you I'd go to the fpdf documentation and work through the examples slowly, adapting them until you get what you want.


问:
Make highchart legends as a individual buttons
I need to make legends as buttons. It should be separate button.

I have tried following styles but it gives whole section as a button

```<code> legend: {
                enabled: true,
                backgroundColor: '#29a2c6',
                borderRadius:3,
                symbolWidth:30
            },
</code>```

But i need like

答:
The Highcharts API lets you customize the item's legend styles in two ways:

Using itemStyle with some CSS restrictions:

Only a subset of CSS is supported, notably those options related to text. Defaults to { "color": "#333333", "cursor": "pointer", "fontSize": "12px", "fontWeight": "bold" }.

or

Using both useHTML and labelFormat

```<code>legend: {
    useHTML: true,
    labelFormat: '<span class="span-legend-item">{name}</span>'
},
</code>```

and setting your styles in a separeted CSS Class

```<code>.span-legend-item {
    background-color: #666;
    color: #fff;
}
</code>```

jsfiddle here

This maybe is not exactly what you are looking for. But It could be a good starting point.

Body:
I need to make legends as buttons. It should be separate button.

I have tried following styles but it gives whole section as a button

 legend: {
                enabled: true,
                backgroundColor: '#29a2c6',
                borderRadius:3,
                symbolWidth:30
            },

But i need like

Body:
The Highcharts API lets you customize the item's legend styles in two ways:

Using itemStyle with some CSS restrictions:

Only a subset of CSS is supported, notably those options related to text. Defaults to { "color": "#333333", "cursor": "pointer", "fontSize": "12px", "fontWeight": "bold" }.

or

Using both useHTML and labelFormat

legend: {
    useHTML: true,
    labelFormat: '<span class="span-legend-item">{name}</span>'
},

and setting your styles in a separeted CSS Class

.span-legend-item {
    background-color: #666;
    color: #fff;
}

jsfiddle here

This maybe is not exactly what you are looking for. But It could be a good starting point.


问:
Injecting Single Instance HttpClient with specific HttpMessageHandler
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

```<code>private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};
</code>```

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

答:
Adding to the conversation from the comments looks like you would need a HttpClient factory

```<code>public interface IHttpClientFactory {
    HttpClient Create(string endpoint);
}
</code>```

and the implementation of the core functionality could look something like this.

public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
    private readonly ConcurrentDictionary<string, HttpClient> _httpClients;

    public DefaultHttpClientFactory()
    {
        this._httpClients = new ConcurrentDictionary<string, HttpClient>();
    }

    public HttpClient Create(string endpoint)
    {
        if (this._httpClients.TryGetValue(endpoint, out var client))
        {
            return client;
        }

        client = new HttpClient
        {
            BaseAddress = new Uri(endpoint),
        };

        this._httpClients.TryAdd(endpoint, client);

        return client;
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        foreach (var httpClient in this._httpClients)
        {
            httpClient.Value.Dispose();
        }
    }
}
```

That said, if you are not particularly happy with the above design. You could abstract away the HttpClient dependency behind a service so that the client does not become an implementation detail.

That consumers of the service need not know exactly how the data is retrieved.

Body:
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

Body:
Adding to the conversation from the comments looks like you would need a HttpClient factory

public interface IHttpClientFactory {
    HttpClient Create(string endpoint);
}

and the implementation of the core functionality could look something like this.

public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
    private readonly ConcurrentDictionary<string, HttpClient> _httpClients;

    public DefaultHttpClientFactory()
    {
        this._httpClients = new ConcurrentDictionary<string, HttpClient>();
    }

    public HttpClient Create(string endpoint)
    {
        if (this._httpClients.TryGetValue(endpoint, out var client))
        {
            return client;
        }

        client = new HttpClient
        {
            BaseAddress = new Uri(endpoint),
        };

        this._httpClients.TryAdd(endpoint, client);

        return client;
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        foreach (var httpClient in this._httpClients)
        {
            httpClient.Value.Dispose();
        }
    }
}

That said, if you are not particularly happy with the above design. You could abstract away the HttpClient dependency behind a service so that the client does not become an implementation detail.

That consumers of the service need not know exactly how the data is retrieved.


问:
How to import Chart.js with Webpack
I have a Vue JS project using Webpack and need to import Chart.js. I have tried

```<code>// import Chart from 'chart.js/Chart.min.js'
</code>```

This gives js errors when trying to use the library.

答:
As seen on this issue, if you use Angular CLI you only need to add this to the scripts array in angular-cli.json:

```<code>"../node_modules/chart.js/dist/Chart.bundle.min.js"
</code>```

Restart your application, live reload won't do the trick.

Title: How to import Chart.js with Webpack

Body:
I have a Vue JS project using Webpack and need to import Chart.js. I have tried

// import Chart from 'chart.js/Chart.min.js'

This gives js errors when trying to use the library.

Body:
As seen on this issue, if you use Angular CLI you only need to add this to the scripts array in angular-cli.json:

"../node_modules/chart.js/dist/Chart.bundle.min.js"

Restart your application, live reload won't do the trick.


问:
autocomplete plugin loading icon sometimes dosent stop spinning when it should
I'm working with the autocomplete plugin from Jquery UI. I have a small graphic that spins, everything works fine as long as a match is found and selected. My problem is that if no results are found or the focus moves the graphic still is visible and spins. If no results are found it also just keeps spinning and the not found message is never displayed.

Code is below, any help would be appreciated.

var _autocomp = {
            source: function(request, response, event) {

                var url = "@Url.Content("~/Jobs/Users")";
                $.getJSON(url, { prefixText: request.term }, function(data) {
                    $.each(data, function(i, Profile) {

                        response($.map(data, function(Profile) {
                            var name = Profile.ID + " - " + Profile.Name;
                            return {
                                label: name,
                                value: Profile.ID
                            };
                        }));
                    });

                });

            },

            minLength: 3,
            delay: 50,
            error:function() {
                $(this).removeClass('loader');
            },
            failure: function() {
                $(this).removeClass('loader');
            },
            select: function(event, ui) {
                this.value = ui.item.label;
                event.preventDefault();
                $(this).removeClass('loader');
            },
            response: function(event, ui) {
                if (ui.content.length === 0) {
                    $(this).text("No results found");
                } else {
                    $(this).empty();
                }

            },
            search: function (e, u) {
                $(this).addClass('loader');
            },
            open:function() {
                $(this).removeClass('loader');
            },
            change: function(event, ui) {
                if (!ui.item) {

                    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                        valid = false;

                    $('.employeeAutoComp').children("option").each(function () {

                        if ($(this).text().match(matcher)) {
                            this.selected = valid = true;
                            return false;
                        }
                    });
                    if (!valid) { // remove invalid value, as it didn't match anything
                        $(this).val("");
                        $('.employeeAutoComp').val("");
                        //input.data("autocomplete").term = "";
                        return false;
                    }

                }
            }
        };

        $('.employeeAutoComp').autocomplete(_autocomp);```
<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></code>```

答: Try remove class "loader" and display message in complete() method. I found if there is no results match, complete method is called. I have a similar issue please see jQuery UI ui-autocomplete-loading spinner not stopping/disappear when found results</p>


问:
How to create a macro in VBA that can automatically determine the boundaries of a matrix
I've started programing in VBA yesterday, and as such I am still quite the newbie at it.

I've tried to make a macro that automatically defines certain areas for me, and while it works quite well in my sheet, it is still limited in the sense that all sheets I use it on have to be identical in setup.

I am currently defining 5 areas

A_mål - Single Cell

Tank_Tabel - Matrix

Int_Tabel - Matrix

Bund - Single Cell

HF - Single Cell

The optimal macro for my problem would be one that prompts the user to enter a number of a container, and then uses that number to automatically determine what sheet the information of said container can be found on, and the automatically determine where the listed areas are, and define them with the given names and the number that the user has entered.

The code can be seen here:

```<code>Option Compare Text
Sub Definer()
    Dim TankNr As Integer, rHF As Range, rAM As Range, rBV As Range, rTT As Range, rIT As Range

    If MsgBox("Vil du definere nye områder for en tank", vbYesNo, "Confirm") = vbYes Then

        TankNr = Application.InputBox("Indtast tank nr på den tank du vil definere områder for", "Tank Nummer", Type:=1)
        If TankNr <> 0 Then

            Set rHF = Sheets("Tank " & TankNr).Cells.Find(What:="HØJESTE FYLDEGRÆNSE =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rHF Is Nothing Then
                rHF.Offset(, 3).Name = "HF_" & TankNr
            End If

            Set rTT = Sheets("Tank " & TankNr).Cells.Find(What:="Enhed i tabellen : Liter", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rTT Is Nothing Then
                rTT.CurrentRegion.Offset(2, 0).Resize(rTT.CurrentRegion.Rows.Count - 2).Name = "Tabel_tank" & TankNr
            End If

            Set rIT = Sheets("Tank " & TankNr).Cells.Find(What:="Interpolationstabel", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rIT Is Nothing Then
                rIT.Resize(11, 11).Offset(1, 0).Name = "Int_tank" & TankNr
            End If

            Set rBV = Sheets("Tank " & TankNr).Cells.Find(What:="Bundvolumen =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rBV Is Nothing Then
                rBV.Offset(, 2).Name = "Bund" & TankNr
            End If

            Set rAM = Sheets("Tank " & TankNr).Cells.Find(What:="A-MÅL =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rAM Is Nothing Then
                rAM.Offset(, 1).Name = "A_mål" & TankNr
            End If

            MsgBox "Områder er blevet defineret"

        End If
    End If
End Sub
</code>```

There are several problems with this:

If the user enters a non integer in the input box, the code ends up with an error, rather than just ending the macro. Solved

If the user hits cancel in the input box, the code also ends up with an error rather than ending the macro. Solved

I tried to use the input "TankNr" as a reference, but it doesn't return the value of the cell, but just what I've written as the reference Solved

Finally, the current boundaries of each defined area is determined by me manually, and it works fine if the values I am looking for is actually in those specific cells. Sometimes the setup of the sheets might vary, and as such I need the macro to be able to automatically determine where the boundaries of the defined areas should be  Solved

The sheets in question can be seen

Due to my reputation, I can only include these two links, but if there's a way to provide more documentation of my work, tell me and I'll happily do so.

答:
Here's the approach I would use. It's only an example, for HF, but hopefully you get the idea and can extend to the other ranges. I've assumed the named range is the cell to the right of the one containing "HF".</p>

```<code>Sub OptimalSolution()

Dim TankNr As Integer, rHF As Range

If MsgBox("Do you wish to define new areas for a container?", vbYesNo, "Confirm") = vbYes Then
    TankNr = Application.InputBox("Please enter the container number", "Container Number", , , , , , 1)
    Set rHF = Sheets("Ark" & TankNr).Cells.Find(What:="HF", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)
    If Not rHF Is Nothing Then
        rHF.Offset(, 1).Name = "HF_" & TankNr
    End If
End If

End Sub
</code>```

Body:
I've started programing in VBA yesterday, and as such I am still quite the newbie at it.

I've tried to make a macro that automatically defines certain areas for me, and while it works quite well in my sheet, it is still limited in the sense that all sheets I use it on have to be identical in setup.

I am currently defining 5 areas

A_mål - Single Cell

Tank_Tabel - Matrix

Int_Tabel - Matrix

Bund - Single Cell

HF - Single Cell

The optimal macro for my problem would be one that prompts the user to enter a number of a container, and then uses that number to automatically determine what sheet the information of said container can be found on, and the automatically determine where the listed areas are, and define them with the given names and the number that the user has entered.

The code can be seen here:

Option Compare Text
Sub Definer()
    Dim TankNr As Integer, rHF As Range, rAM As Range, rBV As Range, rTT As Range, rIT As Range

    If MsgBox("Vil du definere nye områder for en tank", vbYesNo, "Confirm") = vbYes Then

        TankNr = Application.InputBox("Indtast tank nr på den tank du vil definere områder for", "Tank Nummer", Type:=1)
        If TankNr <> 0 Then

            Set rHF = Sheets("Tank " & TankNr).Cells.Find(What:="HØJESTE FYLDEGRÆNSE =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rHF Is Nothing Then
                rHF.Offset(, 3).Name = "HF_" & TankNr
            End If

            Set rTT = Sheets("Tank " & TankNr).Cells.Find(What:="Enhed i tabellen : Liter", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rTT Is Nothing Then
                rTT.CurrentRegion.Offset(2, 0).Resize(rTT.CurrentRegion.Rows.Count - 2).Name = "Tabel_tank" & TankNr
            End If

            Set rIT = Sheets("Tank " & TankNr).Cells.Find(What:="Interpolationstabel", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rIT Is Nothing Then
                rIT.Resize(11, 11).Offset(1, 0).Name = "Int_tank" & TankNr
            End If

            Set rBV = Sheets("Tank " & TankNr).Cells.Find(What:="Bundvolumen =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rBV Is Nothing Then
                rBV.Offset(, 2).Name = "Bund" & TankNr
            End If

            Set rAM = Sheets("Tank " & TankNr).Cells.Find(What:="A-MÅL =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rAM Is Nothing Then
                rAM.Offset(, 1).Name = "A_mål" & TankNr
            End If

            MsgBox "Områder er blevet defineret"

        End If
    End If
End Sub

There are several problems with this:

If the user enters a non integer in the input box, the code ends up with an error, rather than just ending the macro. Solved

If the user hits cancel in the input box, the code also ends up with an error rather than ending the macro. Solved

I tried to use the input "TankNr" as a reference, but it doesn't return the value of the cell, but just what I've written as the reference Solved

Finally, the current boundaries of each defined area is determined by me manually, and it works fine if the values I am looking for is actually in those specific cells. Sometimes the setup of the sheets might vary, and as such I need the macro to be able to automatically determine where the boundaries of the defined areas should be  Solved

The sheets in question can be seen

Due to my reputation, I can only include these two links, but if there's a way to provide more documentation of my work, tell me and I'll happily do so.

Body:
Here's the approach I would use. It's only an example, for HF, but hopefully you get the idea and can extend to the other ranges. I've assumed the named range is the cell to the right of the one containing "HF".

Sub OptimalSolution()

Dim TankNr As Integer, rHF As Range

If MsgBox("Do you wish to define new areas for a container?", vbYesNo, "Confirm") = vbYes Then
    TankNr = Application.InputBox("Please enter the container number", "Container Number", , , , , , 1)
    Set rHF = Sheets("Ark" & TankNr).Cells.Find(What:="HF", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)
    If Not rHF Is Nothing Then
        rHF.Offset(, 1).Name = "HF_" & TankNr
    End If
End If

End Sub


问:
Can I add a wrapper to my layout that has a pure CSS dynamic sticky footer?
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

```<code><div class="wrapper">
    <header class="header"></header>
        <div class="content">
            <button>Click here to insert content into footer.</button>
        </div>
    <footer class="footer"></footer>
</div>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}
</code>```

答:
So all I did was slightly alter the CSS you had in your JSFiddle, and the reason why what you had didn't work was that you needed to apply the same structuring styles to the parent containers since they need to be the same.

To get the footer to stick to the bottom I just used the align-self flex property to position it at the end of the parent flex element.

Hopefully this will work for you.

```<code>html {
  position:relative;
  height:100%;
}
body,
.wrapper{
  height: 100%; /* this makes sure that the body matches the window and the wrapper matches the body. */
  display:-webkit-box;
  display:-webkit-flex;
  display:-ms-flexbox;
  display:flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column
}
body {
  position:relative;
  margin:0;
  padding:0;
  overflow-x:hidden;
  background-color:#eee;
}

.header {
  position:absolute;
  width:100%;
  height:55px;
  background-color:#fff;
}

.content {
  -webkit-box-flex:1;
  -webkit-flex:1;
  -ms-flex:1;
  flex:1;
  width:100%;
  height:auto;
  background-color:pink;
}

button {
  margin:65px 0 0 10px;
}

.footer {
  width: 100%;
  -webkit-align-self: flex-end;
  -ms-flex-item-align: end;
  align-self: flex-end; /* This puts it at the end of the parent flex element. */
  background-color:#fff;
  padding:25px 0;
}
</code>```

Body:
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

            <button>Click here to insert content into footer.</button>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}

Body:
So all I did was slightly alter the CSS you had in your JSFiddle, and the reason why what you had didn't work was that you needed to apply the same structuring styles to the parent containers since they need to be the same.

To get the footer to stick to the bottom I just used the align-self flex property to position it at the end of the parent flex element.

Hopefully this will work for you.

html {
  position:relative;
  height:100%;
}
body,
.wrapper{
  height: 100%; /* this makes sure that the body matches the window and the wrapper matches the body. */
  display:-webkit-box;
  display:-webkit-flex;
  display:-ms-flexbox;
  display:flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column
}
body {
  position:relative;
  margin:0;
  padding:0;
  overflow-x:hidden;
  background-color:#eee;
}

.header {
  position:absolute;
  width:100%;
  height:55px;
  background-color:#fff;
}

.content {
  -webkit-box-flex:1;
  -webkit-flex:1;
  -ms-flex:1;
  flex:1;
  width:100%;
  height:auto;
  background-color:pink;
}

button {
  margin:65px 0 0 10px;
}

.footer {
  width: 100%;
  -webkit-align-self: flex-end;
  -ms-flex-item-align: end;
  align-self: flex-end; /* This puts it at the end of the parent flex element. */
  background-color:#fff;
  padding:25px 0;
}