问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Don't worry so much. Lots of developers, will rarely need to write an interface. You'll frequently use interfaces available within the .NET framework, but if you don't feel the need to write one anytime soon there's nothing surprising about that.

The example I always give to someone is if you have a Sailboat class and a Viper class. They inherit the Boat class and the Car class respectively. Now say that you need to loop through all these objects and call their Drive() method. While you could write some code like the following:

```<code>if(myObject is Boat)
    ((Boat)myObject).Drive()
else
    if (myObject is Car)
        ((Car)myObject).Drive()
</code>```

It would be much much simpler to write:

```<code>((IDrivable)myObject).Drive()
</code>```

LastEditorDisplayName: ALassek

Body:
Don't worry so much. Lots of developers, will rarely need to write an interface. You'll frequently use interfaces available within the .NET framework, but if you don't feel the need to write one anytime soon there's nothing surprising about that.

The example I always give to someone is if you have a Sailboat class and a Viper class. They inherit the Boat class and the Car class respectively. Now say that you need to loop through all these objects and call their Drive() method. While you could write some code like the following:

if(myObject is Boat)
    ((Boat)myObject).Drive()
else
    if (myObject is Car)
        ((Car)myObject).Drive()

It would be much much simpler to write:

((IDrivable)myObject).Drive()

OwnerDisplayName: Spencer Ruport


来源: stackexchange

问:
CSS placing an absolute div beside another div (pure CSS popover)
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

```<code><div>
    <div><figure class="figure"><img ... /></figure></div>
    //css-popover
    <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>
</code>```

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

答:
Change dimensions as per your need

.popover-container{
  position: relative;
}
.css-popover{
  position: absolute;
}
.css-popover {
 background: #88b7d5;
 border: 4px solid #c2e1f5;
}
.css-popover:after, .css-popover:before {
 right: 100%;
 top: 50%;
 border: solid transparent;
 content: " ";
 height: 0;
 width: 0;
 position: absolute;
 pointer-events: none;
}

