问:
add_qt_android_apk strips debug symbols of shared library
I use add_qt_android_apk to build an APK using Qt 5:

```<code>add_qt_android_apk(my_app_apk gustavsfairyland NAME "@string/ApplicationName"
        DEPENDS
        ${QTAV_LIBRARIES}
    )
</code>```

QTAV_LIBRARIES is defined before:

```<code>set(QTAV_LIBRARIES
        "${QTAV_FFMPEG_LIB_DIR}/libavcodec.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavfilter.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavformat.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavresample.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavutil.so"
        "${QTAV_FFMPEG_LIB_DIR}/libswresample.so"
        "${QTAV_FFMPEG_LIB_DIR}/libswscale.so"
        "${CMAKE_BINARY_DIR}/buildqtav/${QTAV_LIB_DIR}/libQtAV.so"
        "${CMAKE_BINARY_DIR}/buildqtav/${QTAV_LIB_DIR}/libQtAVWidgets.so"
    )
</code>```

I build libQtAV.so using the debug mode (user.conf):

```<code>CONFIG += no_config_tests
CONFIG += config_avutil config_avformat config_avcodec config_swscale config_swresample

CONFIG -= release
CONFIG += debug
</code>```

When I use nm to check for symbols I get many symbols:

```<code>nm ../buildqtav/lib_android_arm/libQtAV.so
00062884 t $a
00061d88 t $a
0005f9d0 t $a
...
</code>```

But when I use nm on the copied library in the libs directory I get nothing:

```<code>bash-4.3$ nm armeabi-v7a/libQtAV.so
nm: armeabi-v7a/libQtAV.so: no symbols
</code>```

Does add_qt_android_apk remove the debugging symbols?

In the CMake module for Qt APK I found this:

```<code> if(EXTRA_LIBS)
        set(EXTRA_LIBS "${EXTRA_LIBS},${LIB}")
    else()
        set(EXTRA_LIBS "${LIB}")
    endif()
    endforeach()
    set(QT_ANDROID_APP_EXTRA_LIBS "\"android-extra-libs\": \"${EXTRA_LIBS}\",")
</code>```

so it uses the specified external .so path. It is then added to qtdeploy.json in the CMake variable QT_ANDROID_APP_EXTRA_LIBS. Which has the entry

```<code>buildandroidarmeabi-v7a/buildqtav/lib_android_arm/libQtAV.so
</code>```

in "android-extra-libs":
So it actually has the correct entry but somehow strips the debug symbols. The library in the "libs" folder has a size of 1.1 MiBytes while the original library in "lib_android_arm" has a size of 1.6 MiBytes.

I'd like to see the routines using ndk-stack which prints at the moment:

```<code>Stack frame #05 pc 000b714f  /data/app/org.qtproject.gustavsfairyland-1/lib/arm/libQtAV.so: Routine ??
</code>```

edit:
I use the following CMake module: https://github.com/LaurentGomila/qt-android-cmake

edit2:
It looks like androiddeployqt does always strip symbols of the libraries:
http://code.qt.io/cgit/qt/qttools.git/tree/src/androiddeployqt/main.cpp

stripLibraries() is always called when building the application.

答:
As already mentioned in the edited question and in the answer, androiddeployqt is what strips the debuginfo from the .so file.

I belive the important point here is that androiddeployqt does not modify the file, it creates a copy in the process of generating the apk, and only this copy has the debug infos stripped. In the build output there is still the unmodified .so file which contains the debug infos and which can be used to debug the application (Qt creator does that AFAIK) and which can be used to grab symbol information - I use this for creating readable stacktraces with breakpad crashdump files.

I believe that's also the reason why QTBUG-57771 was rejected as incomplete: The Qt maintainers see no good reason to have the symbols available on the device, as long as debugging the application with Qt creator works with the current build process (and demonstrates that debugging is possible with a properly configured toolchain).

Body:
I use add_qt_android_apk to build an APK using Qt 5:

add_qt_android_apk(my_app_apk gustavsfairyland NAME "@string/ApplicationName"
        DEPENDS
        ${QTAV_LIBRARIES}
    )

QTAV_LIBRARIES is defined before:

set(QTAV_LIBRARIES
        "${QTAV_FFMPEG_LIB_DIR}/libavcodec.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavfilter.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavformat.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavresample.so"
        "${QTAV_FFMPEG_LIB_DIR}/libavutil.so"
        "${QTAV_FFMPEG_LIB_DIR}/libswresample.so"
        "${QTAV_FFMPEG_LIB_DIR}/libswscale.so"
        "${CMAKE_BINARY_DIR}/buildqtav/${QTAV_LIB_DIR}/libQtAV.so"
        "${CMAKE_BINARY_DIR}/buildqtav/${QTAV_LIB_DIR}/libQtAVWidgets.so"
    )

I build libQtAV.so using the debug mode (user.conf):

CONFIG += no_config_tests
CONFIG += config_avutil config_avformat config_avcodec config_swscale config_swresample

CONFIG -= release
CONFIG += debug

When I use nm to check for symbols I get many symbols:

nm ../buildqtav/lib_android_arm/libQtAV.so
00062884 t $a
00061d88 t $a
0005f9d0 t $a
...

But when I use nm on the copied library in the libs directory I get nothing:

bash-4.3$ nm armeabi-v7a/libQtAV.so
nm: armeabi-v7a/libQtAV.so: no symbols

Does add_qt_android_apk remove the debugging symbols?

In the CMake module for Qt APK I found this:

 if(EXTRA_LIBS)
        set(EXTRA_LIBS "${EXTRA_LIBS},${LIB}")
    else()
        set(EXTRA_LIBS "${LIB}")
    endif()
    endforeach()
    set(QT_ANDROID_APP_EXTRA_LIBS "\"android-extra-libs\": \"${EXTRA_LIBS}\",")

so it uses the specified external .so path. It is then added to qtdeploy.json in the CMake variable QT_ANDROID_APP_EXTRA_LIBS. Which has the entry

buildandroidarmeabi-v7a/buildqtav/lib_android_arm/libQtAV.so

in "android-extra-libs":
So it actually has the correct entry but somehow strips the debug symbols. The library in the "libs" folder has a size of 1.1 MiBytes while the original library in "lib_android_arm" has a size of 1.6 MiBytes.

I'd like to see the routines using ndk-stack which prints at the moment:

Stack frame #05 pc 000b714f  /data/app/org.qtproject.gustavsfairyland-1/lib/arm/libQtAV.so: Routine ??

edit:
I use the following CMake module: https://github.com/LaurentGomila/qt-android-cmake

edit2:
It looks like androiddeployqt does always strip symbols of the libraries:
http://code.qt.io/cgit/qt/qttools.git/tree/src/androiddeployqt/main.cpp

stripLibraries() is always called when building the application.


来源: stackexchange

问:
Laravel laratrust attache a role to a new user when registering
Well i am using laratrust to handle roles and permissions for my application.

I want to attach a role to a user when registering but after reading laratrust documentation i cant seem to figure out whats the issue!

Here is my code

```<code> public function register(Request $request) {
     $this->validation($request);
     User::create([
               'name' => $request->name,
                'lastname' => $request->lastname,
                'email' => $request->email,
                'password' => bcrypt($request->password)
     ]);

      $user->attachRole($employer);

      Auth::attempt([
               'email' =>$request->email,
               'password' => $request->password]);
             // Authentication passed...
      return redirect('/');
  }
</code>```

With the above i get error unknown query builder attacheRole!

Any suggestions?

答:
you forget to define $user (see in my code example) but there would be also error with the $employer it isn't definied in the function...

```<code>$user = User::create([
      'name' => $request->name,
     'lastname' => $request->lastname,
     'email' => $request->email,
     'password' => bcrypt($request->password)
 ]);
 $user->attachRole($employer);
</code>```

Laratrust Examples & doc

ContentLicense: CC BY-SA 3.0

Body:
Well i am using laratrust to handle roles and permissions for my application.

I want to attach a role to a user when registering but after reading laratrust documentation i cant seem to figure out whats the issue!

Here is my code

 public function register(Request $request) {
     $this->validation($request);
     User::create([
               'name' => $request->name,
                'lastname' => $request->lastname,
                'email' => $request->email,
                'password' => bcrypt($request->password)
     ]);

      $user->attachRole($employer);

      Auth::attempt([
               'email' =>$request->email,
               'password' => $request->password]);
             // Authentication passed...
      return redirect('/');
  }

With the above i get error unknown query builder attacheRole!

Any suggestions?

Body:
you forget to define $user (see in my code example) but there would be also error with the $employer it isn't definied in the function...

$user = User::create([
      'name' => $request->name,
     'lastname' => $request->lastname,
     'email' => $request->email,
     'password' => bcrypt($request->password)
 ]);
 $user->attachRole($employer);

Laratrust Examples & doc


问:
Draw vertical dotted line
I want to draw a vertical dotted line in xml, using shape.

I used this example:

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

<size
android:height="400dp"
android:width="4dp"/>

<stroke
        android:color="#000000"
        android:dashWidth="100dp"
        android:dashGap="10dp" />
</shape>
</code>```

Then:

```<code><View android:id="@+id/vertical_line"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/dotted_line"
      android:layout_marginLeft="27dp"/>
</code>```

But it doesn't work. How can I do it?

答:
I tried a few things, I liked the drawable solutions and found that this worked.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="-8dp"
    android:bottom="-8dp"
    android:left="-8dp">
    <shape>
        <solid android:color="@android:color/transparent"/>
        <stroke
            android:width="4dp"
            android:color="#df0000"
            android:dashGap="4dp"
            android:dashWidth="4dp"/>
    </shape>
</item>
</layer-list>
</code>```

