问:
recyclerview not working in fragment
I have a tabed activity , im trying make a recyclerview in activity's fragment , when i Declarate recyclerview in oncreate in runtime gives below error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.daneshhamrah.konkuri/com.daneshhamrah.konkuri.Soalate_Konkur}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
</code>```

and when i Declarate recyclerview in oncreateview in runtime gives below error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
</code>```

this error is for recyclerview items layout

how can i sove this problem ?

this is my fragment xml layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.daneshhamrah.konk.Soa_Konk$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:focusableInTouchMode="true">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="10dp"
                >

                <TextView
                    android:id="@+id/soakonk_frag_txt1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_margin="5dp"
                    android:text="ss" />

                <TextView
                    android:id="@+id/soakonk_frag_txt2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:gravity="center"
                    android:text="yy" />

                <TextView
                    android:text="pp"
                    android:id="@+id/soakonk_frag_txt3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_alignParentRight="true"/>

            </RelativeLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/soakonk_frag_rec"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp">

        </android.support.v7.widget.RecyclerView>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

</RelativeLayout>
</code>```

this is recyclerview items layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/sar_list_single_mainlayout">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="3dp"
    android:foreground="?attr/selectableItemBackground">

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
        >

        <Button
            android:id="@+id/soakonk_item_soabtn"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:background="@drawable/ic_soa_g"
            android:layout_margin="5dp"
            android:layout_alignParentLeft="true"/>

        <TextView
            android:id="@+id/soakonk_item_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#000000" />

        <Button
            android:id="@+id/soakonk_item_pasbtn"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:background="@drawable/ic_pas_g"
            android:layout_margin="5dp"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

</LinearLayout>
</code>```

this is java fragment activiy code:

```<code>public class Soa_Konk extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

public static class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_soa__konk, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        TextView tv1 ,tv2 ,tv3 ;
        Typeface vazirTf = Typeface.createFromAsset(getActivity().getAssets(),"font/Vazir.ttf");
        tv1= (TextView)rootView.findViewById(R.id.soakonk_frag_txt1);
        tv2= (TextView)rootView.findViewById(R.id.soakonk_frag_txt2);
        tv3= (TextView)rootView.findViewById(R.id.soakonk_frag_txt3);
        tv1.setTypeface(vazirTf);
        tv2.setTypeface(vazirTf);
        tv3.setTypeface(vazirTf);

        RecyclerView mRecyclerView = (RecyclerView)rootView.findViewById(R.id.soakonk_frag_rec) ;
        RecyclerView.LayoutManager mLayoutManager= new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        String[] mArrayNames = {"95","94","93","92","91","90","89","88","87","86","85","84","83","82","81","80","79"};
        RecyclerView.Adapter  mAdapter = new MyAdapterSoalateKonkur(mArrayNames,getActivity());
        mRecyclerView.setAdapter(mAdapter);

        return rootView;
    }
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Tab A";
            case 1:
                return "Tab B";
            case 2:
                return "Tab C";
            case 3:
                return "Tab D";
        }
        return null;
    }
}
}
</code>```

答: When the Exception occurs for the RecyclerView items, have a look at your MyAdapter class and your related ViewHolder and check if you correctly get your TextView there.

Title: recyclerview not working in fragment

Body:
I have a tabed activity , im trying make a recyclerview in activity's fragment , when i Declarate recyclerview in oncreate in runtime gives below error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.daneshhamrah.konkuri/com.daneshhamrah.konkuri.Soalate_Konkur}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference

and when i Declarate recyclerview in oncreateview in runtime gives below error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference

this error is for recyclerview items layout

how can i sove this problem ?

this is my fragment xml layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.daneshhamrah.konk.Soa_Konk$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:focusableInTouchMode="true">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="10dp"
                >

                <TextView
                    android:id="@+id/soakonk_frag_txt1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_margin="5dp"
                    android:text="ss" />

                <TextView
                    android:id="@+id/soakonk_frag_txt2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:gravity="center"
                    android:text="yy" />

                <TextView
                    android:text="pp"
                    android:id="@+id/soakonk_frag_txt3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:layout_alignParentRight="true"/>

            </RelativeLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/soakonk_frag_rec"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp">

        </android.support.v7.widget.RecyclerView>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

</RelativeLayout>

this is recyclerview items layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/sar_list_single_mainlayout">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="3dp"
    android:foreground="?attr/selectableItemBackground">

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
        >

        <Button
            android:id="@+id/soakonk_item_soabtn"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:background="@drawable/ic_soa_g"
            android:layout_margin="5dp"
            android:layout_alignParentLeft="true"/>

        <TextView
            android:id="@+id/soakonk_item_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#000000" />

        <Button
            android:id="@+id/soakonk_item_pasbtn"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:background="@drawable/ic_pas_g"
            android:layout_margin="5dp"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

</LinearLayout>

this is java fragment activiy code:

public class Soa_Konk extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

public static class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_soa__konk, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        TextView tv1 ,tv2 ,tv3 ;
        Typeface vazirTf = Typeface.createFromAsset(getActivity().getAssets(),"font/Vazir.ttf");
        tv1= (TextView)rootView.findViewById(R.id.soakonk_frag_txt1);
        tv2= (TextView)rootView.findViewById(R.id.soakonk_frag_txt2);
        tv3= (TextView)rootView.findViewById(R.id.soakonk_frag_txt3);
        tv1.setTypeface(vazirTf);
        tv2.setTypeface(vazirTf);
        tv3.setTypeface(vazirTf);

        RecyclerView mRecyclerView = (RecyclerView)rootView.findViewById(R.id.soakonk_frag_rec) ;
        RecyclerView.LayoutManager mLayoutManager= new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        String[] mArrayNames = {"95","94","93","92","91","90","89","88","87","86","85","84","83","82","81","80","79"};
        RecyclerView.Adapter  mAdapter = new MyAdapterSoalateKonkur(mArrayNames,getActivity());
        mRecyclerView.setAdapter(mAdapter);

        return rootView;
    }
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Tab A";
            case 1:
                return "Tab B";
            case 2:
                return "Tab C";
            case 3:
                return "Tab D";
        }
        return null;
    }
}
}


来源: stackexchange

问:
Return String from a webmethod instead of a dataset.
How would I refactor this to get it to return a string not a dataset?      </p>

```<code>[WebMethod]
public DataSet GetPONumber(string Database)
{
    SqlConnection sqlConn = new SqlConnection();

    sqlConn.ConnectionString = GetConnString(Database);

    // build query
    string strSQL = @" A SELECT QUERY!!!!! ";

    SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);
    DataSet ds = new DataSet();
    da.Fill(ds, "NEWPO");

    return (ds);
}
</code>```

答:
```<code>//Use an SqlCommand and the ExecuteScalar method.
//Cast returnValue to known object.
SqlCommand command = sqlConn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = @" A SELECT QUERY!!!!! ";
sqlConn.Open();
object returnValue = command.ExecuteScalar();
command.Dispose();
return returnValue.ToString();
</code>```

OwnerDisplayName: MartGriff

ContentLicense: CC BY-SA 3.0

Body:
How would I refactor this to get it to return a string not a dataset?

[WebMethod]
public DataSet GetPONumber(string Database)
{
    SqlConnection sqlConn = new SqlConnection();

    sqlConn.ConnectionString = GetConnString(Database);

    // build query
    string strSQL = @" A SELECT QUERY!!!!! ";

    SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);
    DataSet ds = new DataSet();
    da.Fill(ds, "NEWPO");

    return (ds);
}

OwnerDisplayName: zowat

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: zowat


问:
How to reuse exception throwing code to return a boolean?
Lets say I have a block of if statements that throw an exception if the conditional is true. How can I create a method that uses those same conditionals, but returns a true or false instead of throwing the exceptions. ie, if an exception is thrown, return false; if an exception isnt thrown then return true. I want to reuse as much of the code as possible.

