问:
Recyclerview updating all viewholders
I have a recyclerview that has multiple view types. Basically, onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase. Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this? My issue is that calling getChildCount() on recyclerview only gets the visible children on the screen. However, I need all children. Am I going about this the right way? Or should I be populating my viewholders with data as it is being shown on the screen?

Code for clarification

This is what I'm using to get the data so that I can insert it into Firebase

```<code>int numberOfViews = displayWorkoutAdapter.rowTypeList.size() - 1;
                                    Log.d("numberOfViews", String.format("%s", numberOfViews));
                                    for (int a = 0; a < numberOfViews; a++) {
                                        RowType rowType = displayWorkoutAdapter.rowTypeList.get(a);
                                        Log.d("rowTypeClass", rowType.getClass().toString());

                                        if (rowType.getClass() == ExerciseModel.class) {
                                            ExerciseModel exerciseModel = (ExerciseModel) rowType;
                                            String exerciseString = exerciseModel.getExercise();
                                            String weightString = exerciseModel.getWeight();
                                            String setString = exerciseModel.getSets();
                                            String repsString = exerciseModel.getReps();
                                            Log.d("exerciseString", exerciseString);

                                            insertDataToTable(tableName, exerciseView, null, exerciseString, weightString, setString, repsString, null, null, "0");

                                        }
</code>```

OnBindViewHolder

```<code>    @Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){

    if(holder instanceof ExerciseRowHolder) {
        ((ExerciseRowHolder) holder).exercise.setText(((ExerciseModel) rowTypeList.get(position)).getExercise());
        ((ExerciseRowHolder) holder).weight.setText(((ExerciseModel) rowTypeList.get(position)).getWeight());
        ((ExerciseRowHolder) holder).set.setText(((ExerciseModel) rowTypeList.get(position)).getSets());
        ((ExerciseRowHolder) holder).rep.setText(((ExerciseModel) rowTypeList.get(position)).getReps());
        ((ExerciseRowHolder) holder).dragHandle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mDragStartListener.onStartDrag(holder);
                }
                return false;
            }
        });
        ((ExerciseRowHolder) holder).exercise.setAdapter(getExerciseAdapter(home.getContext()));
    }
</code>```

ExerciseRowHolder class

```<code>    public static class ExerciseRowHolder extends RecyclerView.ViewHolder{

    public ImageView dragHandle;
    public EditText weight;
    public EditText set;
    public EditText rep;
    public AutoCompleteTextView exercise;
    public ExerciseRowTextListener exerciseRowTextListener;

    public ExerciseRowHolder(View view, ExerciseRowTextListener exerciseRowTextListener){
        super(view);

        dragHandle = view.findViewById(R.id.reorder);
        weight = view.findViewById(R.id.weight);
        set = view.findViewById(R.id.sets);
        rep = view.findViewById(R.id.reps);
        exercise = view.findViewById(R.id.autoCompleteTextView);

    }
}
</code>```

答: adapter.notifyDataSetChanged() is the method in activity which changes all the data...you can perform all firebase operation in your activity and then you can call this method..this will update all the data.

Title: Recyclerview updating all viewholders

Body:
I have a recyclerview that has multiple view types. Basically, onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase. Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this? My issue is that calling getChildCount() on recyclerview only gets the visible children on the screen. However, I need all children. Am I going about this the right way? Or should I be populating my viewholders with data as it is being shown on the screen?

Code for clarification

This is what I'm using to get the data so that I can insert it into Firebase

int numberOfViews = displayWorkoutAdapter.rowTypeList.size() - 1;
                                    Log.d("numberOfViews", String.format("%s", numberOfViews));
                                    for (int a = 0; a < numberOfViews; a++) {
                                        RowType rowType = displayWorkoutAdapter.rowTypeList.get(a);
                                        Log.d("rowTypeClass", rowType.getClass().toString());

                                        if (rowType.getClass() == ExerciseModel.class) {
                                            ExerciseModel exerciseModel = (ExerciseModel) rowType;
                                            String exerciseString = exerciseModel.getExercise();
                                            String weightString = exerciseModel.getWeight();
                                            String setString = exerciseModel.getSets();
                                            String repsString = exerciseModel.getReps();
                                            Log.d("exerciseString", exerciseString);

                                            insertDataToTable(tableName, exerciseView, null, exerciseString, weightString, setString, repsString, null, null, "0");

                                        }

OnBindViewHolder

    @Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){

    if(holder instanceof ExerciseRowHolder) {
        ((ExerciseRowHolder) holder).exercise.setText(((ExerciseModel) rowTypeList.get(position)).getExercise());
        ((ExerciseRowHolder) holder).weight.setText(((ExerciseModel) rowTypeList.get(position)).getWeight());
        ((ExerciseRowHolder) holder).set.setText(((ExerciseModel) rowTypeList.get(position)).getSets());
        ((ExerciseRowHolder) holder).rep.setText(((ExerciseModel) rowTypeList.get(position)).getReps());
        ((ExerciseRowHolder) holder).dragHandle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mDragStartListener.onStartDrag(holder);
                }
                return false;
            }
        });
        ((ExerciseRowHolder) holder).exercise.setAdapter(getExerciseAdapter(home.getContext()));
    }

ExerciseRowHolder class

    public static class ExerciseRowHolder extends RecyclerView.ViewHolder{

    public ImageView dragHandle;
    public EditText weight;
    public EditText set;
    public EditText rep;
    public AutoCompleteTextView exercise;
    public ExerciseRowTextListener exerciseRowTextListener;

    public ExerciseRowHolder(View view, ExerciseRowTextListener exerciseRowTextListener){
        super(view);

        dragHandle = view.findViewById(R.id.reorder);
        weight = view.findViewById(R.id.weight);
        set = view.findViewById(R.id.sets);
        rep = view.findViewById(R.id.reps);
        exercise = view.findViewById(R.id.autoCompleteTextView);

    }
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Paperclip not saving image because of wrong content type
I am having issues uploading an image from Node js app to a remote server.
The remote server app is Rails 5 and using paperclip to save the file.
When I upload the image through Postman , the image is saved successfully and everything works fine. But the issue is when I upload from front end Node app, The image is not saved and this is what I see in the logs

```<code>begin transaction Command :: file -b --mime '/var/folders/90/d3rv8dkd3t1g9wwz90dtk_dx41mg3d/T/b5e7d988cfdb78bc3be1a9c221a8f74420171114-33517-11gthzp.png'
[paperclip] Content Type Spoof: Filename image1.png (text/plain from
Headers, ["image/png"] from Extension), content type discovered from
file command: text/plain. See documentation to allow this combination.
rollback transaction
</code>```

After researching online, it seems like I am not encoding the file correctly in the front end node app.Here is my code

```<code>var FormData = require('form-data');
var fetch = require('node-fetch');

var form = new FormData();
form.append('name', req.body.name);
form.append('image', req.body.attachment, req.body.filename);

fetch('http://localhost:3000/slides', { method: 'POST', body: form,headers: form.getHeaders()})
.then(function(res) {
    return res.json();
}).then(function(json) {
    console.log(json);
});
  res.json(resp)
})
</code>```

Can someone guide me how to fix this?

I have even tried to override content type validation in my backend app, but still doesn't work.

```<code>class Slide < ApplicationRecord
  has_attached_file :image, styles: { small: "64x64", med: "100x100", large: "200x200" }
  validates_attachment_content_type :image, :content_type => ["image/jpg", "text/plain","image/jpeg", "image/png", "image/gif"]

 end
</code>```

config/initializer/paperclip_spoof.rb

```<code>require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end
</code>```

Please I need your help.Thank you in advance

答:
I just had to decode the base64 before sending the file to the server</p>

```<code>var buff = new
Buffer(req.body.attachment.replace(/^data:image\/\w+;base64,/, ""), 'base64');
fs.writeFileSync('image.png', buff);
var form = new FormData();
form.append('name', "some name");
form.append('image', buff, req.body.filename);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having issues uploading an image from Node js app to a remote server.
The remote server app is Rails 5 and using paperclip to save the file.
When I upload the image through Postman , the image is saved successfully and everything works fine. But the issue is when I upload from front end Node app, The image is not saved and this is what I see in the logs

begin transaction Command :: file -b --mime '/var/folders/90/d3rv8dkd3t1g9wwz90dtk_dx41mg3d/T/b5e7d988cfdb78bc3be1a9c221a8f74420171114-33517-11gthzp.png'
[paperclip] Content Type Spoof: Filename image1.png (text/plain from
Headers, ["image/png"] from Extension), content type discovered from
file command: text/plain. See documentation to allow this combination.
rollback transaction

After researching online, it seems like I am not encoding the file correctly in the front end node app.Here is my code

var FormData = require('form-data');
var fetch = require('node-fetch');

var form = new FormData();
form.append('name', req.body.name);
form.append('image', req.body.attachment, req.body.filename);

fetch('http://localhost:3000/slides', { method: 'POST', body: form,headers: form.getHeaders()})
.then(function(res) {
    return res.json();
}).then(function(json) {
    console.log(json);
});
  res.json(resp)
})

Can someone guide me how to fix this?

I have even tried to override content type validation in my backend app, but still doesn't work.

class Slide < ApplicationRecord
  has_attached_file :image, styles: { small: "64x64", med: "100x100", large: "200x200" }
  validates_attachment_content_type :image, :content_type => ["image/jpg", "text/plain","image/jpeg", "image/png", "image/gif"]

 end

config/initializer/paperclip_spoof.rb

require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

Please I need your help.Thank you in advance

Body:
I just had to decode the base64 before sending the file to the server

var buff = new
Buffer(req.body.attachment.replace(/^data:image\/\w+;base64,/, ""), 'base64');
fs.writeFileSync('image.png', buff);
var form = new FormData();
form.append('name', "some name");
form.append('image', buff, req.body.filename);


问:
TextInputLayout Crashing in Android Lollipop and Above
I am using TextInputLayout in one of my app layouts. My app is crashing on user's devices with Lollipop(5.1) version and above.
Below is the error

```<code>android.view.InflateException: Binary XML file line #34: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by android.view.InflateException: Binary XML file line #34: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by java.lang.reflect.InvocationTargetException: arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/design_password_eye.xml from drawable resource ID #0x7f0200b1 arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/avd_show_password.xml from drawable resource ID #0x7f02005c arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/avd_show_password_1.xml from drawable resource ID #0x7f0201bd arrow_drop_down
Caused by org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag x
</code>```

I have tried all solutions at StackOverflow but they are not working. This include updating my libraries, using android:theme="@style/Theme.AppCompat" but my the app is still crashing.

TextInputLayout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TextInputLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:theme="@style/Theme.AppCompat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_bg"
    android:id="@+id/passwordInput"
    app:hintTextAppearance="@style/UI.Text.HintText"
    app:errorTextAppearance="@style/UI.Text.ErrorText"
    android:textColorHint="@color/inputLabelColor"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="#000000">

    <EditText
        android:textSize="18sp"
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:textColorHint="@color/inputLabelColor"
        android:textColor="@android:color/black"
        android:hint="@string/password_hint"
        android:inputType="textPassword"
        android:background="@drawable/apptheme_edit_text_holo_light"
        />
</android.support.design.widget.TextInputLayout>
</code>```

build.gradle

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.all {
            testLogging {
                exceptionFormat = 'full'
            }
        }
    }
    productFlavors {
    }
}