.css-popover:after {
 border-color: rgba(136, 183, 213, 0);
 border-right-color: #88b7d5;
 border-width: 30px;
 margin-top: -30px;
}
.css-popover:before {
 border-color: rgba(194, 225, 245, 0);
 border-right-color: #c2e1f5;
 border-width: 36px;
 margin-top: -36px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <div class = "popover-container" ><figure class="figure"><img ... /></figure><div class="css-popover">User detail: ... bla bla bla ...</div></div>

</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

    //css-popover

User detail: ... bla bla bla ...

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

Body:
Change dimensions as per your need

.popover-container{
  position: relative;
}
.css-popover{
  position: absolute;
}
.css-popover {
 background: #88b7d5;
 border: 4px solid #c2e1f5;
}
.css-popover:after, .css-popover:before {
 right: 100%;
 top: 50%;
 border: solid transparent;
 content: " ";
 height: 0;
 width: 0;
 position: absolute;
 pointer-events: none;
}

.css-popover:after {
 border-color: rgba(136, 183, 213, 0);
 border-right-color: #88b7d5;
 border-width: 30px;
 margin-top: -30px;
}
.css-popover:before {
 border-color: rgba(194, 225, 245, 0);
 border-right-color: #c2e1f5;
 border-width: 36px;
 margin-top: -36px;
}

<div>
    <div class = "popover-container" ><figure class="figure"><img ... /></figure><div class="css-popover">User detail: ... bla bla bla ...</div></div>

</div>


问:
Mockito: When is not working if predefined Search Criteria is passed to dao and service having dao is called
service.searchRaashanRegister contains another method adresseDao.findRaashan(crit) for which should return particular result for parameter setUnit "BUBBA"

```<code>  SearchResult<Raashan> searchResult = new SearchResult<Raashan>();
  searchResult.setSize(1);
  searchResult.setResult(Arrays.asList(raashan));

  SearchCriteria crit = new SearchCriteria ();
  crit.setUnit(new HashSet<String>(Arrays.asList("BUBBA")));
  crit.setPage(0);
  crit.setPageSize(15);
  crit.setSort(null);
  crit.setQuery("");
  crit.setSortAsc(Boolean.TRUE);

  when(raashanDao.findRaashan(crit)).thenReturn(searchResult);

  //This request is sent to web service from which above criteria is created.
  RaashanSearchRequest searchRequest = new RaashanSearchRequest ();
  searchRequest .setPage(0);
  searchRequest .setPageSize(15);
  searchRequest .setUnit("BUBBA");
  searchRequest .setQuery("");
  searchRequest .setSort(null);
  searchRequest .setSortASC(Boolean.TRUE);

  RaashanResponse response = service.searchRaashanRegister(searchRequest );
</code>```

The above code is not giving desired results and adresseDao.findRaashan(crit) is returning Null. When I use any(SearchCriteria.class) then test pass okay but we want results on particular critera.

I also added initMocks in @Before:

```<code>@Before
public void init() {
  MockitoAnnotations.initMocks(this);
</code>```

Unable to get what is reason where error occurs.

答:
As far as I understand your code, I think you need to use eq matcher -org.mockito.Matchers.eq if planning to set expectations on specific instances.

I am assuming raashanDao is a mocked instance , so it would be like ,

when(raashanDao.findRaashan(eq(crit))).thenReturn(searchResult);

UPDATE : For previous discussion, I think, I misunderstood your question. eq(crit) should work as is in when as well as in verify without setting anything since that is a method parameter.

A sample is shown here

You use any for parameter values that you don't care and use eq for specific values.

Body:
service.searchRaashanRegister contains another method adresseDao.findRaashan(crit) for which should return particular result for parameter setUnit "BUBBA"

  SearchResult<Raashan> searchResult = new SearchResult<Raashan>();
  searchResult.setSize(1);
  searchResult.setResult(Arrays.asList(raashan));

  SearchCriteria crit = new SearchCriteria ();
  crit.setUnit(new HashSet<String>(Arrays.asList("BUBBA")));
  crit.setPage(0);
  crit.setPageSize(15);
  crit.setSort(null);
  crit.setQuery("");
  crit.setSortAsc(Boolean.TRUE);

  when(raashanDao.findRaashan(crit)).thenReturn(searchResult);

  //This request is sent to web service from which above criteria is created.
  RaashanSearchRequest searchRequest = new RaashanSearchRequest ();
  searchRequest .setPage(0);
  searchRequest .setPageSize(15);
  searchRequest .setUnit("BUBBA");
  searchRequest .setQuery("");
  searchRequest .setSort(null);
  searchRequest .setSortASC(Boolean.TRUE);

  RaashanResponse response = service.searchRaashanRegister(searchRequest );

The above code is not giving desired results and adresseDao.findRaashan(crit) is returning Null. When I use any(SearchCriteria.class) then test pass okay but we want results on particular critera.

I also added initMocks in @Before:

@Before
public void init() {
  MockitoAnnotations.initMocks(this);

Unable to get what is reason where error occurs.


问:
Generics and Inheritance corner case
I have following code and it is not behaving as i am thinking. I have put the comments inline , that what is happening and what is expected.

```<code>class C<T> {
    void m(T arg) {
    }
}

interface I {
    void m(Class arg);
}

class D extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: error -- abstract method not overridden

abstract class E extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: no error, but no bridge method
</code>```

Can some one please help me understand this behavior.

答:
D is not inheriting anything from I because it has no default method, just a method signature for which you are indeed not providing an implementation. As @RC points out the type of your m is different enough that it is not considered a valid implementation. To get the error about a conflict, you would actually need to add a conflicting implementation.

In E you are marking your class as abstract so it's OK to not have the method implemented as required in the interface. As soon as you do in any class that extends E, you will trigger the error about  conflicting implementations because after type erasure the types would be identical. Basically you just moved the problem from D to whatever is going to extend E.

Title: Generics and Inheritance corner case

Body:
I have following code and it is not behaving as i am thinking. I have put the comments inline , that what is happening and what is expected.

class C<T> {
    void m(T arg) {
    }
}

interface I {
    void m(Class arg);
}

class D extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: error -- abstract method not overridden

abstract class E extends C<Class<String>> implements I {
}
// expected : error -- conflicting inherited methods
// actual: no error, but no bridge method

Can some one please help me understand this behavior.


问:
jquery highlight search text in table
I use below code to highlight text in a table this code work fine but i have a problem that is sensitive for capital and small letter

example: if i do a search on a word like test

if i put a capital Test or TEST i can't found the word only if i put test like that i found the word

How can i solve this problem ??

I want if i put a capital or small letter the word be highlighted.

This the code:

```<code>(function () {
var removeHighlight = function () {
    $('span.highlight').contents().unwrap();
};

var wrapContent = function (index, $el, text) {
    var $highlight = $('<span class="highlight"/>')
        .text(text.substring(0, index));
    //console.log(text.substring(0, index));
    var normalText = document.createTextNode(text.substring(index, text.length));
    //console.log(index, $highlight.text(), normalText);
    $el.html($highlight).append(normalText);
};

var highlightTextInTable = function ($tableElements, searchText) {
    // highlights if text found (during typing)
    var matched = false;
    //remove spans
    removeHighlight();

    $.each($tableElements, function (index, item) {
        var $el = $(item);
        if ($el.text().search(searchText) != -1 && !matched) {
            //console.log("matched", $el, $el.html());
            wrapContent(searchText.length, $el, $el.html());
            //console.log(searchText, $el.text());
            if (searchText.toLowerCase() == $el.text().toLowerCase()) {
                // found the entry
                //console.log("matched");
                matched = true;
            }
        }
    });
};

$(function () {
    //load table into object
    var $tableRows = $('table td');
    var $tableElements = $tableRows.children();

    console.log($tableRows, $tableElements);

    $('#search').on('keyup', function (e) {
        var searchText = $(this).val();

        if (searchText.length == 0) {
            // catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
            removeHighlight(); // remove last remaining highlight
            return;
        }
        //findTextInTable($tableElements, searchText);

        highlightTextInTable($tableElements, searchText);

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

})();

答:
Use toLowerCase() anc change like below:-

```<code>if ($el.text().toLowerCase().search(searchText.toLowerCase()) != -1 && !matched) {
    //console.log("matched", $el, $el.html());
    wrapContent(searchText.length, $el, $el.html());
    console.log($el.text().toLowerCase());
    if (searchText.toLowerCase() == $el.text().toLowerCase()) {
        // found the entry
        //console.log("matched");
        matched = true;
    }
}
</code>```

Workinf fiddle:- https://jsfiddle.net/c612ak5d/

Title: jquery highlight search text in table

Body:
I use below code to highlight text in a table this code work fine but i have a problem that is sensitive for capital and small letter

example: if i do a search on a word like test

if i put a capital Test or TEST i can't found the word only if i put test like that i found the word

How can i solve this problem ??

I want if i put a capital or small letter the word be highlighted.

This the code:

(function () {
var removeHighlight = function () {
    $('span.highlight').contents().unwrap();
};

var wrapContent = function (index, $el, text) {
    var $highlight = $('')
        .text(text.substring(0, index));
    //console.log(text.substring(0, index));
    var normalText = document.createTextNode(text.substring(index, text.length));
    //console.log(index, $highlight.text(), normalText);
    $el.html($highlight).append(normalText);
};

var highlightTextInTable = function ($tableElements, searchText) {
    // highlights if text found (during typing)
    var matched = false;
    //remove spans
    removeHighlight();

    $.each($tableElements, function (index, item) {
        var $el = $(item);
        if ($el.text().search(searchText) != -1 && !matched) {
            //console.log("matched", $el, $el.html());
            wrapContent(searchText.length, $el, $el.html());
            //console.log(searchText, $el.text());
            if (searchText.toLowerCase() == $el.text().toLowerCase()) {
                // found the entry
                //console.log("matched");
                matched = true;
            }
        }
    });
};

$(function () {
    //load table into object
    var $tableRows = $('table td');
    var $tableElements = $tableRows.children();

    console.log($tableRows, $tableElements);

    $('#search').on('keyup', function (e) {
        var searchText = $(this).val();

        if (searchText.length == 0) {
            // catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
            removeHighlight(); // remove last remaining highlight
            return;
        }
        //findTextInTable($tableElements, searchText);

        highlightTextInTable($tableElements, searchText);

    });
});

})();

Body:
Use toLowerCase() anc change like below:-

if ($el.text().toLowerCase().search(searchText.toLowerCase()) != -1 && !matched) {
    //console.log("matched", $el, $el.html());
    wrapContent(searchText.length, $el, $el.html());
    console.log($el.text().toLowerCase());
    if (searchText.toLowerCase() == $el.text().toLowerCase()) {
        // found the entry
        //console.log("matched");
        matched = true;
    }
}

Workinf fiddle:- https://jsfiddle.net/c612ak5d/


问:
Rails text_field_tag, input type missing in production
I'm using materialize with rails 4.2.7, and when i use rails text_field_tag the input type="text" attribute is not available in the production environment, whereas it is available in the developement env

```<code><div class="input-field col l6 m6 s12 clear-margin">
   <%= text_field_tag :address,"", :class => "location-field", id:
   "address" %>
   <label for="address">Address</label>
</div>
</code>```

The output in development is as follow

```<code><input type="text" name="address" id="address" value="" class="location-field" data-parsley-id="6097">
</code>```

But in production the input type attribute is not appearing, can anyone help me with this

Thanks in advance.

答:
Solved the issue by using jquery.</p>

```<code>if($("input:not([type])").length>0){
  $( "input:not([type])").on('focus',function({$(this).siblings("label").addClass("active")})
  $( "input:not([type])").on('blur',function(){
   if (!$(this).val() ) {
     $(this).siblings("label").removeClass("active")
   }
 })
}
</code>```

Body:
I'm using materialize with rails 4.2.7, and when i use rails text_field_tag the input type="text" attribute is not available in the production environment, whereas it is available in the developement env

   <%= text_field_tag :address,"", :class => "location-field", id:
   "address" %>
   Address

The output in development is as follow

<input type="text" name="address" id="address" value="" class="location-field" data-parsley-id="6097">

But in production the input type attribute is not appearing, can anyone help me with this

Thanks in advance.

Body:
Solved the issue by using jquery.

if($("input:not([type])").length>0){
  $( "input:not([type])").on('focus',function({$(this).siblings("label").addClass("active")})
  $( "input:not([type])").on('blur',function(){
   if (!$(this).val() ) {
     $(this).siblings("label").removeClass("active")
   }
 })
}


问:
Google map is not showing in partial view?
I am trying to implement google map in a partial view and trying to call partial view on a page
here is my google map script which I placed on a main view

```<code> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDLhntIiMFhAoHu5XtrxDuh4EeNbm2ZuH0&libraries=places&callback=initAutocomplete" async defer></script>
    <script type="text/javascript">
        function initAutocomplete()
        {

            var map = new google.maps.Map(document.getElementById('map'),
                {
                center: { lat: -33.8688, lng: 151.2195 },
                zoom: 13,
                mapTypeId: 'roadmap'
            });
            console.log('map', map);
            // Create the search box and link it to the UI element.
            var input = document.getElementById('pac-input');
            var searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

            // Bias the SearchBox results towards current map's viewport.
            map.addListener('bounds_changed', function () {
                searchBox.setBounds(map.getBounds());
            });

            var markers = [];
            // Listen for the event fired when the user selects a prediction and retrieve
            // more details for that place.
            searchBox.addListener('places_changed', function () {
                var places = searchBox.getPlaces();

                if (places.length == 0) {
                    return;
                }

                // Clear out the old markers.
                markers.forEach(function (marker) {
                    marker.setMap(null);
                });
                markers = [];

                // For each place, get the icon, name and location.
                var bounds = new google.maps.LatLngBounds();
                places.forEach(function (place) {
                    if (!place.geometry) {
                        console.log("Returned place contains no geometry");
                        return;
                    }
                    var icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25)
                    };
                    // Create a marker for each place.
                    markers.push(new google.maps.Marker({
                        map: map,
                        icon: icon,
                        title: place.name,
                        position: place.geometry.location
                    }));

                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                    var address = $('#pac-input').val();
                    //document.getElementById('pac-input');
                    $.ajax({
                        url: "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false",
                        type: "POST",
                        success: function (res) {
                            latitude = res.results[0].geometry.location.lat;
                            longitude = res.results[0].geometry.location.lng;
                        }
                    });
                });
                map.fitBounds(bounds);
            });
        }
</code>```

And here is my HTML which is placed in partial view

```<code> <div class="form-group">
            <label>Type a location to Search on Map</label>
            <input type="text" id="pac-input" class="form-control" ng-model="MyLocations.Location" required>
            <div class="selectlocatinonmap" id="map">
            </div>
    </div>
</code>```

I have placed this script  on a page where I have to call a partial view but google map is not working on a partial view
I am attaching the image also
please take a look

however console is not showing any error.

答: Run Fiddler it's free  and see if your request is getting to googgle.  Based on your screenshot I don't see any xhr to google mapping api.  I think your being blocked somewhere.</p>


问:
Download 3000+ Images Using C#?
I have a list of around 3000 image URLs, where I need to download them to my desktop.

I'm a web dev, so naturally wrote a little asp.net c# download method to do this but the obvious problem happened and the page timed out before I got hardly any of them.

Was wondering if anyone else knew of a good, quick and robust way of me looping through all the image URL's and downloading them to a folder?  Open to any suggestions, WinForms, batch file although I'm a novice at both.

Any help greatly appreciated

答:
What about wget? It can download a list of URL specified in a file.</p>

```<code>wget -i c:\list-of-urls.txt
</code>```

ContentLicense: CC BY-SA 2.5

Title: Download 3000+ Images Using C#?

Body:
What about wget? It can download a list of URL specified in a file.

wget -i c:\list-of-urls.txt


问:
Execution failed for task ':app:mergeDebugResources' & Build errors
In every project I'm getting same following error

Information:Gradle tasks [clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
  Error:Execution failed for task ':app:mergeDebugResources'.
  Error: Some file crunching failed, see logs for details
  Error:Some file crunching failed, see logs for details
  Information:BUILD FAILED

Even if I'm creating new project, without adding anything I'm getting above error, also getting an

Cannot resolve symbol 'R'

in every project.

答:
Sometimes this error comes due to the path of the project file.

Try relocating your project with short path address and then try to build the project.


问:
Get the daily maximum gives strange results
I have a data set of temperature recorded every 15 minutes. The file looks like that (~50000 rows)

```<code>02/01/2016;05:15:00;10.800
02/01/2016;05:30:00;10.300
02/01/2016;05:45:00;9.200
02/01/2016;06:00:00;9.200
02/01/2016;06:15:00;8.900
02/01/2016;06:30:00;8.900
02/01/2016;06:45:00;9.400
02/01/2016;07:00:00;9.000
02/01/2016;07:15:00;9.200
02/01/2016;07:30:00;11.100
02/01/2016;07:45:00;13.000
02/01/2016;08:00:00;14.400
02/01/2016;08:15:00;15.600
</code>```

My goal is to calculate daily min/max, so here my code to do it

```<code># load dataframe
with open(intraday_file_path, "r") as fl:
    df_intraday = pd.read_csv(fl,
                              **load_args
                              )

df_daily = df_intraday.groupby(df_intraday[0])
df_daily = df_daily.aggregate({0:np.max})

df_daily.index.names = [0]
df_daily.reset_index(level=[0], inplace=True)

df_daily.sort_values(by=[0], inplace=True)
df_daily.drop_duplicates(subset=0,
                         keep="first",
                         inplace=True)

daily_name = "daily_%s" %(intraday_file_name,)
daily_path = os.getcwd() + "\\" + daily_name

df_daily = df_daily[0, 1]

with open(daily_path, "w") as fl:
    df_daily.to_csv(fl,
                    **save_args
                    )
</code>```

But the output is strange as soon as I have a temperature below 10°C. For example for 02/01/2016 the code output is 9.4°C?!

Any ideas?

答:
FYI, there is resample option. Handy tool for time series.

```<code>import pandas as pd

df = pd.read_table('sample.txt', header=None, sep=';')
df.columns=['date', 'time', 'temp']

df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df['temp'] = df['temp'].astype(float)  # dtypes should be float as jezrael mentioned.

df = df.set_index('datetime')[['temp']]
df = pd.concat([df.resample('1D', how=min),
                df.resample('1D', how=max)], axis=1)

df.columns = ['temp_min', 'temp_max']
print(df)
</code>```

result

```<code>            temp_min  temp_max
datetime
2016-02-01       8.9      15.6
</code>```

Body:
I have a data set of temperature recorded every 15 minutes. The file looks like that (~50000 rows)

02/01/2016;05:15:00;10.800
02/01/2016;05:30:00;10.300
02/01/2016;05:45:00;9.200
02/01/2016;06:00:00;9.200
02/01/2016;06:15:00;8.900
02/01/2016;06:30:00;8.900
02/01/2016;06:45:00;9.400
02/01/2016;07:00:00;9.000
02/01/2016;07:15:00;9.200
02/01/2016;07:30:00;11.100
02/01/2016;07:45:00;13.000
02/01/2016;08:00:00;14.400
02/01/2016;08:15:00;15.600

My goal is to calculate daily min/max, so here my code to do it

# load dataframe
with open(intraday_file_path, "r") as fl:
    df_intraday = pd.read_csv(fl,
                              **load_args
                              )

df_daily = df_intraday.groupby(df_intraday[0])
df_daily = df_daily.aggregate({0:np.max})

df_daily.index.names = [0]
df_daily.reset_index(level=[0], inplace=True)

df_daily.sort_values(by=[0], inplace=True)
df_daily.drop_duplicates(subset=0,
                         keep="first",
                         inplace=True)

daily_name = "daily_%s" %(intraday_file_name,)
daily_path = os.getcwd() + "\\" + daily_name

df_daily = df_daily[0, 1]

with open(daily_path, "w") as fl:
    df_daily.to_csv(fl,
                    **save_args
                    )

But the output is strange as soon as I have a temperature below 10°C. For example for 02/01/2016 the code output is 9.4°C?!

Any ideas?

Body:
FYI, there is resample option. Handy tool for time series.

import pandas as pd

df = pd.read_table('sample.txt', header=None, sep=';')
df.columns=['date', 'time', 'temp']

df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df['temp'] = df['temp'].astype(float)  # dtypes should be float as jezrael mentioned.

df = df.set_index('datetime')[['temp']]
df = pd.concat([df.resample('1D', how=min),
                df.resample('1D', how=max)], axis=1)

df.columns = ['temp_min', 'temp_max']
print(df)

result

            temp_min  temp_max
datetime
2016-02-01       8.9      15.6


问:
Which is the best way to take backup of all table data either merging one or separate in SQL Server?
In SQL Server 2005, I have a requirement to take backup the output table After Monthly Processing, the output table contains 50,000 rows. Which is the best way to take backup of the table for each month either taking backup as one table or monthly wise separate tables. Which method provides to save memory and best performance for managing data in SQL Server 2005?</p>

答:
Taking a backup of the entire table is better not because it saves space but because it is much easier to handle.

But again, I would have multiple tables for each months rather handle the same with date/ date time field in a single table.

In my opinion, I would just backup the entire schema frequently so as to minimise any data lose.


问:
how to convert folder into Zip file in codeigniter where folder contains some image file
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

```<code><tr>
    <td align="right">
        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" /></a>
         <?php } ?>

    </td>
   </tr>
