问:
When writing to the Windows Event Log, is it possible to create a custom link text for URLs?
I'm just using the vanilla EventLog.WriteEntry method:

```<code>        EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, id);
</code>```

Here's how the message shows up in the Event Log, with the links in the parenthesis working just fine, but it's ugly:

Example 1:

Please contact us via email (mailto:some@example.com) or online (http://example.com).

Here's how the message shows up in the Event Log, with the HTML "markup", doesn't even handle it:

Example 2:

```<code>Please contact us via <a href="mailto:some@example.com">email</a> or <a href="http://example.com">online</a>.
</code>```

This is how I would like the message to show up, but with "email" and "online" as the link texts:

Example 3:

Please contact us via email or online.

I've tried the ... HTML tags with no success.

答: Beings the EventLog is not rendered as Html, I would have to say it doesn't work that way.</p>

Body:
I'm just using the vanilla EventLog.WriteEntry method:

        EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, id);

Here's how the message shows up in the Event Log, with the links in the parenthesis working just fine, but it's ugly:

Example 1:

Please contact us via email (mailto:some@example.com) or online (http://example.com).

Here's how the message shows up in the Event Log, with the HTML "markup", doesn't even handle it:

Example 2:

Please contact us via email or online.

This is how I would like the message to show up, but with "email" and "online" as the link texts:

Example 3:

Please contact us via email or online.

I've tried the ... HTML tags with no success.


来源: stackexchange

问:
Alternative to negative lookbehind?
I'm specifically using Ruby but I'm curious... say I'm trying to match a decimal followed by at least three digits.

Here's the regexp: /(\.\d{5,})/

Without using a negative lookbehind, how would I make this only match if it follows either A) a space or tab or newline, or B) is the start of a string?

答:
Let's first consider how it would be done with a lookbehind.
Then we just check if before what we capture is the start of the line, or a whitespace:

```<code>(?<=^|\s)(\.\d{5,})
</code>```

We could simply change that lookbehind to a normal capture group.

Which means a preceding whitespace also gets captured.  But in a replace we can just use or not use that capture group 1.

```<code>(^|\s)(\.\d{5,})
</code>```

In the PCRE regex engine we have \K

\K : resets the starting point of the reported match. Any previously
  consumed characters are no longer included in the final match

So by using that \K in the regex, the preceding space isn't included in the match

```<code>(?:^|\s)\K(\.\d{5,})
</code>```

A test here

However, if you use Rubi's scan with a regex that has capture groups?

Then it seems that it only outputs the capture groups (...), but not the non-capture groups (?:...) or what's not in a capture group.

For example:

```<code>m = '.12345 .123456 NOT.1234567'.scan(/(?:^|\s)(\.\d{5,})/)
=> [[".12345"], [".123456"]]

m = 'ab123cd'.scan(/[a-z]+(\d+)(?:[a-z]+)/)
=> [["123"]]
</code>```

So when you use scan, lookarounds don't need to be used.

ContentLicense: CC BY-SA 3.0

Title: Alternative to negative lookbehind?

Body:
Let's first consider how it would be done with a lookbehind.
Then we just check if before what we capture is the start of the line, or a whitespace:

(?<=^|\s)(\.\d{5,})

We could simply change that lookbehind to a normal capture group.

Which means a preceding whitespace also gets captured.  But in a replace we can just use or not use that capture group 1.

(^|\s)(\.\d{5,})

In the PCRE regex engine we have \K

\K : resets the starting point of the reported match. Any previously
  consumed characters are no longer included in the final match

So by using that \K in the regex, the preceding space isn't included in the match

(?:^|\s)\K(\.\d{5,})

A test here

However, if you use Rubi's scan with a regex that has capture groups?

Then it seems that it only outputs the capture groups (...), but not the non-capture groups (?:...) or what's not in a capture group.

For example:

m = '.12345 .123456 NOT.1234567'.scan(/(?:^|\s)(\.\d{5,})/)
=> [[".12345"], [".123456"]]

m = 'ab123cd'.scan(/[a-z]+(\d+)(?:[a-z]+)/)
=> [["123"]]

So when you use scan, lookarounds don't need to be used.

ContentLicense: CC BY-SA 4.0


问:
CSS Star outline
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

```<code>    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}
</code>```

Working example here: jsfiddle

But what about a transparent fill with a red outline?

Title: CSS Star outline

Body:
Is there any way to make a css star shape outline?

I know you can make a filled in one, with the following css

    .star-five {
       margin: 50px 0;
       position: relative;
       display: block;
       color: red;
       width: 0px;
       height: 0px;
       border-right:  100px solid transparent;
       border-bottom: 70px  solid red;
       border-left:   100px solid transparent;
       -moz-transform:    rotate(35deg);
       -webkit-transform: rotate(35deg);
       -ms-transform:     rotate(35deg);
       -o-transform:      rotate(35deg);
    }
.star-five:before{
...
}
.star-five:after {
...
}

Working example here: jsfiddle

But what about a transparent fill with a red outline?

Body:
You could use an SVG:

<svg width="320" height="320"><path  d="
M 160.000 180.000
L 183.511 192.361
L 179.021 166.180
L 198.042 147.639
L 171.756 143.820
L 160.000 120.000
L 148.244 143.820
L 121.958 147.639
L 140.979 166.180
L 136.489 192.361
L 160.000 180.000
" stroke="#f00" stroke-width="1" fill="none"/></svg>

I used this site to generate it if it helps: http://www.smiffysplace.com/stars.html


问:
add_subdirectory() without installing anything
With CMake I use add_subdirectory(gtest) to build gtest for testing my project. I also use CPack to make an installer.

The problem is the gtest repo (which is a git submodule) runs install() on some files so they end up in my installer! Obviously I don't want that. Is there a way to disable install() commands for a given subdirectory without just removing them from the CMakeLists?

答:
You can use this to prevent Google Test from being installed:</p>

```<code>add_directory(gtest EXCLUDE_FROM_ALL)
</code>```

Body:
You can use this to prevent Google Test from being installed:

add_directory(gtest EXCLUDE_FROM_ALL)


问:
SQL Server refactor a column from varchar(50) to uniqueidentifier and surrounding issues
I have a table message in a database that has almost a million rows. It has a externalId column which is varchar(50). The values stored in it are guid but I want to update this column to be uniqueidentifier.

So I think I am going to add a new column which is uniqueidentifier. Copy all the values across to this column and then drop the original column. Then I will rename this column to externalId.

My problem is there are hundreds of stored procs etc and I need to make sure that I don't break anything. I also have to grep through all the code and make changes so that we expect a Guid and not a string. (I am using C#)

Does anyone have some tips or recommendations?

Would I be better do just duplicate this column and not touch the existing column and make any code that does a select on it use the guid column instead of the string (currently it sometimes times-out!). I would also have to update any code then that inserts into this table to also insert a guid...)

I love legacy crap .......................

答:
You could simply

```<code>alter table message
    alter column externalId uniqueidentifier
</code>```

The risk is that if any of the values stored in the column are not guids, you'll see an error like:

```<code>Conversion failed when converting from a character string to uniqueidentifier.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could simply

alter table message
    alter column externalId uniqueidentifier

The risk is that if any of the values stored in the column are not guids, you'll see an error like:

Conversion failed when converting from a character string to uniqueidentifier.


问:
solr schema: org.apache.solr.analysis.StopFilterFactory or solr.StopFilterFactory
My schema file refers to solr.StopFilterFactory however, it seems that this class's actual name is: org.apache.solr.analysis.StopFilterFactory.
Is that correct? If yes, where is that shortcut configured which allows me to use 'solr.StopFilterFactory`?

答: That is done programatically, so if you want to delve into the details I would start in IndexSchema's readSchema() and follow the lead there. You will get to exact place where the substitution is made eventually.</p>


问:
PlaceLikelihoodBuffer is null
I am working on Google Maps and trying to run a github project: "Select Current Place and Show Details on a Map" this is the link . But when i am running the project then it throws a Null Pointer exception on "PlaceLikelihoodBuffer". The block of code where null is returning is this

```<code>PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);

        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
                int i = 0;
                if (!likelyPlaces.getStatus().isSuccess()) {
                    // Request did not complete successfully
                    Toast.makeText(MapsMarkerActivity.this, "Request did not complete successfully", Toast.LENGTH_SHORT).show();
                    likelyPlaces.release();
                    return;
                }
                mLikelyPlaceNames = new String[mMaxEntries];
                mLikelyPlaceAddresses = new String[mMaxEntries];
                mLikelyPlaceAttributions = new String[mMaxEntries];
                mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
                Log.e("result",likelyPlaces.toString());
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    // Build a list of likely places to show the user. Max 5.
                    mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
                    mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
                    mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
                            .getAttributions();
                    mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();

                    i++;
                    if (i > (mMaxEntries - 1)) {
                        break;
                    }
                }
                // Release the place likelihood buffer, to avoid memory leaks.
                likelyPlaces.release();

                // Show a dialog offering the user the list of likely places, and add a
                // marker at the selected place.
                openPlacesDialog();
            }
        });
</code>```