dependencies {
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.google.android.gms:play-services-auth:9.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha6'
}
</code>```

Kindly help me get rid of this bug. I feel like crying. :(

UPDATE

This files can be found in generated folder. e.g for design_password_eye.xml it can be found at /app/build/intermediates/exploded-aar/com.android.support/design/25.1.0/res/drawable-v21/design_password_eye.xml

I don't know why then it's declared missing and crashing my app

UPDATE 2

manifest(app)

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.r.p">

    <uses-sdk tools:overrideLibrary="com.base.ui.auth" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <uses-permission android:name="android.permission.CAMERA" />
    <!-- To access Google+ APIs: -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!--
        The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
        Google Maps Android API v2, but you must specify either coarse or fine
        location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- EXTERNAL_STORAGE permissions are optional for Android 6.0 onwards. -->
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="22" />
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="22" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.example.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
    <application
        android:name=".activities.AppApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:theme">

// Activities here
        </application>

</manifest>
</code>```

Manifest for module auth(com.base.ui.auth)

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.base.ui.auth">

    <application>

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

//activities here
 </application>

    </manifest>
</code>```

Styles

app module

```<code>    <resources>
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/md_blue_900</item>
            <item name="colorAccent">@color/dialog_color</item>
            <!--
            This overrides the default dark or light dialog background color.
            Note that if you use a dark color here, you should set md_dark_theme to
            true so text and selectors look visible
        -->
            <item name="md_background_color">@android:color/transparent</item>
            <!--To change the background of options menu-->
            <item name="android:itemBackground">@color/app_actionBar</item>
            <!--To change the text styling of options menu items</item>-->
            <item name="android:itemTextAppearance">@style/itemStyle</item>
            <item name="android:listPopupWindowStyle">@style/MyListPopupWindowStyle</item>
            <item name="android:actionModeBackground">@color/app_actionBar</item>
            <item name="android:actionModeCloseDrawable">@drawable/ic_action_close</item>
        </style>
 <style name="Toolbar" parent="Base.ThemeOverlay.AppCompat.ActionBar">
        <item name="android:textColorPrimary">@color/md_white_1000</item>
        <!--<item name="android:background">@color/dark_blue</item>-->
    </style>

    <style name="Toolbar_Popup" parent="Base.ThemeOverlay.AppCompat.ActionBar">
        <item name="android:textColorPrimary">@color/md_black_1000</item>
        <item name="android:background">@color/md_white_1000</item>
    </style>

    <style name="MyListPopupWindowStyle" parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@color/app_actionBar</item>
        <item name="android:textColor">@color/md_black_1000</item>
    </style>

    <style name="AppTheme.NoActionBar.PR" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@color/md_white_1000</item>
        <item name="colorAccent">@color/md_blue_900</item>
    </style>

    <style name="AppTheme.NoActionBar.PC" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@color/md_white_1000</item>
        <item name="colorAccent">@color/md_blue_900</item>
    </style>

    <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
            <item name="windowActionBar">false</item>
            <item name="windowNoTitle">true</item>
            <item name="windowActionModeOverlay">true</item>
            <item name="android:actionModeBackground">@color/app_actionBar</item>
            <item name="itemTextAppearance">@style/MyActionBar.MenuTextStyle</item>
        </style

>
</code>```

values-21

```<code><resources>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:itemTextAppearance">@style/MyActionBar.MenuTextStyle</item>
        <!--To change the background of options menu-->
        <item name="android:itemBackground">@color/md_white_1000</item>
    </style>
</resources>
</code>```

styles for module auth

```<code><style name="SplashTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowBackground">@color/app_background</item>
        <item name="colorPrimary">@color/authui_colorPrimary</item>
        <item name="colorPrimaryDark">@color/authui_colorPrimaryDark</item>
        <item name="colorAccent">@color/authui_colorAccent</item>
        <item name="colorButtonNormal">@color/authui_colorPrimary</item>

        <item name="android:buttonStyle">@style/UI.Button</item>
        <item name="android:editTextStyle">@style/UI.EditText</item>
    </style>

<style name="UI.EditText">
        <item name="android:textSize">16sp</item>
        <item name="android:lineSpacingExtra">8sp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:fontFamily">sans-serif</item>
        <item name="android:colorActivatedHighlight">@color/authui_colorPrimary</item>
        <item name="android:colorFocusedHighlight">@color/authui_colorPrimary</item>
    </style>
</code>```

答:
It seems that TextInputLayout try to look up the resources like design_password_eye.xml only while using the default password-toggle Drawable.

So, we can avoid Resources$NotFoundException by setting app:passwordToggleDrawable="@null"

```<code>    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleDrawable="@null"
        app:errorEnabled="true">
