问:
Convert value to as many decimal places in iOS?
I have string which has a double values as 2.344.Now i want to have as many decimal places for this number as i get from server.So i maxdecimalPlaces is 2 then i want to have number as 2.34 if maxdecimalplaces is 3 then i want to have number as 2.344.

I don't want to use [NSString StringwithFormat:@"%.2f",value];
because number of decimal places is dynamic.Please tell how can i resolve this issue,

答:
This is how use NSNumberFormatter

```<code>        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.maximumFractionDigits = 2;
        NSLog(@"%@", [formatter stringFromNumber:@(0.3333)]); // output expected .33
</code>```

Hope it helps you.

Body:
This is how use NSNumberFormatter

        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.maximumFractionDigits = 2;
        NSLog(@"%@", [formatter stringFromNumber:@(0.3333)]); // output expected .33

Hope it helps you.


来源: stackexchange

问:
Passing initial values in redux form on page load
I'm passing initial value to redux form. I'm getting the data while componentWillMount.

When the page is loaded, I'm getting error as, Cannot read property 'id' of undefined. If I refresh the page, data will be there.

Can anyone please help me.

This is my code.

```<code>componentWillMount() {
    this.props.actions.getService(this.props.params.Id);
}

 const mapStateToProps = (state) => {
     return {
         initialValues: {
             user_id:state.userInfo.data.user.id,
        }
    }
}
</code>```

Thank you.

答:
Another way you can do this is by using this.props.initialize, which Redux Form adds for you. You could also use lodash's .get method to prevent having to add extensive checks like this: if (nextState.userInfo && nextState.userInfo.data && nextState.userInfo.data.user && nextState.userInfo.data.user.id && nextState.userInfo.data.user.id !== this.state.userInfo.data.user.id)

Something like this should work:

```<code>componentWillReceiveProps = (nextProps) => {
    if (_.get(nextProps, 'userInfo.data.user.id') !== _.get(this.props, 'userInfo.data.user.id')) {
        this.props.initialize({ user_id: nextProps.userInfo.data.user.id });
    }
}

mapStateToProps = (state) => {
    return {
        userInfo: state.userInfo,
    };
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm passing initial value to redux form. I'm getting the data while componentWillMount.

When the page is loaded, I'm getting error as, Cannot read property 'id' of undefined. If I refresh the page, data will be there.

Can anyone please help me.

This is my code.

componentWillMount() {
    this.props.actions.getService(this.props.params.Id);
}

 const mapStateToProps = (state) => {
     return {
         initialValues: {
             user_id:state.userInfo.data.user.id,
        }
    }
}

Thank you.

Body:
Another way you can do this is by using this.props.initialize, which Redux Form adds for you. You could also use lodash's .get method to prevent having to add extensive checks like this: if (nextState.userInfo && nextState.userInfo.data && nextState.userInfo.data.user && nextState.userInfo.data.user.id && nextState.userInfo.data.user.id !== this.state.userInfo.data.user.id)

Something like this should work:

componentWillReceiveProps = (nextProps) => {
    if (_.get(nextProps, 'userInfo.data.user.id') !== _.get(this.props, 'userInfo.data.user.id')) {
        this.props.initialize({ user_id: nextProps.userInfo.data.user.id });
    }
}

mapStateToProps = (state) => {
    return {
        userInfo: state.userInfo,
    };
}


问:
Routing remains same when called again in angular 2
I am calling this route with this method

```<code>onDateChanged(event: IMyDateModel) {

    this.route.navigate(['/user/events',event.formatted]);
}
</code>```

My events component,

```<code>activatedroute.params.subscribe(p => { this.date = p['date?'] });
    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents()
    }
</code>```

When I call it for the first time,it is triggering that component but when i call the same function again from the same route,then the component is not loaded with new values i.e previous route remains unchanged.Can anyone please help me .Thanks.

答:
From Angular tutorial on routing:

```<code>ngOnInit() {
  this.route.params
    // (+) converts string 'id' to a number
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}
</code>```

For more information go to: https://angular.io/docs/ts/latest/guide/router.html

Body:
I am calling this route with this method

onDateChanged(event: IMyDateModel) {

    this.route.navigate(['/user/events',event.formatted]);
}

My events component,

activatedroute.params.subscribe(p => { this.date = p['date?'] });
    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents()
    }

When I call it for the first time,it is triggering that component but when i call the same function again from the same route,then the component is not loaded with new values i.e previous route remains unchanged.Can anyone please help me .Thanks.

Body:
From Angular tutorial on routing:

ngOnInit() {
  this.route.params
    // (+) converts string 'id' to a number
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}

For more information go to: https://angular.io/docs/ts/latest/guide/router.html


问:
Avoiding define macro when making a lot of similar method calls
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

```<code>a.setValueX(20);
b.setValueX(30);
</code>```

I would like to write something like

```<code>set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);
</code>```

Here is code similar to the code I use at the moment:

```<code>#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();
</code>```

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.

答:
Both set(a, b, ValueX, 20, 30) or set<ValueX>(a, 20, b, 30) would require some kind of preprocessing to concatenate "set" and "ValueX" into a new term.

Personally I think a bit of preprocessor is better than a ton of boilerplate, but as @Angew said, you can easily go with the third option:

set(a, b, &PoorLegacyClass::setValueX, 20, 30);

The only thing I wanted to add is you can use variadic templates to make this work for an arbitrary amount of objects:

```<code>template<class T> void set(void (PoorLegacyClass::*setter)(T))
{}

template<class T, typename... Args> void set(void (PoorLegacyClass::*setter)(T),
PoorLegacyClass& obj, T val, Args&&... args)
{
    (obj.*setter)(val);
    set(setter, std::forward<Args>(args)...);
}
</code>```

The call syntax would slightly change in this case:

set(&PoorLegacyClass::setValueX, a, 20, b, 30);

Body:
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

a.setValueX(20);
b.setValueX(30);

I would like to write something like

set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);

Here is code similar to the code I use at the moment:

#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.

Body:
Both set(a, b, ValueX, 20, 30) or set<ValueX>(a, 20, b, 30) would require some kind of preprocessing to concatenate "set" and "ValueX" into a new term.

Personally I think a bit of preprocessor is better than a ton of boilerplate, but as @Angew said, you can easily go with the third option:

set(a, b, &PoorLegacyClass::setValueX, 20, 30);

The only thing I wanted to add is you can use variadic templates to make this work for an arbitrary amount of objects:

template<class T> void set(void (PoorLegacyClass::*setter)(T))
{}

template<class T, typename... Args> void set(void (PoorLegacyClass::*setter)(T),
PoorLegacyClass& obj, T val, Args&&... args)
{
    (obj.*setter)(val);
    set(setter, std::forward<Args>(args)...);
}

The call syntax would slightly change in this case:

set(&PoorLegacyClass::setValueX, a, 20, b, 30);


问:
How to force MySQL out of TRADITIONAL mode?
I have an old application that started failing after an upgrade from MySQL 5.0 to 5.1.

A bit of research indicated this is due to "strict mode" which prevents inserting certain types of "invalid" values which previously were just automatically converted to something reasonable.

I tried SET @@SESSION.sql_mode = '' and SET @@GLOBAL.sql_mode = '' but I still get the error.

Also tried commenting out sql_mode in the my.ini.

Is there a stronger, sort of "nuclear" option to fix this?

答:
To allow invalid dates, you need:

```<code>SET sql_mode = 'ALLOW_INVALID_DATES';
</code>```

But you'd better fix your application.

ContentLicense: CC BY-SA 2.5

Body:
To allow invalid dates, you need:

SET sql_mode = 'ALLOW_INVALID_DATES';

But you'd better fix your application.


问:
Controlling Class Visibility in Java
My project has currently following package structure.

Here I have added a package name utils and defined all utility classes related to this module inside it. Those have been used by other packages (i.e. impl, internal), and because of that I have made classes and methods in util package public.

Because, it is public, not only classes in this module, classes in other modules can also access this and when I am coding using my IDE they are shown as coding suggestions.

I went through few research papers which describe how this can reduce the usability of the API and give a bad experience to developers who involve in the development [ref1, ref2].

I understand that java does not allow me to make classes inside util accessible to impl and internal packages and not to others.

Is it correct to put my utility classes to a package 'util'? Or should I put all classes that communicate with each other to the same package?

答:
Util classes are fine. Util classes are functionality that is used multiple places in a project but doesn't really belong to a specific class.

In a perfect world of OOP there wouldn't be any util classes, but it is however considered a good practice to create util classes if they do not belong to a specific class.

Your options for access modifiers are listed here:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

There is one way to achieve what you you want, it is however concidered a very bad practice. You can change your access modifiers of  util classes to protected. This will make your util classes accessible from subclasses and packages. So if a class needs access to one of the util classes, then it has to extend this util class and thereby become a subclass. I cannot stress it enought, this is a very bad practice.

Title: Controlling Class Visibility in Java


问:
MySQL error : sql_mode=only_full_group_by
i have this script where i'm used to do a simple projection for a dynamic result

```<code>    SELECT
    M.nom_utilisateur,
    SUM(M.montant_bulletin ) as Montant_Total_BS,
    SUM(M.montant_payer   ) as Montant_Total_payer,
    COUNT(M.ref_bs ) as nbr_bs_total,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Remboursé")) as nbr_bs_total_payer,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Non remboursé")) as nbr_bs_non_payer,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "En cours")) as nbr_bs_en_cours,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Nouveau")) as nbr_bs_nouveau
    FROM mutuelle_bi.`Mutuelle` M
    WHERE M.nom_assurence  = "Star"
    GROUP BY M.nom_utilisateur
