问:
Trigger VSTS pull request build verification based on path filter
We have a repository with multiple projects. For example, one is an Angular project for the frontend, the other is an Azure Function for the backend.

When code is pushed via pull request we have different builds that are triggered to verify the incoming changes.

However, all of the verification builds are always triggered, even though changes are made to a single project, which resides in a specific directory (For example, only Angular coder is changed, all of it is under /Frontend path).

There is one workaround I'm aware of - Splitting the repository in such way so there will be only a single project in each repository.

This workaround is not suitable for my needs.

Is there any other way to achieve this goal?

答:
It is now possible to do this using path filters for pull request policies.
See here: https://learn.microsoft.com/en-us/vsts/release-notes/2017/nov-28-vsts</p>


来源: stackexchange

问:
How to split cell array values into two columns in MATLAB?
I have data in a cell array as shown in the variable viewer here:

```<code>{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}
</code>```

I want to split it into two columns with two decimal-point numbers as:

```<code>2.13   56.95
1.98   50.41
</code>```

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

答:
you should use cell2mat

```<code>A={2.14,1.99;56.95,50.41};
B=cell2mat(A);
</code>```

As for the rounding, you can do:

```<code>B=round(100*B)/100;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have data in a cell array as shown in the variable viewer here:

{[2.13949546690144;56.9515770543056],
 [1.98550875192835;50.4110852121618],
 ...}

I want to split it into two columns with two decimal-point numbers as:

2.13   56.95
1.98   50.41

by removing opening and closing braces and semicolons such as [;]
(to do as like "Text to columns" in Excel).

Body:
you should use cell2mat

A={2.14,1.99;56.95,50.41};
B=cell2mat(A);

As for the rounding, you can do:

B=round(100*B)/100;


问:
MySQL connection via Android error
I have a little Problem with my Android Project.
I want to fill a list with data from my MySQL database, but android would not connect to it.

Here's my code:

MySQLConnector:

```<code>private static Connection con = null;

private static String dbHost = "85.214.101.213"; // changed the ip :)
private static String dbPort = "3306"; // Port -- Standard: 3306
private static String dbName = "ticketsystem"; // Datenbankname
private static String dbUser = "admin"; // Datenbankuser
private static String dbPass = "root"; // Datenbankpasswort

public static void conect() {
    try {
        Class.forName("com.mysql.jdbc.Driver"); // Datenbanktreiber für JDBC

        System.out.println("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);

        con = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);

    } catch (ClassNotFoundException e) {
        System.out.println("Treiber nicht gefunden");
    } catch (SQLException e) {
        System.out.println(e);
        System.out.println("Verbindung nicht moglich");
        System.out.println("SQLException: " + e.getMessage());
        System.out.println("SQLState: " + e.getSQLState());
        System.out.println("VendorError: " + e.getErrorCode());
    }

}
</code>```

SQLManager:

```<code>public SQLManager() {
    MySQLConnection.conect();
    Log.e("test", "nach conect");
    con = MySQLConnection.getCon();
}

public String[] getFreeEvents() {

    ArrayList<String> mList = new ArrayList();

    try
    {
        PreparedStatement ps = con.prepareStatement(" SELECT `EventID`,`Name`,`Zeit`,`Ort` FROM `event` WHERE `freeTickets` >= ?");

        ps.setInt(1, 0);
        ResultSet rs = ps.executeQuery();
        while (rs.next())
        {
            int EventID = rs.getInt("EventID");
            String Name = rs.getString("Name");
            String Zeit = rs.getString("Zeit");
            String Ort = rs.getString("Ort");

            String info = Name +"," + Zeit + ","+Ort  ;

            mList.add(info);
            System.out.println(info);
        }

    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }

    String[] array = mList.toArray(new String[0]);
    return array;
}
</code>```

And the Class form the Android activity:

```<code>Button b;
ListView list;
EditText vor;
TextView nach;
SQLManager man = new SQLManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_ticket);
    setContentView(R.layout.activity_main);
    b = findViewById(R.id.button);
    b.setOnClickListener(this);
    list = findViewById(R.id.list);
    list.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, man.getFreeEvents())); //here is the SQL request...
    vor = findViewById(R.id.editText);
    nach = findViewById(R.id.editText2);
}
</code>```

My probem is that Android could not open a connction.
I have added the Permission request in the Android Manifest:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

So at least I got this error:

```<code>I/System.out: `com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.´
I/System.out: Verbindung nicht moglich
I/System.out: SQLException: Could not create connection to database server.
I/System.out: SQLState: 08001
I/System.out: VendorError: 0
E/test: nach conect
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: ml.gottfried.myapp, PID: 10440
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{ml.gottfried.myapp/ml.gottfried.myapp.NewTicket}: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at ml.gottfried.myapp.SQLManager.getFreeEvents(SQLManager.java:82)
                      at ml.gottfried.myapp.NewTicket.onCreate(NewTicket.java:43)
                      at android.app.Activity.performCreate(Activity.java:6679)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

I hope you can help me

Thanks :)

PS: If you have any quesstions ask them :)

答:
so i tried many thinks and this helped me:

add

```<code>     StrictMode.ThreadPolicy policy = new`StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
</code>```

to the MySQLConnector to the connect methode and add

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >  </uses-permission>
</code>```

to the Android manifest.

Now the connection between my device and my database works :)

Title: MySQL connection via Android error

Body:
I have a little Problem with my Android Project.
I want to fill a list with data from my MySQL database, but android would not connect to it.

Here's my code:

MySQLConnector:

private static Connection con = null;

private static String dbHost = "85.214.101.213"; // changed the ip :)
private static String dbPort = "3306"; // Port -- Standard: 3306
private static String dbName = "ticketsystem"; // Datenbankname
private static String dbUser = "admin"; // Datenbankuser
private static String dbPass = "root"; // Datenbankpasswort

public static void conect() {
    try {
        Class.forName("com.mysql.jdbc.Driver"); // Datenbanktreiber für JDBC

        System.out.println("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);

        con = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?" + "user="
                + dbUser + "&" + "password=" + dbPass);

    } catch (ClassNotFoundException e) {
        System.out.println("Treiber nicht gefunden");
    } catch (SQLException e) {
        System.out.println(e);
        System.out.println("Verbindung nicht moglich");
        System.out.println("SQLException: " + e.getMessage());
        System.out.println("SQLState: " + e.getSQLState());
        System.out.println("VendorError: " + e.getErrorCode());
    }

}

SQLManager:

public SQLManager() {
    MySQLConnection.conect();
    Log.e("test", "nach conect");
    con = MySQLConnection.getCon();
}

public String[] getFreeEvents() {

    ArrayList<String> mList = new ArrayList();

    try
    {
        PreparedStatement ps = con.prepareStatement(" SELECT `EventID`,`Name`,`Zeit`,`Ort` FROM `event` WHERE `freeTickets` >= ?");

        ps.setInt(1, 0);
        ResultSet rs = ps.executeQuery();
        while (rs.next())
        {
            int EventID = rs.getInt("EventID");
            String Name = rs.getString("Name");
            String Zeit = rs.getString("Zeit");
            String Ort = rs.getString("Ort");

            String info = Name +"," + Zeit + ","+Ort  ;

            mList.add(info);
            System.out.println(info);
        }

    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }

    String[] array = mList.toArray(new String[0]);
    return array;
}

And the Class form the Android activity:

Button b;
ListView list;
EditText vor;
TextView nach;
SQLManager man = new SQLManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_ticket);
    setContentView(R.layout.activity_main);
    b = findViewById(R.id.button);
    b.setOnClickListener(this);
    list = findViewById(R.id.list);
    list.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, man.getFreeEvents())); //here is the SQL request...
    vor = findViewById(R.id.editText);
    nach = findViewById(R.id.editText2);
}

My probem is that Android could not open a connction.
I have added the Permission request in the Android Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

So at least I got this error:

I/System.out: `com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.´
I/System.out: Verbindung nicht moglich
I/System.out: SQLException: Could not create connection to database server.
I/System.out: SQLState: 08001
I/System.out: VendorError: 0
E/test: nach conect
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: ml.gottfried.myapp, PID: 10440
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{ml.gottfried.myapp/ml.gottfried.myapp.NewTicket}: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.PreparedStatement java.sql.Connection.prepareStatement(java.lang.String)' on a null object reference
                      at ml.gottfried.myapp.SQLManager.getFreeEvents(SQLManager.java:82)
                      at ml.gottfried.myapp.NewTicket.onCreate(NewTicket.java:43)
                      at android.app.Activity.performCreate(Activity.java:6679)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

I hope you can help me

Thanks :)

PS: If you have any quesstions ask them :)

Body:
so i tried many thinks and this helped me:

