问:
How to get string from arraylist
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

```<code>public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}
</code>```

}

答:
You already have a parameter called position. That will be the parameter of the get. However that will return a Product object and you will need to read the given member from there. Since you did not share the code of the Product class with us, we can only guess:

```<code>    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
        newActivity.putExtra("1st column value", mProductList.get(position).ID);
        newActivity.putExtra("2nd column value", mProductList.get(position).Name);
        newActivity.putExtra("3rd column value", mProductList.get(position).Price);
        newActivity.putExtra("4th column value", mProductList.get(position).Description);
        startActivity(newActivity);
    }
</code>```

Title: How to get string from arraylist

Body:
I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string @....

Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.

public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);

    lvProduct = (ListView)findViewById(R.id.listView1);

    mProductList = new ArrayList<>();
    mProductList.add(new Product(1, "Product_1", "Price", "Description"));
    mProductList.add(new Product(2, "Product_2", "Price", "Description"));
    mProductList.add(new Product(3, "Product_3", "Price", "Description"));

    adapter = new ProductListAdapter(getApplicationContext(), mProductList);
    lvProduct.setAdapter(adapter);

    lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
            newActivity.putExtra("1st column value", mProductList.get(???));
            newActivity.putExtra("2nd column value", mProductList.get(???));
            newActivity.putExtra("3rd column value", mProductList.get(???));
            newActivity.putExtra("4th column value", mProductList.get(???));
            startActivity(newActivity);
        }
    });
}

}

Body:
You already have a parameter called position. That will be the parameter of the get. However that will return a Product object and you will need to read the given member from there. Since you did not share the code of the Product class with us, we can only guess:

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
        newActivity.putExtra("1st column value", mProductList.get(position).ID);
        newActivity.putExtra("2nd column value", mProductList.get(position).Name);
        newActivity.putExtra("3rd column value", mProductList.get(position).Price);
        newActivity.putExtra("4th column value", mProductList.get(position).Description);
        startActivity(newActivity);
    }


来源: stackexchange

问:
MySQL: Update table column using values of same column
I have a MySQL table:

```<code>PriceRange (MinPrice DOUBLE, MaxPrice DOUBLE, TrdDate DATE)
</code>```

I want to apply a multiplication factor on MinPrice and MaxPrice for all the records with TrdDate less than a particular date. For example,

Table before update:

```<code>(10, 12, 01-JAN-2016)
(12, 14, 02-JAN-2016)
(6, 7, 03-JAN-2016)
</code>```

Table after update (with multiplication factor of 0.5 applied on all records for TrdDate < 03-JAN-2016):

```<code>(5, 6, 01-JAN-2016)
(6, 7, 02-JAN-2016)
(6, 7, 03-JAN-2016)
</code>```

I know subquery will not work here as I can't update the same record that I am reading.

Can I solve above problem using JOIN or do I have to use cursor for it?

答:
You can use a simple UPDATE query to solve this:

```<code>UPDATE PriceRange
SET MinPrice = MinPrice * 0.5, MaxPrice = MaxPrice * 0.5
WHERE TrdDate < '2016-01-03'
</code>```

demo on dbfiddle.uk

ContentLicense: CC BY-SA 3.0

Body:
I have a MySQL table:

PriceRange (MinPrice DOUBLE, MaxPrice DOUBLE, TrdDate DATE)

I want to apply a multiplication factor on MinPrice and MaxPrice for all the records with TrdDate less than a particular date. For example,

Table before update:

(10, 12, 01-JAN-2016)
(12, 14, 02-JAN-2016)
(6, 7, 03-JAN-2016)

Table after update (with multiplication factor of 0.5 applied on all records for TrdDate < 03-JAN-2016):

(5, 6, 01-JAN-2016)
(6, 7, 02-JAN-2016)
(6, 7, 03-JAN-2016)

I know subquery will not work here as I can't update the same record that I am reading.

Can I solve above problem using JOIN or do I have to use cursor for it?

Body:
You can use a simple UPDATE query to solve this:

UPDATE PriceRange
SET MinPrice = MinPrice * 0.5, MaxPrice = MaxPrice * 0.5
WHERE TrdDate < '2016-01-03'

demo on dbfiddle.uk

ContentLicense: CC BY-SA 4.0


问:
INSTALL_FAILED_UID_CHANGED error while installing application
```<code>[2013-04-06 14:48:32 - SplitPaneLayout-Demo] Android Launch!
[2013-04-06 14:48:32 - SplitPaneLayout-Demo] adb is running normally.
[2013-04-06 14:48:32 - SplitPaneLayout-Demo] Performing com.mobidevelop.widget.Demo activity launch
[2013-04-06 14:48:32 - SplitPaneLayout-Demo] Automatic Target Mode: using device '015d188469381013'
[2013-04-06 14:48:32 - SplitPaneLayout-Demo] Uploading SplitPaneLayout-Demo.apk onto device '015d188469381013'
[2013-04-06 14:48:32 - SplitPaneLayout-Demo] Installing SplitPaneLayout-Demo.apk...

[2013-04-06 14:48:34 - SplitPaneLayout-Demo] Installation error: INSTALL_FAILED_UID_CHANGED
[2013-04-06 14:48:34 - SplitPaneLayout-Demo] Please check logcat output for more details.
[2013-04-06 14:48:34 - SplitPaneLayout-Demo] Launch canceled!
</code>```

答: Please check if you have added android:sharedUserId in your manifest. Remove it if it is not required. That should fix the issue.</p>


问:
REPLACE a given occurance of a string in a column
I have a column like this:

```<code>vars
-----------
|A|B|A|D|AB|B...
</code>```

I want to replace one var (e.g: the one in 3rd position, which happens to be A) but keep any other A's. The position is determined by a variable. So I should get:

```<code>vars
-----------
|A|B|D|AB|B...
</code>```

I know I should use REPLACE and possibly SUBSTRING_INDEX, but I can't figure out how. Here's what I've tried:
Let's say :pos=3;

```<code>vars = REPLACE(vars, (SUBSTRING_INDEX(SUBSTRING_INDEX(vars, '|', :pos), '|', -1)), '')
</code>```

But this actually replaces all other characters and keeps the one I need replaced.

UPDATE: Mind that I don't know what var I want to replace, only its position.

UPDATE 2:

```<code>vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))
</code>```

This does the trick but I forgot to mention the vars are not always |A and |B etc., but also |AB, |AC... So the position shouldn't always move by one character, but until the next |.

答:
if you know position  number 6 is your position variable

```<code>SELECT  concat(SUBSTRING('|A|B|A|D|G|B',1,6-2),SUBSTRING('|A|B|A|D|G|B',6+1) )
</code>```

or if you know string at second occurrence

```<code>    SELECT REPLACE( '|A|B|A|D|G|B', concat( SUBSTRING_INDEX( '|A|B|A|D|G|B',
'|A', 2 ) , "|A" ) , SUBSTRING_INDEX( '|A|B|A|D|G|B', '|A', 2 ) )
</code>```

Body:
I have a column like this:

vars
-----------
|A|B|A|D|AB|B...

I want to replace one var (e.g: the one in 3rd position, which happens to be A) but keep any other A's. The position is determined by a variable. So I should get:

vars
-----------
|A|B|D|AB|B...

I know I should use REPLACE and possibly SUBSTRING_INDEX, but I can't figure out how. Here's what I've tried:
Let's say :pos=3;

vars = REPLACE(vars, (SUBSTRING_INDEX(SUBSTRING_INDEX(vars, '|', :pos), '|', -1)), '')

But this actually replaces all other characters and keeps the one I need replaced.

UPDATE: Mind that I don't know what var I want to replace, only its position.

UPDATE 2:

vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))

This does the trick but I forgot to mention the vars are not always |A and |B etc., but also |AB, |AC... So the position shouldn't always move by one character, but until the next |.

Body:
if you know position  number 6 is your position variable

SELECT  concat(SUBSTRING('|A|B|A|D|G|B',1,6-2),SUBSTRING('|A|B|A|D|G|B',6+1) )

or if you know string at second occurrence

    SELECT REPLACE( '|A|B|A|D|G|B', concat( SUBSTRING_INDEX( '|A|B|A|D|G|B',
'|A', 2 ) , "|A" ) , SUBSTRING_INDEX( '|A|B|A|D|G|B', '|A', 2 ) )


问:
Koolwired.Imap - How do I delete messages?
I'm trying to delete all the emails from a mailbox using the Koolwired.Imap library. I have the following code that should be marking all the messages and they, once all are marked, delete them,

```<code>        _mailbox = _command.Fetch(_mailbox);
        foreach (ImapMailboxMessage m in _mailbox.Messages)
        {
            try
            {
                _command.SetDeleted(m.ID, true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Marking Error: " + e.Message + "(" + m.MessageID + ")");
            }
        }
        try
        {
            _command.Expunge();
        }
        catch (Exception e)
        {
            Console.WriteLine("Expunge Error: " + e.Message);
        }
</code>```

When I run the above code i get the following errors:

```<code>Marking Error: Input string was not in a correct format.()
Marking Error: No UID found for message number3()
Marking Error: No UID found for message number1()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()
</code>```

I looks like there is an issue with the message UID on most of the message. After this runs about 99% of the messages are not deleted, some 2-3 are deleted. If I re-run the program, i get the same errors but a few less and another 2-3 emails are deleted.

How am I supposed to delete emails with the Koolwired.Imap library?
Are there other Imap libraries that work with c#? When i was looking this is the only one that I found.

答:
Your code looks like it should work according to http://imapnet.codeplex.com/Thread/View.aspx?ThreadId=73377 and I see you posted out there as well.  Have you tried setting up a gmail account and testing it against that just to see what happens?

As for other libraries, I have used the EAGetMail POP3 & IMAP4 component (cannot add link due to my new account: www.emailarchitect.net/eagetmail/)   on previous projects and had good luck with it.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to delete all the emails from a mailbox using the Koolwired.Imap library. I have the following code that should be marking all the messages and they, once all are marked, delete them,

        _mailbox = _command.Fetch(_mailbox);
        foreach (ImapMailboxMessage m in _mailbox.Messages)
        {
            try
            {
                _command.SetDeleted(m.ID, true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Marking Error: " + e.Message + "(" + m.MessageID + ")");
            }
        }
        try
        {
            _command.Expunge();
        }
        catch (Exception e)
        {
            Console.WriteLine("Expunge Error: " + e.Message);
        }

When I run the above code i get the following errors:

Marking Error: Input string was not in a correct format.()
Marking Error: No UID found for message number3()
Marking Error: No UID found for message number1()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()

I looks like there is an issue with the message UID on most of the message. After this runs about 99% of the messages are not deleted, some 2-3 are deleted. If I re-run the program, i get the same errors but a few less and another 2-3 emails are deleted.

How am I supposed to delete emails with the Koolwired.Imap library?
Are there other Imap libraries that work with c#? When i was looking this is the only one that I found.


问:
AngularJS : Why ng-bind is better than {{}} in angular?
I was in one of the angular presentation and one of the person in the meeting mentioned ng-bind is better than {{}} binding.

One of the reason, ng-bind put the variable in the watch list and only when there is a model change the data get pushed to view, on the other hand, {{}} will interpolate the expression every time (I guess it is the angular cycle) and push the value, even if the value changed or not.

Also it is said that, if you have not much data in on the screen you can use {{}} and the performance issue will not be visible. Can someone shed some light on this issue for me?

答:
You can refer to this site it will give you a explanation which one is better as i know {{}} this is slower than ng-bind.

http://corpus.hubwiz.com/2/angularjs/16125872.html
refer this site.


问:
Opening Microsoft Access with parameters
Similar to the OpenArgs property of the Form object, am I able to open the Access Application itself with a passed parameter (say from a .bat file)?

Basically I'm looking to speed up the user's experience by having variable links to .bat files that open the same file, but to a different menu screen etc.

答:
Use the /cmd command-line parameter to start Access, and the Commmand() function in Access-VBA to read it.

"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" D:\Work\myDb.accdb /cmd foo
```

<p>and this function called by an <code>Autoexec</code> macro:</p>

```Public Function AutoExec()

    Dim sCmd As String

    ' ... other initializations ...

    ' Read /cmd command-line parameter
    sCmd = Command()

    Select Case sCmd
        Case "foo": Call Foo()
        Case "bar": Call Bar()
        Case Else: Debug.Print "No valid command-line parameter passed."
    End Select

End Function
```

Body:
Use the /cmd command-line parameter to start Access, and the Commmand() function in Access-VBA to read it.

"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" D:\Work\myDb.accdb /cmd foo

and this function called by an Autoexec macro:

Public Function AutoExec()

    Dim sCmd As String

    ' ... other initializations ...

    ' Read /cmd command-line parameter
    sCmd = Command()

    Select Case sCmd
        Case "foo": Call Foo()
        Case "bar": Call Bar()
        Case Else: Debug.Print "No valid command-line parameter passed."
    End Select

End Function


问:
How to use async method in DelegateCommand
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

```<code>{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}
</code>```

答:
Is UI thread running DelegateCommand and background threads running await expression?

Yes, the UI thread runs the DelegateCommand. In case of an async one, it runs until the first await statement, and then resumes his regular UI thread work. If the awaiter is configured to capture the synchronization context (that is, you do not use .ConfigureAwait(false)) the UI thread will continue to run the DelegateCommand after the await.

Is UI thread running DelegateCommand and background threads running await expression?

Whether the "await expression" runs on a background thread, foreground thread, a threadpool thread or whatever depends on the api you call. For example, you can push cpu-bound work to the threadpool using Task.Run or you can wait for an i/o-operation without using any thread at all with methods like Stream.ReadAsync

Body:
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}


问:
Protractor - waiting for async to finish
In our application we are calling every minute to our feature flags service using angular therefore browser.waitForAngular() always fail.

is there a way to use browser.waitForAngular() and make it ignore this specific feature flag call (API call that is being called every 60 secs) so we can still use the wait for angular and not implement waits on the code?

答:
There is an option to enable/disable waitForAngular which may be used to disable for pages where polling is happening and enabled again later for other pages..Check the below link

browser.waitForAngularEnabled


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答: No, you do not need the try catch. The only reason you would want to use the first function is if you wanted to do some logging or release resources before handling the function further up.</p>

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

OwnerDisplayName: amdfan


问:
Change Toolbar Un-hidden Menu Icon Color
How to change toolbar search icon color? I want it to be white colored. I've change with my own white drawable but the result still black. I've read this post but the post problem is text color not icon color.

ScreenShot

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.zihadrizkyef.project_katalog_grosirmukenalukis_admin.MainActivity"

    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/myToolbar"
        android:layout_height="?android:attr/actionBarSize"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:theme="@style/myToolbarTheme"/>

    <ListView
        android:id="@+id/lvProduct"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

style.xml

```<code><resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:buttonStyle">@style/MyButtonStyle</item>
    </style>

    <style name="MyButtonStyle" parent="Base.Widget.AppCompat.Button">
        <item name="android:textAllCaps">false</item>
        <item name="android:background">@drawable/mybutton</item>
        <item name="android:textColor">@color/myWidgetContentColor</item>
    </style>

    <style name="myToolbarTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:textColorPrimary">@color/myWidgetContentColor</item>
    </style>
</resources>
</code>```

menu_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"
        android:icon="@drawable/ic_action_search"/>
</menu>
</code>```

答:
Add following method where the searchView is declared.

```<code>public Drawable changeDrawableTint(Drawable drawable, int color){
    final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTintList(wrappedDrawable, ColorStateList
            .valueOf(color));
    return wrappedDrawable;
}
</code>```

Now these two lines you've already written

```<code>MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
</code>```

Just add this line

```<code>// To change the color of searchView
searchItem.setIcon(changeDrawableTint(searchItem.getIcon(), Color.WHITE));
</code>```

Body:
How to change toolbar search icon color? I want it to be white colored. I've change with my own white drawable but the result still black. I've read this post but the post problem is text color not icon color.

ScreenShot

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.zihadrizkyef.project_katalog_grosirmukenalukis_admin.MainActivity"

    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/myToolbar"
        android:layout_height="?android:attr/actionBarSize"
        android:layout_width="match_parent"
        android:background="@color/colorPrimary"
        android:theme="@style/myToolbarTheme"/>

    <ListView
        android:id="@+id/lvProduct"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

style.xml

<resources>

</resources>

menu_home.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"
        android:icon="@drawable/ic_action_search"/>
</menu>

Body:
Add following method where the searchView is declared.

public Drawable changeDrawableTint(Drawable drawable, int color){
    final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTintList(wrappedDrawable, ColorStateList
            .valueOf(color));
    return wrappedDrawable;
}

Now these two lines you've already written

MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

Just add this line

// To change the color of searchView
searchItem.setIcon(changeDrawableTint(searchItem.getIcon(), Color.WHITE));


问:
Why has all my text turned black when set it in my android theme to be white?
I am trying to make my textview textColor white in my AppTheme but it appears as black in my fragment.  The fragment has been set to have a background like so:

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="wrap_content"
    android:id="@+id/fragment_settings"
    android:background="?android:attr/windowBackground"
</code>```

The page looks like this now:

The theme looks like this:

```<code><resources>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
     <!--   <item name="android:statusBarColor">@android:color/transparent</item> -->
    </style>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/whiteText</item>
        <item name="android:buttonStyle">@style/MyButton</item>
        <item name="android:statusBarColor">@android:color/black</item>
        <item name="android:colorBackground">#2d314d</item>
        <item name="android:textColorPrimary">@color/whiteText</item>
        <item name="android:textColorPrimaryInverse">@android:color/holo_red_dark</item>
        <item name="android:textColorSecondary">@android:color/holo_blue_bright</item>
        <item name="android:textColorSecondaryInverse">@android:color/holo_red_dark</item>
        <item name="android:colorForeground">@android:color/holo_blue_bright</item>
        <item name="android:windowBackground">?android:attr/colorBackground</item>
    </style>

    <style name="MyButton" parent="android:Widget.Button">
        <item name="android:background">#FF5A79</item>

        <item name="android:textColor">@color/whiteText</item>

    </style>
</resources>
</code>```

Also, not sure this is related but just in case, I was using the Theme Editor and it gives a warning - Not enough contrast with colorButtonNormal - by the android:textcolorPrimary.  I don't know much about what   colorButtonNormal is nor can I find any info about it.  This is what my theme editor looks like with my current settings:

While I'm at it another problem is the text color is white inside the editText fields (WEIGHT and AGE) which is where I need to change it to be black.

Thanks for any help, this android styling stuff is driving me nuts.

答:
Go for this </p>

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:fillViewport="true"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_settings"
        android:background="@android:color/white"/>
</code>```

<p>this will solve your problem. You are setting parent="Theme.AppCompat.Light.DarkActionBar" that is why everything is black </p>

Body:
I am trying to make my textview textColor white in my AppTheme but it appears as black in my fragment.  The fragment has been set to have a background like so:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="wrap_content"
    android:id="@+id/fragment_settings"
    android:background="?android:attr/windowBackground"

The page looks like this now:

The theme looks like this:

<resources>

</resources>

Also, not sure this is related but just in case, I was using the Theme Editor and it gives a warning - Not enough contrast with colorButtonNormal - by the android:textcolorPrimary.  I don't know much about what   colorButtonNormal is nor can I find any info about it.  This is what my theme editor looks like with my current settings:

While I'm at it another problem is the text color is white inside the editText fields (WEIGHT and AGE) which is where I need to change it to be black.

Thanks for any help, this android styling stuff is driving me nuts.

Body:
Go for this

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:fillViewport="true"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_settings"
        android:background="@android:color/white"/>

this will solve your problem. You are setting parent="Theme.AppCompat.Light.DarkActionBar" that is why everything is black


问:
Powershell v2 prompting for value in foreach
This code runs in PowerShell v1 but not in PowerShell v2. It now prompts for a value:

```<code>Get-ChildItem -Path $source -Filter "*.journal" |
 Where-Object { $_.Name -match 'SoundPC\[\d{1,12}-\d{1,12}\].journal' } | Sort-Object -Property CreationTime | ForEach-Object
{

$sourcefile = $_.Name

}
</code>```

Can someone help?

答:
As Shay Levy pointed out, the brace must be on the same line as the ForEach-Object command.

```<code>... | ForEach-Object {
    $sourcefile = $_.Name
}
</code>```

Alternatively, you can use the backtick character ` at the end of the line to cause a continuation, which will then allow you to put the opening brace on the next line. Being a C# developer, I prefer this so that my braces can line up.

```<code>... | ForEach-Object `
{
    $sourcefile = $_.Name
}
</code>```

Body:
This code runs in PowerShell v1 but not in PowerShell v2. It now prompts for a value:

Get-ChildItem -Path $source -Filter "*.journal" |
 Where-Object { $_.Name -match 'SoundPC\[\d{1,12}-\d{1,12}\].journal' } | Sort-Object -Property CreationTime | ForEach-Object
{

$sourcefile = $_.Name

}

Can someone help?

Body:
As Shay Levy pointed out, the brace must be on the same line as the ForEach-Object command.

... | ForEach-Object {
    $sourcefile = $_.Name
}

Alternatively, you can use the backtick character ` at the end of the line to cause a continuation, which will then allow you to put the opening brace on the next line. Being a C# developer, I prefer this so that my braces can line up.

... | ForEach-Object `
{
    $sourcefile = $_.Name
}


问:
checking paragraph property loses the selection
in my vsto addin i have some simple code on a timer

```<code>private void MainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (!dialogopen & Application.Documents.Count > 0)
        {
            var doc = Application.ActiveDocument;
            Word.InlineShapes shps;
            Word.Paragraphs pars;
            try
            {
                pars = doc.Paragraphs;
            }
            catch (Exception)
            {
                return;
            }
            var pars2 = pars.Cast<Word.Paragraph>().ToList();
            foreach (var obj in pars2)
            {
                if (obj.OutlineLevel == Word.WdOutlineLevel.wdOutlineLevelBodyText )//PROBLEM HERE
                {

                };
            }

        }
    }
</code>```

as soon as it reaches the line that checks the outlinelevel, even if i dont do a thing, the selection in the activedocument gets lost

of course the user cant use a plugin which keeps on canceling his selection...

googling didnt give me a thing

thanks

EDIT1

I tried making a static function for checking the styles, but it did not help. Here's the code

```<code>static public class Helpers
{
    static public Word.Paragraph checkPars(List<Word.Paragraph> pars)
    {
        return pars.FirstOrDefault();//(x) => x.OutlineLevel == Word.WdOutlineLevel.wdOutlineLevelBodyText);
    }
}
</code>```

As you can see, I had to remove the actual check, since it was causing the cursor to blink and lose selection

please advise

答:
We use the Application.ScreenUpdating = true; and this keep the selection for all properties in Paragraph except for the Range property.

Then, we tried to access the range via Reflection and this was the solution.

```<code>Range rng = (Range)typeof(Paragraph).GetProperty("Range").GetValue(comObj);
</code>```

Body:
in my vsto addin i have some simple code on a timer

private void MainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (!dialogopen & Application.Documents.Count > 0)
        {
            var doc = Application.ActiveDocument;
            Word.InlineShapes shps;
            Word.Paragraphs pars;
            try
            {
                pars = doc.Paragraphs;
            }
            catch (Exception)
            {
                return;
            }
            var pars2 = pars.Cast<Word.Paragraph>().ToList();
            foreach (var obj in pars2)
            {
                if (obj.OutlineLevel == Word.WdOutlineLevel.wdOutlineLevelBodyText )//PROBLEM HERE
                {

                };
            }

        }
    }

