问:
android - NullPointerException for GoogleMap
in my case app always crash on Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline and i write below codes, but when running show me Force Close error

ActivityMain

```<code>public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
    //Google Maps
    public GoogleMap mMap;

    //
    SQLHelper dbHelper;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //DB
        dbHelper = new SQLHelper(this);
        try {
            dbHelper.createDataBase();
        }
        catch (Exception ioe) {
            Toast.makeText(getApplicationContext(), "Gagal", Toast.LENGTH_LONG).show();
        }

        //BUAT MAP
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.peta);
        mapFragment.getMapAsync(this);

        int simpul_awal = 0;
        int simpul_tujuan = 3;

        //output algoritma
        dijkstra algo = new dijkstra();
        algo.jalurTerpendek(this, simpul_awal, simpul_tujuan);
        Toast.makeText(getBaseContext(), "Jalur terdekat : "+algo.jalur_terpendek1, Toast.LENGTH_LONG).show();
        String[] exp = algo.jalur_terpendek1.split("->");

        int start = 0;
        //Query DB; Gambar Jalurnya!

        dbHelper = new SQLHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        for(int i = 0; i < exp.length-1; i++){
            ArrayList<LatLng> lat_lng = new ArrayList<LatLng>();
            cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal ="+exp[start]+" and simpul_tujuan ="+exp[(++start)], null);
            cursor.moveToFirst();
            int idx_koord = 0;
            String[] exp_koord = cursor.getString(0).split(",");
            for(int j = 0; j < exp_koord.length/2; j++){
                lat_lng.add( new LatLng(Double.parseDouble(exp_koord[idx_koord]), Double.parseDouble(exp_koord[++idx_koord])) );
                ++idx_koord;
            }
            PolylineOptions jalurBiasa = new PolylineOptions();
            jalurBiasa.addAll(lat_lng).width(5).color(0xff4b9efa).geodesic(true);
            **mMap**.addPolyline(jalurBiasa);

        }

        //zoom ke koordinat
        cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal ="+exp[0]+" and simpul_tujuan ="+exp[1], null);
        cursor.moveToFirst();
        String[] koord = cursor.getString(0).split(",");
        **mMap**.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(koord[0]), Double.parseDouble(koord[1])), 12));

    }//oncreate

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kokoro1.com.kokoro1">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->

    <uses-permission android:name="kokoro1.com.kokoro1.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyAIbPBUmnZ1TF0rHkGjLN-g1GNYHsnR5Uo" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

MyLogcat

```<code>D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: kokoro1.com.kokoro1, PID: 26867
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{kokoro1.com.kokoro1/kokoro1.com.kokoro1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
                      at android.app.ActivityThread.access$800(ActivityThread.java:156)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:211)
                      at android.app.ActivityThread.main(ActivityThread.java:5389)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference
                      at kokoro1.com.kokoro1.MainActivity.onCreate(MainActivity.java:80)
                      at android.app.Activity.performCreate(Activity.java:5990)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
                      at android.app.ActivityThread.access$800(ActivityThread.java:156)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:211)
                      at android.app.ActivityThread.main(ActivityThread.java:5389)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Application terminated.
</code>```

答: You must use "mMap" variable after onMapReady is called :)</p>

Body:
in my case app always crash on Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline and i write below codes, but when running show me Force Close error

ActivityMain

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
    //Google Maps
    public GoogleMap mMap;

    //
    SQLHelper dbHelper;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //DB
        dbHelper = new SQLHelper(this);
        try {
            dbHelper.createDataBase();
        }
        catch (Exception ioe) {
            Toast.makeText(getApplicationContext(), "Gagal", Toast.LENGTH_LONG).show();
        }

        //BUAT MAP
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.peta);
        mapFragment.getMapAsync(this);

        int simpul_awal = 0;
        int simpul_tujuan = 3;

        //output algoritma
        dijkstra algo = new dijkstra();
        algo.jalurTerpendek(this, simpul_awal, simpul_tujuan);
        Toast.makeText(getBaseContext(), "Jalur terdekat : "+algo.jalur_terpendek1, Toast.LENGTH_LONG).show();
        String[] exp = algo.jalur_terpendek1.split("->");

        int start = 0;
        //Query DB; Gambar Jalurnya!

        dbHelper = new SQLHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        for(int i = 0; i < exp.length-1; i++){
            ArrayList<LatLng> lat_lng = new ArrayList<LatLng>();
            cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal ="+exp[start]+" and simpul_tujuan ="+exp[(++start)], null);
            cursor.moveToFirst();
            int idx_koord = 0;
            String[] exp_koord = cursor.getString(0).split(",");
            for(int j = 0; j < exp_koord.length/2; j++){
                lat_lng.add( new LatLng(Double.parseDouble(exp_koord[idx_koord]), Double.parseDouble(exp_koord[++idx_koord])) );
                ++idx_koord;
            }
            PolylineOptions jalurBiasa = new PolylineOptions();
            jalurBiasa.addAll(lat_lng).width(5).color(0xff4b9efa).geodesic(true);
            **mMap**.addPolyline(jalurBiasa);

        }

        //zoom ke koordinat
        cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal ="+exp[0]+" and simpul_tujuan ="+exp[1], null);
        cursor.moveToFirst();
        String[] koord = cursor.getString(0).split(",");
        **mMap**.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(koord[0]), Double.parseDouble(koord[1])), 12));

    }//oncreate

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kokoro1.com.kokoro1">

    <uses-permission android:name="kokoro1.com.kokoro1.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyAIbPBUmnZ1TF0rHkGjLN-g1GNYHsnR5Uo" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MyLogcat

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: kokoro1.com.kokoro1, PID: 26867
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{kokoro1.com.kokoro1/kokoro1.com.kokoro1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
                      at android.app.ActivityThread.access$800(ActivityThread.java:156)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:211)
                      at android.app.ActivityThread.main(ActivityThread.java:5389)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference
                      at kokoro1.com.kokoro1.MainActivity.onCreate(MainActivity.java:80)
                      at android.app.Activity.performCreate(Activity.java:5990)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
                      at android.app.ActivityThread.access$800(ActivityThread.java:156)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:211)
                      at android.app.ActivityThread.main(ActivityThread.java:5389)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Application terminated.


来源: stackexchange

问:
How to handle HTTP OPTIONS requests in Spring Boot?
First off, I've read "How to handle HTTP OPTIONS with Spring MVC?" but the answers do not seem directly applicable to Spring Boot.

It looks like I should do this:

configure the dispatcherServlet by setting its
  dispatchOptionsRequest to true

But how to do that, given that I have no XML configs, or any variety of DispatcherServlet initializer class in my code (mentioned by this answer)?

In a @RestController class, I have a method like this, which currently does not get invoked.

```<code>@RequestMapping(value = "/foo", method = RequestMethod.OPTIONS)
public ResponseEntity options(HttpServletResponse response) {
    log.info("OPTIONS /foo called");
    response.setHeader("Allow", "HEAD,GET,PUT,OPTIONS");
    return new ResponseEntity(HttpStatus.OK);
}
</code>```

Spring Boot 1.2.7.RELEASE; a simple setup not very different from that in  Spring REST guide.

答:
I was running into this issue with a Spring Boot 1.3.x based rest app and while diagnosing the problem I allowed my Spring Tool Suite to update to the latest version.

When I created a new test Spring Boot RestController in the updated STS, it worked as the documentation advertises under Spring 4.3.  I noticed that the Maven dependency had jumped to spring boot 1.5.8 in the new test app, so I just changed the dependency for the old app to update it to spring boot 1.5.8 / spring 4.3.12.  That fixed the issue and now it's working as advertised with a RequestMapping annotation specifying an interest in handling the OPTIONS requests...

```<code>@RequestMapping(value="/account/{id}", method={RequestMethod.OPTIONS,RequestMethod.GET})
</code>```

... now sends the OPTIONS request to the handler.

So, if you are able to update to a later version of Spring, you should have no need to define any special configurations in order enable OPTIONS request method handling (Spring 4.3.12 / Spring Boot 1.5.8).

ContentLicense: CC BY-SA 3.0

Body:
First off, I've read "How to handle HTTP OPTIONS with Spring MVC?" but the answers do not seem directly applicable to Spring Boot.

It looks like I should do this:

configure the dispatcherServlet by setting its
  dispatchOptionsRequest to true

But how to do that, given that I have no XML configs, or any variety of DispatcherServlet initializer class in my code (mentioned by this answer)?

In a @RestController class, I have a method like this, which currently does not get invoked.

@RequestMapping(value = "/foo", method = RequestMethod.OPTIONS)
public ResponseEntity options(HttpServletResponse response) {
    log.info("OPTIONS /foo called");
    response.setHeader("Allow", "HEAD,GET,PUT,OPTIONS");
    return new ResponseEntity(HttpStatus.OK);
}

Spring Boot 1.2.7.RELEASE; a simple setup not very different from that in  Spring REST guide.

Body:
I was running into this issue with a Spring Boot 1.3.x based rest app and while diagnosing the problem I allowed my Spring Tool Suite to update to the latest version.

When I created a new test Spring Boot RestController in the updated STS, it worked as the documentation advertises under Spring 4.3.  I noticed that the Maven dependency had jumped to spring boot 1.5.8 in the new test app, so I just changed the dependency for the old app to update it to spring boot 1.5.8 / spring 4.3.12.  That fixed the issue and now it's working as advertised with a RequestMapping annotation specifying an interest in handling the OPTIONS requests...

@RequestMapping(value="/account/{id}", method={RequestMethod.OPTIONS,RequestMethod.GET})

... now sends the OPTIONS request to the handler.

So, if you are able to update to a later version of Spring, you should have no need to define any special configurations in order enable OPTIONS request method handling (Spring 4.3.12 / Spring Boot 1.5.8).


问:
Store a pointer to a non-specified size array
I have a function like this:

```<code>void Menu_show(uint8_t count, char items[][UI_COLS + 1]);
</code>```

where count is the length of the first dimension of the array items.
I call this function in this way:

```<code>#define MAX_SIZE 4
char items[MAX_SIZE ][UI_COLS + 1];