</code>```

but something goes wrong ; as i have this error :

1055 - Expression #5 of SELECT list is not in GROUP BY clause and
  contains nonaggregated column 'mutuelle_bi.M.etat_bs' which is not
  functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by

How may i modify my script by the way to solve this problem ,
given that i shouldn't modify any config file  of my sql server . and i should only write scripts

Any Suggestions ??

答:
You can also try to disable the only_full_group_by setting:

```<code>set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
</code>```

Worked for me.

Body:
i have this script where i'm used to do a simple projection for a dynamic result

    SELECT
    M.nom_utilisateur,
    SUM(M.montant_bulletin ) as Montant_Total_BS,
    SUM(M.montant_payer   ) as Montant_Total_payer,
    COUNT(M.ref_bs ) as nbr_bs_total,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Remboursé")) as nbr_bs_total_payer,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Non remboursé")) as nbr_bs_non_payer,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "En cours")) as nbr_bs_en_cours,

(SELECT COUNT(*) FROM mutuelle_bi.`Mutuelle` WHERE nom_utilisateur = M.nom_utilisateur  AND (M.nom_assurence  = "Star" AND M.etat_bs = "Nouveau")) as nbr_bs_nouveau
    FROM mutuelle_bi.`Mutuelle` M
    WHERE M.nom_assurence  = "Star"
    GROUP BY M.nom_utilisateur

but something goes wrong ; as i have this error :

1055 - Expression #5 of SELECT list is not in GROUP BY clause and
  contains nonaggregated column 'mutuelle_bi.M.etat_bs' which is not
  functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by

How may i modify my script by the way to solve this problem ,
given that i shouldn't modify any config file  of my sql server . and i should only write scripts

Any Suggestions ??

Body:
You can also try to disable the only_full_group_by setting:

set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Worked for me.


问:
Enrich behavior on spring-data-rest repository
I am using spring-data-rest repositories to expose usual CRUD operations from a REST API.

However i need to add additional functionality to those operations.

e.g. I want to send an HTTP request on delete to a third party API.

I was wondering how to override the behavior of some of the methods provided by JpaRepository (or any other data-rest repo)

Also not sure if this shall be implemented at repository level or providing a custom controller ... in that case i am concerned on how to disable access to repository endpoint so all operations pass through my code.

答:
spring-data-rest supports events.

You can either extend an AbstractRepositoryEventListener or a class annotated with @RepositoryEventHandler.

In your case it would be:

```<code>public class AfterDeleteEventListener extends AbstractRepositoryEventListener {

  @Override
  public void onAfterDelete(Object entity) {
    //your code here
  }
}
</code>```

or

```<code>@RepositoryEventHandler (MyClass.class)
public class MyEventHandler {

  @HandleAfterDelete
  public void handleDelete(MyClass p) {
    // your code here
  }

}
</code>```

Body:
spring-data-rest supports events.

You can either extend an AbstractRepositoryEventListener or a class annotated with @RepositoryEventHandler.

In your case it would be:

public class AfterDeleteEventListener extends AbstractRepositoryEventListener {

  @Override
  public void onAfterDelete(Object entity) {
    //your code here
  }
}

or

@RepositoryEventHandler (MyClass.class)
public class MyEventHandler {

  @HandleAfterDelete
  public void handleDelete(MyClass p) {
    // your code here
  }

}


问:
ProgressBar not showing in some devices
I have the following layout:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.pontai"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.markupartist.android.widget.ActionBar
        android:id="@+id/actionbar"
        style="@style/ActionBar"
        android:layout_marginBottom="3dip"
        app:textStyleActionBar="@style/TextViewStyleHeader"
        app:title="@string/app_name" />

    <com.fb.design.SegmentedButton
        android:id="@+id/main_action_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:btnText1="@string/sb_friends"
        app:btnText2="@string/sb_search"
        app:btnText3="@string/sb_summary"
        app:gradientColorOffEnd="@color/segmented_button_off_end"
        app:gradientColorOffStart="@color/segmented_button_off_start"
        app:gradientColorOnEnd="@color/segmented_button_on_end"
        app:gradientColorOnStart="@color/segmented_button_on_start"
        app:gradientColorSelectedEnd="@color/segmented_button_selected_end"
        app:gradientColorSelectedStart="@color/segmented_button_selected_start"
        app:whichButtonIsSelected="0" />

    <View
        android:layout_width="wrap_content"
        android:layout_height="2dp"
        android:layout_marginBottom="3dip"
        android:background="@drawable/gradient_line" >
    </View>

    <LinearLayout
        android:id="@+id/linearLayout7"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/buttonAddFriends"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_input_add"
                android:clickable="true"
                android:height="40dp"
                android:width="40dp" />

            <EditText
                android:id="@+id/search_box"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="@string/type_here_to_filter"
                android:inputType="text"
                android:maxLines="1"
                android:padding="10dp" >
            </EditText>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/loadingPanel"
            style="@style/GenericProgressBackground"
            android:layout_height="match_parent" >

            <ProgressBar style="@style/GenericProgressIndicator" />
        </LinearLayout>

        <ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />

        <TextView
            android:id="@id/android:empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:text="@string/empty_results" />
    </LinearLayout>
</LinearLayout>
</code>```

My Activity has a AsyncTask that upon completion does the following:

```<code>((LinearLayout)findViewById(R.id.loadingPanel)).setVisibility(View.GONE);
</code>```

So, basically I have a LinearLayout holding my ProgressBar and, when I have the data I need, I set the visibility to GONE for this linearlayout.

This is working find on my Galaxy Nexus, but it's not working on my API 8 Emulator and also in the Galaxy S2, using a custom ROM.

Has anyone ever seen this?

My worst case scenario will be removing this linearlayout with a progress bar from the XML and add a ProgressDialog in the code.

Regards,
Felipe

UPDATE

This is how I defined the styles.xml

```<code> <style name="GenericProgressBackground" parent="android:Theme">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">fill_parent</item>
        <item name="android:background">#77ffffff</item>
        <item name="android:gravity">center</item>
    </style>

    <style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Large">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:indeterminate">true</item>
    </style>
</code>```

UPDATE2
I fixed the issue

```<code> <ProgressBar
                android:id="@+id/progressBar1"
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
</code>```

I added the style coming from the android attributes and that alone worked... I have no idea why it didnt work with the style I created... it's weird.

Thanks for the help! :)

答: This can happen on some devices when animations are turned off. Turn your animations on again and you should be fine.</p>

Title: ProgressBar not showing in some devices

Body:
I have the following layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.pontai"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.markupartist.android.widget.ActionBar
        android:id="@+id/actionbar"
        style="@style/ActionBar"
        android:layout_marginBottom="3dip"
        app:textStyleActionBar="@style/TextViewStyleHeader"
        app:title="@string/app_name" />

    <com.fb.design.SegmentedButton
        android:id="@+id/main_action_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:btnText1="@string/sb_friends"
        app:btnText2="@string/sb_search"
        app:btnText3="@string/sb_summary"
        app:gradientColorOffEnd="@color/segmented_button_off_end"
        app:gradientColorOffStart="@color/segmented_button_off_start"
        app:gradientColorOnEnd="@color/segmented_button_on_end"
        app:gradientColorOnStart="@color/segmented_button_on_start"
        app:gradientColorSelectedEnd="@color/segmented_button_selected_end"
        app:gradientColorSelectedStart="@color/segmented_button_selected_start"
        app:whichButtonIsSelected="0" />

    <View
        android:layout_width="wrap_content"
        android:layout_height="2dp"
        android:layout_marginBottom="3dip"
        android:background="@drawable/gradient_line" >
    </View>

    <LinearLayout
        android:id="@+id/linearLayout7"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/buttonAddFriends"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_input_add"
                android:clickable="true"
                android:height="40dp"
                android:width="40dp" />

            <EditText
                android:id="@+id/search_box"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="@string/type_here_to_filter"
                android:inputType="text"
                android:maxLines="1"
                android:padding="10dp" >
            </EditText>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/loadingPanel"
            style="@style/GenericProgressBackground"
            android:layout_height="match_parent" >

            <ProgressBar style="@style/GenericProgressIndicator" />
        </LinearLayout>

        <ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />

        <TextView
            android:id="@id/android:empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:text="@string/empty_results" />
    </LinearLayout>
</LinearLayout>

My Activity has a AsyncTask that upon completion does the following:

((LinearLayout)findViewById(R.id.loadingPanel)).setVisibility(View.GONE);

So, basically I have a LinearLayout holding my ProgressBar and, when I have the data I need, I set the visibility to GONE for this linearlayout.

This is working find on my Galaxy Nexus, but it's not working on my API 8 Emulator and also in the Galaxy S2, using a custom ROM.

Has anyone ever seen this?

My worst case scenario will be removing this linearlayout with a progress bar from the XML and add a ProgressDialog in the code.

Regards,
Felipe

UPDATE

This is how I defined the styles.xml

UPDATE2
I fixed the issue

 <ProgressBar
                android:id="@+id/progressBar1"
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