add

     StrictMode.ThreadPolicy policy = new`StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);

to the MySQLConnector to the connect methode and add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >  </uses-permission>

to the Android manifest.

Now the connection between my device and my database works :)


问:
Type of generic abstract react component
This is my first question, please be gentle ;)

I have several components which share behavior, so I would like to have them all extend the same class, so I don't have to duplicate my functionality:

export abstract class FooComponent
 extends React.Component
 {
    foobar: Foobar = new Foobar();
}
```

<p>Other classes inherit this component like:</p>

<pre class="lang-js prettyprint-override"><code>export class BarComponent extends FooComponent<{baz?: boolean}> {
    //dostuff
}
</code>```

I try to pass these classes as a type into a function, like so:

setFoo (foo: typeof FooComponent) {
    let obj = { foo: foo };
    this.foo = <obj.foo />;
}

this.setFoo(BarComponent);
```

<p>but my compiler throws the following error:</p>

<p><code>Type 'BarComponent' is not assignable to type 'FooComponent<any>'.
  Property 'foobar' is missing in type 'BarComponent'.</code></p>

<p>It works if I don't extend the props, making FooComponent non-generic, but the FooComponents all have different props, which would not be type-safe if I were to set them as any.</p>

<p>Is there a way I can pass the type of my derived classes, and use them as my base class?</p>

<h2>Edit</h2>

<hr>

<p>I found a way to remove all the different props in my FooComponents, so I could make it a base class without a generic type as shown below.</p>

<pre class="lang-js prettyprint-override"><code>export abstract class FooComponent extends React.Component<{baz?: boolean}, {}> {
    foobar: Foobar = new Foobar();
}
</code>```

This way, the setFoo function as shown in the original question works, and no longer throws an error.

Thanks for the provided answers though, They gave me some new insights.

答:
You can specify the constructor signature instead of using typeof

```<code>setFoo <P, T extends FooComponent<P>>(foo: new (... p: any[]) => T)
</code>```

Body:
This is my first question, please be gentle ;)

I have several components which share behavior, so I would like to have them all extend the same class, so I don't have to duplicate my functionality:

export abstract class FooComponent
 extends React.Component
 {
    foobar: Foobar = new Foobar();
}

Other classes inherit this component like:

export class BarComponent extends FooComponent<{baz?: boolean}> {
    //dostuff
}

I try to pass these classes as a type into a function, like so:

setFoo (foo: typeof FooComponent) {
    let obj = { foo: foo };
    this.foo = <obj.foo />;
}

this.setFoo(BarComponent);

but my compiler throws the following error:

Type 'BarComponent' is not assignable to type 'FooComponent<any>'.
  Property 'foobar' is missing in type 'BarComponent'.

It works if I don't extend the props, making FooComponent non-generic, but the FooComponents all have different props, which would not be type-safe if I were to set them as any.

Is there a way I can pass the type of my derived classes, and use them as my base class?

Edit

I found a way to remove all the different props in my FooComponents, so I could make it a base class without a generic type as shown below.

export abstract class FooComponent extends React.Component<{baz?: boolean}, {}> {
    foobar: Foobar = new Foobar();
}

This way, the setFoo function as shown in the original question works, and no longer throws an error.

Thanks for the provided answers though, They gave me some new insights.

Body:
You can specify the constructor signature instead of using typeof

setFoo <P, T extends FooComponent<P>>(foo: new (... p: any[]) => T)


问:
How to run VMware commands from remote scripts on windows
Have a local basic Powershell form for searching and creating VMware virtual machines.

Using new powershell powerCLI module, as described in link

Let's take Get-VM for example:

LOGIC: Type a certain string in TextBox  > click search > prints VM's status/parameters in the form

The problem is, I can't execute Get-VM straight away from the script, but first have to connect using Connect-VIServer command and only than Get-VM will work

Is there any way to do it from the script? Something similar to -m flag of commands plink or putty.

Like: Connect-VIServer -server testvc -flagForExample "commands_list.txt"

答:
Yes, you can. Before providing an immediate answer I'd like to explain what is actually happening.
When you call Connect-VIServer the command sets the value of the variable $DefaultVIServer behind the scenes, which is later used by other cmdlets (such as Get-VM).

However, the Get-VM documentation states that there is a Server parameter available. Which means that you can store your server connection in a variable and then pass it to the Get-VM cmdlet.

Here's a pseudo-code example:

$server = Connect-VIServer -server testvc
Get-VM -Server $server

Furthermore, the Get-VM supports an array of servers, so theoretically you can run the cmdlet on multiple servers at once. For example:

$server1 = Connect-VIServer -server testvc
$server2 = Connect-VIServer -server testvc2
Get-VM -Server @($server1, $server2)


问:
PDOStatement - Use grave accents (`) in columns?
Looking at the PHP manual, does not, at any time, the suggestion to include the grave accents on the columns.

For example: recently, I was trying to run the function below:

``` $pdo->prepare("UPDATE name_table SET convert= :convert, payment = :payment WHERE id = :id") ```

After repeated attempts to try to update the data in MySQL, I noticed that the CONVERT function is a function of the native MySQL.

So after that, put the backticks in the columns and it worked:

``` $pdo->prepare("UPDATE name_table SET `convert`= :convert, `payment` = :payment WHERE id = :id") ```

Does anyone believe that the grave accents are not essential to the object PDOStatements? Just tried to MySQL, but do not know if it really is good to use backticks to further change the database.

答: I would imagine backticks are not required or mentioned because they are specific to mysql and PDO was designed to be used with any RDMS.</p>

ContentLicense: CC BY-SA 2.5

Body:
Looking at the PHP manual, does not, at any time, the suggestion to include the grave accents on the columns.

For example: recently, I was trying to run the function below:

 $pdo->prepare("UPDATE name_table SET convert= :convert, payment = :payment WHERE id = :id")

After repeated attempts to try to update the data in MySQL, I noticed that the CONVERT function is a function of the native MySQL.

So after that, put the backticks in the columns and it worked:

 $pdo->prepare("UPDATE name_table SET `convert`= :convert, `payment` = :payment WHERE id = :id")

Does anyone believe that the grave accents are not essential to the object PDOStatements? Just tried to MySQL, but do not know if it really is good to use backticks to further change the database.


问:
Merging a common project with build variations in .NET MVC
I have a .net mvc site that should be published to a lot of different customers, and thus vary slightly depending on the target.

Is there any way to set up the core project structure, e.g. (simplified):

views

models

controllers

assets

bin

and make a merge at build time with whatever variations the current target might have. For example:

core project:

views

view1.cshtml

view2.cshtml

(removed rest of the folders for brevity)

customer 1 target:

views

view2.cshtml

view3.cshtml

desired merge result:

views

view1.cshtml (from core project)

view2.cshtml (from customer 1 target)

view3.cshtml (from customer 1 target)

The same rule should apply to controllers, binaries etc.

答: What you need is super-admin section, where you could [de]activate different portions of the site, depending on customer.</p>


问:
How to create folder/file that name ended with a dot in Windows?
I wanna create a file that file name end with a dot in Windows.

use "mkdir a.", but i only create a folder named with "a"

And I just wonder how to write a function to create such directory, thanks

答:
Use an extra dot and a trailing backslash:

```<code>mkdir a..\
</code>```

But I highly recommend not to do so. You'll mess the directories up instantly.

Body:
Use an extra dot and a trailing backslash:

mkdir a..\

But I highly recommend not to do so. You'll mess the directories up instantly.


问:
Parse LiveQuery Subscription always receive the old version
I have a collection of beacons that I want to show on a map. I want their positions to be synchronized between all instances of the application.

That is, when I move a beacons to another position I want this change to be reflected in the other instances of the application.

This using the Parse javascript SDK in its version 1.11.0.

I have defined the following Parse model, which represents each object in the collection saved on the server:

```<code>    var Baliza = Parse.Object.extend("Balizas");

    Baliza.prototype.show = function(){
        var self = this;

        var start= '<div class="row" style="width: 350px;">\n' +
            '   <div class="control-group" id="fields">\n' +
            '      <label class="control-label" style="text-align: center;" for="field1">Introducir Mac Asociadas a Ese Punto</label>\n' +
            '      <div class="controls">\n' +
            '         <form id="form" role="form" autocomplete="off">';

        var tmp = '';

        tmp = tmp + '<div  class="entry input-group col-xs-12">\n' +
            '               <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[0]+'">\n' +
            '               <span class="input-group-btn">\n' +
            '               <button baliza-id='+self.id+' class="btn btn-success btn-add" type="button">\n' +
            '               <span class="glyphicon glyphicon-plus"></span>\n' +
            '               </button>\n' +
            '               </span>\n' +
            '            </div>';

        if (self.get("mac").length>1){
            for (var i=1; i<self.get("mac").length; i++) {
                tmp = tmp + '<div class="entry input-group col-xs-12">\n' +
                    '               <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[i]+'">\n' +
                    '               <span class="input-group-btn">\n' +
                    '               <button baliza-id='+self.id+' class="btn  btn-remove col-xs-12" type="button">\n' +
                    '               <span class="glyphicon glyphicon-minus"></span>\n' +
                    '               </button>\n' +
                    '               </span>\n' +
                    '            </div>';
            }
        }

        var end = '</form>\n' +
            '         <br>\n' +
            ' <button  type="button" baliza-id='+self.id+' class="btn btn-block btn-info btn-sm ">Salvar</button>\n' +
            ' <button  type="button" baliza-id='+self.id+' class="btn btn-block btn-danger btn-sm ">Eliminar</button>\n' +
            '      </div>\n' +
            '   </div>\n' +
            '</div>';

        //console.log('impirmiendo marker');
        //console.log(this.marker);

        console.log("Localización -> ", self.get("localizacion"));

        if(self.marker != null) {
            self.marker.setLatLng(new L.LatLng(self.get("localizacion").latitude, self.get("localizacion").longitude),{draggable:'true'});
        } else {

            self.marker = new L.marker([ self.get("localizacion").latitude, self.get("localizacion").longitude], {
                icon: L.AwesomeMarkers.icon({icon: 'certificate', prefix: 'glyphicon', markerColor: 'blue'}),
                draggable: 'true'
            }).bindPopup("", {maxWidth: 560});

            self.marker.on('dragend', function(event){

                var position = event.target.getLatLng();

                console.log("Notify new Location -> ", position.lat, position.lng);

                //Enviamos El Dato a Parse
                this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
                this.save(null, {
                    success: function (balizaSaved) {
                        console.log("Baliza Guardad con éxito: ", balizaSaved);

                    },
                    error: function (baliza, error) {
                        alert('Failed to create new object, with error code: ' + error.message);
                    }
                });
            }.bind(this));

            map.addLayer(self.marker);
        }

        self.marker.getPopup().setContent(start+tmp+end);

    };
</code>```

The code responsible for notifying the change of position in the map is the following:

```<code>self.marker.on('dragend', function(event){

                var position = event.target.getLatLng();

                console.log("Notify new Location -> ", position.lat, position.lng);

                //Enviamos El Dato a Parse
                this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
                this.save(null, {
                    success: function (balizaSaved) {
                        console.log("Baliza Guardad con éxito: ", balizaSaved);

                    },
                    error: function (baliza, error) {
                        alert('Failed to create new object, with error code: ' + error.message);
                    }
                });
            }.bind(this));
</code>```

The subscription was created as follows,

```<code>var query = new Parse.Query(Baliza);
var subscription = query.subscribe();

var mapaBalizasParse = new Map();

// After specifying the Monster subclass...
//Parse.Object.registerSubclass('Balizas',Baliza);

subscription.on('create', function (balizaCreated) {
    console.log("New baliza created -> ", balizaCreated.toJSON());
    var baliza = new Baliza(balizaCreated.toJSON());
    baliza.show();
    mapaBalizasParse.set(baliza.id, baliza);
});

subscription.on('update', function (balizaSaved) {
    console.log('BALIZA ACTUALIZADA -> ', balizaSaved.toJSON());
    var baliza = mapaBalizasParse.get(balizaSaved.id);
    baliza.set("mac", balizaSaved.get("mac"));
    baliza.set("localizacion", balizaSaved.get("localizacion"));
    baliza.show();
});

subscription.on('delete', function (baliza) {
    //console.log(mapaBalizasParse.get(baliza.id));
    map.removeLayer(mapaBalizasParse.get(baliza.id).marker);
    mapaBalizasParse.delete(baliza.id);
});

subscription.on('leave', function (balizaLeave) {
    console.log('Leave called -> ', balizaLeave.id, balizaLeave.get("localizacion"));
});

subscription.on('enter', function (balizaCalled) {
    console.log('Enter called -> ', balizaCalled.id, balizaCalled.get("localizacion"));
});
</code>```

Each time I click on a position on the map I create a Beacons as follows:

```<code>function onMapClick(e) {
        var baliza = new Baliza();

        baliza.set("localizacion",new Parse.GeoPoint(e.latlng.lat, e.latlng.lng));
        baliza.set("mac",["11:22:33:44:55:10"]);
        baliza.set("editando",true);

        baliza.save(null, {
            success: function(baliza) {
                //Añadimos La Baliza Al Mapa Interno
                //mapaBalizasParse.set(baliza.id,baliza);
                //baliza.show();
            },
            error: function(baliza, error) {
                alert('Failed to create new object, with error code: ' + error.message);
            }
        });
    }
</code>```

The list of currently registered "beacons" is shown as follows:

```<code>query.find({
            success: function(results) {
                console.log("Total Balizas -> " + results.length);
                for (var i = 0; i < results.length; i++) {
                    var currentBaliza = results[i];
                    console.log("Baliza " + i + " -> ", currentBaliza);
                    currentBaliza.show();
                    mapaBalizasParse.set(currentBaliza.id, currentBaliza);
                }
            },
            error: function(error) {
                console.log("Error: " + error.code + " " + error.message);
            }
        });
</code>```

The problem is if for example I move the beacon from position ( latitude: 40.961229844235234, longitude: -5.669621229171753 ) to another point in the map (latitude: 40.9604196476232, longitude: -5.6707102060318)

The other instances of the application receive in the update event the old version of the object, its location field has not changed ( latitude: 40.961229844235234, longitude: -5.669621229171753 )

Someone can tell me what I'm doing wrong in the code.

Thanks in advance.

答:
I have been doing some test with minimal configuration and this is that I saw:

In the callback for loading all beacons in the map set  you use this code:

```<code>var beacon = new Baliza({id: baliza.id,  localizacion:
baliza.get("localizacion") , mac: baliza.get("mac"), editando:
baliza.get("editando")});
</code>```

but when you add a new beacon created in the callback of 'create' event, you use this one:

```<code>var beacon = new Baliza();
beacon.id = baliza.id;
beacon.localizacion = baliza.get("localizacion");
beacon.mac = baliza.get("mac");
beacon.editando = baliza.get("editando");
</code>```

In my tests, if you use the first code the beacons updates normally, but if you use the second one, a old version of the beacon is logged in javascript console.

It seems that something special happens in the empty constructor that you are not including in the  overloaded constructor.

I hope that it helps you. :)

Here my complete code:

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple test parse JS</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>

<input type="text" id="txtIndex" class="textbox" value="1">

<button type="button" class="btn-add">Add beacon</button>
<button type="button" class="btn-modify">Modify beacon</button>
<button type="button" class="btn-remove">Remove beacon</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://unpkg.com/parse@1.11.0/dist/parse.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Own JS-->
<script src="./js/demo_parse.js"></script>

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

JS

```<code>var mapBeacons = new Map();
var query;
var subscription;
var Baliza;

function loadAllBeacons(){

    query.find({
        success: function(results) {
            for (var i = 0; i < results.length; i++) {
                //Vamos Creando Los Objetos Que Recibimos
                var beacon = new Baliza();
                beacon.id = results[i].id;
                beacon.localizacion = results[i].get("localizacion");
                beacon.mac = results[i].get("mac");
                mapBeacons.set(beacon.id,beacon);
            }
        },
        error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    });
}

function modifyBeacon(){

    var key = $("#txtIndex").val();
    var baliza = mapBeacons.get(key);
    var my_chance = new Chance();
    var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())
    baliza.set("localizacion",randomLocation);

    baliza.save(null, {
        success: function(baliza) {
            // Execute any logic that should take place after the object is saved.
            mapBeacons.set(baliza.id,baliza);
        },
        error: function(baliza, error) {
            // Execute any logic that should take place if the save fails.
            // error is a Parse.Error with an error code and message.
            alert('Failed to remove new object, with error code: ' + error.message);
        }
    });
}

function removeBeacon(){

    var key = $("#txtIndex").val();
    var baliza = mapBeacons.get(key);

    baliza.destroy({
        success: function(myObject) {
            // The object was deleted from the Parse Cloud.
            //map.removeLayer(baliza.marker);
            //mapaBalizasParse.delete($(this).attr('id'));
            console.log("Beacon removed sucessfully");
            console.log(myObject);

        },
        error: function(myObject, error) {
            // The delete failed.
            // error is a Parse.Error with an error code and message.
        }
    });

}

function addNewBeacon(){

    var baliza = new Baliza();
    var my_chance = new Chance();
    var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())

    baliza.set("localizacion",randomLocation);
    baliza.set("mac",["11:22:33:44:55:10"]);
    baliza.set("editando",true);

    baliza.save(null, {
        success: function(baliza) {
            console.log("OnSave Beacon saved sucessfully");
            console.log(baliza);
        },
        error: function(baliza, error) {
            alert('Failed to create new object, with error code: ' + error.message);
        }
    });

}

$(function() {

    console.log( "ready!" );

    //Init parse
    Parse.initialize("6xuPkPgqEfCdzXwaxAfUuKbTAglJL5ALa1mmY8de");
    Parse.serverURL = 'http://encelocalizacion.com:1337/parse';

    //Objeto Ppara interacturar con el Objeto Baliza de Parser
    Baliza = Parse.Object.extend("Balizas", {
        /**
         * Instance properties go in an initialize method
         */
        id: '',
        localizacion:  '',
        mac:'',
        marker:'',
        popup:'',
        initialize: function (attr, options) {

        }
    });

    query = new Parse.Query(Baliza);
    subscription = query.subscribe();

    // Subscription for create
    subscription.on('create', function (baliza) {

        // TODO CHANGE THIS
        var beacon = new Baliza({id: baliza.id,  localizacion:  baliza.get("localizacion") , mac: baliza.get("mac"), editando: baliza.get("editando")});

        /*
         var beacon = new Baliza();
        beacon.id = baliza.id;
        beacon.localizacion = baliza.get("localizacion");
        beacon.mac = baliza.get("mac");
        beacon.editando = baliza.get("editando");
        */

        mapBeacons.set(beacon.id,beacon);

        console.log("New beacon added to BBDD")
        console.log(mapBeacons)

    });

    // Subscription for update
    subscription.on('update', function (kk) {
        console.log('Updated beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude  + " " + kk.get("mac")+ " " + kk.get("id"));
    });

    // Subscription for delete
    subscription.on('delete', function (kk) {
        mapBeacons.delete(kk.id);
        console.log('Deleted beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude  + " " + kk.get("mac"));
        console.log(mapBeacons)
    });

    loadAllBeacons();

    $(document).on('click', '.btn-add', function(e) {
        addNewBeacon();
    }).on('click', '.btn-remove', function(e) {
        removeBeacon();
        return false;
    }).on('click', '.btn-modify', function(e) {
        modifyBeacon();
    });

});
</code>```