</code>```

Controller code:
Inside admin.php controller file i have the below method

```<code>public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }
</code>```

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.

答:
To archive all files within a folder use $this->zip->read_dir(); method. Example,

```<code>$path = '/path/to/folder';
$this->zip->read_dir($path);
$this->zip->archive('/path/to/folder/foldername.zip');
</code>```

For more info. please have a look: https://www.codeigniter.com/user_guide/libraries/zip.html

Body:
i have some doubts in zipping the folder in codeigniter.Actually i have some image files in the folder and i was trying to zip this folder in codegiter. I have view file where i have written "Download all file" button. On clicking this button i have to take the folder and zip it.
My view file:
I have written the button "Download All Files" inside the anchor tag.

        <?php  if(isset($AppData) && !empty($AppData)) {
          $applicantNo = $AppData[0]['appid']; ?>
        <a href='<?php echo base_url("admin/downloadAllFileZip/$applicantNo");?>'><input type="submit" name="download" value="Download All Files" />
         <?php } ?>

Controller code:
Inside admin.php controller file i have the below method

public function downloadAllFileZip($appId)
    {

        $path = file_get_contents(base_url().'files/'.$appId);
        $applicant_id = $appId;
        $this->zip->add_data($applicant_id,$path);
        $this->zip->archive('/files/'.$applicant_id);
        $this->zip->download($applicant_id);

    }

But when I am clicking the " Download all file " button the popup window for zipping is comming and after downloading its showing 1kb file but there is no image on that file. I can able to zip single image file as a zip file but not able to zip the entire folder. Please help me how to do this.

Body:
To archive all files within a folder use $this->zip->read_dir(); method. Example,

$path = '/path/to/folder';
$this->zip->read_dir($path);
$this->zip->archive('/path/to/folder/foldername.zip');

For more info. please have a look: https://www.codeigniter.com/user_guide/libraries/zip.html


答:
I don't know if there would be any wrong answer here.. but it depends mostly on how this backup table will be used. What I would do:

Back everything up to the single table, but with another field named RunMonth (or something similar) that will indicate the month that those 50k records belong to. This would make querying the historical data much easier as opposed to having them in separate tables.

I hope that makes sense.

Title: Which is the best way to take backup of all table data either merging one or separate in SQL Server?

Body: In SQL Server 2005, I have a requirement to take backup the output table After Monthly Processing, the output table contains 50,000 rows. Which is the best way to take backup of the table for each month either taking backup as one table or monthly wise separate tables. Which method provides to save memory and best performance for managing data in SQL Server 2005?


问:
How do I access css/scss with react?
I have a react component where I am trying to change the background color of the css when clicking the div.

I know you can set the color in the component, but I am using this component many times, and don't to make multiple component files with just a different color, and even if I did, I am curious besides the fact.

How can I access (or even console.log to figure it out on my own) the css file and its properties through the component?  Thanks ahead of time.

答: Better to make an external css file and write your css code in that file and just import that one in index.html</p>

Title: How do I access css/scss with react?


问:
Creating a custom WHILE loop in NANT
I have tried my best to create a custom while loop but ended in vain.
Has anyone been successful in creating a custom while loop in NANT?</p>

答:
Here is one way of writing a WHILE loop in nant, with no custom tasks or script element, taking advantage of failonerror="false" on a foreach loop.

```<code>    <property name="n" value="10000" /><!-- this would be inefficient if "n" is very large -->
    <property name="i" value="0" />
    <foreach item="String" in="${string::pad-right(' ', int::parse(n), ',')}" delim="," property="val" failonerror="false" >
        <if test="${int::parse(i) > 3}"><!-- put our exit condition here -->
            <fail message="condition met, exit loop early" />
        </if>
        <echo message="i: ${i}" />
        <property name="i" value="${int::parse(i) + 1}" />
    </foreach>