I added the style coming from the android attributes and that alone worked... I have no idea why it didnt work with the style I created... it's weird.

Thanks for the help! :)


问:
Numpy: how to convert observations to probabilities?
I have a feature matrix and a corresponding targets, which are ones or zeroes:

```<code># raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])
</code>```

As you can see, each feature may correspond to both ones and zeros. I need to convert my raw observation matrix to probability matrix, where each feature will correspond to the probability of seeing one as  a target:

```<code>[1 1 0] -> 0.5
[0 1 0] -> 0.67
[0 0 1] -> 0
</code>```

I have constructed a quite straight-forward solution:

```<code>import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

from collections import Counter

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    zeros = Counter()
    ones = Counter()

    # collect row-wise number of one and zero targets
    for i, row in enumerate(features[:]):
        if targets[i] == 0:
            zeros[tuple(row)] += 1
        else:
            ones[tuple(row)] += 1

    # iterate over unique features and compute probabilities
    for k in idx:
        unique_row = features[k]

        zero_count = zeros[tuple(unique_row)]
        one_count = ones[tuple(unique_row)]

        proba = float(one_count) / float(zero_count + one_count)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)
</code>```

which:

extracts unique features;

counts number of zero and one observations targets for each unique feature;

computes probability and constructs the result.

Could it be solved in a prettier way using some advanced numpy magic?

Update. Previous code was pretty inefficient O(n^2). Converted it to more performance-friendly. Old code:

```<code>import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    # calculate ZERO class occurences and ONE class occurences
    for k in idx:
        unique_row = features[k]

        zeros = 0
        ones = 0

        for i, row in enumerate(features[:]):
            if np.array_equal(row, unique_row):
                if targets[i] == 0:
                    zeros += 1
                else:
                    ones += 1

        proba = float(ones) / float(zeros + ones)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)
</code>```

答:
```<code>np.sum(np.reshape([targets[f] if tuple(features[f])==tuple(i) else 0 for i in np.vstack(set(map(tuple,features))) for f in range(features.shape[0])],features.shape[::-1]),axis=1)/np.sum(np.reshape([1 if tuple(features[f])==tuple(i) else 0 for i in np.vstack(set(map(tuple,features))) for f in range(features.shape[0])],features.shape[::-1]),axis=1)
</code>```

Here you go, numpy magic! Although unnecceserily so, this could probably be cleaned up using some boring variables ;)
(And this is probably far from optimal)

Body:
I have a feature matrix and a corresponding targets, which are ones or zeroes:

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

As you can see, each feature may correspond to both ones and zeros. I need to convert my raw observation matrix to probability matrix, where each feature will correspond to the probability of seeing one as  a target:

[1 1 0] -> 0.5
[0 1 0] -> 0.67
[0 0 1] -> 0

I have constructed a quite straight-forward solution:

import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

from collections import Counter

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    zeros = Counter()
    ones = Counter()

    # collect row-wise number of one and zero targets
    for i, row in enumerate(features[:]):
        if targets[i] == 0:
            zeros[tuple(row)] += 1
        else:
            ones[tuple(row)] += 1

    # iterate over unique features and compute probabilities
    for k in idx:
        unique_row = features[k]

        zero_count = zeros[tuple(unique_row)]
        one_count = ones[tuple(unique_row)]

        proba = float(one_count) / float(zero_count + one_count)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)

which:

extracts unique features;

counts number of zero and one observations targets for each unique feature;

computes probability and constructs the result.

Could it be solved in a prettier way using some advanced numpy magic?

Update. Previous code was pretty inefficient O(n^2). Converted it to more performance-friendly. Old code:

import numpy as np

# raw observations
features = np.array([[1, 1, 0],
                     [1, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 1, 0],
                     [0, 0, 1]])

targets = np.array([1, 0, 1, 1, 0, 0])

def convert_obs_to_proba(features, targets):
    features_ = []
    targets_ = []

    # compute unique rows (idx will point to some representative)
    b = np.ascontiguousarray(features).view(np.dtype((np.void, features.dtype.itemsize * features.shape[1])))
    _, idx = np.unique(b, return_index=True)

    idx = idx[::-1]

    # calculate ZERO class occurences and ONE class occurences
    for k in idx:
        unique_row = features[k]

        zeros = 0
        ones = 0

        for i, row in enumerate(features[:]):
            if np.array_equal(row, unique_row):
                if targets[i] == 0:
                    zeros += 1
                else:
                    ones += 1

        proba = float(ones) / float(zeros + ones)

        features_.append(unique_row)
        targets_.append(proba)

    return np.array(features_), np.array(targets_)

features_, targets_ = convert_obs_to_proba(features, targets)

print(features_)
print(targets_)

Body:
np.sum(np.reshape([targets[f] if tuple(features[f])==tuple(i) else 0 for i in np.vstack(set(map(tuple,features))) for f in range(features.shape[0])],features.shape[::-1]),axis=1)/np.sum(np.reshape([1 if tuple(features[f])==tuple(i) else 0 for i in np.vstack(set(map(tuple,features))) for f in range(features.shape[0])],features.shape[::-1]),axis=1)

Here you go, numpy magic! Although unnecceserily so, this could probably be cleaned up using some boring variables ;)
(And this is probably far from optimal)


问:
parsleyjs with multi steps form
I'mn creating a multi step form wizard (using Twitter Bootstrap Wizard) and looking at the Parsley multi step example I'm not sure how I would implement it if I have more then two steps my current form has at least 4 steps.

This is what I don't understand

```<code><span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span>
</code>```

My next button is constant

Here is the parsley example

```<code><form id="demo-form" data-parsley-validate>
  <div class="first block1 show">
    <label for="firstname">Firstname:</label>
    <input type="text" name="firstname" data-parsley-group="block1" required/>

    <label for="lastname">Lastname:</label>
    <input type="text" name="lastname" data-parsley-group="block1" required />
    <span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span>
  </div>

  <div class="second block2 hidden">
    <label for="fullname">Email:</label>
    <input type="text" name="fullname" required  data-parsley-type="email" data-parsley-group="block2" />
    <span class="next btn btn-info pull-left" data-current-block="2" data-next-block="1">< Previous</span>
    <input type="submit" class="btn btn-default pull-right" />
  </div>
</form>

<script type="text/javascript">
$(document).ready(function () {
  $('.next').on('click', function () {
    var current = $(this).data('currentBlock'),
      next = $(this).data('nextBlock');

    // only validate going forward. If current group is invalid, do not go further
    // .parsley().validate() returns validation result AND show errors
    if (next > current)
      if (false === $('#demo-form').parsley().validate('block' + current))
        return;

    // validation was ok. We can go on next step.
    $('.block' + current)
      .removeClass('show')
      .addClass('hidden');

    $('.block' + next)
      .removeClass('hidden')
      .addClass('show');

  });
});
</script>
</code>```

答:
I know this is late, but could help someone else in need .Had similar problem and this is how i solved it.

i added this to each control i need to validate on each steps
add this to step1 controls :   data-parsley-group="block-1"
add this to step2 controls:   data-parsley-group="block-2"

....keep increasing for each steps.

in your bootstrapwizard javascript add the code below in the 'OnNext' fuction.

```<code>$('#form').bootstrapWizard({
        tabClass: 'wizard-steps',

       'onNext': function (tab, navigation, index) {
       var $valid = $("#form").parsley().validate({ group: 'block-' + index });
            if(!$valid) {
                return false;
            }
}
});
</code>```

Hope this helps you out.

Title: parsleyjs with multi steps form

Body:
I'mn creating a multi step form wizard (using Twitter Bootstrap Wizard) and looking at the Parsley multi step example I'm not sure how I would implement it if I have more then two steps my current form has at least 4 steps.

This is what I don't understand

Next >

My next button is constant

Here is the parsley example

<form id="demo-form" data-parsley-validate>

    Firstname:
    <input type="text" name="firstname" data-parsley-group="block1" required/>

    Lastname:
    <input type="text" name="lastname" data-parsley-group="block1" required />
    Next >

    Email:
    <input type="text" name="fullname" required  data-parsley-type="email" data-parsley-group="block2" />
    < Previous
    <input type="submit" class="btn btn-default pull-right" />

</form>

Body:
I know this is late, but could help someone else in need .Had similar problem and this is how i solved it.

i added this to each control i need to validate on each steps
add this to step1 controls :   data-parsley-group="block-1"
add this to step2 controls:   data-parsley-group="block-2"

....keep increasing for each steps.

in your bootstrapwizard javascript add the code below in the 'OnNext' fuction.

$('#form').bootstrapWizard({
        tabClass: 'wizard-steps',

       'onNext': function (tab, navigation, index) {
       var $valid = $("#form").parsley().validate({ group: 'block-' + index });
            if(!$valid) {
                return false;
            }
}
});

Hope this helps you out.


问:
Cannot append to textarea after clearing value
I have a dropdown select that appends to a text area on change.  I set a simple button to clear it out which works but afterwords I cannot re-append from the dropdown select.

Fiddle: https://jsfiddle.net/kreza/noy5gqfL/6/

jquery snippet:

```<code>$('#criteriaSelect').change(function () {
    $('#inputCriteria').append((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});
</code>```

What am I doing wrong?

答:
use like this $('#inputCriteria').val($('#inputCriteria').val()+$(this).val() + ';' + '\n');