for (uint8_t i = 0; i < MAX_SIZE ; i++) sprintf(items[i], "%u", i);
...
Menu_show(MAX_SIZE, items);
</code>```

It works, but now I need to store a pointer to the first element of the array in my function.

My tougths:

the first element is items[0][0]

its pointer is &items[0][0]

but now I have a pointer to a char, not to a bidimensional array

In fact, something like printf(items[3]) doesn't work in this way.
Then, I thought that the pointer to the first element of the second (fixed) dimension is &item[0] but:

```<code>char *_items[UI_COLS + 1];
_items = &items[0];
</code>```

gives an error:

assignment to expression with array type

I don't understand the right syntax to keep the bidimensional array usage when store the first location in a pointer.

答:
Arrays can be interpreted as a pointer
If you have

```<code>arr[][]
</code>```

arr can be considered

```<code>&arr[0]
</code>```

and

```<code>arr[i]
</code>```

can be considered as

```<code>&arr[i][0]
</code>```

A two dimensional array doesn't really have a first element, except that it's first element array[0] is the first array in that twodimensional array.

```<code>printf(items[3]);
</code>```

should work, because

```<code>items[3]
</code>```

is a char array.

P.S.

For security reasons use

```<code>printf("%s",items[3]);
</code>```

instead.

Body:
I have a function like this:

void Menu_show(uint8_t count, char items[][UI_COLS + 1]);

where count is the length of the first dimension of the array items.
I call this function in this way:

#define MAX_SIZE 4
char items[MAX_SIZE ][UI_COLS + 1];

for (uint8_t i = 0; i < MAX_SIZE ; i++) sprintf(items[i], "%u", i);
...
Menu_show(MAX_SIZE, items);

It works, but now I need to store a pointer to the first element of the array in my function.

My tougths:

the first element is items[0][0]

its pointer is &items[0][0]

but now I have a pointer to a char, not to a bidimensional array

In fact, something like printf(items[3]) doesn't work in this way.
Then, I thought that the pointer to the first element of the second (fixed) dimension is &item[0] but:

char *_items[UI_COLS + 1];
_items = &items[0];

gives an error:

assignment to expression with array type

I don't understand the right syntax to keep the bidimensional array usage when store the first location in a pointer.

Body:
Arrays can be interpreted as a pointer
If you have

arr[][]

arr can be considered

&arr[0]

and

arr[i]

can be considered as

&arr[i][0]

A two dimensional array doesn't really have a first element, except that it's first element array[0] is the first array in that twodimensional array.

printf(items[3]);

should work, because

items[3]

is a char array.

P.S.

For security reasons use

printf("%s",items[3]);

instead.


问:
Angular2 - custom control validator matching wrong nested control
I have weird problem with validating my custom template-driven form control. Everything I want is a "required" validator. Id sounds pretty easy, however I tried to figure it out for a couple of hours without any success.

My control is a "simple" wrapper for another 3rd party autocomplete component. And I want to mark this whole component as required. It means it's value has to be defined and not null. But if I put the required directive on the control, ie.

```<code><my-control ... required></my-control>
</code>```

the required validator validates content of a text-input somewhere in the nested autocomplete control. If I bind the value (ngModel) of my control I get the correct value. But the validator does not reflect this value.

I also tried to write my own custom-validator. And the result is the same. If I watch the value property of the FormControl passed to the validator I can see the value currently written to the text-input nested somewhere deeper.

答: I got what I was missing - the ValueAccessor configuration inside the providers section of the Component decorator. As far I now know the binding grabs the first value accessor with this configuration. My one was missing so it dig deeper and matches the one bound to the autocomplete input.

Body:
I have weird problem with validating my custom template-driven form control. Everything I want is a "required" validator. Id sounds pretty easy, however I tried to figure it out for a couple of hours without any success.

My control is a "simple" wrapper for another 3rd party autocomplete component. And I want to mark this whole component as required. It means it's value has to be defined and not null. But if I put the required directive on the control, ie.

<my-control ... required></my-control>

the required validator validates content of a text-input somewhere in the nested autocomplete control. If I bind the value (ngModel) of my control I get the correct value. But the validator does not reflect this value.

I also tried to write my own custom-validator. And the result is the same. If I watch the value property of the FormControl passed to the validator I can see the value currently written to the text-input nested somewhere deeper.


问:
Converting Java sendEmail method to Groovy
I have a Java method to send a file attachment via e-mail. I'm trying to port it to Groovy as part of a Grails application. I'm having issue with the format of the FileDataSource declaration. The offending code is marked with an asterisk. What's the proper way to do that part in Groovy? I can't seem to find anything on the web.

```<code>public static void sendEmail(String sendFile)
    {
    //
    // Send the log file via email.
    //
    final String username = "myname@mydomain.com"
    final String password = "mypassword"

    // Strings that contain from, to, subject, body and file path to the attachment
    String from = username;
    String subject = "Test Results"
    String body = "Body of Test Results email."
    String filename = sendFile

    // Set smtp properties
    Properties properties = new Properties()
    properties.put("mail.smtp.starttls.enable", "true")
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.host", "smtp.gmail.com")
    properties.put("mail.smtp.port", "587")

    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username,password)
        }
    });

    try
    {
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(from))
        // For debug uncomment the line below and enter your email address.
        //message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
        // For debug comment the line below out.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
        message.setSubject(subject)
        message.setSentDate(new Date())

        // Set the email body
        MimeBodyPart messagePart = new MimeBodyPart()
        messagePart.setText(body)

        // Set the email attachment file
        MimeBodyPart attachmentPart = new MimeBodyPart()
        *FileDataSource fileDataSource = new FileDataSource(filename)
        *{
        *    @Override
        *    public String getContentType()
        *    {
        *        return "application/octet-stream"
        *    }
        * }
        attachmentPart.setDataHandler(new DataHandler(fileDataSource))
        attachmentPart.setFileName(fileDataSource.getName())

        // Add all parts of the email to Multipart object
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messagePart)
        multipart.addBodyPart(attachmentPart)
        message.setContent(multipart)

        // Send email
        Transport.send(message)
        System.out.println("Mail sent!")
    }
    catch (MessagingException e)
    {
        e.printStackTrace()
    }
}
</code>```

答:
That awful brace style is conflicting with Groovy not requiring semicolons. No need for a non-anonymous class definition though unless it's going to be used more than once, just declare it like this:</p>

```<code>FileDataSource fileDataSource = new FileDataSource(filename) {
    String getContentType() { 'application/octet-stream' }
}
</code>```

Body:
I have a Java method to send a file attachment via e-mail. I'm trying to port it to Groovy as part of a Grails application. I'm having issue with the format of the FileDataSource declaration. The offending code is marked with an asterisk. What's the proper way to do that part in Groovy? I can't seem to find anything on the web.

public static void sendEmail(String sendFile)
    {
    //
    // Send the log file via email.
    //
    final String username = "myname@mydomain.com"
    final String password = "mypassword"

    // Strings that contain from, to, subject, body and file path to the attachment
    String from = username;
    String subject = "Test Results"
    String body = "Body of Test Results email."
    String filename = sendFile

    // Set smtp properties
    Properties properties = new Properties()
    properties.put("mail.smtp.starttls.enable", "true")
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.host", "smtp.gmail.com")
    properties.put("mail.smtp.port", "587")

    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username,password)
        }
    });

    try
    {
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(from))
        // For debug uncomment the line below and enter your email address.
        //message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
        // For debug comment the line below out.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
        message.setSubject(subject)
        message.setSentDate(new Date())

        // Set the email body
        MimeBodyPart messagePart = new MimeBodyPart()
        messagePart.setText(body)

        // Set the email attachment file
        MimeBodyPart attachmentPart = new MimeBodyPart()
        *FileDataSource fileDataSource = new FileDataSource(filename)
        *{
        *    @Override
        *    public String getContentType()
        *    {
        *        return "application/octet-stream"
        *    }
        * }
        attachmentPart.setDataHandler(new DataHandler(fileDataSource))
        attachmentPart.setFileName(fileDataSource.getName())

        // Add all parts of the email to Multipart object
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messagePart)
        multipart.addBodyPart(attachmentPart)
        message.setContent(multipart)

        // Send email
        Transport.send(message)
        System.out.println("Mail sent!")
    }
    catch (MessagingException e)
    {
        e.printStackTrace()
    }
}

Body:
That awful brace style is conflicting with Groovy not requiring semicolons. No need for a non-anonymous class definition though unless it's going to be used more than once, just declare it like this:

FileDataSource fileDataSource = new FileDataSource(filename) {
    String getContentType() { 'application/octet-stream' }
}


问:
MSAL Adding Scope @"offline_access",@"openid" ,@"profile" Issue
I'm Try to adding scope @"offline_access",@"openid" ,@"profile" in Below Code But Show Me Error

```<code>MSALPublicClientApplication *application = [self createClientApplication];
</code>```

[application acquireTokenForScopes:@[@"User.Read", @"Calendars.Read",@"Calendars.ReadWrite",@"Calendars.ReadWrite.Shared",@"Contacts.ReadWrite",@"Contacts.ReadWrite.Shared",@"Tasks.ReadWrite",@"Tasks.ReadWrite.Shared",@"User.Read.All", @"User.ReadBasic.All", @"profile"]
                       completionBlock:^(MSALResult *result, NSError *error)

Showing Error :
MSAL 0.1.1-dev iOS Sim 10.3 [2017-11-13 09:39:50 - 496E2A0F-2D99-4171-96A9-D36ABCB08188] MSALErrorInvalidParameter: {(
    openid,
    profile,
    "offline_access"
)} are reserved scopes and may not be specified in the acquire token call. (-[MSALBaseRequest validateScopeInput:error:]:96)

答: MSAL automatically includes those 3 scopes (offline_access, openid, and profile) in each request, you don't have to explicitly pass them.

Body:
I'm Try to adding scope @"offline_access",@"openid" ,@"profile" in Below Code But Show Me Error

MSALPublicClientApplication *application = [self createClientApplication];

[application acquireTokenForScopes:@[@"User.Read", @"Calendars.Read",@"Calendars.ReadWrite",@"Calendars.ReadWrite.Shared",@"Contacts.ReadWrite",@"Contacts.ReadWrite.Shared",@"Tasks.ReadWrite",@"Tasks.ReadWrite.Shared",@"User.Read.All", @"User.ReadBasic.All", @"profile"]
                       completionBlock:^(MSALResult *result, NSError *error)

Showing Error :
MSAL 0.1.1-dev iOS Sim 10.3 [2017-11-13 09:39:50 - 496E2A0F-2D99-4171-96A9-D36ABCB08188] MSALErrorInvalidParameter: {(
    openid,
    profile,
    "offline_access"
)} are reserved scopes and may not be specified in the acquire token call. (-[MSALBaseRequest validateScopeInput:error:]:96)


问:
Why not volatile on System.Double and System.Long?
A question like mine has been asked, but mine is a bit different.  The question is, "Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

On first blush, I answered my colleague, "Well, on a 32-bit machine, those types take at least two ticks to even enter the processor, and the .Net framework has the intention of abstracting away processor-specific details like that."  To which he responds, "It's not abstracting anything if it's preventing you from using a feature because of a processor-specific problem!"

He's implying that a processor-specific detail should not show up to a person using a framework that "abstracts" details like that away from the programmer.  So, the framework (or C#) should abstract away those and do what it needs to do to offer the same guarantees for System.Double, etc. (whether that's a Semaphore, memory barrier, or whatever).  I argued that the framework shouldn't add the overhead of a Semaphore on volatile, because the programmer isn't expecting such overhead with such a keyword, because a Semaphore isn't necessary for the 32-bit types.  The greater overhead for the 64-bit types might come as a surprise, so, better for the .Net framework to just not allow it, and make you do your own Semaphore on larger types if the overhead is acceptable.

That led to our investigating what the volatile keyword is all about.  (see this page).  That page states, in the notes:

In C#, using the volatile modifier on a field guarantees that all access to that field uses VolatileRead or VolatileWrite.

Hmmm.....VolatileRead and VolatileWrite both support our 64-bit types!! My question, then, is,

"Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

答:
Not really an answer to your question, but...

I'm pretty sure that the MSDN documentation you've referenced is incorrect when it states that "using the volatile modifier on a field guarantees that all access to that field uses VolatileRead or VolatileWrite".

Directly reading or writing to a volatile field only generates a half-fence (an acquire-fence when reading and a release-fence when writing).

The VolatileRead and VolatileWrite methods use MemoryBarrier internally, which generates a full-fence.

Joe Duffy knows a thing or two about concurrent programming; this is what he has to say about volatile:

(As an aside, many people wonder about
  the difference between loads and
  stores of variables marked as volatile
  and calls to Thread.VolatileRead and
  Thread.VolatileWrite.  The difference
  is that the former APIs are
  implemented stronger than the jitted
  code: they achieve acquire/release
  semantics by emitting full fences on
  the right side.  The APIs are more
  expensive to call too, but at least
  allow you to decide on a
  callsite-by-callsite basis which
  individual loads and stores need the
  MM guarantees.)

ContentLicense: CC BY-SA 2.5


问:
NullPointerException org.chromium.android_webview.AwContents$AwViewMethodsImpl.onDragEvent
about 10 days ago, my app started to record this exception (seen on dev console):

```<code>java.lang.NullPointerException:
  at org.chromium.android_webview.AwContents$AwViewMethodsImpl.onDragEvent (AwContents.java:191)
  at com.android.webview.chromium.WebViewChromium.onDragEvent (WebViewChromium.java:782)
  at android.webkit.WebView.onDragEvent (WebView.java:2554)
  at android.view.View.dispatchDragEvent (View.java:22202)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1431)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewRootImpl.handleDragEvent (ViewRootImpl.java:6308)
  at android.view.ViewRootImpl.-wrap11 (ViewRootImpl.java)
  at android.view.ViewRootImpl$ViewRootHandler.handleMessage (ViewRootImpl.java:4199)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1496)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1386)