</code>```

The output from executing the WHILE loop above is as follows. Note that, due to the failonerror="false" the fail call does not terminate the script:

```<code>     [echo] i: 0
     [echo] i: 1
     [echo] i: 2
     [echo] i: 3
  [foreach] myscript.nant(24,18):
  [foreach] condition met, exit loop early

  BUILD SUCCEEDED - 1 non-fatal error(s), 0 warning(s)
</code>```

I based the WHILE loop above on how I build a FOR loop, which is a slightly simplified version of the above code:

```<code>        <property name="n" value="5" />
        <property name="i" value="0" />
        <foreach item="String" in="${string::pad-right(' ', int::parse(n), ',')}" delim="," property="val" >
            <echo message="i: ${i}" />
            <property name="i" value="${int::parse(i) + 1}" /> <!-- increment "i" -->
        </foreach>
</code>```

The output from the FOR loop looks like this:

```<code>     [echo] i: 0
     [echo] i: 1
     [echo] i: 2
     [echo] i: 3
     [echo] i: 4

 BUILD SUCCEEDED
</code>```

OwnerDisplayName: Sarathy

Title: Creating a custom WHILE loop in NANT

Body:
Here is one way of writing a WHILE loop in nant, with no custom tasks or script element, taking advantage of failonerror="false" on a foreach loop.

    <property name="n" value="10000" /><!-- this would be inefficient if "n" is very large -->
    <property name="i" value="0" />
    <foreach item="String" in="${string::pad-right(' ', int::parse(n), ',')}" delim="," property="val" failonerror="false" >
        <if test="${int::parse(i) &gt; 3}"><!-- put our exit condition here -->
            <fail message="condition met, exit loop early" />
        </if>
        <echo message="i: ${i}" />
        <property name="i" value="${int::parse(i) + 1}" />
    </foreach>

The output from executing the WHILE loop above is as follows. Note that, due to the failonerror="false" the fail call does not terminate the script:

     [echo] i: 0
     [echo] i: 1
     [echo] i: 2
     [echo] i: 3
  [foreach] myscript.nant(24,18):
  [foreach] condition met, exit loop early

  BUILD SUCCEEDED - 1 non-fatal error(s), 0 warning(s)

I based the WHILE loop above on how I build a FOR loop, which is a slightly simplified version of the above code:

        <property name="n" value="5" />
        <property name="i" value="0" />
        <foreach item="String" in="${string::pad-right(' ', int::parse(n), ',')}" delim="," property="val" >
            <echo message="i: ${i}" />
            <property name="i" value="${int::parse(i) + 1}" /> <!-- increment "i" -->
        </foreach>

The output from the FOR loop looks like this:

     [echo] i: 0
     [echo] i: 1
     [echo] i: 2
     [echo] i: 3
     [echo] i: 4

 BUILD SUCCEEDED


问:
not redeclaring variable in php
I`ve got problem, my variable $x is not redeclaring to "english". Where is the problem? Thanks a lot:

```<code><?php
// assign language or default english
$x = $lang_detected;
$language_table = '
<form id="lang_detected" method="post"
  action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '">
  <input type="button" value="' . $x . '" onclick = "displayLangList()" style="width:200px;display:block;margin:auto;" />
  <input type="submit" value="ok" />
</form>';

$possible_lang = mysqli_query($con,
'SELECT name2 FROM page WHERE name2 = "' . $lang_detected . '"');

if (mysqli_num_rows($possible_lang) > 0 ) {
  echo $language_table;
} else {
  $x = 'english';
  echo $language_table;
}
?>
</code>```

even if i do:

```<code>if (mysqli_num_rows($possible_lang) > 0 ) {
  $x = "bla bla";
  echo $language_table;
} else {
  $x = 'english';
  echo $language_table;
}
</code>```

$x still holds the value:

```<code>$x = $lang_detected;
</code>```

Thanks a lot!

答:
When you construct a variable using other variables those values are baked in, as-is, at that exact moment. There's no way to defer evaluation other than to wrap that into a function.

That is:

```<code>$x = 'a';
$y = '(' . $x . ')';
$x = 'b';
</code>```

In this case $y is, and will remain, (a) even though $x has changed. There's no binding difference.

In your code you can always move that content down and avoid the duplication:

```<code>if (mysqli_num_rows($possible_lang) > 0 ) {
  $x = "bla bla";
} else {
  $x = 'english';
}

echo '<form ...language table'.$x.'...';
</code>```

Title: not redeclaring variable in php

Body:
I`ve got problem, my variable $x is not redeclaring to "english". Where is the problem? Thanks a lot:

<?php
// assign language or default english
$x = $lang_detected;
$language_table = '
<form id="lang_detected" method="post"
  action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '">
  <input type="button" value="' . $x . '" onclick = "displayLangList()" style="width:200px;display:block;margin:auto;" />
  <input type="submit" value="ok" />
</form>';

$possible_lang = mysqli_query($con,
'SELECT name2 FROM page WHERE name2 = "' . $lang_detected . '"');

if (mysqli_num_rows($possible_lang) > 0 ) {
  echo $language_table;
} else {
  $x = 'english';
  echo $language_table;
}
?>

even if i do:

if (mysqli_num_rows($possible_lang) > 0 ) {
  $x = "bla bla";
  echo $language_table;
} else {
  $x = 'english';
  echo $language_table;
}

$x still holds the value:

$x = $lang_detected;

Thanks a lot!

Body:
When you construct a variable using other variables those values are baked in, as-is, at that exact moment. There's no way to defer evaluation other than to wrap that into a function.

That is:

$x = 'a';
$y = '(' . $x . ')';
$x = 'b';

In this case $y is, and will remain, (a) even though $x has changed. There's no binding difference.

In your code you can always move that content down and avoid the duplication:

if (mysqli_num_rows($possible_lang) > 0 ) {
  $x = "bla bla";
} else {
  $x = 'english';
}

echo '<form ...language table'.$x.'...';


问:
android code for get push notification log when app is in backgroud using firebase
when I try to send the notification with custom data in Firebase I did not get the notification in the background

My Firebase service Code is:

In On message Receive method

```<code>    @Override
public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.e("fcm", "received notification");

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {

            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                int badge = Integer.parseInt(remoteMessage.getData().get("badge"));
                String message = remoteMessage.getData().get("message");
                String timestamp = remoteMessage.getData().get("timestamp");
                handleDataMessage(badge,message,timestamp);

                badgeStore = Integer.parseInt(remoteMessage.getData().get("badge"));

            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }

    }