don't use with append.to avoid the append event in input,textarea tag

$('#criteriaSelect').change(function () {

  $('#inputCriteria').val($('#inputCriteria').val()+$(this).val() + ';' + '\n');
    });
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select type="text" class="form-control" id="criteriaSelect">
  <option disabled selected>Select One:</option>
  <option value="AASHTO">AASHTO Roadside Design Guide</option>
  <option value="RAMCAP">AWWA Risk and Resilience Management of Water and Wastewater Systems (RAMCAP)</option>
  <option value="CDOT DDM">CDOT Drainage Design Manual</option>
  <option value="CDOT MSS">CDOT M&S Standards</option>
  <option value="CDOT SSRBD">CDOT Standard Specifications for Road and Bridge Construction</option>
  <option value="CHPHE DWTW">CHPHE Design Criteria for Domestic Wastewater Treatment Works</option>
  <option value="CDPHE PWS">CDPHE Design Criteria for Potable Water Systems</option>
  <option value="CWCB FSCM">CWCB Floodplain Stormwater and Criteria Manual</option>k
  <option value="FHWA FIRBD">FHWA Framework for Improving Resilience of Bridge Design</option>
  <option value="FHWA Highways">FHWA Highways in the River Environment- Floodplains, Extreme Events, Risk and Resilience</option>
  <option value="FHWA CRBFHP">FHWA Standard Specs for Construction of Roads and Bridges on Federal Highway Projects</option>
  <option value="UDFCD USD">UDFCD Urban Storm Drainage Criteria Manuals</option>
  <option value="DSDM">Rules and Regulations for Dam Safety and Dam Construction</option>
  <option value="Other">Other Manuals Used</option>
</select>
<label for="inputCriteria" class="control-label">Select from drop-down:</label>
<textarea class="form-control" rows="3" id="inputCriteria" style="resize: none;" disabled></textarea>
<button class="btn-danger col-sm-2" id="clearTextArea">Clear</button></code>```

Body:
I have a dropdown select that appends to a text area on change.  I set a simple button to clear it out which works but afterwords I cannot re-append from the dropdown select.

Fiddle: https://jsfiddle.net/kreza/noy5gqfL/6/

jquery snippet:

$('#criteriaSelect').change(function () {
    $('#inputCriteria').append((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});

What am I doing wrong?

Body:
use like this $('#inputCriteria').val($('#inputCriteria').val()+$(this).val() + ';' + '\n');

don't use with append.to avoid the append event in input,textarea tag

$('#criteriaSelect').change(function () {

  $('#inputCriteria').val($('#inputCriteria').val()+$(this).val() + ';' + '\n');
    });
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select type="text" class="form-control" id="criteriaSelect">
  <option disabled selected>Select One:</option>
  <option value="AASHTO">AASHTO Roadside Design Guide</option>
  <option value="RAMCAP">AWWA Risk and Resilience Management of Water and Wastewater Systems (RAMCAP)</option>
  <option value="CDOT DDM">CDOT Drainage Design Manual</option>
  <option value="CDOT MSS">CDOT M&S Standards</option>
  <option value="CDOT SSRBD">CDOT Standard Specifications for Road and Bridge Construction</option>
  <option value="CHPHE DWTW">CHPHE Design Criteria for Domestic Wastewater Treatment Works</option>
  <option value="CDPHE PWS">CDPHE Design Criteria for Potable Water Systems</option>
  <option value="CWCB FSCM">CWCB Floodplain Stormwater and Criteria Manual</option>k
  <option value="FHWA FIRBD">FHWA Framework for Improving Resilience of Bridge Design</option>
  <option value="FHWA Highways">FHWA Highways in the River Environment- Floodplains, Extreme Events, Risk and Resilience</option>
  <option value="FHWA CRBFHP">FHWA Standard Specs for Construction of Roads and Bridges on Federal Highway Projects</option>
  <option value="UDFCD USD">UDFCD Urban Storm Drainage Criteria Manuals</option>
  <option value="DSDM">Rules and Regulations for Dam Safety and Dam Construction</option>
  <option value="Other">Other Manuals Used</option>
</select>
<label for="inputCriteria" class="control-label">Select from drop-down:</label>
<textarea class="form-control" rows="3" id="inputCriteria" style="resize: none;" disabled></textarea>
<button class="btn-danger col-sm-2" id="clearTextArea">Clear</button>


问:
Div background-color change upon drop-down
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

```<code><ul class="dropdown-menu">
    <li id="red"><a href="#">Red</a>
    </li>
    <li><a href="#">Blue</a>
    </li>
    <li><a href="#">Green</a>
    </li>
    <li><a href="#">Yellow</a>
    </li>
</ul>
</code>```

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

答:
Try this simple code

Demo

Code:

```<code><div class="btn-group"> <a class="btn " href="#">Dropdown 1</a>
 <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>

    <ul class="dropdown-menu">
        <li data-color="red"><a href="#">Red</a>
        </li>
        <li data-color="blue"><a href="#">Blue</a>
        </li>
        <li data-color="green"><a href="#">Green</a>
        </li>
        <li data-color="yellow"><a href="#">Yellow</a>
        </li>
    </ul>
</div>

<div id ="box"><div>

$( document ).ready(function() {
 $('.dropdown-menu li').click(function(){
        var color = $(this).data("color");

        $("#box").css('background-color',color);
        });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

Red

Blue

Green

Yellow

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

Body:
Try this simple code

Demo

Code:

<div class="btn-group"> <a class="btn " href="#">Dropdown 1</a>
 <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>

    <ul class="dropdown-menu">
        <li data-color="red"><a href="#">Red</a>
        </li>
        <li data-color="blue"><a href="#">Blue</a>
        </li>
        <li data-color="green"><a href="#">Green</a>
        </li>
        <li data-color="yellow"><a href="#">Yellow</a>
        </li>
    </ul>
</div>

<div id ="box"><div>

$( document ).ready(function() {
 $('.dropdown-menu li').click(function(){
        var color = $(this).data("color");

        $("#box").css('background-color',color);
        });
});


问:
Trying to drop NaN indexed row in dataframe
I'm using python 2.7.3 and Pandas version 0.12.0.

I want to drop the row with the NaN index so that I only have valid site_id values.

```<code>print df.head()
            special_name
site_id
NaN          Banana
OMG          Apple

df.drop(df.index[0])

TypeError: 'NoneType' object is not iterable
</code>```

If I try dropping a range, like this:

```<code>df.drop(df.index[0:1])
</code>```

I get this error:

```<code>AttributeError: 'DataFrame' object has no attribute 'special_name'
</code>```

答:
As of pandas 0.19, Indexes do have a .notnull() method, so the answer by timdiels can be simplified to:

```<code>df[df.index.notnull()]
</code>```

which I think is (currently) the simplest you can get.

Body:
I'm using python 2.7.3 and Pandas version 0.12.0.

I want to drop the row with the NaN index so that I only have valid site_id values.

print df.head()
            special_name
site_id
NaN          Banana
OMG          Apple

df.drop(df.index[0])

TypeError: 'NoneType' object is not iterable

If I try dropping a range, like this:

df.drop(df.index[0:1])

I get this error:

AttributeError: 'DataFrame' object has no attribute 'special_name'

Body:
As of pandas 0.19, Indexes do have a .notnull() method, so the answer by timdiels can be simplified to:

df[df.index.notnull()]

which I think is (currently) the simplest you can get.


问:
Do I need to submit my IOS app if I only need the link valid
It's the first time I submit a app to apple. I have a app need to start from click an email link, I'm trying deep linking and I want to test it now, so I need a link from apple, I get that link from my ITunes Connect, now my APP is in 1.0 prepare to submit. but when I click the link it cannot find in itunes, is it means I have to submit app to apple now, its not finish so I afraid apple will reject it. or there's some other way to do it? Thank you!</p>

答:
After pass apple's review, I found out the link I need is not a itunes link. itunes link is for user did not installed my App. I was need open my App from another link in email.
what i need to do is add a url scheme in plist. the following link is best guide for what should do:
link

and add conference to server and ios part as this
, and this.


问:
Horizontal-scrolling text won't scroll when text is non-english
here is the website:    http://yumeituan.host.181idc.com/

the text of image below is english.
when the text inside the "barword" div changed to non-english text , then it did not scroll or draggle.
can anyone figure it out.
thx.

here is the css code:

```<code>.share-left{
    background:url(images/share-left.png) no-repeat 0 0;
    width:21px;
    height:30px;
    float:left;
}
#bar{
    float:left;
    position:relative;
    background:url(images/bg-share-corner.png) no-repeat -39px 0;
    height:22px;
    padding-top:8px;
    width:128px;
    overflow:hidden;
}
#barword{
    position:relative;
    width:128px;
    height:22px;
    overflow:hidden;
}
.share-right{
    background:url(images/bg-share-corner.png) no-repeat 100% -50px;
    width:21px;
    height:30px;
    float:left;
}
</code>```

html code:

```<code>  <div class="share-left">
    </div>
    <div id="bar">
    <div id="barword">aaaaaaaaabbbbbbbbbbbbbcccccccccccccddddddddddd</div>
    </div>
    <div class="share-right">
    </div>
</code>```

js code:

```<code> <script type="text/javascript">
var scrollingBox;
var scrollingInterval;
var delay=100;
var dragging=false;
var test;
var mouseY;
var mouseX;
window.onload = function(){
    test = document.getElementById("barword");
    test.onmousedown = down;
    test.onmousemove = move;
    test.onmouseup = up;

    //test.style.position = "relative";
    //test.style.top = "0px";
    //test.style.left = "0px";
}
function down(event)
{
    event = event || window.event;
    dragging = true;
    mouseX = parseInt(event.clientX);
    mouseY = parseInt(event.clientY);
    //objY = parseInt(test.style.top);
    //objX = parseInt(test.style.left);
}
function move(event){
    event = event || window.event;
    if(dragging == true){
    var x,y;
    //y = event.clientY - mouseY + objY;
    //x = event.clientX ;
    //test.style.top = y + "px";
    //test.style.left = x + "px";
    test.scrollLeft=3*(event.clientX-713);  //0~272
    //console.log(test.scrollLeft);//713~839

    }
}
function up(){
    dragging = false;
}
//1.初始化滚动新闻
function initScrolling(obj){
    scrollingBox = document.getElementById(obj);
    //scrollingBox.style.width = "20px";
    //scrollingBox.style.overflow = "hidden";
    scrollingInterval = setInterval("scrolling()",delay);
    scrollingBox.onmouseover=function(){
    clearInterval(scrollingInterval);
    };
    scrollingBox.onmouseout=function(){
    scrollingInterval = setInterval("scrolling()",delay);
    }
}
//3.滚动效果
function scrolling(){
    //开始滚动
    scrollingBox.scrollLeft++;
    var origin = scrollingBox.scrollLeft++;
    //console.log(test.scrollLeft);
    if(origin == scrollingBox.scrollLeft){
    //延时固定时间后返回顶部
    setTimeout("scrollingBox.scrollLeft=0",1000)
    }
}
initScrolling("barword");
</script>
</code>```

答:
The problem is not related to English or non-English text. It's caused because you put blank space between words.

To solve the problem, add <nobr> around the text, for example:

```<code><div id="barword"><nobr>远大路金源店：海淀区远大路1号金源时代购物中心5层</nobr></div>
</code>```

The reason this is happening is the script is using "scrollLeft" to make the text scroll... by default when there are blank spaces in the text, it's being wrapped to new lines thus scrollLeft will always be zero. By adding the <nobr> tag you force the whole text in one line and the scrollLeft has the desired effect.

Body:
here is the website:    http://yumeituan.host.181idc.com/

the text of image below is english.
when the text inside the "barword" div changed to non-english text , then it did not scroll or draggle.
can anyone figure it out.
thx.

here is the css code:

.share-left{
    background:url(images/share-left.png) no-repeat 0 0;
    width:21px;
    height:30px;
    float:left;
}
#bar{
    float:left;
    position:relative;
    background:url(images/bg-share-corner.png) no-repeat -39px 0;
    height:22px;
    padding-top:8px;
    width:128px;
    overflow:hidden;
}
#barword{
    position:relative;
    width:128px;
    height:22px;
    overflow:hidden;
}
.share-right{
    background:url(images/bg-share-corner.png) no-repeat 100% -50px;
    width:21px;
    height:30px;
    float:left;
}