The trick is the negative top bottom and left values as these are set outside of the object now, leaving a single dashed line.

Its used in the following view.

```<code><View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />
</code>```

Title: Draw vertical dotted line

Body:
I want to draw a vertical dotted line in xml, using shape.

I used this example:

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

<size
android:height="400dp"
android:width="4dp"/>

<stroke
        android:color="#000000"
        android:dashWidth="100dp"
        android:dashGap="10dp" />
</shape>

Then:

<View android:id="@+id/vertical_line"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/dotted_line"
      android:layout_marginLeft="27dp"/>

But it doesn't work. How can I do it?

Body:
I tried a few things, I liked the drawable solutions and found that this worked.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="-8dp"
    android:bottom="-8dp"
    android:left="-8dp">
    <shape>
        <solid android:color="@android:color/transparent"/>
        <stroke
            android:width="4dp"
            android:color="#df0000"
            android:dashGap="4dp"
            android:dashWidth="4dp"/>
    </shape>
</item>
</layer-list>

The trick is the negative top bottom and left values as these are set outside of the object now, leaving a single dashed line.

Its used in the following view.

<View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />


问:
Comparing druid and pipelinedb
I have been working on aggregation of streaming data, I found 2 tools to achieve the same. They are druid and pipelinedb. I have understood the implementation and architecture of the both. But couldn't figure out a way to benchmark these two. Is there any existing benchmark test that has been done? Or if I want to do a benchmarking of my own apart from the speed and scalability what are all the factors that I need to consider. Any ideas, links and help would be really appreciable. Also do share your own experience with pipelinedb and druid </p>

<p>Thanks </p>

答:
UPD:

After reading PipelineDB pages, I only wonder why do you need to compare such different things?

Druid is quite complex to install and maintain, it requires several external dependencies (such as zookeeper and hdfs/amazon, which must be maintained too).

And for that price you buy the key features of druid: column-oriented and distributed storage and processing. That also implies horizontal scalabitily out-of-the box, and it is completely automatic, you don't have even to think about it.

So if you don't need its distributed nature, I'd say you don't need druid at all.

FIRST VERSION:

I have no experience with pipelinedb (what is it? google shows nothing, pls share some link), but I have much experience with druid. So I would consider (apart from [query] speed and scalability):

ingesting performance (how many rows per sec/min/hour/... can be
inserted?)

RAM consumption of ingesting (how much RAM it needs to ingest with target speed?)

compression level (how many disk space needs one
    hour/day/month/... of data?)

fault-tolerance (what happens when some
    of the components fail? it is critical for my business?)

Caching (just keep in mind)

Title: Comparing druid and pipelinedb

Body:
I have been working on aggregation of streaming data, I found 2 tools to achieve the same. They are druid and pipelinedb. I have understood the implementation and architecture of the both. But couldn't figure out a way to benchmark these two. Is there any existing benchmark test that has been done? Or if I want to do a benchmarking of my own apart from the speed and scalability what are all the factors that I need to consider. Any ideas, links and help would be really appreciable. Also do share your own experience with pipelinedb and druid

Thanks


问:
ReactJS - Href Triggered DELETE Method
I'm determining the correct method for triggering my DELETE route through the use of href and node-fetch. I had originally thought that passing a function in my stateful component as an attribute on my stateless component and then using that as the link location would trigger the function, but it doesn't appear to work and now I am left second guessing my approach. Is there a better solution to what I have attempted?

Here is my stateful component:

```<code>class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    commentInformation(e){
        //e.preventDefault();
        console.log("commentInformation function triggered");
        this.deleteComment(this.props.recordIdHash, this.recordCommentId);
    }

    deleteComment(recordId, recordCommentId){
        var body = { recordId: recordId, recordCommentId: recordCommentId };
        var route = 'http://localhost:3000/app/record/' + recordId + '/comment/' + recordCommentId;
        fetch(route,
            {
                method: 'DELETE',
                body: JSON.stringify(body),
                headers: {
                    'X-CSRF-Token': 'csrfToken',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.props.updateComments(data)
                this.setState({'flash': 'success'});
            })
            .catch(err => {
                console.log(err);
                this.setState({'flash': 'error'});
            });
    }

    render(){
        return (
            <div className="record-comment__record">
                <div className="row">
                    <div className="col-md-12">
                        <div className="record-comment__meta">
                            <div className="row">
                                <div className="col-md-8 record-comment__profile">
                                    <img src={this.props.app.picture} className="profile__picture profile__picture--small"/>
                                    <p className="record-comment__info"><b>{this.props.app.fullNameSlug}</b> | <i>{this.props.createdAtDateSlug}</i></p>
                                    <DeleteComment commentUserId={this.props.app.userId} userId={this.props.currentUserId} recordId={this.props.recordIdHash} deleteComment={this.commentInformation} commentId={this.props.recordCommentId}/>
                                </div>
                            </div>
                        </div>
                        <div className="record-comment__body">
                            <div className="row">
                                <div className="col-md-12">
                                    <p>{this.props.comment}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
</code>```

Here is my <DeleteComment> component which maps the comment user id to the logged in user id and if they are the same, then show the delete href:

```<code>const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
            <a href={props.deleteComment} className="record-comment__delete"> | Delete</a>
        )
    } else {
        return null;
    }
}
</code>```

答:
It should be onClick instead of href:

```<code>const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
            <a onClick={props.deleteComment} className="record-comment__delete"> | Delete</a>
        )
    } else {
        return null;
    }
}
</code>```

Also, I think you are going to need to bind deleteComment method in your Comment component to not lose your this reference (see https://reactjs.org/docs/handling-events.html)

```<code>class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
        this.deleteComment = this.deleteComment.bind(this);
    }

}
</code>```

Title: ReactJS - Href Triggered DELETE Method

Body:
I'm determining the correct method for triggering my DELETE route through the use of href and node-fetch. I had originally thought that passing a function in my stateful component as an attribute on my stateless component and then using that as the link location would trigger the function, but it doesn't appear to work and now I am left second guessing my approach. Is there a better solution to what I have attempted?

Here is my stateful component:

class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    commentInformation(e){
        //e.preventDefault();
        console.log("commentInformation function triggered");
        this.deleteComment(this.props.recordIdHash, this.recordCommentId);
    }

    deleteComment(recordId, recordCommentId){
        var body = { recordId: recordId, recordCommentId: recordCommentId };
        var route = 'http://localhost:3000/app/record/' + recordId + '/comment/' + recordCommentId;
        fetch(route,
            {
                method: 'DELETE',
                body: JSON.stringify(body),
                headers: {
                    'X-CSRF-Token': 'csrfToken',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.props.updateComments(data)
                this.setState({'flash': 'success'});
            })
            .catch(err => {
                console.log(err);
                this.setState({'flash': 'error'});
            });
    }

    render(){
        return (

{this.props.app.fullNameSlug} | {this.props.createdAtDateSlug}

                                    <DeleteComment commentUserId={this.props.app.userId} userId={this.props.currentUserId} recordId={this.props.recordIdHash} deleteComment={this.commentInformation} commentId={this.props.recordCommentId}/>

{this.props.comment}

        )
    }
}

Here is my <DeleteComment> component which maps the comment user id to the logged in user id and if they are the same, then show the delete href:

const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
             | Delete
        )
    } else {
        return null;
    }
}

Body:
It should be onClick instead of href:

const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
            <a onClick={props.deleteComment} className="record-comment__delete"> | Delete</a>
        )
    } else {
        return null;
    }
}

Also, I think you are going to need to bind deleteComment method in your Comment component to not lose your this reference (see https://reactjs.org/docs/handling-events.html)

class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
        this.deleteComment = this.deleteComment.bind(this);
    }

}


问:
Observable<string>.switchMap is not function
I'm upgrading an application from Angular 4 to Angular 5, and have the following code in a service

```<code>loadRefData(): Observable<RefData> {
    return this.participant$.switchMap((role) => {
      return this.http.get(`${this.API_URL}/${role}/participantGroups/refdata`)
        .map(refData => refData as RefData);
});
</code>```

Since Angular 5 comes with the minimum requirement of RxJS 5.5.2, I'm converting it to use lettable operators with the .pipe() operator.

I thought I could do this

```<code>loadRefData(): Observable<RefData> {
    return this.participant$.switchMap((role) => {
      return this.http.get(`${this.API_URL}/${role}/participantGroups/refdata`)
        .pipe(
            map(refData => refData as RefData);
        );
});
</code>```

but I get the error TypeError: this.participant$.switchMap is not a function. I get no compilation errors from the typescript compiler though.

this.participant$ is of type Observable<string>, and unless I'm mistaken I should be able to perform a switchMap on it.

What am I missing?

This is with typescript@^2.6.1, rxjs@^5.5.2.

EDIT:
I just noticed that this.participant$ which is populated from ngrx\store.select is of type Store<string>.

答:
Thats a quote taken from Angulars Blog, which might help you.

HttpClient

In version 4.3 we shipped HttpClient in @angular/common as a smaller,
  easier, and more powerful way to make web requests in Angular. The new
  HttpClient has gotten some great praise from developers, so we’re now
  recommending HttpClient for all applications, and deprecating the
  previous @angular/http library.

To update to HttpClient, you’ll need to replace HttpModule with
  HttpClientModule from @angular/common/http in each of your modules,
  inject the HttpClient service, and remove any map(res => res.json())
  calls, which are no longer needed.

Source: Angular 5

Body:
I'm upgrading an application from Angular 4 to Angular 5, and have the following code in a service

