问:
Android Error While using ExifInterface
I am trying to check the orientation of bitmap and flip it if there is a need, but I have error while applying the code. Here is my code while i am trying to flipp the image using ExifInterface:

```<code>@RequiresApi(api = Build.VERSION_CODES.N)
    public void flipping(Bitmap b)
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG,100, bos);
        byte[] bitmapdata = bos.toByteArray();
        ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
        try {

            ExifInterface exif = new ExifInterface(bs);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            switch(orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotateImage(b, 90);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotateImage(b, 180);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotateImage(b, 270);
                    break;

                case ExifInterface.ORIENTATION_NORMAL:

                default:
                    break;
            }

            encoding();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Bitmap rotateImage(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                matrix, true);
    }
</code>```

And here is the error:

```<code>java.lang.NoSuchMethodError: No direct method <init>(Ljava/io/InputStream;)V in class Landroid/media/ExifInterface; or its super classes (declaration of 'android.media.ExifInterface' appears in /system/framework/framework.jar)
                                                                       at com.sara.image_test.MainActivity.flipping(MainActivity.java:181)
                                                                       at com.sara.image_test.MainActivity.onActivityResult(MainActivity.java:66)
                                                                       at android.app.Activity.dispatchActivityResult(Activity.java:7165)
                                                                       at android.app.ActivityThread.deliverResults(ActivityThread.java:4994)
                                                                       at android.app.ActivityThread.handleSendResult(ActivityThread.java:5041)
                                                                       at android.app.ActivityThread.access$1600(ActivityThread.java:229)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
Add this to your build.gradle file

```<code>compile "com.android.support:exifinterface:25.1.0"
</code>```

for me it worked.

Title: Android Error While using ExifInterface

Body:
I am trying to check the orientation of bitmap and flip it if there is a need, but I have error while applying the code. Here is my code while i am trying to flipp the image using ExifInterface:

@RequiresApi(api = Build.VERSION_CODES.N)
    public void flipping(Bitmap b)
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG,100, bos);
        byte[] bitmapdata = bos.toByteArray();
        ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
        try {

            ExifInterface exif = new ExifInterface(bs);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            switch(orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotateImage(b, 90);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotateImage(b, 180);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotateImage(b, 270);
                    break;

                case ExifInterface.ORIENTATION_NORMAL:

                default:
                    break;
            }

            encoding();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Bitmap rotateImage(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                matrix, true);
    }

And here is the error:

java.lang.NoSuchMethodError: No direct method <init>(Ljava/io/InputStream;)V in class Landroid/media/ExifInterface; or its super classes (declaration of 'android.media.ExifInterface' appears in /system/framework/framework.jar)
                                                                       at com.sara.image_test.MainActivity.flipping(MainActivity.java:181)
                                                                       at com.sara.image_test.MainActivity.onActivityResult(MainActivity.java:66)
                                                                       at android.app.Activity.dispatchActivityResult(Activity.java:7165)
                                                                       at android.app.ActivityThread.deliverResults(ActivityThread.java:4994)
                                                                       at android.app.ActivityThread.handleSendResult(ActivityThread.java:5041)
                                                                       at android.app.ActivityThread.access$1600(ActivityThread.java:229)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
Add this to your build.gradle file

compile "com.android.support:exifinterface:25.1.0"

for me it worked.


来源: stackexchange

问:
how to find a descendant with highest value in xml actionscript
ok so in actionscript using xml I can find all the nodes of the same name using

```<code>xmlList.descendants("nodename");
</code>```

and that returns me a XMLlist of those nodes that exist within the xmlList I provided all well and good but now I want to only get the one node of the returned value that has the largest value.

So the question is this. Do I have to loop through the resulting nodes or can I get that node without a loop maybe some other xmllist function I'm not aware of ?

thanks

答:
With this xml:

```<code>var data:XML = <items>
         <item name="Wii">
             <price>364.00</price>
         </item>
         <item name="Wii">
             <price>249.99</price>
         </item>
         <item name="X-Box 360">
             <price>399.99</price>
         </item>
         <item name="PlayStation 3">
             <price>599.99</price>
        </item>
</items>;

var filter:XMLList = data.item.(price > 300);
            trace(filter);
</code>```

You will get an output of:

```<code><item name="Wii">
  <source>Amazon</source>
  <price>364.00</price>
</item>
<item name="X-Box 360">
  <source>Amazon</source>
  <price>399.99</price>
</item>
<item name="PlayStation 3">
  <source>Amazon</source>
  <price>599.99</price>
</item>
</code>```

I think this is the closest you could get with getting numbers,and there is no a way you can get a max/min value straight from XML (you probably need to create some functions) you can read an implementation of it here :
MinMaxXML

ContentLicense: CC BY-SA 2.5

Body:
ok so in actionscript using xml I can find all the nodes of the same name using

xmlList.descendants("nodename");

and that returns me a XMLlist of those nodes that exist within the xmlList I provided all well and good but now I want to only get the one node of the returned value that has the largest value.

So the question is this. Do I have to loop through the resulting nodes or can I get that node without a loop maybe some other xmllist function I'm not aware of ?

thanks

Body:
With this xml:

var data:XML = <items>
         <item name="Wii">
             <price>364.00</price>
         </item>
         <item name="Wii">
             <price>249.99</price>
         </item>
         <item name="X-Box 360">
             <price>399.99</price>
         </item>
         <item name="PlayStation 3">
             <price>599.99</price>
        </item>
</items>;

var filter:XMLList = data.item.(price > 300);
            trace(filter);

You will get an output of:

<item name="Wii">
  <source>Amazon</source>
  <price>364.00</price>
</item>
<item name="X-Box 360">
  <source>Amazon</source>
  <price>399.99</price>
</item>
<item name="PlayStation 3">
  <source>Amazon</source>
  <price>599.99</price>
</item>

I think this is the closest you could get with getting numbers,and there is no a way you can get a max/min value straight from XML (you probably need to create some functions) you can read an implementation of it here :
MinMaxXML


问:
In Angular for which arrtributes we have to use parentheses and for which we have to use bracket
I am a bit confused about using parentheses and brackets on attributes in Angular.</p>

```<code><form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>
</code>```

答: Parantheses is used for function calling while brackets used to pass or set an attribute. For more go through angular documentation @ www.angular.io</p>

ContentLicense: CC BY-SA 3.0

Body:
I am a bit confused about using parentheses and brackets on attributes in Angular.

<form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>


问:
C++: Is a pointer as function's parameter really copied?
According to the answer https://stackoverflow.com/a/11842442/5835947, if you code like this, function parameter Bubble * targetBubble will be copied inside the function.

```<code>bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}
</code>```

However, I made a test, finding that a pointer as function parameter will be the same as the outside one, until I changed it's value:

```<code>// c++ test ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "c++ test ConsoleApplication2.h"
using namespace std;
#include<iostream>

int main()
{
    int a= 1;
    int* pointerOfA = &a;

    cout << "address of pointer is" << pointerOfA << endl;
    cout << *pointerOfA << endl;
    func(pointerOfA);
    cout << *pointerOfA << endl;

}