</code>```

Body:
I am using TextInputLayout in one of my app layouts. My app is crashing on user's devices with Lollipop(5.1) version and above.
Below is the error

android.view.InflateException: Binary XML file line #34: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by android.view.InflateException: Binary XML file line #34: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.TextInputLayout arrow_drop_down
Caused by java.lang.reflect.InvocationTargetException: arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/design_password_eye.xml from drawable resource ID #0x7f0200b1 arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/avd_show_password.xml from drawable resource ID #0x7f02005c arrow_drop_down
Caused by android.content.res.Resources$NotFoundException: File res/drawable-v21/avd_show_password_1.xml from drawable resource ID #0x7f0201bd arrow_drop_down
Caused by org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag x

I have tried all solutions at StackOverflow but they are not working. This include updating my libraries, using android:theme="@style/Theme.AppCompat" but my the app is still crashing.

TextInputLayout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TextInputLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:theme="@style/Theme.AppCompat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_bg"
    android:id="@+id/passwordInput"
    app:hintTextAppearance="@style/UI.Text.HintText"
    app:errorTextAppearance="@style/UI.Text.ErrorText"
    android:textColorHint="@color/inputLabelColor"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="#000000">

    <EditText
        android:textSize="18sp"
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:textColorHint="@color/inputLabelColor"
        android:textColor="@android:color/black"
        android:hint="@string/password_hint"
        android:inputType="textPassword"
        android:background="@drawable/apptheme_edit_text_holo_light"
        />
</android.support.design.widget.TextInputLayout>

build.gradle

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.all {
            testLogging {
                exceptionFormat = 'full'
            }
        }
    }
    productFlavors {
    }
}

dependencies {
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.google.android.gms:play-services-auth:9.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha6'
}

Kindly help me get rid of this bug. I feel like crying. :(

UPDATE

This files can be found in generated folder. e.g for design_password_eye.xml it can be found at /app/build/intermediates/exploded-aar/com.android.support/design/25.1.0/res/drawable-v21/design_password_eye.xml

I don't know why then it's declared missing and crashing my app

UPDATE 2

manifest(app)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.r.p">

    <uses-sdk tools:overrideLibrary="com.base.ui.auth" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

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

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

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

    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="22" />
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="22" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.example.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
    <application
        android:name=".activities.AppApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:screenOrientation="portrait"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:theme">

// Activities here
        </application>

</manifest>

Manifest for module auth(com.base.ui.auth)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.base.ui.auth">

    <application>

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

//activities here
 </application>

    </manifest>

Styles

app module

    <resources>

values-21

<resources>

</resources>

styles for module auth

Body:
It seems that TextInputLayout try to look up the resources like design_password_eye.xml only while using the default password-toggle Drawable.

So, we can avoid Resources$NotFoundException by setting app:passwordToggleDrawable="@null"

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleDrawable="@null"
        app:errorEnabled="true">


问:
How to load a URL in chromium?
I created a new activity which extends SingleTabActivity and it calls:

```<code>getActivityTab().loadUrl(new LoadUrlParams("http://google.com.vn", PageTransition.AUTO_TOPLEVEL));
</code>```

But nothing is showing up. Do I need anything else to tell Chromium to render web content?

Thank you!

答:
I found the answer. Override finishNativeInitialization and add following lines:</p>

```<code>LayoutManager layoutDriver = new CustomTabLayoutManager(getCompositorViewHolder());
    initializeCompositorContent(layoutDriver, findViewById(org.chromium.chrome.R.id.url_bar),
            (ViewGroup) findViewById(android.R.id.content),
            (ToolbarControlContainer) findViewById(org.chromium.chrome.R.id.control_container));
</code>```

Title: How to load a URL in chromium?

Body:
I created a new activity which extends SingleTabActivity and it calls:

getActivityTab().loadUrl(new LoadUrlParams("http://google.com.vn", PageTransition.AUTO_TOPLEVEL));

But nothing is showing up. Do I need anything else to tell Chromium to render web content?

Thank you!

Body:
I found the answer. Override finishNativeInitialization and add following lines:

LayoutManager layoutDriver = new CustomTabLayoutManager(getCompositorViewHolder());
    initializeCompositorContent(layoutDriver, findViewById(org.chromium.chrome.R.id.url_bar),
            (ViewGroup) findViewById(android.R.id.content),
            (ToolbarControlContainer) findViewById(org.chromium.chrome.R.id.control_container));


问:
Python find CRC32 of string
I tried to get crc32 of a string data type variable but getting the following error.

```<code>>>> message='hello world!'
>>> import binascii
>>> binascii.crc32(message)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
</code>```

For a string values it can be done with binascii.crc32(b'hello world!') but I would like to know how to do this for a string data-type variable

答:
When you are computing crc32 of some data, you need to know the exact value of bytes you are hashing. One string can represent different values of bytes in different encodings, therefore passing string as parameter is ambiguous.

When using binascii.crc32(b'hello world!'), you are converting char array into array of bytes using simple ascii table as conversion.

To convert any string, you can use:

```<code>import binascii

text = 'hello'
binascii.crc32(text.encode('utf8'))
</code>```

Title: Python find CRC32 of string

Body:
I tried to get crc32 of a string data type variable but getting the following error.

>>> message='hello world!'
>>> import binascii
>>> binascii.crc32(message)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

For a string values it can be done with binascii.crc32(b'hello world!') but I would like to know how to do this for a string data-type variable

Body:
When you are computing crc32 of some data, you need to know the exact value of bytes you are hashing. One string can represent different values of bytes in different encodings, therefore passing string as parameter is ambiguous.

When using binascii.crc32(b'hello world!'), you are converting char array into array of bytes using simple ascii table as conversion.

To convert any string, you can use:

import binascii

text = 'hello'
binascii.crc32(text.encode('utf8'))


问:
How to avoid warning of Unreachable code
I have the below

```<code>string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;
</code>```

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

答:
You are using 'break;' wihout any condition. This will cause the loop to brak on the very first time. So, incremental part 'm = m.NextMatch()' won't execute even a single time, for which you are getting the warning. Try to use an if condition like as follows:

```<code>If(currency<0){break;}
</code>```

Use the proper condition for which you want the 'break' to happen. That should help you just fine.

Regards

ContentLicense: CC BY-SA 2.5

Body:
I have the below

string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

Body:
You are using 'break;' wihout any condition. This will cause the loop to brak on the very first time. So, incremental part 'm = m.NextMatch()' won't execute even a single time, for which you are getting the warning. Try to use an if condition like as follows:

If(currency<0){break;}

Use the proper condition for which you want the 'break' to happen. That should help you just fine.

Regards


问:
error: Invalid argument; while sending msgsnd() message; not matching queue ID
I was just learning IPC on linux and come up with three simple programs. One is made to create (and administrate in the feature) the message queue. The second should just send the message to the queue created by the first one. The third program is receiving data from the queue.

All programs are inheriting from the same root directory and spiting in to separate directories per source and binaries.

So lets just focus on creating and sending part, and that shall help me fix the third program as well.

add queue main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define FAILED -1

int main(int argc, char *argv[]) {
  // message data
  key_t key;
  int msgqid;

  if ((key = ftok("../src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if ((msgqid = msgget(key, 0666 | IPC_CREAT)) == FAILED) { /* create an message queue with owner & group & others permission set to rw- */
    perror("msgget");
    exit(1);
  }

  printf("Message Queue %i with key %i, been created [press return to delete]", msgqid, key);
  getchar();

  if (msgctl(msgqid, IPC_RMID, NULL) == FAILED) {
    perror("msgctl");
    exit(1);
  }
  printf("I'm outta here! \n");

  return 0;
}
</code>```

send main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <stddef.h>
#include <string.h>

#include "../../lib/shared_msgbuf.h" /* mbuf, MSGSZ */

#define FAILED -1

