问:
How to test if alert/error message is displayed
I have a property on my VM with validation:

```<code>private string _test;
[Required(ErrorMessage = "Required.")]
public string Test {
    get { return _test; }
    set { SetProperty(ref _test, value); }
}
</code>```

Reference to ValidationAttribute: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx

and this is my control from my View:

```<code><TextBox Grid.Column="1"
        Text="{Binding Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        Style="{StaticResource TextBoxStyle}"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Errors[Test][0]}"
        Style="{StaticResource ViewErrorStyle}"/>
</code>```

How can I unit test if the error message is shown?

Thanks

答:
You cannot use MVC annotation directly on uwp. You can use prism validation. Please refer to follow link for more information.
https://blogs.u2u.be/diederik/post/User-input-validation-with-Prism-and-data-annotations-on-the-UWP.

Some Sample code in views:

```<code>    <TextBox x:Name="Email"
             Header="Email"
             Text="{x:Bind Path=ViewModel.Email, Mode=TwoWay}"
             MaxLength="50"
             InputScope="EmailSmtpAddress"
             AutomationProperties.IsRequiredForForm="True" />

    <TextBlock Text="{x:Bind Path=ViewModel.Error_Email, Mode=TwoWay}"
               Foreground="Red"
               HorizontalAlignment="Right" />
</code>```

Some Sample code in view models:

```<code>    [EmailAddress(ErrorMessage = "Please enter valid email address")]
    [Required]
    public string Email
    {
        get { return _Email ?? string.Empty; }
        set
        {
            SetProperty(ref _Email, value);
            Error_Email = Errors[nameof(Email)].Count > 0 ? Errors[nameof(Email)][0] : string.Empty;
        }
    }

    public string Error_Email
    {
        get { return _error_Email ?? string.Empty; }
        set { SetProperty(ref _error_Email, value); }
    }
</code>```

Body:
I have a property on my VM with validation:

private string _test;
[Required(ErrorMessage = "Required.")]
public string Test {
    get { return _test; }
    set { SetProperty(ref _test, value); }
}

Reference to ValidationAttribute: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx

and this is my control from my View:

<TextBox Grid.Column="1"
        Text="{Binding Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        Style="{StaticResource TextBoxStyle}"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Errors[Test][0]}"
        Style="{StaticResource ViewErrorStyle}"/>

How can I unit test if the error message is shown?

Thanks

Body:
You cannot use MVC annotation directly on uwp. You can use prism validation. Please refer to follow link for more information.
https://blogs.u2u.be/diederik/post/User-input-validation-with-Prism-and-data-annotations-on-the-UWP.

Some Sample code in views:

    <TextBox x:Name="Email"
             Header="Email"
             Text="{x:Bind Path=ViewModel.Email, Mode=TwoWay}"
             MaxLength="50"
             InputScope="EmailSmtpAddress"
             AutomationProperties.IsRequiredForForm="True" />

    <TextBlock Text="{x:Bind Path=ViewModel.Error_Email, Mode=TwoWay}"
               Foreground="Red"
               HorizontalAlignment="Right" />

Some Sample code in view models:

    [EmailAddress(ErrorMessage = "Please enter valid email address")]
    [Required]
    public string Email
    {
        get { return _Email ?? string.Empty; }
        set
        {
            SetProperty(ref _Email, value);
            Error_Email = Errors[nameof(Email)].Count > 0 ? Errors[nameof(Email)][0] : string.Empty;
        }
    }

    public string Error_Email
    {
        get { return _error_Email ?? string.Empty; }
        set { SetProperty(ref _error_Email, value); }
    }


来源: stackexchange

问:
get indexPath of UITableViewCell on click of Button from Cell

I have a button (red color cross) in the UITableViewCell and on click of that button I want to get indexPath of the UITableViewCell.

Right now I am assigning tag to each of the button like this
cell.closeButton.tag = indexPath.section
and the on click of the button I get the indexPath.section value like this:

```<code>@IBAction func closeImageButtonPressed(sender: AnyObject) {
  data.removeAtIndex(sender.tag)
  tableView.reloadData()
}
</code>```

Is this the right way of implementation or is there any other clean way to do this?

答:
How to get cell indexPath for tapping button in Swift 4 with button selector</p>

```<code>@objc func buttonClicked(_sender:UIButton){

 let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView)
 let indexPath = self.tableView.indexPathForRow(at:buttonPosition)
 let cell = self.tableView.cellForRow(at: indexPath) as! UITableViewCell
 print(cell.itemLabel.text)//print or get item
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a button (red color cross) in the UITableViewCell and on click of that button I want to get indexPath of the UITableViewCell.

Right now I am assigning tag to each of the button like this
cell.closeButton.tag = indexPath.section
and the on click of the button I get the indexPath.section value like this:

@IBAction func closeImageButtonPressed(sender: AnyObject) {
  data.removeAtIndex(sender.tag)
  tableView.reloadData()
}

Is this the right way of implementation or is there any other clean way to do this?

Body:
How to get cell indexPath for tapping button in Swift 4 with button selector

@objc func buttonClicked(_sender:UIButton){

 let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView)
 let indexPath = self.tableView.indexPathForRow(at:buttonPosition)
 let cell = self.tableView.cellForRow(at: indexPath) as! UITableViewCell
 print(cell.itemLabel.text)//print or get item
}


问:
PHP login access doesn't working in web server
I am making a login system. But, I don't know whats the problem. When I checked by the right email and password or wrong email and password it show my error message Please enter valid Email/Password!! . I am using Php 7.1.7 . Also when I add wrong db username, password and table it doesn't show any error.
My Php code:

```<code>$mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";
$result = $mysqli->query($query);
$num_log = $result->num_rows;

if($num_log == 1){

        while($row = $result->fetch_object()){
            echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

        }
}else{

    echo "Please enter valid Email/Password!!";
}
</code>```

My database table structure:

答:
I think this is not the right way to go. The simplest is to add a "Role" column and determine if the client is "admin", "customer" or any other level that you want to have, so you can manage multiple admin with each own access.
For the code it will be enough for you to check what is the "Role" of your client and to display the corresponding message / page.</p>

```<code>            <?php
            $mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

            if ($mysqli->connect_errno) {
                printf("Echec de la connexion: %s\n", $mysqli->connect_error);
                exit();
            }

            $result = $mysqli->query("SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='");
            $row = $result->num_rows;

            if($row == 1){

                        echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

            }else{

                echo "Please enter valid Email/Password!!";
            }

            ?>