as soon as it reaches the line that checks the outlinelevel, even if i dont do a thing, the selection in the activedocument gets lost

of course the user cant use a plugin which keeps on canceling his selection...

googling didnt give me a thing

thanks

EDIT1

I tried making a static function for checking the styles, but it did not help. Here's the code

static public class Helpers
{
    static public Word.Paragraph checkPars(List<Word.Paragraph> pars)
    {
        return pars.FirstOrDefault();//(x) => x.OutlineLevel == Word.WdOutlineLevel.wdOutlineLevelBodyText);
    }
}

As you can see, I had to remove the actual check, since it was causing the cursor to blink and lose selection

please advise

Body:
We use the Application.ScreenUpdating = true; and this keep the selection for all properties in Paragraph except for the Range property.

Then, we tried to access the range via Reflection and this was the solution.

Range rng = (Range)typeof(Paragraph).GetProperty("Range").GetValue(comObj);


问:
Checking if there is any validation error when using custom form request class
I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

```<code>public function store(CustomFormRequest $request)
{
  //
}
</code>```

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

```<code>// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}
</code>```

Could you please help ?
Thanks in advance.

答:
try this:

```<code>form.ajaxSubmit({
    async: false,
    type: yourMethod,
    url: yourRoute,
    headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
    dataType: 'json',
    success: function(data){
        location.href = data.redirect_to;
    },
    error: function(data) {
        var errors = data.responseJSON;
        var errorsArr = [];
        for (error in errors) {
            errorsArr.push(errors[error]);
        }

        errorsArr = $.map(errorsArr, function(n){
            return n;
        });

        alert("<strong class='text-danger'>" + errorsArr.join("<br>") + "</strong>");
        console.log(errors);

    }
});
</code>```

and in your controller store method make return:

```<code>return response()->json(['redirect_to' => '/your_route']);
</code>```

Body:
I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

public function store(CustomFormRequest $request)
{
  //
}

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}

Could you please help ?
Thanks in advance.

Body:
try this:

form.ajaxSubmit({
    async: false,
    type: yourMethod,
    url: yourRoute,
    headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
    dataType: 'json',
    success: function(data){
        location.href = data.redirect_to;
    },
    error: function(data) {
        var errors = data.responseJSON;
        var errorsArr = [];
        for (error in errors) {
            errorsArr.push(errors[error]);
        }

        errorsArr = $.map(errorsArr, function(n){
            return n;
        });

        alert("<strong class='text-danger'>" + errorsArr.join("<br>") + "</strong>");
        console.log(errors);

    }
});

and in your controller store method make return:

return response()->json(['redirect_to' => '/your_route']);


问:
Open Sans letter-spacing issue with Firefox on Ubuntu
I have an issue with the letter-spacing in firefox on Ubuntu (Mint). I know that there are differences between browsers and how they render fonts, but I don't have this problem in Firefox on Windows (Nor do we have it on Chrome in Ubuntu).

Below is an example of the problem:

Font difference over different browsers

Code of the "TV - AUDIO" header:

body {
 font-family:             'Source Sans Pro', sans-serif;
 font-size:               13px;
 -webkit-font-smoothing:  antialiased;
 -moz-osx-font-smoothing: grayscale;
}

h4.f_h4 {
 font-family:    'Open Sans', sans-serif;
 font-size:      12px;
 font-weight:    bold;
 text-transform: uppercase;
 cursor:         default;
}