void func(int *pointer)
{
    cout << "address of pointer is " << pointer  <<" it's the same as the pointer outside!"<<endl;

    int b = 2;
    pointer = &b;
    cout << "address of pointer is" << pointer <<" it's changed!"<< endl;

    cout << *pointer<<endl;

}
</code>```

Output is below:

```<code>address of pointer is0093FEB4
1
address of pointer is 0093FEB4 it's the same as the pointer outside!
address of pointer is0093FDC4 it's changed!
2
1
</code>```

So, the truth is that, a pointer as function parameter will not be copied, until it's changed, right? Or am I missing something here?

答:
The pointer (variable holding just an address - usually just a 32 or 64 bit integer) is copied.
What the pointer points to is not.

So yes, you are missing something. You need to understand that a pointer is not the object it points to. It's just a small integer value saying "that's the object over there" - and copying that pointer is cheap and doesn't change what it's pointing at.

Body:
According to the answer https://stackoverflow.com/a/11842442/5835947, if you code like this, function parameter Bubble * targetBubble will be copied inside the function.

bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}

However, I made a test, finding that a pointer as function parameter will be the same as the outside one, until I changed it's value:

// c++ test ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "c++ test ConsoleApplication2.h"
using namespace std;
#include<iostream>

int main()
{
    int a= 1;
    int* pointerOfA = &a;

    cout << "address of pointer is" << pointerOfA << endl;
    cout << *pointerOfA << endl;
    func(pointerOfA);
    cout << *pointerOfA << endl;

}

void func(int *pointer)
{
    cout << "address of pointer is " << pointer  <<" it's the same as the pointer outside!"<<endl;

    int b = 2;
    pointer = &b;
    cout << "address of pointer is" << pointer <<" it's changed!"<< endl;

    cout << *pointer<<endl;

}

Output is below:

address of pointer is0093FEB4
1
address of pointer is 0093FEB4 it's the same as the pointer outside!
address of pointer is0093FDC4 it's changed!
2
1

So, the truth is that, a pointer as function parameter will not be copied, until it's changed, right? Or am I missing something here?


问:
Don't get firebase token when I use firebase-ui in gradle
I am using the following command to get a token from firebase:

```<code>FirebaseInstanceId.getInstance().getToken();
</code>```

Everything works great but when I use the following command in gradle I get the error:

```<code>compile 'com.firebaseui:firebase-ui:0.6.2'
</code>```

My logcat is:

```<code>Process: ir.bitafaraz.dpnaadmin, PID: 17325
java.lang.NoSuchMethodError: com.google.android.gms.common.util.zzx.getNoBackupFilesDir
at com.google.firebase.iid.zzg.zzeC(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzd.zzb(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at ir.bitafaraz.dpnaadmin.LoginActivity.onClick(LoginActivity.java:250)
at android.view.View.performClick(View.java:4457)
at com.balysv.materialripple.MaterialRippleLayout$PerformClickEvent.run(MaterialRippleLayout.java:648)
at com.balysv.materialripple.MaterialRippleLayout$3.onAnimationEnd(MaterialRippleLayout.java:336)
at android.animation.AnimatorSet$AnimatorSetListener.onAnimationEnd(AnimatorSet.java:818)
at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1078)
at android.animation.ValueAnimator.access$400(ValueAnimator.java:53)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:649)
at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:665)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:768)
at android.view.Choreographer.doCallbacks(Choreographer.java:581)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:754)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)
</code>```

My gradle is:

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "ir.bitafaraz.dpnaadmin"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 16
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:animated-vector-drawable:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:palette-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:customtabs:25.3.1'

    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    compile 'com.firebaseui:firebase-ui:0.6.2'
}

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

答:
I changed version firebase to 1.1.1 and firebase messaging to 10.0.1:

```<code>compile 'com.firebaseui:firebase-ui:1.1.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'
</code>```

And then add this command to application tag in Manifest.xml:

```<code>tools:replace="android:supportsRtl"
</code>```

And Add this command to gradle:

```<code>allprojects {
    repositories {
        jcenter()

        // Required for 'com.firebaseui:firebase-ui:1.1.1'
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
I am using the following command to get a token from firebase:

FirebaseInstanceId.getInstance().getToken();

Everything works great but when I use the following command in gradle I get the error:

compile 'com.firebaseui:firebase-ui:0.6.2'

My logcat is:

Process: ir.bitafaraz.dpnaadmin, PID: 17325
java.lang.NoSuchMethodError: com.google.android.gms.common.util.zzx.getNoBackupFilesDir
at com.google.firebase.iid.zzg.zzeC(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzg.<init>(Unknown Source)
at com.google.firebase.iid.zzd.zzb(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at ir.bitafaraz.dpnaadmin.LoginActivity.onClick(LoginActivity.java:250)
at android.view.View.performClick(View.java:4457)
at com.balysv.materialripple.MaterialRippleLayout$PerformClickEvent.run(MaterialRippleLayout.java:648)
at com.balysv.materialripple.MaterialRippleLayout$3.onAnimationEnd(MaterialRippleLayout.java:336)
at android.animation.AnimatorSet$AnimatorSetListener.onAnimationEnd(AnimatorSet.java:818)
at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1078)
at android.animation.ValueAnimator.access$400(ValueAnimator.java:53)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:649)
at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:665)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:768)
at android.view.Choreographer.doCallbacks(Choreographer.java:581)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:754)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:711)
at dalvik.system.NativeStart.main(Native Method)

My gradle is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "ir.bitafaraz.dpnaadmin"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 16
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:animated-vector-drawable:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:palette-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:customtabs:25.3.1'

    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.1@aar'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    compile 'com.firebaseui:firebase-ui:0.6.2'
}

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

Body:
I changed version firebase to 1.1.1 and firebase messaging to 10.0.1:

compile 'com.firebaseui:firebase-ui:1.1.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'

And then add this command to application tag in Manifest.xml:

tools:replace="android:supportsRtl"

And Add this command to gradle:

allprojects {
    repositories {
        jcenter()

        // Required for 'com.firebaseui:firebase-ui:1.1.1'
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
Sychronize text with audio file
I have a poem text inserted in an HTML page. Each verse of the poem is inserted into a div with an id corresponding to the number of the verse.

My wish is as follows:

Each verse has a matching audio file and when the user clicks the play button, playback starts and the audio of the corresponding verse is played back also the background Color changes to show the current verse. Also, the current verse div must be scrolled on top of the window.

The javascript code below doesn't work as expected and it changes the color for all div and not playing the sound correctly.

```<code>function lecture() {
  var nbDivs = 28;
  for (i = 1; i <= nbDivs.length; i++) {

    location.href = '#'+i;
    var div = document.getElementById(i);
    div.style.backgroundColor = 'green';
    var audio = new Audio(i + '.mp3');
    audio.play();
  }
}
</code>```

For the HTML code is verse are in separated div elements with the number of the verse as an id.

That's what I've got till now but that's not working.

Any idea to do it in javascript or in Angular2

答: I would propose to have a time-verse mapping where you specify which line starts at which time. Afterwards you could simply look for the corresponding div element and move that to the top or hide all previous elements.</p>

Title: Sychronize text with audio file

Body:
I have a poem text inserted in an HTML page. Each verse of the poem is inserted into a div with an id corresponding to the number of the verse.

My wish is as follows:

Each verse has a matching audio file and when the user clicks the play button, playback starts and the audio of the corresponding verse is played back also the background Color changes to show the current verse. Also, the current verse div must be scrolled on top of the window.

The javascript code below doesn't work as expected and it changes the color for all div and not playing the sound correctly.

function lecture() {
  var nbDivs = 28;
  for (i = 1; i <= nbDivs.length; i++) {

    location.href = '#'+i;
    var div = document.getElementById(i);
    div.style.backgroundColor = 'green';
    var audio = new Audio(i + '.mp3');
    audio.play();
  }
}

For the HTML code is verse are in separated div elements with the number of the verse as an id.

That's what I've got till now but that's not working.

Any idea to do it in javascript or in Angular2


问:
POST form when fields are valid
I have form. when use submit the form I run jquery script that check validation. Is it possible to POST the form/page only if all the fields are valid?</p>

答:
e.preventDefault() is what you need to stop form from submitting if it is not validated.

validateForm() function validates the form and returns true or false.
if it returns true then only form submits otherwise nothing happens.

<form id="myform" action="abc.php" method="post">
<input type="text" />
<input id="submit_btn" type="submit" value="submit">
</form>

```

Title: POST form when fields are valid

Body:
e.preventDefault() is what you need to stop form from submitting if it is not validated.

validateForm() function validates the form and returns true or false.
if it returns true then only form submits otherwise nothing happens.

<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>

<body>
<form id="myform" action="abc.php" method="post">
<input type="text" />
<input id="submit_btn" type="submit" value="submit">
</form>
</body>

<script>

$("document").ready(function(e){

$("#myform").submit(function(e){

var test = validateForm();
if(test){
 $("#myform").submit();
}
else{
 e.preventDefault();
}

});

function validateForm()
{
 //after checking everything returns true or false
 return false;
}

});

</script>

</html>


问:
Redirect to HTTPS with URI & without www
I have the same problem as the User in this thread. I basically want to redirect all http requests to https without www using htaccess.

I have implemented a solution to this problem and it does a pretty good job.

However, it does not redirect to the corresponding URI. If I visit my website on port 80 example.com/news I will be redirected to https://example.com/index.php which is basically the root page..

I really need your help guys, I totally have no clue about htaccess..

EDIT This is what my mod_rewrite looks like..

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{HTTPS} off
    # First rewrite to HTTPS:
    # Don't put www. here. If it is already there it will be included, if not
    # the subsequent rule will catch it.
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
</code>```

答: The issue probably is that you first rewrite to index.php and then make an external redirection. Try changing the order of the rules. Note that the L flag only terminates the current walk through the rule set. It is restarted after that. So first do the external direction to switch to the https protocol, then do the internal rewriting if that is corrected.

Body:
I have the same problem as the User in this thread. I basically want to redirect all http requests to https without www using htaccess.

I have implemented a solution to this problem and it does a pretty good job.

However, it does not redirect to the corresponding URI. If I visit my website on port 80 example.com/news I will be redirected to https://example.com/index.php which is basically the root page..

I really need your help guys, I totally have no clue about htaccess..

EDIT This is what my mod_rewrite looks like..

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{HTTPS} off
    # First rewrite to HTTPS:
    # Don't put www. here. If it is already there it will be included, if not
    # the subsequent rule will catch it.
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>


问:
Add ajax to rails no database form calculator
I trying to add ajax to rails no database form calculator. But it seams to not responding. It gives me 204 no content server answer. I trying to solve this issue, but i'm stuck. My JavaScript knowledge is very basic, so detailed response would be very helpful. Without ajax it works fine and pass all tests.

calculator controller

```<code>class InterestCalculatorController
  def new
    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js
    end

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number
    number_to_number(@first_0, @second_0)

 private

   def number_to_number(a = 0, b = 0)
    # If the first number is zero, it sends 0% answer. If the second number is zero
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end
  end
end
</code>```

index.js.erb

```<code>document.getElementById("answer_0").innerHTML = <%= @result_0 %>
</code>```

view index.html.erb

```<code><h1>Interest Calculator</h1>

<div id="interest_calculator_main">
  <div id="interest_calculator">
    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>
      <p>Сколько % составляет число</p>
      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>
      <p>от числа</p>
      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>
      <p>Number <%= @first_0 %> from number <%= @second_0 %> = <label id="answer_0">%</label></p>
    <% end %>
  </div>
</div>
</code>```

答:
Your form is being submitted to new action, but you have no template for that action (i.e new.js.erb), so you get a 204 No Content response, which should show the following in your server logs:

No template found for InterestCalculatorController#new

Rename index.js.erb to new.js.erb, and you will no longer get that error.

Also (not related to this error), you may wan't to change <%= @result_0 %> to "<%= @result_0 %>" in your now new.js.erb file:

```<code>document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"
</code>```

Otherwise your code will throw another error when @result_0 is set to "infinity".

Body:
I trying to add ajax to rails no database form calculator. But it seams to not responding. It gives me 204 no content server answer. I trying to solve this issue, but i'm stuck. My JavaScript knowledge is very basic, so detailed response would be very helpful. Without ajax it works fine and pass all tests.

calculator controller

class InterestCalculatorController
  def new
    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js
    end

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number
    number_to_number(@first_0, @second_0)

 private

   def number_to_number(a = 0, b = 0)
    # If the first number is zero, it sends 0% answer. If the second number is zero
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end
  end
end

index.js.erb

document.getElementById("answer_0").innerHTML = <%= @result_0 %>

view index.html.erb

Interest Calculator

    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>

Сколько % составляет число

      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>

от числа

      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>

Number <%= @first_0 %> from number <%= @second_0 %> = %

    <% end %>

Body:
Your form is being submitted to new action, but you have no template for that action (i.e new.js.erb), so you get a 204 No Content response, which should show the following in your server logs:

No template found for InterestCalculatorController#new

Rename index.js.erb to new.js.erb, and you will no longer get that error.

Also (not related to this error), you may wan't to change <%= @result_0 %> to "<%= @result_0 %>" in your now new.js.erb file:

document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"

Otherwise your code will throw another error when @result_0 is set to "infinity".


问:
Fast vector difference/similarity measures

I'm working on a project where I am using genetic algorithms to generate word lists which best describe a text.

I'm presently using cosine similarity to do it, but it has two flaws: it's far too slow for purpose and that if two vectors being compared are zeroes, it ends up with an artificially high similarity and a word vector that isn't very good.
Any suggestions for other measures which would be faster/take less notice of words that aren't there?
Thanks.

答:
Cosine similarity is dot-product over product-of-magnitudes, so minimizing number of dimensions is crucial.

To cull the herd a bit, you might want to apply stemming to collapse words with similar meaning into a single dimension, and toss out hapax legomena (words that only occur once in the corpus under consideration) from the dimension pool, since an algorithm isn't likely to be able to derive much useful information from them.

I'm not sure what would give rise to the zero vectors, though.  Can you give an example?

EDIT: So what you're after is to create a word list that is selective for a particular document or cluster?  In that case, you need some ways to eliminate low-selectivity words.

You might want to treat the most common words as stop words to further cull your dimension set and get back a little bit more performance.  Also, on the genetic algorithm side, your fitness function needs to penalize word lists that match documents outside of the target cluster, not just reward those that match documents within the cluster, so your word list doesn't get cluttered with terms that are merely frequent rather than selective.

If you need better semantic selectivity even after tuning the fitness function., you might want to consider using orthogonal sparse bigrams instead of individual words.  I've no idea what it'll do in terms of number of dimensions, though, because while there will be O(kn2) distinct terms instead of n, a lot more of them will be hapaxes.  This may cause a problem if you need individual words instead of OSBs in your term lists though.


问:
Meteor JS ReactMeteorData - CreateContainer - Super expression must either be null or a function
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

```<code>Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)
</code>```

AppContainer.jsx:

```<code>import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);
</code>```

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;
</code>```

答: You might be missing super() in the App Component.

Body:
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)

AppContainer.jsx:

import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;

ContentLicense: CC BY-SA 4.0


问:
Unable to include QTimer
I am a beginner at programming and I am unable to include QTimer class of Qt 5.6 in my project. I reinstalled qt twice but its not working yet.

答:
Did you add QT += core on your .pro file? And #include < QTimer> in your source file.

Include files get available when you add corresponding modules in your pro files. Required modules are documented on top of the class documentation you want to use.

http://doc.qt.io/qt-5/qtmodules.html

Title: Unable to include QTimer


问:
JavaClassStatics / StaticClass, how to use an object of that type?
I am having a really hard time trying to use such object.

In my case it is holding an static enum from:

```<code>obj = new ScriptEngineManager().getEngineByMimeType("text/javascript").
eval("Java.type('"+((Class<Enum>)enumClass).getName()+"');");
</code>```

now I need to be able to do something with obj from within java, not only from within a bind in javascript (where it would work easily).

Can I cast it in some way to access the enum reference it is holding from within java? I would like to access the .values() of such enum but I dont know if it is possible that way.

答:
for enums, was quite simple, using javascript itself:

eval("Java.type('"+((Class<Enum>)enumClass).getName()+"').values();");

I couldnt find a way to use the StaticClass object, but at least for enums it will be easy now.

OwnerDisplayName: Aquarius Power

Body:
I am having a really hard time trying to use such object.

In my case it is holding an static enum from:

obj = new ScriptEngineManager().getEngineByMimeType("text/javascript").
eval("Java.type('"+((Class<Enum>)enumClass).getName()+"');");

now I need to be able to do something with obj from within java, not only from within a bind in javascript (where it would work easily).

Can I cast it in some way to access the enum reference it is holding from within java? I would like to access the .values() of such enum but I dont know if it is possible that way.


问:
C# how to change object attributes dynamically
am reading this tutorial
 http://chalaki.com/how-to-program-msagl-glee-to-create-hierarchical-graph-layouts/519/

using the code sample.

am trying to make the attributes dynamic (i want to be able to load the attributes from a database later)

i have tried

```<code>string dColor = "Red";
string dShape = "Diamond";

Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
n2.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.dColor;
n2.Attr.Shape = Microsoft.Glee.Drawing.Shape.dShape;
</code>```

but its not working, how do i do this or even read about doing this dynamically?

[ANSWER]
Am not sure if this is the best way,but it works.

--For Colors i did

```<code>using mColor = Microsoft.Msagl.Drawing.Color;
using sColor = System.Drawing.Color;

sColor c = sColor.FromName("Red");
graph.FindNode("test1").Attr.FillColor = new mColor(c.A,c.R,c.G,c.B);
</code>```

--For the shape i did

```<code> graph.FindNode("test1").Attr.Shape = (Shape)
 (int)Enum.Parse(typeof(Shape),"Diamond");
</code>```

where "test1","diamond" and "Red" values come from the database.

答:
A Color is not a string.

```<code>Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
var someColor = System.Drawing.Color.Red;
n2.Attr.Fillcolor = someColor;
</code>```

If you will be storing the colors in the database, you can use one of the static methods on Color:

```<code>string dColor = "Red";
n2.Attr.Fillcolor = Color.FromName(dColor);
</code>```

If you will not stick to the named colors, there is also Color.FromArgb(int);

EDIT

Looks like they are using a different Color class from the one in System.Drawing here. I found an example on the MSDN forums:

```<code>string color = "Red";
var cvtColor = new ColorConverter();
var sysColor = cvtColor.ConvertFromString(color);
n2.Attr.Fillcolor = new Microsoft.Msagl.Drawing.Color(sysColor.R, sysColor.B, sysColor.G);
</code>```

There is some example code on GitHub:

```<code>n2.Attr.Fillcolor = Microsoft.Msagl.Drawing.Color.Magenta;
</code>```

Body:
am reading this tutorial
 http://chalaki.com/how-to-program-msagl-glee-to-create-hierarchical-graph-layouts/519/

using the code sample.

am trying to make the attributes dynamic (i want to be able to load the attributes from a database later)

i have tried

string dColor = "Red";
string dShape = "Diamond";

Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
n2.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.dColor;
n2.Attr.Shape = Microsoft.Glee.Drawing.Shape.dShape;

but its not working, how do i do this or even read about doing this dynamically?

[ANSWER]
Am not sure if this is the best way,but it works.

--For Colors i did

using mColor = Microsoft.Msagl.Drawing.Color;
using sColor = System.Drawing.Color;

sColor c = sColor.FromName("Red");
graph.FindNode("test1").Attr.FillColor = new mColor(c.A,c.R,c.G,c.B);

--For the shape i did

 graph.FindNode("test1").Attr.Shape = (Shape)
 (int)Enum.Parse(typeof(Shape),"Diamond");

where "test1","diamond" and "Red" values come from the database.

Body:
A Color is not a string.

Microsoft.Glee.Drawing.Node n2 = graph.FindNode(strNode2);
var someColor = System.Drawing.Color.Red;
n2.Attr.Fillcolor = someColor;

If you will be storing the colors in the database, you can use one of the static methods on Color:

string dColor = "Red";
n2.Attr.Fillcolor = Color.FromName(dColor);

If you will not stick to the named colors, there is also Color.FromArgb(int);

EDIT

Looks like they are using a different Color class from the one in System.Drawing here. I found an example on the MSDN forums:

string color = "Red";
var cvtColor = new ColorConverter();
var sysColor = cvtColor.ConvertFromString(color);
n2.Attr.Fillcolor = new Microsoft.Msagl.Drawing.Color(sysColor.R, sysColor.B, sysColor.G);

There is some example code on GitHub:

n2.Attr.Fillcolor = Microsoft.Msagl.Drawing.Color.Magenta;


问:
jQuery not working in chrome but working in Firefox
I can't use jQuery in Chrome but it works in Firefox. What is the problem here?

```<code>$(document).ready(function() {
  console.log( "ready!" );
  $('.test').click(function () {
    console.log('test');
  });
});
</code>```

It does log "ready" but it doesn't log "test". In firefox it works..

CDN i use:

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

Element:

```<code><button type="button" class="btn btn-success test">Test</button>
</code>```

答: I've solved my problem by just reinstalling mac OSX. My MacBook was a bit buggy anyway and this solved the problem. Thanks for everyone who was thinking with me and sorry i've posted a post like this.</p>

Body:
I can't use jQuery in Chrome but it works in Firefox. What is the problem here?

$(document).ready(function() {
  console.log( "ready!" );
  $('.test').click(function () {
    console.log('test');
  });
});

It does log "ready" but it doesn't log "test". In firefox it works..

CDN i use:

Element:

<button type="button" class="btn btn-success test">Test</button>


问:
Is My Page Being Loaded from the Browser Cache?
I have a "new items" badge on a page that I want to update immediately the page is loaded from the cache (i.e. when hitting "Back" or "Forward" to return to this page). What is the best way to accomplish this?

The setup is pretty simple. The layout for the app looks for new items every 8 seconds, and updates the badge + list of items accordingly.

```<code>$(function() {
    setInterval( App.pollForNewItems, 8000 );
});
</code>```

When someone navigates away from this page to look at the details of an item, a lot can happen. Things are "new" until any user has viewed them, and the app will likely have several user using it simultaneously (the kind of workflow used for a call center or support tickets).

To make sure that the badges are always up to date, I have:

```<code>$(window).bind('focus load', function ( event ) {
    App.pollForNewItems();
});
</code>```

..And though this works, polling for new items on 'load' is only useful when the page is loaded from the cache. Is there a reliable cross-browser way to tell if a page is being loaded from the cache?

答:
You can ask the web browser to not cache the page.  Try these HTTP headers:

```<code>Cache-control: no-cache
Cache-control: no-store
Pragma: no-cache
Expires: 0
</code>```

Particularly, Cache-control: no-store is interesting because it tells the browser to not store the page in memory at all which prevents a stale page being loaded when you hit the back/forward button.

If you do this instead, you don't have to poll for data on page load.

Body:
I have a "new items" badge on a page that I want to update immediately the page is loaded from the cache (i.e. when hitting "Back" or "Forward" to return to this page). What is the best way to accomplish this?

The setup is pretty simple. The layout for the app looks for new items every 8 seconds, and updates the badge + list of items accordingly.

$(function() {
    setInterval( App.pollForNewItems, 8000 );
});

When someone navigates away from this page to look at the details of an item, a lot can happen. Things are "new" until any user has viewed them, and the app will likely have several user using it simultaneously (the kind of workflow used for a call center or support tickets).

To make sure that the badges are always up to date, I have:

$(window).bind('focus load', function ( event ) {
    App.pollForNewItems();
});

..And though this works, polling for new items on 'load' is only useful when the page is loaded from the cache. Is there a reliable cross-browser way to tell if a page is being loaded from the cache?

Body:
You can ask the web browser to not cache the page.  Try these HTTP headers:

Cache-control: no-cache
Cache-control: no-store
Pragma: no-cache
Expires: 0

Particularly, Cache-control: no-store is interesting because it tells the browser to not store the page in memory at all which prevents a stale page being loaded when you hit the back/forward button.

If you do this instead, you don't have to poll for data on page load.


问:
Script to output information of foreign keys
I would like to know the detail about  my foreign keys.

I tried this

```<code>SELECT * FROM sys.foreign_keys;
</code>```

But I need more than the information I can get now.
Is there a way to know the columns they are refering to by using scripts like this ?

答:
To get list of all tables and their column names, use the next code:-

```<code>select
    t.name as TableWithForeignKey,
    c.name as ForeignKeyColumn
from
    sys.foreign_key_columns as fk
inner join
    sys.tables as t on fk.parent_object_id = t.object_id
inner join
    sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
    fk.referenced_object_id in (select object_id
                               from sys.tables )
order by
    TableWithForeignKey
</code>```

Reference:- How can I list all foreign keys referencing a given table in SQL Server?

Body:
I would like to know the detail about  my foreign keys.

I tried this

SELECT * FROM sys.foreign_keys;

But I need more than the information I can get now.
Is there a way to know the columns they are refering to by using scripts like this ?

Body:
To get list of all tables and their column names, use the next code:-

select
    t.name as TableWithForeignKey,
    c.name as ForeignKeyColumn
from
    sys.foreign_key_columns as fk
inner join
    sys.tables as t on fk.parent_object_id = t.object_id
inner join
    sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
    fk.referenced_object_id in (select object_id
                               from sys.tables )
order by
    TableWithForeignKey

Reference:- How can I list all foreign keys referencing a given table in SQL Server?


问:
How to show or hide an ionic field/component at runtime depending on the chosen option on ion-select
In the app I'm making I have a situation where I need to present to the user some content depending on the option chosen on a ion-select in the same page. The bellow snipet is a illustration of the actual list:

```<code><ion-item no-lines>
    <ion-label>Options</ion-label>
    <ion-select formControlName="option">
        <ion-option *ngFor="let option of options">
            {{ option }}
        </ion-option>
    </ion-select>
</ion-item>
</code>```

In this case, if one of the options, say 'option B', is chosen, then I want another list of options to be presented to the user to choose:

```<code><ion-item no-lines>
    <ion-label>Sub options of B</ion-label>
    <ion-select formControlName="subOptionOfB">
        <ion-option *ngFor="let subOption of subOptions">
            {{ subOption }}
        </ion-option>
    </ion-select>
</ion-item>
</code>```

In this case scenario, only B has the 'power' to trigger this change on the page, but here is the catch: If the user choose B, the sub-list should appear; if it chooses another option, it should disappear or, if it isn't render yet, not cause any reaction on the page, given it a dynamically feeling.

In my search I have encounter similar problems that were resolved with ngIf or hidden attributes. I have tried those but with no success: with ngIf only, the component still shows when should disappear; with hidden attribute only, it disappears only when rendering, after that nothing changes (if the component were rendered as 'invisible', than stays that way and do not show anymore; if it were rendered as 'visible', than stays that way and do not disappears anymore); using both generate the same problems as when using the hidden attribute only.

I have a feeling that this has something to do with asynchronous requests, since when I was studying Java a few months back I learn something similar when making web pages. Using asynchronous requests I could put and/or take out content depending on the situation without the need to refresh the page (which is exactly what I need), but I could not wrap my head around Observables and such yet.

Could someone please tell me what I need to do or, at least, what I'm doing wrong?

[EDIT-1]: I don't know if this changes anything, but I'm using formControlName instead [(ngModel)] for data binding.

Both lists are on the same level and not nested. Each one in their respective ion-item.

I'm using Ionic 2 with Angular 2 and TypeScript.

答:
It's just a simple case. Try and adjust your code to fit the snippets i present below.

in your html page

```<code> ...
<ion-item no-lines>
    <ion-label>Options</ion-label>
    <ion-select formControlName="option" (ionChange)="onSelectChangeOption()" submitText="Ok" cancelText="Cancel">
        <ion-option *ngFor="let option of options">
            {{ option }}
        </ion-option>
    </ion-select>
</ion-item>

<ion-item no-lines  *ngIf="showSubOptionOfB">
    <ion-label>Sub options of B</ion-label>
    <ion-select formControlName="subOptionOfB">
        <ion-option *ngFor="let subOption of subOptions">
            {{ subOption }}
        </ion-option>
    </ion-select>
</ion-item>
...
</code>```

then for your typescript page

```<code>....

  showSubOptionOfB:boolean = false; //default

  onSelectChangeOption() {

    //grab form value
    let optionValue = this.yourForm.get('option').value;

    //show subOptions
    if(optionValue == "B"){
        this.showSubOptionOfB = true;
    }
    else{
        this.showSubOptionOfB = false;
    }
      }

  //say you declared your formgroup as yourForm
  public yourForm = this.formBuilder.group({
    option: ["", Validators.required],
    subOptionOfB: ["", Validators.required],
    ...
    });

  ...
</code>```

Body:
In the app I'm making I have a situation where I need to present to the user some content depending on the option chosen on a ion-select in the same page. The bellow snipet is a illustration of the actual list:

<ion-item no-lines>
    <ion-label>Options</ion-label>
    <ion-select formControlName="option">
        <ion-option *ngFor="let option of options">
            {{ option }}
        </ion-option>
    </ion-select>
</ion-item>

In this case, if one of the options, say 'option B', is chosen, then I want another list of options to be presented to the user to choose:

<ion-item no-lines>
    <ion-label>Sub options of B</ion-label>
    <ion-select formControlName="subOptionOfB">
        <ion-option *ngFor="let subOption of subOptions">
            {{ subOption }}
        </ion-option>
    </ion-select>
</ion-item>

In this case scenario, only B has the 'power' to trigger this change on the page, but here is the catch: If the user choose B, the sub-list should appear; if it chooses another option, it should disappear or, if it isn't render yet, not cause any reaction on the page, given it a dynamically feeling.

In my search I have encounter similar problems that were resolved with ngIf or hidden attributes. I have tried those but with no success: with ngIf only, the component still shows when should disappear; with hidden attribute only, it disappears only when rendering, after that nothing changes (if the component were rendered as 'invisible', than stays that way and do not show anymore; if it were rendered as 'visible', than stays that way and do not disappears anymore); using both generate the same problems as when using the hidden attribute only.

I have a feeling that this has something to do with asynchronous requests, since when I was studying Java a few months back I learn something similar when making web pages. Using asynchronous requests I could put and/or take out content depending on the situation without the need to refresh the page (which is exactly what I need), but I could not wrap my head around Observables and such yet.

Could someone please tell me what I need to do or, at least, what I'm doing wrong?

[EDIT-1]: I don't know if this changes anything, but I'm using formControlName instead [(ngModel)] for data binding.

Both lists are on the same level and not nested. Each one in their respective ion-item.

I'm using Ionic 2 with Angular 2 and TypeScript.

Body:
It's just a simple case. Try and adjust your code to fit the snippets i present below.

in your html page

 ...
<ion-item no-lines>
    <ion-label>Options</ion-label>
    <ion-select formControlName="option" (ionChange)="onSelectChangeOption()" submitText="Ok" cancelText="Cancel">
        <ion-option *ngFor="let option of options">
            {{ option }}
        </ion-option>
    </ion-select>
</ion-item>

<ion-item no-lines  *ngIf="showSubOptionOfB">
    <ion-label>Sub options of B</ion-label>
    <ion-select formControlName="subOptionOfB">
        <ion-option *ngFor="let subOption of subOptions">
            {{ subOption }}
        </ion-option>
    </ion-select>
</ion-item>
...

then for your typescript page

....

  showSubOptionOfB:boolean = false; //default

  onSelectChangeOption() {

    //grab form value
    let optionValue = this.yourForm.get('option').value;

    //show subOptions
    if(optionValue == "B"){
        this.showSubOptionOfB = true;
    }
    else{
        this.showSubOptionOfB = false;
    }
      }

  //say you declared your formgroup as yourForm
  public yourForm = this.formBuilder.group({
    option: ["", Validators.required],
    subOptionOfB: ["", Validators.required],
    ...
    });

  ...


问:
Google Play console reporting crashes from unreleased applications
I would like to share a situation I am facing analysing the new features at Google Play console and try to find a solution for it.

As many of you may already know, Google has released updates at Google Play console and introduced Android vitals. One of the good particularities is that now the session ANRs & Crashes shows all ANRs & crashes collected from Android devices whose users have opted in to automatically share usage and diagnostics data (during phone first setup).

However, I am seeing crash reports from unreleased applications. I mean, from a developer version that hasn't been published yet. Moreover, this crash report came from an application signed with an android-debug key, not my production key. I have looked into the available documentation but I couldn't found details on the filtering for these reports.

It seems harmful and wrong to me using any income data without validating signing as anyone can simply write a short peace of code and start flooding a specific application package name with tons of dummy stacktraces.

Do you know if this is the normal behavior for this new tool ?

答:
I also faced the same issue.

It shows Crash reports when I go to All applications ->  -> Dashboard -> Crashes

But if I go directly to Android Vitals -> ANRs & crashes it doesnt show anything.

Anyway for the first case you can click on 'View details' and select 'Hide' from dropdown menu for each crash type reported.

This is just a temporary fix , but I think Google has to provide proper fix for it.


问:
Error : screenSize|smallestScreenSize android studio Target SDK 23
I'm trying to integrate HeyZap ads into my app but I keep getting this error on build : Error:screenSize|smallestScreenSize).

I've searched on it and I found that it's target sdk error which should be at least 13 but here I'm using SDK 23 .

Here is my Manifest file :

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name="com.celebria.MyApplication">

        <activity
            android:name=".ActivitySplash"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Tutorial"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityLogin"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <receiver
            android:name=".AlarmReceiver"
            android:enabled="true"
            android:process=":remote"
            android:exported="true"/>
        <receiver
            android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

        <service
            android:name=".DownloadService"
            android:enabled="true"
            android:stopWithTask="false"
            android:exported="true"/>

        <activity
            android:name=".Home"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityCreateAccount"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityActiveTrivia"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityMatchUp"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityQuestionAnswer"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityWinner"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity android:name=".CreateAccount"
            android:theme="@style/AppThemeLogin"/>

        <activity android:name=".ActivityForgotPassword"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>

        <activity android:name="com.heyzap.sdk.ads.HeyzapIncentivizedActivity" android:configChanges="orientation|screenSize" android:theme="@android:style/Theme.Translucent" android:hardwareAccelerated="true" />
        <activity android:name="com.heyzap.sdk.ads.HeyzapInterstitialActivity" android:configChanges="orientation|screenSize" android:theme="@android:style/Theme.Translucent" />
        <activity android:name="com.heyzap.sdk.ads.MediationTestActivity" />
        <activity android:name="com.fyber.ads.ofw.OfferWallUnityActivity" android:configChanges="orientation" />
        <service android:name="com.fyber.cache.CacheVideoDownloadService" android:exported="false" />
        <meta-data android:name="FYBVideoPlayerOptionCloseButtonDelay" android:value="-1" />

    </application>

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

<p>Here is my build.gradle file : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.celebria"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {

    mavenCentral()

    maven {
        name "Fyber's maven repo"
        url "https://fyber.bintray.com/maven"
    }
    flatDir {
        dirs "libs"
    }

}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile'com.google.android.gms:play-services-location:10.0.1'
    compile'com.google.android.gms:play-services-ads:10.0.1'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.squareup.picasso:picasso:2.5.0'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'jp.wasabeef:blurry:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'me.relex:circleindicator:1.2.2@aar'
    compile(name:'heyzap-unified-platform-10.3.0', ext:'aar')
}</code>```

This is a picture of the error :

and this is the link I've been following : https://developers.heyzap.com/docs/android_sdk_setup_and_requirements

答:
```<code>android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
</code>```

screenSize & smallestScreenSize attributes are not available in SDK 10.They are available from API level 13.

For more details:
http://developer.android.com/guide/topics/manifest/activity-element.html#config

Body:
I'm trying to integrate HeyZap ads into my app but I keep getting this error on build : Error:screenSize|smallestScreenSize).

I've searched on it and I found that it's target sdk error which should be at least 13 but here I'm using SDK 23 .

Here is my Manifest file :

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name="com.celebria.MyApplication">

        <activity
            android:name=".ActivitySplash"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Tutorial"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityLogin"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <receiver
            android:name=".AlarmReceiver"
            android:enabled="true"
            android:process=":remote"
            android:exported="true"/>
        <receiver
            android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

        <service
            android:name=".DownloadService"
            android:enabled="true"
            android:stopWithTask="false"
            android:exported="true"/>

        <activity
            android:name=".Home"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityCreateAccount"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityActiveTrivia"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityMatchUp"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityQuestionAnswer"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name=".ActivityWinner"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <activity android:name=".CreateAccount"
            android:theme="@style/AppThemeLogin"/>

        <activity android:name=".ActivityForgotPassword"
            android:theme="@style/AppThemeLogin"
            android:windowSoftInputMode="adjustPan" />

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>

        <activity android:name="com.heyzap.sdk.ads.HeyzapIncentivizedActivity" android:configChanges="orientation|screenSize" android:theme="@android:style/Theme.Translucent" android:hardwareAccelerated="true" />
        <activity android:name="com.heyzap.sdk.ads.HeyzapInterstitialActivity" android:configChanges="orientation|screenSize" android:theme="@android:style/Theme.Translucent" />
        <activity android:name="com.heyzap.sdk.ads.MediationTestActivity" />
        <activity android:name="com.fyber.ads.ofw.OfferWallUnityActivity" android:configChanges="orientation" />
        <service android:name="com.fyber.cache.CacheVideoDownloadService" android:exported="false" />
        <meta-data android:name="FYBVideoPlayerOptionCloseButtonDelay" android:value="-1" />

    </application>

</manifest>

Here is my build.gradle file :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.celebria"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {

    mavenCentral()

    maven {
        name "Fyber's maven repo"
        url "https://fyber.bintray.com/maven"
    }
    flatDir {
        dirs "libs"
    }

}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile'com.google.android.gms:play-services-location:10.0.1'
    compile'com.google.android.gms:play-services-ads:10.0.1'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.squareup.picasso:picasso:2.5.0'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'jp.wasabeef:blurry:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'me.relex:circleindicator:1.2.2@aar'
    compile(name:'heyzap-unified-platform-10.3.0', ext:'aar')
}