</code>```

Body:
I am making a login system. But, I don't know whats the problem. When I checked by the right email and password or wrong email and password it show my error message Please enter valid Email/Password!! . I am using Php 7.1.7 . Also when I add wrong db username, password and table it doesn't show any error.
My Php code:

$mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";
$result = $mysqli->query($query);
$num_log = $result->num_rows;

if($num_log == 1){

        while($row = $result->fetch_object()){
            echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

        }
}else{

    echo "Please enter valid Email/Password!!";
}

My database table structure:

Body:
I think this is not the right way to go. The simplest is to add a "Role" column and determine if the client is "admin", "customer" or any other level that you want to have, so you can manage multiple admin with each own access.
For the code it will be enough for you to check what is the "Role" of your client and to display the corresponding message / page.

            <?php
            $mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

            if ($mysqli->connect_errno) {
                printf("Echec de la connexion: %s\n", $mysqli->connect_error);
                exit();
            }

            $result = $mysqli->query("SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='");
            $row = $result->num_rows;

            if($row == 1){

                        echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

            }else{

                echo "Please enter valid Email/Password!!";
            }

            ?>


问:
Raw Input an alternative keyboard hook?
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

```<code>RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));
</code>```

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers

答: not sure exactly about raw input, but for keyboard hook in general you need to make it a dll and register in system so it will be loaded by every process. some details here in remarks</p>

ContentLicense: CC BY-SA 2.5

Title: Raw Input an alternative keyboard hook?

Body:
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers


问:
In MediaWiki: Check if user account is blocked within page
In MediaWiki I'd like to create a page that links to a user account. As we use blocking in order to deactivate user accounts (as there is no other way provided to achieve this) it would be nice to present a note next to a link if the account has been blocked. Therefor I require some way to distinguish between different states of a user account.

Therefor my question: Is there a parser function or some other kind of instrument to detect if a user account is blocked? I can't find one. Or is there some other way how to achieve this functionality within a page?

Note: Deleting a user page is not an option. There is an {{#ifexist}} parser function which could check for existence of a page but I do not want to delete the user pages and do not want to confuse admins. The "user-is-blocked" flag is the only thing available that we could perform some kind of branching on. Do you have any ideas how to accomplish this?

答:
You could install the markblocked gadget from English Wikipedia. This would do it client-side and not as part of the page parse, which is sort of preferable as it reacts better to changes in blockedness of a user (and will work on any link to the user, regardless of how it's added to the wiki).

There is currently talk about the possibility of turning this gadget into an extension; see T180555 for more about that (it'd make it easier to install).

Also, the extension might work for displaying indicators about membership of different groups (this is what the markadmins gadget does), so for example you could change your workflow to, rather than blocking old users, adding them to a 'noncurrent' user group (and giving that group no rights). Then, you could vary the display of the usernames according to user group.


问:
Playing a Configurable Number of MP3 Files in Succession
So I will have the user select a range of tracks (all tracks are numbered) from a select box.  So if I select the numbers 1 and 34, I want all 34 .mp3 files to be played, with each .mp3 file playing as soon as the previous one ends.

What would be the simplest way to do this in Javascript/Jquery? Will I have to load each individual audio file, and clear the last one played?  What are your suggestions/recommendations?

答:
The most simple answer is -

using audio html element

push the list of mp3 files path in an array

add event listener on audio element for ended event, inside the callback function simple pop the mp3 files and assign it to audio src that's it

No you don't have to clear the last played file because browser has it's own pruning logic, although you can have your pruning logic at more granular level but that is required only when you have lot's of video elements of high resolution preventing your system's memory to consumed too much.

Hope it helps-


问:
java.io.FileNotFoundException for Cloud Iot core Code
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

```<code>W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)
</code>```

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

```<code>package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

The MqttExample.java

```<code>package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}
</code>```

and the MqttExampleOptions.java code:

```<code>package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}
</code>```

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.

答:
The example you are following is not designed for Android.

res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";

Will not relate to the same directory on the Android file system.

I wrote up an AndroidThings explanation of how to talk to Cloud IoT Core here: http://blog.blundellapps.co.uk/tut-google-cloud-iot-core-mqtt-on-android/

You can setup communication like this (with your pem file going into the /raw directory)

```<code>// Setup the communication with your Google IoT Core details
        communicator = new IotCoreCommunicator.Builder()
                .withContext(this)
                .withCloudRegion("your-region") // ex: europe-west1
                .withProjectId("your-project-id")   // ex: supercoolproject23236
                .withRegistryId("your-registry-id") // ex: my-devices
                .withDeviceId("a-device-id") // ex: my-test-raspberry-pi
                .withPrivateKeyRawFileId(R.raw.rsa_private)
                .build();
</code>```

Source code is here: https://github.com/blundell/CloudIoTCoreMQTTExample

Note that the above is good enough for a secure environment or for testing that the end to end works. However if you wanted to release a production IoT device, you would look at embedding the PEM into the ROM and using private file storage access. https://developer.android.com/training/articles/keystore.html

An example of this can be found here: https://github.com/androidthings/sensorhub-cloud-iot

Specifically this class:

https://github.com/androidthings/sensorhub-cloud-iot/blob/e50bde0100fa81818ebbadb54561b3b68ccb64b8/app/src/main/java/com/example/androidthings/sensorhub/cloud/cloudiot/MqttAuthentication.java

You can then generate and use the PEM on the device:

```<code>  public Certificate getCertificate() {
    KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
    ks.load(null);

    certificate = ks.getCertificate("Cloud IoT Authentication");
    if (certificate == null) {
      Log.w(TAG, "No IoT Auth Certificate found, generating new cert");
      generateAuthenticationKey();
      certificate = ks.getCertificate(keyAlias);
    }
    Log.i(TAG, "loaded certificate: " + keyAlias);
 }
</code>```

and

```<code>    private void generateAuthenticationKey() throws GeneralSecurityException {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
      kpg.initialize(new KeyGenParameterSpec.Builder("Cloud IoT Authentication",KeyProperties.PURPOSE_SIGN)
       .setKeySize(2048)
       .setCertificateSubject(new X500Principal("CN=unused"))
       .setDigests(KeyProperties.DIGEST_SHA256)
     .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
       .build());

      kpg.generateKeyPair();
   }
</code>```

Body:
I am presently working on program on Android Things for connecting to Google Cloud IoT Core. I used to sample maven code provided by Google and modified it for Gradle(with all the imports and stuff). After doing every kind of check, whenever I am trying to run the program on a Raspberry Pi3 running Android Things it keeps giving this error

W/System.err: java.io.FileNotFoundException: com/example/adityaprakash/test/rsa_private.pem (No such file or directory)

telling me that the private key file that I am supposed to use for the JWT doesn't exist despite the fact it does and I have given the path for the pem file.Here are my java codes

package com.example.adityaprakash.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        Log.i("#########","######");
        MqttExample mqtt = new MqttExample();
        try {
            mqtt.Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The MqttExample.java

package com.example.adityaprakash.test;
// [END cloudiotcore_mqtt_imports]
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.joda.time.DateTime;

import java.io.BufferedReader;
import java.io.FileReader;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import android.util.Base64;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class MqttExample {

    // [START cloudiotcore_mqtt_createjwt]
    /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
    public static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
        DateTime now = new DateTime();

        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(privateKeyFile));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        // Create a JWT to authenticate this device. The device will be disconnected after the token
        // expires, and will have to reconnect with a new token. The audience field should always be set
        // to the GCP project id.
        JwtBuilder jwtBuilder =
                Jwts.builder()
                        .setIssuedAt(now.toDate())
                        .setExpiration(now.plusMinutes(20).toDate())
                        .setAudience(projectId);
        String privateKeyPEM = strKeyPEM;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decode(privateKeyPEM,Base64.DEFAULT);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
    }

    /** Parse arguments, configure MQTT, and publish messages. */
    public void Start() throws Exception {
        // [START cloudiotcore_mqtt_configuremqtt]
        MqttExampleOptions options = MqttExampleOptions.values();
        if (options == null) {
            // Could not parse.
            System.exit(1);
        }
        // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
        // connections are accepted. For server authentication, the JVM's root certificates
        // are used.
        final String mqttServerAddress =
                String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);

        // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
        // Google Cloud IoT Core, it must be in the format below.
        final String mqttClientId =
                String.format(
                        "projects/%s/locations/%s/registries/%s/devices/%s",
                        options.projectId, options.cloudRegion, options.registryId, options.deviceId);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        // Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
        // explictly set this. If you don't set MQTT version, the server will immediately close its
        // connection to your device.
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
        // Paho client library to send the password field. The password field is used to transmit a JWT
        // to authorize the device.
        connectOptions.setUserName("unused");

        System.out.println(options.algorithm);
        if (options.algorithm.equals("RS256")) {
            connectOptions.setPassword(
                    createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
        }else {
            throw new IllegalArgumentException(
                    "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
        }
        // [END cloudiotcore_mqtt_configuremqtt]

        // [START cloudiotcore_mqtt_publish]
        // Create a client, and connect to the Google MQTT bridge.
        MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
        try {
            client.connect(connectOptions);

            // Publish to the events or state topic based on the flag.
            String subTopic = options.messageType.equals("event") ? "events" : options.messageType;

            // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
            // required to be in the format below. Note that this is not the same as the device registry's
            // Cloud Pub/Sub topic.
            String mqttTopic = String.format("/devices/%s/%s", options.deviceId, subTopic);

            // Publish numMessages messages to the MQTT bridge, at a rate of 1 per second.
            for (int i = 1; i <= options.numMessages; ++i) {
                String payload = String.format("%s/%s-payload number-%d", options.registryId, options.deviceId, i);
                System.out.format(
                        "Publishing %s message %d/%d: '%s'\n",
                        options.messageType, i, options.numMessages, payload);

                // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(mqttTopic, message);

                if (options.messageType.equals("event")) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                }
                else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        } finally {
            // Disconnect the client and finish the run.
            client.disconnect();
        }
        System.out.println("Finished loop successfully. Goodbye!");
        // [END cloudiotcore_mqtt_publish]
    }

}