Body:
I have a collection of beacons that I want to show on a map. I want their positions to be synchronized between all instances of the application.

That is, when I move a beacons to another position I want this change to be reflected in the other instances of the application.

This using the Parse javascript SDK in its version 1.11.0.

I have defined the following Parse model, which represents each object in the collection saved on the server:

    var Baliza = Parse.Object.extend("Balizas");

    Baliza.prototype.show = function(){
        var self = this;

        var start= '
\n' +
            '
\n' +
            '      Introducir Mac Asociadas a Ese Punto\n' +
            '
\n' +
            '         <form id="form" role="form" autocomplete="off">';

        var tmp = '';

        tmp = tmp + '
\n' +
            '               <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[0]+'">\n' +
            '               \n' +
            '               <button baliza-id='+self.id+' class="btn btn-success btn-add" type="button">\n' +
            '               \n' +
            '               </button>\n' +
            '               \n' +
            '
';

        if (self.get("mac").length>1){
            for (var i=1; i<self.get("mac").length; i++) {
                tmp = tmp + '
\n' +
                    '               <input class="form-control" name="fields[]" type="text" value="'+self.get("mac")[i]+'">\n' +
                    '               \n' +
                    '               <button baliza-id='+self.id+' class="btn  btn-remove col-xs-12" type="button">\n' +
                    '               \n' +
                    '               </button>\n' +
                    '               \n' +
                    '
';
            }
        }

        var end = '</form>\n' +
            '
\n' +
            ' <button  type="button" baliza-id='+self.id+' class="btn btn-block btn-info btn-sm ">Salvar</button>\n' +
            ' <button  type="button" baliza-id='+self.id+' class="btn btn-block btn-danger btn-sm ">Eliminar</button>\n' +
            '
\n' +
            '
\n' +
            '
';

        //console.log('impirmiendo marker');
        //console.log(this.marker);

        console.log("Localización -> ", self.get("localizacion"));

        if(self.marker != null) {
            self.marker.setLatLng(new L.LatLng(self.get("localizacion").latitude, self.get("localizacion").longitude),{draggable:'true'});
        } else {

            self.marker = new L.marker([ self.get("localizacion").latitude, self.get("localizacion").longitude], {
                icon: L.AwesomeMarkers.icon({icon: 'certificate', prefix: 'glyphicon', markerColor: 'blue'}),
                draggable: 'true'
            }).bindPopup("", {maxWidth: 560});

            self.marker.on('dragend', function(event){

                var position = event.target.getLatLng();

                console.log("Notify new Location -> ", position.lat, position.lng);

                //Enviamos El Dato a Parse
                this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
                this.save(null, {
                    success: function (balizaSaved) {
                        console.log("Baliza Guardad con éxito: ", balizaSaved);

                    },
                    error: function (baliza, error) {
                        alert('Failed to create new object, with error code: ' + error.message);
                    }
                });
            }.bind(this));

            map.addLayer(self.marker);
        }

        self.marker.getPopup().setContent(start+tmp+end);

    };

The code responsible for notifying the change of position in the map is the following:

self.marker.on('dragend', function(event){

                var position = event.target.getLatLng();

                console.log("Notify new Location -> ", position.lat, position.lng);

                //Enviamos El Dato a Parse
                this.set("localizacion", new Parse.GeoPoint(position.lat, position.lng));
                this.save(null, {
                    success: function (balizaSaved) {
                        console.log("Baliza Guardad con éxito: ", balizaSaved);

                    },
                    error: function (baliza, error) {
                        alert('Failed to create new object, with error code: ' + error.message);
                    }
                });
            }.bind(this));

The subscription was created as follows,

var query = new Parse.Query(Baliza);
var subscription = query.subscribe();

var mapaBalizasParse = new Map();

// After specifying the Monster subclass...
//Parse.Object.registerSubclass('Balizas',Baliza);

subscription.on('create', function (balizaCreated) {
    console.log("New baliza created -> ", balizaCreated.toJSON());
    var baliza = new Baliza(balizaCreated.toJSON());
    baliza.show();
    mapaBalizasParse.set(baliza.id, baliza);
});

subscription.on('update', function (balizaSaved) {
    console.log('BALIZA ACTUALIZADA -> ', balizaSaved.toJSON());
    var baliza = mapaBalizasParse.get(balizaSaved.id);
    baliza.set("mac", balizaSaved.get("mac"));
    baliza.set("localizacion", balizaSaved.get("localizacion"));
    baliza.show();
});

subscription.on('delete', function (baliza) {
    //console.log(mapaBalizasParse.get(baliza.id));
    map.removeLayer(mapaBalizasParse.get(baliza.id).marker);
    mapaBalizasParse.delete(baliza.id);
});

subscription.on('leave', function (balizaLeave) {
    console.log('Leave called -> ', balizaLeave.id, balizaLeave.get("localizacion"));
});

subscription.on('enter', function (balizaCalled) {
    console.log('Enter called -> ', balizaCalled.id, balizaCalled.get("localizacion"));
});

Each time I click on a position on the map I create a Beacons as follows:

function onMapClick(e) {
        var baliza = new Baliza();

        baliza.set("localizacion",new Parse.GeoPoint(e.latlng.lat, e.latlng.lng));
        baliza.set("mac",["11:22:33:44:55:10"]);
        baliza.set("editando",true);

        baliza.save(null, {
            success: function(baliza) {
                //Añadimos La Baliza Al Mapa Interno
                //mapaBalizasParse.set(baliza.id,baliza);
                //baliza.show();
            },
            error: function(baliza, error) {
                alert('Failed to create new object, with error code: ' + error.message);
            }
        });
    }

The list of currently registered "beacons" is shown as follows:

query.find({
            success: function(results) {
                console.log("Total Balizas -> " + results.length);
                for (var i = 0; i < results.length; i++) {
                    var currentBaliza = results[i];
                    console.log("Baliza " + i + " -> ", currentBaliza);
                    currentBaliza.show();
                    mapaBalizasParse.set(currentBaliza.id, currentBaliza);
                }
            },
            error: function(error) {
                console.log("Error: " + error.code + " " + error.message);
            }
        });

The problem is if for example I move the beacon from position ( latitude: 40.961229844235234, longitude: -5.669621229171753 ) to another point in the map (latitude: 40.9604196476232, longitude: -5.6707102060318)

The other instances of the application receive in the update event the old version of the object, its location field has not changed ( latitude: 40.961229844235234, longitude: -5.669621229171753 )

Someone can tell me what I'm doing wrong in the code.

Thanks in advance.

Body:
I have been doing some test with minimal configuration and this is that I saw:

In the callback for loading all beacons in the map set  you use this code:

var beacon = new Baliza({id: baliza.id,  localizacion:
baliza.get("localizacion") , mac: baliza.get("mac"), editando:
baliza.get("editando")});

but when you add a new beacon created in the callback of 'create' event, you use this one:

var beacon = new Baliza();
beacon.id = baliza.id;
beacon.localizacion = baliza.get("localizacion");
beacon.mac = baliza.get("mac");
beacon.editando = baliza.get("editando");

In my tests, if you use the first code the beacons updates normally, but if you use the second one, a old version of the beacon is logged in javascript console.

It seems that something special happens in the empty constructor that you are not including in the  overloaded constructor.

I hope that it helps you. :)

Here my complete code:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple test parse JS</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>