This is a picture of the error :

and this is the link I've been following : https://developers.heyzap.com/docs/android_sdk_setup_and_requirements

Body:
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

screenSize & smallestScreenSize attributes are not available in SDK 10.They are available from API level 13.

For more details:
http://developer.android.com/guide/topics/manifest/activity-element.html#config


问:
Scatter plotting pandas DataFrame with categorically labeled rows/columns
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

```<code>import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4
</code>```

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

```<code>flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()
</code>```

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

答:
It's not exactly what you were asking for, but it helps to visualize values in a similar way:

```<code>import seaborn as sns

sns.heatmap(df[::-1], annot=True)
</code>```

Result:

Body:
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

Body:
It's not exactly what you were asking for, but it helps to visualize values in a similar way:

import seaborn as sns

sns.heatmap(df[::-1], annot=True)

Result:


问:
VBA MS-WORD load all the yellow highlighted texts in variable array
I would like to run a macro that would extract all the yellow highlighted text of the document and pass all those highlighted text into an array variable.

I found this link: How to perform a selective extraction of text highlighted in yellow from an MS Word document?

but the solution proposed does not work and is not exactly the same.

So basically the logic would be:

look up all the document
count how many highlighted pices of text there are

```<code>Dim CountYellow as integer
Dim HltText as variant
'i dont know how to do this next:
countyellow= number of highlighted texts
redim HltText(1 to countyellow)
for i=1 to countyellow
'I dont know how to do this next:
FIND THE NEXT YELLOW HIGHLIGHTED TEXT
HltText(i)= HIGHLIGHTED TEXT
next i
</code>```