and the MqttExampleOptions.java code:

package com.example.adityaprakash.test;

public class MqttExampleOptions {
    String projectId;
    String registryId;
    String deviceId;
    String privateKeyFile;
    String algorithm;
    String cloudRegion;
    int numMessages;
    String mqttBridgeHostname;
    short mqttBridgePort;
    String messageType;

    /** Construct an MqttExampleOptions class. */
    public static MqttExampleOptions values() {

        try {

            MqttExampleOptions res = new MqttExampleOptions();

            res.projectId = "_";
            res.registryId = "_";
            res.deviceId = "_";
            res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";
            res.algorithm = "RS256";
            res.cloudRegion = "asia-east1";
            res.numMessages = 100;
            res.mqttBridgeHostname = "mqtt.googleapis.com";
            res.mqttBridgePort = 8883;
            res.messageType = "event";
            return res;

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}

Please can anyone give a solution to this problem.

P.S. I know the code looks totally crappy.I don't have experience with Android programming,so please let it go.

Body:
The example you are following is not designed for Android.

res.privateKeyFile = "com/example/adityaprakash/test/rsa_private.pem";

Will not relate to the same directory on the Android file system.

I wrote up an AndroidThings explanation of how to talk to Cloud IoT Core here: http://blog.blundellapps.co.uk/tut-google-cloud-iot-core-mqtt-on-android/

You can setup communication like this (with your pem file going into the /raw directory)

// Setup the communication with your Google IoT Core details
        communicator = new IotCoreCommunicator.Builder()
                .withContext(this)
                .withCloudRegion("your-region") // ex: europe-west1
                .withProjectId("your-project-id")   // ex: supercoolproject23236
                .withRegistryId("your-registry-id") // ex: my-devices
                .withDeviceId("a-device-id") // ex: my-test-raspberry-pi
                .withPrivateKeyRawFileId(R.raw.rsa_private)
                .build();

Source code is here: https://github.com/blundell/CloudIoTCoreMQTTExample

Note that the above is good enough for a secure environment or for testing that the end to end works. However if you wanted to release a production IoT device, you would look at embedding the PEM into the ROM and using private file storage access. https://developer.android.com/training/articles/keystore.html

An example of this can be found here: https://github.com/androidthings/sensorhub-cloud-iot

Specifically this class:

https://github.com/androidthings/sensorhub-cloud-iot/blob/e50bde0100fa81818ebbadb54561b3b68ccb64b8/app/src/main/java/com/example/androidthings/sensorhub/cloud/cloudiot/MqttAuthentication.java

You can then generate and use the PEM on the device:

  public Certificate getCertificate() {
    KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
    ks.load(null);

    certificate = ks.getCertificate("Cloud IoT Authentication");
    if (certificate == null) {
      Log.w(TAG, "No IoT Auth Certificate found, generating new cert");
      generateAuthenticationKey();
      certificate = ks.getCertificate(keyAlias);
    }
    Log.i(TAG, "loaded certificate: " + keyAlias);
 }

and

    private void generateAuthenticationKey() throws GeneralSecurityException {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
      kpg.initialize(new KeyGenParameterSpec.Builder("Cloud IoT Authentication",KeyProperties.PURPOSE_SIGN)
       .setKeySize(2048)
       .setCertificateSubject(new X500Principal("CN=unused"))
       .setDigests(KeyProperties.DIGEST_SHA256)
     .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
       .build());

      kpg.generateKeyPair();
   }


问:
Problem installing mysql gem on Snow Leopard: uninitialized constant MysqlCompat::MysqlRes
I've got a problem trying to install the Ruby mysql gem driver.

I recently upgraded to Snow Leopard and did the Hivelogic manual install of MySQL. This all seems to work fine as I can access mysql from the command line and make changes to the database.

My problem is that if I now use

```<code>rake db:migrate
</code>```

I get:

```<code>rake aborted!
uninitialized constant MysqlCompat::MysqlRes

(See full trace by running task with --trace)
</code>```

Now it appears that my mysql gem isn't working correctly as I can access MySQL fine from Python using the Python driver (which I compiled to). I therefore tried to rebuild the gem using the following command from this site: http://techliberty.blogspot.com/, (incidentally I am using a recent Intel MacBook Pro):

```<code>  sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
</code>```

This compiles although I get No definition for the documentation:

```<code>  Building native extensions.  This could take a while...
  Successfully installed mysql-2.8.1
  1 gem installed
  Installing ri documentation for mysql-2.8.1...

  No definition for next_result

  No definition for field_name
  ...
</code>```

I'm a little stumped as my mysql_config is located in the correct place:

```<code> /usr/local/mysql/bin/mysql_config
</code>```

And I have removed all other instances of the mysql gem, from my system.

Any suggestions would be greatly appreciated. Many thanks.

PS I saw this previous post uninitialized constant MysqlCompat::MysqlRes (using mms2r gem) but it doesn't seem applicable for my version.

答:
If you're using MySQL 5.5, these are the steps that made it work for us:

Command to install mysql-2.8.1:

```<code>sudo env ARCHFLAGS="-arch x86_64" gem install --no-rdoc --no-ri  mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
</code>```

Command to make mysql-2.8.1 work with mysql 5.5:

```<code>sudo ln -s ../mysql/lib/libmysqlclient.16.dylib libmysqlclient.16.dylib
</code>```

Hope that helps!

Body:
I've got a problem trying to install the Ruby mysql gem driver.

I recently upgraded to Snow Leopard and did the Hivelogic manual install of MySQL. This all seems to work fine as I can access mysql from the command line and make changes to the database.

My problem is that if I now use

rake db:migrate

I get:

rake aborted!
uninitialized constant MysqlCompat::MysqlRes

(See full trace by running task with --trace)

Now it appears that my mysql gem isn't working correctly as I can access MySQL fine from Python using the Python driver (which I compiled to). I therefore tried to rebuild the gem using the following command from this site: http://techliberty.blogspot.com/, (incidentally I am using a recent Intel MacBook Pro):

  sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

This compiles although I get No definition for the documentation:

  Building native extensions.  This could take a while...
  Successfully installed mysql-2.8.1
  1 gem installed
  Installing ri documentation for mysql-2.8.1...

  No definition for next_result

  No definition for field_name
  ...

I'm a little stumped as my mysql_config is located in the correct place:

 /usr/local/mysql/bin/mysql_config

And I have removed all other instances of the mysql gem, from my system.

Any suggestions would be greatly appreciated. Many thanks.

PS I saw this previous post uninitialized constant MysqlCompat::MysqlRes (using mms2r gem) but it doesn't seem applicable for my version.

Body:
If you're using MySQL 5.5, these are the steps that made it work for us:

Command to install mysql-2.8.1:

sudo env ARCHFLAGS="-arch x86_64" gem install --no-rdoc --no-ri  mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Command to make mysql-2.8.1 work with mysql 5.5:

sudo ln -s ../mysql/lib/libmysqlclient.16.dylib libmysqlclient.16.dylib

Hope that helps!


问:
docker-compose replays past output on container reboot
It appears that docker-compose replays captured output on container re-launch.  This is against expectation, and is misleading about what my container is actually doing.  Can this be disabled?

For instance,

I have a simple service that logs and exits w/ code 0.

In docker-compose.yml, i have restart: always set.

When running docker-compose up, each time the logging container comes back up after existing, I see all previous output relogged, plus any new additions from the current run.

Here's an easy to run example.

clone, cd <project>/fluentd, docker-compose build, & docker-compose up

I'm using docker-compose version 1.16.1, build 6d1ac21 on OSX.

Tips would be great!

答: Ok. Did you try to remove the restart always for your container? </p>


问:
nodejs, launch an executable file and exit node process
I am writing an application in node that does some verification and configuration and should then launch another process and exit.

I want this new process to run in the same console window and to use the same output and accept keyboard input from the console.

Is this possible with node? I know that I can create child processes but as far as I am aware they will die when node exits.

Thanks

答:
You may find some help in answer at below link at stackoverflow. It suggests running the two separate scripts (one where node.js configures options for 'new process' and second where your "new process" will run) separated with '&' character in terminal.

How do you run multiple programs in parallel from a bash script?

Using it, you might need to change in your node.js script so that you could be able to run the 'new process' directly from terminal instead of launching it through node script. Just configure options through node.js script and launch the process from terminal.


问:
CoordinatorLayout and toolbar and TabLayout sometimes cannot work move right and left scroll
I make the collapse toolbar activity use the CoordinatorLayout.

1. main_activity

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:background="@android:color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:background="?attr/colorPrimary"
            android:paddingLeft="@dimen/layout_margin"
            android:theme="@style/ThemeToolbar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:layout_collapseMode="pin"/>
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@color/text_space"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="2dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </android.support.v4.widget.SwipeRefreshLayout>
    <android.support.design.widget.FloatingActionButton
        android:visibility="gone"
        android:id="@+id/fabButton_menu"
        android:src="@drawable/plus"
        app:fabSize="normal"
        app:backgroundTint="@color/color_family"
        app:borderWidth="0dp"
        style="@style/FabStyle_Normal"/>
</android.support.design.widget.CoordinatorLayout>
</code>```

2. code

```<code>pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new TabFragment_Home(), "T1");
pagerAdapter.addFragment(new TabFragment_Pharm(),"T2");
pagerAdapter.addFragment(new TabFragment_Family(), "T3");
pagerAdapter.addFragment(new TabFragment_Board(), "T4");

viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager, false);
</code>```

This code is very simple and basic code.
I have one question the scroll action please see the image below.

Question: why cannot scroll move right? this is bug or my mistake? please let me know. thanks

答:
programmatically you can also set scrollable mode: </p>

```<code>tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
</code>```

Body:
I make the collapse toolbar activity use the CoordinatorLayout.

1. main_activity

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:background="@android:color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:background="?attr/colorPrimary"
            android:paddingLeft="@dimen/layout_margin"
            android:theme="@style/ThemeToolbar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:layout_collapseMode="pin"/>
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@color/text_space"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="2dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </android.support.v4.widget.SwipeRefreshLayout>
    <android.support.design.widget.FloatingActionButton
        android:visibility="gone"
        android:id="@+id/fabButton_menu"
        android:src="@drawable/plus"
        app:fabSize="normal"
        app:backgroundTint="@color/color_family"
        app:borderWidth="0dp"
        style="@style/FabStyle_Normal"/>
</android.support.design.widget.CoordinatorLayout>

2. code

pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new TabFragment_Home(), "T1");
pagerAdapter.addFragment(new TabFragment_Pharm(),"T2");
pagerAdapter.addFragment(new TabFragment_Family(), "T3");
pagerAdapter.addFragment(new TabFragment_Board(), "T4");

viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager, false);

This code is very simple and basic code.
I have one question the scroll action please see the image below.

Question: why cannot scroll move right? this is bug or my mistake? please let me know. thanks

Body:
programmatically you can also set scrollable mode:

tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);


问:
Post JavaScript Array to Codeigniter Framework (MVC) Controller Function
I have this problem with assigning a certain array variable. When I post it to Codeigniter Controller, It produces this error Click to view Image.

View:

      <button type="button" onClick="submit();">SUBMIT</button>

```
</div>
</div>
</p>