</code>```

I've no idea it could be (so i can't replicate it) and stacktrace covers none of my classes. About this exception I only know that:

effects only devices with android 7 or 7.1

first time occurred 11 Oct 2017

it occurred about 50 times per days, until 5 Nov 2017

it exploded from 6 Nov 2017 until now with about 340 occurrences per day

Users-app-usage is stable from about 1 year (3000 sessions per days, 15minutes per sessions).
App is a solitaire card games (no framework as libgdx used).

This is my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "com.pisano.app.solitari"
        minSdkVersion 15
        targetSdkVersion 23

        multiDexEnabled = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            signingConfig signingConfigs.config
        }
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile project(':pagecontrol')
    compile 'com.facebook.android:facebook-android-sdk:4.26.0'
    compile 'com.google.android.gms:play-services-games:11.2.2'
    compile 'com.google.android.gms:play-services-plus:11.2.2'
    compile 'com.google.android.gms:play-services-analytics:11.2.2'
    compile 'com.google.android.gms:play-services-location:11.2.2'
    compile 'com.google.firebase:firebase-core:11.2.2'
    compile 'com.google.firebase:firebase-ads:11.2.2'

}

apply plugin: 'com.google.gms.google-services'
</code>```

Thank you very much.

答: The problem is due to admob banner. If it refreshes during a drag, the target of drag is set to null.</p>

Body:
about 10 days ago, my app started to record this exception (seen on dev console):

java.lang.NullPointerException:
  at org.chromium.android_webview.AwContents$AwViewMethodsImpl.onDragEvent (AwContents.java:191)
  at com.android.webview.chromium.WebViewChromium.onDragEvent (WebViewChromium.java:782)
  at android.webkit.WebView.onDragEvent (WebView.java:2554)
  at android.view.View.dispatchDragEvent (View.java:22202)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1431)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewGroup.dispatchDragEvent (ViewGroup.java:1417)
  at android.view.ViewRootImpl.handleDragEvent (ViewRootImpl.java:6308)
  at android.view.ViewRootImpl.-wrap11 (ViewRootImpl.java)
  at android.view.ViewRootImpl$ViewRootHandler.handleMessage (ViewRootImpl.java:4199)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1496)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1386)