I also would want to try to avoid simply catching all exceptions I'm throwing.

edit:sorry typos

答: Move the code into a function that returns the boolean, then change the original function to call the new one and throw an exception if it returns false.


问:
Disabling the scrollbar with active menu overlay
I'm having trouble with disabling the scroll bar on my website when the menu overlay is active (class: .overlay). I created a menu overlay and I would like the scroll bar to be disabled when the overlay is visible. Similar to this Just disable scroll not hide it?

So I would like to disable the scroll bar, not hide it.
What I understand so far: Basically what I need to do is to add inline CSS to the html when the overlay is on display: block and remove the inline CSS when the overlay is on display: none;

I tried multiple solutions given on Stackoverflow, but no result so far. This was my latest solution, which didnt work in the end:

```<code>if( $(".overlay").css('display') == 'block') {

$('html').css('position','fixed');
$('html').css('overflow-y','scroll');
$('html').css('width','100%');

} else {
$('html').css('position','');
$('html').css('overflow-y','');
$('html').css('width','');
}
</code>```

Above is based on this: div display if block jquery

Here is my website (under development):

http://www.wouterpasman.com/view/

The menu overlay is activated when you click the menu button in the top right corner. Goal: When the overlay is active, the scroll bar should be temporarily disabled, but still visible.

Thanks for your assistance!

答:
You can simply add an overflow hidden and auto :
</p>

```<code>if( $(".overlay").css('display') == 'block') {
   $('html').css('position','fixed');
   $('html').css('overflow-y','hidden');
   $('html').css('width','100%');
} else {
   $('html').css('position','');
   $('html').css('overflow-y','');
   $('html').css('width','');
}
</code>```

Body:
I'm having trouble with disabling the scroll bar on my website when the menu overlay is active (class: .overlay). I created a menu overlay and I would like the scroll bar to be disabled when the overlay is visible. Similar to this Just disable scroll not hide it?

So I would like to disable the scroll bar, not hide it.
What I understand so far: Basically what I need to do is to add inline CSS to the html when the overlay is on display: block and remove the inline CSS when the overlay is on display: none;

I tried multiple solutions given on Stackoverflow, but no result so far. This was my latest solution, which didnt work in the end:

if( $(".overlay").css('display') == 'block') {

$('html').css('position','fixed');
$('html').css('overflow-y','scroll');
$('html').css('width','100%');

} else {
$('html').css('position','');
$('html').css('overflow-y','');
$('html').css('width','');
}

Above is based on this: div display if block jquery

Here is my website (under development):

http://www.wouterpasman.com/view/

The menu overlay is activated when you click the menu button in the top right corner. Goal: When the overlay is active, the scroll bar should be temporarily disabled, but still visible.

Thanks for your assistance!

Body:
You can simply add an overflow hidden and auto :

if( $(".overlay").css('display') == 'block') {
   $('html').css('position','fixed');
   $('html').css('overflow-y','hidden');
   $('html').css('width','100%');
} else {
   $('html').css('position','');
   $('html').css('overflow-y','');
   $('html').css('width','');
}


问:
chrome.runtime.onMessage undefined in content script
manifest,json

```<code>{
"background": {
    "scripts": ["jquery-3.2.1.min.js", "background.js"]
},
"content_scripts": [{
    "all_frames": true,
    "run_at": "document_start",
    "matches": [
        "http://*/*",
        "https://*/*",
        "file:///*"
    ],
    "css": ["mystyles.css"],
    "js": ["jquery-3.2.1.min.js", "myscript.js"]
}],
"permissions": [
    "<all_urls>",
    "contextMenus",
    "storage",
    "clipboardWrite",
    "clipboardRead",
    "activeTab",
    "identity",
    "webRequest",
    "webRequestBlocking"
],
"web_accessible_resources": [
    "*.png"
]}
</code>```

content script

```<code>chrome.runtime.onMessage(function(message, sender, sendResponse){
console.log(message);});
</code>```

chrome console

my chrome version : 58.0.3029.110 (64-bit)
why chrome.runtime.onMessage is undefined in content_script?
Please tell me how to solve this problem~:)

Whether there are other ways to achieve that background sendMessage to content script?

答:
chrome.runtime.onMessage is not a function indeed, it's an Event object that provides addListener function method:

```<code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  ...
});
</code>```

Body:
manifest,json

{
"background": {
    "scripts": ["jquery-3.2.1.min.js", "background.js"]
},
"content_scripts": [{
    "all_frames": true,
    "run_at": "document_start",
    "matches": [
        "http://*/*",
        "https://*/*",
        "file:///*"
    ],
    "css": ["mystyles.css"],
    "js": ["jquery-3.2.1.min.js", "myscript.js"]
}],
"permissions": [
    "<all_urls>",
    "contextMenus",
    "storage",
    "clipboardWrite",
    "clipboardRead",
    "activeTab",
    "identity",
    "webRequest",
    "webRequestBlocking"
],
"web_accessible_resources": [
    "*.png"
]}

content script

chrome.runtime.onMessage(function(message, sender, sendResponse){
console.log(message);});

chrome console

my chrome version : 58.0.3029.110 (64-bit)
why chrome.runtime.onMessage is undefined in content_script?
Please tell me how to solve this problem~:)

Whether there are other ways to achieve that background sendMessage to content script?

Body:
chrome.runtime.onMessage is not a function indeed, it's an Event object that provides addListener function method:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  ...
});


问:
How do you compare a gam model with a gamm model? (mgcv)
I've fit two models, one with gam and another with gamm.

```<code>gam(y ~ x, family= betar)

gamm(y ~ x)
</code>```

So the only difference is the distributional assumption. I use betar with gam and normal with gamm.

I would like to compare these two models, but I am guessing AIC will not work since the two models are based on different methods? Is there then some other suitable estimate I can use for comparison? I know I could just fit the second with gam, but let's ignore that for the sake of this question.

答:
AIC is independent of the type of model used as soon as y is exactly the same observation to be predicted. This is only a computation of deviance explained penalised by the number of parameters fitted.

However, depending on the goal of your model, if you want to be able to use the model for prediction for instance, you should use validation to compare model performance. 10-fold cross-validation would be a good idea for instance.

ContentLicense: CC BY-SA 4.0

Body:
I've fit two models, one with gam and another with gamm.

gam(y ~ x, family= betar)

gamm(y ~ x)

So the only difference is the distributional assumption. I use betar with gam and normal with gamm.

I would like to compare these two models, but I am guessing AIC will not work since the two models are based on different methods? Is there then some other suitable estimate I can use for comparison? I know I could just fit the second with gam, but let's ignore that for the sake of this question.


问:
InputStream printing weird character
I am try to receive data from my Arduino using an InputStream but for some reason I get this as the output.

ààà  à àà  ààà  a  ààà à àà ààààà  àààààà  à àà  ààà  à  ààà à àà ààààà  àààààà à àà  ààà  à

This is my code for receiving data:

```<code>package midistep;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public OutputStream out1;
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                out1=out;
                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
                    System.out.print(new String(buffer,0,len));
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        public OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }
    public void writetoport(int Steps) {

        try {
                out1.write(Steps);
                out1.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

And my Arduino code:

```<code>int received = 0;
void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  delay(1000);
  Serial.println("Hello world");
  if (Serial.available() > 0) {
    received = Serial.read();
    if (received > 1000) {
      int speed = received;
      String tempstring = String(speed);
      tempstring.substring(1);
      speed = tempstring.toInt();
      Serial.println("gotit" + speed);
    }
    else if (received = 1) {
      Serial.print("I received something >");
      Serial.print(received);
      Serial.println("<");
      digitalWrite(LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}
</code>```

Hopefully this is a simple problem. Thank you

答:
You have set the wrong baud rate. You Java code has

```<code> serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
</code>```

but in your Arduino sketch you have

```<code> Serial.begin(9600);
</code>```

The baud rates must be identical else you'll get transmission errors.

Title: InputStream printing weird character

Body:
I am try to receive data from my Arduino using an InputStream but for some reason I get this as the output.

ààà  à àà  ààà  a  ààà à àà ààààà  àààààà  à àà  ààà  à  ààà à àà ààààà  àààààà à àà  ààà  à

This is my code for receiving data:

package midistep;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public OutputStream out1;
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                out1=out;
                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
                    System.out.print(new String(buffer,0,len));
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        public OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }
    public void writetoport(int Steps) {

        try {
                out1.write(Steps);
                out1.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And my Arduino code:

int received = 0;
void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  delay(1000);
  Serial.println("Hello world");
  if (Serial.available() > 0) {
    received = Serial.read();
    if (received > 1000) {
      int speed = received;
      String tempstring = String(speed);
      tempstring.substring(1);
      speed = tempstring.toInt();
      Serial.println("gotit" + speed);
    }
    else if (received = 1) {
      Serial.print("I received something >");
      Serial.print(received);
      Serial.println("<");
      digitalWrite(LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

Hopefully this is a simple problem. Thank you

Body:
You have set the wrong baud rate. You Java code has

 serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

but in your Arduino sketch you have

 Serial.begin(9600);

The baud rates must be identical else you'll get transmission errors.


问:
calculate month and day using millisecond in javascript
i want to calculate the remaining month and days by using the millisecond..

the below code ..i calculate the number of year when user enter the birth date but how can i calculate remaining month and days.

<!DOCTYPE html>

A Web Page

<input type="text "id="demo">
<button type="button" onclick="myFunction()">Try it</button>

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
function myFunction() {
 var a=document.getElementById("demo").value;
 var birthdate = new Date(a);
 var cur = new Date();
 var diff = cur-birthdate; // This is the difference in milliseconds
 var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
     var month=;//i want to calcuate this using millsecond only
     var days=;//i want to calcuate this using millsecond only

 alert("Hi ..you are "+ age+"and"+month+"and"+days+" year old Now");
}
</script></code>```

help mi thanks..

答:
Months and dys are calculated from the remainder of the division</p>

```<code>var remainder = diff % 31557600000;
var month = Math.floor(remainder / (1000*60*60*24*30.5));
var remainder2 = remainder % (1000*60*60*24*30.5);
var days = Math.floor(remainder2 / (1000*60*60*24));
</code>```

Body:
i want to calculate the remaining month and days by using the millisecond..

the below code ..i calculate the number of year when user enter the birth date but how can i calculate remaining month and days.

<!DOCTYPE html>

A Web Page

<input type="text "id="demo">
<button type="button" onclick="myFunction()">Try it</button>

help mi thanks..

Body:
Months and dys are calculated from the remainder of the division

var remainder = diff % 31557600000;
var month = Math.floor(remainder / (1000*60*60*24*30.5));
var remainder2 = remainder % (1000*60*60*24*30.5);
var days = Math.floor(remainder2 / (1000*60*60*24));


问:
Some questions on Android GPS and SQLite
1)I have the following code (originally clicked is false):

```<code>void configure_button(){
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                    ,10);
        }
        return;
    }
    // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            if (clicked){
                locationManager.removeUpdates(listener);
            }
            else {
                locationManager.requestLocationUpdates("gps", 5000, 0, listener);
            clicked=true;}
            distance=0;
            clicked=true;
            preloc=null;
            time1=c.get(Calendar.SECOND);
        }
    });
}
</code>```

Android studio shows this error:

```<code>Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException.
</code>```

However, if  locationManager.requestLocationUpdates("gps", 5000, 0, listener);
is outside and before the if, the code works fine. What is the problem?

2) How do I notify android that it is time to upgrade an SQLite Database? In other words, when does Android call onUpgrade?

3) When coordinates are found, they have many fractional points, but when they are stored and retrived from and SQLite database (stored as two floats), they only have 4 . For example, 41.13507153... will be stored as 41.1350. Is that normal? Is this enough to get an accurate location?

答:
1) I believe that you can just redo the check in the else clause i.e. it's saying that it can't be sure that the checking code will always be undertaken because you are setting a listener which runs independently of the code that sets the listener.

I'd suggest having a read of Android check permission for LocationManager.

2) How do I notify android that it is time to upgrade an SQLite
  Database? In other words, when does Android call onUpgrade?

onUpgrade is called when the version number is increased, there is also an onDowngrade which is called when the version number is reduced.

In short YOU specify when by changing the version number passed, as the 4th parameter, to the SQLiteOpenHelper's super.

Example 1 Change DBVERSION to be 2 for onUpgrade to be called.

```<code>public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    .....
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ''''
    }
</code>```

Example 2 Version passed via the helper

```<code>public class DBHelper extends SQLiteOpenHelper {

        public DBHelper(Context context, String dbname, int version) {
            super(context, dbname, null, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        .....
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        ''''
        }
</code>```

Code in activity; changing DBVERSION will pass the new version through to the helper and call onUpgrade.

```<code>public static final String DBNAME = "mydb";
public static final String DBVERSION = 1;

DBHleper myhelper = new DBHelper(this,DBNAME,DBVERSION);
</code>```

One thing to be wary of is that many tutorials have code like :-

```<code>    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TblLogin);
        onCreate(db);
    }
</code>```

Which would effectively destroy any existing data. So if you are upgrading a database and you don't want to lose the data, you have to include code that caters for this as the above code will only change the structure.

3) Is that normal?

According to the SQLite documentation, as per link:-

REAL. The value is a floating point value, stored as an 8-byte IEEE
  floating point number.

A column will be REAL, when REAL, DOUBLE, DOUBLE PRECISION or FLOAT is specified as the column type (actually the following applies If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.
 BUT this is the 4th rule; others rules such as rule 1 for INT would have INTREAL be INTEGER).

This might be of interest Datatypes In SQLite Version 3 , which is the basis of the above.

What you might be doing is getting the data from the cursor via cursor.getString(columnindex), which I believe reduces the precision. To get a higher precision then use getDouble(columnindex);

e.g. I did (hastily put together):-

```<code>MyDBHelper mydbhelper = new MyDBHelper(this);
    mydbhelper.insertRow(1.3);
    mydbhelper.insertRow(1);
    mydbhelper.insertRow(5.674389123459834);

    Cursor getfloats = mydbhelper.getAllMyFloats();
    Log.d("TESTFLOAT","Rows returned from getALlFloats = " + getfloats.getCount());
    while (getfloats.moveToNext()) {
        Log.d("TESTFLOAT","Via getString = " + getfloats.getString(getfloats.getColumnIndex(mydbhelper.MYFLOATCOL)));
        Log.d("TESTFLOAT","Via getFloat = " + Float.toHexString(
                getfloats.getFloat(
                        getfloats.getColumnIndex(
                                mydbhelper.MYFLOATCOL
                        )
                )
        ));
        Log.d("TESTFLOAT","Via getDouble = " +Double.toString(
                getfloats.getDouble(
                        getfloats.getColumnIndex(
                                mydbhelper.MYFLOATCOL
                        )

                )));
    }
    getfloats.close();
</code>```

MyDBHelper being :-

```<code>public class MyDBHelper extends SQLiteOpenHelper {

    public static final String DBNname = "mydb";
    public static final int DBVersion = 1;
    public static final String TESTFLOATTABLE = "testfloat";
    public static final String STDIDCOL = "_id INTEGER PRIMARYKEY";
    public static final String MYFLOATCOL = "myfloat";
    public static final String MYFLOATTYPE = " FLOAT DEFAULT 0.0";

    public MyDBHelper(Context context) {
        super(context,DBNname,null,DBVersion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " +
                TESTFLOATTABLE +
                "(" +
                STDIDCOL +
                "," +
                MYFLOATCOL +
                MYFLOATTYPE +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldeversion, int newversion) {

    }

    public long insertRow(double myfloatvalue) {
        long rv;
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(MYFLOATCOL,myfloatvalue);
        rv = db.insert(TESTFLOATTABLE,null,cv);
        return rv;
    }

    public Cursor getAllMyFloats() {
        Cursor rv;
        SQLiteDatabase db = getReadableDatabase();
        rv = db.query(TESTFLOATTABLE,null,null,null,null,null,null);
        return rv;
    }
}
</code>```