<p>Controller:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public function save_Production()
{

    $table = json_decode($_POST['pTableData'],true);
    $msg = $table['table1'];
    echo $msg;

}</code>```

答:
try this</p>

```<code>function submit()
{
    var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
    //var Data = JSON.stringify(TableData);
    $.ajax({
        type: "POST",
        url: "http://janncomputing/tabulation/judges/save_Production",
        dataType: 'json',
        data: {pTableData : TableData},
        success: function(result){ //retrieve data
            alert('Success');
            alert(result); //alert it
        }//success
    });
}
</code>```

Body:
I have this problem with assigning a certain array variable. When I post it to Codeigniter Controller, It produces this error Click to view Image.

View:

      <button type="button" onClick="submit();">SUBMIT</button>

Controller:

public function save_Production()
{

    $table = json_decode($_POST['pTableData'],true);
    $msg = $table['table1'];
    echo $msg;

}

Body:
try this

function submit()
{
    var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
    //var Data = JSON.stringify(TableData);
    $.ajax({
        type: "POST",
        url: "http://janncomputing/tabulation/judges/save_Production",
        dataType: 'json',
        data: {pTableData : TableData},
        success: function(result){ //retrieve data
            alert('Success');
            alert(result); //alert it
        }//success
    });
}


问:
Sockets, communication stops
I have a simple question about socket programming. I've done to implement a server and two clients as following codes, but all of sudden it stops while it communicates each other. I have no idea why it happens all the time.

Would you give me advice, hint, or help?

Thank you for your time.

Client

```<code># simple client

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 12345

buf = 100

s.connect((host, port))
i = 0

timestep = 0

while(1):
    k = '01'#+str(timestep)
    #1
    s.send(k)
    print 'sending message is', k

    #2
    v = s.recv(buf)
    print v

    if v == 'hold 01':
        print 'timestep is', timestep#'send the previous message'
        if timestep == 0:
            timestep == 0
        else:
            timestep -= 1
    else:
        print 'read data'
        FILE = open("datainfo1.txt", "r+")
        msg = FILE.read()
        FILE.close()

        #3
        while(1):
            tmp, msg = msg[:buf], msg[buf:]

            s.send(tmp)

            print len(tmp)

            if len(tmp) < buf:
                print 'break'
                break
        # send file
    i+=1
    timestep+=1
print 'end'
s.close()
</code>```

Server

```<code>import socket, sys

# set up listening socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345

# bind lstn socket to this port
lstn.bind(("", port))
lstn.listen(5)

# initialize buffer size
buf = 100

# initialize concatenate string, v
v = ''

# initialize client socket list
cs = []
check = [0, 0]

# a fixed number of clients
nc = 1

count = 0
status = [0,0]
j = 0
step = [0,0]

for i in range(nc):
    (clnt,ap) = lstn.accept()
    clnt.setblocking(0)
    cs.append(clnt)

file = open("output_analysis.txt","w+")

while (len(cs) > 0):
    clnt = cs.pop(0)
    cs.append(clnt)

    try:
        #1
        k = clnt.recv(buf)
        print "k=",k,"\n"#[:2]
        if k == '01':
            print "1st client connected", status[0]
            file.write("1st\t")

            if status[0] == 0:
                v = 'hold 01'
                check[0] = 1
            elif status[0] == 1:
                v = 'go 01'
                # status[0] = 0

            print v, "the message\n"

            file.write(v)
            file.write("\t")
            #2
            clnt.send(v)

            if status[0] == 1:

                FILE = open("client1.txt","w+")
                print 'receive 01'
                #3
                while(1):
                    status[0] = 0
                    print '1st : receiving'
                    msg = clnt.recv(buf)
                    print len(msg)

                    if len(msg) < buf:
                        print 'break'
                        #FILE.close()
                        break

        elif k == '02':
            print "2nd client connected", status[0]
            file.write("2nd\t")

            if status[1] == 0:
                v = 'hold 02'
                check[1] = 1
            elif status[1] == 1:
                v = 'go 02'
                # status[0] = 0

            print v, "the message\n"

            file.write(v)
            file.write("\t")
            #2
            clnt.send(v)

            if status[1] == 1:

                FILE = open("client2.txt","w+")
                print 'receive 02'
                #3
                while(1):
                    status[1] = 0
                    print '2nd : receiving'
                    msg = clnt.recv(buf)
                    print len(msg)

                    if len(msg) < buf:
                        print 'break'
                        #FILE.close()
                        break

        if check[0] == 1:# and check[1] == 1:
            print j, 'here\n'
            j += 1
            for i in range(2):
                check[i] = 0
                status[i] = 1 # which means, all clients are connected
            print check, status
        else:
            print 'hello'

    except: pass