Actually in above code likelyPlaces is null. I want to ask that why likelyPlaces are null and how to solve this error.

UPDATE

These are the Log details

E/result: PlaceLikelihoodBuffer{status=Status{statusCode=ERROR, resolution=null}, attributions=null}

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                                             java.lang.NullPointerException
                                                 at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
                                                 at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
                                                 at android.widget.AbsListView.obtainView(AbsListView.java:2177)
                                                 at android.widget.ListView.measureHeightOfChildren(ListView.java:1247)
                                                 at android.widget.ListView.onMeasure(ListView.java:1159)
                                                 at android.view.View.measure(View.java:15848)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                 at android.view.View.measure(View.java:15848)
</code>```

at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.view.View.measure(View.java:15848)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
                                                       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1079)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:562)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:532)
                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
                                                       at android.os.Handler.handleCallback(Handler.java:730)
                                                       at android.os.Handler.dispatchMessage(Handler.java:92)
                                                       at android.os.Looper.loop(Looper.java:137)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5103)
                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:525)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                       at dalvik.system.NativeStart.main(Native Method)

When we click on Get Places button then this error appears.

答:
you are right about the problem being in "placeLikelihood", I ran into the same problem and after some research found out that I forgot to enable "Google Places API for Android" from Google Developer Console. This should solve the null pointer exception.
Go to this link: https://console.developers.google.com .Then choose your connected app and click on enable API. Then on the next page search for the Google Places API and enable it, the above problem would be resolved. Cheers!</p>

Title: PlaceLikelihoodBuffer is null

Body:
I am working on Google Maps and trying to run a github project: "Select Current Place and Show Details on a Map" this is the link . But when i am running the project then it throws a Null Pointer exception on "PlaceLikelihoodBuffer". The block of code where null is returning is this

PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);

        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
                int i = 0;
                if (!likelyPlaces.getStatus().isSuccess()) {
                    // Request did not complete successfully
                    Toast.makeText(MapsMarkerActivity.this, "Request did not complete successfully", Toast.LENGTH_SHORT).show();
                    likelyPlaces.release();
                    return;
                }
                mLikelyPlaceNames = new String[mMaxEntries];
                mLikelyPlaceAddresses = new String[mMaxEntries];
                mLikelyPlaceAttributions = new String[mMaxEntries];
                mLikelyPlaceLatLngs = new LatLng[mMaxEntries];
                Log.e("result",likelyPlaces.toString());
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    // Build a list of likely places to show the user. Max 5.
                    mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
                    mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
                    mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
                            .getAttributions();
                    mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();

                    i++;
                    if (i > (mMaxEntries - 1)) {
                        break;
                    }
                }
                // Release the place likelihood buffer, to avoid memory leaks.
                likelyPlaces.release();

                // Show a dialog offering the user the list of likely places, and add a
                // marker at the selected place.
                openPlacesDialog();
            }
        });

Actually in above code likelyPlaces is null. I want to ask that why likelyPlaces are null and how to solve this error.

UPDATE

These are the Log details

E/result: PlaceLikelihoodBuffer{status=Status{statusCode=ERROR, resolution=null}, attributions=null}

E/AndroidRuntime: FATAL EXCEPTION: main
                                             java.lang.NullPointerException
                                                 at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
                                                 at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
                                                 at android.widget.AbsListView.obtainView(AbsListView.java:2177)
                                                 at android.widget.ListView.measureHeightOfChildren(ListView.java:1247)
                                                 at android.widget.ListView.onMeasure(ListView.java:1159)
                                                 at android.view.View.measure(View.java:15848)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                 at android.view.View.measure(View.java:15848)

at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at android.view.View.measure(View.java:15848)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
                                                       at android.view.View.measure(View.java:15848)
                                                       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
                                                       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1079)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:562)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:532)
                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
                                                       at android.os.Handler.handleCallback(Handler.java:730)
                                                       at android.os.Handler.dispatchMessage(Handler.java:92)
                                                       at android.os.Looper.loop(Looper.java:137)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5103)
                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:525)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                       at dalvik.system.NativeStart.main(Native Method)

When we click on Get Places button then this error appears.


问:
How to save previous state/ page data before going to another page in React JS

this.state = {
            name: '',
            color: '',
            description: '',
            beacons: []
        };

         handleColors = (item) => {
          this.setState({
              color: item.value
          });

      };

    handleBeaconChange = (beacons) => {
          this.setState({
              beacons
          });

      };

    handleInputChange(event) {

        this.setState({
            [event.target.name]: event.target.value
        });

    }

                    NAME*
                      <input type="text"
                       className="form-control margin-select"
                       placeholder="Name"
                       value={this.state.name}
                        name="name"
                        onChange={this.handleInputChange}
                       />

                            COLOR
                        <Select
                          className="margin-select"
                          value={this.state.color}
                          options={colorValues}
                          onChange={this.handleColors}/>

                    DESCRIPTION
                      <textarea
                      className="form-control margin-select"
                      placeholder="Description"
                      value={this.state.description}
                        name="description"
                        onChange={this.handleInputChange}
                      />

{this.props.label}

                            BEACON (s)
                        <Select.Async
                          multi={true}
                          className="margin-select"
                          value={this.state.beacons}
                          loadOptions={getBeacons}
                          onChange={this.handleBeaconChange}/>

                        Add Beacon

```

This is the image.
Now i just wanted to save previous form data before going to another page
Like for example in this picture i had entered name and color values in the fields and when i click on "Add beacon link", it will route me to another form but the values i entered in this form were lost when i will come back to it.
Any solutions regarding that?

答:
You can make use of Redux to achieve the same. What you need to do is to save the form states in redux store rather than the component localState itself

You reducer will look something like

```<code>const initialState = {
      name: '',
            color: '',
            description: '',
            beacons: []
}
const BeaconForm = (state = initialState, action) => {
      switch(action.type) {
          case 'UPDATE_BEACON_FORM_VALUE':
               return {
                    ...state, [action.newVal.key]: action.newVal.value
               }
          default: return state
      }
}

export default BeaconForm
</code>```

And then have an action

```<code>export function updataFormValue(updatedVal) {
       return { type: 'UPDATE_BEACON_FORM_VALUE', newVal: updatedVal}
}
</code>```

And in the compoennt

```<code>handleInputChange(event) {

    var data = {[event.target.name]: event.target.value}
    this.props.updataFormValue(data);

}
</code>```

Apart from this you need to make your component Redux compatible with connect, mapStateToProps , etc which I assume you already know

And then instead of setting input value from state you will set it from props that youu get from redux store

Body:
this.state = {
            name: '',
            color: '',
            description: '',
            beacons: []
        };

         handleColors = (item) => {
          this.setState({
              color: item.value
          });

      };

    handleBeaconChange = (beacons) => {
          this.setState({
              beacons
          });

      };

    handleInputChange(event) {

        this.setState({
            [event.target.name]: event.target.value
        });

    }

                    NAME*
                      <input type="text"
                       className="form-control margin-select"
                       placeholder="Name"
                       value={this.state.name}
                        name="name"
                        onChange={this.handleInputChange}
                       />

                            COLOR
                        <Select
                          className="margin-select"
                          value={this.state.color}
                          options={colorValues}
                          onChange={this.handleColors}/>

                    DESCRIPTION
                      <textarea
                      className="form-control margin-select"
                      placeholder="Description"
                      value={this.state.description}
                        name="description"
                        onChange={this.handleInputChange}
                      />

{this.props.label}

                            BEACON (s)
                        <Select.Async
                          multi={true}
                          className="margin-select"
                          value={this.state.beacons}
                          loadOptions={getBeacons}
                          onChange={this.handleBeaconChange}/>

                        Add Beacon

This is the image.
Now i just wanted to save previous form data before going to another page
Like for example in this picture i had entered name and color values in the fields and when i click on "Add beacon link", it will route me to another form but the values i entered in this form were lost when i will come back to it.
Any solutions regarding that?

Body:
You can make use of Redux to achieve the same. What you need to do is to save the form states in redux store rather than the component localState itself

You reducer will look something like

const initialState = {
      name: '',
            color: '',
            description: '',
            beacons: []
}
const BeaconForm = (state = initialState, action) => {
      switch(action.type) {
          case 'UPDATE_BEACON_FORM_VALUE':
               return {
                    ...state, [action.newVal.key]: action.newVal.value
               }
          default: return state
      }
}

export default BeaconForm

And then have an action