ul.f_cats {
 font-family:     'Open Sans', sans-serif;
 font-size:       11px;
 color:           #787878;
 padding-left:    0;
 list-style-type: none;
}

ul.f_cats > li {
 padding: 3px 0;
}

ul.f_cats > li > a {
 font-size:       11px;
 font-weight:     bold;
 color:           #787878;
 text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://fonts.googleapis.com/css?family=Open+Sans|Source+Sans+Pro" rel="stylesheet">

<div class="col-md-2 col-sm-4 col-xs-12 hcats">
  <h4 class="f_h4">TV - AUDIO</h4>
  <ul class="f_cats" id="cats1">
    <li>TELEVISIE</li>
    <li>AUDIO - HIFI</li>
    <li>DVD - BLU-RAY</li>
    <li>RADIO-CD-WEKKER-MP3</li>
    <li>HOOFDTELEFOONS</li>
  </ul>
</div></code>```

We tried the following:

downloading the fonts instead of serving them from the google fonts
api

removing the font smoothing

letter-spacing: 0

font-kernel

using reset.css

and probably some other things that I have forgotten by now.

Adding letter-spacing: -1px; is the only way I currently found to work around it but I feel like this is not a good solution. I'd like to know why this happens and if it can be solved in a more friendly manner.

Thanks in advance!

答:
I think we found the problem.

When including our fonts, we only had 300 and 400 weights enabled, like so:

```<code><link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet">
</code>```

The other font-weights were probably rendered by the browser. Including more solved the problem.

Body:
I have an issue with the letter-spacing in firefox on Ubuntu (Mint). I know that there are differences between browsers and how they render fonts, but I don't have this problem in Firefox on Windows (Nor do we have it on Chrome in Ubuntu).

Below is an example of the problem:

Font difference over different browsers

Code of the "TV - AUDIO" header:

body {
 font-family:             'Source Sans Pro', sans-serif;
 font-size:               13px;
 -webkit-font-smoothing:  antialiased;
 -moz-osx-font-smoothing: grayscale;
}

h4.f_h4 {
 font-family:    'Open Sans', sans-serif;
 font-size:      12px;
 font-weight:    bold;
 text-transform: uppercase;
 cursor:         default;
}

ul.f_cats {
 font-family:     'Open Sans', sans-serif;
 font-size:       11px;
 color:           #787878;
 padding-left:    0;
 list-style-type: none;
}

ul.f_cats > li {
 padding: 3px 0;
}

ul.f_cats > li > a {
 font-size:       11px;
 font-weight:     bold;
 color:           #787878;
 text-decoration: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://fonts.googleapis.com/css?family=Open+Sans|Source+Sans+Pro" rel="stylesheet">

TV - AUDIO

TELEVISIE

AUDIO - HIFI

DVD - BLU-RAY

RADIO-CD-WEKKER-MP3

HOOFDTELEFOONS

We tried the following:

downloading the fonts instead of serving them from the google fonts
api

removing the font smoothing

letter-spacing: 0

font-kernel

using reset.css

and probably some other things that I have forgotten by now.

Adding letter-spacing: -1px; is the only way I currently found to work around it but I feel like this is not a good solution. I'd like to know why this happens and if it can be solved in a more friendly manner.

Thanks in advance!

Body:
I think we found the problem.

When including our fonts, we only had 300 and 400 weights enabled, like so:

<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet">

The other font-weights were probably rendered by the browser. Including more solved the problem.


问:
Is it any way possible to do text shadows with current IE9 beta CSS?
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

```<code>p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}
</code>```

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?

答: IE has shadow filter which should do what you want - http://msdn.microsoft.com/en-us/library/ms533086(VS.85).aspx</p>

Body:
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?


问:
limit maxsockets request package
I try to limit request package maxsockets ,
I use fiddler for testing how much it uses concurrent.

As I see ,it doesnt apply the 10 limit that i try to set.

i dont want request module use more than 10 concurrent

what may i be doing wrong?

```<code>process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var loglar='idler2.txt';
var url = require('url');
var util = require('util');
var http = require('http');
var https = require('https');
var request = require('request');
var fs = require('fs');
var linkler = [];
var starttime = Math.round(new Date().getTime() / 1000);

http.globalAgent.maxSockets = 10;
https.globalAgent.maxSockets = 10;

var timeoutsure = 30 * 1000;
var success=0,fail=0;

process.on('exit', onExit);

function onExit() {
    console.log('\n%d secs,\n%d suc ,\n%d fail\n---------------------\n',
    (Math.round(new Date().getTime() / 1000)) - starttime,success,fail);
}

function logla(data)
{
    var fd = fs.openSync(loglar, 'a+');
    fs.writeSync(fd, data);
    fs.closeSync(fd);
}

for(i=0;i<1000;i++)
{
    sorgutest();
}

var r = request.defaults({'proxy':'http://127.0.0.1:8888',pool: {maxSockets: 10}});

function sorgutest()
{

r.get({url:'https://freegeoip.net/json/',pool: {maxSockets: 10}}, function optionalCallback(err, httpResponse, body) {
  if (err) {
      fail++;
    return console.error('failed: 49', err);
  }
  else {
  try {bodyjson=JSON.parse(body);
  logla(body);
  success++;
  }
  catch(e){console.log("hamina 54");}
  }
});
}
</code>```

答:
As stated in the documentation:

Note that if you are sending multiple requests in a loop and creating multiple new pool objects, maxSockets will not work as intended. To work around this, either use request.defaults with your pool options or create the pool object with the maxSockets property outside of the loop.

try to change the pool option of request.defaults or create a pool object and use it on all request calls.

Edit:

I've noticed that you already used request.default, the fix should be to simply remove the pool option in the r.get call.

from:
r.get({url:'https://freegeoip.net/json/',pool: {maxSockets: 10}}, function optionalCallback(err, httpResponse, body) {

to: r.get({url:'https://freegeoip.net/json/'}, function optionalCallback(err, httpResponse, body) {

Title: limit maxsockets request package

Body:
I try to limit request package maxsockets ,
I use fiddler for testing how much it uses concurrent.

As I see ,it doesnt apply the 10 limit that i try to set.

i dont want request module use more than 10 concurrent

what may i be doing wrong?

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var loglar='idler2.txt';
var url = require('url');
var util = require('util');
var http = require('http');
var https = require('https');
var request = require('request');
var fs = require('fs');
var linkler = [];
var starttime = Math.round(new Date().getTime() / 1000);

http.globalAgent.maxSockets = 10;
https.globalAgent.maxSockets = 10;

var timeoutsure = 30 * 1000;
var success=0,fail=0;

process.on('exit', onExit);

function onExit() {
    console.log('\n%d secs,\n%d suc ,\n%d fail\n---------------------\n',
    (Math.round(new Date().getTime() / 1000)) - starttime,success,fail);
}

function logla(data)
{
    var fd = fs.openSync(loglar, 'a+');
    fs.writeSync(fd, data);
    fs.closeSync(fd);
}

for(i=0;i<1000;i++)
{
    sorgutest();
}

var r = request.defaults({'proxy':'http://127.0.0.1:8888',pool: {maxSockets: 10}});

function sorgutest()
{

r.get({url:'https://freegeoip.net/json/',pool: {maxSockets: 10}}, function optionalCallback(err, httpResponse, body) {
  if (err) {
      fail++;
    return console.error('failed: 49', err);
  }
  else {
  try {bodyjson=JSON.parse(body);
  logla(body);
  success++;
  }
  catch(e){console.log("hamina 54");}
  }
});
}


问:
Should Enterprise Java entities be dumb?
In our legacy Java EE application, there are loads of value object (VO) classes which typically contain only getters and setters, maybe equals() and hashCode(). These are (typically) the entities to be saved in persistence storage. (For the record, our app has no EJBs  - although that might change in the future -, and we use Hibernate for persisting our entities.) All the business logic to manipulate the data in VOs is in separate classes (not EJBs, just POJOs). My OO mindset hates this, as I do believe that the operations on a given class should reside in that same class. So I have an urge to refactor to move logic into the related VOs.

I just had a discussion with a co-worker who is much more experienced in Java EE than me, and he confirmed that dumb entities at least used to be the recommended way to go. However, he has also read opinions recently which question the validity of this stance.

I understand that there are issues which at least limit what can be put inside an entity class:

it should not have direct dependency to the data layer (e.g. query code should rather go into separate DAOs)

if it is directly exposed to higher layers or to the client (e.g. via SOAP), its interface may need to be limited

Are there any more valid reasons not to move logic into my entities? Or any other concerns to take into account?

答:
Entities are frequently generated. In languages like Java there is no such thing as a partial class, so we cannot extend an entity (not considering patterns like Visitor). So when you need to regenerate your entities, you'll have to add the business logic again, which is not at all practical.

With entities I'd rather go for a high cohesion design between entities and their logic.

Other issues to consider are the fact that not all business operations on an entity are equal in all situations. Also, allowing business logic in entities tends to subject the entity to coupling with integration technologies like XML which, in my opinion, should be kept away from domain logic at all times. In an onion architecture, XML would be in the outer shell and domain objects in the inner, to illustrate how far they really are remove from each other if you want to create a reusable pluggable system.


问:
How to write Gson for this code?
In this code I'm parsing JSON and using ArrayList displaying it in a searchable spinner. The code works perfectly but when it comes to parse large JSON then it takes time and memory on mobile data.

Can any one suggest me a better idea to parse large JSON or can any one explain me how to parse it with Gson and loading into the searchable spinner?

   try {
       if (response.has("products_data")) {
            jsonArray = new JSONArray();
               jsonArray = response.getJSONArray("products_data");
            for (int t = 0; t < jsonArray.length(); t++) {
               object = jsonArray.getJSONObject(t);
               retailer_id = object.getString("retailer_id");
               retailer_name = object.getString("retailer_name");
               product_code = object.getString("product_code");
               product_name = object.getString("product_name");
               pro_packing = object.getString("pro_packing");
               pro_company=object.getString("pro_company");
               pro_generic_code=object.getString("pro_generic_code");
               pro_generic_name=object.getString("pro_generic_name");
               pro_stock = object.getInt("product_stock");
               product_MRP=object.getDouble("product_MRP");
               p = new Product();
               p.setRetailer_id(retailer_id);
               p.setRetailer_name(retailer_name);
               p.setProduct_code(product_code);
               p.setProduct_name(product_name);
               p.setPro_packing(pro_packing);
               p.setPro_company(pro_company);
               p.setPro_generic_code(pro_generic_code);
               p.setPro_generic_name(pro_generic_name);
               p.setPro_stock(pro_stock);
               p.setProduct_MRP(product_MRP);
               productlist.add(p);
               }
               progressDialog.dismiss();

         final List<String> pname = new ArrayList<String>();
         final List<String> pcode = new ArrayList<String>();
         pname.clear();
         pname.add(0,"Select Products");
         for (int i = 0; i < productlist.size(); i++) {
                                       pname.add(productlist.get(i).getProduct_name());
                                }
               // Creating adapter for spinner
         final ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_spinnertxt, pname);

                                spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
             runOnUiThread(new Runnable() {
                    @Override
                public void run() {
                       // attaching data adapter to spinner

   autoCompleteTextView.setAdapter(spinnerAdapter);
                                        autoCompleteTextView.setSelection(0);
                                    }
                                });
                                     autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
       public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
          if(i>0) {
         p_id = productlist.get(i - 1).getProduct_code();
         p_stock = productlist.get(i - 1).getPro_stock();
         ppack = productlist.get(i - 1).getPro_packing();
         pcomp = productlist.get(i - 1).getPro_company();
         mrp = productlist.get(i - 1).getProduct_MRP();
         pseller = productlist.get(i - 1).getRetailer_name();
        // Log.i("pID:", p_id);
        //Log.i("pStock:", String.valueOf(p_stock));
         //Log.i("PMRP:", String.valueOf(mrp));
                                        }
                                    }

                                    @Override
  public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });

                            }

                        }
```