file.close()
lstn.close()
</code>```

答:
```<code>except: pass
</code>```

You're ignoring all exceptions. This is a bad idea, because it doesn't let you know when things go wrong. You'll need to remove that except handler before you can reasonably debug your code.

Title: Sockets, communication stops

Body:
I have a simple question about socket programming. I've done to implement a server and two clients as following codes, but all of sudden it stops while it communicates each other. I have no idea why it happens all the time.

Would you give me advice, hint, or help?

Thank you for your time.

Client

# simple client

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 12345

buf = 100

s.connect((host, port))
i = 0

timestep = 0

while(1):
    k = '01'#+str(timestep)
    #1
    s.send(k)
    print 'sending message is', k

    #2
    v = s.recv(buf)
    print v

    if v == 'hold 01':
        print 'timestep is', timestep#'send the previous message'
        if timestep == 0:
            timestep == 0
        else:
            timestep -= 1
    else:
        print 'read data'
        FILE = open("datainfo1.txt", "r+")
        msg = FILE.read()
        FILE.close()

        #3
        while(1):
            tmp, msg = msg[:buf], msg[buf:]

            s.send(tmp)

            print len(tmp)

            if len(tmp) < buf:
                print 'break'
                break
        # send file
    i+=1
    timestep+=1
print 'end'
s.close()

Server

import socket, sys

# set up listening socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345

# bind lstn socket to this port
lstn.bind(("", port))
lstn.listen(5)

# initialize buffer size
buf = 100

# initialize concatenate string, v
v = ''

# initialize client socket list
cs = []
check = [0, 0]

# a fixed number of clients
nc = 1

count = 0
status = [0,0]
j = 0
step = [0,0]

for i in range(nc):
    (clnt,ap) = lstn.accept()
    clnt.setblocking(0)
    cs.append(clnt)

file = open("output_analysis.txt","w+")

while (len(cs) > 0):
    clnt = cs.pop(0)
    cs.append(clnt)

    try:
        #1
        k = clnt.recv(buf)
        print "k=",k,"\n"#[:2]
        if k == '01':
            print "1st client connected", status[0]
            file.write("1st\t")

            if status[0] == 0:
                v = 'hold 01'
                check[0] = 1
            elif status[0] == 1:
                v = 'go 01'
                # status[0] = 0

            print v, "the message\n"

            file.write(v)
            file.write("\t")
            #2
            clnt.send(v)

            if status[0] == 1:

                FILE = open("client1.txt","w+")
                print 'receive 01'
                #3
                while(1):
                    status[0] = 0
                    print '1st : receiving'
                    msg = clnt.recv(buf)
                    print len(msg)

                    if len(msg) < buf:
                        print 'break'
                        #FILE.close()
                        break

        elif k == '02':
            print "2nd client connected", status[0]
            file.write("2nd\t")

            if status[1] == 0:
                v = 'hold 02'
                check[1] = 1
            elif status[1] == 1:
                v = 'go 02'
                # status[0] = 0

            print v, "the message\n"

            file.write(v)
            file.write("\t")
            #2
            clnt.send(v)

            if status[1] == 1:

                FILE = open("client2.txt","w+")
                print 'receive 02'
                #3
                while(1):
                    status[1] = 0
                    print '2nd : receiving'
                    msg = clnt.recv(buf)
                    print len(msg)

                    if len(msg) < buf:
                        print 'break'
                        #FILE.close()
                        break

        if check[0] == 1:# and check[1] == 1:
            print j, 'here\n'
            j += 1
            for i in range(2):
                check[i] = 0
                status[i] = 1 # which means, all clients are connected
            print check, status
        else:
            print 'hello'

    except: pass

file.close()
lstn.close()

Body:
except: pass

You're ignoring all exceptions. This is a bad idea, because it doesn't let you know when things go wrong. You'll need to remove that except handler before you can reasonably debug your code.


问:
Generating Multiple Apk according to the Native ABI
I am building release apk based on the ABI because of apk size to publish on Play store.

So I started apk building for ABI = armeabi-v7a then building ABI = x86 and ABI = areambi

so my gradle look like this

app gradle

```<code>android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.package"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        ndk {
            abiFilters "armeabi-v7a"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
    splits {
        // Configures multiple APKs based on ABI.
        abi {
            // Enables building multiple APKs per ABI.
            enable true
            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "armeabi-v7a"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk false
        }
    }
}
</code>```

So my question

I need to make changes in versionCode 1 for each ABI, so which version code for which ABI should I use.

答:
```<code>productFlavors{

    arm{
        ndk{
            abiFilters "arm64-v8a" , "armeabi"  , "armeabi-v7a"
        }
    }
    x86{
        ndk{
            abiFilters "x86" , "x86_64"
        }
    }
}
</code>```

Body:
I am building release apk based on the ABI because of apk size to publish on Play store.

So I started apk building for ABI = armeabi-v7a then building ABI = x86 and ABI = areambi

so my gradle look like this

app gradle

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.package"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        ndk {
            abiFilters "armeabi-v7a"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
    splits {
        // Configures multiple APKs based on ABI.
        abi {
            // Enables building multiple APKs per ABI.
            enable true
            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "armeabi-v7a"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk false
        }
    }
}

So my question

I need to make changes in versionCode 1 for each ABI, so which version code for which ABI should I use.


问:
MySQL split cell into multiple rows but copying the remaining row data
We have a table like the following:

```<code>|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE, Sony     | 10
|  123456 | GE           | 25
</code>```

We need to split the rows where more than one manufacturer is listed, and copy the remaining row data (SKU is not unique). So the expected results would be following:

```<code>|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE           | 10 |
|  12345  | Sony         | 10 |
|  123456 | GE           | 25 |
</code>```

Can this be even done with MySQL, if so the how? If not, what would other options be then?

答:
Try the answer:

```<code>CREATE TABLE Temp (SKU INT, Manufacturer VARCHAR(15),Qty INT);
INSERT INTO Temp VALUES(12345,'GE, Sony',10);
INSERT INTO Temp VALUES(123456,'GE',25);

select
  Temp.SKU,
  SUBSTRING_INDEX(SUBSTRING_INDEX(Temp.Manufacturer, ',', numbers.n), ',', -1) Manufacturer,
  Temp.Qty
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN Temp
  on CHAR_LENGTH(Temp.Manufacturer)
     -CHAR_LENGTH(REPLACE(Temp.Manufacturer, ',', ''))>=numbers.n-1
order by
  SKU, n
</code>```

Check with SQL Fiddle

Body:
We have a table like the following:

|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE, Sony     | 10
|  123456 | GE           | 25

We need to split the rows where more than one manufacturer is listed, and copy the remaining row data (SKU is not unique). So the expected results would be following:

|  SKU    | Manufacturer | Qty
|-----------------------------|
|  12345  | GE           | 10 |
|  12345  | Sony         | 10 |
|  123456 | GE           | 25 |

Can this be even done with MySQL, if so the how? If not, what would other options be then?

Body:
Try the answer:

CREATE TABLE Temp (SKU INT, Manufacturer VARCHAR(15),Qty INT);
INSERT INTO Temp VALUES(12345,'GE, Sony',10);
INSERT INTO Temp VALUES(123456,'GE',25);

select
  Temp.SKU,
  SUBSTRING_INDEX(SUBSTRING_INDEX(Temp.Manufacturer, ',', numbers.n), ',', -1) Manufacturer,
  Temp.Qty
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN Temp
  on CHAR_LENGTH(Temp.Manufacturer)
     -CHAR_LENGTH(REPLACE(Temp.Manufacturer, ',', ''))>=numbers.n-1
order by
  SKU, n

Check with SQL Fiddle


问:
@JsonProperty seems to only work for non boolean members
I have an object I'm trying to map to JSON and everything seems to work marvelously, except for boolean members, as we can see below:

```<code>public class Foo implements Serializable {

    @JsonProperty("this_does_not_work")
    private boolean isBar;

    @JsonProperty("this_works")
    private int bar;

    @JsonProperty("this_works_too")
    public boolean isBar() {
        return isBar;
    }

}
</code>```

This would be serialized to this:

```<code>{
    this_works: ...,
    this_works_too: ...
}
</code>```

Why do boolean members can't have a @JsonProperty (but their getters do)?

答:
Summarising the statements from comments: if you change your boolean field name to enabled

```<code>@JsonProperty("custom_name")
private boolean enabled;