export function updataFormValue(updatedVal) {
       return { type: 'UPDATE_BEACON_FORM_VALUE', newVal: updatedVal}
}

And in the compoennt

handleInputChange(event) {

    var data = {[event.target.name]: event.target.value}
    this.props.updataFormValue(data);

}

Apart from this you need to make your component Redux compatible with connect, mapStateToProps , etc which I assume you already know

And then instead of setting input value from state you will set it from props that youu get from redux store


问:
What is the proper way to cache a user profile in the MVC5 layout page
I have a UserProfile class which is generated and updated for each new registered user. What is the proper technique for storing/caching that object in the layout page so it can be used every time a new page loads once the user has logged in and is authenticated?

I currently am loading it into a model

```<code>protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (User.Identity.IsAuthenticated)
        {
            var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
            lvm.LoggedInUserProfile =
                MyProject.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);

            var iconSource = string.Empty; //= ConfigurationHelpers.UserIcons.FemaleUserIconSource;//var profile = MyProject.UserService.UserHelpers.GetUserProfileIncluding(User.Identity.GetUserId());

            if (lvm.LoggedInUserProfile != null)
            {
                if (lvm.LoggedInUserProfile.AvatarUrl != null)
                {
                    iconSource = lvm.LoggedInUserProfile.Gender == Gender.Female ? ConfigurationHelpers.UserIcons.FemaleUserIconSource : ConfigurationHelpers.UserIcons.MaleUserIconSource;
                }
                iconSource = lvm.LoggedInUserProfile.AvatarUrl;
            }

            if (lvm.LoggedInUserProfile != null) ViewData.Add("FullName", lvm.LoggedInUserProfile.FirstName);
            ViewData.Add("IconSource", iconSource);
            ViewData.Add("ViewModel", lvm);
        }
        base.OnActionExecuted(filterContext);
    }
</code>```

but this seems to run dozens of times and seems wasteful.

答:
Using Session, as suggested by the two commenters, seems to be the way to go. Now that code is only being hit once.

```<code>protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (User.Identity.IsAuthenticated && Session["LayoutViewModel"] == null)
        {
            var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
            lvm.LoggedInUserProfile =
                MyProject.Services.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);

            if (lvm.LoggedInUserProfile != null)
            {
                Session["LayoutViewModel"] = lvm;
            }
            else
            {
                Session["LayoutViewModel"] = null;
            }

        }
        base.OnActionExecuted(filterContext);
    }
</code>```

And in your layout view, make sure you cast the Session when retrieving it.

```<code>@using MyProject.ViewModels
@{
    var svm = (LayoutViewModel)Session["LayoutViewModel"];
 }
</code>```

Body:
I have a UserProfile class which is generated and updated for each new registered user. What is the proper technique for storing/caching that object in the layout page so it can be used every time a new page loads once the user has logged in and is authenticated?

I currently am loading it into a model

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (User.Identity.IsAuthenticated)
        {
            var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
            lvm.LoggedInUserProfile =
                MyProject.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);

            var iconSource = string.Empty; //= ConfigurationHelpers.UserIcons.FemaleUserIconSource;//var profile = MyProject.UserService.UserHelpers.GetUserProfileIncluding(User.Identity.GetUserId());

            if (lvm.LoggedInUserProfile != null)
            {
                if (lvm.LoggedInUserProfile.AvatarUrl != null)
                {
                    iconSource = lvm.LoggedInUserProfile.Gender == Gender.Female ? ConfigurationHelpers.UserIcons.FemaleUserIconSource : ConfigurationHelpers.UserIcons.MaleUserIconSource;
                }
                iconSource = lvm.LoggedInUserProfile.AvatarUrl;
            }

            if (lvm.LoggedInUserProfile != null) ViewData.Add("FullName", lvm.LoggedInUserProfile.FirstName);
            ViewData.Add("IconSource", iconSource);
            ViewData.Add("ViewModel", lvm);
        }
        base.OnActionExecuted(filterContext);
    }

but this seems to run dozens of times and seems wasteful.

Body:
Using Session, as suggested by the two commenters, seems to be the way to go. Now that code is only being hit once.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (User.Identity.IsAuthenticated && Session["LayoutViewModel"] == null)
        {
            var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
            lvm.LoggedInUserProfile =
                MyProject.Services.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);

            if (lvm.LoggedInUserProfile != null)
            {
                Session["LayoutViewModel"] = lvm;
            }
            else
            {
                Session["LayoutViewModel"] = null;
            }

        }
        base.OnActionExecuted(filterContext);
    }

And in your layout view, make sure you cast the Session when retrieving it.

@using MyProject.ViewModels
@{
    var svm = (LayoutViewModel)Session["LayoutViewModel"];
 }


问:
Updating a list with data from another list
I have two lists and I want to create a 3rd one combining information from both, assigning values to positions derived from the first list wit the actual values calculated from the second list... an example is probably more explanatory:

```<code>list1 = [ 0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0]
list2 = [ 0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0]
</code>```

the new list I want to create should contain the sum value of the second list across the original 1 value intervals:

```<code>list3 = [ 0,0,0,3,3,3,3,3,0,0,0,2,2,2,2,0]
</code>```

any advise?  I'm very new to python.
I'm looking to use some itertool somehow but not getting very far...

THanks in advance for any tips.

答:
Just one way, detecting the groups in list1 and handling each group's corresponding elements in list2.

```<code>list1 = [ 0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0]
list2 = [ 0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0]

from itertools import groupby, islice
it2 = iter(list2)
result = []
for k, g in groupby(list1):
    n = len(list(g))
    result += [k * sum(islice(it2, n))] * n

print(result)
</code>```

Prints:

```<code>[0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 2, 2, 2, 2, 0]
</code>```

Body:
I have two lists and I want to create a 3rd one combining information from both, assigning values to positions derived from the first list wit the actual values calculated from the second list... an example is probably more explanatory:

list1 = [ 0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0]
list2 = [ 0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0]

the new list I want to create should contain the sum value of the second list across the original 1 value intervals:

list3 = [ 0,0,0,3,3,3,3,3,0,0,0,2,2,2,2,0]

any advise?  I'm very new to python.
I'm looking to use some itertool somehow but not getting very far...

THanks in advance for any tips.

Body:
Just one way, detecting the groups in list1 and handling each group's corresponding elements in list2.

list1 = [ 0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0]
list2 = [ 0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0]

from itertools import groupby, islice
it2 = iter(list2)
result = []
for k, g in groupby(list1):
    n = len(list(g))
    result += [k * sum(islice(it2, n))] * n

print(result)

Prints:

[0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 0, 2, 2, 2, 2, 0]