</code>```

答:
please register your firebase service in menifest file

```<code><service
android:name=".MyFirebaseMessagingService">
<intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</code>```

Add these lines inside the application tag to set the custom default icon and custom color:

```<code><meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />

<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />
</code>```

Body:
when I try to send the notification with custom data in Firebase I did not get the notification in the background

My Firebase service Code is:

In On message Receive method

    @Override
public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.e("fcm", "received notification");

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {

            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                int badge = Integer.parseInt(remoteMessage.getData().get("badge"));
                String message = remoteMessage.getData().get("message");
                String timestamp = remoteMessage.getData().get("timestamp");
                handleDataMessage(badge,message,timestamp);

                badgeStore = Integer.parseInt(remoteMessage.getData().get("badge"));

            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }

    }

Body:
please register your firebase service in menifest file

<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>

Add these lines inside the application tag to set the custom default icon and custom color:

<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />

<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />


问:
Working with MultiLevel XML in C# and SQL Server
I have a client API which sends me an XML in the following format. I have to change few values and send the same XML to my client's another API. What is the best possible way to do it. We are currently using SQL Server 2014 and C#.

```<code><?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <JobPositionInformation>
            <JobPositionTitle>R and D manager #2 banglore</JobPositionTitle>
            <JobClassifications>
                <PrimaryJobCategory>
                    <JobIndustryCode>7</JobIndustryCode>
                    <JobFunctionCode>8</JobFunctionCode>
                    <JobRoleCode>8.31</JobRoleCode>
                </PrimaryJobCategory>
            </JobClassifications>
            <JobPositionDescription>
                <JobKeywords>Java</JobKeywords>
                <JobPositionLocation>
                    <InterNationalLoc></InterNationalLoc>
                    <InterNationalLocOther></InterNationalLocOther>
                    <IndianLoc>25.30.159</IndianLoc>
                    <IndianLocOther></IndianLocOther>
                </JobPositionLocation>
                <CompensationDescription>
                    <Pay>
                        <SalaryCurrency>Rupees</SalaryCurrency>
                        <MinimumSalary>250000</MinimumSalary>
                        <MaximumSalary>325000</MaximumSalary>
                        <DisplaySalary>Y</DisplaySalary>
                    </Pay>
                    <BenifitsDescription>Job Benefits Description</BenifitsDescription>
                </CompensationDescription>
                <SummaryText>Job Description(brief about JD)</SummaryText>
            </JobPositionDescription>
            <JobPositionRequirements>
                <SummaryText>Desired Candidate Profile Summary Text - Required Competencies/Skills/Leadership E-mail
         </SummaryText>
                <JobExperience>
                    <MinimumExperience>2</MinimumExperience>
                    <MaximumExperience>4</MaximumExperience>
                </JobExperience>
                <JobQualifications>
                    <UGQualifications />
                    <UGSpecializations />
                    <PGQualifications />
                    <PGSpecializations />
                </JobQualifications>
            </JobPositionRequirements>
            <AddJobsToRefSite>true</AddJobsToRefSite>
            <ReferenceCode>Your Unique Job Reference code</ReferenceCode>
        </JobPositionInformation>
        <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>Client E-mail for Response Management , in case not using ATS Integration
           </E-mail>
                </ByEmail>
                <ByWeb>
                    <URL></URL>
                    <ApplyIntegration>1</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>Standard Questionnaire name if you know the same, else contact your Account manager</QUESTIONNAIRE>
            </ApplicationMethods>
        </HowToApply>
        <ReferralDetails>
            <Amount> 1000</Amount>
            <Benefit>  gift voucher</Benefit>
        </ReferralDetails>
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>
</code>```

I am following the below approach. I replaced all the value fields in my XML with some variables by separating them with pipe(|) symbols. Please find below the replaced one.

```<code><?xml version="1.0"?>
<JobPositionPostings>
   <JobPositionPosting>
                    <JobAction>|JAct_M|</JobAction>
                    <JobPositionPostingID>|JID_M|</JobPositionPostingID>
                    <JobType>|JType_M|</JobType>
   <HiringOrg>
                    <WebSite>|JWebSite_N|</WebSite>
                    <HiringOrgName>|JComp_M|</HiringOrgName>
        <Industry>
                    <SummaryText>|JCompDesc_M|</SummaryText>
        </Industry>
    <Contact>
            <PersonName>
                    <FormattedName>|JContactName_N|</FormattedName>
            </PersonName>
    </Contact>
   </HiringOrg>
   <JobDisplayOptions>
                    <MicrositeName>|JMSite_S|</MicrositeName>
                    <TemplateName>|JTempl_N|</TemplateName>
   </JobDisplayOptions>
   <JobPositionInformation>
                    <JobPositionTitle>|JTitle_M|</JobPositionTitle>
       <JobClassifications>
            <PrimaryJobCategory>
                    <JobIndustryCode>|JIndustryCode_M|</JobIndustryCode>
                    <JobFunctionCode>|JFunCode_M|</JobFunctionCode>
                    <JobRoleCode>|JRoleCode_M|</JobRoleCode>
            </PrimaryJobCategory>
       </JobClassifications>
       <JobPositionDescription>
                    <JobKeywords>|JSkills_M|</JobKeywords>
            <JobPositionLocation>
                    <InterNationalLoc>|JIntlCode_M|</InterNationalLoc>
                    <InterNationalLocOther>|JIntlCodeOther_N|</InterNationalLocOther>
                    <IndianLoc>|JLocCode_M|</IndianLoc>
                    <IndianLocOther>|JLocOther_N|</IndianLocOther>
            </JobPositionLocation>
            <CompensationDescription>
                <Pay>
                        <SalaryCurrency>|JCurr_M|</SalaryCurrency>
                        <MinimumSalary>|JMinSal_M|</MinimumSalary>
                        <MaximumSalary>|JMaxSal_M|</MaximumSalary>
                        <DisplaySalary>|JSalDisp_N|</DisplaySalary>
                </Pay>
                    <BenifitsDescription>|JBenefits_N|</BenifitsDescription>
            </CompensationDescription>
                    <SummaryText>|JJD_M|</SummaryText>
       </JobPositionDescription>
       <JobPositionRequirements>
                    <SummaryText>|JDesCand_N|</SummaryText>
            <JobExperience>
                    <MinimumExperience>|JMinExp_M|</MinimumExperience>
                    <MaximumExperience>|JMaxExp_M|</MaximumExperience>
            </JobExperience>
            <JobQualifications>
                    <UGQualifications>|JQual1_M|</UGQualifications>
                    <UGSpecializations>|JSpec1_M|</UGSpecializations>
                    <PGQualifications>|JQual2_M|</PGQualifications>
                    <PGSpecializations>|JSpec2_M|</PGSpecializations>
                    <DoctorateQualifications>|JQual3_M|</DoctorateQualifications>
                    <DoctorateSpecializations>|JSpec3_M|</DoctorateSpecializations>
            </JobQualifications>
       </JobPositionRequirements>
                <AddJobsToRefSite>|JRefSite_N|</AddJobsToRefSite>
                <ReferenceCode>|JRefCode_N|</ReferenceCode>
    </JobPositionInformation>
    <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>|JLntMail_M|</E-mail>
                </ByEmail>
            <ByEapps>
                <Eapps>|JeApps_M|</Eapps>
            </ByEapps>
                <ByWeb>
                    <URL>|JURL_M|</URL>
                    <ApplyIntegration>|JAppInt_M|</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>|JQuest_N|</QUESTIONNAIRE>
            </ApplicationMethods>
     </HowToApply>
     <ReferralDetails>
                        <Benefit>|JBenefit_N|</Benefit>
                        <Amount>|JBAmt_N|</Amount>
     </ReferralDetails>
  </JobPositionPosting>
                <JobFeedResponseEmail>|JFeedRespEmail_N|</JobFeedResponseEmail>