public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean isEnabled) {
    this.enabled = isEnabled;
}
</code>```

it will give desired output { "custom_name" : true }

The original problem is not following java field naming conventions:

```<code>@JsonProperty("custom_name")
@Column(name = "fl_enabled")
private boolean isEnabled;

public boolean isEnabled() {
    return isEnabled;
}

public void setEnabled(boolean isEnabled) {
    this.isEnabled = isEnabled;
}
</code>```

When FasterXML serializes an object, it looks for fields and getters.

In your case, it found boolean field isEnabled and serialized it with custom_name.

Then it excluded getter of this boolean field from processing - possible getter names to exclude are getIsEnabled and 'isIsEnabled' - you don't have any.

Then it finds method isEnabled that looks like a getter for field enabled. So it takes its value and serializes it with key enabled.

So again, the problem is you should not name boolean fields with prefix is.

Body:
I have an object I'm trying to map to JSON and everything seems to work marvelously, except for boolean members, as we can see below:

public class Foo implements Serializable {

    @JsonProperty("this_does_not_work")
    private boolean isBar;

    @JsonProperty("this_works")
    private int bar;

    @JsonProperty("this_works_too")
    public boolean isBar() {
        return isBar;
    }

}

This would be serialized to this:

{
    this_works: ...,
    this_works_too: ...
}

Why do boolean members can't have a @JsonProperty (but their getters do)?

Body:
Summarising the statements from comments: if you change your boolean field name to enabled

@JsonProperty("custom_name")
private boolean enabled;

public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean isEnabled) {
    this.enabled = isEnabled;
}

it will give desired output { "custom_name" : true }

The original problem is not following java field naming conventions:

@JsonProperty("custom_name")
@Column(name = "fl_enabled")
private boolean isEnabled;

public boolean isEnabled() {
    return isEnabled;
}

public void setEnabled(boolean isEnabled) {
    this.isEnabled = isEnabled;
}

When FasterXML serializes an object, it looks for fields and getters.

In your case, it found boolean field isEnabled and serialized it with custom_name.

Then it excluded getter of this boolean field from processing - possible getter names to exclude are getIsEnabled and 'isIsEnabled' - you don't have any.

Then it finds method isEnabled that looks like a getter for field enabled. So it takes its value and serializes it with key enabled.

So again, the problem is you should not name boolean fields with prefix is.


问:
Scrape the dynamic content using python scrapy
I would like to scrape the 'calendar' content in this link:
https://gomore.dk/lejebil/27035

I wonder if i could use python scrapy without using selenium to crawl this content. As i cant find any info from the network tab. Thanks!

答: https://dgaqgnnkkz5ef.cloudfront.net/assets/application-840c6707422c9d0ee7fb9005972e7c7201803d9c24bbcd23253e6ec7beedd6a1.js this is the JS file where they are getting data from, I dont have mush time to inspect, but you can do more research on how they are doing it search for js-occupancy-calendar and rental_ad_occupancy_calendar/main and you will have some idea.

ContentLicense: CC BY-SA 4.0


问:
nVarchar and SqlParameter
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

```<code>insert into tbl_text(text)values(N'Chci tančit v oblasti')
</code>```

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

答:
You should parametrize your inserts with SqlParameters which allow you to specify the datatype explicitly. (Also it saves you the headache of figuring out the SQL server injection attack your query caused).

Example:

```<code>SqlCommand cmd  = new SqlCommand("insert into tbl_text (text) values(@MYTEXT)", myConnection);
cmd.Parameters.Add(new SqlParameter("@MYTEXT", SqlDbType.NVarChar)).Value = "Chci tančit v";
cmd.ExecuteNonQuery();
</code>```

Title: nVarchar and SqlParameter

Body:
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

insert into tbl_text(text)values(N'Chci tančit v oblasti')

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

Body:
You should parametrize your inserts with SqlParameters which allow you to specify the datatype explicitly. (Also it saves you the headache of figuring out the SQL server injection attack your query caused).

Example:

SqlCommand cmd  = new SqlCommand("insert into tbl_text (text) values(@MYTEXT)", myConnection);
cmd.Parameters.Add(new SqlParameter("@MYTEXT", SqlDbType.NVarChar)).Value = "Chci tančit v";
cmd.ExecuteNonQuery();


问:
Python: Why am I getting a "ZeroDivisionError: division by zero" in function?
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

```<code>def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)
</code>```

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?

答:
So the only way this can happen is because the code that increments a, b, c and d is never reached.

That can have a few reasons:

inFile is empty so the whole for loop never enters its body

len(words) is 0, so that for loop never enters its body

len(keywords) is 0, so that for loop never enters its body

The value of timezone is something other than those values you test for

words is initially [], so its length can stay 0 if that loop that appends things to it never runs.

From here, it's impossible for us to see which of these is happening, but it should be very easy for you with some print statements or such.

Body:
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?


问:
Solr search score in the range from 0 to 1
Is it possible to configure Solr so that the document similarity score would be in the range for example from 0 (no match) to 1 (complete document and query match).

Thanks!

答: You need this for some kind of UI meter? Maybe you should look at cosine similarity between documents, http://en.wikipedia.org/wiki/Cosine_similarity , where the first document is the query.</p>


问:
How to execute PowerShell script while creating a Custom Project Template in Visual Studio 2015?
I am creating a Custom Visual Studio Project Template. This custom project template consists of two folders which needs to contain some binaries. These binaries has to copied from some server location. As these binaries will be updated periodically i can't simply enclose them while creating the custom project template. I would like to copy them from server location whenever the developer selects this custom project template the two folders inside their Visual Studio might get the latest binaries from the server location. I have to do this with PowerShell script only. Can someone help me on how to execute PowerShell scripts while creating custom project template in Visual Studio.</p>

答: Why don't you create your own custom nuget packages? Then you only have to "refresh nuget packages" after creating the project from template.


问:
Open model in a given revision
Intro: I am using Team Foundation Server to manage the requirements. Every time I change a TFS requirement a new revision is created and I can always look up the contents of some given revision from the past:

Latest
 http://mytfs:8080/tfs/defaultcollection/WorkItemTracking/workitem.aspx?artifactMoniker=123456

Revision 13: http://mytfs:8080/tfs/defaultcollection/WorkItemTracking/workitem.aspx?artifactMoniker=123456&Rev=13

When I open my Enterprise Architect model (which is stored on a SQL Server) I always get presented the latest "revision" of it. Is there a way to open an old "revision" of a model in EA? Is this somehow related to baselining?

Background: I would like to place a link to my model in the description of my requirement, but opening an old revision of a requirement should link to the revision of the model that was at that time the latest. Naturally this requires to update the link in my requirement every time I change it to the revision of the model that is consistent with the requirement.

答:
There is not really an easy way to do this.
The model stored in SQL server only stores the latest version of the model, it does not keep track of previous revisions.

You would have to control the whole model to TFS, and in theory that would allow you to restore the model to a certain point.

One of problems here is that you would have to restore each and every package to the state of that revision, which is quite a cumbersome job.

Another issue is that the model on your SQL server would be reset to that revision, for all users, not just for you.

Alternative workarounds (given that you have the whole model version controlled in TFS)

Branch in copy model

Create a branch in TFS marking the state of a certain revision for the whole set of files from EA

Export your model to a .eap file (or another database model)

Link your Version Control configuration to the new branch

Do a getAllLatest from the copy .eap file

Rollback in main model (in case you really want to rollback the whole model completely to a previous revision)

Rollback the whole EA directory in TFS to a certain revision/date/label

Do a GetAllLatest in the main model on SQL Server.

Title: Open model in a given revision


问:
SQL - Coulmn headers as rows (for both 0's and 1's)
Please help, I have a table like this :

```<code>ID  HCC1    HCC2    HCC3    HCC4
101 0   1   1   0
102 0   0   1   0
103 0   0   0   0
</code>```

I want the resulting table to look like this:

```<code>ID  HCC
101 HCC2
101 HCC3
102 HCC3
103 0
</code>```

If a member has 1 in multiple HCC's , both need to be listed in separate rows (for instance ID-101). If member has 0 in all HCC's then there should be 0 in HCC column (for instance ID-103). I tried "unpivot" but it works only for 1's, I need 0's too.

I have 150 such column headers and 100,000 ID's

Thank You!

答:
This is only applicable if the dbms is MS SQL Server (or perhaps other platforms supporting the "apply operator" and that allow values). A script could be built to generate the ~150 case expressions (or use Excel) but the advantage here is that there is just one pass through the source table.

DEMO (MS SQL Server)

```<code>CREATE TABLE Table1
    ([ID] int, [HCC1] int, [HCC2] int, [HCC3] int, [HCC4] int)