问:
How to change console logging in production with Spring in log4j2?
How can I disable console logging completely in production? (eg using spring.profiles.active=production?

During dev I always want to see the full console logging. But in production I'd like to prevent console out. But how?

log4j2-spring.xml:

```<code><configuration>
   <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
        </Console>

        <RollingRandomAccessFile name="XML"  .../>
    </Appenders>

    <Loggers>
       <Root level="all">
            <AppenderRef ref="CONSOLE" />
            <AppenderRef ref="XML" />
       </Root>
    </Loggers>
</configuration>
</code>```

Sidenote: the INFO statements should still be logged to XML file. They should just not be printed to console additionally.

答:
It's possible using vm args as follows:

```<code><Configuration>
    <Properties>
       <property name="console.log">INFO</property> <!-- default value if not set -->
    </Properties>

        <Console name="CONSOLE" target="SYSTEM_OUT">
            <ThresholdFilter level="${sys:console.log}" onMatch="ACCEPT" onMismatch="DENY" />
        </Console>
</code>```

The logger will use INFO level by default. And when providing eg -Dconsole.log=ERROR on launch, it will only log errors to console.

Would be even nicer if log4j2 could read just a property defined in application-production.properties, but for not the approach works.

Body:
How can I disable console logging completely in production? (eg using spring.profiles.active=production?

During dev I always want to see the full console logging. But in production I'd like to prevent console out. But how?

log4j2-spring.xml:

<configuration>
   <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
        </Console>

        <RollingRandomAccessFile name="XML"  .../>
    </Appenders>

    <Loggers>
       <Root level="all">
            <AppenderRef ref="CONSOLE" />
            <AppenderRef ref="XML" />
       </Root>
    </Loggers>
</configuration>

Sidenote: the INFO statements should still be logged to XML file. They should just not be printed to console additionally.

Body:
It's possible using vm args as follows:

<Configuration>
    <Properties>
       <property name="console.log">INFO</property> <!-- default value if not set -->
    </Properties>

        <Console name="CONSOLE" target="SYSTEM_OUT">
            <ThresholdFilter level="${sys:console.log}" onMatch="ACCEPT" onMismatch="DENY" />
        </Console>

The logger will use INFO level by default. And when providing eg -Dconsole.log=ERROR on launch, it will only log errors to console.

Would be even nicer if log4j2 could read just a property defined in application-production.properties, but for not the approach works.


问:
How can I create a datetime column without 'date' part?
I have a dataframe and there's a column named 'Time' in it like the below(HH:MM:SS:fffff).

```<code>>>> df['Time']
0        09:42:29:75284
1        09:42:29:95584
2        09:42:31:15036
3        09:42:35:15138
4        09:42:35:95491
5        09:42:43:55414
6        09:42:45:35866
7        09:42:46:74638
8        09:42:47:35582
9        09:42:47:74774
10       09:42:48:94582
...
Name: Time, Length: 18924, dtype: object
</code>```

I want to change its type as datetime, in order to make it easier to calculate. Is it possible to change its type, using pandas.to_datetime, as datetime without date?

Body:
I have a dataframe and there's a column named 'Time' in it like the below(HH:MM:SS:fffff).

>>> df['Time']
0        09:42:29:75284
1        09:42:29:95584
2        09:42:31:15036
3        09:42:35:15138
4        09:42:35:95491
5        09:42:43:55414
6        09:42:45:35866
7        09:42:46:74638
8        09:42:47:35582
9        09:42:47:74774
10       09:42:48:94582
...
Name: Time, Length: 18924, dtype: object

I want to change its type as datetime, in order to make it easier to calculate. Is it possible to change its type, using pandas.to_datetime, as datetime without date?

Body:
Please refer python to_datetime documentation.

import pandas as pd
df = pd.DataFrame({'Time': ['09:42:29:75284','09:42:29:95584','09:42:31:15036']})

   df
Out[]:
             Time
0  09:42:29:75284
1  09:42:29:95584
2  09:42:31:15036

You can convert this into datetime format by specifying format as follows:

pd.to_datetime(df['Time'], format='%H:%M:%S:%f')
Out[]:
0   1900-01-01 09:42:29.752840
1   1900-01-01 09:42:29.955840
2   1900-01-01 09:42:31.150360
Name: Time, dtype: datetime64[ns]

but doing this will also add date 1900-01-01.


问:
Given an array of uint8_t what is a good way to extract any subsequence of bits as a uint32_t?
I have run into an interesting problem lately:

Lets say I have an array of bytes (uint8_t to be exact) of length at least one. Now i need a function that will get a subsequence of bits from this array, starting with bit X (zero based index, inclusive) and having length L and will return this as an uint32_t. If L is smaller than 32 the remaining high bits should be zero.

Although this is not very hard to solve, my current thoughts on how to do this seem a bit cumbersome to me. I'm thinking of a table of all the possible masks for a given byte (start with bit 0-7, take 1-8 bits) and then construct the number one byte at a time using this table.

Can somebody come up with a nicer solution? Note that i cannot use Boost or STL for this - and no, it is not a homework, its a problem i run into at work and we do not use Boost or STL in the code where this thing goes. You can assume that: 0 < L <= 32 and that the byte array is large enough to hold the subsequence.

One example of correct input/output:

array: 00110011 1010 1010 11110011 01 101100

subsequence: X = 12 (zero based index), L = 14

resulting uint32_t = 00000000 00000000 00 101011 11001101

答: Take a look at std::bitset and boost::dynamic_bitset.</p>


问:
nyc (istanbul) doesn't work when NODE_ENV is set to test
I'm performing mocha tests on my React components that I wrote using ES6 syntax. I'm using Istanbul to do code coverage tests. When i set my NODE_ENV to 'test`, I get the following output:

```<code>----------|----------|----------|----------|----------|----------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files |  Unknown |  Unknown |  Unknown |  Unknown |                |
----------|----------|----------|----------|----------|----------------|
</code>```

As can be seen, it says unknown for everything. When I remove the NODE_ENV variable, it works fine. What can I do to run this test in the above environment?

答:
I have been trying the last two days to set up a similar environment using babel, nyc and react and faced similar problems.
How are you setting the NODE_ENV? Are you on Windows?

This is what I had in my package.json:

```<code>"test:c": "set NODE_ENV=test && npm run coverage"
</code>```

When this is executed, windows actually sets the NODE_ENV as "test " not as "test".
Notice the trailing whitespace.

I fixed this by removing the space from the script :

```<code>"test:c": "set NODE_ENV=test&& npm run coverage"
</code>```

Body:
I'm performing mocha tests on my React components that I wrote using ES6 syntax. I'm using Istanbul to do code coverage tests. When i set my NODE_ENV to 'test`, I get the following output:

----------|----------|----------|----------|----------|----------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files |  Unknown |  Unknown |  Unknown |  Unknown |                |
----------|----------|----------|----------|----------|----------------|

As can be seen, it says unknown for everything. When I remove the NODE_ENV variable, it works fine. What can I do to run this test in the above environment?

Body:
I have been trying the last two days to set up a similar environment using babel, nyc and react and faced similar problems.
How are you setting the NODE_ENV? Are you on Windows?

This is what I had in my package.json:

"test:c": "set NODE_ENV=test && npm run coverage"

When this is executed, windows actually sets the NODE_ENV as "test " not as "test".
Notice the trailing whitespace.

I fixed this by removing the space from the script :

"test:c": "set NODE_ENV=test&& npm run coverage"


问:
Removing characters after the decimal point for a double
How can I remove the all the characters after the decimal point.

Instead of 7.3456, I would just like 7.

This is what I do to get the number so far with decimal places.

```<code>[NSString stringWithFormat:@" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];
</code>```

Many Thanks,
-Code

答:
You may also use

double newDvalue =floor(dValue);

it will remove all the decimals point

using %.0f  for string format will be good also

Body:
How can I remove the all the characters after the decimal point.

Instead of 7.3456, I would just like 7.

This is what I do to get the number so far with decimal places.

[NSString stringWithFormat:@" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];

Many Thanks,
-Code


问:
Tab-Navigation - Remember user selection
I'm using a TAB navigation for my subpage Products -> ?p=products (see code below, website is realized with HTML and PHP)

The problem:

The user clicks, for example, in the second TAB the link Details. Then he uses the back button. Now he comes back to the Product site, but not in the second tab, rather in the first.

I would like to remember the last used tab (here: href="#section-2"), if the user goes back to the product page.

How can I realize this?

```<code><div id="tabs" class="tabs">
    <nav>
        <ul>
            <li><a href="#section-1" class="icon-cross"><span>Product 1</span></a></li>
            <li><a href="#section-2" class="icon-cross"><span>Product 2</span></a></li>
            <li><a href="#section-3" class="icon-cross"><span>Product 3</span></a></li>
            <li><a href="#section-4" class="icon-cross"><span>Product 4</span></a></li>
        </ul>
    </nav>

    <div class="content">

        <section id="section-1">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 1</strong></h2>
                <hr>
            </div>
            ...
        </section>

        <section id="section-2">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 2</strong></h2>
                <hr>
            </div>

            <a href="?p=details">Details</a>

        </section>
    </div>
</div>
</code>```

答:
Give id for each tab.Then ,</p>

```<code>$(".icon-cross").click(function(){
    var selected_id= $(this).attr('id);
    //save this id to cookie.Then retrieve this cookie value on next page visit
})
</code>```

Body:
I'm using a TAB navigation for my subpage Products -> ?p=products (see code below, website is realized with HTML and PHP)

The problem:

The user clicks, for example, in the second TAB the link Details. Then he uses the back button. Now he comes back to the Product site, but not in the second tab, rather in the first.

I would like to remember the last used tab (here: href="#section-2"), if the user goes back to the product page.

How can I realize this?

Product 1

Product 2

Product 3

Product 4

Product 1

            ...

Product 2

            Details

Body:
Give id for each tab.Then ,

$(".icon-cross").click(function(){
    var selected_id= $(this).attr('id);
    //save this id to cookie.Then retrieve this cookie value on next page visit
})


问:
How to add two List<Class> together in c#?
I have two List<Student> that I want to concat.

Student is just a class that contains a few properties.

I also have another Form that creates the Student and populates a List<Student>

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. Effectively updating the main list.

This is the main bit of code I'm having trouble with, I get an error saying I can't convert some IEnumerable<something> to List<something>

```<code>private void update_students(addStudent s)
        {
            Form activeForm = Form.ActiveForm;
            if(activeForm == this)
            {
                tempList = s.StudentList;
                studentList_HomeForm = tempList.Concat(tempList);
            }
        }
</code>```

This is the main line that gives the error

```<code>tempList.Concat(tempList)
</code>```

How do I fix this error?

答:
You can use the AddRange method -
https://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx</p>

```<code>studentList.AddRange(tempList);
</code>```

Body:
I have two List<Student> that I want to concat.

Student is just a class that contains a few properties.

I also have another Form that creates the Student and populates a List<Student>

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. Effectively updating the main list.

This is the main bit of code I'm having trouble with, I get an error saying I can't convert some IEnumerable<something> to List<something>

private void update_students(addStudent s)
        {
            Form activeForm = Form.ActiveForm;
            if(activeForm == this)
            {
                tempList = s.StudentList;
                studentList_HomeForm = tempList.Concat(tempList);
            }
        }

This is the main line that gives the error

tempList.Concat(tempList)

How do I fix this error?

Body:
You can use the AddRange method -
https://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx

studentList.AddRange(tempList);


问:
Responsive menu not working on WordPress
As I converted my website to WordPress I realised that my responsive menu stopped working properly.
Instead of hiding the menu and revealing the burger button which should toggle the menu, the ul appears visible at all times and seems unaffected by any of the jquery code. Would anyone happen to have any idea as per how to correct that please?
Thank you all in advance for your attention.

HTML:

```<code><nav>
  <a href="#" id="burger_menu"><i class="fa fa-bars"></i></a>
  <?php
    wp_nav_menu(array(
      'theme_location'  => 'primary',
      'container'       => 'div'
    ));
  ?>
</nav>
</code>```

CSS:

```<code>header nav #burger_menu {
  padding-right: 20px;
  font-size: 40px;
  display: none;
  color: #fff;
}

header nav .menu ul {
  display: block;
  line-height: 0;
}

header nav .menu ul li {
  padding: 10px;
  display: inline-block !important;
  float: left;
}

@media screen and (max-width: 1023px) {
  /* NAV */
  header nav #burger_menu {
    display: inline-block;
  }

  header nav ul {
    background: rgba(98,194,210,0.85) !important;
    line-height: 10px !important;
  }

  header nav ul,
  nav:active ul {
    display: none !important;
    position: absolute;
    padding: 20px 40px;
    background: #62c2d2;
    right: 0;
    top: 80px;
    width: 30%;
  }
}
</code>```

jQuery:

```<code>//RESPONSIVE NAV
$('#burger_menu').on('click', function(e) {
  e.preventDefault();
  $('header ul').toggle();
  $('header ul').mouseleave(function() {
    $('header ul').css('display', 'none !important');
  });
});
</code>```

答:
it looks like you are using the wrong media query. Find the Media Query for a smaller screen or are you just using the one?

```<code>@media screen and (max-width: 1023px)
</code>```

Also change px to % where applicable.

If you could post a url or a dev url I could  be more helpful.

Body:
As I converted my website to WordPress I realised that my responsive menu stopped working properly.
Instead of hiding the menu and revealing the burger button which should toggle the menu, the ul appears visible at all times and seems unaffected by any of the jquery code. Would anyone happen to have any idea as per how to correct that please?
Thank you all in advance for your attention.

HTML:

  <?php
    wp_nav_menu(array(
      'theme_location'  => 'primary',
      'container'       => 'div'
    ));
  ?>

CSS:

header nav #burger_menu {
  padding-right: 20px;
  font-size: 40px;
  display: none;
  color: #fff;
}

header nav .menu ul {
  display: block;
  line-height: 0;
}

header nav .menu ul li {
  padding: 10px;
  display: inline-block !important;
  float: left;
}

@media screen and (max-width: 1023px) {
  /* NAV */
  header nav #burger_menu {
    display: inline-block;
  }

  header nav ul {
    background: rgba(98,194,210,0.85) !important;
    line-height: 10px !important;
  }

  header nav ul,
  nav:active ul {
    display: none !important;
    position: absolute;
    padding: 20px 40px;
    background: #62c2d2;
    right: 0;
    top: 80px;
    width: 30%;
  }
}

jQuery:

//RESPONSIVE NAV
$('#burger_menu').on('click', function(e) {
  e.preventDefault();
  $('header ul').toggle();
  $('header ul').mouseleave(function() {
    $('header ul').css('display', 'none !important');
  });
});

Body:
it looks like you are using the wrong media query. Find the Media Query for a smaller screen or are you just using the one?

@media screen and (max-width: 1023px)

Also change px to % where applicable.

If you could post a url or a dev url I could  be more helpful.


问:
Resource interpreted as Document but transferred with MIME type image/png
I have two copies of the following code on two different rented servers:

```<code><?php
$my_img = imagecreatefrompng("img.png");
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $text_color );
?>
</code>```

When I try to run one copy I get the error in the title. When I run the other copy it works fine. What could be causing the issue?

答:
Try using this:

```<code><?php
  header("Content-Type: image/png");
  readfile("img.png");
  exit;
?>
</code>```

There is no need to recreate image if you want just to load & show it from php file.

Body:
I have two copies of the following code on two different rented servers:

<?php
$my_img = imagecreatefrompng("img.png");
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $text_color );
?>

When I try to run one copy I get the error in the title. When I run the other copy it works fine. What could be causing the issue?

Body:
Try using this:

<?php
  header("Content-Type: image/png");
  readfile("img.png");
  exit;
?>

There is no need to recreate image if you want just to load & show it from php file.


问:
Facebook Like Button error
The facebook 'like' button isn't working on my webpage when i upload it to the web. It works perfectly on my computer though. Any guesses as to why this is happening ?

http://savetheearth.99k.org/pledge.htm is the URL

答: The like button shows up for me just fine - I'm not even logged into facebook.</p>

Title: Facebook Like Button error


问:
Plugin loads its scripts but does not apply
I created a WordPress theme from a PSD and tryed to install the 'Monarch Social Sharing Plugin'.

The plugin install fine and load all scripts (js) and CSS files, I see on the Network tab on the developer tools in the browser.

I have put the wp_head() before the  and wp_footer() before the

On the content page I can see the info about the share count that the plugin generate, but without styles.

If I try to load by hand the css files on the header file I see some styles but with broken areas.

I have read all the 'Theme Development' (https://codex.wordpress.org/Theme_Development) but I didn't not found my mistake.

This same plugin works fine on the default wordpress theme and others themes.

Any suggestion?

Link of the page: http://dev.quadradigital.com.br/isd/

答:
You missed to mention below code in you custom theme header.php

```<code><?php wp_head(); ?>
</code>```

In this function only fetch all plugin and theme enqueue scripts in website.

Body:
You missed to mention below code in you custom theme header.php

<?php wp_head(); ?>

In this function only fetch all plugin and theme enqueue scripts in website.


问:
How do I grant other users permission to write to SQLite database?
I faced a strange error related to permissions for a SQLite database.

I type in bash

```<code>rm -f test.db
sqlite3 test.db 'CREATE TABLE t (qwe, qqq)'
chmod 666 test.db
sudo -u another-user sqlite3 test.db 'INSERT INTO t VALUES (4, 2)'
</code>```

It prints

Error: unable to open database file

It prints the same if I change an owner of test.db file to another-user.
But if I try to insert the record on behalf of root or me, there is no any
error, and it's inserted successfully.

What's the troubles?

An output of getfacl test.db is the following

```<code># file: test.db
# owner: mymedia
# group: mymedia
user::rw-
group::rw-
other::rw-
</code>```

AppArmor has no profiles related to SQLite, SeLinux is disabled. I was
experimenting on Ubuntu 16.04. The version of SQLite is 3.11.0.

答: Here the problem seems to be not with file permissions, but with directory. Check if a directory where your database file is placed has proper permissions for another-user.

Body:
I faced a strange error related to permissions for a SQLite database.

I type in bash

rm -f test.db
sqlite3 test.db 'CREATE TABLE t (qwe, qqq)'
chmod 666 test.db
sudo -u another-user sqlite3 test.db 'INSERT INTO t VALUES (4, 2)'

It prints

Error: unable to open database file

It prints the same if I change an owner of test.db file to another-user.
But if I try to insert the record on behalf of root or me, there is no any
error, and it's inserted successfully.

What's the troubles?

An output of getfacl test.db is the following

# file: test.db
# owner: mymedia
# group: mymedia
user::rw-
group::rw-
other::rw-

AppArmor has no profiles related to SQLite, SeLinux is disabled. I was
experimenting on Ubuntu 16.04. The version of SQLite is 3.11.0.


问:
Multiple blank lines are not squeezed in one blank line(C) using I/O redirection
I am asked to squeezed two or more consecutive blank lines in the input as one blank line in the output. So I  have to use Cygwin to do I/O or test it.
Example: ./Lab < test1.txt > test2.txt

my code is:

```<code>   int main(void){

    format();
    printf("\n");
    return 0;
}

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;
    int spaceCheck = ' ';

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){/*changed from isspace(c) to c==' ' because isspace is true for spaces/tabs/newlines*/
           /* while (isspace(c = getchar())); it counts while there is space we will put one space only */
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }

        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(nlines >0){
                continue;
            }
            else{
                putchar(c);
                nlines++;
                nspace = 0;
            }

        }

        else{
            putchar(c);
            nspace = 0;
            nlines = 0;

        }

    }

}
</code>```

However my test2.txt doesn't have the result I want. Is there something wrong in my logic/code?

答:
To dissect this:

```<code>if(c == '\n') {
        nlines++;
</code>```

is nlines ever reset to zero?

```<code>        if(nlines > 1){
            c = '\n';
</code>```

And what happens on the third \n in sequence? will nlines > 1 be true? Think about it!

```<code>        }
}
putchar(c);
</code>```

I don't get this: You unconditionally output your character anyways, defeating the whole purpose of checking whether it's a newline.

A correct solution would set a flag when c is a newline and not output anything. Then, when c is NOT a newline (else branch), output ONE newline if your flag is set and reset the flag. I leave the code writing to you now :)

Body:
I am asked to squeezed two or more consecutive blank lines in the input as one blank line in the output. So I  have to use Cygwin to do I/O or test it.
Example: ./Lab < test1.txt > test2.txt

my code is:

   int main(void){

    format();
    printf("\n");
    return 0;
}

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;
    int spaceCheck = ' ';

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){/*changed from isspace(c) to c==' ' because isspace is true for spaces/tabs/newlines*/
           /* while (isspace(c = getchar())); it counts while there is space we will put one space only */
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }

        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(nlines >0){
                continue;
            }
            else{
                putchar(c);
                nlines++;
                nspace = 0;
            }

        }

        else{
            putchar(c);
            nspace = 0;
            nlines = 0;

        }

    }

}