The results from a first run (subsequent runs will add another set of rows and so on) :-

```<code>06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Rows returned from getALlFloats = 3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 1.3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.4cccccp0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 1.3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 1
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.0p0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 1.0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 5.67439
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.6b293p2
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 5.674389123459834
</code>```

So looking at the last 3 rows, getString, gets to 5dp, whilst getDouble gets to 15dp here (not sure of the max precision, a quick look suggests 15-17).

Body:
1)I have the following code (originally clicked is false):

void configure_button(){
    // first check for permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                    ,10);
        }
        return;
    }
    // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //noinspection MissingPermission
            if (clicked){
                locationManager.removeUpdates(listener);
            }
            else {
                locationManager.requestLocationUpdates("gps", 5000, 0, listener);
            clicked=true;}
            distance=0;
            clicked=true;
            preloc=null;
            time1=c.get(Calendar.SECOND);
        }
    });
}

Android studio shows this error:

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException.

However, if  locationManager.requestLocationUpdates("gps", 5000, 0, listener);
is outside and before the if, the code works fine. What is the problem?

2) How do I notify android that it is time to upgrade an SQLite Database? In other words, when does Android call onUpgrade?

3) When coordinates are found, they have many fractional points, but when they are stored and retrived from and SQLite database (stored as two floats), they only have 4 . For example, 41.13507153... will be stored as 41.1350. Is that normal? Is this enough to get an accurate location?

Body:
1) I believe that you can just redo the check in the else clause i.e. it's saying that it can't be sure that the checking code will always be undertaken because you are setting a listener which runs independently of the code that sets the listener.

I'd suggest having a read of Android check permission for LocationManager.

2) How do I notify android that it is time to upgrade an SQLite
  Database? In other words, when does Android call onUpgrade?

onUpgrade is called when the version number is increased, there is also an onDowngrade which is called when the version number is reduced.

In short YOU specify when by changing the version number passed, as the 4th parameter, to the SQLiteOpenHelper's super.

Example 1 Change DBVERSION to be 2 for onUpgrade to be called.

public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    .....
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ''''
    }

Example 2 Version passed via the helper

public class DBHelper extends SQLiteOpenHelper {

        public DBHelper(Context context, String dbname, int version) {
            super(context, dbname, null, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        .....
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        ''''
        }

Code in activity; changing DBVERSION will pass the new version through to the helper and call onUpgrade.

public static final String DBNAME = "mydb";
public static final String DBVERSION = 1;

DBHleper myhelper = new DBHelper(this,DBNAME,DBVERSION);

One thing to be wary of is that many tutorials have code like :-

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TblLogin);
        onCreate(db);
    }

Which would effectively destroy any existing data. So if you are upgrading a database and you don't want to lose the data, you have to include code that caters for this as the above code will only change the structure.

3) Is that normal?

According to the SQLite documentation, as per link:-

REAL. The value is a floating point value, stored as an 8-byte IEEE
  floating point number.

A column will be REAL, when REAL, DOUBLE, DOUBLE PRECISION or FLOAT is specified as the column type (actually the following applies If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.
 BUT this is the 4th rule; others rules such as rule 1 for INT would have INTREAL be INTEGER).

This might be of interest Datatypes In SQLite Version 3 , which is the basis of the above.

What you might be doing is getting the data from the cursor via cursor.getString(columnindex), which I believe reduces the precision. To get a higher precision then use getDouble(columnindex);

e.g. I did (hastily put together):-

MyDBHelper mydbhelper = new MyDBHelper(this);
    mydbhelper.insertRow(1.3);
    mydbhelper.insertRow(1);
    mydbhelper.insertRow(5.674389123459834);

    Cursor getfloats = mydbhelper.getAllMyFloats();
    Log.d("TESTFLOAT","Rows returned from getALlFloats = " + getfloats.getCount());
    while (getfloats.moveToNext()) {
        Log.d("TESTFLOAT","Via getString = " + getfloats.getString(getfloats.getColumnIndex(mydbhelper.MYFLOATCOL)));
        Log.d("TESTFLOAT","Via getFloat = " + Float.toHexString(
                getfloats.getFloat(
                        getfloats.getColumnIndex(
                                mydbhelper.MYFLOATCOL
                        )
                )
        ));
        Log.d("TESTFLOAT","Via getDouble = " +Double.toString(
                getfloats.getDouble(
                        getfloats.getColumnIndex(
                                mydbhelper.MYFLOATCOL
                        )

                )));
    }
    getfloats.close();

MyDBHelper being :-

public class MyDBHelper extends SQLiteOpenHelper {

    public static final String DBNname = "mydb";
    public static final int DBVersion = 1;
    public static final String TESTFLOATTABLE = "testfloat";
    public static final String STDIDCOL = "_id INTEGER PRIMARYKEY";
    public static final String MYFLOATCOL = "myfloat";
    public static final String MYFLOATTYPE = " FLOAT DEFAULT 0.0";

    public MyDBHelper(Context context) {
        super(context,DBNname,null,DBVersion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " +
                TESTFLOATTABLE +
                "(" +
                STDIDCOL +
                "," +
                MYFLOATCOL +
                MYFLOATTYPE +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldeversion, int newversion) {

    }

    public long insertRow(double myfloatvalue) {
        long rv;
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(MYFLOATCOL,myfloatvalue);
        rv = db.insert(TESTFLOATTABLE,null,cv);
        return rv;
    }

    public Cursor getAllMyFloats() {
        Cursor rv;
        SQLiteDatabase db = getReadableDatabase();
        rv = db.query(TESTFLOATTABLE,null,null,null,null,null,null);
        return rv;
    }
}

The results from a first run (subsequent runs will add another set of rows and so on) :-

06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Rows returned from getALlFloats = 3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 1.3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.4cccccp0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 1.3
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 1
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.0p0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 1.0
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getString = 5.67439
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getFloat = 0x1.6b293p2
06-05 10:49:35.279 21951-21951/mjt.testvcsuse D/TESTFLOAT: Via getDouble = 5.674389123459834

So looking at the last 3 rows, getString, gets to 5dp, whilst getDouble gets to 15dp here (not sure of the max precision, a quick look suggests 15-17).


问:
How to deseralize an XML thats a DataTable?
I have an XML file, and when I used XSD tool to create a class object from the XML, I get a message saying "A column named 'link' already belongs to this DataTable: cannot set a nested table to the same name.

I want to know how I can correctly deserialize this XML file so that I can display the data on an app. This XML file is basically just Rss news feed data.

You can see the entire XML file structure here: https://github.com/karimo94/XMLDemo/blob/master/leaguenews.xml

答:
Try followng :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            dt.Columns.Add("Link", typeof(string));
            dt.Columns.Add("IsPermaLink", typeof(Boolean));
            dt.Columns.Add("GUID", typeof(string));
            dt.Columns.Add("Publish Date", typeof(DateTime));
            dt.Columns.Add("Width", typeof(int));
            dt.Columns.Add("Height", typeof(int));
            dt.Columns.Add("URL", typeof(string));

            XDocument doc = XDocument.Load(FILENAME); //or uri
            List<XElement> items = doc.Descendants("item").ToList();