;

INSERT INTO Table1
    ([ID], [HCC1], [HCC2], [HCC3], [HCC4])
VALUES
    (101, 0, 1, 1, 0),
    (102, 0, 0, 1, 0),
    (103, 0, 0, 0, 0)
;
</code>```

Query 1:

```<code>SELECT
      id, ca.HCC
FROM table1
CROSS APPLY (
  values
       (case when HCC1+HCC2+HCC3+HCC4 = 0 then '0' end)
     , (case when HCC1 = 1 then 'HCC1' end)
     , (case when HCC2 = 1 then 'HCC2' end)
     , (case when HCC3 = 1 then 'HCC3' end)
   ) ca(HCC)
WHERE ca.hcc IS NOT NULL
</code>```

Results:

```<code>|  id |  HCC |
|-----|------|
| 101 | HCC2 |
| 101 | HCC3 |
| 102 | HCC3 |
| 103 |    0 |
</code>```

if nothing else, perhaps this dbms specific answer will prompt you to add which dbms is actually being used.

Body:
Please help, I have a table like this :

ID  HCC1    HCC2    HCC3    HCC4
101 0   1   1   0
102 0   0   1   0
103 0   0   0   0

I want the resulting table to look like this:

ID  HCC
101 HCC2
101 HCC3
102 HCC3
103 0

If a member has 1 in multiple HCC's , both need to be listed in separate rows (for instance ID-101). If member has 0 in all HCC's then there should be 0 in HCC column (for instance ID-103). I tried "unpivot" but it works only for 1's, I need 0's too.

I have 150 such column headers and 100,000 ID's

Thank You!

Body:
This is only applicable if the dbms is MS SQL Server (or perhaps other platforms supporting the "apply operator" and that allow values). A script could be built to generate the ~150 case expressions (or use Excel) but the advantage here is that there is just one pass through the source table.

DEMO (MS SQL Server)

CREATE TABLE Table1
    ([ID] int, [HCC1] int, [HCC2] int, [HCC3] int, [HCC4] int)
;

INSERT INTO Table1
    ([ID], [HCC1], [HCC2], [HCC3], [HCC4])
VALUES
    (101, 0, 1, 1, 0),
    (102, 0, 0, 1, 0),
    (103, 0, 0, 0, 0)
;

Query 1:

SELECT
      id, ca.HCC
FROM table1
CROSS APPLY (
  values
       (case when HCC1+HCC2+HCC3+HCC4 = 0 then '0' end)
     , (case when HCC1 = 1 then 'HCC1' end)
     , (case when HCC2 = 1 then 'HCC2' end)
     , (case when HCC3 = 1 then 'HCC3' end)
   ) ca(HCC)
WHERE ca.hcc IS NOT NULL

Results:

|  id |  HCC |
|-----|------|
| 101 | HCC2 |
| 101 | HCC3 |
| 102 | HCC3 |
| 103 |    0 |

if nothing else, perhaps this dbms specific answer will prompt you to add which dbms is actually being used.


问:
extending the c programming language with gcc
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

```<code>namespace TcpConnection {
    void* connect(char *addr)
}
</code>```

would translate to:

```<code>void* TcpConnection_connect(char *addr)
</code>```

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?

答:
You could hack something on top of http://cil.sourceforge.net/

Clang is another option, but it's not the most useful code rewriting tool, and modifying its parser frontend is not that easy.

Body:
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

namespace TcpConnection {
    void* connect(char *addr)
}

would translate to:

void* TcpConnection_connect(char *addr)

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?


问:
C++ How to link mongoc and mongocxx static library using CMakeList.txt
I follow the official tutorial for the installation : https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/installation/
I've enabled the flag --enable-static=yes with the ./configure before doing make && sudo make install and I got the libmongoc-1.0.a and the libbson-1.0.a which are static. I have given

```<code>cmake -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=/your/cxxdriver/prefix
    -DLIBMONGOC_DIR=/your/cdriver/prefix
    -DLIBBSON_DIR=/your/cdriver/prefix ..
</code>```

Then make && sudo make install is also done. So this far, everything it's alright.

when I check libraries which are linked to my final executable file are

```<code>ldd ./prabhandhak
    linux-vdso.so.1 =>  (0x00007fff6d1f0000)
    libbsoncxx.so._noabi => /usr/local/lib/libbsoncxx.so._noabi (0x00007f021cffb000)
    libmongocxx.so._noabi => /usr/local/lib/libmongocxx.so._noabi (0x00007f021cda4000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f021ca06000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f021c6fd000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f021c4e6000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f021c11c000)
    libbson-1.0.so.0 => /usr/local/lib/libbson-1.0.so.0 (0x00007f021bee5000)
    libmongoc-1.0.so.0 => /usr/local/lib/libmongoc-1.0.so.0 (0x00007f021bc6e000)
    /lib64/ld-linux-x86-64.so.2 (0x000055ef6575a000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f021ba51000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f021b848000)
    libsnappy.so.0 => /usr/local/lib/libsnappy.so.0 (0x00007f021b631000)
</code>```

Here i want to link mongo static libraries

this is my cmakelist.txt

```<code>cmake_minimum_required (VERSION 3.5)

# -------------------------------------------------------------------------------------
## Checking if an env variable for "3rd party includes" is set.
## If not, we throw an error and exit.
#Message("Checking for environment variable" "IAM_EXT_INCLUDES")
#if (DEFINED ENV{IAM_EXT_INCLUDES})
#  Message ("found:" $ENV{IAM_EXT_INCLUDES})
#else()
#  Message(FATAL_ERROR "I need the environment variable IAM_EXT_INCLUDES to continue.")
#endif()
# -------------------------------------------------------------------------------------

project(mango VERSION 0.1.0)

# search for CPP_HOME. If found use this as the install_root dir.
# else, use /usr/local
message (STATUS "Searching for environment var CPP_HOME ...")
if (DEFINED ENV{CPP_HOME})
message (STATUS "Found CPP_HOME: " $ENV{CPP_HOME})
set (CPP_HOME $ENV{CPP_HOME})
else()
message (STATUS "Could not find.  Treating /usr/local as CPP_HOME...")
set (CPP_HOME /usr/local)
endif()
set(Boost_USE_STATIC_LIBS ON)
set(BOOST_LIBRARYDIR /usr/lib/x86_64-linux-gnu/)
# link_directories(/usr/lib/x86_64-linux-gnu/)
find_package(Boost REQUIRED COMPONENTS system date_time)
set(Boost_USE_STATIC_LIBS ON)
find_package(libmongocxx REQUIRED)
find_package(libbsoncxx REQUIRED)
include_directories(${dbconn_SOURCE_DIR}/Implementation/mongo)
include_directories(${BOOST_INCLUDE_DIRS})
set (CMAKE_CXX_STANDARD 11)

if(libmongocxx_FOUND)
message("include path:" ${LIBMONGOCXX_INCLUDE_DIRS})
endif()
add_library(mongodbapi mongo_db_api.cpp)