<input type="text" id="txtIndex" class="textbox" value="1">

<button type="button" class="btn-add">Add beacon</button>
<button type="button" class="btn-modify">Modify beacon</button>
<button type="button" class="btn-remove">Remove beacon</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://chancejs.com/chance.min.js"></script>
<script src="https://unpkg.com/parse@1.11.0/dist/parse.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Own JS-->
<script src="./js/demo_parse.js"></script>

</body>
</html>

JS

var mapBeacons = new Map();
var query;
var subscription;
var Baliza;

function loadAllBeacons(){

    query.find({
        success: function(results) {
            for (var i = 0; i < results.length; i++) {
                //Vamos Creando Los Objetos Que Recibimos
                var beacon = new Baliza();
                beacon.id = results[i].id;
                beacon.localizacion = results[i].get("localizacion");
                beacon.mac = results[i].get("mac");
                mapBeacons.set(beacon.id,beacon);
            }
        },
        error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    });
}

function modifyBeacon(){

    var key = $("#txtIndex").val();
    var baliza = mapBeacons.get(key);
    var my_chance = new Chance();
    var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())
    baliza.set("localizacion",randomLocation);

    baliza.save(null, {
        success: function(baliza) {
            // Execute any logic that should take place after the object is saved.
            mapBeacons.set(baliza.id,baliza);
        },
        error: function(baliza, error) {
            // Execute any logic that should take place if the save fails.
            // error is a Parse.Error with an error code and message.
            alert('Failed to remove new object, with error code: ' + error.message);
        }
    });
}

function removeBeacon(){

    var key = $("#txtIndex").val();
    var baliza = mapBeacons.get(key);

    baliza.destroy({
        success: function(myObject) {
            // The object was deleted from the Parse Cloud.
            //map.removeLayer(baliza.marker);
            //mapaBalizasParse.delete($(this).attr('id'));
            console.log("Beacon removed sucessfully");
            console.log(myObject);

        },
        error: function(myObject, error) {
            // The delete failed.
            // error is a Parse.Error with an error code and message.
        }
    });

}

function addNewBeacon(){

    var baliza = new Baliza();
    var my_chance = new Chance();
    var randomLocation = new Parse.GeoPoint(my_chance.latitude(), my_chance.longitude())

    baliza.set("localizacion",randomLocation);
    baliza.set("mac",["11:22:33:44:55:10"]);
    baliza.set("editando",true);

    baliza.save(null, {
        success: function(baliza) {
            console.log("OnSave Beacon saved sucessfully");
            console.log(baliza);
        },
        error: function(baliza, error) {
            alert('Failed to create new object, with error code: ' + error.message);
        }
    });

}