            foreach (XElement item in items)
            {
                dt.Rows.Add(new object[] {
                    (string)item.Element("title"),
                    (string)item.Element("description"),
                    (string)item.Element("link"),
                    (Boolean)item.Element("guid").Attribute("isPermaLink"),
                    (string)item.Element("guid"),
                    (DateTime)item.Element("pubDate"),
                    (int)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("width"),
                    (int)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("height"),
                    (string)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("url")
                });
            }

        }
    }

}
</code>```

Body:
Try followng :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            dt.Columns.Add("Link", typeof(string));
            dt.Columns.Add("IsPermaLink", typeof(Boolean));
            dt.Columns.Add("GUID", typeof(string));
            dt.Columns.Add("Publish Date", typeof(DateTime));
            dt.Columns.Add("Width", typeof(int));
            dt.Columns.Add("Height", typeof(int));
            dt.Columns.Add("URL", typeof(string));

            XDocument doc = XDocument.Load(FILENAME); //or uri
            List<XElement> items = doc.Descendants("item").ToList();

            foreach (XElement item in items)
            {
                dt.Rows.Add(new object[] {
                    (string)item.Element("title"),
                    (string)item.Element("description"),
                    (string)item.Element("link"),
                    (Boolean)item.Element("guid").Attribute("isPermaLink"),
                    (string)item.Element("guid"),
                    (DateTime)item.Element("pubDate"),
                    (int)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("width"),
                    (int)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("height"),
                    (string)item.Elements().Where(x => x.Name.LocalName == "thumbnail").FirstOrDefault().Attribute("url")
                });
            }

        }
    }

}


问:
Is virtual memory used when using Port-mapped I/O?
If I have a Memory-mapped I/O device, and I want to write to a register for this device located at address 0x16D34, the 0x16D34 address is actually a virtual address, and the CPU will translate it to a physical address first, and then write the data to the physical address.

But what about Port-mapped I/O devices (for example: a serial port), so if I want to write to a register for a serial port located at address 0x3F8, is the 0x3F8 address a physical address or a virtual address?

Edit: I am on x86 architecture.

答:
Port-mapped I/O on x86/x86-64 (most other modern architectures don't even support it) happens in an entirely separate address space. This address space is not subject to memory mapping, so there are no virtual port addresses, only physical ones. Special in and out instructions must be used to perform port I/O, simple memory access (e.g. with mov) can't access this separate address space. Access protection based on privilege level is possible; most modern OSes prevent user space processes from accessing I/O ports by default.

For details, you can for example check the chapter "INPUT/OUTPUT" of Intel's "Intel® 64 and IA-32 Architectures Developer's Manual: Vol. 1" (chapter 18 as of this writing).

Note that in the early days of x86, port addresses were hardwired in each device, including ISA add-in cards. If you were lucky, the card had a set of jumpers for selecting one of a limited set of possible port ranges for the device, in order to avoid range clashes between devices. Later, Plug & Play was introduced to make the selection dynamically during system boot. PCI further refined this, so that I/O BARs can pretty much be mapped anywhere within the 0x0000-0xffff address space by the operating system and/or firmware. Port-mapped I/O is now strongly discouraged when designing new hardware due to its many inherent limitations.


问:
Unable to print array in node.js
Here is my code in routes

```<code>router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }
        });
        console.log(myset);   //blank array
        console.log("-----");
        console.log(ItemArray);   //blank array
        console.log("-----");
            res.render( 'new/post-select-table',
                {
                    title: 'Select Database',
                    session_store:req.session,
                });
        });
});
</code>```

I'm getting blank array when I'm trying to print array outside for loop. Can anyone help me where im going wrong.

答:
connection.query() is asynchronous, and in your code you're logging ItemArray outside of the callback of your query. The array will be empty since it isn't set to anything yet (i.e. your callback wouldn't have fired yet with the results). The following moves your console.logs and render function outside of the for loop, but inside of the callback, so it should print your final results for ItemArray as expected:

```<code>router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }

            console.log(myset);   //blank array
            console.log("-----");
            console.log(ItemArray);   //blank array
            console.log("-----");
                res.render( 'new/post-select-table',
                    {
                        title: 'Select Database',
                        session_store:req.session,
                    });
        });
    });
});
</code>```

Title: Unable to print array in node.js

Body:
Here is my code in routes

router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }
        });
        console.log(myset);   //blank array
        console.log("-----");
        console.log(ItemArray);   //blank array
        console.log("-----");
            res.render( 'new/post-select-table',
                {
                    title: 'Select Database',
                    session_store:req.session,
                });
        });
});

I'm getting blank array when I'm trying to print array outside for loop. Can anyone help me where im going wrong.

Body:
connection.query() is asynchronous, and in your code you're logging ItemArray outside of the callback of your query. The array will be empty since it isn't set to anything yet (i.e. your callback wouldn't have fired yet with the results). The following moves your console.logs and render function outside of the for loop, but inside of the callback, so it should print your final results for ItemArray as expected:

router.get('/chkjson', function(req, res, next) {
    req.getConnection(function(err,connection){
        var ItemArray = [];
        var myset = [];

        var query = connection.query('SELECT `db_name` FROM `database`',function(err,rows)
        {
            ItemArray.push({
                allDb : []
            });
            var k=0;
            for (var i in rows) {
                    retset = JSON.stringify(rows[i]);
                    var jsonset =  JSON.parse(retset);
                    console.log(ItemArray);
                    console.log("========");
                    myset.push(ItemArray);
                    ItemArray[0].allDb.push(jsonset.db_name);
            }

            console.log(myset);   //blank array
            console.log("-----");
            console.log(ItemArray);   //blank array
            console.log("-----");
                res.render( 'new/post-select-table',
                    {
                        title: 'Select Database',
                        session_store:req.session,
                    });
        });
    });
});


问:
Error installation Drupal 8 - LogicException: Cannot change the ID of an active session
Server:
Centos 7 + nginx + php-fpm

[root@centos ~]# php -v
PHP 7.0.16 (cli) (built: Feb 18 2017 10:25:02) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.16, Copyright (c) 1999-2017, by Zend Technologies

Try install Drupal 8

After step config connect to DB this error

答:
i fix this

problem in php.ini

drupal try up the session, and dont check if this alredy exist

change line in php.ini

```<code>session.auto_start = 0
</code>```

Body:
i fix this

problem in php.ini

drupal try up the session, and dont check if this alredy exist

change line in php.ini

session.auto_start = 0


问:
HTML5 audio codecs, support for other formats besides OGG
I started tinkering around with HTML5 recently and am very interested in Audio tag. Though one thing immediately came to my attention, it appears that OGG is the only format supported in Firefox!

I understand that this is because MP3 and other codecs are proprietary software and require a license to use. But how is HTML5 Audio (and Video) going to catch on if you can only use OGG?? Like it or not the world is currently hooked to MP3 or Apple's AAC.

And to further hinder things it seems that Mozilla is all for only natively supporting OGG.

So I'm curious. Why can't Firefox, and other browsers, use System installed codecs for playing media? Why do they have to be installed into the browser, or depend on technologies like Flash? It just seems like bad design to me.

Perhaps, I'm just naive about this, but this whole codec war is just a nuisance. Can anyone point me to information, laws, and other information regarding why browsers can't use system installed codecs? I would also like to hear other users opinions about this as well. Thanks!

Edit In case this comes off as not being a programming question, I want to clarify that to me this issue directly affects web programmers. For example, in the case of audio support, do we have to use flash? or will these issues eventually be handled in HTML5. Where does it seem that things are going, technology-wise, in regards to this issue?

答: The <object> or <embed> tag could be used to reference any media, and allowed to transcend the browser for handling.  The purpose of HTML5's media is to somewhat standardize a common encoding (lowest common denominator if you will) across platforms and have a browser-native player.  The Ogg container and various encodings make perfect sense.


问:
C# 'is' operator performance
I have a program that requires fast performance.  Within one of its inner loops, I need to test the type of an object to see whether it inherits from a certain interface.

One way to do this would be with the CLR's built-in type-checking functionality.  The most elegant method there probably being the 'is' keyword:

```<code>if (obj is ISpecialType)
</code>```

Another approach would be to give the base class my own virtual GetType() function which returns a pre-defined enum value (in my case, actually, i only need a bool).  That method would be fast, but less elegant.

I have heard that there is an IL instruction specifically for the 'is' keyword, but that doesn't mean it executes fast when translated into native assembly.  Can anyone share some insight into the performance of 'is' versus the other method?

UPDATE:  Thanks for all the informed answers!  It seem a couple helpful points are spread out among the answers:  Andrew's point about 'is' automatically performing a cast is essential, but the performance data gathered by Binary Worrier and Ian is also extremely useful.  It would be great if one of the answers were edited to include all of this information.

答:
Point Andrew Hare made about performance loss when you perform is check and then cast was valid but since C# 7.0 we can do is check with pattern match to avoid additional cast later on:

```<code>if (obj is ISpecialType st)
{
   //st is in scope here and can be used
}
</code>```

Further more if you need to check between multiple types C# 7.0 pattern matching constructs now allow you to do switch on types:

```<code>public static double ComputeAreaModernSwitch(object shape)
{
    switch (shape)
    {
        case Square s:
            return s.Side * s.Side;
        case Circle c:
            return c.Radius * c.Radius * Math.PI;
        case Rectangle r:
            return r.Height * r.Length;
        default:
            throw new ArgumentException(
                message: "shape is not a recognized shape",
                paramName: nameof(shape));
    }
}
</code>```

You can read more about pattern matching in C# in documentation here.

OwnerDisplayName: JubJub

Title: C# 'is' operator performance

Body:
I have a program that requires fast performance.  Within one of its inner loops, I need to test the type of an object to see whether it inherits from a certain interface.

One way to do this would be with the CLR's built-in type-checking functionality.  The most elegant method there probably being the 'is' keyword:

if (obj is ISpecialType)

Another approach would be to give the base class my own virtual GetType() function which returns a pre-defined enum value (in my case, actually, i only need a bool).  That method would be fast, but less elegant.

I have heard that there is an IL instruction specifically for the 'is' keyword, but that doesn't mean it executes fast when translated into native assembly.  Can anyone share some insight into the performance of 'is' versus the other method?

UPDATE:  Thanks for all the informed answers!  It seem a couple helpful points are spread out among the answers:  Andrew's point about 'is' automatically performing a cast is essential, but the performance data gathered by Binary Worrier and Ian is also extremely useful.  It would be great if one of the answers were edited to include all of this information.

LastEditorDisplayName: JubJub

Body:
Point Andrew Hare made about performance loss when you perform is check and then cast was valid but since C# 7.0 we can do is check with pattern match to avoid additional cast later on:

if (obj is ISpecialType st)
{
   //st is in scope here and can be used
}

Further more if you need to check between multiple types C# 7.0 pattern matching constructs now allow you to do switch on types:

public static double ComputeAreaModernSwitch(object shape)
{
    switch (shape)
    {
        case Square s:
            return s.Side * s.Side;
        case Circle c:
            return c.Radius * c.Radius * Math.PI;
        case Rectangle r:
            return r.Height * r.Length;
        default:
            throw new ArgumentException(
                message: "shape is not a recognized shape",
                paramName: nameof(shape));
    }
}

You can read more about pattern matching in C# in documentation here.


问:
Two svgo-loader conflict
I am using webpack to build svg-sprite.

But there is a problem: part of icons have multiple colors, and part — only one. They are used as is.

One color icons should change color according to :hover / :active.

And, according to this I should clean fill attributes for one color icons.

Which I can't do with multicolor ones.

I decide to separate them to different folders and create two webpack rules:

{
  test: /icon\/.*\.svg$/,
  loaders: [
    'svg-sprite-loader',
    {
      loader: 'svgo-loader',
      options: {
        plugins: [
          // ...
        ],
      },
    },
  ],
},
{
  test: /monoicon\/.*\.svg$/,
  loaders: [
    'svg-sprite-loader',
    {
      loader: 'svgo-loader',
      options: {
        enforce: 'pre',
        plugins: [
          // ...
          { removeAttrs: { attrs: '(fill|stroke)' } },
        ],
      },
    },
  ],
},
```
<p>And everything is fine, but it don't actually work. I am getting in the console:</p>
```…/monoicon/cross.svg
Module build failed: Error: Error in parsing SVG: Non-whitespace before first tag.
Line: 0
Column: 1
Char: i…
```