int main(void) {
  char s[MSGSZ];

  printf("Enter a message: ");

  if (fgets(s, sizeof s, stdin) == NULL)
    perror("fgets");
  else
    strcpy(mbuf.mtext, s);

  printf("Connecting to the queue... \n", s);

  // Setup
  key_t key;
  int msgqid;

  if ((key = ftok("../../adqueue/src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if (msgqid = msgget(key, 0666) == FAILED) {
    perror("msget");
    exit(1);
  }

  printf("\n*CONNECTION ESTABLISHED* \n");
  printf("queue id: %i \n", msgqid);
  printf("queue key: %d \n", key);
  printf("message: %s \n", s);

  printf("Sending the message... \n");
  if (msgsnd(msgqid, &mbuf, MSGSZ, 0) == FAILED) {
    perror("msgsnd");
    exit(0);
  }

  return 0;
}
</code>```

So the problem is that I'm getting Invalid argument error number when trying to send the message. Looking at the data, I can't get why the id is not matching since connection to the queue seems to work...

Exemplar data:

```<code>./cadqueue
Message Queue 327680 with key 1510081535, been created [press return to delete]

./send
Enter a message: test
Connecting to the queue...

*CONNECTION ESTABLISHED*
queue id: 0
queue key: 1510081535
message: test

Sending the message...
msgsnd: Invalid argument
</code>```

答:
these are the header files needed for msgsnd()

```<code>   #include <sys/types.h>
   #include <sys/ipc.h>
   #include <sys/msg.h>
</code>```

The posted code, for portability, is missing two of those header file include statements

===========

this statement:

```<code>if (msgqid = msgget(key, 0666) == FAILED) {
</code>```

is missing the the IPC_CREAT that should be part of the 0666 parameter

===========

the mbuf has two fields, the mtype field, which MUST be positive, > 0
and the mtext field.

The posted code is setting the mtext field, but failing to set the mtype field.

=============

this statement:

```<code>printf("Connecting to the queue... \n", s);
</code>```

has the problem that there is a input parameter, but their is no format specifier in the 'format string'

============

The key value must be the same for every access to the same message queue.

so the calls to ftok() must all have the same parameter, otherwise they will generate different/unique message queues via the call to msgget()

============

Note: message queues do not 'go away' just because a program exits.  Therefore, the controlling program (or the last user of the last message) should be calling msgctl() to remove the message queue

Body:
I was just learning IPC on linux and come up with three simple programs. One is made to create (and administrate in the feature) the message queue. The second should just send the message to the queue created by the first one. The third program is receiving data from the queue.

All programs are inheriting from the same root directory and spiting in to separate directories per source and binaries.

So lets just focus on creating and sending part, and that shall help me fix the third program as well.

add queue main.c:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define FAILED -1

int main(int argc, char *argv[]) {
  // message data
  key_t key;
  int msgqid;

  if ((key = ftok("../src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if ((msgqid = msgget(key, 0666 | IPC_CREAT)) == FAILED) { /* create an message queue with owner & group & others permission set to rw- */
    perror("msgget");
    exit(1);
  }

  printf("Message Queue %i with key %i, been created [press return to delete]", msgqid, key);
  getchar();

  if (msgctl(msgqid, IPC_RMID, NULL) == FAILED) {
    perror("msgctl");
    exit(1);
  }
  printf("I'm outta here! \n");

  return 0;
}

send main.c:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <stddef.h>
#include <string.h>

#include "../../lib/shared_msgbuf.h" /* mbuf, MSGSZ */

#define FAILED -1

int main(void) {
  char s[MSGSZ];

  printf("Enter a message: ");

  if (fgets(s, sizeof s, stdin) == NULL)
    perror("fgets");
  else
    strcpy(mbuf.mtext, s);

  printf("Connecting to the queue... \n", s);

  // Setup
  key_t key;
  int msgqid;

  if ((key = ftok("../../adqueue/src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if (msgqid = msgget(key, 0666) == FAILED) {
    perror("msget");
    exit(1);
  }

  printf("\n*CONNECTION ESTABLISHED* \n");
  printf("queue id: %i \n", msgqid);
  printf("queue key: %d \n", key);
  printf("message: %s \n", s);

  printf("Sending the message... \n");
  if (msgsnd(msgqid, &mbuf, MSGSZ, 0) == FAILED) {
    perror("msgsnd");
    exit(0);
  }

  return 0;
}

So the problem is that I'm getting Invalid argument error number when trying to send the message. Looking at the data, I can't get why the id is not matching since connection to the queue seems to work...

Exemplar data:

./cadqueue
Message Queue 327680 with key 1510081535, been created [press return to delete]

./send
Enter a message: test
Connecting to the queue...

*CONNECTION ESTABLISHED*
queue id: 0
queue key: 1510081535
message: test

Sending the message...
msgsnd: Invalid argument

Body:
these are the header files needed for msgsnd()

   #include <sys/types.h>
   #include <sys/ipc.h>
   #include <sys/msg.h>

The posted code, for portability, is missing two of those header file include statements

===========

this statement:

if (msgqid = msgget(key, 0666) == FAILED) {

is missing the the IPC_CREAT that should be part of the 0666 parameter

===========

the mbuf has two fields, the mtype field, which MUST be positive, > 0
and the mtext field.

The posted code is setting the mtext field, but failing to set the mtype field.

=============

this statement:

printf("Connecting to the queue... \n", s);

has the problem that there is a input parameter, but their is no format specifier in the 'format string'

============

The key value must be the same for every access to the same message queue.

so the calls to ftok() must all have the same parameter, otherwise they will generate different/unique message queues via the call to msgget()

============

Note: message queues do not 'go away' just because a program exits.  Therefore, the controlling program (or the last user of the last message) should be calling msgctl() to remove the message queue


问:
How can I load fonts from a different location in MathJax?
MathJax enforces a directory structure based on its library design. Fonts bundled with the library are in a subdirectory alongside some Javascript configuration and other components.

I want to serve the fonts from a different location on disk but I'm not seeing any configuration values that allow me to do that. I've checked the documentation and while I'm seeing different ways to load the full library and pieces of configuration, I'm not seeing how to isolate the fonts.

How can I load fonts from a different location in MathJax?

Edit: This is a client-side solution; we're doing this in the browser. We're using the TeX-AMS_CHTML.js configuration, which uses the CommonHTML rendering strategy. In the configuration (which is minified) it looks like there's a MathJax.OutputJax.fontDir that could be edited?

答:
You want to override the CommonHTML webfontDir.  Try

```<code><script type="text/x-mathjax-config">
MathJax.Hub.Register.StartupHook('CommonHTML Jax Ready", function () {
  MathJax.OutputJax.CommonHTML.webfontDir = 'myURL/myDontDirectory';
});
</script>
</code>```

where myURL/myFontDirectory is the full URL to the directory containing your fonts.  You may need to set the access control for the fonts directory to allow cross-domain access if the URL domain is not the same as the domain of the page loading MathJax.  See the MathJax documentation on shared installations for more details.

Body:
You want to override the CommonHTML webfontDir.  Try

<script type="text/x-mathjax-config">
MathJax.Hub.Register.StartupHook('CommonHTML Jax Ready", function () {
  MathJax.OutputJax.CommonHTML.webfontDir = 'myURL/myDontDirectory';
});
</script>

where myURL/myFontDirectory is the full URL to the directory containing your fonts.  You may need to set the access control for the fonts directory to allow cross-domain access if the URL domain is not the same as the domain of the page loading MathJax.  See the MathJax documentation on shared installations for more details.


问:
How to receive full stacktrace with methods, file paths, and line numbers for JavaScript instead native errors via fabric.io in React-native
I have manage to setup the fabric.io in ios and android using https://github.com/corymsmith/react-native-fabric but the crash report is in native code i.e. java and objective-c, that is completely unhelpful.

Is there way to receive the full stacktrace with methods, file paths, and line numbers for JavaScript instead native errors.

by doing some research I found if I upload sourcemap than there is a possibility of receiving the JavaScript stacktrace.

答:
At this moment I am aware of two companies that do this:

1) Sentry: https://sentry.io/welcome/

2) Bugsnag: https://www.bugsnag.com/

I eventually went with Sentry since it has a bigger community and you can install it on premise if you want to.

Bugsnag has a cool feature advertized which is snoozing the crashes which almost made me go for it, but Sentry has it too.

I was using Fabric too, but eventually moved to Sentry due to this.


问:
How can I remove all old related items in an array list when I insert a new item? i.e. Cube 1 removed when adding Cube 2
```<code>String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));
</code>```

I add the total string 1 by 1 by pressing a button

```<code>total_list.add(newstring);
</code>```

So, my array will be like this:

```<code>ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}
</code>```

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

答:
Use this..removeAll will remove all the data and then you can add new data.</p>

```<code>total_list.removeAll(total_list);

total_list.add("new item");
</code>```

Body:
String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));

I add the total string 1 by 1 by pressing a button

total_list.add(newstring);

So, my array will be like this:

ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

Body:
Use this..removeAll will remove all the data and then you can add new data.

total_list.removeAll(total_list);

total_list.add("new item");


问:
adding timeout to jena (for sparql) using dbpedia as end point?
I would like to know whether there is a way to use Jena to do a sparql query through dbpedia and using the timeout setting given in http://dbpedia.org/sparql (if you see this page, you could see that there is a way to set the timeout there), this is needed since I would like to make a big query and I have tried several times (via the page) that without setting the timeout, I cannot get the result (it is always a transaction timeout exception)

edited: I use java.

答:
To execute your query, I guess you're using :

```<code>QueryExecutionFactory.sparqlService(String service, Query query)
</code>```

One thing you could try is:

```<code>QueryEngineHTTP objectToExec=QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql",YOUR_QUERY);
objectToExec.addParam("timeout","5000"); //5 sec
resultset=objectToExec.execSelect();
</code>```

It seems that QueryEngineHTTP implements QueryExecution which has an addParam method. There's no description of that method but I'd assume that adds a parameter to the HTTP request.

Let me know if it works !!

Edited
to fix error actually it was the other way around ... QueryEngineHTTP implements QueryExecution

Body:
To execute your query, I guess you're using :

QueryExecutionFactory.sparqlService(String service, Query query)

One thing you could try is:

QueryEngineHTTP objectToExec=QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql",YOUR_QUERY);
objectToExec.addParam("timeout","5000"); //5 sec
resultset=objectToExec.execSelect();

It seems that QueryEngineHTTP implements QueryExecution which has an addParam method. There's no description of that method but I'd assume that adds a parameter to the HTTP request.

Let me know if it works !!

Edited
to fix error actually it was the other way around ... QueryEngineHTTP implements QueryExecution


问:
How to convert enum to QString?
I am trying to use the Qt reflection for converting enum to QString.

Here is the part of code:

```<code>class ModelApple
{
    Q_GADGET
    Q_ENUMS(AppleType)
public:
    enum AppleType {
      Big,
      Small
    }
}
</code>```

And here is i trying to do:

```<code>convertEnumToQString(ModelApple::Big)
</code>```

Return "Big"

Is this possible?
If you have any idea about convertEnumToQString, please share it

答:
Much more elegant way found (Qt 5.9), just one single line, with the help of mighty QVariant.

turns enum into string:

```<code>QString theBig = QVariant::fromValue(ModelApple::Big).toString();
</code>```

Perhaps you don't need QMetaEnum anymore.

Sample code here:

ModelApple (no need to claim Q_DECLARE_METATYE)

```<code>class ModelApple : public QObject
{
    Q_OBJECT
public:
    enum AppleType {
      Big,
      Small
    };
    Q_ENUM(AppleType)
    explicit ModelApple(QObject *parent = nullptr);
};
</code>```

And I create a widget application, calling QVaraint function there :

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <modelapple.h>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString s = QVariant::fromValue(ModelApple::Big).toString();
    qDebug() << s;

}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

You can see that i try to output the string on console , which really did:

And sorry for reverse casting , i tried successfully in some project , but some how this time i met compiling error. So i decide to remove it from my answer.

Title: How to convert enum to QString?

Body:
I am trying to use the Qt reflection for converting enum to QString.

Here is the part of code:

class ModelApple
{
    Q_GADGET
    Q_ENUMS(AppleType)
public:
    enum AppleType {
      Big,
      Small
    }
}

And here is i trying to do:

convertEnumToQString(ModelApple::Big)

Return "Big"

Is this possible?
If you have any idea about convertEnumToQString, please share it

Body:
Much more elegant way found (Qt 5.9), just one single line, with the help of mighty QVariant.

turns enum into string:

QString theBig = QVariant::fromValue(ModelApple::Big).toString();

Perhaps you don't need QMetaEnum anymore.

Sample code here:

ModelApple (no need to claim Q_DECLARE_METATYE)

class ModelApple : public QObject
{
    Q_OBJECT
public:
    enum AppleType {
      Big,
      Small
    };
    Q_ENUM(AppleType)
    explicit ModelApple(QObject *parent = nullptr);
};

And I create a widget application, calling QVaraint function there :

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <modelapple.h>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString s = QVariant::fromValue(ModelApple::Big).toString();
    qDebug() << s;

}

MainWindow::~MainWindow()
{
    delete ui;
}

You can see that i try to output the string on console , which really did:

And sorry for reverse casting , i tried successfully in some project , but some how this time i met compiling error. So i decide to remove it from my answer.


问:
Drawing text in canvas element
could you tell me what is the problem with the text on my canvas? I tried to change the text size if I make it bigger it looks fine but if I make it smaller it looks weird. I'm not sure what exactly affect the text; I tried to play with font property but with no result, whenever I make the font smaller I got the result like in the snippet below
here is my code

(function(){
    function init(){
        var canvas = document.getElementsByTagName('canvas')[0];
        var c = canvas.getContext('2d');
        var animationStartTime =0;
        c.fillStyle = 'white';
        c.font = 'normal 10pt';
        var textarray = 'you can live a beatiful life with a postive mind';

        var j=1;
        //time - next repaint time - HRT
        function draw(time){

            c.fillText(textarray.substr(0,j),10,70);
            if(time - animationStartTime > 100){
                animationStartTime = time;
                j++;
            }
            if( j <= textarray.length){
            requestAnimationFrame(draw);   // 17ms
            }
          }
        function start(){
            animationStartTime = window.performance.now();
            requestAnimationFrame(draw);
        }

        start();
    }
//invoke function init once document is fully loaded
    window.addEventListener('load',init,false);
}()); //self invoking function```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas{
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}
canvas {
  width:100%;
  height:80vh;
  left: 0;
  margin: 0;
  padding: 0;
  position: relative;
  top: 0;
}
 </code>```

       <canvas >

      </canvas>

```