html code:

aaaaaaaaabbbbbbbbbbbbbcccccccccccccddddddddddd

js code:

Body:
The problem is not related to English or non-English text. It's caused because you put blank space between words.

To solve the problem, add <nobr> around the text, for example:

<div id="barword"><nobr>远大路金源店：海淀区远大路1号金源时代购物中心5层</nobr></div>

The reason this is happening is the script is using "scrollLeft" to make the text scroll... by default when there are blank spaces in the text, it's being wrapped to new lines thus scrollLeft will always be zero. By adding the <nobr> tag you force the whole text in one line and the scrollLeft has the desired effect.


问:
Set Table Column width problems in iText7
When I want to create table in PDF, I can use the following two ways:
But the first one failed.

method 1:

```<code>float[] columnWidths = {20, 30, 50};
Table table = new Table(columnWidths);
</code>```

It's failed to control columnWidths
method 2:

```<code>UnitValue[] unitValue = new UnitValue[]{
UnitValue.createPercentValue((float) 20),
UnitValue.createPercentValue((float) 30),
UnitValue.createPercentValue((float) 50)};
Table table = new Table(columnWidths);
</code>```

It's success!
Why does this happen?

答:
Yes, there is no way to scale column widths in iText 7.0.2, as Vernon said.

If you want to use directly 20, 30, and 50 points for columns despite min widths you shall use this construction:

```<code>Table table = new Table(new float[] {20, 30, 50}) // in points
        .setWidth(100) //100 pt
        .setFixedLayout();
</code>```

If you set fixed layout you must set width as well, it is required for fixed layout.

Body:
When I want to create table in PDF, I can use the following two ways:
But the first one failed.

method 1:

float[] columnWidths = {20, 30, 50};
Table table = new Table(columnWidths);

It's failed to control columnWidths
method 2:

UnitValue[] unitValue = new UnitValue[]{
UnitValue.createPercentValue((float) 20),
UnitValue.createPercentValue((float) 30),
UnitValue.createPercentValue((float) 50)};
Table table = new Table(columnWidths);

It's success!
Why does this happen?

Body:
Yes, there is no way to scale column widths in iText 7.0.2, as Vernon said.

If you want to use directly 20, 30, and 50 points for columns despite min widths you shall use this construction:

Table table = new Table(new float[] {20, 30, 50}) // in points
        .setWidth(100) //100 pt
        .setFixedLayout();

If you set fixed layout you must set width as well, it is required for fixed layout.


问:
C++ - Method/Member access
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

```<code>class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

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

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?

答:
The «access control» happen at compile time and only for c++ code. you even not need edit the machine code - you can easy call private methods from assembly language - so this demonstrate that this is only for c++ restriction. and of course no any additional machine code that controls that in run-time - this at all impossible control who call method.

simply demo . note function names, how it mangled depended from x86 or x64 compiling and from compiler probably - my demo for CL compiler and x64 platform bat it can be easy changed to x86 or other compiler

c++ code

```<code>class Print
{
public:
    void printPublic();

private:
    void printPrivate();
};

// must be not inline or referenced from c++ code or will be droped by compiler!
void Print::printPrivate()// thiscall
{
    DbgPrint("%s<%p>\n", __FUNCTION__, this);
}
void Print::printPublic()// thiscall
{
    DbgPrint("%s<%p>\n", __FUNCTION__, this);
}

extern "C"
{
    // stub impemeted in asm
    void __fastcall Print_printPrivate(Print* This);
    void __fastcall Print_printPublic(Print* This);
};

    Print p;
    //p.printPrivate();//error C2248
    p.printPublic();
    Print_printPrivate(&p);
    Print_printPublic(&p);
</code>```

and asm code (for ml64)

```<code>_TEXT segment 'CODE'

extern ?printPrivate@Print@@AEAAXXZ:proc
extern ?printPublic@Print@@QEAAXXZ:proc

Print_printPrivate proc
    jmp ?printPrivate@Print@@AEAAXXZ
Print_printPrivate endp

Print_printPublic proc
    jmp ?printPublic@Print@@QEAAXXZ
Print_printPublic endp

_TEXT ENDS
END
</code>```

also note for x86 only that all c++ methods use thiscall calling convention - first parameter this in ECX  register and next in stack as for __stdcall - so if method have no parameters (really one this ) we can use __fastcall for asm function as is, and if exist parameters we need push EDX to stack in assembler stub. for x64 no this problem - here only one calling convention, but all this already not related to main question.

example for x86 code with extra params, for show how transform __fastcall to __thiscall

```<code>class Print
{
public:
    void printPublic(int a, int b)// thiscall
    {
        DbgPrint("%s<%p>(%x, %x)\n", __FUNCTION__, this, a, b);
    }

private:
    void printPrivate(int a, int b);
};

// must be not inline or referenced from c++ code or will be droped by compiler!
void Print::printPrivate(int a, int b)// thiscall
{
    DbgPrint("%s<%p>(%x, %x)\n", __FUNCTION__, this, a, b);
}

extern "C"
{
    // stub impemeted in asm
    void __fastcall Print_printPrivate(Print* This, int a, int b);
    void __fastcall Print_printPublic(Print* This, int a, int b);
};
        Print p;
        //p.printPrivate(1,2);//error C2248
        p.printPublic(1, 2);
        Print_printPrivate(&p, 1, 2);
        Print_printPublic(&p, 1, 2);
</code>```

and asm

```<code>.686p

_TEXT segment

extern ?printPublic@Print@@QAEXHH@Z:proc
extern ?printPrivate@Print@@AAEXHH@Z:proc

@Print_printPrivate@12 proc
    xchg [esp],edx
    push edx
    jmp ?printPrivate@Print@@AAEXHH@Z
@Print_printPrivate@12 endp

@Print_printPublic@12 proc
    xchg [esp],edx
    push edx
    jmp ?printPublic@Print@@QAEXHH@Z
@Print_printPublic@12 endp

_TEXT ends