Digging the web I have found:

It was a problem with the way I was loading it. you need to prefix require("-!... when you're overriding other loaders...

https://github.com/jhamlet/svg-react-loader/issues/3#issuecomment-146334228

So it look like source of the problem is that I have to rules with svgo-loader. Rewrite webpack loaders rule in each svg import — kinda shitty idea. So how I may solve this in appropriate way?

Regards.

答:
I am an idiot. Write regexp's:</p>

```<code>/\/icon\/.*\.svg$/
/\/monoicon\/.*\.svg$/
</code>```

Title: Two svgo-loader conflict

Body:
I am using webpack to build svg-sprite.

But there is a problem: part of icons have multiple colors, and part — only one. They are used as is.

One color icons should change color according to :hover / :active.

And, according to this I should clean fill attributes for one color icons.

Which I can't do with multicolor ones.

I decide to separate them to different folders and create two webpack rules:

{
  test: /icon\/.*\.svg$/,
  loaders: [
    'svg-sprite-loader',
    {
      loader: 'svgo-loader',
      options: {
        plugins: [
          // ...
        ],
      },
    },
  ],
},
{
  test: /monoicon\/.*\.svg$/,
  loaders: [
    'svg-sprite-loader',
    {
      loader: 'svgo-loader',
      options: {
        enforce: 'pre',
        plugins: [
          // ...
          { removeAttrs: { attrs: '(fill|stroke)' } },
        ],
      },
    },
  ],
},

And everything is fine, but it don't actually work. I am getting in the console:

…/monoicon/cross.svg
Module build failed: Error: Error in parsing SVG: Non-whitespace before first tag.
Line: 0
Column: 1
Char: i…

Digging the web I have found:

It was a problem with the way I was loading it. you need to prefix require("-!... when you're overriding other loaders...

https://github.com/jhamlet/svg-react-loader/issues/3#issuecomment-146334228

So it look like source of the problem is that I have to rules with svgo-loader. Rewrite webpack loaders rule in each svg import — kinda shitty idea. So how I may solve this in appropriate way?

Regards.

Body:
I am an idiot. Write regexp's:

/\/icon\/.*\.svg$/
/\/monoicon\/.*\.svg$/


答:
The callback function in the query is called asynchronously, your prints are executed before the data is populated in the arrays.

You have to call res.render asynchronously from the callback. I dont understand all the operations in your code but here is an example of chaining a query and the response:

```<code>router.get('/chkjson', function(req, res, next) {
  req.getConnection(function(err,connection){
    connection.query('SELECT `db_name` FROM `database`',function(err,rows) {
      var myset = [], row;
      for (row in rows) {
        myset.push(row);
      }
      res.render( 'new/post-select-table', {
        title: 'Select Database',
        session_store:req.session,
        set: myset
      });
    });
  });
});
</code>```

If you need to chain requests, you can use promise-mysql to handle synchronisation easily, or modularise your code to avoid callback hell.

Example:

```<code>var connection, row1, row2
router.get('/chkjson', handleRequest);
function handleRequest (req, res, next) {
  req.getConnection(onGotConnection);
}
function onGotConnection(err,conn) {
  connection = conn;
  connection.query(query1, onGotEntity1);
}
function onGotEntity1(err,rows) {
  rows1 = rows

  connection.query(query2, onGotEntity2);
}
function onGotEntity2(err,rows) {
   row2 = rows

   // render view
   res.render( 'new/post-select-table', {
      k1: rows1,
      k2: rows2
   });
}
</code>```

But I recommend using promises that are a lot easier to read (and managing errors):

```<code>mysql.createConnection(opts).then(function(conn){
    connection = conn;
    return connection.query(query1);
}).then(function(rows){
    return connection.query(query2);
}).then(function(rows){
    // render view
});
</code>```

Title: Unable to print array in node.js

Body:
The callback function in the query is called asynchronously, your prints are executed before the data is populated in the arrays.

You have to call res.render asynchronously from the callback. I dont understand all the operations in your code but here is an example of chaining a query and the response:

router.get('/chkjson', function(req, res, next) {
  req.getConnection(function(err,connection){
    connection.query('SELECT `db_name` FROM `database`',function(err,rows) {
      var myset = [], row;
      for (row in rows) {
        myset.push(row);
      }
      res.render( 'new/post-select-table', {
        title: 'Select Database',
        session_store:req.session,
        set: myset
      });
    });
  });
});

If you need to chain requests, you can use promise-mysql to handle synchronisation easily, or modularise your code to avoid callback hell.

Example:

var connection, row1, row2
router.get('/chkjson', handleRequest);
function handleRequest (req, res, next) {
  req.getConnection(onGotConnection);
}
function onGotConnection(err,conn) {
  connection = conn;
  connection.query(query1, onGotEntity1);
}
function onGotEntity1(err,rows) {
  rows1 = rows

  connection.query(query2, onGotEntity2);
}
function onGotEntity2(err,rows) {
   row2 = rows

   // render view
   res.render( 'new/post-select-table', {
      k1: rows1,
      k2: rows2
   });
}

But I recommend using promises that are a lot easier to read (and managing errors):

mysql.createConnection(opts).then(function(conn){
    connection = conn;
    return connection.query(query1);
}).then(function(rows){
    return connection.query(query2);
}).then(function(rows){
    // render view
});


问:
Unable to make connections to more than 6k queues in RabbitMq using node js
I am quite new to Node js and RabbitMq. I wanted to create 100k queues. but I am getting the following error after creating around 6ooo queues.

error: "Cannot read property 'createChannel' of undefined"

I want to call conn.createConnection() method again if I have an error. How to do this?

Here's the code

```<code>var amqp = require("amqplib/callback_api");
var time = 0;
var limit = 100000
var timer = setInterval(() => {
  time+=1;
  if(time>=limit){
    clearInterval(timer);
  }
  var now = Date.now()
  //RabbitMQ
  amqp.connect("amqp://localhost",function(err,conn){
    conn.createChannel(function(err,ch){
      if(err){
        //try to do conn.createChannel again
      }
      var q = "queue_name"+time.toString();
      // console.log(q);
      var msg = "this is the message string!!!";
      ch.assertQueue(q,{durable: false});
      ch.sendToQueue(q,new Buffer(msg),{persistent: false});
      // console.log("time = "+time);
    });
  });
  //RabbitMQ`
},10);
</code>```

答:
What you are doing is not only creating 100k queues, but also 100k connections and channels. Likely you are running out of file handles and you can adjust the ulimit to allow more. However, you probably don't want to create all those connections and channels.

Try using one connection with one publisher channel with something along these lines:

```<code>var amqp = require("amqplib/callback_api");
var time = 0;
var limit = 100000