</JobPositionPostings>
</code>```

After that in SQL server I am replacing them with desired values and forwarding that XML to my client.

```<code>set @Nxml = replace(@Nxml, '|JAct_M|','Add')
set @Nxml = replace(@Nxml, '|JID_M|',@reqmt_id)
set @Nxml = replace(@Nxml, '|JType_M|','P')
</code>```

Is this best method or is there any other easy approach.
Thanks in advance.

答:
In this case you are modifying a lot of elements.  So I recommend using serialization.  Below is a start.  I read file and deserialized, then wrote same results.  I recommend you continue like I've done with original data and compare input and output to be the same.</p>

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

namespace ConsoleApplication1
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test1.xml";
        const string OUTPUT_FILENAME = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {
            JobPositionPostings postings = Load(INPUT_FILENAME);

            // modify posting here

            Save(OUTPUT_FILENAME, postings);

        }
        static JobPositionPostings Load(string filename)
        {
            StreamReader reader = new StreamReader(INPUT_FILENAME);

            XmlSerializer serializer = new XmlSerializer(typeof(JobPositionPostings));
            JobPositionPostings postings =  (JobPositionPostings)serializer.Deserialize(reader);

            return postings;
        }
        static void Save(string filename, JobPositionPostings postings)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(JobPositionPostings));
            StreamWriter writer = new StreamWriter(filename);

            serializer.Serialize(writer, postings);

        }

    }
    [XmlRoot("JobPositionPostings")]
    public class JobPositionPostings
    {
        [XmlElement("JobPositionPosting")]
        public List<JobPositionPosting> jobPositionPostings { get; set; }
    }
    [XmlRoot("JobPositionPosting")]
    public class JobPositionPosting
    {
        [XmlElement("JobAction")]
        public string JobAction { get; set; }

        [XmlElement("JobType")]
        public string jobType { get; set; }

        [XmlElement("JobPositionPostingID")]
        public int jobPositionPostingID { get; set; }

        [XmlElement("HiringOrg")]
        public HiringOrg hiringOrg { get; set; }

        [XmlElement("JobDisplayOptions")]
        public JobDisplayOptions jobDisplayOptions { get; set; }
    }
    [XmlRoot("HiringOrg")]
    public class HiringOrg
    {

        [XmlElement("HiringOrgName")]
        public string hiringOrgName { get; set; }

        [XmlElement("Industry")]
        public Industry industry { get; set; }

        [XmlElement("Contact")]
        public Contact contact { get; set; }

    }
    [XmlRoot("Industry")]
    public class Industry
    {
        [XmlElement("SummaryText")]
        public string summaryText { get; set; }

        [XmlElement("Contact")]
        public string contact { get; set; }
    }
    [XmlRoot("Contact")]
    public class Contact
    {
       [XmlElement("PersonName")]
        public PersonName personName { get; set; }
    }
    [XmlRoot("PersonName")]
    public class PersonName
    {
        [XmlElement("FormattedName")]
        public string formattedName { get; set; }
    }
    [XmlRoot("JobDisplayOptions")]
    public class JobDisplayOptions
    {
        [XmlElement("MicrositeName")]
        public string micrositeName { get; set; }

        [XmlElement("TemplateName")]
        public string templateName { get; set; }
}

}
</code>```

Body:
I have a client API which sends me an XML in the following format. I have to change few values and send the same XML to my client's another API. What is the best possible way to do it. We are currently using SQL Server 2014 and C#.

<?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <JobPositionInformation>
            <JobPositionTitle>R and D manager #2 banglore</JobPositionTitle>
            <JobClassifications>
                <PrimaryJobCategory>
                    <JobIndustryCode>7</JobIndustryCode>
                    <JobFunctionCode>8</JobFunctionCode>
                    <JobRoleCode>8.31</JobRoleCode>
                </PrimaryJobCategory>
            </JobClassifications>
            <JobPositionDescription>
                <JobKeywords>Java</JobKeywords>
                <JobPositionLocation>
                    <InterNationalLoc></InterNationalLoc>
                    <InterNationalLocOther></InterNationalLocOther>
                    <IndianLoc>25.30.159</IndianLoc>
                    <IndianLocOther></IndianLocOther>
                </JobPositionLocation>
                <CompensationDescription>
                    <Pay>
                        <SalaryCurrency>Rupees</SalaryCurrency>
                        <MinimumSalary>250000</MinimumSalary>
                        <MaximumSalary>325000</MaximumSalary>
                        <DisplaySalary>Y</DisplaySalary>
                    </Pay>
                    <BenifitsDescription>Job Benefits Description</BenifitsDescription>
                </CompensationDescription>
                <SummaryText>Job Description(brief about JD)</SummaryText>
            </JobPositionDescription>
            <JobPositionRequirements>
                <SummaryText>Desired Candidate Profile Summary Text - Required Competencies/Skills/Leadership E-mail
         </SummaryText>
                <JobExperience>
                    <MinimumExperience>2</MinimumExperience>
                    <MaximumExperience>4</MaximumExperience>
                </JobExperience>
                <JobQualifications>
                    <UGQualifications />
                    <UGSpecializations />
                    <PGQualifications />
                    <PGSpecializations />
                </JobQualifications>
            </JobPositionRequirements>
            <AddJobsToRefSite>true</AddJobsToRefSite>
            <ReferenceCode>Your Unique Job Reference code</ReferenceCode>
        </JobPositionInformation>
        <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>Client E-mail for Response Management , in case not using ATS Integration
           </E-mail>
                </ByEmail>
                <ByWeb>
                    <URL></URL>
                    <ApplyIntegration>1</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>Standard Questionnaire name if you know the same, else contact your Account manager</QUESTIONNAIRE>
            </ApplicationMethods>
        </HowToApply>
        <ReferralDetails>
            <Amount> 1000</Amount>
            <Benefit>  gift voucher</Benefit>
        </ReferralDetails>
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>

I am following the below approach. I replaced all the value fields in my XML with some variables by separating them with pipe(|) symbols. Please find below the replaced one.

<?xml version="1.0"?>
<JobPositionPostings>
   <JobPositionPosting>
                    <JobAction>|JAct_M|</JobAction>
                    <JobPositionPostingID>|JID_M|</JobPositionPostingID>
                    <JobType>|JType_M|</JobType>
   <HiringOrg>
                    <WebSite>|JWebSite_N|</WebSite>
                    <HiringOrgName>|JComp_M|</HiringOrgName>
        <Industry>
                    <SummaryText>|JCompDesc_M|</SummaryText>
        </Industry>
    <Contact>
            <PersonName>
                    <FormattedName>|JContactName_N|</FormattedName>
            </PersonName>
    </Contact>
   </HiringOrg>
   <JobDisplayOptions>
                    <MicrositeName>|JMSite_S|</MicrositeName>
                    <TemplateName>|JTempl_N|</TemplateName>
   </JobDisplayOptions>
   <JobPositionInformation>
                    <JobPositionTitle>|JTitle_M|</JobPositionTitle>
       <JobClassifications>
            <PrimaryJobCategory>
                    <JobIndustryCode>|JIndustryCode_M|</JobIndustryCode>
                    <JobFunctionCode>|JFunCode_M|</JobFunctionCode>
                    <JobRoleCode>|JRoleCode_M|</JobRoleCode>
            </PrimaryJobCategory>
       </JobClassifications>
       <JobPositionDescription>
                    <JobKeywords>|JSkills_M|</JobKeywords>
            <JobPositionLocation>
                    <InterNationalLoc>|JIntlCode_M|</InterNationalLoc>
                    <InterNationalLocOther>|JIntlCodeOther_N|</InterNationalLocOther>
                    <IndianLoc>|JLocCode_M|</IndianLoc>
                    <IndianLocOther>|JLocOther_N|</IndianLocOther>
            </JobPositionLocation>
            <CompensationDescription>
                <Pay>
                        <SalaryCurrency>|JCurr_M|</SalaryCurrency>
                        <MinimumSalary>|JMinSal_M|</MinimumSalary>
                        <MaximumSalary>|JMaxSal_M|</MaximumSalary>
                        <DisplaySalary>|JSalDisp_N|</DisplaySalary>
                </Pay>
                    <BenifitsDescription>|JBenefits_N|</BenifitsDescription>
            </CompensationDescription>
                    <SummaryText>|JJD_M|</SummaryText>
       </JobPositionDescription>
       <JobPositionRequirements>
                    <SummaryText>|JDesCand_N|</SummaryText>
            <JobExperience>
                    <MinimumExperience>|JMinExp_M|</MinimumExperience>
                    <MaximumExperience>|JMaxExp_M|</MaximumExperience>
            </JobExperience>
            <JobQualifications>
                    <UGQualifications>|JQual1_M|</UGQualifications>
                    <UGSpecializations>|JSpec1_M|</UGSpecializations>
                    <PGQualifications>|JQual2_M|</PGQualifications>
                    <PGSpecializations>|JSpec2_M|</PGSpecializations>
                    <DoctorateQualifications>|JQual3_M|</DoctorateQualifications>
                    <DoctorateSpecializations>|JSpec3_M|</DoctorateSpecializations>
            </JobQualifications>
       </JobPositionRequirements>
                <AddJobsToRefSite>|JRefSite_N|</AddJobsToRefSite>
                <ReferenceCode>|JRefCode_N|</ReferenceCode>
    </JobPositionInformation>
    <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>|JLntMail_M|</E-mail>
                </ByEmail>
            <ByEapps>
                <Eapps>|JeApps_M|</Eapps>
            </ByEapps>
                <ByWeb>
                    <URL>|JURL_M|</URL>
                    <ApplyIntegration>|JAppInt_M|</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>|JQuest_N|</QUESTIONNAIRE>
            </ApplicationMethods>
     </HowToApply>
     <ReferralDetails>
                        <Benefit>|JBenefit_N|</Benefit>
                        <Amount>|JBAmt_N|</Amount>
     </ReferralDetails>
  </JobPositionPosting>
                <JobFeedResponseEmail>|JFeedRespEmail_N|</JobFeedResponseEmail>