end
</code>```

Title: C++ - Method/Member access

Body:
We all know that private methods and members are only accessable inside the class, same way that protected methods and members are accessable inside the class and classes that derived from that class. But where is the «access control» of this? Does the «access control» happen in compile time, or does the compiler add addional machine code that controls that in runtime?

Can I create a class like this:

class Print
{
        public:
                void printPublic();

        private:
                void printPrivate();
};

int main()
{
        Print print;

        print.printPublic() // Change this to printPrivate() after compiling the code

        return(EXIT_SUCCESS);
}

And then after compiling the code edit the machine code to call printPrivate() instead of printPublic() method without error?

Body:
The «access control» happen at compile time and only for c++ code. you even not need edit the machine code - you can easy call private methods from assembly language - so this demonstrate that this is only for c++ restriction. and of course no any additional machine code that controls that in run-time - this at all impossible control who call method.

simply demo . note function names, how it mangled depended from x86 or x64 compiling and from compiler probably - my demo for CL compiler and x64 platform bat it can be easy changed to x86 or other compiler

c++ code

class Print
{
public:
    void printPublic();

private:
    void printPrivate();
};

// must be not inline or referenced from c++ code or will be droped by compiler!
void Print::printPrivate()// thiscall
{
    DbgPrint("%s<%p>\n", __FUNCTION__, this);
}
void Print::printPublic()// thiscall
{
    DbgPrint("%s<%p>\n", __FUNCTION__, this);
}

extern "C"
{
    // stub impemeted in asm
    void __fastcall Print_printPrivate(Print* This);
    void __fastcall Print_printPublic(Print* This);
};

    Print p;
    //p.printPrivate();//error C2248
    p.printPublic();
    Print_printPrivate(&p);
    Print_printPublic(&p);

and asm code (for ml64)

_TEXT segment 'CODE'

extern ?printPrivate@Print@@AEAAXXZ:proc
extern ?printPublic@Print@@QEAAXXZ:proc

Print_printPrivate proc
    jmp ?printPrivate@Print@@AEAAXXZ
Print_printPrivate endp

Print_printPublic proc
    jmp ?printPublic@Print@@QEAAXXZ
Print_printPublic endp

_TEXT ENDS
END

also note for x86 only that all c++ methods use thiscall calling convention - first parameter this in ECX  register and next in stack as for __stdcall - so if method have no parameters (really one this ) we can use __fastcall for asm function as is, and if exist parameters we need push EDX to stack in assembler stub. for x64 no this problem - here only one calling convention, but all this already not related to main question.

example for x86 code with extra params, for show how transform __fastcall to __thiscall

class Print
{
public:
    void printPublic(int a, int b)// thiscall
    {
        DbgPrint("%s<%p>(%x, %x)\n", __FUNCTION__, this, a, b);
    }

private:
    void printPrivate(int a, int b);
};

// must be not inline or referenced from c++ code or will be droped by compiler!
void Print::printPrivate(int a, int b)// thiscall
{
    DbgPrint("%s<%p>(%x, %x)\n", __FUNCTION__, this, a, b);
}

extern "C"
{
    // stub impemeted in asm
    void __fastcall Print_printPrivate(Print* This, int a, int b);
    void __fastcall Print_printPublic(Print* This, int a, int b);
};
        Print p;
        //p.printPrivate(1,2);//error C2248
        p.printPublic(1, 2);
        Print_printPrivate(&p, 1, 2);
        Print_printPublic(&p, 1, 2);

and asm

.686p

_TEXT segment

extern ?printPublic@Print@@QAEXHH@Z:proc
extern ?printPrivate@Print@@AAEXHH@Z:proc

@Print_printPrivate@12 proc
    xchg [esp],edx
    push edx
    jmp ?printPrivate@Print@@AAEXHH@Z
@Print_printPrivate@12 endp

@Print_printPublic@12 proc
    xchg [esp],edx
    push edx
    jmp ?printPublic@Print@@QAEXHH@Z
@Print_printPublic@12 endp

_TEXT ends

end


问:
Select2 works on fiddle not on localserver
I wanted to use Select2 (Source: https://select2.github.io/) for selecting and tagging purpose.

Went through an example on
JsFiddle and tried to replicate it on my local server (xampp). Here is the code, which is exactly the same as on the fiddle.

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>

<body>

<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>

<script>
$("#e1").select2();
</script>
</body>
</html>
</code>```

Now, the code on the fiddle works but the same exact thing on my localserver doesn't.

Why?

答:
include jquery library file
 before Select2.js file</p>

Body:
I wanted to use Select2 (Source: https://select2.github.io/) for selecting and tagging purpose.

Went through an example on
JsFiddle and tried to replicate it on my local server (xampp). Here is the code, which is exactly the same as on the fiddle.

<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>

Now, the code on the fiddle works but the same exact thing on my localserver doesn't.

Why?


问:
What prevent me from get this json data
I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>

```<code>    {
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion   ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}
</code>```

and this is my full AyncTask.

```<code>     private class AysncImages extends AsyncTask<String, Void, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
//            pDialog = new ProgressDialog(getActivity());
//            pDialog.setMessage("Please wait...");
//            pDialog.setCancelable(false);
//            pDialog.show();

        }

        @Override
        protected Integer doInBackground(String... arg0) {
            // Building Parameters
            HttpHandler sh = new HttpHandler();

            String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));

            //jsonStr = sh.makeServiceCall(url + 373); //or url + ID
            Log.i(TAG, "doInBackground Image: " + jsonStr);

            if (jsonStr != null) {

                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    JSONArray arrayObj = jsonObj.getJSONArray("images");

                    Log.i(TAG, "array: "+ jsonObj);

                    GridItem item = new GridItem();
                    for (int i = 0; i < arrayObj.length(); i++) {
                        String images = arrayObj.getString(i);

                        Log.i(TAG, "parseResult: " + jsonObj);
                        item.setImage(IMAGE_LINK + images);//IMAGE_LINK +

                        Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
                        mGridData.add(item);

                    }
                    // Getting JSON Array node

                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
//            if (result == 1) {
                mGridAdapter.setGridData(mGridData);
            //} else {
              //  Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
           // }

            //Hide progressbar
            mProgressBar.setVisibility(View.GONE);
        }

    }
</code>```

In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?

My Log for jsonStr

答:
the json string you get is [{id:abc,...}]
but a JsonObject should start with {id:abc,...}
maybe you try to remove the '[' and ']' at the end of string in order to get the object

as start with '[' should be an array

Title: What prevent me from get this json data

Body:
I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>

    {
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion   ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}

and this is my full AyncTask.

     private class AysncImages extends AsyncTask<String, Void, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
//            pDialog = new ProgressDialog(getActivity());
//            pDialog.setMessage("Please wait...");
//            pDialog.setCancelable(false);
//            pDialog.show();

        }

        @Override
        protected Integer doInBackground(String... arg0) {
            // Building Parameters
            HttpHandler sh = new HttpHandler();

            String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));

            //jsonStr = sh.makeServiceCall(url + 373); //or url + ID
            Log.i(TAG, "doInBackground Image: " + jsonStr);

            if (jsonStr != null) {

                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    JSONArray arrayObj = jsonObj.getJSONArray("images");

                    Log.i(TAG, "array: "+ jsonObj);

                    GridItem item = new GridItem();
                    for (int i = 0; i < arrayObj.length(); i++) {
                        String images = arrayObj.getString(i);

                        Log.i(TAG, "parseResult: " + jsonObj);
                        item.setImage(IMAGE_LINK + images);//IMAGE_LINK +

                        Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
                        mGridData.add(item);

                    }
                    // Getting JSON Array node

                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
//            if (result == 1) {
                mGridAdapter.setGridData(mGridData);
            //} else {
              //  Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
           // }

            //Hide progressbar
            mProgressBar.setVisibility(View.GONE);
        }

    }

In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?

My Log for jsonStr


问:
How do I make link_to open external URLs in a new window?
I need to convert a rails 2.3 site so that all external URLs open in a new window.  I could go though every call to link_to and add :target => '_blank', but I'd like to do it in one step for all links, present and future.  Is there a way I can monkey patch link_to to get the desired behaviour?

答:
In the end I went with this, in an initialiser:</p>

```<code>module ExternalLinksInNewTabs
  def new_tab_link_to *args, &block
    if block_given?
      options = args.first || {}
      html_options = args[1] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to options, html_options, &block
    else
      name = args.first
      options = args[1] || {}
      html_options = args[2] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to name, options, html_options
    end
  end

  def self.is_external_link? host, url
    host.sub! /^www\./, ''
    url =~ /^http/i && url !~ /^http:\/\/(www\.)?#{host}/i
  end
end

module ActionView
  module Helpers
    module UrlHelper
      include ExternalLinksInNewTabs

      alias_method :same_tab_link_to, :link_to
      alias_method :link_to, :new_tab_link_to
    end
  end
end
</code>```

Body:
In the end I went with this, in an initialiser:

module ExternalLinksInNewTabs
  def new_tab_link_to *args, &block
    if block_given?
      options = args.first || {}
      html_options = args[1] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to options, html_options, &block
    else
      name = args.first
      options = args[1] || {}
      html_options = args[2] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to name, options, html_options
    end
  end

  def self.is_external_link? host, url
    host.sub! /^www\./, ''
    url =~ /^http/i && url !~ /^http:\/\/(www\.)?#{host}/i
  end
end

module ActionView
  module Helpers
    module UrlHelper
      include ExternalLinksInNewTabs

      alias_method :same_tab_link_to, :link_to
      alias_method :link_to, :new_tab_link_to
    end
  end
end