amqp.connect("amqp://localhost", function(err, conn) {
    if (err) {
        console.log('Somethings wrong with connection:', err);
        return;
    }
    conn.createChannel(function(err, ch){
        if (err) {
            console.log('Somethings wrong with channel:', err);
            return;
        }

        var timer = setInterval(() => {
            time+=1;
            if(time>=limit) {
                clearInterval(timer);
            }
            var now = Date.now()
            var q = "queue_name"+time.toString();
            var msg = "this is the message string!!!";
            ch.assertQueue(q, {durable: false} );
            ch.sendToQueue(q, new Buffer(msg),{persistent: false});
            console.log('sent', time);
        },10);
    });
});
</code>```

Body:
I am quite new to Node js and RabbitMq. I wanted to create 100k queues. but I am getting the following error after creating around 6ooo queues.

error: "Cannot read property 'createChannel' of undefined"

I want to call conn.createConnection() method again if I have an error. How to do this?

Here's the code

var amqp = require("amqplib/callback_api");
var time = 0;
var limit = 100000
var timer = setInterval(() => {
  time+=1;
  if(time>=limit){
    clearInterval(timer);
  }
  var now = Date.now()
  //RabbitMQ
  amqp.connect("amqp://localhost",function(err,conn){
    conn.createChannel(function(err,ch){
      if(err){
        //try to do conn.createChannel again
      }
      var q = "queue_name"+time.toString();
      // console.log(q);
      var msg = "this is the message string!!!";
      ch.assertQueue(q,{durable: false});
      ch.sendToQueue(q,new Buffer(msg),{persistent: false});
      // console.log("time = "+time);
    });
  });
  //RabbitMQ`
},10);

Body:
What you are doing is not only creating 100k queues, but also 100k connections and channels. Likely you are running out of file handles and you can adjust the ulimit to allow more. However, you probably don't want to create all those connections and channels.

Try using one connection with one publisher channel with something along these lines:

var amqp = require("amqplib/callback_api");
var time = 0;
var limit = 100000

amqp.connect("amqp://localhost", function(err, conn) {
    if (err) {
        console.log('Somethings wrong with connection:', err);
        return;
    }
    conn.createChannel(function(err, ch){
        if (err) {
            console.log('Somethings wrong with channel:', err);
            return;
        }

        var timer = setInterval(() => {
            time+=1;
            if(time>=limit) {
                clearInterval(timer);
            }
            var now = Date.now()
            var q = "queue_name"+time.toString();
            var msg = "this is the message string!!!";
            ch.assertQueue(q, {durable: false} );
            ch.sendToQueue(q, new Buffer(msg),{persistent: false});
            console.log('sent', time);
        },10);
    });
});


问:
Clob transformer not working in DIH
I am using solr 5.4.1. Here I am using dataimport handler to index data with SQL Server.

I am using CLOB transformer to convert clob value to string. Indexing is working fine but clob transformation is not working. Expected string value is not coming for clob column. There is no error or exception coming in log.

Here is the configuration:

<dataConfig>
  <datasource name="one" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://localhost;databaseName=Dictionary;"    user="sa"    password="xxxxxxxx" batchSize="5" />
  <document>
    <entity name="TestEntity" query="SELECT id, rules FROM tag" transformer="ClobTransformer">
      <field column="Id" name="id"  />
      <field column="rules" name="rules"  clob="true"/>
    </entity>
  </document>
</dataConfig>
```

I tried using RegexTransformer, it worked. But ClobTransformer is not working. Please assist.

答:
```<code><entity name="TestEntity" transformer="ClobTransformer" query="SELECT id, rules FROM tag" >