<p>This is my JSON Response:</p>

```"products_data": [
{
  "retailer_id": "mum0022",
  "retailer_name": "SAKTI MEDICO",
  "product_code": "6474",
  "product_name": "EPISOFT CLEANSING LOTION",
  "pro_packing": "125ML",
  "pro_company": "GLENMARK-GRACEWELLSPECIALITY",
  "pro_generic_code": "",
  "pro_generic_name": "",
  "product_stock": "7",
  "product_MRP": "209"
},
{
  "retailer_id": "mum0022",
  "retailer_name": "SAKTI MEDICO",
  "product_code": "8403",
  "product_name": "ELOVERA LOTION 150ML (BIG)",
  "pro_packing": "150ML",
  "pro_company": "GLENMARK (DERMAX)",
  "pro_generic_code": "",
  "pro_generic_name": "",
  "product_stock": "3",
  "product_MRP": "324.5"
},
...
```

答:
Try this </p>

```<code>public class Products_data implements Parcelable {
@SerializedName("retailer_id")
private String retailer_id;

@SerializedName("retailer_name")
private String retailer_name;

@SerializedName("product_code")
private String product_code;

@SerializedName("product_name")
private String product_name;

@SerializedName("pro_packing")
private String pro_packing;

@SerializedName("pro_company")
private String pro_company;

@SerializedName("pro_generic_code")
private String pro_generic_code;

@SerializedName("pro_generic_name")
private String pro_generic_name;

@SerializedName("product_stock")
private Integer product_stock;

@SerializedName("product_MRP")
private Double product_MRP;

public Products_data() {
}

protected Products_data(Parcel in) {
    retailer_id = in.readString();
    retailer_name = in.readString();
    product_code = in.readString();
    product_name = in.readString();
    pro_packing = in.readString();
    pro_company = in.readString();
    pro_generic_code = in.readString();
    pro_generic_name = in.readString();
    product_stock = in.readInt();
    product_MRP = in.readDouble();
}

public static final Creator<Products_data> CREATOR = new Creator<Products_data>() {
    @Override
    public Products_data createFromParcel(Parcel in) {
        return new Products_data(in);
    }

    @Override
    public Products_data[] newArray(int size) {
        return new Products_data[size];
    }
};

public String getRetailer_id() {
    return retailer_id;
}

public void setRetailer_id(String retailer_id) {
    this.retailer_id = retailer_id;
}

public String getRetailer_name() {
    return retailer_name;
}

public void setRetailer_name(String retailer_name) {
    this.retailer_name = retailer_name;
}

public String getProduct_code() {
    return product_code;
}

public void setProduct_code(String product_code) {
    this.product_code = product_code;
}

public String getProduct_name() {
    return product_name;
}

public void setProduct_name(String product_name) {
    this.product_name = product_name;
}

public String getPro_packing() {
    return pro_packing;
}

public void setPro_packing(String pro_packing) {
    this.pro_packing = pro_packing;
}

public String getPro_company() {
    return pro_company;
}

public void setPro_company(String pro_company) {
    this.pro_company = pro_company;
}

public String getPro_generic_code() {
    return pro_generic_code;
}

public void setPro_generic_code(String pro_generic_code) {
    this.pro_generic_code = pro_generic_code;
}

public String getPro_generic_name() {
    return pro_generic_name;
}

public void setPro_generic_name(String pro_generic_name) {
    this.pro_generic_name = pro_generic_name;
}

public Integer getProduct_stock() {
    return product_stock;
}

public void setProduct_stock(Integer product_stock) {
    this.product_stock = product_stock;
}

public Double getProduct_MRP() {
    return product_MRP;
}

public void setProduct_MRP(Double product_MRP) {
    this.product_MRP = product_MRP;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(retailer_id);
    parcel.writeString(retailer_name);
    parcel.writeString(product_code);
    parcel.writeString(product_name);
    parcel.writeString(pro_packing);
    parcel.writeString(pro_company);
    parcel.writeString(pro_generic_code);
    parcel.writeString(pro_generic_name);
    parcel.writeInt(product_stock);
    parcel.writeDouble(product_MRP);
}
}
</code>```

<p>After making this POJO class </p>

```<code>gson.fromJson(json, Products_data.class);
</code>```

Title: How to write Gson for this code?

Body:
In this code I'm parsing JSON and using ArrayList displaying it in a searchable spinner. The code works perfectly but when it comes to parse large JSON then it takes time and memory on mobile data.

Can any one suggest me a better idea to parse large JSON or can any one explain me how to parse it with Gson and loading into the searchable spinner?

   try {
       if (response.has("products_data")) {
            jsonArray = new JSONArray();
               jsonArray = response.getJSONArray("products_data");
            for (int t = 0; t < jsonArray.length(); t++) {
               object = jsonArray.getJSONObject(t);
               retailer_id = object.getString("retailer_id");
               retailer_name = object.getString("retailer_name");
               product_code = object.getString("product_code");
               product_name = object.getString("product_name");
               pro_packing = object.getString("pro_packing");
               pro_company=object.getString("pro_company");
               pro_generic_code=object.getString("pro_generic_code");
               pro_generic_name=object.getString("pro_generic_name");
               pro_stock = object.getInt("product_stock");
               product_MRP=object.getDouble("product_MRP");
               p = new Product();
               p.setRetailer_id(retailer_id);
               p.setRetailer_name(retailer_name);
               p.setProduct_code(product_code);
               p.setProduct_name(product_name);
               p.setPro_packing(pro_packing);
               p.setPro_company(pro_company);
               p.setPro_generic_code(pro_generic_code);
               p.setPro_generic_name(pro_generic_name);
               p.setPro_stock(pro_stock);
               p.setProduct_MRP(product_MRP);
               productlist.add(p);
               }
               progressDialog.dismiss();

         final List<String> pname = new ArrayList<String>();
         final List<String> pcode = new ArrayList<String>();
         pname.clear();
         pname.add(0,"Select Products");
         for (int i = 0; i < productlist.size(); i++) {
                                       pname.add(productlist.get(i).getProduct_name());
                                }
               // Creating adapter for spinner
         final ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_spinnertxt, pname);

                                spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
             runOnUiThread(new Runnable() {
                    @Override
                public void run() {
                       // attaching data adapter to spinner

   autoCompleteTextView.setAdapter(spinnerAdapter);
                                        autoCompleteTextView.setSelection(0);
                                    }
                                });
                                     autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
       public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
          if(i>0) {
         p_id = productlist.get(i - 1).getProduct_code();
         p_stock = productlist.get(i - 1).getPro_stock();
         ppack = productlist.get(i - 1).getPro_packing();
         pcomp = productlist.get(i - 1).getPro_company();
         mrp = productlist.get(i - 1).getProduct_MRP();
         pseller = productlist.get(i - 1).getRetailer_name();
        // Log.i("pID:", p_id);
        //Log.i("pStock:", String.valueOf(p_stock));
         //Log.i("PMRP:", String.valueOf(mrp));
                                        }
                                    }

                                    @Override
  public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });

                            }

                        }