I've no idea it could be (so i can't replicate it) and stacktrace covers none of my classes. About this exception I only know that:

effects only devices with android 7 or 7.1

first time occurred 11 Oct 2017

it occurred about 50 times per days, until 5 Nov 2017

it exploded from 6 Nov 2017 until now with about 340 occurrences per day

Users-app-usage is stable from about 1 year (3000 sessions per days, 15minutes per sessions).
App is a solitaire card games (no framework as libgdx used).

This is my build.gradle:

apply plugin: 'com.android.application'

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "com.pisano.app.solitari"
        minSdkVersion 15
        targetSdkVersion 23

        multiDexEnabled = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            signingConfig signingConfigs.config
        }
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile project(':pagecontrol')
    compile 'com.facebook.android:facebook-android-sdk:4.26.0'
    compile 'com.google.android.gms:play-services-games:11.2.2'
    compile 'com.google.android.gms:play-services-plus:11.2.2'
    compile 'com.google.android.gms:play-services-analytics:11.2.2'
    compile 'com.google.android.gms:play-services-location:11.2.2'
    compile 'com.google.firebase:firebase-core:11.2.2'
    compile 'com.google.firebase:firebase-ads:11.2.2'

}

apply plugin: 'com.google.gms.google-services'

Thank you very much.


问:
Android O issues with WiFi Peer Discovery
I am developing an Android Application that employs WiFi (Direct) for service discovery and P2P peer discovery/connection.

My development enviromment is as follows:-

```<code>Android Studio 3.0 Beta 4
Build #AI-171.4304935, built on August 29, 2017
JRE: 1.8.0_152-release-915-b01 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.11.6
</code>```