<field column="RULES" name="RULES" clob="true" sourceColName="RULES" />
</code>```

REF :: ClobTransformer

It's work with me

try to set RULES in upper case

Title: Clob transformer not working in DIH

Body:
I am using solr 5.4.1. Here I am using dataimport handler to index data with SQL Server.

I am using CLOB transformer to convert clob value to string. Indexing is working fine but clob transformation is not working. Expected string value is not coming for clob column. There is no error or exception coming in log.

Here is the configuration:

<dataConfig>
  <datasource name="one" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://localhost;databaseName=Dictionary;"    user="sa"    password="xxxxxxxx" batchSize="5" />
  <document>
    <entity name="TestEntity" query="SELECT id, rules FROM tag" transformer="ClobTransformer">
      <field column="Id" name="id"  />
      <field column="rules" name="rules"  clob="true"/>
    </entity>
  </document>
</dataConfig>

I tried using RegexTransformer, it worked. But ClobTransformer is not working. Please assist.

Body:
<entity name="TestEntity" transformer="ClobTransformer" query="SELECT id, rules FROM tag" >

<field column="RULES" name="RULES" clob="true" sourceColName="RULES" />

REF :: ClobTransformer

It's work with me

try to set RULES in upper case


问:
super() in a constructor of a class without inheritance
The following code (shortened version of the class) I have seen in a Java Video-Tutorial.

```<code>public class Address {
    private String firstName;
    private String lastName;

    public Address() {
        super();
    }

    public Address(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    ...
}
</code>```

The class which is shown there has no extend keyword. Nevertheless super() is used within the constructor without a parameter.

It calls the constructor of Object class? Am I right?

But why?

What is the reason for having this call of super()?

答:
Constructors of superclasses are invoked when you create an instance of your class. In case your class extends sth explicitly, there are two options:

If the super class has a default constructor, then it's invoked;

In case there is no default constructor, you should specify which constructor you invoke and send corresponding arguments for it.

Calling super() without parameters basically means that you invoke a default constructor. It's not necessary, because it will be invoked even if you don't do it explicitly.

Since all the objects in java implicitly extend Object, then the default constructor of Object is invoked all the time you create an instance of the class. super() just makes it explicit. But, why should we add explicitness to something that is quite clear already.

Moreover, that's sometimes added by IDE when you use code generation tools(e.g. Eclipse).

You can read really good description on how consturtors of class/superclass work in a book for OCA preparation: https://www.amazon.com/OCA-Certified-Associate-Programmer-1Z0-808/dp/1118957407

Body:
The following code (shortened version of the class) I have seen in a Java Video-Tutorial.

public class Address {
    private String firstName;
    private String lastName;

    public Address() {
        super();
    }

    public Address(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    ...
}

The class which is shown there has no extend keyword. Nevertheless super() is used within the constructor without a parameter.

It calls the constructor of Object class? Am I right?

But why?

What is the reason for having this call of super()?


问:
Use Filesaver js with angular2
i have checked all the post i can find on the use of Filesaver JS with angular, but i still could not wrap my head around a soution.
I added this  to the map section of my system.config.js

```<code> 'filesaver': 'node_modules/filesaver/src/Filesaver.js'
</code>```

I added this to the packages section of the system.config.js

```<code>  'filesaver': {defaultExtension: 'js'}
</code>```

I then imported it in my service.ts this way

```<code>import { saveAs } from 'filesaver';
</code>```

Yet i get this error.

Can someone help please?

答:
For angular-cli with http (followed by httpClient):

```<code>npm install file-saver --save
</code>```

Add this third party lib to  .angular-cli.json

```<code>"scripts": [
      "../node_modules/file-saver/FileSaver.js"
    ],
</code>```

In the blabla service:

```<code>downloadBlaBlasCSV() {
        let options = {responseType: ResponseContentType.ArrayBuffer };
        return this.http.get(this.config.apiUrl + '/blablasCSV', options)
        .catch((err: Response) => Observable.throw(err.json()));
    }
</code>```

Finally int the component:

```<code>import { saveAs } from 'file-saver';

downloadBlaBlasCSV() {
    this.blablaService.downloadBlaBlasCSV().subscribe(
      (data) => { this.openFileForDownload(data); },
      (error: any) => {
        ...
      });
  }

openFileForDownload(data: Response) {
    //var blob = new Blob([data._body], { type: 'text/csv;charset=utf-8' });
    //saveAs(blob, 'Some.csv');
    let content_type = data.headers.get('Content-type');
    let x_filename = data.headers.get('x-filename');
    saveAs(data.blob(), x_filename);
  }
</code>```

httpClient

It's the same like http but the service method is different:

```<code>downloadBlaBlasCSV() {
        return this.httpClient.get(this.config.apiUrl + '/blablasCSV',  {
            headers: new HttpHeaders().set('Accept', 'text/csv' ),
            observe: 'response',
            responseType: 'blob'
        })
    }
</code>```

Title: Use Filesaver js with angular2

Body:
i have checked all the post i can find on the use of Filesaver JS with angular, but i still could not wrap my head around a soution.
I added this  to the map section of my system.config.js

 'filesaver': 'node_modules/filesaver/src/Filesaver.js'

I added this to the packages section of the system.config.js

  'filesaver': {defaultExtension: 'js'}

I then imported it in my service.ts this way

import { saveAs } from 'filesaver';

Yet i get this error.

Can someone help please?

Body:
For angular-cli with http (followed by httpClient):

npm install file-saver --save

Add this third party lib to  .angular-cli.json

"scripts": [
      "../node_modules/file-saver/FileSaver.js"
    ],

In the blabla service:

downloadBlaBlasCSV() {
        let options = {responseType: ResponseContentType.ArrayBuffer };
        return this.http.get(this.config.apiUrl + '/blablasCSV', options)
        .catch((err: Response) => Observable.throw(err.json()));
    }

Finally int the component:

import { saveAs } from 'file-saver';

downloadBlaBlasCSV() {
    this.blablaService.downloadBlaBlasCSV().subscribe(
      (data) => { this.openFileForDownload(data); },
      (error: any) => {
        ...
      });
  }

openFileForDownload(data: Response) {
    //var blob = new Blob([data._body], { type: 'text/csv;charset=utf-8' });
    //saveAs(blob, 'Some.csv');
    let content_type = data.headers.get('Content-type');
    let x_filename = data.headers.get('x-filename');
    saveAs(data.blob(), x_filename);
  }

httpClient

It's the same like http but the service method is different:

downloadBlaBlasCSV() {
        return this.httpClient.get(this.config.apiUrl + '/blablasCSV',  {
            headers: new HttpHeaders().set('Accept', 'text/csv' ),
            observe: 'response',
            responseType: 'blob'
        })
    }


问:
Mysql alter a primary key column that has a relationship with another table
Could I change a primary key column that has a relationship in another table to be auto increment.

this is my code

```<code> alter table sales_agreement modify column client_id int(11)  auto_increment ;
</code>```

but I get error:-

```<code> Cannot change column 'Client_id': used in a foreign key constraint 'Relationship5' of table ' order_sheet'
</code>```

Edit
 Sales_Agreement  Table

```<code>    CREATE TABLE  Sales_Agreement
    (

      Client_id Int NOT NULL,
      Client Varchar(200) NOT NULL,
     PRIMARY KEY (Client_id)
    ) ;
</code>```

Table order_sheet

```<code> CREATE TABLE Sales.Order_Sheet
(
  Client_id Int NOT NULL
)
;
ALTER TABLE Sales.Order_Sheet ADD PRIMARY KEY (Client_id)
;

ALTER TABLE Order_Sheet ADD CONSTRAINT Relationship5 FOREIGN KEY (Client_id) REFERENCES Sales_Agreement (Client_id)
;
</code>```

答:
Try to drop foreign key first,

ALTER TABLE 'Order_Sheet' DROP FOREIGN KEY 'Relationship5';

and then alter table by modifying the primary key.

Body:
Could I change a primary key column that has a relationship in another table to be auto increment.

this is my code

 alter table sales_agreement modify column client_id int(11)  auto_increment ;

but I get error:-

 Cannot change column 'Client_id': used in a foreign key constraint 'Relationship5' of table ' order_sheet'

Edit
 Sales_Agreement  Table

    CREATE TABLE  Sales_Agreement
    (

      Client_id Int NOT NULL,
      Client Varchar(200) NOT NULL,
     PRIMARY KEY (Client_id)
    ) ;

Table order_sheet

 CREATE TABLE Sales.Order_Sheet
(
  Client_id Int NOT NULL
)
;
ALTER TABLE Sales.Order_Sheet ADD PRIMARY KEY (Client_id)
;

ALTER TABLE Order_Sheet ADD CONSTRAINT Relationship5 FOREIGN KEY (Client_id) REFERENCES Sales_Agreement (Client_id)
;