This is my JSON Response:

"products_data": [
{
  "retailer_id": "mum0022",
  "retailer_name": "SAKTI MEDICO",
  "product_code": "6474",
  "product_name": "EPISOFT CLEANSING LOTION",
  "pro_packing": "125ML",
  "pro_company": "GLENMARK-GRACEWELLSPECIALITY",
  "pro_generic_code": "",
  "pro_generic_name": "",
  "product_stock": "7",
  "product_MRP": "209"
},
{
  "retailer_id": "mum0022",
  "retailer_name": "SAKTI MEDICO",
  "product_code": "8403",
  "product_name": "ELOVERA LOTION 150ML (BIG)",
  "pro_packing": "150ML",
  "pro_company": "GLENMARK (DERMAX)",
  "pro_generic_code": "",
  "pro_generic_name": "",
  "product_stock": "3",
  "product_MRP": "324.5"
},
...

Body:
Try this

public class Products_data implements Parcelable {
@SerializedName("retailer_id")
private String retailer_id;

@SerializedName("retailer_name")
private String retailer_name;

@SerializedName("product_code")
private String product_code;

@SerializedName("product_name")
private String product_name;

@SerializedName("pro_packing")
private String pro_packing;

@SerializedName("pro_company")
private String pro_company;

@SerializedName("pro_generic_code")
private String pro_generic_code;

@SerializedName("pro_generic_name")
private String pro_generic_name;

@SerializedName("product_stock")
private Integer product_stock;

@SerializedName("product_MRP")
private Double product_MRP;

public Products_data() {
}

protected Products_data(Parcel in) {
    retailer_id = in.readString();
    retailer_name = in.readString();
    product_code = in.readString();
    product_name = in.readString();
    pro_packing = in.readString();
    pro_company = in.readString();
    pro_generic_code = in.readString();
    pro_generic_name = in.readString();
    product_stock = in.readInt();
    product_MRP = in.readDouble();
}

public static final Creator<Products_data> CREATOR = new Creator<Products_data>() {
    @Override
    public Products_data createFromParcel(Parcel in) {
        return new Products_data(in);
    }

    @Override
    public Products_data[] newArray(int size) {
        return new Products_data[size];
    }
};

public String getRetailer_id() {
    return retailer_id;
}

public void setRetailer_id(String retailer_id) {
    this.retailer_id = retailer_id;
}

public String getRetailer_name() {
    return retailer_name;
}

public void setRetailer_name(String retailer_name) {
    this.retailer_name = retailer_name;
}

public String getProduct_code() {
    return product_code;
}

public void setProduct_code(String product_code) {
    this.product_code = product_code;
}

public String getProduct_name() {
    return product_name;
}

public void setProduct_name(String product_name) {
    this.product_name = product_name;
}

public String getPro_packing() {
    return pro_packing;
}

public void setPro_packing(String pro_packing) {
    this.pro_packing = pro_packing;
}

public String getPro_company() {
    return pro_company;
}

public void setPro_company(String pro_company) {
    this.pro_company = pro_company;
}

public String getPro_generic_code() {
    return pro_generic_code;
}

public void setPro_generic_code(String pro_generic_code) {
    this.pro_generic_code = pro_generic_code;
}

public String getPro_generic_name() {
    return pro_generic_name;
}

public void setPro_generic_name(String pro_generic_name) {
    this.pro_generic_name = pro_generic_name;
}

public Integer getProduct_stock() {
    return product_stock;
}

public void setProduct_stock(Integer product_stock) {
    this.product_stock = product_stock;
}

public Double getProduct_MRP() {
    return product_MRP;
}

public void setProduct_MRP(Double product_MRP) {
    this.product_MRP = product_MRP;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(retailer_id);
    parcel.writeString(retailer_name);
    parcel.writeString(product_code);
    parcel.writeString(product_name);
    parcel.writeString(pro_packing);
    parcel.writeString(pro_company);
    parcel.writeString(pro_generic_code);
    parcel.writeString(pro_generic_name);
    parcel.writeInt(product_stock);
    parcel.writeDouble(product_MRP);
}
}

After making this POJO class

gson.fromJson(json, Products_data.class);


问:
How to evaluate the json response from google's JSON/Atom Custom Search API by using php?
How to evaluate the json response from google's JSON/Atom Custom Search API by using php?</p>

答:
use json_decode to convert the response into an object you can iterate through

http://php.net/json_decode

From PHP's site for that function:

```<code><?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
</code>```

Body:
use json_decode to convert the response into an object you can iterate through

http://php.net/json_decode

From PHP's site for that function:

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>


问:
How to access jQuery in HTML 5 web worker
I am unable to to access jQuery inside an HTML5 web worker. Is there a way I can do that?</p>

答:
The answer of Tomáš Zato was correct, but no longer works with newer jQuery version. I added some more for jQuery 3.1.1:</p>

```<code>var document = self.document = { parentNode: null, nodeType: 9, toString: function () { return "FakeDocument" } };
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString = function () { return "FakeElement" };
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;

document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function () { return fakeElement; };
document.createDocumentFragment = function () { return this; };
document.getElementsByTagName = document.getElementsByClassName = function () { return [fakeElement]; };
document.getAttribute = document.setAttribute = document.removeChild =
    document.addEventListener = document.removeEventListener =
    function () { return null; };
document.cloneNode = document.appendChild = function () { return this; };
document.appendChild = function (child) { return child; };
document.childNodes = [];
document.implementation = {
    createHTMLDocument: function () { return document; }
}
</code>```

Body:
The answer of Tomáš Zato was correct, but no longer works with newer jQuery version. I added some more for jQuery 3.1.1:

var document = self.document = { parentNode: null, nodeType: 9, toString: function () { return "FakeDocument" } };
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString = function () { return "FakeElement" };
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;

document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function () { return fakeElement; };
document.createDocumentFragment = function () { return this; };
document.getElementsByTagName = document.getElementsByClassName = function () { return [fakeElement]; };
document.getAttribute = document.setAttribute = document.removeChild =
    document.addEventListener = document.removeEventListener =
    function () { return null; };
document.cloneNode = document.appendChild = function () { return this; };
document.appendChild = function (child) { return child; };
document.childNodes = [];
document.implementation = {
    createHTMLDocument: function () { return document; }
}


问:
How to get file size from url using jquery

  Whistleblower and Complaint Policy filesize
```

答:
Not sure about your application in  details but I have written a small one for my application to get the file size without downloading :

```<code>  var req;
  req = $.ajax({
    type: "HEAD",
    url: $("#url").val(),
    success: function () {
      alert("Size is " + request.getResponseHeader("Content-Length"));
    }
  });
</code>```

Hope this helps.

Body:
Not sure about your application in  details but I have written a small one for my application to get the file size without downloading :

  var req;
  req = $.ajax({
    type: "HEAD",
    url: $("#url").val(),
    success: function () {
      alert("Size is " + request.getResponseHeader("Content-Length"));
    }
  });

Hope this helps.


问:
destruction es6 default value in react's props
<ComponentB from="3/1/2016" to="12/1/2016" />

and in componentB's constructor I can do

const { from, to } = this.props but my from to value is optional. I can't do

this.state = { from, to } if they are or null. Any way to set default value for destruction?

I can do if(from && to) {} but just curious what's the best way to handle optional props in react.

答:
Use default props to set default values to 'to' and 'from' variables.

Component.defaultProps = {
 from: "28/12/1992",
 to: "28/12/1992"
};```


问:
sbt multimodule project importing trait from another module
I have an sbt project with multiple modules, each with their own build.sbt file.

In the root project, I have the following:

```<code>lazy val commonSettings = Seq(
    organization := "com.game.scala",
    sourcesInBase := false,
    fork in run := true,
    scalaVersion := "2.12.1"
)

lazy val common = project.settings(commonSettings)

lazy val original = project.settings(commonSettings).dependsOn(common)

lazy val functional = project.settings(commonSettings).dependsOn(common)

lazy val root = (project in file("."))
  .aggregate(original, functional)
  .settings(commonSettings)
</code>```

The build.sbt in all the submodules are pretty much the same:

```<code>lazy val module = (project in file("."))

  .settings(
    name := "Game subpart",
    version := "0.1.0-SNAPSHOT"
  )
</code>```

And the layout of the project looks something like:

```<code>root
|__ common
|__ original
|__ functional
</code>```

The problem is that from within the functional module, if I try importing a trait declared in common module, I get an error that it is not available:

Error:(1, 12) object game is not a member of package com

import com.game.scala

What am I missing?

答: This is because you never compiled your common project. The dependsOn method only add a dependency to the other project, but do no action on it, unless explicitly asked to. If you want your dependency to be re-compiled whenever the functional module is compiled, you should do both dependsOn(common) and aggregate(common).

Body:
I have an sbt project with multiple modules, each with their own build.sbt file.

In the root project, I have the following:

lazy val commonSettings = Seq(
    organization := "com.game.scala",
    sourcesInBase := false,
    fork in run := true,
    scalaVersion := "2.12.1"
)

lazy val common = project.settings(commonSettings)

lazy val original = project.settings(commonSettings).dependsOn(common)

lazy val functional = project.settings(commonSettings).dependsOn(common)

lazy val root = (project in file("."))
  .aggregate(original, functional)
  .settings(commonSettings)

The build.sbt in all the submodules are pretty much the same:

lazy val module = (project in file("."))

  .settings(
    name := "Game subpart",
    version := "0.1.0-SNAPSHOT"
  )

And the layout of the project looks something like:

root
|__ common
|__ original
|__ functional

The problem is that from within the functional module, if I try importing a trait declared in common module, I get an error that it is not available:

Error:(1, 12) object game is not a member of package com

import com.game.scala

What am I missing?


问:
SendMessage function
can I make the SendMessage function using python instead of c++?

I'm using python for desktop application that connecting to PHP in a web server!

答:
Install pywin32.

And use it like:

```<code>import win32api, win32con

hwnd = ... # obtain it using spy++, etc.

win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_SHIFT, 0)
</code>```

Title: SendMessage function

Body:
Install pywin32.

And use it like:

import win32api, win32con

hwnd = ... # obtain it using spy++, etc.

win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_SHIFT, 0)