Thanks a lot

PS; after I re-read my question I would like to add here for clarification. the text would be something like this:

Lorem ipsum dolor sit amet, THIS TEXT IS YELLOW HIGHLIGHTED consectetur adipiscing elit. Curabitur iaculis vehicula arcu, accumsan facilisis eros sagittis sed. Duis sit amet diam sit amet magna pharetra molestie. Cras sagittis lacus non tortor accumsan accumsan commodo at mi. Ut ipsum nunc, suscipit at elit quis, auctor rutrum diam. Mauris vel dictum dolor. Quisque THIS SECOND TEXT IS YELLOW HIGHLIGHTED porta a purus in sodales. Pellentesque accumsan ac tellus a molestie. Duis tempor sapien enim, eu THIS ANOTHER TEXT AS WELL IS HIGHLIGHTED sollicitudin turpis volutpat sit amet. Ut libero dui, dapibus in vulputate vitae, aliquet vel turpis. Donec nec congue est. In enim turpis, scelerisque id condimentum ac, porta quis tellus.

where then:
HltText(1)="THIS TEXT IS YELLOW HIGHLIGHTED"
HltText(2)="HIS SECOND TEXT IS YELLOW HIGHLIGHTED"
etc...

答:
I would like to post another alternative solution not involving FIND using characters.