答:
When you fillText on the canvas, it stops being letters and starts being a letter-shaped collection of pixels. When you zoom in on it, the pixels become bigger. That's how a canvas works.

When you want the text to scale as a vector-based font and not as pixels, don't draw them on the canvas. You could create  HTML elements instead and place them on top of the canvas using CSS positioning. That way the rendering engine will render the fonts in a higher resolution when you zoom in and they will stay sharp. But anything you draw on the canvas will zoom accordingly.

But what I would recommend for this simple example is just doing it in html, css, and javascript like so:

var showText = function (target, message, index, interval) {
  if (index < message.length) {
    $(target).append(message[index++]);
    setTimeout(function () { showText(target, message, index, interval); }, interval);
  }
}

$(function () {

  showText("#text", "you can live a beatiful life with a postive mind", 0, 100);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas{
  position: relative;
  width: 100%;
  height: 80vh;
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}

#text {

  position: absolute;
  top: 50%;
  left: 20px;
  color: #fff;
  font-size: 20px;

}</code>```

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

<p><em>I'll leave it up to you to position the text and whatnot but you can see in this example that you can make the text as small, or as big, as you want.</em></p>

<p><strong>However</strong> </p>

<p>...if you still absolutely need it to be a canvas then the following example works. It works because the canvas is not being stretched by css, the width and height are predefined.</p>

<p>The canvas element runs independent from the device or monitor's pixel ratio.</p>

<p>On the iPad 3+, this ratio is 2. This essentially means that your 1000px width canvas would now need to fill 2000px to match it's stated width on the iPad display. Fortunately for us, this is done automatically by the browser. On the other hand, this is also the reason why you see less definition on images and canvas elements that were made to directly fit their visible area. Because your canvas only knows how to fill 1000px but is asked to draw to 2000px, the browser must now intelligently fill in the blanks between pixels to display the element at its proper size.</p>

<p>I would highly recommend you read this article from HTML5Rocks which explains in more detail how to create high definition elements.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "12px Arial";
ctx.fillText("Hello World",10,50);</code>```

#canvas{
  position: relative;
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

<canvas id="canvas" width="800" height="500"
style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>

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

Title: Drawing text in canvas element

Body:
could you tell me what is the problem with the text on my canvas? I tried to change the text size if I make it bigger it looks fine but if I make it smaller it looks weird. I'm not sure what exactly affect the text; I tried to play with font property but with no result, whenever I make the font smaller I got the result like in the snippet below
here is my code

(function(){
    function init(){
        var canvas = document.getElementsByTagName('canvas')[0];
        var c = canvas.getContext('2d');
        var animationStartTime =0;
        c.fillStyle = 'white';
        c.font = 'normal 10pt';
        var textarray = 'you can live a beatiful life with a postive mind';

        var j=1;
        //time - next repaint time - HRT
        function draw(time){

            c.fillText(textarray.substr(0,j),10,70);
            if(time - animationStartTime > 100){
                animationStartTime = time;
                j++;
            }
            if( j <= textarray.length){
            requestAnimationFrame(draw);   // 17ms
            }
          }
        function start(){
            animationStartTime = window.performance.now();
            requestAnimationFrame(draw);
        }

        start();
    }
//invoke function init once document is fully loaded
    window.addEventListener('load',init,false);
}()); //self invoking function

#canvas{
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}
canvas {
  width:100%;
  height:80vh;
  left: 0;
  margin: 0;
  padding: 0;
  position: relative;
  top: 0;
}

       <canvas >

      </canvas>

Body:
When you fillText on the canvas, it stops being letters and starts being a letter-shaped collection of pixels. When you zoom in on it, the pixels become bigger. That's how a canvas works.

When you want the text to scale as a vector-based font and not as pixels, don't draw them on the canvas. You could create  HTML elements instead and place them on top of the canvas using CSS positioning. That way the rendering engine will render the fonts in a higher resolution when you zoom in and they will stay sharp. But anything you draw on the canvas will zoom accordingly.

But what I would recommend for this simple example is just doing it in html, css, and javascript like so:

var showText = function (target, message, index, interval) {
  if (index < message.length) {
    $(target).append(message[index++]);
    setTimeout(function () { showText(target, message, index, interval); }, interval);
  }
}

$(function () {

  showText("#text", "you can live a beatiful life with a postive mind", 0, 100);

});

#canvas{
  position: relative;
  width: 100%;
  height: 80vh;
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}

#text {

  position: absolute;
  top: 50%;
  left: 20px;
  color: #fff;
  font-size: 20px;

}

<div id="canvas">
  <p id="text"> </p>
</div>

I'll leave it up to you to position the text and whatnot but you can see in this example that you can make the text as small, or as big, as you want.

However

...if you still absolutely need it to be a canvas then the following example works. It works because the canvas is not being stretched by css, the width and height are predefined.

The canvas element runs independent from the device or monitor's pixel ratio.

On the iPad 3+, this ratio is 2. This essentially means that your 1000px width canvas would now need to fill 2000px to match it's stated width on the iPad display. Fortunately for us, this is done automatically by the browser. On the other hand, this is also the reason why you see less definition on images and canvas elements that were made to directly fit their visible area. Because your canvas only knows how to fill 1000px but is asked to draw to 2000px, the browser must now intelligently fill in the blanks between pixels to display the element at its proper size.

I would highly recommend you read this article from HTML5Rocks which explains in more detail how to create high definition elements.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "12px Arial";
ctx.fillText("Hello World",10,50);

#canvas{
  position: relative;
  overflow:hidden;
  background-image: url('http://linux2.gps.stthomas.edu/~algh3635/practice/proj/img/img4.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
}

<!DOCTYPE html>
<html>
<body>

<canvas id="canvas" width="800" height="500"
style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>

</body>
</html>


问:
Error timespan codeigniter
I'm trying to calcute the time between now and a given time. But when I use timespan I get this error:

Fatal error: Call to undefined function timespan() in /Applications/MAMP/htdocs/VERSIE0.1/application/views/welcome_message.php on line 54
A PHP Error was encountered
Severity: ErrorMessage: Call to undefined function timespan()Filename: views/welcome_message.phpLine Number: 54Backtrace:

```<code><span class="time"><?php

                                 $post_date = $t['story_date'];
                                   $now = date('Y-m-d H:i:s');

                                   echo timespan($post_date, $now);

                                   ?>
</span>
</code>```

答:
Right answer is to include the helper on your view file. Just load the helper

```<code>$this->load->helper('date');
</code>```

in your view, not in controller.

Title: Error timespan codeigniter

Body:
I'm trying to calcute the time between now and a given time. But when I use timespan I get this error:

Fatal error: Call to undefined function timespan() in /Applications/MAMP/htdocs/VERSIE0.1/application/views/welcome_message.php on line 54
A PHP Error was encountered
Severity: ErrorMessage: Call to undefined function timespan()Filename: views/welcome_message.phpLine Number: 54Backtrace:

<?php

                                 $post_date = $t['story_date'];
                                   $now = date('Y-m-d H:i:s');

                                   echo timespan($post_date, $now);

                                   ?>

Body:
Right answer is to include the helper on your view file. Just load the helper

$this->load->helper('date');

in your view, not in controller.


问:
python for loop after update step?
I copied this code from this website, and am just wondering about the grammar here? Why is the for loop under the 'i+1'?

```<code># centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}
</code>```

The code produce the following results:

```<code>>>> np.random.seed(200)
>>> k = 3
>>> # centroids[i] = [x, y]
... centroids = {
...     i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
...     for i in range(k)
... }
>>>
...
>>> centroids
{1: [26, 16], 2: [68, 42], 3: [55, 76]}
</code>```

答:
It's a dictionary comprehension (similar to a list comprehension), but the brackets make it seem like it's a normal dictionary initialisation.

Imagine if the brackets were on the same line:

```<code>centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}
</code>```

So it's just a more verbose way of saying:

```<code>centroids = {}
for i in range(k):
    centroids[i+1] = [np.random.randint(0, 80), np.random.randint(0, 80)]
</code>```

Title: python for loop after update step?

Body:
I copied this code from this website, and am just wondering about the grammar here? Why is the for loop under the 'i+1'?

# centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}

The code produce the following results:

>>> np.random.seed(200)
>>> k = 3
>>> # centroids[i] = [x, y]
... centroids = {
...     i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
...     for i in range(k)
... }
>>>
...
>>> centroids
{1: [26, 16], 2: [68, 42], 3: [55, 76]}

Body:
It's a dictionary comprehension (similar to a list comprehension), but the brackets make it seem like it's a normal dictionary initialisation.

Imagine if the brackets were on the same line:

centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}

So it's just a more verbose way of saying:

centroids = {}
for i in range(k):
    centroids[i+1] = [np.random.randint(0, 80), np.random.randint(0, 80)]


问:
How to build/extend a designer for Visual Studio
I just finished a quick intro in Linq2Sql and I decided to try my hands at it.
To my dismay, it appears the dbml designer supports SqlServer and SqlClient providers only.

After reading around, I found that I had to hand-code my classes in order to do Linq2Sql for other data providers like SQLite (which I use very often).

I wanted to know:

Are there any resources from which I can learn how to extend the dbml designer in Visual Studio?

If there is no way to extend the dbml designer, how do I build custom code generation designers for visual studio?

答:
You don't need to build or extend the designer. All you need is a valid DBML file.

I recommend to check DbLinq and it's source code:

[DbLinq] allows for Linq as well as DBML file
  generation using non-MS databases,
  such as MySQL, PostgreSQL, Oracle,
  Ingres, SQLite, FireBird, and SQL
  Server

BTW, are you targeting a particular DB server? (DbLinq is not probably the best choice in your case as it seems to be unmaintained since some time, and there are more and more vendor-provided LinqToSql/Entities providers...)


问:
Hide selected option from first dropdown on the next dropdown
I have a dynamic form that has dropdown select. I get the data from the option using ng repeat and then display it onthe dropdown. My code somewhat goes like this.

```<code><select name="languageCat" id="languageCat" ng-model="languageItem.languageCat" ng-required="true" required>
     <option value="">---Please select---</option>
     <option ng-repeat="item in scpLangCat" value="{{item.language_name}}">{{item.language_name}} - {{item.language_description}}</option>
 </select>
</code>```

I get the data from this API call.

```<code>Service.fetchDropdownData('language')
 .then(function(data){
     $scope.scpLangCat = data.data;
     localStorage.LanguageCategory = JSON.stringify(data.data);
 })
</code>```

This dropdown is in my dynamic form. I I selected a value in the first form in this dropdown, I need to hide that value on the second dropdown in the second form. The addition of dynamic form code is this.

```<code>scope.addLanguageItem = function() {
            $scope.LanguageFormData.language.push({ bName: null, pName: null, pNameSub: null, lFeature: null, lIngredient: null, lInstruction: null, languageCat: null });
            $scope.disablebrand=false;

    };
</code>```

How can I possibly do that?

答:
This can be solved by model-binding and ng-hide if the option is equal to some value (from the first dropdown). Assuming you are binding to "data" in the first dropdown, have you tried something along the lines of (in the second dropdown):</p>

```<code><option ng-repeat="item in scpLangCat" ng-hide="data.someValue == item.someValue" value="{{item.language_name}}">{{item.language_name}} - {{item.language_description}}</option>
</code>```

Body:
I have a dynamic form that has dropdown select. I get the data from the option using ng repeat and then display it onthe dropdown. My code somewhat goes like this.

<select name="languageCat" id="languageCat" ng-model="languageItem.languageCat" ng-required="true" required>
     <option value="">---Please select---</option>
     <option ng-repeat="item in scpLangCat" value="{{item.language_name}}">{{item.language_name}} - {{item.language_description}}</option>
 </select>

I get the data from this API call.

Service.fetchDropdownData('language')
 .then(function(data){
     $scope.scpLangCat = data.data;
     localStorage.LanguageCategory = JSON.stringify(data.data);
 })

This dropdown is in my dynamic form. I I selected a value in the first form in this dropdown, I need to hide that value on the second dropdown in the second form. The addition of dynamic form code is this.

scope.addLanguageItem = function() {
            $scope.LanguageFormData.language.push({ bName: null, pName: null, pNameSub: null, lFeature: null, lIngredient: null, lInstruction: null, languageCat: null });
            $scope.disablebrand=false;

    };

How can I possibly do that?

Body:
This can be solved by model-binding and ng-hide if the option is equal to some value (from the first dropdown). Assuming you are binding to "data" in the first dropdown, have you tried something along the lines of (in the second dropdown):

<option ng-repeat="item in scpLangCat" ng-hide="data.someValue == item.someValue" value="{{item.language_name}}">{{item.language_name}} - {{item.language_description}}</option>


问:
Python config parser to get all the values from a section?
I want to get all the values from a section using config parser

I used this but it gives only the first value

```<code>def ConfigSectionMap(section):
  dict1 = {}
  options = Config.options(section)
  for option in options:
    try:
      dict1[option] = Config.get(section, option)
      if dict1[option] == -1:
        DebugPrint("skip: %s" % option)
    except:
      print("exception on %s!" % option)
      dict1[option] = None
    return dict1

  Config = ConfigParser.ConfigParser()
  Config.read("/etc/harvest.conf")
  print ConfigSectionMap("files").values()
</code>```

答:
You can make it a list if ordering is important</p>

```<code>list(Config.items('Section'))
</code>```

Body:
I want to get all the values from a section using config parser

I used this but it gives only the first value

def ConfigSectionMap(section):
  dict1 = {}
  options = Config.options(section)
  for option in options:
    try:
      dict1[option] = Config.get(section, option)
      if dict1[option] == -1:
        DebugPrint("skip: %s" % option)
    except:
      print("exception on %s!" % option)
      dict1[option] = None
    return dict1

  Config = ConfigParser.ConfigParser()
  Config.read("/etc/harvest.conf")
  print ConfigSectionMap("files").values()

Body:
You can make it a list if ordering is important

list(Config.items('Section'))


问:
'override' can only be specified on class members - Xcode 9.0, Swift 4
I keep receiving the error message "'override' can only be specified on class members" in regards to the override func.  I have tried inserting a "}" before the override func but received even more errors.</p>

```<code>    import UIKit

    class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableVideo: UITableView!

        var partyRocks = [PartyRock]()

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return partyRocks.count
}

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            tableView.delegate = self
            tableView.dataSource = self

            if let cell = tableView.dequeueReusableCell(withIdentifier: "PartyCell", for: indexPath) as? PartyCell {

                let partyRock = partyRocks[indexPath.row]

                return cell
            } else {

            return UITableViewCell()
        }

           override func viewDidLoad() {
            super.viewDidLoad()

        }
        let p1 = PartyRock(imageURL: "https://www.lonelyplanet.com/travel-tips-and-articles/eight-amazing-cities-for-street-art/40625c8c-8a11-5710-a052-1479d276ed25", videoURL: "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/9f31OCHXAsI\" frameborder=\"0\" allowfullscreen></iframe>", videoTitle: "Stephen's Artwork")

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return partyRocks.count
        }

        }

    }
</code>```