</JobPositionPostings>

After that in SQL server I am replacing them with desired values and forwarding that XML to my client.

set @Nxml = replace(@Nxml, '|JAct_M|','Add')
set @Nxml = replace(@Nxml, '|JID_M|',@reqmt_id)
set @Nxml = replace(@Nxml, '|JType_M|','P')

Is this best method or is there any other easy approach.
Thanks in advance.

Body:
In this case you are modifying a lot of elements.  So I recommend using serialization.  Below is a start.  I read file and deserialized, then wrote same results.  I recommend you continue like I've done with original data and compare input and output to be the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test1.xml";
        const string OUTPUT_FILENAME = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {
            JobPositionPostings postings = Load(INPUT_FILENAME);

            // modify posting here

            Save(OUTPUT_FILENAME, postings);

        }
        static JobPositionPostings Load(string filename)
        {
            StreamReader reader = new StreamReader(INPUT_FILENAME);

            XmlSerializer serializer = new XmlSerializer(typeof(JobPositionPostings));
            JobPositionPostings postings =  (JobPositionPostings)serializer.Deserialize(reader);

            return postings;
        }
        static void Save(string filename, JobPositionPostings postings)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(JobPositionPostings));
            StreamWriter writer = new StreamWriter(filename);

            serializer.Serialize(writer, postings);

        }

    }
    [XmlRoot("JobPositionPostings")]
    public class JobPositionPostings
    {
        [XmlElement("JobPositionPosting")]
        public List<JobPositionPosting> jobPositionPostings { get; set; }
    }
    [XmlRoot("JobPositionPosting")]
    public class JobPositionPosting
    {
        [XmlElement("JobAction")]
        public string JobAction { get; set; }

        [XmlElement("JobType")]
        public string jobType { get; set; }

        [XmlElement("JobPositionPostingID")]
        public int jobPositionPostingID { get; set; }

        [XmlElement("HiringOrg")]
        public HiringOrg hiringOrg { get; set; }

        [XmlElement("JobDisplayOptions")]
        public JobDisplayOptions jobDisplayOptions { get; set; }
    }
    [XmlRoot("HiringOrg")]
    public class HiringOrg
    {

        [XmlElement("HiringOrgName")]
        public string hiringOrgName { get; set; }

        [XmlElement("Industry")]
        public Industry industry { get; set; }

        [XmlElement("Contact")]
        public Contact contact { get; set; }

    }
    [XmlRoot("Industry")]
    public class Industry
    {
        [XmlElement("SummaryText")]
        public string summaryText { get; set; }

        [XmlElement("Contact")]
        public string contact { get; set; }
    }
    [XmlRoot("Contact")]
    public class Contact
    {
       [XmlElement("PersonName")]
        public PersonName personName { get; set; }
    }
    [XmlRoot("PersonName")]
    public class PersonName
    {
        [XmlElement("FormattedName")]
        public string formattedName { get; set; }
    }
    [XmlRoot("JobDisplayOptions")]
    public class JobDisplayOptions
    {
        [XmlElement("MicrositeName")]
        public string micrositeName { get; set; }

        [XmlElement("TemplateName")]
        public string templateName { get; set; }
}

}


问:
What does ".()" mean in Kotlin?
I've seen examples where a function has an argument given by ClassName.()
This doesn't seem to be an extension function, which is ClassName.Function()

An example is Kotterknife:

```<code>private val View.viewFinder: View.(Int) -> View?
    get() = { findViewById(it) }
</code>```

Which I don't quite know the function of,

and MaterialDrawerKt

```<code>fun Activity.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer {
    val builder = DrawerBuilderKt(this)
    builder.setup()
    return builder.build()
}
</code>```

Where the code allows you to directly call

```<code>drawer {
    ...
}
</code>```

rather than give it arguments surrounded by the parentheses.

Is there any documentation on this anywhere?

答:
A function that takes in nothing and returns nothing in Kotlin looks like:

var function : () -> Unit
```
<p>The difference is that the function in your code takes in nothing, returns nothing, <strong>but is invoked on an object</strong>.</p>
<p>For example,</p>
<pre class="lang-kotlin prettyprint-override"><code>class Builder (val multiplier: Int) {

    fun invokeStuff(action: (Builder.() -> Unit)) {
        this.action()
    }

    fun multiply(value: Int) : Int {
        return value * multiplier
    }
}
</code>```

The important bit here is the way we've declared the type of action

action: (Builder.() -> Unit)
```
<p>This is a function that returns nothing, takes in nothing but <strong>is invoked on an object of type <code>Builder</code></strong>.</p>
<p>This means when we use this builder like so</p>
<pre class="lang-kotlin prettyprint-override"><code>var builder = Builder(10)
builder.invokeStuff({
    var result = multiply(1)
    println(result)
})
</code>```

The context of this has been set to the builder object and we can invoke functions declared within the builder.

Refer more here.

Title: What does ".()" mean in Kotlin?

Body:
I've seen examples where a function has an argument given by ClassName.()
This doesn't seem to be an extension function, which is ClassName.Function()

An example is Kotterknife:

private val View.viewFinder: View.(Int) -> View?
    get() = { findViewById(it) }

Which I don't quite know the function of,

and MaterialDrawerKt

fun Activity.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer {
    val builder = DrawerBuilderKt(this)
    builder.setup()
    return builder.build()
}

Where the code allows you to directly call

drawer {
    ...
}

rather than give it arguments surrounded by the parentheses.

Is there any documentation on this anywhere?

Body:
A function that takes in nothing and returns nothing in Kotlin looks like:

var function : () -> Unit

The difference is that the function in your code takes in nothing, returns nothing, but is invoked on an object.

For example,

class Builder (val multiplier: Int) {

    fun invokeStuff(action: (Builder.() -> Unit)) {
        this.action()
    }

    fun multiply(value: Int) : Int {
        return value * multiplier
    }
}

The important bit here is the way we've declared the type of action

action: (Builder.() -> Unit)

This is a function that returns nothing, takes in nothing but is invoked on an object of type Builder.

This means when we use this builder like so

var builder = Builder(10)
builder.invokeStuff({
    var result = multiply(1)
    println(result)
})

The context of this has been set to the builder object and we can invoke functions declared within the builder.

Refer more here.

ContentLicense: CC BY-SA 4.0


问:
How to convert date string into date in swift 3
I have formatted date in string format like "07/06/2017 11:23 AM" so I want to convert it into again date format. How to do this?.</p>

答:
You can use this:

```<code>let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy HH:mm a"
let date = df.string(from: dateString)
</code>```

For more formats: http://nsdateformatter.com/.

Body:
You can use this:

let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy HH:mm a"
let date = df.string(from: dateString)

For more formats: http://nsdateformatter.com/.


问:
Stable sorting in google chrome
I am using a dojo datagrid with col1 as the column with primary sorting and col2 as the secondary sorting column. After the grid loads if I again sort by col1 by clicking on the header, I can see the order of the rows getting changed randomly where the col1 has the similar values in Google Chrome . In Firefox everything seems to be working fine as they have stable sort implementation which maintains the original order of the input in case of similar key values. Is there a way I can implement some custom comparator for Array.sort() or something to avoid this problem in google chrome. Thanks in advance!

答:
It's already implemented. Give a chance to lodash function _.sortBy. It doing stable sort.

Here is docs: https://lodash.com/docs/4.17.4#sortBy