```<code>Dim YellowWord(1 To 100) As String
Dim i As Integer, j As Integer, k As Integer  'counter
i = 0

With Selection
.HomeKey Unit:=wdStory
While (ActiveDocument.Range.End - 1) > .Range.End
strText = ""
' mark first character of the current word
.MoveRight Unit:=WdUnits.wdCharacter, Count:=1, Extend:=wdExtend
If .Characters(1).FormattedText.HighlightColorIndex = m_lngFindColor Then
Do
' save charcater
strText = strText & .Text
' next character
.MoveRight Unit:=WdUnits.wdCharacter, Count:=1, Extend:=wdMove
Loop While .Characters(1).FormattedText.HighlightColorIndex = m_lngFindColor And ((ActiveDocument.Range.End - 1) > Selection.Range.End)
Debug.Print strText
i = i + 1
YellowWord(i) = strText
Debug.Print "YellowWord(" & i & ")= "; yellowWord(i)
End If
.Move WdUnits.wdWord, 1
Wend
End With
</code>```

works wonderfuly.

take care that the user do not use any other yellow. I suggest to include a button for highlight in the specific vbyellow color. You know what I mean.

Body:
I would like to run a macro that would extract all the yellow highlighted text of the document and pass all those highlighted text into an array variable.

I found this link: How to perform a selective extraction of text highlighted in yellow from an MS Word document?