My Gradle build:-

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.research.wifi_direct"

        minSdkVersion 19
        targetSdkVersion 26

        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    buildTypes {

        debug {
            buildConfigField "String", "INSTANCE_NAME", "\"_vascodagama\""
            buildConfigField "String", "SERVICE_TYPE", "\"_presence._tcp\""
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.0.2'
    implementation 'com.android.support:recyclerview-v7:26.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.yarolegovich:lovely-dialog:1.0.7'

    implementation 'io.realm:android-adapters:2.1.0'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
</code>```

The devices I am testing on include:-

```<code>Nexus 7 - Android 6.0.1
Nexus 9 - Android 7.1.1
Samsung Tablet - Android 4.4.1
Pixel - Android 8.0.0
</code>```

The service discovery works fine on all four devices.

However the P2P Peers List is always empty on the Pixel XL running Android 8.0.0.
The other three devices consistently discover each other as well as other miscellaneous devices
around my office e.g. such as a Samsung TV and my colleagues personal phones etc..

The only thing I can think of is that theres something about Android O that inhibits P2P peers being discovered.
I cannot see anything in the "Whats New In Android O" to identify the culprit

Has anyone seen this behaviour on Android O? What am I doing wrong? What am I missing?

The code I am basing my application on is to be found here

https://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html
https://developer.android.com/training/connect-devices-wirelessly/nsd-wifi-direct.html

Something odd that I noticed was that when I tried to keep the WiFi "stack" awake using an android.net.wifi.WifiManager.WifiLock
my application stopped working altogether. Further more I had to power off all my devices and restart them once I had removed the
associated WiFiLock code. And yes... I did add uses-permission android:name="android.permission.WAKE_LOCK".

UPDATE - 0001

Whats odd is that when I log out the extras available in my Broadcast Receiver for PEER_CHANGED I can see the available peers listed as shown here when the Android O Pixel XL has discovered my Nexus

```<code>WiFiDirectBroadcastRcvr: android.net.wifi.p2p.PEERS_CHANGED<<<<<EXTRA DATA :: ------------------------START
WiFiDirectBroadcastRcvr: EXTRA DATA :: wifiP2pDeviceList
                         Device: Nexus 7
                          deviceAddress: da:50:e6:7c:56:4e
                          primary type: 000A0050F2040005
                          secondary type: null
                          wps: 392
                          grpcapab: 0
                          devcapab: 37
                          status: 3
                          wfdInfo: WFD enabled: trueWFD DeviceInfo: 0
                          WFD CtrlPort: 0
                          WFD MaxThroughput: 0 (android.net.wifi.p2p.WifiP2pDeviceList)
WiFiDirectBroadcastRcvr: EXTRA DATA :: ------------------------FINISH
</code>```

However when I then make my subsequent call to requestPeers I always receive an empty WifiP2pDeviceList?

```<code>case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION:
                Log.d(TAG, "onReceive: WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION");
                mWiFiPeer2PeerCommander.requestPeers(mWifiP2pManager, mWifiP2pManagerChannel);
                break;
</code>```

Am I supposed to use the WifiP2pDeviceList from the passed Extra an not bother to call requestPeers?

答:
I had the same problem. On my nexus 5x now also Android O.
And I also always got an empty WifiP2pDeviceList.
I think it's assign (?) with similar problem on Android 6
SCAN_RESULTS_AVAILABLE_ACTION return empty list in Android 6.0

It works for me...

Body:
I am developing an Android Application that employs WiFi (Direct) for service discovery and P2P peer discovery/connection.

My development enviromment is as follows:-

Android Studio 3.0 Beta 4
Build #AI-171.4304935, built on August 29, 2017
JRE: 1.8.0_152-release-915-b01 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.11.6

My Gradle build:-

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.research.wifi_direct"

        minSdkVersion 19
        targetSdkVersion 26

        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    buildTypes {

        debug {
            buildConfigField "String", "INSTANCE_NAME", "\"_vascodagama\""
            buildConfigField "String", "SERVICE_TYPE", "\"_presence._tcp\""
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.0.2'
    implementation 'com.android.support:recyclerview-v7:26.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.yarolegovich:lovely-dialog:1.0.7'

    implementation 'io.realm:android-adapters:2.1.0'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

The devices I am testing on include:-

Nexus 7 - Android 6.0.1
Nexus 9 - Android 7.1.1
Samsung Tablet - Android 4.4.1
Pixel - Android 8.0.0

The service discovery works fine on all four devices.

However the P2P Peers List is always empty on the Pixel XL running Android 8.0.0.
The other three devices consistently discover each other as well as other miscellaneous devices
around my office e.g. such as a Samsung TV and my colleagues personal phones etc..

The only thing I can think of is that theres something about Android O that inhibits P2P peers being discovered.
I cannot see anything in the "Whats New In Android O" to identify the culprit

Has anyone seen this behaviour on Android O? What am I doing wrong? What am I missing?

The code I am basing my application on is to be found here

https://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html
https://developer.android.com/training/connect-devices-wirelessly/nsd-wifi-direct.html

Something odd that I noticed was that when I tried to keep the WiFi "stack" awake using an android.net.wifi.WifiManager.WifiLock
my application stopped working altogether. Further more I had to power off all my devices and restart them once I had removed the
associated WiFiLock code. And yes... I did add uses-permission android:name="android.permission.WAKE_LOCK".

UPDATE - 0001

Whats odd is that when I log out the extras available in my Broadcast Receiver for PEER_CHANGED I can see the available peers listed as shown here when the Android O Pixel XL has discovered my Nexus

WiFiDirectBroadcastRcvr: android.net.wifi.p2p.PEERS_CHANGED<<<<<EXTRA DATA :: ------------------------START
WiFiDirectBroadcastRcvr: EXTRA DATA :: wifiP2pDeviceList
                         Device: Nexus 7
                          deviceAddress: da:50:e6:7c:56:4e
                          primary type: 000A0050F2040005
                          secondary type: null
                          wps: 392
                          grpcapab: 0
                          devcapab: 37
                          status: 3
                          wfdInfo: WFD enabled: trueWFD DeviceInfo: 0
                          WFD CtrlPort: 0
                          WFD MaxThroughput: 0 (android.net.wifi.p2p.WifiP2pDeviceList)
WiFiDirectBroadcastRcvr: EXTRA DATA :: ------------------------FINISH

However when I then make my subsequent call to requestPeers I always receive an empty WifiP2pDeviceList?

case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION:
                Log.d(TAG, "onReceive: WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION");
                mWiFiPeer2PeerCommander.requestPeers(mWifiP2pManager, mWifiP2pManagerChannel);
                break;

Am I supposed to use the WifiP2pDeviceList from the passed Extra an not bother to call requestPeers?


问:
Trouble with displaying images pulled in from JSON file
I'm still pretty new to ionic and angular, and I'm working on a pokedex app. When I try to display images that I pulled in from a JSON file after setting up the data service, it displays the file path instead of the actual image. I'm not sure what I'm doing wrong. Can anyone help?

Here is a snippet from the JSON file:

{
    "pocketMonsters": [

        {
            "pokemonName": "Bulbasaur",
            "pokedexNumber": "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage": ""
        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : ""
        },```
</div>
</div>
</p>

<p>And here's the template. Besides the code that I already have in here, I have also tried <code><img src="pocketMonster.pokemonImage /></code> instead of {{poketMonster.pokemonImage}} and that returned a 404 error in the console.
<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><ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      {{pocketMonster.pokemonImage}}
    </ion-item>
   </ion-list>

  <!--<div *ngIf="pocketMonsters.length"></div> -->

</ion-content></code>```

I'll go ahead and include the home component and the data service in case those are needed as well.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   this.pocketMonsters = data;
                   return pocketMonster;

               });

               console.log(this.pocketMonsters);
           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}```
</div>
</div>
</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-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}</code>```

答:
Try it this way:

```<code>  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img src="{{pocketMonster.pokemonImage}}">
    </ion-item>
   </ion-list>
</code>```

or alternatively

```<code>  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img [src]="pocketMonster.pokemonImage">
    </ion-item>
   </ion-list>
</code>```

and in your data, do not put a premade tag, just the asset:

```<code>    {
        "pokemonName" : "Ivysaur",
        "pokedexNumber" : "002",
        "description" : "",
        "pokemonImage" : "assets/imgs/ivysaur.png"
    },
</code>```

This is assuming your image is in that location.

Also look here, but in your case there is no good reason to include HTML snippets.

It is bad practice too, in my opinion, at least in most™ cases.

Body:
I'm still pretty new to ionic and angular, and I'm working on a pokedex app. When I try to display images that I pulled in from a JSON file after setting up the data service, it displays the file path instead of the actual image. I'm not sure what I'm doing wrong. Can anyone help?

Here is a snippet from the JSON file:

{
    "pocketMonsters": [

        {
            "pokemonName": "Bulbasaur",
            "pokedexNumber": "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage": ""
        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : ""
        },

And here's the template. Besides the code that I already have in here, I have also tried  instead of {{poketMonster.pokemonImage}} and that returned a 404 error in the console.

<ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      {{pocketMonster.pokemonImage}}
    </ion-item>
   </ion-list>

</ion-content>

I'll go ahead and include the home component and the data service in case those are needed as well.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   this.pocketMonsters = data;
                   return pocketMonster;

               });

               console.log(this.pocketMonsters);
           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}

Body:
Try it this way:

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img src="{{pocketMonster.pokemonImage}}">
    </ion-item>
   </ion-list>

or alternatively

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img [src]="pocketMonster.pokemonImage">
    </ion-item>
   </ion-list>

and in your data, do not put a premade tag, just the asset:

    {
        "pokemonName" : "Ivysaur",
        "pokedexNumber" : "002",
        "description" : "",
        "pokemonImage" : "assets/imgs/ivysaur.png"
    },

This is assuming your image is in that location.

Also look here, but in your case there is no good reason to include HTML snippets.

It is bad practice too, in my opinion, at least in most™ cases.


问:
Difference in permission between "C" and "extern C"
I am trying to use a function in C in a C++ function.

Part of this function involves using fopen:

```<code>FILE * fd = NULL;
fd = fopen("/sys/platform/dacc/config","w");
if(!fd){
    perror("Platform configuration failed:");
    return -1;
}
fwrite(conf,1,4096,fd);
fclose(fd);
return 0;
</code>```

I had some code doing this in C which worked how I wanted. I would like to connect this operation to a button using Qt, and after asking a question about it here, I was able to call the function using "extern C" to include it into my c++ code.

Now that I have this same code running in C++ however, I am no longer able to open the file in question. Instead I now get a null returned by fopen, and perror gives the message

```<code>Platform configuration failed: Permission Denied
</code>```

This is confusing to me, as my C test code was run from a terminal without any elevation, so I didn't permissions should be any kind of issue.

Is there a difference in what permissions are available to a program running C code and those available to a C++ program including C code?

答: There should be no difference in permissions when using the "extern C" keyword. This just prevents the compiler from mangling the function's name.

Body:
I am trying to use a function in C in a C++ function.

Part of this function involves using fopen:

FILE * fd = NULL;
fd = fopen("/sys/platform/dacc/config","w");
if(!fd){
    perror("Platform configuration failed:");
    return -1;
}
fwrite(conf,1,4096,fd);
fclose(fd);
return 0;

I had some code doing this in C which worked how I wanted. I would like to connect this operation to a button using Qt, and after asking a question about it here, I was able to call the function using "extern C" to include it into my c++ code.

Now that I have this same code running in C++ however, I am no longer able to open the file in question. Instead I now get a null returned by fopen, and perror gives the message

Platform configuration failed: Permission Denied

This is confusing to me, as my C test code was run from a terminal without any elevation, so I didn't permissions should be any kind of issue.

Is there a difference in what permissions are available to a program running C code and those available to a C++ program including C code?


问:
Python: Understanding dictionary view objects
I've been trying to understand built-in view objects return by .items(), .values(), .keys() in Python 3 or similarly by .viewitems(), .viewvalues(), .viewkeys(). There are other threads on that subject but none (even the doc) seems to described how they work internally.

The main gain here seems to be efficienty compared to the copy of type list returned in Python 2. There are often compared to a window to the dictionnary items (like in this thread).

But what is that window and why is it more efficient ?

The only thing I can see is that the view objects seems to be  set-like objects, which are generally faster for membership testing. But is this the only factor ?

Code sample

```<code>>>> example_dict = {'test':'test'}
>>> example_dict.items()
dict_items([('test', 'test')])
>>> type(example_dict.items())
<class 'dict_items'>
</code>```

So, my question is regarding this dict_items class. How does that work internally?

答:
One of the main advantages is that views are dynamic:

```<code>>>> di={1:'one',2:'two',3:'three'}
>>> view=di.viewitems()
>>> view
dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
>>> di[2]='new two'
>>> view
dict_items([(1, 'one'), (2, 'new two'), (3, 'three')])
</code>```

Therefore you do not need to regenerate the item, key or value list (as you would with dict.items()) if the dictionary changes.

Think of the Python 2 dict.items() as a type of copy of the dict -- the way it was when the copy was made.

Think of Python 3 dict.items() or the Python 2 equivalent of dict.viewitems() as an up-to-date copy of the way the dict is now. (Same with .viewkeys(), .viewvalues() obviously.)

The Python 3.6 documents have good examples of why and when you would use one.

Value views are not set-like, since dicts can have duplicate values. Key views are set-like, and items views are set-like for dicts with hashable values.

Note: With Python 3, the view replaces what Python 2 had with .keys() .values() or .items() Some may relying on dict.keys() or dict.values() being a static representation of a dict's previous state may have a surprise.

Body:
I've been trying to understand built-in view objects return by .items(), .values(), .keys() in Python 3 or similarly by .viewitems(), .viewvalues(), .viewkeys(). There are other threads on that subject but none (even the doc) seems to described how they work internally.

The main gain here seems to be efficienty compared to the copy of type list returned in Python 2. There are often compared to a window to the dictionnary items (like in this thread).

But what is that window and why is it more efficient ?

The only thing I can see is that the view objects seems to be  set-like objects, which are generally faster for membership testing. But is this the only factor ?

Code sample

>>> example_dict = {'test':'test'}
>>> example_dict.items()
dict_items([('test', 'test')])
>>> type(example_dict.items())
<class 'dict_items'>

So, my question is regarding this dict_items class. How does that work internally?

Body:
One of the main advantages is that views are dynamic:

>>> di={1:'one',2:'two',3:'three'}
>>> view=di.viewitems()
>>> view
dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
>>> di[2]='new two'
>>> view
dict_items([(1, 'one'), (2, 'new two'), (3, 'three')])

Therefore you do not need to regenerate the item, key or value list (as you would with dict.items()) if the dictionary changes.

Think of the Python 2 dict.items() as a type of copy of the dict -- the way it was when the copy was made.

Think of Python 3 dict.items() or the Python 2 equivalent of dict.viewitems() as an up-to-date copy of the way the dict is now. (Same with .viewkeys(), .viewvalues() obviously.)

The Python 3.6 documents have good examples of why and when you would use one.

Value views are not set-like, since dicts can have duplicate values. Key views are set-like, and items views are set-like for dicts with hashable values.

Note: With Python 3, the view replaces what Python 2 had with .keys() .values() or .items() Some may relying on dict.keys() or dict.values() being a static representation of a dict's previous state may have a surprise.


问:
Adding external Google APIs to add-on initial auth scopes
I've built a Google Sheets add-on that retrieves data from the Google Search Console API and writes it to the user's spreadsheets.

Since the Search Console API isn't available in the "Advanced Google services" section in Apps Script, I used the OAuth2 library available on GitHub, with the "https://www.googleapis.com/auth/webmasters.readonly" scope. It currently uses separate credentials in the Developer Console.

While the add-on works fairly well, when a user installs it for the first time, he/she has to authorize it using Google's OAuth process for certain scopes that are automatically detected in the script (managing spreadsheets, send emails, do external requests, and so on). After the authorization is completed, the add-on displays the usual add-on sidebar where the user has to do an additional OAuth process, this time for approving access to the Search Console API (via the OAuth2 library mentioned earlier).

My goal would be to include the Search Console scope in the initial OAuth process, so that users wouldn't need to go through the process twice. Unfortunately, the "Scopes" section in the Apps Script Project Properties isn't editable, so I cannot add that manually, and as far as I know there's no way to make it so it gets automatically detected.

Is there any way to do that? Would it make any difference if I were to use the Apps Script credentials for the OAuth2 library that I'm using to access the Search Console API (instead of having a separate set)?

Thanks!

答:
It is now possible to customize the OAuth list of a project via editing its manifest file: https://developers.google.com/apps-script/concepts/scopes

Google mentions that not all Google OAuth scopes are included (I haven't managed to find an exact list), but I've tested adding the Google Search Console scope and it seems to work fine.


问:
Collatz - maximum number of steps and the corresponding number
I am trying to write a Scala function that takes an upper bound as argument and calculates the steps for the numbers in a range from 1 up to this bound. It had to return the maximum number of steps and the corresponding number that needs that many steps. (as a pair - first element is the number of steps and second is the corresponding index)

I already have created a function called "collatz" which computes the number of steps. I am very new with Scala and I am a bit stuck because of the limitations. Here's how I thought to start the function:

```<code>def max(x:Int):Int = {
  for (i<-(1 to x).toList) yield collatz(i)
</code>```

the way I think to solve this problem is to: 1. iterate through the range and apply collatz to all elements while putting them in a new list which stores the number of steps. 2. find the maximum of the new list by using List.max 3. Use List.IndexOf to find the index. However, I'm really stuck since I don't know how to do this without using var (and only using val). Thanks!

Body:
I am trying to write a Scala function that takes an upper bound as argument and calculates the steps for the numbers in a range from 1 up to this bound. It had to return the maximum number of steps and the corresponding number that needs that many steps. (as a pair - first element is the number of steps and second is the corresponding index)

I already have created a function called "collatz" which computes the number of steps. I am very new with Scala and I am a bit stuck because of the limitations. Here's how I thought to start the function:

def max(x:Int):Int = {
  for (i<-(1 to x).toList) yield collatz(i)

the way I think to solve this problem is to: 1. iterate through the range and apply collatz to all elements while putting them in a new list which stores the number of steps. 2. find the maximum of the new list by using List.max 3. Use List.IndexOf to find the index. However, I'm really stuck since I don't know how to do this without using var (and only using val). Thanks!

Body:
Try:

(1 to x).map(collatz).maxBy(_._2)._1


问:
Using SQL charindex to get string between quotes or multiple strings between occurrence or quotes
we are having to ID some data coming from a bad import and any help would be appreciated.
For instance a string like below and identifier char for the charindex.

```<code>SET @InputString  = 'The quick brown fox jumped "over" or "under" the log'
SET @IdentifierChar = '"'
</code>```

The issue we are having is that we can run our test against a hard coded string like the one above and get the result of 'over'. we have tried to put it in a while loop and then we get 'over','or','under'. The Expected Result for us would be only returning 'over', 'under' and not the or.

Our first go at a test was something like below just to see try and split:

```<code>DECLARE @InputString Nvarchar(MAX)
DECLARE @IdentifierChar NCHAR(1)
SET @InputString  = 'The quick brown fox jumped "over" or "under" the log'
SET @IdentifierChar = '"'

declare @FirstID int
declare @SecondID int
declare @Length int
declare @TargetString Nvarchar(MAX)

Set @FirstID = CHARINDEX(@IdentifierChar,@InputString,1)
Set @SecondID = CHARINDEX(@IdentifierChar,@InputString,@FirstID+1)
Set @Length = @SecondID-@FirstID
Set @TargetString = SUBSTRING(@InputString,@FirstID+1,@Length-1)
</code>```

Like I said then we literally just threw it in a hard coded loop and set the value of the substring to the last position of the identifier of the specialcharacter just to test and see how the charindex was splitting out the strings between the quotes and we did not think about it getting the 'or' as well.

so here is the dirty loop:

```<code>Set @COUNT = 0
Set @Length = 0
WHILE(@COUNT)<3
BEGIN
Set @FirstID = CHARINDEX(@IdentifierChar,@InputString,@Length)
Set @SecondID = CHARINDEX(@IdentifierChar,@InputString,@FirstID+1)
Set @Length = @SecondID-@FirstID
Set @TargetString = SUBSTRING(@InputString,@FirstID+1,@Length-1)
SET @COUNT = @COUNT+1
Set @Length =@SecondID
END
</code>```

答:
Just wanted to update. I continued to toy around with the code and got something to work in case anyone wants to use similar logic in the future. This did what we discussed above.</p>

```<code>DECLARE @TargetString NVARCHAR(MAX)
DECLARE @stringLen int
DECLARE @splitTbl TABLE(siteId NVARCHAR(MAX))
DECLARE @idChar NCHAR(1)

SET @TargetString = 'The quick brown fox jumped "over" or "under" the "log"'
SET @stringLen = CHARINDEX(' ', @TargetString)
SET @idChar = '"'

WHILE CHARINDEX(' ', @TargetString) > 0
BEGIN
SET @stringLen = CHARINDEX(' ', @TargetString);

INSERT INTO @splitTbl
SELECT SUBSTRING(@TargetString,1,@stringLen - 1);

SET @TargetString = SUBSTRING(@TargetString, @stringLen + 1,
LEN(@TargetString));
END

DECLARE @buildResults NVARCHAR(MAX)
INSERT INTO @splitTbl
SELECT @TargetString

DECLARE @buildLike NVARCHAR(MAX)
SET @buildLike = '%'+@idChar+'%'
SELECT  @buildResults = COALESCE(@buildResults + ', ', '')
+SUBSTRING(siteId, 2, lEN(siteId) - 2)
FROM @splitTbl
WHERE siteId LIKE @buildLike
</code>```

Body:
we are having to ID some data coming from a bad import and any help would be appreciated.
For instance a string like below and identifier char for the charindex.

SET @InputString  = 'The quick brown fox jumped "over" or "under" the log'
SET @IdentifierChar = '"'

The issue we are having is that we can run our test against a hard coded string like the one above and get the result of 'over'. we have tried to put it in a while loop and then we get 'over','or','under'. The Expected Result for us would be only returning 'over', 'under' and not the or.

Our first go at a test was something like below just to see try and split:

DECLARE @InputString Nvarchar(MAX)
DECLARE @IdentifierChar NCHAR(1)
SET @InputString  = 'The quick brown fox jumped "over" or "under" the log'
SET @IdentifierChar = '"'

declare @FirstID int
declare @SecondID int
declare @Length int
declare @TargetString Nvarchar(MAX)

Set @FirstID = CHARINDEX(@IdentifierChar,@InputString,1)
Set @SecondID = CHARINDEX(@IdentifierChar,@InputString,@FirstID+1)
Set @Length = @SecondID-@FirstID
Set @TargetString = SUBSTRING(@InputString,@FirstID+1,@Length-1)

Like I said then we literally just threw it in a hard coded loop and set the value of the substring to the last position of the identifier of the specialcharacter just to test and see how the charindex was splitting out the strings between the quotes and we did not think about it getting the 'or' as well.

so here is the dirty loop:

Set @COUNT = 0
Set @Length = 0
WHILE(@COUNT)<3
BEGIN
Set @FirstID = CHARINDEX(@IdentifierChar,@InputString,@Length)
Set @SecondID = CHARINDEX(@IdentifierChar,@InputString,@FirstID+1)
Set @Length = @SecondID-@FirstID
Set @TargetString = SUBSTRING(@InputString,@FirstID+1,@Length-1)
SET @COUNT = @COUNT+1
Set @Length =@SecondID
END

Body:
Just wanted to update. I continued to toy around with the code and got something to work in case anyone wants to use similar logic in the future. This did what we discussed above.

DECLARE @TargetString NVARCHAR(MAX)
DECLARE @stringLen int
DECLARE @splitTbl TABLE(siteId NVARCHAR(MAX))
DECLARE @idChar NCHAR(1)

SET @TargetString = 'The quick brown fox jumped "over" or "under" the "log"'
SET @stringLen = CHARINDEX(' ', @TargetString)
SET @idChar = '"'

WHILE CHARINDEX(' ', @TargetString) > 0
BEGIN
SET @stringLen = CHARINDEX(' ', @TargetString);

INSERT INTO @splitTbl
SELECT SUBSTRING(@TargetString,1,@stringLen - 1);

SET @TargetString = SUBSTRING(@TargetString, @stringLen + 1,
LEN(@TargetString));
END

DECLARE @buildResults NVARCHAR(MAX)
INSERT INTO @splitTbl
SELECT @TargetString

DECLARE @buildLike NVARCHAR(MAX)
SET @buildLike = '%'+@idChar+'%'
SELECT  @buildResults = COALESCE(@buildResults + ', ', '')
+SUBSTRING(siteId, 2, lEN(siteId) - 2)
FROM @splitTbl
WHERE siteId LIKE @buildLike


问:
C# Embedded Browser ignores CSS Wordwrap
I have primary login page that we access and bring into an embedded browser.
I am attempting to get the words to wrap properly on the page.

We have CSS class attached to the html elements coming through but the word wrap seems to be ignored. I have an inclination that this is a property of the Web Control that can be set. The word wrap does not seem to think it needs to be wrapped at all. The background color works just fine.

We have a flex property on the parent CSS which I tried removing but that did not seem to work.

HTML section

```<code>    <div class="words">
      <p class="test">ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ</p>
      <p class="test"><a href='about.asp' target='_blank'>YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY</a></p>
    </div>
</code>```

CSS Entries

```<code>.words {
  flex: 0 1 auto;
  .corporateFontFamily;

  padding: 0 50px 20px 0;
  word-wrap:break-word;
}

.test {
    word-wrap: break-word;
    background-color: #4286f4;
}
</code>```

XAML

```<code>  <Grid>

    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
        <Grid x:Name="LayoutRoot" Height="550" Width="600">
      <WebBrowser x:Name="EmbeddedBrowser" MinHeight="20" MinWidth="20"
                            Height="550" Width="650"
                            Navigated="EmbeddedBrowserLoadCompleted"
                            Margin="0,0,0,0"
                            ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                            ScrollViewer.VerticalScrollBarVisibility="Hidden"
                            ScrollViewer.IsDeferredScrollingEnabled="False"
                            ScrollViewer.CanContentScroll="False"
                            >
      </WebBrowser>
    </Grid>
  </Grid>
</AppCore:DialogViewBase>
</code>```

What the page looks like. You can see the Salmon colored entries spill off the page. Why would the word wrap be ignored?

答:
The WebBrowser control uses older Internet Explorer (IE7) by default.

You can override that behavior with special markup in your webpage's header or with a registry setting, as explained at:

https://blogs.msdn.microsoft.com/patricka/2015/01/12/controlling-webbrowser-control-compatibility/

Body:
I have primary login page that we access and bring into an embedded browser.
I am attempting to get the words to wrap properly on the page.

We have CSS class attached to the html elements coming through but the word wrap seems to be ignored. I have an inclination that this is a property of the Web Control that can be set. The word wrap does not seem to think it needs to be wrapped at all. The background color works just fine.

We have a flex property on the parent CSS which I tried removing but that did not seem to work.

HTML section

ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ

YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY

CSS Entries

.words {
  flex: 0 1 auto;
  .corporateFontFamily;

  padding: 0 50px 20px 0;
  word-wrap:break-word;
}

.test {
    word-wrap: break-word;
    background-color: #4286f4;
}

XAML

  <Grid>

    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
        <Grid x:Name="LayoutRoot" Height="550" Width="600">
      <WebBrowser x:Name="EmbeddedBrowser" MinHeight="20" MinWidth="20"
                            Height="550" Width="650"
                            Navigated="EmbeddedBrowserLoadCompleted"
                            Margin="0,0,0,0"
                            ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                            ScrollViewer.VerticalScrollBarVisibility="Hidden"
                            ScrollViewer.IsDeferredScrollingEnabled="False"
                            ScrollViewer.CanContentScroll="False"
                            >
      </WebBrowser>
    </Grid>
  </Grid>
</AppCore:DialogViewBase>

What the page looks like. You can see the Salmon colored entries spill off the page. Why would the word wrap be ignored?


问:
HLSL hue change algorithm
I want to make a pixel shader for Silverlight which will help me to change the Hue/Saturation/Lightness using  a slider.
* Hue slider has values in range: [-180, 180]
* Saturation slider has values in range: [-100, 100]
* Lightness slider has values in range: [-100, 100]

I managed to create a pixel shader which can manipulate the Saturation and Lightness values.
But I can find any algorithm for changing the hue value.
Can anyone provide me an algorithm? Thank you.

Here is my HLSL code:

```<code>/// <summary>The brightness offset.</summary>
/// <minValue>-180</minValue>
/// <maxValue>180</maxValue>
/// <defaultValue>0</defaultValue>
float Hue : register(C0);

/// <summary>The saturation offset.</summary>
/// <minValue>-100</minValue>
/// <maxValue>100</maxValue>
/// <defaultValue>0</defaultValue>
float Saturation : register(C1);

/// <summary>The lightness offset.</summary>
/// <minValue>-100</minValue>
/// <maxValue>100</maxValue>
/// <defaultValue>0</defaultValue>
float Lightness : register(C2);

sampler2D input : register(S0);

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------

float4 main(float2 uv : TEXCOORD) : COLOR
{
 // some vars
 float saturation = Saturation / 100 + 1;
 float lightness = Lightness / 100;
 float3  luminanceWeights = float3(0.299,0.587,0.114);

    // input raw pixel
    float4 srcPixel = tex2D(input, uv);

    // Apply saturation
    float luminance = dot(srcPixel, luminanceWeights);
    float4 dstPixel = lerp(luminance, srcPixel, saturation);

    // Apply lightness
    dstPixel.rgb += lightness;

    //retain the incoming alpha
    dstPixel.a = srcPixel.a;

    return dstPixel;
}
</code>```

答: The conversions between colour spaces are available at EasyRGB, see this post at nokola.com for a Silverlight implementation of a Hue shift. It may be possible to fit hue, saturation and brightness in one PS 2.0 shader if you take the approach mentioned here but I haven't tried.</p>

Title: HLSL hue change algorithm

Body:
I want to make a pixel shader for Silverlight which will help me to change the Hue/Saturation/Lightness using  a slider.
* Hue slider has values in range: [-180, 180]
* Saturation slider has values in range: [-100, 100]
* Lightness slider has values in range: [-100, 100]

I managed to create a pixel shader which can manipulate the Saturation and Lightness values.
But I can find any algorithm for changing the hue value.
Can anyone provide me an algorithm? Thank you.

Here is my HLSL code:

/// The brightness offset.
/// <minValue>-180</minValue>
/// <maxValue>180</maxValue>
/// <defaultValue>0</defaultValue>
float Hue : register(C0);

/// The saturation offset.
/// <minValue>-100</minValue>
/// <maxValue>100</maxValue>
/// <defaultValue>0</defaultValue>
float Saturation : register(C1);

/// The lightness offset.
/// <minValue>-100</minValue>
/// <maxValue>100</maxValue>
/// <defaultValue>0</defaultValue>
float Lightness : register(C2);

sampler2D input : register(S0);

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------

float4 main(float2 uv : TEXCOORD) : COLOR
{
 // some vars
 float saturation = Saturation / 100 + 1;
 float lightness = Lightness / 100;
 float3  luminanceWeights = float3(0.299,0.587,0.114);

    // input raw pixel
    float4 srcPixel = tex2D(input, uv);

    // Apply saturation
    float luminance = dot(srcPixel, luminanceWeights);
    float4 dstPixel = lerp(luminance, srcPixel, saturation);

    // Apply lightness
    dstPixel.rgb += lightness;

    //retain the incoming alpha
    dstPixel.a = srcPixel.a;

    return dstPixel;
}


问:
When appending a python variable to a list I am getting object values
```<code>print("Device discovered: %s" % remote)
m.append(remote)
print(m)
</code>```

I am getting the following result. How Can I get same value is the list names m

```<code>Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]
</code>```

答: Did you try m.append(str(remote))? It is possible there is a __str__ function implemented in remote object. Such magic function will handle object to string conversion when it's necessary. When you format the object it is necessary to convert to str but when you append it to a list it's not.

Body:
print("Device discovered: %s" % remote)
m.append(remote)
print(m)

I am getting the following result. How Can I get same value is the list names m

Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]


问:
Is it possible to get cv2 frame from another process?
I am trying to run simple motion detection with opencv. Got that working. Now that process is running as a background process.

I want to be able to see the processed image by connecting to it via flask.

How do you start a process and connect to it at any point in time to see the output of that processed frame w/o writing the image to a database? Is there a way?

would appreciate any tutorial /reference / code

答:
Figured it out.

You can write to an intermediary file. 2nd process can read this file, only issue is that you get a "flickering" effect because the 2nd process might be trying to read the image b4 the 1st process has a chance to read it in entirety

You can try and replicate the same with pyperclip, but not sure how you'd do multiple clipboards


问:
Creating abstract object in Spring - Lookup Method
I've came across this article ARTICLE when I was looking for information about LookUp methods in Spring. I can't understand one thing which isn't explained there. If we got a class:

```<code>public abstract class PizzaShop {
public abstract Pizza makePizza();
public abstract Pizza makeVeggiePizza();
}
</code>```

and Spring Container:

```<code><?xml version="1.0" encoding="UTF-8"?>

(...)

<bean id="pizzaShop" class="com.javarticles.spring.PizzaShop">
    <lookup-method name="makePizza" bean="pizza"/>
    <lookup-method name="makeVeggiePizza" bean="veggiePizza"/>
</bean>

<bean id="pizza" class="com.javarticles.spring.Pizza" scope="prototype"/>

<bean id="veggiePizza" class="com.javarticles.spring.Pizza" scope="prototype">
    <property name="isVeg" value="true"/>
</bean>
</code>```

Which has a bean which is created basing on abstract class!
And now when we perform such code in main method:

```<code>ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");
PizzaShop pizzaShop = (PizzaShop) context.getBean("pizzaShop");
</code>```

We are creating an abstract object! Which apart framework isn't allowed. Why is it possible here, or where i'm making mistake in understanding whole concept?

答:
It is possible because the Spring Framework manipulates bytecode at runtime to create a subclass of the bean class that defines at least one of these properties with  lookup-method.

Here is Spring 5 Lookup method injection documentation.

Lookup method injection

Lookup method injection is the ability of the container to override
  methods on container managed beans, to return the lookup result for
  another named bean in the container. The lookup typically involves a
  prototype bean as in the scenario described in the preceding section.
  The Spring Framework implements this method injection by using
  bytecode generation from the CGLIB library to generate dynamically a
  subclass that overrides the method.

Whatever the method be abstract or not, Spring relies on the same mechanism : a dynamically generated subclass.

In the first case, it implements.

In the second case, it overrides.

If the method is abstract, the dynamically-generated subclass
  implements the method. Otherwise, the dynamically-generated subclass
  overrides the concrete method defined in the original class.

Body:
I've came across this article ARTICLE when I was looking for information about LookUp methods in Spring. I can't understand one thing which isn't explained there. If we got a class:

public abstract class PizzaShop {
public abstract Pizza makePizza();
public abstract Pizza makeVeggiePizza();
}

and Spring Container:

<?xml version="1.0" encoding="UTF-8"?>

(...)

<bean id="pizzaShop" class="com.javarticles.spring.PizzaShop">
    <lookup-method name="makePizza" bean="pizza"/>
    <lookup-method name="makeVeggiePizza" bean="veggiePizza"/>
</bean>

<bean id="pizza" class="com.javarticles.spring.Pizza" scope="prototype"/>

<bean id="veggiePizza" class="com.javarticles.spring.Pizza" scope="prototype">
    <property name="isVeg" value="true"/>
</bean>

Which has a bean which is created basing on abstract class!
And now when we perform such code in main method:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");
PizzaShop pizzaShop = (PizzaShop) context.getBean("pizzaShop");

We are creating an abstract object! Which apart framework isn't allowed. Why is it possible here, or where i'm making mistake in understanding whole concept?


问:
React Routing, refresh does not render specific view, but redirects to parent view
This is our parent view:
http://localhost:8080/#/dashboard/

When I click on a link to Menu Navigation:
http://localhost:8080/#/dashboard/menu-navigation

This will load up the correct menu-navigation view, however if I refresh the app goes back to /dashboard instead of staying on menu-navigation.

From the main Routes.js

```<code>const Routes = () => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route path="/login" exact component={Login} />
        <Route path="/redirect" component={FirebaseRedirector} />
        <Route path="/restricted-access" component={RestrictedAccess} />
        <Route path="/change-password/:hash?" component={ChangePassword} />
        <Route path="/reset-password" exact component={ResetPassword} />
        <Route path="/" component={Main} />
        <Route path="*" component={NotFound} />
      </Switch>
    </ConnectedRouter>
  </Provider>
);