However my test2.txt doesn't have the result I want. Is there something wrong in my logic/code?

Body:
To dissect this:

if(c == '\n') {
        nlines++;

is nlines ever reset to zero?

        if(nlines > 1){
            c = '\n';

And what happens on the third \n in sequence? will nlines > 1 be true? Think about it!

        }
}
putchar(c);

I don't get this: You unconditionally output your character anyways, defeating the whole purpose of checking whether it's a newline.

A correct solution would set a flag when c is a newline and not output anything. Then, when c is NOT a newline (else branch), output ONE newline if your flag is set and reset the flag. I leave the code writing to you now :)


问:
BEM Methodology proper HTML structure
I have a doubts about this HTML structure. Is it correct according to BEM approach?

```<code><div class="boxWithBorder">
  <div class="header">
    <h2 class="boxWithBorder__element"></h2>
  </div>
</div>
</code>```

To my mind it should look like that

```<code><div class="boxWithBorder">
  <div class="header">
    <h2 class="header__element"></h2>
  </div>
</div>
</code>```

What keeps elements encapsulated.

答:
Generally we do components and structures, that means structures are compositions of components. It will require nesting so that part is ok. As far as your first approach that is not ok by our standards and not used. block1 should not live inside block2 but block2 has to live inside block1 as it's a nested component. Makes sense? BTW BEM is perfectly fine to use and a lot of frontend devs do it, heavyweights as well, check out csswizardry.com for instance, he got some great articles about BEM