loadRefData(): Observable<RefData> {
    return this.participant$.switchMap((role) => {
      return this.http.get(`${this.API_URL}/${role}/participantGroups/refdata`)
        .map(refData => refData as RefData);
});

Since Angular 5 comes with the minimum requirement of RxJS 5.5.2, I'm converting it to use lettable operators with the .pipe() operator.

I thought I could do this

loadRefData(): Observable<RefData> {
    return this.participant$.switchMap((role) => {
      return this.http.get(`${this.API_URL}/${role}/participantGroups/refdata`)
        .pipe(
            map(refData => refData as RefData);
        );
});

but I get the error TypeError: this.participant$.switchMap is not a function. I get no compilation errors from the typescript compiler though.

this.participant$ is of type Observable<string>, and unless I'm mistaken I should be able to perform a switchMap on it.

What am I missing?

This is with typescript@^2.6.1, rxjs@^5.5.2.

EDIT:
I just noticed that this.participant$ which is populated from ngrx\store.select is of type Store<string>.


问:
What is the best way to delete a Pod after a Kubernetes Job completes
I have a situation in which I run a Kubernetes Job and then want to delete the pod in which the Job's containers run when the job completes. The Kubernetes documentation says the it is the responsibility of the user to delete the pod.

However, my goal is to run a CPU intensive job by spinning up a big honking pod, let the job run, and then upon job completion, automagically nuke the pod. My thinking is that paying for an expensive, resource intensive pod is worth it when the revenue producing job runs. Once the job is over, the revenue stream ends and I need to cut the expense, hence nuking the pod.

I am thinking of having my code in the job container send a out a message upon program completion to a publisher that is picked up by a subscriber. The subscriber knows how to run the command, kubectl delete jobs/myContainer to nuke the pod.

But, maybe there is a better way. Thus, I ask.

Thanks in advance.

答: Why would you need to delete the pod at all ? If the job completed successfully (exit code 0) then the pod will be completed, it will no longer use cpu/memory resurces, and should be garbage collected when needed.</p>


问:
Passing strings between activities, intents not working
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

```<code>    String Name,Pass,tokenString;

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

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}
</code>```

here is the code for the home activity (the relevant bits) :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }
</code>```

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

答:
You are using two different intents to call the same activity.class file.
Insted of using two different use only 1 intent,and put data to that Intent only.
NO REQUIREMENT OF TWO DIFFERENT INTENT TO CALL HOME.CLASS ACTIVITY.</p>

```<code>private void launchHomeActivity() {
Intent intent = new Intent(this, Home.class);
startActivity(intent);}

public void createIntent(){
Intent i = new Intent(this, Home.class);
i.putExtra("Token", getToken());
startActivity(i);}
</code>```

Body:
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

    String Name,Pass,tokenString;

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

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}

here is the code for the home activity (the relevant bits) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

Body:
You are using two different intents to call the same activity.class file.
Insted of using two different use only 1 intent,and put data to that Intent only.
NO REQUIREMENT OF TWO DIFFERENT INTENT TO CALL HOME.CLASS ACTIVITY.

private void launchHomeActivity() {
Intent intent = new Intent(this, Home.class);
startActivity(intent);}

public void createIntent(){
Intent i = new Intent(this, Home.class);
i.putExtra("Token", getToken());
startActivity(i);}


问:
Suggestions for dealing with IE's terrible Javascript / Dom accessing engine
I'm working on a site that has a page that can potentially become very long.  It can have in theory 1000+ rows of data in it.  Then these rows could each have sub-rows.

I'm currently using a list / sublist structure to represent the data because it's difficult to visualize subsets in tables.  the subset data is in a table though.

The Problem is this:  In IE.   my hovering over the row styles,  tooltips and other javascripts are taking upwards of 5 seconds to fire!   The page hangs like crazy and is pretty much unuseable.  In FF, Chrome, and Safari it works just fine.

I don't need a whole bunch of stats saying IE is slow. i know it is. what i need is some suggestions / theories/ ideas on how to combat the slowness!

Some of the ideas i've had so far:
-some kind of paging mechanism.   But that gets tricky b/c 1.  It's a list not a table, and 2.  it's got sub sub lists and sub tables for those sub lists.   so we'd need to somehow page based on the top level i think.  because we don't want to split the data up at all.    I guess that might be feasible...

-some kind of mechanism that holds the content in a javascript array or object or soomething and doesn't add it to the dom until it's been scrolled to.   and takes it away when you scroll past it.  in theory this would be cool. but i think it would be horrible to impliment.

-something else entirely?

Thanks in Advance for any ideas!  I'm probably going to try and put a bounty on this as soon as i'm able to help inspire you ;)

EDIT:

OH MY!  I think i may have found part of the problem using dyna trace!  thanks Pointy for reminding me about this tool. i had forgotten about out.   the click event of one of my buttons seems to be firing an insane amount.  like 2000 times and count.  something is clicking it automatically or something crazy like that.   weird thing is, i don't have any javascripts that trigger that button click!  EDIT:  This doesn't seem to be an issue anymore.

EDIT:

Also: i don't think it is the complexity of my markup that is affecting the responsiveness of my scripts(i know if i could use just id selectors it would be best, but i've optimized my selectors and qtips as much as possible (with help from s.o. in the past).  i have a button that is just on the page, not nested in anything,  that the click handler takes 4 or 5 seconds to register.  It's not that the click action takes a long time, it's just slow to notice that it's been clicked.

EDIT: i had 5 spans that were each nested in a span unnecessarily,  i un-nested those and it seems to have cut the slowness in about 1/2!!    (these 5 spans were repeated in every row)

EDIT:   Here's some of the relevant scripts:

The Main Button Handler:

```<code>$('#FilterScheduledShifts').click(function () {
  var categoryId = $('#CategoryId').val();
  var activityId = $('#ActivityId').val();
  var shiftStatusFilters = GetShiftStatusFilterIds();
  var dayOfWeekFilters = GetDayOfWeekFilters();
  var startDateFilter = GetStartDateFilter();
  var endDateFilter = GetStartEndFilter();
  var dataToPost = {
    categoryId: categoryId,
    activityId: activityId,
    statuses: shiftStatusFilters,
    daysOfWeek: dayOfWeekFilters,
    startDate: startDateFilter,
    endDate: endDateFilter
  };
  var url = $('#UrlToFilter').val();
  $('#ListHolder').html("<%=web.loading %>");
  $.ajax({
    url: url,
    data: dataToPost,
    type: 'POST',
    success: function (data) {
      document.getElementById('ScheduledActivityShiftListHolder').innerHTML = data;
    },
    error: function () {
      v2ErrorNotice(v2Text.shared.genericAjaxErrorMessage);
    }
  });
});
</code>```

The Get...FIlter functions are very simple functions that run in a few milliseconds... nothing interesting or noteworthy happening in there.

this bit attaches some of the behaviour that is very slow:
in other pages they react nice and quick, on this page... 2-3 seconds.

```<code>$('span.infoCard').die();
$('span.infoCard').live("mouseover", function () {

  var $this = $(this);
  if (!$this.data("toolTipAttached")) {

    var title = '';

    if ($this.attr('infoCardTitle') != "") {
      title = $this.attr('infoCardTitle');
    } else {
      title = $this.html();
    }

    $this.qtip({
      content: {
        text: "loading",
        title: title,
        ajax: {
          url: $this.attr('urlToGet')
          // data: data,
        }
      },
      position: {
        at: 'right middle',
        my: 'left top',
        adjust: {
          screen: 'flip'
        }
      },
      hide: {
        fixed: true,
        when: 'mouseout'
      },
      show: {
        solo: true,
        delay: 500,
        ready: true
      },
      style: {
        classes: 'ui-tooltip-light InfoCardTip',
        widget: true,
        tip: {
          corner: true,
          width: 15,
          height: 15
        }
      }
    });
    $this.data("toolTipAttached", true);
  }
});
</code>```

There are 2 different versions of this for 2 different classes, one gets a single "shift" one gets the user s for a bunch of shifts. as with other things.  once the function itself runs quick,  the ajax is fast, the v2ReLoadScheduledActivitySection runs in about 50 ms. nothing interesting in there. :

```<code>$('div.GetShiftUserArrow').die('click');
$('div.GetShiftUserArrow').live('click', function () {
  var listIsVisible = $(this).attr('listIsVisible');
  var holder = $('#' + $(this).attr('listHolder'));
  var activityHolder = $('#TopLevel{0}'.format($(this).attr('activityShiftId')));

  if (listIsVisible == -1) {
    v2ReLoadScheduledActivitySection($(this), 1);
  } else {
    holder.empty().toggle('hide');
    $(this).removeClass('GetShiftUserArrowOpen');
    $(this).attr('listIsVisible', listIsVisible * -1);
  }
});
</code>```

Here's a bit of the HTML. this is the
 for a day... the main list has one of these for every day of the year (or whatever range they pick).  There could be any number of sub li's in that list, but it tends to be between 1-10.

```<code><li class="EntityRow" style="font-weight:normal;">
 <div class="TopLevelRow" sectiondate="1/21/2011 12:00:00 AM">
  <div class="ScheduleDayHeader OnlyFloatLeftInIE7" style="width:100%;margin-bottom:0px;font-weight:normal;">
   <div class="Buttons OnlyFloatLeftInIE7" style="padding-top:0px; padding-bottom:0px;margin-top:0px;margin-bottom:0px;">
    <div class="GetDayUserArrow OnlyFloatLeftInIE7" listisvisible="-1" sectiondate="1/21/2011 12:00:00 AM" url="/This/IsNot/TheReal/Url"></div>
   </div><span class="CategorizedNameHolder OnlyFloatLeftInIE7" style="display:inline-block; width:380px;padding-bottom:2px;">Friday, January 21, 2011</span> <span class="TimeHolderSpan">Start</span> <span class="TimeHolderSpan">End</span> <span class="StatusIcons">Status</span> <span class="SkinnyColumn GlossaryMe" tooltip="A Number">Mn</span> <span class="SkinnyColumn GlossaryMe" tooltip="A Number">Mx</span> <span class="SkinnyColumn GlossaryMe" tooltip="A Number">BU</span> <span class=
   "SkinnyColumn GlossaryMe" tooltip="A Number">Av</span> <span class="SkinnyColumn GlossaryMe" tooltip="Assigned">As</span> <span class="SkinnyColumn GlossaryMe" tooltip="A Number">Co</span>
  </div>

  <div class="ShiftListHolder" sectiondate="1/21/2011 12:00:00 AM">
   <ul class="ScheduledActivitiesForDayList EntityList FancyList SubList">
    <li class="EntityRow" activityshiftid="4645" id="ListItemFor4645">
     <div class="BlueOnHover ScheduleShiftHeader" style="width:100%;">
      <div class="Buttons OnlyFloatLeftInIE7" style="padding-top:0px; padding-bottom:0px;margin-top:0px;margin-bottom:0px;">
       <div class="GetShiftUserArrow OnlyFloatLeftInIE7" listisvisible="-1" activityshiftid="4645" url="/Some/Url=4645" sectiondate="1/21/2011 12:00:00 AM"></div>
      </div><span class="CategorizedNameHolder OnlyFloatLeftInIE7" style="display:inline-block; width:350px;padding-bottom:2px;"><span class="AssignLink" activityshiftid="4645">SomeText</span></span> <span class="TimeHolderSpan">9:00 AM</span> <span class="TimeHolderSpan">12:30 PM</span>

      <div class="StatusIcons OnlyFloatLeftInIE7">
       <div class='TipMe LegendMe ClassToPickTheIcon' tooltip='Min # scheduled' legendgroupid='5'>
        <span class='NoDisplay'>3</span>
       </div>

       <div class='TipMe LegendMe OtherClassToPickTheIcon' tooltip='Unlocked' legendgroupid='5'>
        <span class='NoDisplay'>2</span>
       </div>

       <div class='TipMe LegendMe AnotherClassToPickTheIcon' tooltip='Do not auto assign' legendgroupid='5'>
        <span class='NoDisplay'>1</span>
       </div>

       <div class='TipMe LegendMe ClassToPickTheIconAgain' tooltip='Do not autolock' legendgroupid='5'>
        <span class='NoDisplay'>1</span>
       </div>
      </div><span class="OnlyFloatLeftInIE7"><span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">1</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">--</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="Assigned">2</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip=
      "A Number">0</span></span>
     </div>

     <div class="UserListHoder" id="UserListHolder4645" activityshiftid="4645"></div>
    </li>

    <li class="EntityRow" activityshiftid="4129" id="ListItemFor4129">
     <div class="BlueOnHover ScheduleShiftHeader" style="width:100%;">
      <div class="Buttons OnlyFloatLeftInIE7" style="padding-top:0px; padding-bottom:0px;margin-top:0px;margin-bottom:0px;">
       <div class="GetShiftUserArrow OnlyFloatLeftInIE7" listisvisible="-1" activityshiftid="4129" url="/Some/Url=4129" sectiondate="1/21/2011 12:00:00 AM"></div>
      </div><span class="CategorizedNameHolder OnlyFloatLeftInIE7" style="display:inline-block; width:350px;padding-bottom:2px;"><span class="AssignLink" activityshiftid="4129">Blah Bla blah</span></span> <span class="TimeHolderSpan">9:00 AM</span> <span class="TimeHolderSpan">5:00 PM</span>

      <div class="StatusIcons OnlyFloatLeftInIE7">
       <div class='TipMe LegendMe ClassToPickTheIcon' tooltip='Min # scheduled' legendgroupid='5'>
        <span class='NoDisplay'>3</span>
       </div>

       <div class='TipMe LegendMe OtherClassToPickTheIcon' tooltip='Unlocked' legendgroupid='5'>
        <span class='NoDisplay'>2</span>
       </div>

       <div class='TipMe LegendMe AnotherClassToPickTheIcon' tooltip='Do not auto assign' legendgroupid='5'>
        <span class='NoDisplay'>1</span>
       </div>

       <div class='TipMe LegendMe OtherClassForIcon' tooltip='on availabilities' legendgroupid='5'>
        <span class='NoDisplay'>2</span>
       </div>
      </div><span class="OnlyFloatLeftInIE7"><span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">1</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">5</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="Assigned">5</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip=
      "A Number">0</span></span>
     </div>

     <div class="UserListHoder" id="UserListHolder4129" activityshiftid="4129"></div>
    </li>

    <li class="EntityRow" activityshiftid="3534" id="ListItemFor3534">
     <div class="BlueOnHover ScheduleShiftHeader" style="width:100%;">
      <div class="Buttons OnlyFloatLeftInIE7" style="padding-top:0px; padding-bottom:0px;margin-top:0px;margin-bottom:0px;">
       <div class="GetShiftUserArrow OnlyFloatLeftInIE7" listisvisible="-1" activityshiftid="3534" url="/Some/Url=3534" sectiondate="1/21/2011 12:00:00 AM"></div>
      </div><span class="CategorizedNameHolder OnlyFloatLeftInIE7" style="display:inline-block; width:350px;padding-bottom:2px;"><span class="AssignLink" activityshiftid="3534">even more</span></span> <span class="TimeHolderSpan">1:00 PM</span> <span class="TimeHolderSpan">4:30 PM</span>

      <div class="StatusIcons OnlyFloatLeftInIE7">
       <div class='TipMe LegendMe SchedulingFullyA NumberIcon' tooltip='Min # A Number' legendgroupid='5'>
        <span class='NoDisplay'>4</span>
       </div>

       <div class='TipMe LegendMe LockedIcon' tooltip='Locked' legendgroupid='5'>
        <span class='NoDisplay'>1</span>
       </div>

       <div class='TipMe LegendMe ClassToPickTheIconAgain' tooltip='Auto assign' legendgroupid='5'>
        <span class='NoDisplay'>2</span>
       </div>

       <div class='TipMe LegendMe OtherClassForIcon' tooltip='on assignments' legendgroupid='5'>
        <span class='NoDisplay'>3</span>
       </div>
      </div><span class="OnlyFloatLeftInIE7"><span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">1</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">5</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="A Number">0</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip="Assigned">7</span> <span class="SkinnyColumn TipMe ContentToolTip" tooltip=
      "A Number">3</span></span>
     </div>

     <div class="UserListHoder" id="UserListHolder3534" activityshiftid="3534"></div>
    </li>
   </ul>
  </div>
 </div>
</li>

</code>```

anything with TipMe, or GlossaryMe brings up a qtip tooltip.

like this:

```<code> $(".TipMe").live("mouseover", function () {
  var $this = $(this);
  $this.removeAttr('title');
  $this.removeAttr('alt');

  if (!$this.data("toolTipAttached")) {

    $this.qtip({
      show: {
        ready: true,
        solo: true,
        delay: 500
      },
      style: {
        classes: 'ui-tooltip-light InfoCardTip',
        widget: true
      },
      content: $this.attr('tooltip'),
      position: {
        at: 'bottomRight',
        my: 'topleft',
        adjust: {
          screen: 'flip',
          x: 0,
          y: 0
        }
      },
      hide: {
        fixed: true,
        inactive: 1000
      }
    });
    $this.data("toolTipAttached", true);
    //    $this.trigger("mouseover");
  }
});
</code>```

Something tells me it might be all my tooltip handlers that are causing the problem...

Let me know if you guys want anything else!

答:
"I don't think it is the complexity of my markup that is affecting the responsiveness of my scripts"

False assumptions are the worst leaders of the mind. It's interesting because you also said:

"this bit attaches some of the behaviour that is very slow, in other pages they react nice and quick, on this page... 2-3 seconds."

"i had 5 spans that were each nested in a span unnecessarily, i un-nested those and it seems to have cut the slowness in about 1/2!! (these 5 spans were repeated in every row)"

There you go. :)

What you can try is to change live handlers to delegate. The main difference between them is that live attaches The Handler to the document, while in case of delegate you can specify where to attach it. I think this can be the tipping point. Also try mouseenter which fires less frequently.

```<code>$('#ROOT').delegate(".infoCard", "mouseenter", function () { ... })
</code>```

root can be any element depending on your site. You can try the parent
 for example.

Another thing to try is to use your own handler (but you can't use mouseenter then):

```<code>$("#ROOT").mouseover(function (e) {
    var $this = $(e.target);
    if ($this.hasClass('TipMe')) {
        // TipMe code...
    } else if ($this.hasClass('infoCard')) {
        // infoCard code...
    }
});
</code>```

Let me know if any of them helped! :)

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a site that has a page that can potentially become very long.  It can have in theory 1000+ rows of data in it.  Then these rows could each have sub-rows.

I'm currently using a list / sublist structure to represent the data because it's difficult to visualize subsets in tables.  the subset data is in a table though.

The Problem is this:  In IE.   my hovering over the row styles,  tooltips and other javascripts are taking upwards of 5 seconds to fire!   The page hangs like crazy and is pretty much unuseable.  In FF, Chrome, and Safari it works just fine.

I don't need a whole bunch of stats saying IE is slow. i know it is. what i need is some suggestions / theories/ ideas on how to combat the slowness!

Some of the ideas i've had so far:
-some kind of paging mechanism.   But that gets tricky b/c 1.  It's a list not a table, and 2.  it's got sub sub lists and sub tables for those sub lists.   so we'd need to somehow page based on the top level i think.  because we don't want to split the data up at all.    I guess that might be feasible...

-some kind of mechanism that holds the content in a javascript array or object or soomething and doesn't add it to the dom until it's been scrolled to.   and takes it away when you scroll past it.  in theory this would be cool. but i think it would be horrible to impliment.

-something else entirely?

Thanks in Advance for any ideas!  I'm probably going to try and put a bounty on this as soon as i'm able to help inspire you ;)

EDIT:

OH MY!  I think i may have found part of the problem using dyna trace!  thanks Pointy for reminding me about this tool. i had forgotten about out.   the click event of one of my buttons seems to be firing an insane amount.  like 2000 times and count.  something is clicking it automatically or something crazy like that.   weird thing is, i don't have any javascripts that trigger that button click!  EDIT:  This doesn't seem to be an issue anymore.

EDIT:

Also: i don't think it is the complexity of my markup that is affecting the responsiveness of my scripts(i know if i could use just id selectors it would be best, but i've optimized my selectors and qtips as much as possible (with help from s.o. in the past).  i have a button that is just on the page, not nested in anything,  that the click handler takes 4 or 5 seconds to register.  It's not that the click action takes a long time, it's just slow to notice that it's been clicked.

EDIT: i had 5 spans that were each nested in a span unnecessarily,  i un-nested those and it seems to have cut the slowness in about 1/2!!    (these 5 spans were repeated in every row)

EDIT:   Here's some of the relevant scripts:

The Main Button Handler:

$('#FilterScheduledShifts').click(function () {
  var categoryId = $('#CategoryId').val();
  var activityId = $('#ActivityId').val();
  var shiftStatusFilters = GetShiftStatusFilterIds();
  var dayOfWeekFilters = GetDayOfWeekFilters();
  var startDateFilter = GetStartDateFilter();
  var endDateFilter = GetStartEndFilter();
  var dataToPost = {
    categoryId: categoryId,
    activityId: activityId,
    statuses: shiftStatusFilters,
    daysOfWeek: dayOfWeekFilters,
    startDate: startDateFilter,
    endDate: endDateFilter
  };
  var url = $('#UrlToFilter').val();
  $('#ListHolder').html("<%=web.loading %>");
  $.ajax({
    url: url,
    data: dataToPost,
    type: 'POST',
    success: function (data) {
      document.getElementById('ScheduledActivityShiftListHolder').innerHTML = data;
    },
    error: function () {
      v2ErrorNotice(v2Text.shared.genericAjaxErrorMessage);
    }
  });
});

The Get...FIlter functions are very simple functions that run in a few milliseconds... nothing interesting or noteworthy happening in there.

this bit attaches some of the behaviour that is very slow:
in other pages they react nice and quick, on this page... 2-3 seconds.

$('span.infoCard').die();
$('span.infoCard').live("mouseover", function () {

  var $this = $(this);
  if (!$this.data("toolTipAttached")) {

    var title = '';

    if ($this.attr('infoCardTitle') != "") {
      title = $this.attr('infoCardTitle');
    } else {
      title = $this.html();
    }

    $this.qtip({
      content: {
        text: "loading",
        title: title,
        ajax: {
          url: $this.attr('urlToGet')
          // data: data,
        }
      },
      position: {
        at: 'right middle',
        my: 'left top',
        adjust: {
          screen: 'flip'
        }
      },
      hide: {
        fixed: true,
        when: 'mouseout'
      },
      show: {
        solo: true,
        delay: 500,
        ready: true
      },
      style: {
        classes: 'ui-tooltip-light InfoCardTip',
        widget: true,
        tip: {
          corner: true,
          width: 15,
          height: 15
        }
      }
    });
    $this.data("toolTipAttached", true);
  }
});

There are 2 different versions of this for 2 different classes, one gets a single "shift" one gets the user s for a bunch of shifts. as with other things.  once the function itself runs quick,  the ajax is fast, the v2ReLoadScheduledActivitySection runs in about 50 ms. nothing interesting in there. :

$('div.GetShiftUserArrow').die('click');
$('div.GetShiftUserArrow').live('click', function () {
  var listIsVisible = $(this).attr('listIsVisible');
  var holder = $('#' + $(this).attr('listHolder'));
  var activityHolder = $('#TopLevel{0}'.format($(this).attr('activityShiftId')));

  if (listIsVisible == -1) {
    v2ReLoadScheduledActivitySection($(this), 1);
  } else {
    holder.empty().toggle('hide');
    $(this).removeClass('GetShiftUserArrowOpen');
    $(this).attr('listIsVisible', listIsVisible * -1);
  }
});

Here's a bit of the HTML. this is the
 for a day... the main list has one of these for every day of the year (or whatever range they pick).  There could be any number of sub li's in that list, but it tends to be between 1-10.

Friday, January 21, 2011 Start End Status Mn Mx BU Av As Co

SomeText 9:00 AM 12:30 PM

        3

        2

        1

        1

1 -- 0 0 2 0

Blah Bla blah 9:00 AM 5:00 PM

        3

        2

        1

        2

1 5 0 0 5 0

even more 1:00 PM 4:30 PM

        4

        1

        2

        3

1 5 0 0 7 3

anything with TipMe, or GlossaryMe brings up a qtip tooltip.

like this:

 $(".TipMe").live("mouseover", function () {
  var $this = $(this);
  $this.removeAttr('title');
  $this.removeAttr('alt');

  if (!$this.data("toolTipAttached")) {

    $this.qtip({
      show: {
        ready: true,
        solo: true,
        delay: 500
      },
      style: {
        classes: 'ui-tooltip-light InfoCardTip',
        widget: true
      },
      content: $this.attr('tooltip'),
      position: {
        at: 'bottomRight',
        my: 'topleft',
        adjust: {
          screen: 'flip',
          x: 0,
          y: 0
        }
      },
      hide: {
        fixed: true,
        inactive: 1000
      }
    });
    $this.data("toolTipAttached", true);
    //    $this.trigger("mouseover");
  }
});

Something tells me it might be all my tooltip handlers that are causing the problem...

Let me know if you guys want anything else!

Body:
"I don't think it is the complexity of my markup that is affecting the responsiveness of my scripts"

False assumptions are the worst leaders of the mind. It's interesting because you also said:

"this bit attaches some of the behaviour that is very slow, in other pages they react nice and quick, on this page... 2-3 seconds."

"i had 5 spans that were each nested in a span unnecessarily, i un-nested those and it seems to have cut the slowness in about 1/2!! (these 5 spans were repeated in every row)"

There you go. :)

What you can try is to change live handlers to delegate. The main difference between them is that live attaches The Handler to the document, while in case of delegate you can specify where to attach it. I think this can be the tipping point. Also try mouseenter which fires less frequently.

$('#ROOT').delegate(".infoCard", "mouseenter", function () { ... })

root can be any element depending on your site. You can try the parent <ul> for example.

Another thing to try is to use your own handler (but you can't use mouseenter then):

$("#ROOT").mouseover(function (e) {
    var $this = $(e.target);
    if ($this.hasClass('TipMe')) {
        // TipMe code...
    } else if ($this.hasClass('infoCard')) {
        // infoCard code...
    }
});

Let me know if any of them helped! :)


问:
Activating environment in virtualenvwrapper
i installed virtualenv and virtualenvwrapper and with this command i created an environment:

```<code>mkvirtualenv cv
</code>```

it works and after creating i was in the new environment. right now i restarted my computer and i want to activate that environment again, but how?

i use this tutorial to install Opencv on my Mac and one of steps is creating new environment. im confused right now:

```<code>http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/
</code>```

i uses virtualenv already but im new to virtualenvwrapper and i dont know what i have to do now

答:
I too faced the same problem.
So first I uninstalled virtualenvwrapper using,

```<code>$ sudo pip uninstall virtualenvwrapper
</code>```

Then I performed the documentation steps again with some changes this time. You can also do the same, it will work.

Install Steps

$ sudo pip install virtualenvwrapper

Now create a directory to store your virtual environment

$ mkdir ~/.virtualenvs

Now,

$ export WORKON_HOME=~/.virtualenvs

Now you have to open .bashrc file and add one line to it.

So, to do this first copy the line written below and then run,
$ nano .bashrc
And now paste it at the end of the script

. /usr/local/bin/virtualenvwrapper.sh

This will add virtualenvwrapper.sh to .bashrc

Now run ,

source /usr/local/bin/virtualenvwrapper.sh

Finally run to reload .bashrc,

source ~/.bashrc

Finally you can use
mkvirtualenv and workon commands without any problem.

Hope it helps.

Body:
i installed virtualenv and virtualenvwrapper and with this command i created an environment:

mkvirtualenv cv

it works and after creating i was in the new environment. right now i restarted my computer and i want to activate that environment again, but how?

i use this tutorial to install Opencv on my Mac and one of steps is creating new environment. im confused right now:

http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/

i uses virtualenv already but im new to virtualenvwrapper and i dont know what i have to do now

Body:
I too faced the same problem.
So first I uninstalled virtualenvwrapper using,

$ sudo pip uninstall virtualenvwrapper

Then I performed the documentation steps again with some changes this time. You can also do the same, it will work.

Install Steps

$ sudo pip install virtualenvwrapper

Now create a directory to store your virtual environment

$ mkdir ~/.virtualenvs

Now,

$ export WORKON_HOME=~/.virtualenvs

Now you have to open .bashrc file and add one line to it.

So, to do this first copy the line written below and then run,
$ nano .bashrc
And now paste it at the end of the script

. /usr/local/bin/virtualenvwrapper.sh

This will add virtualenvwrapper.sh to .bashrc

Now run ,

source /usr/local/bin/virtualenvwrapper.sh

Finally run to reload .bashrc,

source ~/.bashrc

Finally you can use
mkvirtualenv and workon commands without any problem.

Hope it helps.


问:
RestSharp ignoring system proxy (for example Fiddler) on .NET Core
I want check the http traffic with Fiddler, but no any http traffic captured, my testing codes:

```<code>private static void ByRestSharp()
{
    var restClient = new RestClient("https://jsonplaceholder.typicode.com");
    var request = new RestRequest("posts", Method.GET);
    var response = restClient.Get<List<Post>>(request);
    Console.WriteLine("{0} posts return by RestSharp.", response.Data.Count);
}
</code>```

But after I changed to use HttpClient, Fiddler can capture the http traffic, sample codes:

```<code>private static void ByHttpClient()
{
    var httpClient = new HttpClient();
    using (var req = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts"))
    using (var resp = httpClient.SendAsync(req).Result)
    {
        var json = resp.Content.ReadAsStringAsync().Result;
        var users = SimpleJson.SimpleJson.DeserializeObject<List<Post>>(json);
        Console.WriteLine("{0} posts return by HttpClient.", users.Count);
    }
}
</code>```

Is this a issue of RestSharp or Fiddler?

答:
RestSharp supported system proxy until we moved to .NET Standard. Then, we got issues with proxy on .NET Core and then using the system proxy was removed entirely. We have an issue opened on Github and you can check the progress there.

However, explicitly setting the proxy should work for full .NET Framework, check this issue.

Code from the issue, which is confirmed to be working:

```<code>var client = new RestClient("http://www.google.com");
client.Proxy = new WebProxy("127.0.0.1", 8888);
var req = new RestRequest("/", Method.GET);
var resp = client.Execute(req);
</code>```

Update 2018-05-31: RestSharp 106.3 is using the default proxy on .NET Core also, automatically. Tested with Fiddler.

Update 2022-02-23: RestSharp 107 has the Proxy property moved to RestClientOptions:

```<code>var options = new RestClientOptions("http://www.google.com") {
    Proxy = new WebProxy("127.0.0.1", 8888)
};
var client = new RestClient(options);
var req = new RestRequest("/");
var resp = await client.ExecuteAsync(req);
</code>```

Body:
I want check the http traffic with Fiddler, but no any http traffic captured, my testing codes:

private static void ByRestSharp()
{
    var restClient = new RestClient("https://jsonplaceholder.typicode.com");
    var request = new RestRequest("posts", Method.GET);
    var response = restClient.Get<List<Post>>(request);
    Console.WriteLine("{0} posts return by RestSharp.", response.Data.Count);
}

But after I changed to use HttpClient, Fiddler can capture the http traffic, sample codes:

private static void ByHttpClient()
{
    var httpClient = new HttpClient();
    using (var req = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts"))
    using (var resp = httpClient.SendAsync(req).Result)
    {
        var json = resp.Content.ReadAsStringAsync().Result;
        var users = SimpleJson.SimpleJson.DeserializeObject<List<Post>>(json);
        Console.WriteLine("{0} posts return by HttpClient.", users.Count);
    }
}

Is this a issue of RestSharp or Fiddler?

Body:
RestSharp supported system proxy until we moved to .NET Standard. Then, we got issues with proxy on .NET Core and then using the system proxy was removed entirely. We have an issue opened on Github and you can check the progress there.

However, explicitly setting the proxy should work for full .NET Framework, check this issue.

Code from the issue, which is confirmed to be working:

var client = new RestClient("http://www.google.com");
client.Proxy = new WebProxy("127.0.0.1", 8888);
var req = new RestRequest("/", Method.GET);
var resp = client.Execute(req);

Update 2018-05-31: RestSharp 106.3 is using the default proxy on .NET Core also, automatically. Tested with Fiddler.

Update 2022-02-23: RestSharp 107 has the Proxy property moved to RestClientOptions:

var options = new RestClientOptions("http://www.google.com") {
    Proxy = new WebProxy("127.0.0.1", 8888)
};
var client = new RestClient(options);
var req = new RestRequest("/");
var resp = await client.ExecuteAsync(req);

ContentLicense: CC BY-SA 4.0


问:
Visual Studio Publish Website Using SCP/SFTP
Is there a way to publish a web site from Visual Studio 2008 using SCP or SFTP?  I know it is possible to publish to my local filesystem and then perform the transfer with SCP, but I'd like something more seamless (e.g. part of Visual Studio).  Does this feature exist?  An addin perhaps?</p>

答:
If you have Windows 10 and bash/linux subsystem installed and a Linux/BSD server you can:

Combine ssh and rsync

I prefer to use rsync through a ssh pipe, since it won't upload files that werer not modified, it's more efficient.

from visual studio, publish in a folder, say I:/www/WebProject

use this command that updates changes only, and delete files that were deleted/absent from publish folder thanks to --delete

bash -c "rsync -avH --delete --progress /mnt/i/www/WebProject -e ssh server:/var/www/"

Where I:/www/WebProject is the local folder where the project was published, and /var/www the remote directory of the web application.

Preparation (to do once)

You need to work a bit to allow ssh to work without password but with keys.

let's say your bash username is also the same on the server; if not, just use username@server

name your server:

add xx.xx.xx.xx server to the file c:/windows/system32/drivers/etc/hosts)

add your server to hosts from bash with sudo echo "xx.xx.xx.xx server" >> /etc/hosts

from bash, generate your keys:

ssh --keygen
then [enter] (no passphrase)

send your public key to the server, in your home folder:

scp ~/.ssh/id_rsa.pub servername:~/

from your server (ssh server then password):

cat id_rsa.pub >> .ssh/authorized_keys && rm id_rsa.pub

Now you can ssh and scp without password. IMO this is way better than filezilla or just scp.


问:
How do I use Kotlin object by reflection
Let's say I need to set property A given by a String in Kotlin object O given by a String by reflection. If O was a class I could do something like this (disregard it has no sense):

```<code>fun setValue(ownerClassName: String, fieldName: String, value : Any) {
    val enclosingClass = Class.forName(ownerClassName).newInstance()
    val enclosingClassField = enclosingClass.javaClass.getDeclaredField(fieldName)
    enclosingClassField.isAccessible = true
    enclosingClassField.set(enclosingClass, value)
}
</code>```

But how would I do it if O is an object?

答:
object is translated into a class with a private constructor and a static  field called INSTANCE where the only instance is stored when this class is loaded, so replacing Class.forName(ownerClassName).newInstance() with

```<code>Class.forName(ownerClassName).getDeclaredField("INSTANCE").get(null)
</code>```

should work.

Javadoc:

Class#forName

Class#getDeclaredField

Field#get

Body:
Let's say I need to set property A given by a String in Kotlin object O given by a String by reflection. If O was a class I could do something like this (disregard it has no sense):

fun setValue(ownerClassName: String, fieldName: String, value : Any) {
    val enclosingClass = Class.forName(ownerClassName).newInstance()
    val enclosingClassField = enclosingClass.javaClass.getDeclaredField(fieldName)
    enclosingClassField.isAccessible = true
    enclosingClassField.set(enclosingClass, value)
}

But how would I do it if O is an object?

Body:
object is translated into a class with a private constructor and a static  field called INSTANCE where the only instance is stored when this class is loaded, so replacing Class.forName(ownerClassName).newInstance() with

Class.forName(ownerClassName).getDeclaredField("INSTANCE").get(null)

should work.

Javadoc:

Class#forName

Class#getDeclaredField

Field#get


问:
Setting up default images in PHP
I am building a social networking site and one functionality is an update status whereby one can update text only as their status or the could update text and an image. As follows:

avatar pic - update text - update image(if image)

avatar pic - update text - default image(if update image not uploaded)

default avatar pic - update text - default image(if avatar and update image not uploaded)

I got the default avatar to work fine but the problem is getting the default update image to show if one does not include an update image.

How do I do this or does anyone have a different solution?

Below is my code:

PHP

```<code><?php
$user_id = $_SESSION['UserSession'];
//query user avatar
$query_avatar_thumb = "SELECT picture_thumb_url FROM picture WHERE user_id='$user_id' AND avatar='1' LIMIT 1";
$avatar_thumb_result = mysql_query($query_avatar_thumb) or die(mysql_error());
$avatar_thumb = mysql_fetch_assoc($avatar_thumb_result);
$totalRows_avatar_thumb = mysql_num_rows($avatar_thumb_result);

//query username
$query_user_info = "SELECT username FROM users WHERE user_id='$user_id'";
$user_info = mysql_query($query_user_info, $connections) or die(mysql_error());
$row_user_info = mysql_fetch_assoc($user_info);

//query update image
$query_wid_updates = "SELECT update_text, picture_thumb_url FROM wid_updates LEFT JOIN picture ON wid_updates.attached_picture_id = picture.picture_id
WHERE wid_updates.user_id = '$user_id' ORDER BY wid_updates.update_id DESC";
$wid_updates = mysql_query($query_wid_updates, $connections) or die(mysql_error());
$row_wid_updates = mysql_fetch_assoc($wid_updates);
$totalRows_wid_updates = mysql_num_rows($wid_updates);
?>
</code>```

MY HTML to show results:

```<code><div id="previous_updates">
<?php do { ?>
<table width="460" border="0">
  <tr>
    <td height="50" width="50">
    <?php
    if ($totalRows_avatar_thumb==1)
    {
        echo "<a href='index.php?#main_profile_div'><img src='User_Images/$avatar_thumb[picture_thumb_url]' border='0' height='50' width='50'/></a>";
    }
    else
    {
        echo "<a href='index.php?#main_profile_div'><img src='/NNL/Style/Images/default_avatar.png' border='0' height='50' width='50'/></a>";
    }
    ?>
    </td>
    <td width="360" colspan="3" class="overide" id="update_box"><div><?php echo $row_wid_updates['update_text']; ?></div></td>
    <td width="50">
    <?php
    if ($totalRows_wid_updates)
    {
        echo "<a href='#pictures.php'><img src='User_Images/$row_wid_updates[picture_thumb_url]' border='0' height='50' width='50'/></a>";
    }
    else
    {
        echo "<a href='#pictures.php'><img src='/NNL/Style/Images/no_update_image.png' border='0' height='50' width='50'/></a>";
    }
    ?>
    </td>
  </tr>
  <tr>
    <td width="50" height="30"></td>
    <td width="120"></td>
    <td width="120" class="ordinary_text_12_green">Comment</td>
    <td width="120"></td>
    <td width="50"></td>
  </tr>
</table>
<?php } while ($row_wid_updates = mysql_fetch_assoc($wid_updates)); ?>
</div>
</code>```

My wid_updates table:

```<code>update_id   update_text     attached_picture_id     user_id     timestamp
48             b                   NULL                92   2011-01-13 13:22:23
51             c                   61                  92   2011-01-13 18:30:06
52          d                   NULL                92  2011-01-13 18:30:14
53          PPP                 67                  95  2011-01-17 10:28:01
54          PPP                 NULL                95  2011-01-17 10:28:36
55          oo                  68                  95  2011-01-17 10:30:42
56          ll                  69                  95  2011-01-17 10:35:16
57          tt                  70                  95  2011-01-17 10:35:34
58          monday              71                  92  2011-01-17 10:52:59
</code>```

As of right now, the default images are blank and and I understand why, my if ($totalRows_wid_updates) statement is wrong. How do I fix it. Btw, this is in profile.php where only a users updates are shown, index.php will containing a users plus his pals updates.

答:
```<code><img src="User_Images/<?php echo ($avatar_thumb[picture_thumb_url] != ''? $avatar_thumb[picture_thumb_url]: 'file_name_of_some_default_image.png'); ?>" border='0' height='50' width='50'/>
</code>```

Title: Setting up default images in PHP

Body:
I am building a social networking site and one functionality is an update status whereby one can update text only as their status or the could update text and an image. As follows:

avatar pic - update text - update image(if image)

avatar pic - update text - default image(if update image not uploaded)

default avatar pic - update text - default image(if avatar and update image not uploaded)

I got the default avatar to work fine but the problem is getting the default update image to show if one does not include an update image.

How do I do this or does anyone have a different solution?

Below is my code:

PHP

<?php
$user_id = $_SESSION['UserSession'];
//query user avatar
$query_avatar_thumb = "SELECT picture_thumb_url FROM picture WHERE user_id='$user_id' AND avatar='1' LIMIT 1";
$avatar_thumb_result = mysql_query($query_avatar_thumb) or die(mysql_error());
$avatar_thumb = mysql_fetch_assoc($avatar_thumb_result);
$totalRows_avatar_thumb = mysql_num_rows($avatar_thumb_result);

//query username
$query_user_info = "SELECT username FROM users WHERE user_id='$user_id'";
$user_info = mysql_query($query_user_info, $connections) or die(mysql_error());
$row_user_info = mysql_fetch_assoc($user_info);

//query update image
$query_wid_updates = "SELECT update_text, picture_thumb_url FROM wid_updates LEFT JOIN picture ON wid_updates.attached_picture_id = picture.picture_id
WHERE wid_updates.user_id = '$user_id' ORDER BY wid_updates.update_id DESC";
$wid_updates = mysql_query($query_wid_updates, $connections) or die(mysql_error());
$row_wid_updates = mysql_fetch_assoc($wid_updates);
$totalRows_wid_updates = mysql_num_rows($wid_updates);
?>

MY HTML to show results:

<?php do { ?>

    <?php
    if ($totalRows_avatar_thumb==1)
    {
        echo "";
    }
    else
    {
        echo "";
    }
    ?>

<?php echo $row_wid_updates['update_text']; ?>

    <?php
    if ($totalRows_wid_updates)
    {
        echo "";
    }
    else
    {
        echo "";
    }
    ?>

    Comment

<?php } while ($row_wid_updates = mysql_fetch_assoc($wid_updates)); ?>

My wid_updates table:

update_id   update_text     attached_picture_id     user_id     timestamp
48             b                   NULL                92   2011-01-13 13:22:23
51             c                   61                  92   2011-01-13 18:30:06
52          d                   NULL                92  2011-01-13 18:30:14
53          PPP                 67                  95  2011-01-17 10:28:01
54          PPP                 NULL                95  2011-01-17 10:28:36
55          oo                  68                  95  2011-01-17 10:30:42
56          ll                  69                  95  2011-01-17 10:35:16
57          tt                  70                  95  2011-01-17 10:35:34
58          monday              71                  92  2011-01-17 10:52:59

As of right now, the default images are blank and and I understand why, my if ($totalRows_wid_updates) statement is wrong. How do I fix it. Btw, this is in profile.php where only a users updates are shown, index.php will containing a users plus his pals updates.


问:
making counter in verilog, Modelsim

i'm trying to make round robin counter in verilog

```<code>module rr_arbiter (
clk, // positive edge trigger
reset,  // negative edge trigger
req0, req1, req2, req3,
grant0, grant1, grant2, grant3,
priority, priority_req);

input clk, reset;
input req0, req1, req2, req3;
input priority;
input [1:0] priority_req;

output grant0, grant1, grant2, grant3;

reg x

always(posedge clk or negedge reset) begin
pirority_req = priority;

if (reset) begin
    grant0 <= 1'b0;
    grant1 <= 1'b0;
    grant2 <= 1'b0;
    grant3 <= 1'b0;
   end
else
begin
    if(priority == 1)
        if (priority req == 2b'00)
            begin
            x=1;
            grant0 <= (grant0*(~x))+(grant1*x);
            x=0;
            grant0 <= (grant0*(~x))+(grant1*x);
            grant1 <= grant2;
            grant2 <= grant3;
            grant3 <= grant1;
            //  counter 0012300123
            end
        else if (priority req == 2b'01)
            begin
            grant0 <= grant1;
            x=1;
            grant1 <= (grant1*(~x))+(grant2*x);
            x=0;
            grant1 <= (grant1*(~x))+(grant2*x);
            grant2 <= grant3;
            grant3 <= grant1;
            //  counter 0112301123
            end
        else if (priority req == 2b'10)
            begin
            grant0 <= grant1;
            grant1 <= grant2;
            x=1;
            grant2 <= (grant2*(~x))+(grant3*x);
            x=0;
            grant2 <= (grant2*(~x))+(grant3*x);
            grant3 <= grant1;
            //  counter 0122301223
            end
        else if (priority req == 2b'11)
            begin
            grant0 <= grant1;
            grant1 <= grant2;
            grant2 <= grant3;
            x=1;
            grant3 <= (grant3*(~x))+(grant1*x);
            x=0;
            grant3 <= (grant3*(~x))+(grant1*x);
            //  counter 0123301233
            end
    end

    else
    begin
        grant0 <= ~grant2 * grant3;
        grant1 <= grant0;
        grant2 <= grant1;
        grant3 <= grant2;
        //counter 01230123
    end
end
end

end

endmodule
</code>```

as you can see, i'm trying to make round robin counter.
each case it's like (grant)01230123.., 0012300123.., 0112301123.., 0122301223.., 0123301233...

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(17): near "always": syntax error, unexpected always, expecting ';' or ','.

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(22): near "<=": syntax error, unexpected <=.

** Error: C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(22): (vlog-13205) Syntax error found in the scope following 'grant0'. Is there a missing '::'?

答:
The error message for line 17 is self-explanatory. It is expecting a ';'. You are missing a ';' on line 15.

If an error message appears to make no sense, always cast your eye up the screen to see whether the problem is with a previous line.

Title: making counter in verilog, Modelsim

Body:
i'm trying to make round robin counter in verilog

module rr_arbiter (
clk, // positive edge trigger
reset,  // negative edge trigger
req0, req1, req2, req3,
grant0, grant1, grant2, grant3,
priority, priority_req);

input clk, reset;
input req0, req1, req2, req3;
input priority;
input [1:0] priority_req;

output grant0, grant1, grant2, grant3;

reg x

always(posedge clk or negedge reset) begin
pirority_req = priority;

if (reset) begin
    grant0 <= 1'b0;
    grant1 <= 1'b0;
    grant2 <= 1'b0;
    grant3 <= 1'b0;
   end
else
begin
    if(priority == 1)
        if (priority req == 2b'00)
            begin
            x=1;
            grant0 <= (grant0*(~x))+(grant1*x);
            x=0;
            grant0 <= (grant0*(~x))+(grant1*x);
            grant1 <= grant2;
            grant2 <= grant3;
            grant3 <= grant1;
            //  counter 0012300123
            end
        else if (priority req == 2b'01)
            begin
            grant0 <= grant1;
            x=1;
            grant1 <= (grant1*(~x))+(grant2*x);
            x=0;
            grant1 <= (grant1*(~x))+(grant2*x);
            grant2 <= grant3;
            grant3 <= grant1;
            //  counter 0112301123
            end
        else if (priority req == 2b'10)
            begin
            grant0 <= grant1;
            grant1 <= grant2;
            x=1;
            grant2 <= (grant2*(~x))+(grant3*x);
            x=0;
            grant2 <= (grant2*(~x))+(grant3*x);
            grant3 <= grant1;
            //  counter 0122301223
            end
        else if (priority req == 2b'11)
            begin
            grant0 <= grant1;
            grant1 <= grant2;
            grant2 <= grant3;
            x=1;
            grant3 <= (grant3*(~x))+(grant1*x);
            x=0;
            grant3 <= (grant3*(~x))+(grant1*x);
            //  counter 0123301233
            end
    end

    else
    begin
        grant0 <= ~grant2 * grant3;
        grant1 <= grant0;
        grant2 <= grant1;
        grant3 <= grant2;
        //counter 01230123
    end
end
end

end

endmodule

as you can see, i'm trying to make round robin counter.
each case it's like (grant)01230123.., 0012300123.., 0112301123.., 0122301223.., 0123301233...

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(17): near "always": syntax error, unexpected always, expecting ';' or ','.

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(22): near "<=": syntax error, unexpected <=.

** Error: C:/Modeltech_pe_edu_10.4a/examples/rr_arbiter.v(22): (vlog-13205) Syntax error found in the scope following 'grant0'. Is there a missing '::'?


问:
How can I stop Android Studio Indexing/Scanning/Building altogether at startup?
How can I stop this indexing or whatever this startup process? What is it for? Why is it doing it? Can I defer the loading of such huge process later on when I most need it?</p>

答:
You can actually cancel the build on start. I find this build to be pointless for a variety of reasons:

most devs would start the program then connect the phone/open the emulator first

even though the builds the app this doesn't mean much because when you click build again it starts over...

The way to cancel the build is just simply click on the little red x at the task at the bottom.

When you ready to build then you can just click on run again.

I consider this a bug because it's indeed pointless since it does not make consequent builds any faster nor it is required for the IDE to work unlike what the accepted answer suggests.

However mind that this does not the same as "Indexing" which is Android Studio indeed need. However on a normal startup case you can just cancel the build.

I have an open request for this at Google, we will see if they actually do something with it in the future since I don't see the point of wasting sometimes minutes for a initial build I cannot even use later.


问:
How to display MYSQL table columns in a CSS block style?
I want to display table columns in a css display:block style.The end result i want should look like the table below.

I use MYSQL and PHP to display the columns of the table

This is how the data from the table currently looks like when it is rendered in the browser.

Source code

```<code><?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "<table style ='width:100%'>";
  echo "<tr>";

  echo "<th>".$columnnames. "</th>";

  echo "</tr>";
  echo "</table>";

 }
 ?>
</code>```

答:
Every instance the loop is running, it is creating a table with the width of 100% and pasting a header with the value of $columnames in to it. This means that since the loop is looking for if 0 is greater than the amount of columns (and adding one to it) that it will do this for every instance, and since the width is 100%, the "new table" created by the loop won't have space to fit in something like the side.

To solve this, use this code:

```<code><?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);

  echo "<table style ='width:100%'>";
  echo "<tr>";

for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "<th>".$columnnames. "</th>";

 }

  echo "</tr>";
  echo "</table>";
 ?>
</code>```

Body:
I want to display table columns in a css display:block style.The end result i want should look like the table below.

I use MYSQL and PHP to display the columns of the table

This is how the data from the table currently looks like when it is rendered in the browser.

Source code

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "
";
  echo "
";

  echo "".$columnnames. "	";

  echo "
";
  echo "
";

 }
 ?>

Body:
Every instance the loop is running, it is creating a table with the width of 100% and pasting a header with the value of $columnames in to it. This means that since the loop is looking for if 0 is greater than the amount of columns (and adding one to it) that it will do this for every instance, and since the width is 100%, the "new table" created by the loop won't have space to fit in something like the side.

To solve this, use this code:

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);

  echo "<table style ='width:100%'>";
  echo "<tr>";

for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "<th>".$columnnames. "</th>";

 }

  echo "</tr>";
  echo "</table>";
 ?>


问:
RichEdit20A line selection mode similar to Notepad
I'm trying to change the way RichEdit20A Windows control selects line so it's similar to how it works in Notepad.

By default, if I select a line (e.g. Shift-End), then all the characters and the end of line is selected:

```<code>Sample text
^^^^^^^^^^^^ <- this is the selection
</code>```

In Notepad it selects just the text:

```<code>Sample text
^^^^^^^^^^^
</code>```

As a result, pressing delete (or backspace) in RichEdit20A control removes the line while in Notepad it just removes the text and keeps the line empty.

Is there any simple way (other than handling selection on my own) to configure the RichEdit20A control to keep formatting but make the line selection to work like in Notepad?

答:
I don't know such a setting to influence the RTF control. But pressing Shift+End is a key input that is possible to trap with a WM_KEYDOWN handler, when you subclass the control.

You can use EM_LINEINDEX with -1 to get the current line start index.

Now with this index you can use EM_LINELENGTH.

Get the current selection (EM_GESTEL) and now you are free to use EM_SETSEL with the values you like to extend it.

Body:
I'm trying to change the way RichEdit20A Windows control selects line so it's similar to how it works in Notepad.

By default, if I select a line (e.g. Shift-End), then all the characters and the end of line is selected:

Sample text
^^^^^^^^^^^^ <- this is the selection

In Notepad it selects just the text:

Sample text
^^^^^^^^^^^

As a result, pressing delete (or backspace) in RichEdit20A control removes the line while in Notepad it just removes the text and keeps the line empty.

Is there any simple way (other than handling selection on my own) to configure the RichEdit20A control to keep formatting but make the line selection to work like in Notepad?


问:
Use tasks in always @* blocks
I was intended to use a customized task in an always @* block, like:

```<code>input [31:0] a;
input b;
output reg [31:0] c;

task mytask;
begin
    if (b) begin
        c = a;
    end
end
endtask

always @* begin
    // ... (b is not included)
    mytask;
    // ... (b is not included)
end
</code>```

What I think is that when signal b changes from 0 to 1, c will be set to the content of a. Then I found the always block is not sensitive to signal b (using ISim 14.7).

Is this a bug or designed to behave like this?

答:
That is the defined behavior in Verilog. If you wan to make the task sensitive to the signals you have to put them in the I/O list:

```<code>task mytask(input b);
</code>```

(And the reason I know is that I also made that error and looked it up)

Title: Use tasks in always @* blocks

Body:
I was intended to use a customized task in an always @* block, like:

input [31:0] a;
input b;
output reg [31:0] c;

task mytask;
begin
    if (b) begin
        c = a;
    end
end
endtask

always @* begin
    // ... (b is not included)
    mytask;
    // ... (b is not included)
end

What I think is that when signal b changes from 0 to 1, c will be set to the content of a. Then I found the always block is not sensitive to signal b (using ISim 14.7).

Is this a bug or designed to behave like this?

Body:
That is the defined behavior in Verilog. If you wan to make the task sensitive to the signals you have to put them in the I/O list:

task mytask(input b);

(And the reason I know is that I also made that error and looked it up)


问:
Set cookie by php session username
I have set a general cookie that works fine for a run once situation. However, what I need to do is set a cookie by username so a message is displayed only once per user. I am using php to set a session for the username linked to mysql.

I have posted the code I am using for the general cookie and wonder if it can be modified to target a username rather than a general cookie.

I would be grateful if someone could help with this. Thanks

```<code><script>
$(document).ready(function() {
  if (document.cookie.indexOf("runOnce") < 0) {
    $("#message3").dialog({
      modal: true,

      buttons: {
        'Confirm': function() {
            document.cookie = 'runOnce = true; expires = Fri, 31 Dec 9999 23:59:59 GMT; path = /';
            $(this).dialog("close");
          }
          /* ,
          No: function () {
          $( this ).dialog( "close" );
          }*/

      }
    });

    // Hide the close button
    jQuery("a.ui-dialog-titlebar-close").hide();

    //Disable the confirm button on page load
    $(":button:contains('Confirm')").attr("disabled", true).addClass("ui-state-disabled");

    // Uncheck the 'agree' checkbox
    $(function() {
      $('#message3 input[type=checkbox]').attr('checked', false);
    });

    // Hide red message paragraph
    $('#agreemsg').hide();

    // Function to enable and disable confirm button based on checkbox click event
    $("#checkme").click(function() {

      var isChecked = $("#checkme").is(":checked");

      if (isChecked) {

        //alert("CheckBox checked.");
        $(":button:contains('Confirm')").removeAttr('disabled').removeClass('ui-state-disabled');
        $('#agreemsg').show();

      } else {
        //alert("CheckBox not checked.");
        $(":button:contains('Confirm')").prop("disabled", true).addClass("ui-state-disabled");
        $('#agreemsg').hide();
      }
    });
    //}
  };
});
</script>
</code>```

答:
Cookies are not the correct place to implement this. It's best to add additional property in the database associated with your user, for example:

Table: users

Columns:

```<code>id
username
... other fields ...
is_first_login
</code>```

Display your message if is_first_login is not true

Mark is_first_login to true in the database after your message has been displayed

Title: Set cookie by php session username

Body:
Cookies are not the correct place to implement this. It's best to add additional property in the database associated with your user, for example:

Table: users

Columns:

id
username
... other fields ...
is_first_login

Display your message if is_first_login is not true

Mark is_first_login to true in the database after your message has been displayed