答:
This shall rid you of the override error - some weird brace usage perhaps caused by inaccurate cut and pasting of your tableview methods...

```<code>import UIKit

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableVideo: UITableView!

    var partyRocks = [PartyRock]()

    let p1 = PartyRock(imageURL: "https://www.lonelyplanet.com/travel-tips-and-articles/eight-amazing-cities-for-street-art/40625c8c-8a11-5710-a052-1479d276ed25", videoURL: "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/9f31OCHXAsI\" frameborder=\"0\" allowfullscreen></iframe>", videoTitle: "Stephen's Artwork")

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return partyRocks.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.delegate = self
        tableView.dataSource = self

        if let cell = tableView.dequeueReusableCell(withIdentifier: "PartyCell", for: indexPath) as? PartyCell {
            let partyRock = partyRocks[indexPath.row]
            return cell
        } else {
            return UITableViewCell()
        }
    }
}
</code>```

Also beware you will encounter problems as you duplicated the numberofrowsinsection method twice in your viewcontroller so I deleted one...

Body:
I keep receiving the error message "'override' can only be specified on class members" in regards to the override func.  I have tried inserting a "}" before the override func but received even more errors.

    import UIKit

    class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableVideo: UITableView!

        var partyRocks = [PartyRock]()

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return partyRocks.count
}

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            tableView.delegate = self
            tableView.dataSource = self

            if let cell = tableView.dequeueReusableCell(withIdentifier: "PartyCell", for: indexPath) as? PartyCell {

                let partyRock = partyRocks[indexPath.row]

                return cell
            } else {

            return UITableViewCell()
        }

           override func viewDidLoad() {
            super.viewDidLoad()

        }
        let p1 = PartyRock(imageURL: "https://www.lonelyplanet.com/travel-tips-and-articles/eight-amazing-cities-for-street-art/40625c8c-8a11-5710-a052-1479d276ed25", videoURL: "", videoTitle: "Stephen's Artwork")

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return partyRocks.count
        }

        }

    }

Body:
This shall rid you of the override error - some weird brace usage perhaps caused by inaccurate cut and pasting of your tableview methods...

import UIKit

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableVideo: UITableView!

    var partyRocks = [PartyRock]()

    let p1 = PartyRock(imageURL: "https://www.lonelyplanet.com/travel-tips-and-articles/eight-amazing-cities-for-street-art/40625c8c-8a11-5710-a052-1479d276ed25", videoURL: "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/9f31OCHXAsI\" frameborder=\"0\" allowfullscreen></iframe>", videoTitle: "Stephen's Artwork")

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return partyRocks.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.delegate = self
        tableView.dataSource = self

        if let cell = tableView.dequeueReusableCell(withIdentifier: "PartyCell", for: indexPath) as? PartyCell {
            let partyRock = partyRocks[indexPath.row]
            return cell
        } else {
            return UITableViewCell()
        }
    }
}

Also beware you will encounter problems as you duplicated the numberofrowsinsection method twice in your viewcontroller so I deleted one...


问:
Different Java file name than the class name in Eclipse IDE
I am at the beginner level in JAVA and finding difficulty in understanding this scenario.

I have read that, the name of the class should match the name of the file that holds the program. In the attached image, i have two classes and the name of the class file is different than that of classes having the program.

When compiled in cmd it shows error as expected, but why the Eclipse compiler not giving any error here ?

Eclipse Image

答:
There is no error during compilation either in cmd or eclipse. Since you are new for this. You need to have a look what is public class and class.

I would rather said that the filename and the class name is must have same name but not strict. Well since you are beginner, just understand this. When you get familiar with java, you can go digging about the JLS

Here explanation that might be can help you to understand.

I create similar project like yours.

So you see there is a A.java but contain Box and BoxDemo class inside A.java. What happen when you compile? Below is the generated class file when you compile.

There is no A.class. Why? you should read about more public class and class just like i mention.

Below is the another example java class.

And below is the generated class files.

Hope this help you to understand how it works.


问:
Constraint check on date type - not working postgresql
While creating a table that tracks certain activity,
I am unable to setup the date constraint to work. I get an error (shown below).

My Query:

```<code>create table tracker (
    event varchar(25) primary key,
    create_ydt date not null check (create_ydt > ‘2010-01-01’)
);
</code>```

I get the following error
ERROR:  syntax error at or near ")"
LINE 3: create_ydt date not null check ()2010-01-01create_ydt >

答:
The problem is the single quotes -- yours are curly.  Try:

```<code>create table tracker (
    event varchar(25) primary key,
    create_ydt date not null check (create_ydt > '2010-01-01')
);
</code>```

Here is a rextester example.

Body:
While creating a table that tracks certain activity,
I am unable to setup the date constraint to work. I get an error (shown below).

My Query:

create table tracker (
    event varchar(25) primary key,
    create_ydt date not null check (create_ydt > ‘2010-01-01’)
);

I get the following error
ERROR:  syntax error at or near ")"
LINE 3: create_ydt date not null check ()2010-01-01create_ydt >

Body:
The problem is the single quotes -- yours are curly.  Try:

create table tracker (
    event varchar(25) primary key,
    create_ydt date not null check (create_ydt > '2010-01-01')
);

Here is a rextester example.


问:
Converting Fahrenheit to Celsius using while() loop PHP
I need to use the while() loop to print a table of Fahrenheit and Celsius temperature equivalents from –50 degrees F to 50 degrees F in 5-degree increments

To convert from Fahrenheit to Celsius I need subtract 32 from the temperature, multiply by 5, and divide by 9

Looks like conversion works but the Fahrenheit column remains the same

What's the issue here?

```<code><html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>
</head>
<body>

    <?php
        $min_fahr = -50;
        $max_fahr = 50;
        $celsius = ($max_fahr - 32) * 5 / 9;
    ?>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        while ($min_fahr <= $max_fahr) {

            print "<tr><td>$max_fahr</td><td>$celsius</td></tr>";

            $min_fahr += 5;
            $celsius -= 5;

        } ?>

    </table>

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

答:
@RobbyCornelissen Thank you, this code works perfectly fine

```<code><html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

    </table>

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

Body:
I need to use the while() loop to print a table of Fahrenheit and Celsius temperature equivalents from –50 degrees F to 50 degrees F in 5-degree increments

To convert from Fahrenheit to Celsius I need subtract 32 from the temperature, multiply by 5, and divide by 9

Looks like conversion works but the Fahrenheit column remains the same

What's the issue here?

    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

    <?php
        $min_fahr = -50;
        $max_fahr = 50;
        $celsius = ($max_fahr - 32) * 5 / 9;
    ?>

            Fahrenheit
            Celsius

        <?php
        while ($min_fahr <= $max_fahr) {

            print "
$max_fahr	$celsius
";

            $min_fahr += 5;
            $celsius -= 5;

        } ?>

Body:
@RobbyCornelissen Thank you, this code works perfectly fine

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>


问:
Xamarin Forms error diagnostic when laying out root page (Platform.LayoutRootPage)
When working on application written in Xamarin Forms, quite ofter I see the following exception which causes application to crash:

```<code>11-16 11:00:40.009 I/MonoDroid(16094): UNHANDLED EXCEPTION:
11-16 11:00:40.113 I/MonoDroid(16094): System.NullReferenceException: Object reference not set to an instance of an object.
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage (Xamarin.Forms.Page page, System.Int32 width, System.Int32 height) [0x0000c] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:290
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x00003] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x0000e] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
11-16 11:00:40.113 I/MonoDroid(16094):   at Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv, System.IntPtr native__this, System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in <e975227ac8644a30bb0866117325de0d>:0
11-16 11:00:40.113 I/MonoDroid(16094):   at (wrapper dynamic-method) System.Object:55caff06-7828-42f0-9580-cfb6673c4b5a (intptr,intptr,bool,int,int,int,int)
</code>```

Sometimes there is something wrong in XAML, sometimes, there is issue with view model binding (via attached property) but usually it takes me quite a lot of time to figure out where is the problem. Is there a way to get more information? Does Xamarin.Forms have a verbose logging which could be turned on to get more diagnostic information or something similar?

Also, in the MainActivity, I have the following code (using Serilog for logging):