# include third party lib headers (such as plog)
include_directories(/Volumes/second/nvi/github/externals/)
include_directories(../../../Interface/)
include_directories(./include/ext/)
include_directories(../../../../../utils/)
include_directories(${CPP_HOME}/externals/plog/include)
include_directories(${include_directories} ${LIBMONGOCXX_INCLUDE_DIRS})
include_directories(${include_directories} ${LIBBSONCXX_INCLUDE_DIRS})

target_link_libraries(mongodbapi ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(mongodbapi ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(mongodbapi ${Boost_LIBRARIES})

set (inst_dir_prefix mango-v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR})
install (TARGETS mongodbapi DESTINATION ${inst_dir_prefix}/lib)
FILE(GLOB inc_files "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp")
install (FILES ${inc_files} DESTINATION ${inst_dir_prefix}/include)

FILE(GLOB utils_includes "../../../../../utils/*.hpp")
#install (FILES ${inc_files} DESTINATION ${inst_dir_prefix}/include)
INSTALL(FILES ${utils_includes} DESTINATION "${CPP_HOME}/utils")
</code>```

Please Help me to link static libraries to cmakefile.txt

答:
Looks like there's relevant option in mongocxx's CMakeLists.txt. So

```<code>--- cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local ..
+++ cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=False -DCMAKE_INSTALL_PREFIX=/usr/local ..
</code>```

(this is from Step 4 of your tutorial)

Body:
I follow the official tutorial for the installation : https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/installation/
I've enabled the flag --enable-static=yes with the ./configure before doing make && sudo make install and I got the libmongoc-1.0.a and the libbson-1.0.a which are static. I have given

cmake -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=/your/cxxdriver/prefix
    -DLIBMONGOC_DIR=/your/cdriver/prefix
    -DLIBBSON_DIR=/your/cdriver/prefix ..

Then make && sudo make install is also done. So this far, everything it's alright.

when I check libraries which are linked to my final executable file are

ldd ./prabhandhak
    linux-vdso.so.1 =>  (0x00007fff6d1f0000)
    libbsoncxx.so._noabi => /usr/local/lib/libbsoncxx.so._noabi (0x00007f021cffb000)
    libmongocxx.so._noabi => /usr/local/lib/libmongocxx.so._noabi (0x00007f021cda4000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f021ca06000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f021c6fd000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f021c4e6000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f021c11c000)
    libbson-1.0.so.0 => /usr/local/lib/libbson-1.0.so.0 (0x00007f021bee5000)
    libmongoc-1.0.so.0 => /usr/local/lib/libmongoc-1.0.so.0 (0x00007f021bc6e000)
    /lib64/ld-linux-x86-64.so.2 (0x000055ef6575a000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f021ba51000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f021b848000)
    libsnappy.so.0 => /usr/local/lib/libsnappy.so.0 (0x00007f021b631000)

Here i want to link mongo static libraries

this is my cmakelist.txt

cmake_minimum_required (VERSION 3.5)

# -------------------------------------------------------------------------------------
## Checking if an env variable for "3rd party includes" is set.
## If not, we throw an error and exit.
#Message("Checking for environment variable" "IAM_EXT_INCLUDES")
#if (DEFINED ENV{IAM_EXT_INCLUDES})
#  Message ("found:" $ENV{IAM_EXT_INCLUDES})
#else()
#  Message(FATAL_ERROR "I need the environment variable IAM_EXT_INCLUDES to continue.")
#endif()
# -------------------------------------------------------------------------------------

project(mango VERSION 0.1.0)

# search for CPP_HOME. If found use this as the install_root dir.
# else, use /usr/local
message (STATUS "Searching for environment var CPP_HOME ...")
if (DEFINED ENV{CPP_HOME})
message (STATUS "Found CPP_HOME: " $ENV{CPP_HOME})
set (CPP_HOME $ENV{CPP_HOME})
else()
message (STATUS "Could not find.  Treating /usr/local as CPP_HOME...")
set (CPP_HOME /usr/local)
endif()
set(Boost_USE_STATIC_LIBS ON)
set(BOOST_LIBRARYDIR /usr/lib/x86_64-linux-gnu/)
# link_directories(/usr/lib/x86_64-linux-gnu/)
find_package(Boost REQUIRED COMPONENTS system date_time)
set(Boost_USE_STATIC_LIBS ON)
find_package(libmongocxx REQUIRED)
find_package(libbsoncxx REQUIRED)
include_directories(${dbconn_SOURCE_DIR}/Implementation/mongo)
include_directories(${BOOST_INCLUDE_DIRS})
set (CMAKE_CXX_STANDARD 11)

if(libmongocxx_FOUND)
message("include path:" ${LIBMONGOCXX_INCLUDE_DIRS})
endif()
add_library(mongodbapi mongo_db_api.cpp)

# include third party lib headers (such as plog)
include_directories(/Volumes/second/nvi/github/externals/)
include_directories(../../../Interface/)
include_directories(./include/ext/)
include_directories(../../../../../utils/)
include_directories(${CPP_HOME}/externals/plog/include)
include_directories(${include_directories} ${LIBMONGOCXX_INCLUDE_DIRS})
include_directories(${include_directories} ${LIBBSONCXX_INCLUDE_DIRS})

target_link_libraries(mongodbapi ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(mongodbapi ${LIBMONGOCXX_LIBRARIES})
target_link_libraries(mongodbapi ${Boost_LIBRARIES})

set (inst_dir_prefix mango-v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR})
install (TARGETS mongodbapi DESTINATION ${inst_dir_prefix}/lib)
FILE(GLOB inc_files "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp")
install (FILES ${inc_files} DESTINATION ${inst_dir_prefix}/include)

FILE(GLOB utils_includes "../../../../../utils/*.hpp")
#install (FILES ${inc_files} DESTINATION ${inst_dir_prefix}/include)
INSTALL(FILES ${utils_includes} DESTINATION "${CPP_HOME}/utils")

Please Help me to link static libraries to cmakefile.txt

Body:
Looks like there's relevant option in mongocxx's CMakeLists.txt. So

--- cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local ..
+++ cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=False -DCMAKE_INSTALL_PREFIX=/usr/local ..

(this is from Step 4 of your tutorial)


问:
python unicode convert to Japanese character
I am trying to convert u'\u30c9\u30e9\u30b4\u30f3' to japanese character using python

here is my sample code

```<code>s = u'\u30c9\u30e9\u30b4\u30f3'.encode('utf-8')
print str(s)
</code>```

I got this error
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

答:
This will depend on your OS and configuration, but normally, you just print the Unicode string.  If your OS, default terminal encoding, and font support Japanese, you only need:

```<code>>>> s = u'\u30c9\u30e9\u30b4\u30f3'
>>> print s
ドラゴン
</code>```

On Linux, this requires your terminal to be properly configured to (typically) UTF-8.

On Windows, you need an IDE that supports UTF-8, but if using the Windows console, you will get a UnicodeEncodeError unless using a localized version of Windows that supports Japanese, or changing the system locale to Japanese.  Another workaround is to use win-unicode-console and install a Japanese console font.

My example above used the PythonWin IDE that comes with the pywin32 module, and also works in the Python IDLE IDE that comes with a standard Python installation.

Body:
I am trying to convert u'\u30c9\u30e9\u30b4\u30f3' to japanese character using python

here is my sample code

s = u'\u30c9\u30e9\u30b4\u30f3'.encode('utf-8')
print str(s)

I got this error
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Body:
This will depend on your OS and configuration, but normally, you just print the Unicode string.  If your OS, default terminal encoding, and font support Japanese, you only need:

>>> s = u'\u30c9\u30e9\u30b4\u30f3'
>>> print s
ドラゴン

On Linux, this requires your terminal to be properly configured to (typically) UTF-8.

On Windows, you need an IDE that supports UTF-8, but if using the Windows console, you will get a UnicodeEncodeError unless using a localized version of Windows that supports Japanese, or changing the system locale to Japanese.  Another workaround is to use win-unicode-console and install a Japanese console font.

My example above used the PythonWin IDE that comes with the pywin32 module, and also works in the Python IDLE IDE that comes with a standard Python installation.