问:
Getting a null pointer exception while calling getTimeStamp from firebase database
The first time i run the app after uninstalling & reinstalling sometimes it crashes due to

```<code> viewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString((long) model.getTimestamp()).toString());
</code>```

giving an error

```<code>Exception java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
</code>```

what should i do to solve this issue as after crashing once the next time everything works fine.If you need more codes to guide me then just ask.

答:
you can use it in try catch
like this way.</p>

```<code>try
{
viewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString((long) model.getTimestamp()).toString());
}
catch(Exception e)
{
}
</code>```

Body:
The first time i run the app after uninstalling & reinstalling sometimes it crashes due to

 viewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString((long) model.getTimestamp()).toString());

giving an error

Exception java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference

what should i do to solve this issue as after crashing once the next time everything works fine.If you need more codes to guide me then just ask.

Body:
you can use it in try catch
like this way.

try
{
viewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString((long) model.getTimestamp()).toString());
}
catch(Exception e)
{
}


问:
Breaking a line every 46 characters using Javascript
Im trying to use the following code lines in order to check whether or not the string is larger than 46 characters. If it is longer, it'll break a new line every 46 characters, however, i'm failing to do so.

Can anyone tell me what's wrong?

function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "
   ";
    var newcontent = "";
    var toadd = "";
    if (content.length > 46)
    {
        for (var i = 0, len = content.length; i < len; i++) {
            if(i/46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
            toadd = "";
        }
    }
    return newcontent;
}```

答:
You are doing wrong in for loop & if condition.

```<code>function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "<br/>   ";
    var newcontent = "";
    var toadd = "";
    var len = content.length
    if (len > 46)
    {
        for (var i = 0; i < len; i++) {
            if(i%46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
        }
    }
}
</code>```

Body:
You are doing wrong in for loop & if condition.

function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "<br/>&nbsp; &nbsp;";
    var newcontent = "";
    var toadd = "";
    var len = content.length
    if (len > 46)
    {
        for (var i = 0; i < len; i++) {
            if(i%46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
        }
    }
}


问:
Parsing csv using ANTLR in c#
I have created  following grammar  in ANTLR for parsing csv file.

```<code>grammar CSV;

file returns [List<List<string>> data]
@init {$data = new List<List<string>>();}
 : (row {$data.Add($row.list);})+ EOF
 ;

row returns [List<string> list]
@init {$list = new List<string>();}
 : a=value {
        $list.Add($a.val);
    }
    (Comma b=value {
        $list.Add($b.val);}
        )*
        (LineBreak | EOF)
 ;

value returns [string val]
 : SimpleValue {$val = $SimpleValue.text;}
 | QuotedValue
   {
     System.Console.WriteLine($val);
     $val = $QuotedValue.text;
     $val = $val.Substring(1, $val.Length-1);
     $val = $val.Replace("\"\"", "\"");
   }
 ;

Comma  :
 ( ' '* ',' ' '*);

LineBreak  :
 '\r'? '\n';