but the solution proposed does not work and is not exactly the same.

So basically the logic would be:

look up all the document
count how many highlighted pices of text there are

Dim CountYellow as integer
Dim HltText as variant
'i dont know how to do this next:
countyellow= number of highlighted texts
redim HltText(1 to countyellow)
for i=1 to countyellow
'I dont know how to do this next:
FIND THE NEXT YELLOW HIGHLIGHTED TEXT
HltText(i)= HIGHLIGHTED TEXT
next i

Thanks a lot

PS; after I re-read my question I would like to add here for clarification. the text would be something like this:

Lorem ipsum dolor sit amet, THIS TEXT IS YELLOW HIGHLIGHTED consectetur adipiscing elit. Curabitur iaculis vehicula arcu, accumsan facilisis eros sagittis sed. Duis sit amet diam sit amet magna pharetra molestie. Cras sagittis lacus non tortor accumsan accumsan commodo at mi. Ut ipsum nunc, suscipit at elit quis, auctor rutrum diam. Mauris vel dictum dolor. Quisque THIS SECOND TEXT IS YELLOW HIGHLIGHTED porta a purus in sodales. Pellentesque accumsan ac tellus a molestie. Duis tempor sapien enim, eu THIS ANOTHER TEXT AS WELL IS HIGHLIGHTED sollicitudin turpis volutpat sit amet. Ut libero dui, dapibus in vulputate vitae, aliquet vel turpis. Donec nec congue est. In enim turpis, scelerisque id condimentum ac, porta quis tellus.

where then:
HltText(1)="THIS TEXT IS YELLOW HIGHLIGHTED"
HltText(2)="HIS SECOND TEXT IS YELLOW HIGHLIGHTED"
etc...

Body:
I would like to post another alternative solution not involving FIND using characters.

Dim YellowWord(1 To 100) As String
Dim i As Integer, j As Integer, k As Integer  'counter
i = 0

With Selection
.HomeKey Unit:=wdStory
While (ActiveDocument.Range.End - 1) > .Range.End
strText = ""
' mark first character of the current word
.MoveRight Unit:=WdUnits.wdCharacter, Count:=1, Extend:=wdExtend
If .Characters(1).FormattedText.HighlightColorIndex = m_lngFindColor Then
Do
' save charcater
strText = strText & .Text
' next character
.MoveRight Unit:=WdUnits.wdCharacter, Count:=1, Extend:=wdMove
Loop While .Characters(1).FormattedText.HighlightColorIndex = m_lngFindColor And ((ActiveDocument.Range.End - 1) > Selection.Range.End)
Debug.Print strText
i = i + 1
YellowWord(i) = strText
Debug.Print "YellowWord(" & i & ")= "; yellowWord(i)
End If
.Move WdUnits.wdWord, 1
Wend
End With

works wonderfuly.

take care that the user do not use any other yellow. I suggest to include a button for highlight in the specific vbyellow color. You know what I mean.


问:
Optimizing generating random number in Matlab
I have a two 1 by 10^3 matrix which its elements change in each step of the loop of simulation. To find a new element in each for loop step, I need 2*1000 Gaussian random numbers. the number of loop steps is equal to 10^5. Which method is less time-consuming in this case?

creating two 10^5 by 1000 random matrix before for loop and call them inside the loop.

creating two 1 by 10^3 random matrix in each step of the loop?

答:
Here is a little code to answer your question:

```<code>function rnd_time_test
rnd_test = @(n) randn(2,n,1000);
N = 1e5;
one_time = timeit(@() rnd_test(N))
loop_time = timeit(@() rnd_test_loop(N))

    function R = rnd_test_loop(n)
        for k = 1:n
            R = randn(2,1000);
        end
    end
end
</code>```

and the result:

```<code>one_time =
      2.245
loop_time =
      1.6311
</code>```

So, on my machine, using a loop is faster.

Body:
Here is a little code to answer your question:

function rnd_time_test
rnd_test = @(n) randn(2,n,1000);
N = 1e5;
one_time = timeit(@() rnd_test(N))
loop_time = timeit(@() rnd_test_loop(N))

    function R = rnd_test_loop(n)
        for k = 1:n
            R = randn(2,1000);
        end
    end
end

and the result:

one_time =
      2.245
loop_time =
      1.6311

So, on my machine, using a loop is faster.


问:
You have to be inside an Angular CLI project in order to use the serve command. Error on running a dynamic web project
I am trying to make a dynamic web project using angular 2. I did so by creating dynamic web project in eclipse EE neon. After that I right clicked on project -> show in-> terminal. After this I ran ng serve command but below error is coming.

You have to be inside an Angular CLI project in order to use the serve command

Angular cli is installed at global level(C drive). My workspace is in D drive.

I also tried to install angular CLI at Drive.

Kindly help me in this.

答:
You seems not have installed npm modules in your project or in that directory location from where you are getting this error.
Run npm install from command line on the same directory location, and then try ng build or Ng serve ..


问:
C++: Is a pointer as function's parameter really copied?
According to the answer https://stackoverflow.com/a/11842442/5835947, if you code like this, function parameter Bubble * targetBubble will be copied inside the function.

```<code>bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}
</code>```

However, I made a test, finding that a pointer as function parameter will be the same as the outside one, until I changed it's value:

```<code>// c++ test ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "c++ test ConsoleApplication2.h"
using namespace std;
#include<iostream>

int main()
{
    int a= 1;
    int* pointerOfA = &a;

    cout << "address of pointer is" << pointerOfA << endl;
    cout << *pointerOfA << endl;
    func(pointerOfA);
    cout << *pointerOfA << endl;

}

void func(int *pointer)
{
    cout << "address of pointer is " << pointer  <<" it's the same as the pointer outside!"<<endl;

    int b = 2;
    pointer = &b;
    cout << "address of pointer is" << pointer <<" it's changed!"<< endl;

    cout << *pointer<<endl;

}
</code>```

Output is below:

```<code>address of pointer is0093FEB4
1
address of pointer is 0093FEB4 it's the same as the pointer outside!
address of pointer is0093FDC4 it's changed!
2
1
</code>```

So, the truth is that, a pointer as function parameter will not be copied, until it's changed, right? Or am I missing something here?

答: Pointers are used because instead of copying entire object which may be costly it will copy/pass to function as arguments the address of the object. When you are passing the pointer to the function and making changes to it outside the function or in the function it will modify the same object. You are printing the value of the pointing object by doing *p. If you want to check if pointer variable is copied then output p and check which may be different.

Body:
According to the answer https://stackoverflow.com/a/11842442/5835947, if you code like this, function parameter Bubble * targetBubble will be copied inside the function.

bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}