Also I would suggest the following using BEM (or any html/css for that matter) is that skip the camleCase and use "-" instead

```<code><div class="box-with-border">
  <div class="header">
    <h2 class="header__element"></h2>
  </div>
</div>

<div class="hero hero--red-with-border">
  <h1 class="hero__title>Title...</h1>
  <p class="hero__body-text">Text...</p>
</div>
</code>```

Title: BEM Methodology proper HTML structure

Body:
I have a doubts about this HTML structure. Is it correct according to BEM approach?

To my mind it should look like that

What keeps elements encapsulated.

Body:
Generally we do components and structures, that means structures are compositions of components. It will require nesting so that part is ok. As far as your first approach that is not ok by our standards and not used. block1 should not live inside block2 but block2 has to live inside block1 as it's a nested component. Makes sense? BTW BEM is perfectly fine to use and a lot of frontend devs do it, heavyweights as well, check out csswizardry.com for instance, he got some great articles about BEM

Also I would suggest the following using BEM (or any html/css for that matter) is that skip the camleCase and use "-" instead

<div class="box-with-border">
  <div class="header">
    <h2 class="header__element"></h2>
  </div>
</div>

<div class="hero hero--red-with-border">
  <h1 class="hero__title>Title...</h1>
  <p class="hero__body-text">Text...</p>
</div>


问:
Does OpenVswitch support BFD?
How to use BFD in OpenVswitch ?
any practical steps to test BFD in OpenVswitch will be appreciated .

cordially!

答:
The workflow should be something like this:

Assume you have:

machine0 with eth1 having IP 192.168.1.1, and

machine1 with eth1 having IP 192.168.1.2

On machine0
- Create a bridge:

```<code>ovs-vsctl add-br br0
</code>```

Add a port to this bridge (in this case, I am adding a GRE tunnel as
a port with a remote end point of 192.168.1.2)

ovs-vsctl add-port br0 gre0 -- set interface gre0 type=gre options:remote_ip:192.168.1.2

Enable bfd on that tunnel

ovs-vsctl set interface gre0 bfd:enable=true

Now repeat the same on machine1. You will have bfd traffic going between them.

Title: Does OpenVswitch support BFD?

Body:
The workflow should be something like this:

Assume you have:

machine0 with eth1 having IP 192.168.1.1, and

machine1 with eth1 having IP 192.168.1.2

On machine0
- Create a bridge:

ovs-vsctl add-br br0

Add a port to this bridge (in this case, I am adding a GRE tunnel as
a port with a remote end point of 192.168.1.2)

ovs-vsctl add-port br0 gre0 -- set interface gre0 type=gre options:remote_ip:192.168.1.2

Enable bfd on that tunnel

ovs-vsctl set interface gre0 bfd:enable=true

Now repeat the same on machine1. You will have bfd traffic going between them.


问:
Why have leading ffffff for single byte
I am reading data some are 1 byte, some are are 2 byte, some are 3 byte etc. For single byte

```<code>byte qtySat = r.readByte();
</code>```

for 2 bytes I read as

```<code>int serialNumber = r.readUnsignedShort();
</code>```

The reading is all fine and working well. The problem when I convert to show in hex format I get funny scenarios. For example for

```<code>Integer.toHexString(qtySat )
</code>```

I get the output as ffffffce but I just want ce ?

Then for Integer.toHexString(serialNumber)
I get output as say A1 but I want the leading 00 A1 cause this 2 byte of data. What changes to Integer.toHexString should I do?

答:
if the byte (8 bits) qtySat variable is negative, then leading ones will be added when is promoted to an integer, wich is  what Integer.toHexString(int)  requires as parameter

to get rid off those you will need to ensure a non negative argument

```<code>System.out.println(Integer.toHexString(Math.abs(serialNumber)));
</code>```

Title: Why have leading ffffff for single byte

Body:
I am reading data some are 1 byte, some are are 2 byte, some are 3 byte etc. For single byte

byte qtySat = r.readByte();

for 2 bytes I read as

int serialNumber = r.readUnsignedShort();

The reading is all fine and working well. The problem when I convert to show in hex format I get funny scenarios. For example for

Integer.toHexString(qtySat )

I get the output as ffffffce but I just want ce ?

Then for Integer.toHexString(serialNumber)
I get output as say A1 but I want the leading 00 A1 cause this 2 byte of data. What changes to Integer.toHexString should I do?

Body:
if the byte (8 bits) qtySat variable is negative, then leading ones will be added when is promoted to an integer, wich is  what Integer.toHexString(int)  requires as parameter

to get rid off those you will need to ensure a non negative argument

System.out.println(Integer.toHexString(Math.abs(serialNumber)));


问:
Use a Query to access column description in SQL
I am trying to access the Column description properties using the INFORMATION_SCHEMA

I have created this Query in the past to get the column name but i can not figure out how to get description of the column

```<code>SELECT COLUMN_NAME AS Output, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE  (TABLE_NAME = @Tablename) AND (ORDINAL_POSITION = @Location)
</code>```

This is where the Description is on the field properties

答:
If you specifically want to use INFORMATION_SCHEMA (as I was) then the following query should help you obtain the column's description field:</p>

```<code>SELECT COLUMN_NAME AS [Output]
    ,ORDINAL_POSITION
    ,prop.value AS [COLUMN_DESCRIPTION]
FROM INFORMATION_SCHEMA.TABLES AS tbl
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS col ON col.TABLE_NAME = tbl.TABLE_NAME
INNER JOIN sys.columns AS sc ON sc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
    AND sc.NAME = col.COLUMN_NAME
LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id
    AND prop.minor_id = sc.column_id
    AND prop.NAME = 'MS_Description'
WHERE tbl.TABLE_NAME = @TableName
</code>```

Body:
I am trying to access the Column description properties using the INFORMATION_SCHEMA

I have created this Query in the past to get the column name but i can not figure out how to get description of the column