SimpleValue
 : ~[,\r\n"]+
 ;

QuotedValue
 : '"' ('""' | ~'"')* '"'
 ;
</code>```

Above grammar is parsing following csv file without error.

```<code>a,b
1,2
3,4
</code>```

but when I am parsing following csv file it's throwing following error

```<code>a,b
,2
3,4

line 2:0 extraneous input ',' expecting {<EOF>, SimpleValue, QuotedValue}
</code>```

can someone guide me how to solve this problem?

Main Program

```<code> public List<List<string>> Parse()
        {
            string csvData = string.Empty;
            if (string.IsNullOrEmpty(_path))
                throw new ArgumentException("Path can not be empty");

            try
            {

                csvData = File.ReadAllText(_path);

            }
            catch (Exception)
            {

                throw new FileNotFoundException(string.Format("{0} not found", _path));
            }

            // create an instance of the lexer
            CSVLexer lexer = new CSVLexer(new AntlrInputStream(csvData));

            // wrap a token-stream around the lexer
            CommonTokenStream tokens = new CommonTokenStream(lexer);

            // create the parser
            CSVParser parser = new CSVParser(tokens);

            // invoke the entry point of our grammar
            _results = parser.file().data;

            return _results;
        }
</code>```

Upadte

As per the Mike Lischke  answer I have updated the row rule as below. Now I am not getting any error

```<code>row returns [List<string> list]
@init {$list = new List<string>();}
 : Comma? a=value {
        $list.Add($a.val);

    }
    (Comma b=value {
        $list.Add($b.val);
        }
        )*
        (LineBreak | EOF)
 ;
</code>```

答:
Obviously your row rule is not flexible enough to handle missing values. You should use something like this instead:

```<code>row: Comma? value (Comma value)*;
</code>```

which adds the possibility for a leading comma (actually a missing first value).

And a recommendation: don't use action code in your grammar to collect the values. Instead create and assign a parse listener to your parser whose methods are triggered during parsing to do all the background work. It keeps the grammar a lot cleaner and allows to use it indepent of the actual target language.

Title: Parsing csv using ANTLR in c#

Body:
I have created  following grammar  in ANTLR for parsing csv file.

grammar CSV;

file returns [List<List<string>> data]
@init {$data = new List<List<string>>();}
 : (row {$data.Add($row.list);})+ EOF
 ;

row returns [List<string> list]
@init {$list = new List<string>();}
 : a=value {
        $list.Add($a.val);
    }
    (Comma b=value {
        $list.Add($b.val);}
        )*
        (LineBreak | EOF)
 ;

value returns [string val]
 : SimpleValue {$val = $SimpleValue.text;}
 | QuotedValue
   {
     System.Console.WriteLine($val);
     $val = $QuotedValue.text;
     $val = $val.Substring(1, $val.Length-1);
     $val = $val.Replace("\"\"", "\"");
   }
 ;

Comma  :
 ( ' '* ',' ' '*);

LineBreak  :
 '\r'? '\n';

SimpleValue
 : ~[,\r\n"]+
 ;

QuotedValue
 : '"' ('""' | ~'"')* '"'
 ;

Above grammar is parsing following csv file without error.

a,b
1,2
3,4

but when I am parsing following csv file it's throwing following error

a,b
,2
3,4

line 2:0 extraneous input ',' expecting {<EOF>, SimpleValue, QuotedValue}

can someone guide me how to solve this problem?

Main Program

 public List<List<string>> Parse()
        {
            string csvData = string.Empty;
            if (string.IsNullOrEmpty(_path))
                throw new ArgumentException("Path can not be empty");

            try
            {

                csvData = File.ReadAllText(_path);

            }
            catch (Exception)
            {

                throw new FileNotFoundException(string.Format("{0} not found", _path));
            }

            // create an instance of the lexer
            CSVLexer lexer = new CSVLexer(new AntlrInputStream(csvData));

            // wrap a token-stream around the lexer
            CommonTokenStream tokens = new CommonTokenStream(lexer);

            // create the parser
            CSVParser parser = new CSVParser(tokens);

            // invoke the entry point of our grammar
            _results = parser.file().data;

            return _results;
        }

Upadte

As per the Mike Lischke  answer I have updated the row rule as below. Now I am not getting any error

row returns [List<string> list]
@init {$list = new List<string>();}
 : Comma? a=value {
        $list.Add($a.val);

    }
    (Comma b=value {
        $list.Add($b.val);
        }
        )*
        (LineBreak | EOF)
 ;

Body:
Obviously your row rule is not flexible enough to handle missing values. You should use something like this instead:

row: Comma? value (Comma value)*;

which adds the possibility for a leading comma (actually a missing first value).

And a recommendation: don't use action code in your grammar to collect the values. Instead create and assign a parse listener to your parser whose methods are triggered during parsing to do all the background work. It keeps the grammar a lot cleaner and allows to use it indepent of the actual target language.


问:
Scalameta inline with maven
I tried to implement scala-meta inline / meta style macro annotation in a scala-maven project. I'm getting following error in the compilation.

```<code>[ERROR] /home/tiran/.../validatable.scala:12: ';' expected but 'def' found.
[ERROR]   inline def apply(defn: Any): Any = meta {
[ERROR]          ^
</code>```

Do we need additional compiler plugin for scala meta to work or, am I missing something here? By the way scalameta dependency is the only dependency i have added. My scala version is 2.11

答:
From https://github.com/scalameta/sbt-macro-example/blob/master/build.sbt:

```<code>// A dependency on macro paradise 3.x is required to both write and expand
// new-style macros.  This is similar to how it works for old-style macro
// annotations and a dependency on macro paradise 2.x.
addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-M7" cross CrossVersion.full),
scalacOptions += "-Xplugin-require:macroparadise",
</code>```

So you need to add the Maven equivalent.

Title: Scalameta inline with maven

Body:
I tried to implement scala-meta inline / meta style macro annotation in a scala-maven project. I'm getting following error in the compilation.

[ERROR] /home/tiran/.../validatable.scala:12: ';' expected but 'def' found.
[ERROR]   inline def apply(defn: Any): Any = meta {
[ERROR]          ^

Do we need additional compiler plugin for scala meta to work or, am I missing something here? By the way scalameta dependency is the only dependency i have added. My scala version is 2.11

Body:
From https://github.com/scalameta/sbt-macro-example/blob/master/build.sbt:

// A dependency on macro paradise 3.x is required to both write and expand
// new-style macros.  This is similar to how it works for old-style macro
// annotations and a dependency on macro paradise 2.x.
addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-M7" cross CrossVersion.full),
scalacOptions += "-Xplugin-require:macroparadise",

So you need to add the Maven equivalent.


问:
Multiple Custom UIPickerViews in the same UIView in swift
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

```<code> @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }
</code>```

答:
Set the tags for pickerview in viewDidLoad as shown below,</p>

```<code>pickerView.tag = 0
duration.tag = 1
</code>```

Body:
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

 @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }

Body:
Set the tags for pickerview in viewDidLoad as shown below,

pickerView.tag = 0
duration.tag = 1


问:
Compiled distribution of Qt application for windows
I was successfully able to compile and run my Qt application. However, when I move the .exe file outside its original path, I found out that I have to manually copy the Qt DLLs (e.g. mingw10.dll, qtcore4.dll). Is there any dynamic way to link these libraries with my application?</p>

答: If the DLLs are on the PATH for the application, then they will be found and work. So, you could add where your Qt binaries/dlls are into the %PATH% environment variable. If you're going to create an installer for your application, you'll need to either package these libraries in so they're in the bin directory - or you'll have to expect every user to install and possibly compile Qt themselves (hint: go with the first option. :) )</p>


问:
How to send (AJAX) POST data to url and redirect to the same url with data?
```<code>jQuery(".w").click(function() {
    var id =jQuery(this).attr('id');

    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
        url: location,
        type:'POST',
        data:{data:id}
    });
});
</code>```

I want to redirect to location along with data, can't use form in my case

答:
I don't see any reason to involve JavaScript in this at all.

If you want to click on an image and submit data via POST, simply use something like

```<code><form method="post" action="http://localhost:8888/Admin/description/description.php">
  <input type="image" name="data" value="your-id-value"
         src="/url/of/some/image">
</form>
</code>```

If that really doesn't float your boat, you could approach it like this...

```<code>jQuery('.w').on('click', function(e) {
  e.preventDefault(); // just in case
  const form = document.createElement('form')
  form.method = 'POST'
  form.action = 'http://localhost:8888/Admin/description/description.php'
  const input = document.createElement('input')
  input.type = 'hidden'
  input.name = 'data'
  input.value = this.id
  form.appendChild(input)
  form.submit()
})
</code>```

Body:
jQuery(".w").click(function() {
    var id =jQuery(this).attr('id');

    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
        url: location,
        type:'POST',
        data:{data:id}
    });
});

I want to redirect to location along with data, can't use form in my case

Body:
I don't see any reason to involve JavaScript in this at all.

If you want to click on an image and submit data via POST, simply use something like

<form method="post" action="http://localhost:8888/Admin/description/description.php">
  <input type="image" name="data" value="your-id-value"
         src="/url/of/some/image">
</form>

If that really doesn't float your boat, you could approach it like this...

jQuery('.w').on('click', function(e) {
  e.preventDefault(); // just in case
  const form = document.createElement('form')
  form.method = 'POST'
  form.action = 'http://localhost:8888/Admin/description/description.php'
  const input = document.createElement('input')
  input.type = 'hidden'
  input.name = 'data'
  input.value = this.id
  form.appendChild(input)
  form.submit()
})


问:
RXJS Switchmap - is it possible on value
Is there a way to switchMap on a particular value ? </p>

```<code> jobsFilter(value) {
    console.log(value);
   value.switchMap(value => this.http.get(`http://localhost:55250/api/search/jobs/${value}`))
      .map(res => res.json());
  }
</code>```

答:
Wrap your simply value inside an Observable "Everything is a Stream" </p>

```<code>Observable.of(yourValue).switchMap(yourSwitchMapFunction)
</code>```

<p>@pixelbits the constructor of a Subject doesn't have any parameter, and less a value, since the productor of values of the Subject are outside the stream, if you want to use a Subject you need to do something like this:</p>

```<code>const mySubject = new Subject<string>();
mySubject.switchMap(mySwitchMapFunction);

mySubject.next(myValue);
</code>```

Body:
Is there a way to switchMap on a particular value ?

 jobsFilter(value) {
    console.log(value);
   value.switchMap(value => this.http.get(`http://localhost:55250/api/search/jobs/${value}`))
      .map(res => res.json());
  }

Body:
Wrap your simply value inside an Observable "Everything is a Stream"

Observable.of(yourValue).switchMap(yourSwitchMapFunction)

@pixelbits the constructor of a Subject doesn't have any parameter, and less a value, since the productor of values of the Subject are outside the stream, if you want to use a Subject you need to do something like this:

const mySubject = new Subject<string>();
mySubject.switchMap(mySwitchMapFunction);

mySubject.next(myValue);


问:
Getting current session id when session data is stored in the ci_Sessions table
I am using ion auth to handle my authorization to controllers and i am storing session data into the database. I can see the session info is being stored into the database.

I am logged in as admin and i need to update the current session data to show that another user is logged in,in short, i am trying to impersonate a user by updating session user id with a user id i know of.

```<code>$user = $this->ion_auth->user()->row();

echo "```";
//print_r($res);
    echo 'Hello  '.$user->email;
echo "```";

    $this->db->order_by('id', 'DESC');
    $this->db->limit(1);
    $last_session = $this->db->get('ci_sessions')->row_array();

    print_r($last_session['data']);//prints current session data
</code>```

The first echo gets the correct email of logged in user and also the correct session data. My question is, is the this line print_r($last_session['data']);

always going to get me my session data even if multiple users are logged in?.

答: Unfortunately no. The session data always change every 5 mins (default) this is set in the config.php <code>$config['sess_time_to_update']</code>. This change only updates an existing session record (if exists) and create new record if doesn't. You can see how it is being handled in the Session.php located in the system/libraries/Session.php. </p>

Body:
I am using ion auth to handle my authorization to controllers and i am storing session data into the database. I can see the session info is being stored into the database.

I am logged in as admin and i need to update the current session data to show that another user is logged in,in short, i am trying to impersonate a user by updating session user id with a user id i know of.

$user = $this->ion_auth->user()->row();

echo "
";
//print_r($res);
    echo 'Hello  '.$user->email;
echo "
";

    $this->db->order_by('id', 'DESC');
    $this->db->limit(1);
    $last_session = $this->db->get('ci_sessions')->row_array();

    print_r($last_session['data']);//prints current session data

The first echo gets the correct email of logged in user and also the correct session data. My question is, is the this line print_r($last_session['data']);

always going to get me my session data even if multiple users are logged in?.

Body: Unfortunately no. The session data always change every 5 mins (default) this is set in the config.php $config['sess_time_to_update']. This change only updates an existing session record (if exists) and create new record if doesn't. You can see how it is being handled in the Session.php located in the system/libraries/Session.php.