However, I made a test, finding that a pointer as function parameter will be the same as the outside one, until I changed it's value:

// c++ test ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "c++ test ConsoleApplication2.h"
using namespace std;
#include<iostream>

int main()
{
    int a= 1;
    int* pointerOfA = &a;

    cout << "address of pointer is" << pointerOfA << endl;
    cout << *pointerOfA << endl;
    func(pointerOfA);
    cout << *pointerOfA << endl;

}

void func(int *pointer)
{
    cout << "address of pointer is " << pointer  <<" it's the same as the pointer outside!"<<endl;

    int b = 2;
    pointer = &b;
    cout << "address of pointer is" << pointer <<" it's changed!"<< endl;

    cout << *pointer<<endl;

}

Output is below:

address of pointer is0093FEB4
1
address of pointer is 0093FEB4 it's the same as the pointer outside!
address of pointer is0093FDC4 it's changed!
2
1

So, the truth is that, a pointer as function parameter will not be copied, until it's changed, right? Or am I missing something here?


问:
Community edition UML tool
Can anyone suggest me a free or community edition UML tool for C++. Any UML tool is fine but I need something that can generate class templates for c++. Why I need to generate class codes is because, if in future if I make some changes to my Class diagram it should easily reflect in my code. </p>

答: Try JUDE community - now known as Astah.</p>

Title: Community edition UML tool


问:
Copy POJO content from one bean to another
I have few Pojos in different packages, each POJO contains set of the another pojo from the same package. I need to copy all items with the same name from Package B Pojos to objects in Package A.

Eaxmple:

```<code>package com.vanilla.packageA;

public class Student{

    private String firstName;
    private String lastName;
    private Set<Course> course;

    //getters and setters ommited

}
</code>```

```<code>package com.vanilla.packageA;

    public class Course{
    private String courseName;
    private String courseDescription;

    //seters and getters
}
</code>```

```<code>package com.vanilla.packageB;

public class Student{

    private String firstName;
    private String lastName;
    private Address address;
    private Set<Course> course;
    Private Date birtday;

    //getters and setters ommited

}
</code>```

```<code>package com.vanilla.packageB;

public class Course{
    private String courseName;
    private String courseDescription;
    private <Lecturer> lecturer;
    private Integer hours;

    //seters and getters
}
</code>```

I want to copy recursively all items from PackageB classes to packageA classes which exists in PaCkageB and shares the same name.

Updates:

Guys, I understand that that this is stupid question, but I need to maintain this code, now the code is written in the way that they have to call 50 getters and setter, or calling constructor with 50 parameters.
Unfortunately,  I can't use the same object and I need to copy it, but I must find more "elegant" way to copy tese beans.

答:
Copying fields values are a need I almost every project, for example for do the clone(). I also think that for accomplish some goals isn't necessary import .jars for using only one function. I would like share some little code in which I was working, there are some things that I left in the inkwell but in general it do the work. In this case I use reflection.

```<code>public class ObjectCopyTools {

static String[] bases = new String[] {"byte", "short", "int", "long", "float", "double", "char", "boolean"};
static String[] equivalents = new String[] {"Byte", "Short", "Integer", "Long", "Float", "Double", "Character", "Boolean"};

static {

}

private static boolean areEquivalents(String type1, String type2){
    for (int i = 0; i < bases.length; i++) {
        if((type1.equals(bases[i]) && type2.equals(equivalents[i]))
                || (type2.equals(bases[i]) && type1.equals(equivalents[i]))){
            return true;
        }
    }
    return false;
}

public static <T extends Object, Y extends Object> Y deepReflectionObjectCopy(T origin, Class<Y> resultClass) {
    Class<? extends Object> origClass = origin.getClass();
    Y resultObject = null;
    for (Constructor<?> constructor : resultClass.getConstructors()) {
        if (constructor.getParameterCount() == 0) {
            try {
                resultObject = (Y) constructor.newInstance();
            }catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            }
            break;
        }
    }
    if(resultObject == null){
        return null;
    }
    Field[] origFields = origClass.getDeclaredFields();
    Field[] destFields = resultObject.getClass().getDeclaredFields();

    Object value = null;
    for(Field dstField: destFields){
        try {
            Field tempOrigField = origClass.getDeclaredField(dstField.getName());
            if(tempOrigField.getType().equals(dstField.getType())
                    || areEquivalents(tempOrigField.getType().getSimpleName(), dstField.getType().getSimpleName())){
                dstField.set(resultObject, tempOrigField.get(origin));
            }
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        }
    }
    return resultObject;
}
</code>```

Hope this help.

Body:
I have few Pojos in different packages, each POJO contains set of the another pojo from the same package. I need to copy all items with the same name from Package B Pojos to objects in Package A.

Eaxmple:

package com.vanilla.packageA;

public class Student{

    private String firstName;
    private String lastName;
    private Set<Course> course;

    //getters and setters ommited

}

package com.vanilla.packageA;

    public class Course{
    private String courseName;
    private String courseDescription;

    //seters and getters
}

package com.vanilla.packageB;

public class Student{

    private String firstName;
    private String lastName;
    private Address address;
    private Set<Course> course;
    Private Date birtday;

    //getters and setters ommited

}

package com.vanilla.packageB;

public class Course{
    private String courseName;
    private String courseDescription;
    private <Lecturer> lecturer;
    private Integer hours;

    //seters and getters
}

I want to copy recursively all items from PackageB classes to packageA classes which exists in PaCkageB and shares the same name.

Updates:

Guys, I understand that that this is stupid question, but I need to maintain this code, now the code is written in the way that they have to call 50 getters and setter, or calling constructor with 50 parameters.
Unfortunately,  I can't use the same object and I need to copy it, but I must find more "elegant" way to copy tese beans.

Body:
Copying fields values are a need I almost every project, for example for do the clone(). I also think that for accomplish some goals isn't necessary import .jars for using only one function. I would like share some little code in which I was working, there are some things that I left in the inkwell but in general it do the work. In this case I use reflection.

public class ObjectCopyTools {

static String[] bases = new String[] {"byte", "short", "int", "long", "float", "double", "char", "boolean"};
static String[] equivalents = new String[] {"Byte", "Short", "Integer", "Long", "Float", "Double", "Character", "Boolean"};

static {

}

private static boolean areEquivalents(String type1, String type2){
    for (int i = 0; i < bases.length; i++) {
        if((type1.equals(bases[i]) && type2.equals(equivalents[i]))
                || (type2.equals(bases[i]) && type1.equals(equivalents[i]))){
            return true;
        }
    }
    return false;
}

public static <T extends Object, Y extends Object> Y deepReflectionObjectCopy(T origin, Class<Y> resultClass) {
    Class<? extends Object> origClass = origin.getClass();
    Y resultObject = null;
    for (Constructor<?> constructor : resultClass.getConstructors()) {
        if (constructor.getParameterCount() == 0) {
            try {
                resultObject = (Y) constructor.newInstance();
            }catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            }
            break;
        }
    }
    if(resultObject == null){
        return null;
    }
    Field[] origFields = origClass.getDeclaredFields();
    Field[] destFields = resultObject.getClass().getDeclaredFields();

    Object value = null;
    for(Field dstField: destFields){
        try {
            Field tempOrigField = origClass.getDeclaredField(dstField.getName());
            if(tempOrigField.getType().equals(dstField.getType())
                    || areEquivalents(tempOrigField.getType().getSimpleName(), dstField.getType().getSimpleName())){
                dstField.set(resultObject, tempOrigField.get(origin));
            }
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        }
    }
    return resultObject;
}

Hope this help.


问:
Image doesn't show in Wordpress but does in HTML/CSS
I have a div with a background image and text inside, but this doesn't show in Wordpress. However it works fine in HTML/CSS, as you can see here https://fiddle.jshell.net/tLavv0w1/

When I try to look at the code in Firefox developer tools, the CSS doesn't show. So it seems that the CSS doesn't connect with the HTML at all. I have also tried to change the div's name but it didn't work. I don't even know where to look for clues. Any help is much appreciated!

答: I have found the solution. Through Firefox developer tools, I found out that a comment tag before the CSS wasn't closed. It's now closed!</p>