问:
Pandas: how to get status of lines read when using read_csv?
I am loading a very huge csv file, like 10 millions records, using pandas and read_csv method and I wanted to know if there is a way to show the progress of that loading, something like:

```<code>100,000 lines read
150,000 lines read
</code>```

Thanks.

答:
To show progress like this:

```<code>Completed 1 %
Completed 2 %
...
Completed 99 %
Completed 100 %
</code>```

you can try this:

```<code>import os, pandas
filename = "VeryLong.csv"
lines_number = sum(1 for line in open(filename))
lines_in_chunk = 500 # I don't know what size is better
counter = 0
completed = 0
reader = pandas.read_csv(filename, chunksize=lines_in_chunk)
for chunk in reader:
    # < ... reading the chunk somehow... >
    # showing progress:
    counter += lines_in_chunk
    new_completed = int(round(float(counter)/lines_number * 100))
    if (new_completed > completed):
        completed = new_completed
        print "Completed", completed, "%"
</code>```

Body:
I am loading a very huge csv file, like 10 millions records, using pandas and read_csv method and I wanted to know if there is a way to show the progress of that loading, something like:

100,000 lines read
150,000 lines read

Thanks.

Body:
To show progress like this:

Completed 1 %
Completed 2 %
...
Completed 99 %
Completed 100 %

you can try this:

import os, pandas
filename = "VeryLong.csv"
lines_number = sum(1 for line in open(filename))
lines_in_chunk = 500 # I don't know what size is better
counter = 0
completed = 0
reader = pandas.read_csv(filename, chunksize=lines_in_chunk)
for chunk in reader:
    # < ... reading the chunk somehow... >
    # showing progress:
    counter += lines_in_chunk
    new_completed = int(round(float(counter)/lines_number * 100))
    if (new_completed > completed):
        completed = new_completed
        print "Completed", completed, "%"


问:
Replace only text content inside DIV using JavaScript
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

```
</div>
</div>
</p>
<p>I've tried this code :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";</code>```

But it doesn't work, here's the result:

  text changed

```

Any help would be appreciated

答:
You are pointing to the id of the h1 tag and not the anchor ()tag containing the text to be changed. this im not not sure will allow you to insert the text exactly where you want it to be. using the query selector or any other means of selecting the tag wrapping the text you what to change will surely do. if you dont mind, jquery selector will do the job much easier

you can try something like $("#DeltaPlaceHolderPageTitleInTitleArea a").text("")

Body:
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

I've tried this code :

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";

But it doesn't work, here's the result:

  text changed

Any help would be appreciated


问:
Akka Stream connect to multiple sinks
I have implemented a custom component in akka stream which takes elements as input, groups and merges them based on a key and sends them out through one of a dozen outlets. You can think of this component as a kind of GroupBy component which does not partition the flow into subflows, but actual flows. In addition to partitioning incoming elements, it merges them into one element, i.e. there is some buffering happening inside the component such that 1 element in does not necessarily mean 1 element out through an outlet.

Below is a simplified implementation of said component.

```<code>class CustomGroupBy[A,B](k: Int, f: A => Int) extends GraphStage[FlowShape[B, B]] {

  val in = Inlet[A]("CustomGroupBy.in")
  val outs = (0 until k).map(i => Outlet[B](s"CustomGroupBy.$i.out"))

  override val shape = new AmorphousShape(scala.collection.immutable.Seq(in), outs)

  /* ... */
}
</code>```

I now what to connect each outlet of that component to a different Sink and combine the materialized value of all these sinks.

I have tried a few things with the graph DSL, but have not quite managed to get it working. Would anyone be so kind as to provide me with a snippet to do that or point me in the right direction?

Thanks in advance!

答:
You most likely want the built-in broadcast stage.  Example usage can be found here:</p>

```<code>val bcast = builder.add(Broadcast[Int](2))

in ~> f1 ~> bcast ~> f2 ~> merge ~> f3 ~> out
            bcast ~> f4 ~> merge
</code>```

Title: Akka Stream connect to multiple sinks

Body:
I have implemented a custom component in akka stream which takes elements as input, groups and merges them based on a key and sends them out through one of a dozen outlets. You can think of this component as a kind of GroupBy component which does not partition the flow into subflows, but actual flows. In addition to partitioning incoming elements, it merges them into one element, i.e. there is some buffering happening inside the component such that 1 element in does not necessarily mean 1 element out through an outlet.

Below is a simplified implementation of said component.

class CustomGroupBy[A,B](k: Int, f: A => Int) extends GraphStage[FlowShape[B, B]] {

  val in = Inlet[A]("CustomGroupBy.in")
  val outs = (0 until k).map(i => Outlet[B](s"CustomGroupBy.$i.out"))

  override val shape = new AmorphousShape(scala.collection.immutable.Seq(in), outs)

  /* ... */
}

I now what to connect each outlet of that component to a different Sink and combine the materialized value of all these sinks.

I have tried a few things with the graph DSL, but have not quite managed to get it working. Would anyone be so kind as to provide me with a snippet to do that or point me in the right direction?

Thanks in advance!

Body:
You most likely want the built-in broadcast stage.  Example usage can be found here:

val bcast = builder.add(Broadcast[Int](2))

in ~> f1 ~> bcast ~> f2 ~> merge ~> f3 ~> out
            bcast ~> f4 ~> merge


问:
How to get permalink to a specific WooCommerce endpoint?
Hi I am looking how to get a permalink to a woocommerce my account page endpoint. For example edit-address or orders.

I tried this which I know can't possibly be right, it also appends a 0 onto the end of the link.

```<code>get_permalink( get_option('woocommerce_myaccount_page_id') )+"orders";
</code>```

答:
Replace your code with this

```<code>get_permalink( get_option('woocommerce_myaccount_page_id') ) . "orders";
</code>```

PHP concatenation is dot symbol not plus symbol. https://stackoverflow.com/a/1866194/1593365. Your code seems right only

Body:
Hi I am looking how to get a permalink to a woocommerce my account page endpoint. For example edit-address or orders.

I tried this which I know can't possibly be right, it also appends a 0 onto the end of the link.

get_permalink( get_option('woocommerce_myaccount_page_id') )+"orders";

Body:
Replace your code with this

get_permalink( get_option('woocommerce_myaccount_page_id') ) . "orders";

PHP concatenation is dot symbol not plus symbol. https://stackoverflow.com/a/1866194/1593365. Your code seems right only


问:
How to get parameters properties from a stored procedure in Oracle?
I am developing an admin panel where we can determine which stored procedures and views can be called in Oracle 12c schemas, from services in our micro-services platform.

The services must know which parameters a procedure needs, and which columns a view has available, in order to call them.

I the admin panel, the creator of the procedure or view may register it, by typing in these information, like object's name, each parameter's name, length and data type.

But it would be much more elegant if the user just types the name of the object and then a SQL SELECT would retrieve a procedure's parameters properties in a table, and the same with the view's column's properties, so the panel would register those configurations automatically.

Could anybody post a query on how to achieve this? I am very new to Oracle and I don't know how to query the objects metadata.

答:
This can be used for views (I used USER_... metadata views, but you can use DBA_... depending of user grants):</p>

```<code>SELECT A.TABLE_NAME, A.COLUMN_NAME, A.DATA_TYPE
  FROM USER_TAB_COLUMNS A
  INNER JOIN USER_VIEWS B ON A.TABLE_NAME = B.VIEW_NAME
/* WHERE A.TABLE_NAME = 'xxxx' */
 ORDER BY TABLE_NAME, COLUMN_ID;
</code>```

Body:
This can be used for views (I used USER_... metadata views, but you can use DBA_... depending of user grants):

SELECT A.TABLE_NAME, A.COLUMN_NAME, A.DATA_TYPE
  FROM USER_TAB_COLUMNS A
  INNER JOIN USER_VIEWS B ON A.TABLE_NAME = B.VIEW_NAME
/* WHERE A.TABLE_NAME = 'xxxx' */
 ORDER BY TABLE_NAME, COLUMN_ID;


问:
getting NoClassDefFound for com/pi4j/io/i2c/I2CFactory
I know this question has been asked before but I tried the solutions given in other Threads with no success.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/pi4j/io/i2c
/I2CFactory at com.jksoft.rpi.dashpi.pishock.Sensor.setup(Sensor.java:32)
</code>```

on my windows machine i used maven to get the pi4j dependency and for the I ran the curl statemet shown here (curl -s get.pi4j.com | sudo bash) an then tried to add the classes to the classpath with the command shown on that site: (sudo java -classpath .:classes:/opt/pi4j/lib/'*' ...)
In my case:

```<code>sudo java -classpath .:classes:/opt/pi4j/lib/'*':. -jar DashPi-1.0-SNAPSHOT.jar
</code>```

but it still gives me that error and I dont know whats wrong.

Maybe this happens because pi4j has been installed unter

```<code>/opt/pi4j
</code>```

and my jar is at

```<code>/home/pi
</code>```

Any help would be appreciated!

the code looks as follows:

```<code>public Sensor(){
    this.setup();
}

private void setup(){
    try {
        this.bus = I2CFactory.getInstance(I2CBus.BUS_1);
        this.device = this.bus.getDevice(0x53);
    } catch (IOException ex) {
        Logger.getLogger(Sensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

答:
Why are you using the wildcard on that call? It seems that the classpath is wrong and should be something like:</p>

```<code>sudo java -classpath .:classes:/opt/pi4j/lib/:. -jar DashPi-1.0-SNAPSHOT.jar
</code>```

Body:
I know this question has been asked before but I tried the solutions given in other Threads with no success.

Exception in thread "main" java.lang.NoClassDefFoundError: com/pi4j/io/i2c
/I2CFactory at com.jksoft.rpi.dashpi.pishock.Sensor.setup(Sensor.java:32)

on my windows machine i used maven to get the pi4j dependency and for the I ran the curl statemet shown here (curl -s get.pi4j.com | sudo bash) an then tried to add the classes to the classpath with the command shown on that site: (sudo java -classpath .:classes:/opt/pi4j/lib/'*' ...)
In my case:

sudo java -classpath .:classes:/opt/pi4j/lib/'*':. -jar DashPi-1.0-SNAPSHOT.jar

but it still gives me that error and I dont know whats wrong.

Maybe this happens because pi4j has been installed unter

/opt/pi4j

and my jar is at

/home/pi

Any help would be appreciated!

the code looks as follows:

public Sensor(){
    this.setup();
}

private void setup(){
    try {
        this.bus = I2CFactory.getInstance(I2CBus.BUS_1);
        this.device = this.bus.getDevice(0x53);
    } catch (IOException ex) {
        Logger.getLogger(Sensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Body:
Why are you using the wildcard on that call? It seems that the classpath is wrong and should be something like:

sudo java -classpath .:classes:/opt/pi4j/lib/:. -jar DashPi-1.0-SNAPSHOT.jar


问:
Android: Set alpha on button on click. Preferably xml only
I want to introduce a 'down' style on some buttons. I've created a style, and a state list.

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/inactive_button_background" android:state_enabled="false"/>
    <item android:drawable="@drawable/active_button_background" android:state_enabled="true"/>
    <item android:drawable="@drawable/pressed_button_background" android:state_pressed="true"></item>
</selector>
</code>```

The problem is that I want to be able to change just the alpha of the background when the button gets clicked (I will have variable backgrounds, so setting a sold color with alpha channel is not a solution).

And I want to do this from the declarative xml only (don't want to polute my code with layout stuff).

Problem is I don't know how to apply this alpha blending to the button from a xml drawable.
I am pretty sure there's a way though.

答:
Adding something to Michael answer, if you are looking for a "softer" click animation. I added this:

```<code>btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {
            switch (motionEvent.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    v.animate().alpha(0.3f).setDuration(200).start();
                    break;
                case MotionEvent.ACTION_UP:
                    v.animate().alpha(1f).setDuration(200).start();
                default :
                    v.setAlpha(1f);
            }
            return false;
        }
    });
}
</code>```

with lies on the same idea but with a animation

Body:
I want to introduce a 'down' style on some buttons. I've created a style, and a state list.

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/inactive_button_background" android:state_enabled="false"/>
    <item android:drawable="@drawable/active_button_background" android:state_enabled="true"/>
    <item android:drawable="@drawable/pressed_button_background" android:state_pressed="true"></item>
</selector>

The problem is that I want to be able to change just the alpha of the background when the button gets clicked (I will have variable backgrounds, so setting a sold color with alpha channel is not a solution).

And I want to do this from the declarative xml only (don't want to polute my code with layout stuff).

Problem is I don't know how to apply this alpha blending to the button from a xml drawable.
I am pretty sure there's a way though.

Body:
Adding something to Michael answer, if you are looking for a "softer" click animation. I added this:

btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {
            switch (motionEvent.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    v.animate().alpha(0.3f).setDuration(200).start();
                    break;
                case MotionEvent.ACTION_UP:
                    v.animate().alpha(1f).setDuration(200).start();
                default :
                    v.setAlpha(1f);
            }
            return false;
        }
    });
}

with lies on the same idea but with a animation


问:
SSIS Derived Column Date Formats
I have a large data file that I am running through SSIS. Very simple XML source into a SQL database. I seldom use SSIS so I am far from an expert.

I have some records that I push into an error table because the dates are incorrect.

What I want to say is, if the date is not in a date format, then update this date to NULL.

I don't know if Derived Column is the way to go, but it appears it should be given examples I have been reading online.

I want to fix this issue in the SSIS stage, not in SQL after the data has been loaded in to the error tables.

答:
SSIS expressions are limited in date and error handling.  I would suggest, instead, to use a script component.

Under input columns, select the column that you want to work with.  In the example below, my column is called "date"

Add the following to the script:

```<code>using System.Globalization;
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
    DateTime dateResult;
    if (!DateTime.TryParse(Row.date, culture, DateTimeStyles.None, out dateResult))
    {
        Row.date = null;
    }
}
</code>```

The date column is a string, which can be converted to Datetime with a data conversion component before being inserted into the database.
The Culture is set to US English, but this can be changed to your specific needs.  This hint will accept the local time format, i.e. MM/dd/yyyy.

TryParse() returns true if it can successfully parse a date from the input string.  When it returns false, we just set the column to null.

Title: SSIS Derived Column Date Formats

Body:
SSIS expressions are limited in date and error handling.  I would suggest, instead, to use a script component.

Under input columns, select the column that you want to work with.  In the example below, my column is called "date"

Add the following to the script:

using System.Globalization;
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
    DateTime dateResult;
    if (!DateTime.TryParse(Row.date, culture, DateTimeStyles.None, out dateResult))
    {
        Row.date = null;
    }
}

The date column is a string, which can be converted to Datetime with a data conversion component before being inserted into the database.
The Culture is set to US English, but this can be changed to your specific needs.  This hint will accept the local time format, i.e. MM/dd/yyyy.

TryParse() returns true if it can successfully parse a date from the input string.  When it returns false, we just set the column to null.


问:
CSS element not showing over image
I bet this is probably something stupid, I am trying put an absolute element over an image, but its not appearing.

```<code><div class="circle" style="position: absolute; top: 200px; left: 100px;"></div>

                    <img src="images/madison-siteplan.png" class="siteplan" />
</code>```

here is the attentional css for the circle:

```<code>.circle {
            border-radius: 50%;
            width: 100px;
            height: 100px;
            color: red;
            }
</code>```

答:
It has no border or outline, so the edge won't show up.

It has no background colour, so it is transparent.

It has no content inside it, so the foreground colour has no practical effect.

Change any one of the above.

Title: CSS element not showing over image

Body:
I bet this is probably something stupid, I am trying put an absolute element over an image, but its not appearing.

here is the attentional css for the circle:

.circle {
            border-radius: 50%;
            width: 100px;
            height: 100px;
            color: red;
            }


问:
Delete directory on clean
I have a C#/TypeScript project which uses webpack to bundle the TypeScript code into a directory bundles.

The directory bundles is created by webpack, which is triggered as a post-build event on the project.

I would like the bundles directory (or all of its children) to be deleted when I clean the project or solution. How can I do this?

答:
User CleanPlugin for webpack. Here is my config for my server side code in node (see the plugins section uses clean-webpack-plugin):

```<code>plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
    // rest of plugins
],
</code>```

The whole config

```<code>var webpack = require("webpack");
var path = require("path");
var CleanPlugin = require('clean-webpack-plugin');

var projectRootPath = path.resolve(__dirname, '../');
var buildPath = path.join(projectRootPath, './build');

module.exports = {
  target: "node",
  cache: false,
  context: projectRootPath,
  devtool: "source-map",
  entry: [ "./server/server.prod.js" ],
  output: {
    path: path.join(__dirname, "../build"),
    filename: "server.prod.js"
  },
  plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
  ],
  module: {
    rules: [
      { test: /\.js$/, enforce: "pre", loader: 'eslint-loader', exclude: /node_modules/ },
      {
        test: /\.js$/,
        enforce: "post",
        exclude: /node_modules/,
        use: [ { loader: 'babel-loader' } ]
      }
    ]
  },
  externals: nodeModules, // nodeModules is an array variable
  resolve: {
    modules: [
      path.resolve('./server'),
      path.resolve('./client'),
      path.resolve('./node_modules')
    ],
    extensions: [ ".json", ".js" ]
  }
};
</code>```

Title: Delete directory on clean

Body:
User CleanPlugin for webpack. Here is my config for my server side code in node (see the plugins section uses clean-webpack-plugin):

plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
    // rest of plugins
],

The whole config

var webpack = require("webpack");
var path = require("path");
var CleanPlugin = require('clean-webpack-plugin');

var projectRootPath = path.resolve(__dirname, '../');
var buildPath = path.join(projectRootPath, './build');

module.exports = {
  target: "node",
  cache: false,
  context: projectRootPath,
  devtool: "source-map",
  entry: [ "./server/server.prod.js" ],
  output: {
    path: path.join(__dirname, "../build"),
    filename: "server.prod.js"
  },
  plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
  ],
  module: {
    rules: [
      { test: /\.js$/, enforce: "pre", loader: 'eslint-loader', exclude: /node_modules/ },
      {
        test: /\.js$/,
        enforce: "post",
        exclude: /node_modules/,
        use: [ { loader: 'babel-loader' } ]
      }
    ]
  },
  externals: nodeModules, // nodeModules is an array variable
  resolve: {
    modules: [
      path.resolve('./server'),
      path.resolve('./client'),
      path.resolve('./node_modules')
    ],
    extensions: [ ".json", ".js" ]
  }
};