SELECT COLUMN_NAME AS Output, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE  (TABLE_NAME = @Tablename) AND (ORDINAL_POSITION = @Location)

This is where the Description is on the field properties

Body:
If you specifically want to use INFORMATION_SCHEMA (as I was) then the following query should help you obtain the column's description field:

SELECT COLUMN_NAME AS [Output]
    ,ORDINAL_POSITION
    ,prop.value AS [COLUMN_DESCRIPTION]
FROM INFORMATION_SCHEMA.TABLES AS tbl
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS col ON col.TABLE_NAME = tbl.TABLE_NAME
INNER JOIN sys.columns AS sc ON sc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
    AND sc.NAME = col.COLUMN_NAME
LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id
    AND prop.minor_id = sc.column_id
    AND prop.NAME = 'MS_Description'
WHERE tbl.TABLE_NAME = @TableName


问:
String constructing issue in coverity
I am working with a coverity issue . In my code ,

```<code>    props =
    StandardUtils.getProperties(="/Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties, inst_Id);

This vulnerability is found by my coverity server and showing the message

"CID 127299 (#1 of 1): Filesystem path, filename, or URI manipulation
</code>```

(PATH_MANIPULATION)
   4. sink: Constructing a path or URI using the tainted value
   /Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties, inst_Id. This may allow an attacker to access,
   modify, or test the existence of critical or sensitive files "

Then i assign this String to a String variable again did my coverity scan but
  showing the same error message " "

```<code>    String loc="/Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties";
    props = StandardUtils.getProperties(loc, inst_id);
</code>```

But issue is still exists .

coverity suggest that "Path manipulation vulnerabilities can be addressed by
   proper input validation. Blacklisting characters that allow unsafe path
   traversal can improve the safety of the input, but the recommended approach
   is to whitelist the set of expected characters. This should exclude absolute
   paths and upward directory traversal."

These type of issues are reported multiple places in my code .

How can we resolve these type of issues ? Can any one help me on this ?

答:
You should read up on path traversal, but basically, your code is still vulnerable to an attack, while it may not be a path traversal attack specifically this may be subject to an indirect object reference attack.

What if cust_id looked like this:

```<code>String cust_id = request.getParameter("cust_id");
</code>```

and i provided a url

```<code>http://your_server.com:8080/?cust_id=123
</code>```

then this:

```<code>String loc = "/Dir/tomcat/properties/lib/standardlib_" +
        cust_id + ".properties";
</code>```

would expand too:

```<code>String loc = "/Dir/tomcat/properties/lib/standardlib_123.properties";
</code>```

So assuming there are different log files for different customers, it may be possible to view the file for someone else.

To fix this, you either need to validate cust_id, or check access for it somehow.

You can then safely mark it as a false-positive once you have fixed the issue.

Title: String constructing issue in coverity

Body:
I am working with a coverity issue . In my code ,

    props =
    StandardUtils.getProperties(="/Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties, inst_Id);

This vulnerability is found by my coverity server and showing the message

"CID 127299 (#1 of 1): Filesystem path, filename, or URI manipulation

(PATH_MANIPULATION)
   4. sink: Constructing a path or URI using the tainted value
   /Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties, inst_Id. This may allow an attacker to access,
   modify, or test the existence of critical or sensitive files "

Then i assign this String to a String variable again did my coverity scan but
  showing the same error message " "

    String loc="/Dir/tomcat/properties/lib/standardlib_" +
    cust_id + ".properties";
    props = StandardUtils.getProperties(loc, inst_id);

But issue is still exists .

coverity suggest that "Path manipulation vulnerabilities can be addressed by
   proper input validation. Blacklisting characters that allow unsafe path
   traversal can improve the safety of the input, but the recommended approach
   is to whitelist the set of expected characters. This should exclude absolute
   paths and upward directory traversal."

These type of issues are reported multiple places in my code .

How can we resolve these type of issues ? Can any one help me on this ?

Body:
You should read up on path traversal, but basically, your code is still vulnerable to an attack, while it may not be a path traversal attack specifically this may be subject to an indirect object reference attack.

What if cust_id looked like this:

String cust_id = request.getParameter("cust_id");

and i provided a url

http://your_server.com:8080/?cust_id=123

then this:

String loc = "/Dir/tomcat/properties/lib/standardlib_" +
        cust_id + ".properties";

would expand too:

String loc = "/Dir/tomcat/properties/lib/standardlib_123.properties";

So assuming there are different log files for different customers, it may be possible to view the file for someone else.

To fix this, you either need to validate cust_id, or check access for it somehow.

You can then safely mark it as a false-positive once you have fixed the issue.


问:
One SQL query to create multiple tables with same sheet
I'm trying to create multiple tables with same sheet in a single query like this

```<code> $query ="CREATE TABLE users1, users2, users3 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    )";
</code>```

then tried to execute it using PDO

```<code>$stmt->execute();
</code>```

but didn't work, Then tried separating them

```<code>$query = "CREATE TABLE users1 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
CREATE TABLE users2 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
CREATE TABLE users3 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
";
</code>```

once with and without the ;
but still give an error

答:
Try below code: </p>

```<code>$sql = "
CREATE TABLE users1 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
CREATE TABLE users2 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
CREATE TABLE users3 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
";

try {
    $stmt = $db->prepare($sql);
    $stmt->execute();
}
catch (PDOException $e)
{
    echo $e->getMessage();
    die();
}
</code>```

<p>You can read something interesting about pdo multi query :PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND) </p>

Body:
I'm trying to create multiple tables with same sheet in a single query like this

 $query ="CREATE TABLE users1, users2, users3 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    )";

then tried to execute it using PDO

$stmt->execute();

but didn't work, Then tried separating them

$query = "CREATE TABLE users1 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
CREATE TABLE users2 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
CREATE TABLE users3 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(24) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
    );
";

once with and without the ;
but still give an error

Body:
Try below code:

$sql = "
CREATE TABLE users1 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
CREATE TABLE users2 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
CREATE TABLE users3 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(24) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
";

try {
    $stmt = $db->prepare($sql);
    $stmt->execute();
}
catch (PDOException $e)
{
    echo $e->getMessage();
    die();
}

You can read something interesting about pdo multi query :PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)


问:
change gridview colour when checkbox selected
I have a gridview with some data bound to it. I also have different background for alternating rows, so the table is more readable... How do I change the color of the row background when checkbox in the first column is checked and change it back to original when it is unchecked. The problem I'm having is, how to know if original background (after unchecking the checkbox) is for normal row or for alternating row?

I know how to change row attributes like this:

```<code>protected void gvUser_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#D9ECFB'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
    }
}
</code>```

But, what if there are more checkboxes selected, how do I know which is the original background?

答:
```<code>This worked for me.

private void setrowcolor()
   {
       bool checkSelected = false;
       foreach (DataGridViewRow row in gridgencsv.Rows)
       {
          checkSelected =Convert.ToBoolean(row.Cells["select_check"].Value);
            if (checkSelected == true)
              {
                    row.DefaultCellStyle.BackColor = System.Drawing.Color.CadetBlue;
              }
            else
              {
                    row.DefaultCellStyle.BackColor = System.Drawing.Color.White;
              }

        }
   }
</code>```

Body:
I have a gridview with some data bound to it. I also have different background for alternating rows, so the table is more readable... How do I change the color of the row background when checkbox in the first column is checked and change it back to original when it is unchecked. The problem I'm having is, how to know if original background (after unchecking the checkbox) is for normal row or for alternating row?

I know how to change row attributes like this:

protected void gvUser_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#D9ECFB'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
    }
}

But, what if there are more checkboxes selected, how do I know which is the original background?


答:
You provide too little code, the interesting part would be the loop around the code you posted...

What you actually have to do there is skipping the output:

```<code>FILE* file = ...;
char c, prev = 0;
while((c = fgets(file)) != EOF)
{
    if(c != '\n' || prev != '\n')
        putchar(c);
    prev = c;
}
</code>```

If we have an empty line following another one, then we encounter two subsequent newline characters, so both c and prev are equal to '\n', which is the situation we do not want to output c (the subsequent newline) – and the inverse situation is any one of both being unequal to '\n', as you see above – and only then you want to output your character...

Side note: prev = 0 – well, I need to initalise it to anything different than a newline, could as well have been 's' – unless, of course, you want to skip an initial empty line, too, then you would have to initialise it with '\n'...

Edit, referring to your modified code: Edit2 (removed references to code as it changed again)

As your modified code shows that you do not only want to condense blank lines, but whitespace, too, you first have to consider that you have two classes of white space, on one hand, the newlines, on the other, any others. So you have to differentiate appropriately.

I recommend now using some kind of state machine:

```<code>#define OTH  0
#define WS   1
#define NL1  2
#define NL2  3

int state = OTH;

while (( c= getchar()) != EOF )
{
    // first, the new lines:
    if(c == '\n')
    {
        if(state != NL2)
        {
            putchar('\n');
            state = state == NL1 ? NL2 : NL1;
        }
    }
    // then, any other whitespace
    else if(isspace(c))
    {
        if(state != WS)
        {
            putchar(' ');
            state = WS;
        }
    }
    // finally, all remaining characters
    else
    {
        putchar(c);
        state = OTH;
    }
}
</code>```

First differentiation occurs to the current character's own class (newline, whitespace or other), second differentiation according to the previous character's class, which defines the current state. Output occurs always for any non-whitespace character or if the two subsequent whitespace characters only, if they are of different class (newline is a little specific, I need two states for, as we want to leave one blank line, which means we need two subsequent newline characters...).

Be aware: whitespace only lines do not apply as blank lines in above algorithm, so they won't be eliminated (but reduced to a line containing one single space). From the code you posted, I assume this is intended...

For completeness: This is a variant removing leading and trailing whitespace entirely and counting whitespace-only lines as empty lines:

```<code>if(c == '\n')
{
    if(state != NL2)
    {
        putchar('\n');
        state = state == NL1 ? NL2 : NL1;
    }
}
else if(isspace(c))
{
    if(state == OTH)
        state = WS;
}
else
{
    if(state == WS)
    {
        putchar('');
    }
    putchar(c);
    state = OTH;
}
</code>```

Secret: Only enter the whitespace state, if there was a non-ws character before, but print the space character not before you encounter the next non-whitespace.

Coming to the newlines - well, if there was a normal character, we are either in state OTH or WS, but none of the two NL states. If there was only whitespace on the line, the state is not modified, thus we remain in the corresponding NL state (1 or 2) and skip the line correspondingly...

Title: Multiple blank lines are not squeezed in one blank line(C) using I/O redirection

Body:
You provide too little code, the interesting part would be the loop around the code you posted...

What you actually have to do there is skipping the output:

FILE* file = ...;
char c, prev = 0;
while((c = fgets(file)) != EOF)
{
    if(c != '\n' || prev != '\n')
        putchar(c);
    prev = c;
}

If we have an empty line following another one, then we encounter two subsequent newline characters, so both c and prev are equal to '\n', which is the situation we do not want to output c (the subsequent newline) – and the inverse situation is any one of both being unequal to '\n', as you see above – and only then you want to output your character...

Side note: prev = 0 – well, I need to initalise it to anything different than a newline, could as well have been 's' – unless, of course, you want to skip an initial empty line, too, then you would have to initialise it with '\n'...

Edit, referring to your modified code: Edit2 (removed references to code as it changed again)

As your modified code shows that you do not only want to condense blank lines, but whitespace, too, you first have to consider that you have two classes of white space, on one hand, the newlines, on the other, any others. So you have to differentiate appropriately.

I recommend now using some kind of state machine:

#define OTH  0
#define WS   1
#define NL1  2
#define NL2  3

int state = OTH;

while (( c= getchar()) != EOF )
{
    // first, the new lines:
    if(c == '\n')
    {
        if(state != NL2)
        {
            putchar('\n');
            state = state == NL1 ? NL2 : NL1;
        }
    }
    // then, any other whitespace
    else if(isspace(c))
    {
        if(state != WS)
        {
            putchar(' ');
            state = WS;
        }
    }
    // finally, all remaining characters
    else
    {
        putchar(c);
        state = OTH;
    }
}

First differentiation occurs to the current character's own class (newline, whitespace or other), second differentiation according to the previous character's class, which defines the current state. Output occurs always for any non-whitespace character or if the two subsequent whitespace characters only, if they are of different class (newline is a little specific, I need two states for, as we want to leave one blank line, which means we need two subsequent newline characters...).

Be aware: whitespace only lines do not apply as blank lines in above algorithm, so they won't be eliminated (but reduced to a line containing one single space). From the code you posted, I assume this is intended...

For completeness: This is a variant removing leading and trailing whitespace entirely and counting whitespace-only lines as empty lines:

if(c == '\n')
{
    if(state != NL2)
    {
        putchar('\n');
        state = state == NL1 ? NL2 : NL1;
    }
}
else if(isspace(c))
{
    if(state == OTH)
        state = WS;
}
else
{
    if(state == WS)
    {
        putchar('');
    }
    putchar(c);
    state = OTH;
}

Secret: Only enter the whitespace state, if there was a non-ws character before, but print the space character not before you encounter the next non-whitespace.

Coming to the newlines - well, if there was a normal character, we are either in state OTH or WS, but none of the two NL states. If there was only whitespace on the line, the state is not modified, thus we remain in the corresponding NL state (1 or 2) and skip the line correspondingly...


答:
Integer.toHexString(qtySat ) gives you a binary representation of the int value passed to it. If you are passing a negative byte, it will become a negative int of the same value, which explains all the 1 bits you are seeing.

You can use Integer.toHexString(qtySat & 0xff) to set all the bits other than the low 8 bits to 0 before converting to hex String.

```<code>byte qtySat = (byte)0xce;
System.out.println (qtySat);
System.out.println (Integer.toHexString(qtySat & 0xff));
</code>```

prints

```<code>-50
ce
</code>```

Title: Why have leading ffffff for single byte

Body:
Integer.toHexString(qtySat ) gives you a binary representation of the int value passed to it. If you are passing a negative byte, it will become a negative int of the same value, which explains all the 1 bits you are seeing.

You can use Integer.toHexString(qtySat & 0xff) to set all the bits other than the low 8 bits to 0 before converting to hex String.

byte qtySat = (byte)0xce;
System.out.println (qtySat);
System.out.println (Integer.toHexString(qtySat & 0xff));

prints

-50
ce


问:
xml class cannot be found
I am trying to work with fluidxml to test if I can use it, but I cant get it to start working, I am using codeigniter framework. I cloned the repo https://github.com/servo-php/fluidxml and added it to a folder I created called thirdparty. Then here is the code for the function

```<code>public function xmltrial(){
        $this->load->helper('file');
        require_once(APPPATH.'third_party/fluidxml/source/FluidXml.php');

        $book = new FluidXml();
        $book->add([ 'title'  => 'The Theory Of Everything',
             'author' => 'S. Hawking',
             'chapters' => [
                    [ 'chapter' => [
                            '@id' => '1',
                            '@'   => 'Ideas About The Universe' ] ],
                    [ 'chapter' => [
                            '@id' => '2',
                            '@'   => 'The Expanding Universe' ] ],
           ]]);

        echo $book;
    }
</code>```

So I am getting two errors , one is Fatal error: Class 'FluidXml' not found even and the second one is if I use use function \FluidXml\fluidxml;
use function \FluidXml\fluidns;
use function \FluidXml\fluidify; all this character inside my xmltrial function it shows a red error on them.

答:
You should use composer to manage your dependencies. Get composer installed, then install FluidXml into the vendor folder by typing

composer require servo/fluidxml

in the command line. Then you can

require_once 'vendor/autoload.php'

in your index.php, and you can forget about having to require in the files! You just need to put the relevant use statement under your namespace declaration.In your case,

use FluidXml\FluidXml;

Now you can start calling your class!

See Packagist for composer package details https://packagist.org/packages/servo/fluidxml

See Composer site to get composer into CodeIgniter if you don't already https://getcomposer.org/

Title: xml class cannot be found

Body:
I am trying to work with fluidxml to test if I can use it, but I cant get it to start working, I am using codeigniter framework. I cloned the repo https://github.com/servo-php/fluidxml and added it to a folder I created called thirdparty. Then here is the code for the function

public function xmltrial(){
        $this->load->helper('file');
        require_once(APPPATH.'third_party/fluidxml/source/FluidXml.php');

        $book = new FluidXml();
        $book->add([ 'title'  => 'The Theory Of Everything',
             'author' => 'S. Hawking',
             'chapters' => [
                    [ 'chapter' => [
                            '@id' => '1',
                            '@'   => 'Ideas About The Universe' ] ],
                    [ 'chapter' => [
                            '@id' => '2',
                            '@'   => 'The Expanding Universe' ] ],
           ]]);

        echo $book;
    }

So I am getting two errors , one is Fatal error: Class 'FluidXml' not found even and the second one is if I use use function \FluidXml\fluidxml;
use function \FluidXml\fluidns;
use function \FluidXml\fluidify; all this character inside my xmltrial function it shows a red error on them.


问:
which data structure should I use in java to store duplicate values?
Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?

thanks
EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can store the duplicate values.

答: You should use List<E> but you should implement a int[] getDuplicateValuesIndexes(String value) method and a int getCount(String value). These will be useful because in List<E> implementations, there are nothing to treat duplicate values as they store just values of any kind.