Title: Stable sorting in google chrome


问:
Trouble with profile details
I what to develop a FBML internal application. I used:

```<code>require 'facebook.php';$appId ='xxx';$secret ='xyx';$facebook = new Facebook(array( 'appId'  => $appId,  'secret' => $secret,  'cookie' => true,)); $session = $facebook->getSession();
</code>```

But I can not get the profile data of the user logged in..uid,name, etc...

Where I get it wrong?

答:
You need to respond to the user login attempt and also retrieve the cookie...

```<code>//attach this below your current code
  FB.Event.subscribe('auth.login', function(response) {
    window.location.reload();
  });
</code>```

And then also

```<code>//somewhere before you load the page...
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
</code>```

Check http://developers.facebook.com/docs/authentication/ and look at Single Sign On with Javascript SDK

Title: Trouble with profile details

Body:
I what to develop a FBML internal application. I used:

require 'facebook.php';$appId ='xxx';$secret ='xyx';$facebook = new Facebook(array( 'appId'  => $appId,  'secret' => $secret,  'cookie' => true,)); $session = $facebook->getSession();

But I can not get the profile data of the user logged in..uid,name, etc...

Where I get it wrong?

Body:
You need to respond to the user login attempt and also retrieve the cookie...

//attach this below your current code
  FB.Event.subscribe('auth.login', function(response) {
    window.location.reload();
  });

And then also

//somewhere before you load the page...
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);

Check http://developers.facebook.com/docs/authentication/ and look at Single Sign On with Javascript SDK


问:
Could not migrate and how to set mysql DB using Django python
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

```<code>Unknown command: 'migrate'
Type 'manage.py help' for usage.
</code>```

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

```<code>"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
</code>```

Please help me to resolve the above issue and connect to DB.

答:
migrate command found in Django version 1.7 and above. You should use syncdb what it can do is create a database table and rows for you based on your models.

If you want more migrations like latest Django on Django 1.6 please consider use south

Body:
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

Unknown command: 'migrate'
Type 'manage.py help' for usage.

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

Please help me to resolve the above issue and connect to DB.


问:
What is the byte format of an 8-bit monaural WAV file?
Setup:  WAV 8bit 8kHz mono PCM file.

By spec, 8-bit bytes are unsigned [0,255].  Is the byte value 2's compliment?  Is it simply binary offset?  What EXACTLY is the byte format?

MSDN says the byte is in 2's compliment. Yet, DSP discussions say binary offset, meaning zero amplitude is 127?

答:
8-bit WAV is the only format which is unsigned. The linked MSDN blog is wrong. I can verify this from experience and also the wikipedia page for WAV files https://en.wikipedia.org/wiki/WAV has a mention.

So if you were to consider a full scale sine wave, the zero crossing would be at 127, the positive peak would be at 255, and the negative peak would be at 0 or 1, depending on implementation (although you should account for the possibility of it being zero)


问:
jquery highlight search text in table
I use below code to highlight text in a table this code work fine but i have a problem that is sensitive for capital and small letter

example: if i do a search on a word like test

if i put a capital Test or TEST i can't found the word only if i put test like that i found the word

How can i solve this problem ??

I want if i put a capital or small letter the word be highlighted.

This the code:

```<code>(function () {
var removeHighlight = function () {
    $('span.highlight').contents().unwrap();
};

var wrapContent = function (index, $el, text) {
    var $highlight = $('<span class="highlight"/>')
        .text(text.substring(0, index));
    //console.log(text.substring(0, index));
    var normalText = document.createTextNode(text.substring(index, text.length));
    //console.log(index, $highlight.text(), normalText);
    $el.html($highlight).append(normalText);
};

var highlightTextInTable = function ($tableElements, searchText) {
    // highlights if text found (during typing)
    var matched = false;
    //remove spans
    removeHighlight();

    $.each($tableElements, function (index, item) {
        var $el = $(item);
        if ($el.text().search(searchText) != -1 && !matched) {
            //console.log("matched", $el, $el.html());
            wrapContent(searchText.length, $el, $el.html());
            //console.log(searchText, $el.text());
            if (searchText.toLowerCase() == $el.text().toLowerCase()) {
                // found the entry
                //console.log("matched");
                matched = true;
            }
        }
    });
};

$(function () {
    //load table into object
    var $tableRows = $('table td');
    var $tableElements = $tableRows.children();

    console.log($tableRows, $tableElements);

    $('#search').on('keyup', function (e) {
        var searchText = $(this).val();

        if (searchText.length == 0) {
            // catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
            removeHighlight(); // remove last remaining highlight
            return;
        }
        //findTextInTable($tableElements, searchText);

        highlightTextInTable($tableElements, searchText);

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

})();

答:
Using toLowerCase() you can achieve it :

```<code>if (searchText.toLowerCase() == $el.text().toLowerCase()) {
    // found the entry
   // console.log("matched");
   matched = true;
}
</code>```

Title: jquery highlight search text in table

Body:
I use below code to highlight text in a table this code work fine but i have a problem that is sensitive for capital and small letter

example: if i do a search on a word like test

if i put a capital Test or TEST i can't found the word only if i put test like that i found the word

How can i solve this problem ??

I want if i put a capital or small letter the word be highlighted.

This the code:

(function () {
var removeHighlight = function () {
    $('span.highlight').contents().unwrap();
};

var wrapContent = function (index, $el, text) {
    var $highlight = $('')
        .text(text.substring(0, index));
    //console.log(text.substring(0, index));
    var normalText = document.createTextNode(text.substring(index, text.length));
    //console.log(index, $highlight.text(), normalText);
    $el.html($highlight).append(normalText);
};

var highlightTextInTable = function ($tableElements, searchText) {
    // highlights if text found (during typing)
    var matched = false;
    //remove spans
    removeHighlight();

    $.each($tableElements, function (index, item) {
        var $el = $(item);
        if ($el.text().search(searchText) != -1 && !matched) {
            //console.log("matched", $el, $el.html());
            wrapContent(searchText.length, $el, $el.html());
            //console.log(searchText, $el.text());
            if (searchText.toLowerCase() == $el.text().toLowerCase()) {
                // found the entry
                //console.log("matched");
                matched = true;
            }
        }
    });
};

$(function () {
    //load table into object
    var $tableRows = $('table td');
    var $tableElements = $tableRows.children();

    console.log($tableRows, $tableElements);

    $('#search').on('keyup', function (e) {
        var searchText = $(this).val();

        if (searchText.length == 0) {
            // catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
            removeHighlight(); // remove last remaining highlight
            return;
        }
        //findTextInTable($tableElements, searchText);

        highlightTextInTable($tableElements, searchText);

    });
});

})();

Body:
Using toLowerCase() you can achieve it :

if (searchText.toLowerCase() == $el.text().toLowerCase()) {
    // found the entry
   // console.log("matched");
   matched = true;
}


问:
ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8
I recently upgraded from Visual Studio 2010 to the Visual Studio 2012 RC. The installer also installs IIS 8 Express which Visual Studio now uses as the default web server.

IIS 8 is blocking my WEB API requests that use PUT AND DELETE verbs. IIS returns a 405 error, The requested resource does not support http method 'PUT'.

I know people have issues with this in the past and there are several messages about it on Stack Overflow. With IIS 7 Express the solution was to uninstall WebDav. Unfortunately I don't see any way to do that with IIS 8.

I've tried editing out the WebDav sections from applicationhost.config but that hasn't helped. For example I removed <add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /> from the config file.

I've spent far too long on this. There must be a simple way to enable PUT and DELETE?

答:
In IIS 8.5/ Windows 2012R2, Nothing mentioned here worked for me.
I don't know what is meant by Removing WebDAV but that didn't solve the issue for me.

What helped me is the below steps;

I went to IIS manager.

In the left panel selected the site.

In the left working area, selected the WebDAV, Opened it double clicking.

In the right most panel, disabled it.

Now everything is working.


问:
Best way of CSS override?
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

```<code>.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}
</code>```

2. example

```<code>.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}
</code>```

Which is one best way overriding, example 1 or example 2. if any advantages?

答:
There is really not much of a difference because compiling css is really easy for todays machines. But from what i know if you use it as example 1, it wouldnt look into .custom .ex1 because .ex1 has already been defined.

But as i said, it does not really matter. Its like going to police because someone took tiny dust of your sugar

Title: Best way of CSS override?

Body:
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}

2. example

.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

Which is one best way overriding, example 1 or example 2. if any advantages?