$(function() {

    console.log( "ready!" );

    //Init parse
    Parse.initialize("6xuPkPgqEfCdzXwaxAfUuKbTAglJL5ALa1mmY8de");
    Parse.serverURL = 'http://encelocalizacion.com:1337/parse';

    //Objeto Ppara interacturar con el Objeto Baliza de Parser
    Baliza = Parse.Object.extend("Balizas", {
        /**
         * Instance properties go in an initialize method
         */
        id: '',
        localizacion:  '',
        mac:'',
        marker:'',
        popup:'',
        initialize: function (attr, options) {

        }
    });

    query = new Parse.Query(Baliza);
    subscription = query.subscribe();

    // Subscription for create
    subscription.on('create', function (baliza) {

        // TODO CHANGE THIS
        var beacon = new Baliza({id: baliza.id,  localizacion:  baliza.get("localizacion") , mac: baliza.get("mac"), editando: baliza.get("editando")});

        /*
         var beacon = new Baliza();
        beacon.id = baliza.id;
        beacon.localizacion = baliza.get("localizacion");
        beacon.mac = baliza.get("mac");
        beacon.editando = baliza.get("editando");
        */

        mapBeacons.set(beacon.id,beacon);

        console.log("New beacon added to BBDD")
        console.log(mapBeacons)

    });

    // Subscription for update
    subscription.on('update', function (kk) {
        console.log('Updated beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude  + " " + kk.get("mac")+ " " + kk.get("id"));
    });

    // Subscription for delete
    subscription.on('delete', function (kk) {
        mapBeacons.delete(kk.id);
        console.log('Deleted beacon:' + kk.get("localizacion").latitude + " " + kk.get("localizacion").longitude  + " " + kk.get("mac"));
        console.log(mapBeacons)
    });

    loadAllBeacons();

    $(document).on('click', '.btn-add', function(e) {
        addNewBeacon();
    }).on('click', '.btn-remove', function(e) {
        removeBeacon();
        return false;
    }).on('click', '.btn-modify', function(e) {
        modifyBeacon();
    });

});


问:
Prevent compilation of unused template specialization in c++
Let's consider a struct Foo, templated by an enum called TYPE:

```<code>enum TYPE
{
    TYPE_A,
    TYPE_B
};

template<TYPE T>
struct Foo;
</code>```

Foo is not defined but only specialized twice. One specialization adds a int* to the class while the other adds a pointer to an object of type MayBeNotDefined:

```<code>template<>
struct Foo<TYPE_A>
{
    int* A;
};

template<>
struct Foo<TYPE_B>
{
    MayBeNotDefined* B;
};
</code>```

The MayBeNotDefined type is not defined in some of my project, so only Foo<TYPE_A> is used:

```<code>int main()
{
    Foo<TYPE_A> a;
    a.A = new int;
    //...
}
</code>```

In other projects, MayBeNotDefined is actually defined before the declaration of Foo (with something like using MayBeNotDefined = int;) and both Foo<TYPE_A> and Foo<TYPE_B> are used:

```<code>int main()
{
    Foo<TYPE_A> a;
    Foo<TYPE_B> b;
    //...
}
</code>```

The thing is that in the first case, the compiler generates code for both specializations, even if I only use Foo<TYPE_A>... Therefore, an error occurs since MayBeNotDefined is unknown.

So I have two questions :

Why does the compiler need to generate code for every specializations?
I naively thought that if the compiler meets a variable of type Foo<TYPE_A>, then it would generate only the code of the first specialization. If no Foo<TYPE_B> are parsed, why does it need to also generate the associated code?

How to prevent the compiler to compile code for unused specialization? Is there any easy workaround, preferably without using pre-processor macros? It seems possible to 'delete' already compiled but unused code (cf G++ generates code for unused template specializations?). What I want is that the code is not even compiled at all, so that the undefined type MayBeNotDefined is not a problem.

Thanks!

答:
Why does the compiler need to generate code for every specializations?

The compiler doesn't need to generate code for unused template specialization, but it must ensure it's definition is correct according to the same rules as those applied to generic classes.

How to prevent the compiler to compile code for unused specialization?

You cannot. Unused specializations must compile, but if they do, the (decent) compiler won't produce binary code for it.

But, if you told us what you exactly expect, we might give you alternative. As example:

```<code>enum TYPE
{
    TYPE_A,
    TYPE_B
};

template<TYPE T>
struct MayBeNotDefined;

// FOR PROJECT WITH MayBeNotDefined ONLY ---
template<>
struct MayBeNotDefined<TYPE_B> { typedef char type; };
// FOR PROJECT WITH MayBeNotDefined ONLY ---

template<TYPE T>
struct Foo
{
    typename MayBeNotDefined<T>::type* B;
};

template<>
struct Foo<TYPE_A>
{
    int* A;
};

int main()
{
    Foo<TYPE_A> a;
    a.A = new int;

    // FOR PROJECT WITH MayBeNotDefined ONLY ---
    Foo<TYPE_B> b;
    b.B = new char;
    // FOR PROJECT WITH MayBeNotDefined ONLY ---
}
</code>```

(this works even if you remove the two specified blocks)

Body:
Let's consider a struct Foo, templated by an enum called TYPE:

enum TYPE
{
    TYPE_A,
    TYPE_B
};

template<TYPE T>
struct Foo;

Foo is not defined but only specialized twice. One specialization adds a int* to the class while the other adds a pointer to an object of type MayBeNotDefined:

template<>
struct Foo<TYPE_A>
{
    int* A;
};

template<>
struct Foo<TYPE_B>
{
    MayBeNotDefined* B;
};

The MayBeNotDefined type is not defined in some of my project, so only Foo<TYPE_A> is used:

int main()
{
    Foo<TYPE_A> a;
    a.A = new int;
    //...
}

In other projects, MayBeNotDefined is actually defined before the declaration of Foo (with something like using MayBeNotDefined = int;) and both Foo<TYPE_A> and Foo<TYPE_B> are used:

int main()
{
    Foo<TYPE_A> a;
    Foo<TYPE_B> b;
    //...
}

The thing is that in the first case, the compiler generates code for both specializations, even if I only use Foo<TYPE_A>... Therefore, an error occurs since MayBeNotDefined is unknown.

So I have two questions :

Why does the compiler need to generate code for every specializations?
I naively thought that if the compiler meets a variable of type Foo<TYPE_A>, then it would generate only the code of the first specialization. If no Foo<TYPE_B> are parsed, why does it need to also generate the associated code?

How to prevent the compiler to compile code for unused specialization? Is there any easy workaround, preferably without using pre-processor macros? It seems possible to 'delete' already compiled but unused code (cf G++ generates code for unused template specializations?). What I want is that the code is not even compiled at all, so that the undefined type MayBeNotDefined is not a problem.

Thanks!

Body:
Why does the compiler need to generate code for every specializations?

The compiler doesn't need to generate code for unused template specialization, but it must ensure it's definition is correct according to the same rules as those applied to generic classes.

How to prevent the compiler to compile code for unused specialization?

You cannot. Unused specializations must compile, but if they do, the (decent) compiler won't produce binary code for it.

But, if you told us what you exactly expect, we might give you alternative. As example:

enum TYPE
{
    TYPE_A,
    TYPE_B
};

template<TYPE T>
struct MayBeNotDefined;

// FOR PROJECT WITH MayBeNotDefined ONLY ---
template<>
struct MayBeNotDefined<TYPE_B> { typedef char type; };
// FOR PROJECT WITH MayBeNotDefined ONLY ---

template<TYPE T>
struct Foo
{
    typename MayBeNotDefined<T>::type* B;
};

template<>
struct Foo<TYPE_A>
{
    int* A;
};

int main()
{
    Foo<TYPE_A> a;
    a.A = new int;

    // FOR PROJECT WITH MayBeNotDefined ONLY ---
    Foo<TYPE_B> b;
    b.B = new char;
    // FOR PROJECT WITH MayBeNotDefined ONLY ---
}

(this works even if you remove the two specified blocks)


问:
Node.js fs.readfile works infinitly
I have a problem with a fs.readfile method. I have the following code:

```<code>fs.readFile(path.join(__static, '/file.json'), function (err, data) {
        if (err) {
            console.log('Error loading client secret file: ' + err);

            return;
        }

        authorize(JSON.parse(data));
    });
</code>```

The problem is, it worked fine all the time on my main computer but today I cloned my repo on the laptop and it does not work that well. I always reach the line above readFile occurence on laptop, but most of the times (not always), readFile seems to be working infinitly, it neither logs any errors nor runs authorize method. When I refresh my app and run this again, it reads the file instantly. This seems to me like the reading thread blocks itself for some reason, don't know why. And by the way, .json file I'm reading is 1kB.

答:
You don't have to do fs.readFile on json files. Just require() the file and it will be available to you as parsed object.</p>

```<code>let file = require('./file.json');

console.log(file)
</code>```

Title: Node.js fs.readfile works infinitly

Body:
I have a problem with a fs.readfile method. I have the following code:

fs.readFile(path.join(__static, '/file.json'), function (err, data) {
        if (err) {
            console.log('Error loading client secret file: ' + err);

            return;
        }

        authorize(JSON.parse(data));
    });

The problem is, it worked fine all the time on my main computer but today I cloned my repo on the laptop and it does not work that well. I always reach the line above readFile occurence on laptop, but most of the times (not always), readFile seems to be working infinitly, it neither logs any errors nor runs authorize method. When I refresh my app and run this again, it reads the file instantly. This seems to me like the reading thread blocks itself for some reason, don't know why. And by the way, .json file I'm reading is 1kB.

Body:
You don't have to do fs.readFile on json files. Just require() the file and it will be available to you as parsed object.

let file = require('./file.json');

console.log(file)


问:
TeamCity CI build pull requests from BitBucket -> ArcBees/teamcity-plugins
I'm trying to use the following plug in but for some reason the trigger does not get hit.

https://github.com/ArcBees/teamcity-plugins/wiki/Configuring-Bitbucket-Pull-Requests-Plugin

I think the VCS Root is correct because all pending changes from Pull Requests shows up, the problem is that they only show as Pending and never starts to build.

The settings menu for the trigger does not look like the Wiki description but it is quite similar. For API URL I have tried both https://bitbucket.org and https://api.bitbucket.org. Other values are checked and correct, the user has access to the repository.

Version: TeamCity Enterprise 2017.1.3 (build 46961)

According to this question it should be trigger related:

TeamCity pending changes are not run

答: According to this Github issue the problem could be solved by updating the base branch to be master rather than ref/heads/master


问:
How do I tell Cargo to run files from a directory other than "src"?
I have a front-end project that has a lot of stuff in src folder, and I have the opportunity to also use Rust on the server side. All my Rust server files are in the server folder; how can I tell Cargo to run ./server/app.rs?

答:
As stated in the comments, you are probably better off just moving all of your code into the "server" directory. If you don't, you are going to be swimming uphill against defaults, which is not usually a great idea.

That being said, you can specify the path to the binary or library in your Cargo.toml:

```<code>[[bin]]
name = "quux"
path = "server/main.rs"
</code>```

```<code>[lib]
name = "quux"
path = "server/lib.rs"
</code>```

See also:

Rust package with both a library and a binary?

Body:
As stated in the comments, you are probably better off just moving all of your code into the "server" directory. If you don't, you are going to be swimming uphill against defaults, which is not usually a great idea.

That being said, you can specify the path to the binary or library in your Cargo.toml:

[[bin]]
name = "quux"
path = "server/main.rs"

[lib]
name = "quux"
path = "server/lib.rs"

See also:

Rust package with both a library and a binary?


问:
Cannot read entire content of 600MB text file
So I have this very big text file, which is suposed to be 64 millions password.
(https://crackstation.net/buy-crackstation-wordlist-password-cracking-dictionary.htm <- Smaller Wordlist (Human Passwords Only))
I can't open it with notepad++ or any other editor, even thought I have 32GB or ram.

I tried to read it all at once, while removing the duplicate then storing it in a file :

```<code>import os

IN_FILE = "./realhuman_phill.txt"
base, ext = os.path.splitext(IN_FILE)
outfile = base + "_no_duplicate" + ext
print "reading " + IN_FILE
all_words = open(IN_FILE).read().splitlines()
print "{} element in file".format(len(all_words))
print "removing duplicates"
myset = set()
myset.update(all_words)
print "{} elements remaining after duplicate removal".format(len(myset))

print "writing data"
with open(outfile, 'w') as f:
    for line in myset:
        f.write("%s\n" % line)
</code>```

but then I end up with a ~200MB file (more than 600MB before) with only 19991889 lines (19.9 Millions)
So many duplicates? weird

So I made this script to count the number of lines, according to
Lazy Method for Reading Big File in Python?
it should only load in the file in ram 1 line at a time :

```<code>abs_filename = r"D:\realhuman_phill.txt"
print "counting lines in {}".format(abs_filename)
with open(abs_filename) as infile:
    counter = 0
    for line in infile:
        counter = counter + 1
print counter
</code>```

and it returns 19991889 = 19 991 889, same number, far from 64 millions, with no duplicate removal.

I'm guessing either python or my OS do not let me access the rest of the file,
any idea of what is going on?

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

答:
Issue could be with the Line Endings. Try enforcing the file read mode as binary. </p>

```<code>with open(abs_filename, 'rb') as infile:
</code>```

Body:
So I have this very big text file, which is suposed to be 64 millions password.
(https://crackstation.net/buy-crackstation-wordlist-password-cracking-dictionary.htm <- Smaller Wordlist (Human Passwords Only))
I can't open it with notepad++ or any other editor, even thought I have 32GB or ram.

I tried to read it all at once, while removing the duplicate then storing it in a file :

import os

IN_FILE = "./realhuman_phill.txt"
base, ext = os.path.splitext(IN_FILE)
outfile = base + "_no_duplicate" + ext
print "reading " + IN_FILE
all_words = open(IN_FILE).read().splitlines()
print "{} element in file".format(len(all_words))
print "removing duplicates"
myset = set()
myset.update(all_words)
print "{} elements remaining after duplicate removal".format(len(myset))

print "writing data"
with open(outfile, 'w') as f:
    for line in myset:
        f.write("%s\n" % line)

but then I end up with a ~200MB file (more than 600MB before) with only 19991889 lines (19.9 Millions)
So many duplicates? weird

So I made this script to count the number of lines, according to
Lazy Method for Reading Big File in Python?
it should only load in the file in ram 1 line at a time :

abs_filename = r"D:\realhuman_phill.txt"
print "counting lines in {}".format(abs_filename)
with open(abs_filename) as infile:
    counter = 0
    for line in infile:
        counter = counter + 1
print counter

and it returns 19991889 = 19 991 889, same number, far from 64 millions, with no duplicate removal.

I'm guessing either python or my OS do not let me access the rest of the file,
any idea of what is going on?

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

Body:
Issue could be with the Line Endings. Try enforcing the file read mode as binary.

with open(abs_filename, 'rb') as infile:


问:
ios version of themes and styles
As an Android developer new to iOS/swift, I am trying to implement a global theme/style which every view controller can inherit. I expect one file which I can modify which would affect all View Controllers's UI. This is possible in android. Does iOS have anything similar?</p>

答:
Usually if you want to do something like that, you can go to the AppDelegate File, and add code like the ones below:

```<code>[[UITextField appearance] setTintColor:[UIColor redColor]];
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
</code>```

For example textfield by default has a bluish tint color, but with the code above, the default tint color becomes red. The single line of code you place will affect all UI related to it. Try it out.

Title: ios version of themes and styles

Body:
Usually if you want to do something like that, you can go to the AppDelegate File, and add code like the ones below:

[[UITextField appearance] setTintColor:[UIColor redColor]];
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

For example textfield by default has a bluish tint color, but with the code above, the default tint color becomes red. The single line of code you place will affect all UI related to it. Try it out.


问:
How to set up a cron job via PHP (not CPanel)?
How to set up a cron job via PHP (not CPanel)?</p>

答:
If what you're getting at is dynamically adding lots of jobs to crontab form your application, a better way to do that is manually add ONE cron job:

```<code>php -f /path/to/your/runner.php
</code>```

Store your jobs that you would be adding to cron manually in a table (or one table per task-type), and then have your runner go through the table(s) every minute/hour/day/whatever and execute all the ones that should be executed at that time.

Body:
If what you're getting at is dynamically adding lots of jobs to crontab form your application, a better way to do that is manually add ONE cron job:

php -f /path/to/your/runner.php

Store your jobs that you would be adding to cron manually in a table (or one table per task-type), and then have your runner go through the table(s) every minute/hour/day/whatever and execute all the ones that should be executed at that time.


问:
ng build --prod UnhandledPromiseRejectionWarning: Unhandled promise rejection
Angular 4.3  I get the following error when trying to ng build --prod

```<code>94% asset optimization(node:7184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token: name (i)
</code>```

I have no idea where this issue stems from as thats the only error I can find.

答:
Same here :(

In my case the problem occurs in combination with popper.js as stated here: https://github.com/angular/angular-cli/issues/7725

EDIT: I found a solution:
Instead of using this one in the Angular-CLI-Configuration (.angular-cli.json):

```<code>"scripts": [
  ...
  "../node_modules/popper.js/dist/popper.min.js",
  ...
],
</code>```

I used that one (i changed the library to the /dist/umd one):

```<code>"scripts": [
 ...
 "../node_modules/popper.js/dist/umd/popper.min.js",
 ...
],
</code>```

Body:
Angular 4.3  I get the following error when trying to ng build --prod

94% asset optimization(node:7184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token: name (i)

I have no idea where this issue stems from as thats the only error I can find.

Body:
Same here :(

In my case the problem occurs in combination with popper.js as stated here: https://github.com/angular/angular-cli/issues/7725

EDIT: I found a solution:
Instead of using this one in the Angular-CLI-Configuration (.angular-cli.json):

"scripts": [
  ...
  "../node_modules/popper.js/dist/popper.min.js",
  ...
],

I used that one (i changed the library to the /dist/umd one):

"scripts": [
 ...
 "../node_modules/popper.js/dist/umd/popper.min.js",
 ...
],


问:
Duplicate results on JOIN
Here is my question : I am trying to get all the games of a class. the class can host a game, or have a game in another class.

games table have : guest_class (ID of class) and host_class(ID of class)

classes table have : id_class (ID of class)

An example I am trying to get the games of the class 1.
There are only 2 games with class 1.

```<code>id_game: 1, id_class: 1, host_class: 3, guest_class: 1,
id_game: 2, id_class: 1, host_class: 1, guest_class: 6,
</code>```

Why am I getting duplicated results ?

QUERY

```<code>var classID = Number(req.query.searchValue);
var query = `SELECT * FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )`;
con2.query(query, [classID,classID] , function (err, result) {
</code>```

RESULT

```<code>[ RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 3},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 6} ]
</code>```

答:
Would you try like this;</p>

```<code>select * from games where id_game IN (
SELECT g.id_game FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )
group by g.id_game)
</code>```

Title: Duplicate results on JOIN

Body:
Here is my question : I am trying to get all the games of a class. the class can host a game, or have a game in another class.

games table have : guest_class (ID of class) and host_class(ID of class)

classes table have : id_class (ID of class)

An example I am trying to get the games of the class 1.
There are only 2 games with class 1.

id_game: 1, id_class: 1, host_class: 3, guest_class: 1,
id_game: 2, id_class: 1, host_class: 1, guest_class: 6,

Why am I getting duplicated results ?

QUERY

var classID = Number(req.query.searchValue);
var query = `SELECT * FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )`;
con2.query(query, [classID,classID] , function (err, result) {

RESULT

[ RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 3},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 6} ]

Body:
Would you try like this;

select * from games where id_game IN (
SELECT g.id_game FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )
group by g.id_game)


问:
Capture changes for the last 30 minutes from tables
I need only to capture the changes for last 30 minutes only in for the below query:

```<code>  SELECT
  P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
  FROM
  TABLE1 P,
  TABLE2 C,
  TABLE3 T
  WHERE
  PM.COL1(+)  = C.COL1
  AND T.COL2(+) = C.COL2
</code>```

TABLE 1, TABLE 2 AND TABLE3 each has a modification date column, but I think adding the following to the query logically won't be right and it might degrade the query execution performance

```<code> SELECT
 P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
 FROM
 TABLE1 P,
 TABLE2 C,
 TABLE3 T
 WHERE
 PM.COL1(+)  = C.COL1
 AND T.COL2(+) = C.COL2
 AND P.MODIFICATION_DATE > SYSDATE - 30
 AND C.MODIFICATION_DATE > SYSDATE - 30
 AND T.MODIFICATION_DATE > SYSDATE - 30;
</code>```

Also not all the 3 tables are updated at the same time, TABLE2 as an example last modification_date was yesterday at 11:00 am while TABLE3 modification_date is today at 2:00 pm.

How can I capture the latest 30 minutes changes between the tables?

答:
How can I capture the latest 30 minutes changes between the tables?

You can find the last 30 minutes activity for each COL1 and COL2 from one table using:

```<code>SELECT *
FROM   (
  SELECT C.*,
         MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1, COL2 ) AS last_mod_date
  FROM   TABLE2 C
)
WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
</code>```

If you just want the last 30 minutes for the entire table (rather than for each combination of COL1 and COL2) then remove the PARTITION BY COL1, COL2 clause to just leave it as OVER ().

So to get the last 30 minutes of each table you can do:

```<code>WITH C AS (
  SELECT *
  FROM   (
    SELECT C.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1, COL2 ) AS last_mod_date
    FROM   TABLE2 C
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
),
P AS (
  SELECT *
  FROM   (
    SELECT P.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1 ) AS last_mod_date
    FROM   TABLE1 P
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
),
T AS (
  SELECT *
  FROM   (
    SELECT T.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL2 ) AS last_mod_date
    FROM   TABLE2 T
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
)
SELECT P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
FROM   C
       LEFT OUTER JOIN P
       ON (    P.COL1  = C.COL1 )
       LEFT OUTER JOIN T
       ON (    T.COL2 = C.COL2 );
</code>```

Without some sample data and seeing what your expected results are it is difficult to know if you need/want the PARTITION BY clauses.

Body:
I need only to capture the changes for last 30 minutes only in for the below query:

  SELECT
  P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
  FROM
  TABLE1 P,
  TABLE2 C,
  TABLE3 T
  WHERE
  PM.COL1(+)  = C.COL1
  AND T.COL2(+) = C.COL2

TABLE 1, TABLE 2 AND TABLE3 each has a modification date column, but I think adding the following to the query logically won't be right and it might degrade the query execution performance

 SELECT
 P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
 FROM
 TABLE1 P,
 TABLE2 C,
 TABLE3 T
 WHERE
 PM.COL1(+)  = C.COL1
 AND T.COL2(+) = C.COL2
 AND P.MODIFICATION_DATE > SYSDATE - 30
 AND C.MODIFICATION_DATE > SYSDATE - 30
 AND T.MODIFICATION_DATE > SYSDATE - 30;

Also not all the 3 tables are updated at the same time, TABLE2 as an example last modification_date was yesterday at 11:00 am while TABLE3 modification_date is today at 2:00 pm.

How can I capture the latest 30 minutes changes between the tables?

Body:
How can I capture the latest 30 minutes changes between the tables?

You can find the last 30 minutes activity for each COL1 and COL2 from one table using:

SELECT *
FROM   (
  SELECT C.*,
         MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1, COL2 ) AS last_mod_date
  FROM   TABLE2 C
)
WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE

If you just want the last 30 minutes for the entire table (rather than for each combination of COL1 and COL2) then remove the PARTITION BY COL1, COL2 clause to just leave it as OVER ().

So to get the last 30 minutes of each table you can do:

WITH C AS (
  SELECT *
  FROM   (
    SELECT C.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1, COL2 ) AS last_mod_date
    FROM   TABLE2 C
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
),
P AS (
  SELECT *
  FROM   (
    SELECT P.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL1 ) AS last_mod_date
    FROM   TABLE1 P
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
),
T AS (
  SELECT *
  FROM   (
    SELECT T.*,
           MAX( MODIFICATION_DATE ) OVER ( PARTITION BY COL2 ) AS last_mod_date
    FROM   TABLE2 T
  )
  WHERE  MODIFICATION_DATE >= LAST_MOD_DATE - INTERVAL '30' MINUTE
)
SELECT P.COL1, P.COL2, P.COL3, C.COL1, C.COL2, T.COL1, T.COL2, P.COL4+T.COL4 AS "COL4"
FROM   C
       LEFT OUTER JOIN P
       ON (    P.COL1  = C.COL1 )
       LEFT OUTER JOIN T
       ON (    T.COL2 = C.COL2 );

Without some sample data and seeing what your expected results are it is difficult to know if you need/want the PARTITION BY clauses.


问:
can't get value from html tag
I'm trying to retrieve the value inside an html tag. I can retrieve the whole tag but not the value inside.

in app.component.html:

```<code><p #docTitle>the thing I want to extract</p>
</code>```

in app.component.ts

```<code>docTitle;

@ViewChild('docTitle') docTitle;

ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.value); //this gives me the whole tag
}
</code>```

i've tried

```<code><p id="docTitle">what I want to retrieve</p>
</code>```

with

```<code>document.getElementById('docTitle').value //same as above, gives whole tag
</code>```

The point of this whole thing is to retrieve the value (which is translated in different languages with i18n) in order to use it to settle the html page's title.

Thanks for the help.

答:
```<code>docTitle.getElementById('docTitle').innerText
</code>```

or

```<code>docTitle.getElementById('docTitle').textContent
</code>```

or

```<code>docTitle.getElementById('docTitle').innerHTML
</code>```

value is for input elements

Title: can't get value from html tag

Body:
I'm trying to retrieve the value inside an html tag. I can retrieve the whole tag but not the value inside.

in app.component.html:

the thing I want to extract

in app.component.ts

docTitle;

@ViewChild('docTitle') docTitle;

ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.value); //this gives me the whole tag
}

i've tried

what I want to retrieve

with

document.getElementById('docTitle').value //same as above, gives whole tag

The point of this whole thing is to retrieve the value (which is translated in different languages with i18n) in order to use it to settle the html page's title.

Thanks for the help.

Body:
docTitle.getElementById('docTitle').innerText

or

docTitle.getElementById('docTitle').textContent

or

docTitle.getElementById('docTitle').innerHTML

value is for input elements


问:
regular expression on method Pattern.compile()
i have to create a regular expression to put into the method Pattern.compile(regex);
My regex has to allow integer (without 0 at the beginning of the number),a sequence of numbers and char (A-Za-z),but the problem is the third point: a string that must begin and end with the char ' " ', must avoid the chars backslash (unless there isn't one other backslash) and the char '"' (unless there is before a backslash)

but i don't understand how to do the second point ( i have met a lot of errors), this is my java code:

```<code>public static void main(String[] args) {
    if (args.length == 0)
        throw new IllegalArgumentException();
    Matcher matcher = Pattern.compile("([a-zA-Z]+[0-9a-zA-Z_]*)|"
            + "(0(?![0-9])|([1-9]+)([0-9]*))|" //"?!" è una asserzione : " se la condizione tra parentesi è vera non considerare lo zero
            + "([\"]{1}(([\\\\][^\"\\][\\\"])*)[\"]{1})"
            + "|(\\s+)").matcher(args[0]);// \s = [ \t\n\x0B\f\r]
    System.out.println("Input: " + args[0]); //println va a capo dopo la stampa
    while (matcher.lookingAt()) {
        System.out.print("Lexeme '" + matcher.group() + "'"); //non va a capo dopo la stampa
        System.out.println(" group " + ExampleLexer.getGroup(matcher));
        matcher.region(matcher.end(), matcher.regionEnd());
    }

     //attenzione: matcher.hitEnd() restituisce true se il matcher arriva in fondo
     //all'input anche se l'ultimo match non ha avuto successo, quindi funziona solo
     //per espressioni regolari "semplici"
    if (matcher.regionStart() == matcher.regionEnd())
        System.out.println("All lexems succesfully matched");
    else {
        System.err.print("Unmatched lexem ");
        matcher.usePattern(Pattern.compile(".*"));
        matcher.lookingAt();
        System.err.println(matcher.group());
    }
}
</code>```

答:
```<code>"\"(\\\\.|[^\"\\\\])*\""            // (1)
"\"(\\\\[\"\\\\]|[^\"\\\\])*\""     // (2)
</code>```

quote

zero or more times (...)*

either backslash \ followed by (1) any char . / (2) any non-quote/non-backslash

or | not a quote, not a backslash [^ ... ]

quote

On the escapes:

\" is a String escape representing one char, the double quote.

\\ is the String escape representing a backslash, one char.

\\\\ is the regex escape \\ to represent the backslash itself instead of being a regex escape sequence itself.

If you ever want to replace backslashes, first attempt it without regex: s = s.replace("\\", "\\\\"); doubles every backslash. Guess how that is written in regex with replaceAll.

Body:
i have to create a regular expression to put into the method Pattern.compile(regex);
My regex has to allow integer (without 0 at the beginning of the number),a sequence of numbers and char (A-Za-z),but the problem is the third point: a string that must begin and end with the char ' " ', must avoid the chars backslash (unless there isn't one other backslash) and the char '"' (unless there is before a backslash)

but i don't understand how to do the second point ( i have met a lot of errors), this is my java code:

public static void main(String[] args) {
    if (args.length == 0)
        throw new IllegalArgumentException();
    Matcher matcher = Pattern.compile("([a-zA-Z]+[0-9a-zA-Z_]*)|"
            + "(0(?![0-9])|([1-9]+)([0-9]*))|" //"?!" è una asserzione : " se la condizione tra parentesi è vera non considerare lo zero
            + "([\"]{1}(([\\\\][^\"\\][\\\"])*)[\"]{1})"
            + "|(\\s+)").matcher(args[0]);// \s = [ \t\n\x0B\f\r]
    System.out.println("Input: " + args[0]); //println va a capo dopo la stampa
    while (matcher.lookingAt()) {
        System.out.print("Lexeme '" + matcher.group() + "'"); //non va a capo dopo la stampa
        System.out.println(" group " + ExampleLexer.getGroup(matcher));
        matcher.region(matcher.end(), matcher.regionEnd());
    }

     //attenzione: matcher.hitEnd() restituisce true se il matcher arriva in fondo
     //all'input anche se l'ultimo match non ha avuto successo, quindi funziona solo
     //per espressioni regolari "semplici"
    if (matcher.regionStart() == matcher.regionEnd())
        System.out.println("All lexems succesfully matched");
    else {
        System.err.print("Unmatched lexem ");
        matcher.usePattern(Pattern.compile(".*"));
        matcher.lookingAt();
        System.err.println(matcher.group());
    }
}

Body:
"\"(\\\\.|[^\"\\\\])*\""            // (1)
"\"(\\\\[\"\\\\]|[^\"\\\\])*\""     // (2)

quote

zero or more times (...)*

either backslash \ followed by (1) any char . / (2) any non-quote/non-backslash

or | not a quote, not a backslash [^ ... ]

quote

On the escapes:

\" is a String escape representing one char, the double quote.

\\ is the String escape representing a backslash, one char.

\\\\ is the regex escape \\ to represent the backslash itself instead of being a regex escape sequence itself.

If you ever want to replace backslashes, first attempt it without regex: s = s.replace("\\", "\\\\"); doubles every backslash. Guess how that is written in regex with replaceAll.


问:
Set a number of spinners to default
I have 18 spinners in a GridLayout with values assigned to each one manually(no adapters) in the activity layout. Now I want a "clear button" to call a method:"onClickClear" that sets each spinner to the default value.

Is there a way to do that without writing a reference to 18 spinners and using setSelection(0). I'm pretty new to Android and this is a proof of concept project I'm doing :)

答:
```<code>Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setSelection(pos);
</code>```

here pos is integer (your array item position)

array is like below then pos = 0;

```<code>String str[] = new String{"Select Gender","male", "female" };
</code>```

then in onItemSelected

```<code>@Override
public void onItemSelected(AdapterView<?> main, View view, int position,
        long Id) {

    if(position > 0){
      // get spinner value
    }else{
      // show toast select gender
    }

}
</code>```

Title: Set a number of spinners to default

Body:
Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setSelection(pos);

here pos is integer (your array item position)

array is like below then pos = 0;

String str[] = new String{"Select Gender","male", "female" };

then in onItemSelected

@Override
public void onItemSelected(AdapterView<?> main, View view, int position,
        long Id) {

    if(position > 0){
      // get spinner value
    }else{
      // show toast select gender
    }

}