export default Routes;
</code>```

Note once you are logged in the Main component above is loaded:

```<code>render() {
  return (
    <Main
      user={this.props.user}
      signOut={this.signOut}
    >
      <Switch>
        <Route
          path="/dashboard/categories/unmatched-api/:id?"
          component={CategoriesUnmatchedApi}
          notExact
        />
        <Route path="/dashboard/menu-navigation" exact component={MenuNavigation} />
        <Route path="/dashboard/home-screen" exact component={HomeScreen} />
        <Route path="/dashboard/categories/product-config" component={CategoryProductConfig} />
        <Route path="/dashboard/categories/:category?" component={Categories} />
        <Route path="/dashboard/playground" exact component={Playground} />
        <Route path="/dashboard" exact component={Drafts} />
        <Route path="/" exact component={Drafts} />
        <Route path="*" component={NotFound} />
      </Switch>
    </Main>
  );
}
</code>```

Here is the state once you navigate to the MenuNavigation route

Then the state after refresh

Seems like react router is not respecting <Route path="/dashboard/menu-navigation" ?

I did notice after refresh that the Main.js route section gets hit 3 times, the first time the this.props.location is correct, however the next 2 times it's just /dashboard

答:
Figured it out! We had a redirect to the /dashboard everytime.

Inside our login actions we had:

onAuthStateChange -> checkAuth which contained this:

dispatch(push(authDasboardView));

After removing the dispatch to authDashboardView, this fixed the problem!

Body:
This is our parent view:
http://localhost:8080/#/dashboard/

When I click on a link to Menu Navigation:
http://localhost:8080/#/dashboard/menu-navigation

This will load up the correct menu-navigation view, however if I refresh the app goes back to /dashboard instead of staying on menu-navigation.

From the main Routes.js

const Routes = () => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route path="/login" exact component={Login} />
        <Route path="/redirect" component={FirebaseRedirector} />
        <Route path="/restricted-access" component={RestrictedAccess} />
        <Route path="/change-password/:hash?" component={ChangePassword} />
        <Route path="/reset-password" exact component={ResetPassword} />
        <Route path="/" component={Main} />
        <Route path="*" component={NotFound} />
      </Switch>
    </ConnectedRouter>
  </Provider>
);

export default Routes;

Note once you are logged in the Main component above is loaded:

render() {
  return (

      <Switch>
        <Route
          path="/dashboard/categories/unmatched-api/:id?"
          component={CategoriesUnmatchedApi}
          notExact
        />
        <Route path="/dashboard/menu-navigation" exact component={MenuNavigation} />
        <Route path="/dashboard/home-screen" exact component={HomeScreen} />
        <Route path="/dashboard/categories/product-config" component={CategoryProductConfig} />
        <Route path="/dashboard/categories/:category?" component={Categories} />
        <Route path="/dashboard/playground" exact component={Playground} />
        <Route path="/dashboard" exact component={Drafts} />
        <Route path="/" exact component={Drafts} />
        <Route path="*" component={NotFound} />
      </Switch>

  );
}

Here is the state once you navigate to the MenuNavigation route

Then the state after refresh

Seems like react router is not respecting <Route path="/dashboard/menu-navigation" ?

I did notice after refresh that the Main.js route section gets hit 3 times, the first time the this.props.location is correct, however the next 2 times it's just /dashboard


问:
How to create library or framework for iPhone?
I want to create a library in Objective C in XCode, like the MKMapKit framework. How can I create this?

What type of project do I have to create for this?

答: You create a framework project - Apple dev docs</p>


问:
Sqoop import statement
The below mentioned sqoop import statements worked for me the other day and today the same statements is showing error. Below is the error and import statement.

ERROR:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sqoop import

```<code>sqoop import \
--connect jdbc:mysql://localhost/loudacre \
--username training --password training \
--table device \
-- target-dir /loudacre/device
-m 1
</code>```

答: Error solved guys. Turns out when you copy paste the command from notepad to terminal, " changes and results into an error.We need to explicitly write " in the temrinal.</p>

Title: Sqoop import statement

Body:
The below mentioned sqoop import statements worked for me the other day and today the same statements is showing error. Below is the error and import statement.

ERROR:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sqoop import

sqoop import \
--connect jdbc:mysql://localhost/loudacre \
--username training --password training \
--table device \
-- target-dir /loudacre/device
-m 1