```<code>    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        ...
        RegisterExceptionHandlers();
        ...

    }
    private void RegisterExceptionHandlers()
    {
        TaskScheduler.UnobservedTaskException += UnobservedException;
        AppDomain.CurrentDomain.UnhandledException += UnhandledException;
        AndroidEnvironment.UnhandledExceptionRaiser += UnhandledExceptionRaiser;
    }

    private void UnhandledException(object source, UnhandledExceptionEventArgs args)
    {
        Log.Error("Domain Exception from {source}: {exception}", source, args.ExceptionObject?.ToString() ?? "N/A");
    }
    private void UnobservedException(object source, UnobservedTaskExceptionEventArgs args)
    {
        Log.Error("TaskSchedulerException: {source} {exception}", source, args);
        if (!args.Observed)
            args.SetObserved();
    }

    private void UnhandledExceptionRaiser(object source, RaiseThrowableEventArgs args)
    {
        Log.Error("Exception from {source}: {exception}", source, args.Exception?.ToString() ?? "N/A");
    }
</code>```

But none of these events are triggered when the exception occurs. Does anybody knows why?

答:
Is there a way to get more information?

You could use : Diagnostic MSBuild Output

Here is the image :

But none of these events are triggered when the exception occurs.

If the error is something wrong with your XAML, it was a Compile Error, it cant trigger your ExceptionHandlers.

Body:
When working on application written in Xamarin Forms, quite ofter I see the following exception which causes application to crash:

11-16 11:00:40.009 I/MonoDroid(16094): UNHANDLED EXCEPTION:
11-16 11:00:40.113 I/MonoDroid(16094): System.NullReferenceException: Object reference not set to an instance of an object.
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage (Xamarin.Forms.Page page, System.Int32 width, System.Int32 height) [0x0000c] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:290
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x00003] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
11-16 11:00:40.113 I/MonoDroid(16094):   at Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout (System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x0000e] in D:\agent\_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
11-16 11:00:40.113 I/MonoDroid(16094):   at Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv, System.IntPtr native__this, System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in <e975227ac8644a30bb0866117325de0d>:0
11-16 11:00:40.113 I/MonoDroid(16094):   at (wrapper dynamic-method) System.Object:55caff06-7828-42f0-9580-cfb6673c4b5a (intptr,intptr,bool,int,int,int,int)

Sometimes there is something wrong in XAML, sometimes, there is issue with view model binding (via attached property) but usually it takes me quite a lot of time to figure out where is the problem. Is there a way to get more information? Does Xamarin.Forms have a verbose logging which could be turned on to get more diagnostic information or something similar?

Also, in the MainActivity, I have the following code (using Serilog for logging):

    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        ...
        RegisterExceptionHandlers();
        ...

    }
    private void RegisterExceptionHandlers()
    {
        TaskScheduler.UnobservedTaskException += UnobservedException;
        AppDomain.CurrentDomain.UnhandledException += UnhandledException;
        AndroidEnvironment.UnhandledExceptionRaiser += UnhandledExceptionRaiser;
    }

    private void UnhandledException(object source, UnhandledExceptionEventArgs args)
    {
        Log.Error("Domain Exception from {source}: {exception}", source, args.ExceptionObject?.ToString() ?? "N/A");
    }
    private void UnobservedException(object source, UnobservedTaskExceptionEventArgs args)
    {
        Log.Error("TaskSchedulerException: {source} {exception}", source, args);
        if (!args.Observed)
            args.SetObserved();
    }

    private void UnhandledExceptionRaiser(object source, RaiseThrowableEventArgs args)
    {
        Log.Error("Exception from {source}: {exception}", source, args.Exception?.ToString() ?? "N/A");
    }

But none of these events are triggered when the exception occurs. Does anybody knows why?


问:
Powermock/Easymock tests take 10x as long when not on VPN
I'll be as specific as I can with this...

Basically, the current unit tests for a large java project take around 19m30s to run when not on an OpenVPN network. When on the OpenVPN network, the tests take about 2m0s to run. Why is this?

From what I can tell, there are no external calls being made. One specific test takes 1m36s off VPN and then 1s when on VPN. Are the tests written inefficiently? Where should I start looking to improve the time it takes off the VPN? What could cause issues like this?

We are using Powermock and Easymock to do the unit tests. The specific test above uses an in-memory database.

答:
This has nothing to do with the mocking frameworks. However the test content can cause such thing. In general it is caused by code trying to do DNS resolution, even for localhost (InetAddress.getLocalHost().getHostAddress()).

Your best bet is to do a bunch of thread dumps during the test and look for network code like above.

The solution is usually to add a line in /etc/hosts to resolve quickly what your test is looking for. Or to fix the network but sometimes it's not that easy.


问:
Rendering multiple datasets in react native flatlist
I want to display images and other data in scrolling container.
I have two separate apis for image & other data.
I'm using react-native flatlist. How can I render two datasets at the same time.

This is my code:

```<code><FlatList
    horizontal={true}
    data={data1, data2}
    renderItem={this.renderData}
    keyExtractor={item => item.id}
    removeClippedSubviews={false}
    bounces={false}
    showsHorizontalScrollIndicator={false}/>

renderData = (item) => {
    <View></View>
}
</code>```

答:
If you want to render multiple arrays in flatlist you have to concatenate them. Change your data prop in your flatlist component to:

```<code>data={data1.concat(data2)}
</code>```

I'm assuming data1 and data2 are arrays because you haven't shown what they actually are. Best case scenario here is that the 2 arrays have the same data structure just different values.

Body:
I want to display images and other data in scrolling container.
I have two separate apis for image & other data.
I'm using react-native flatlist. How can I render two datasets at the same time.

This is my code:

<FlatList
    horizontal={true}
    data={data1, data2}
    renderItem={this.renderData}
    keyExtractor={item => item.id}
    removeClippedSubviews={false}
    bounces={false}
    showsHorizontalScrollIndicator={false}/>

renderData = (item) => {
    <View></View>
}

Body:
If you want to render multiple arrays in flatlist you have to concatenate them. Change your data prop in your flatlist component to:

data={data1.concat(data2)}

I'm assuming data1 and data2 are arrays because you haven't shown what they actually are. Best case scenario here is that the 2 arrays have the same data structure just different values.


问:
Can we transpile dart code to multiple JS files?
Let's say that a developer has created a general-purpose Dart library, aimed at the client, that contains a large number of class and functionality definitions, of which only a small subset is ever expected to be used in a single web page.

As a Javascript example, Mathjax provides files that contain a large amount of functionality related to displaying mathematical expressions in the browser, though any given web page displaying mathematical expressions is likely to only use a very small amount of the functionality defined by Mathjax. Thus, what page authors tend to do is to link each page they create to a single copy of the large, general-purpose JS file (in the page header, for example) and to then write their own, usually relatively small JS files defining behaviour particular to the page. They can thus potentially have hundreds of pages each linking to a single general-purpose JS file.

When we transpile Dart to JS, however, the output is a single, large JS file that appears to contain the functionality of any dependencies along with the behaviour desired for the particular page. If we had hundreds of pages, each linked to their own dart2js-produced JS file, we appear to have a tremendous amount of redundancy in the code. Further, if we need to make a change to the general-purpose library, it seems that we would have to regenerate the JS for each of the pages. (Or maybe I completely misunderstand things.)

My question is: is it possible to transpile Dart code to multiple JS files? For example, Dart code for a given page might be transpiled into one JS file containing the dependency functionality (that many pages can link to) and one small JS file defining the behaviour particular to the page?

答: Sounds like you should rethink your website as a single-page app.  Then, you get a payload that can process any of your pages, but is still tree-shaken to have only exactly what you need for all of them.


问:
How to Disable UWP App Suspension?
I am using C# to develop a UWP app for Windows 10 running only on desktop computers, targeting platform version 10.0.14393.0. Due to business requirements, the app lifecycle must behave like a traditional Win32 application.

Therefore, I followed the recommendation from this article to request an ExtendedExecutionSession  with ExtendedExecutionReason.Unspecified. I also configured Windows to never sleep and never hibernate.

Still, on rare occasions, Windows will revoke the extended execution session with reason SystemPolicy and then proceed to suspend the UWP app.

Two questions:

How can I get more information (system logs? event logs?) regarding what led to Windows revoking the extended execution session?

How can I get rid of these rare cases of suspensions so that the UWP app lifecycle behaves exactly like Win32 applications (that is, stay running until user explicitly stops it from running)?

Thanks!

答:
Use Visual Studio debug mode to run the app, and the app will never run into a suspended state. It is kept awakened by Visual Studio.

Ahh, this is just a joke.

I think unfortunately what you expect is a behavior that is in contradiction to the design principles of UWP.

The system reserves the right to suspend a background app after some “deferal”. If you request an extended execution session, you have to prepare for the revocation as well, being connected to wall power does not keep the app running forever.

Option 1 is resort to desktop app, though this may not be an option. If you get this requirement because users like UWP but doesn’t like the idea of “suspended” (What the... suspended??), I am afraid you cannot fulfill this requirement.

Option 2 is... is there any real task that has to be kept running even the app is switched to the background?  If the task needs to run periodically, like checking inbox of a mail account, you can use some kind of timer triggered background task.

Option 3: Think about kiosk mode, there is only one app allowed to run on the device, so it cannot be possibly switched to the background and put into suspension.

Title: How to Disable UWP App Suspension?