问:
Select data in array between start and end date
I have script that show markers on heatmap

Here is script

```<code>    function getDriving() {
    markers.length = 0;
    var todayval = new Date();
    var url = $('#map').data('request-url2');
    $.getJSON(url,
        function (data) {
            $.each(data,
                function (i, item) {

                    markers.push({
                        'location': new google.maps.LatLng(item.Latitude, item.Longitude),
                        'map': map,
                        'weight': item.Speed,
                        'radius': 10,
                        'date': item.CurrentDateTime,
                        'imei': item.Imei
                    });
                });

            $.each(markers, function (i, marker) {
                var getDate = marker.date.match(/\d/g).join('');
                var markerDate = new Date(parseFloat(getDate));
                console.log(markerDate);
                if (markerDate.getDate() === todayval.getDate()) {
                    todaymarkersfiltered.push(marker);
                }
            });
            var pointArray = new google.maps.MVCArray(todaymarkersfiltered);
            console.log(pointArray);
            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });
};
</code>```

In View I have startDate and EndDate

Now I filter only by startDate.

Here is script

```<code> filtered.length = 0;
$('#filter').on('click',
    function () {
        heatmap.setMap(null);
        var startValue = $('#startDate').val().split("/");
        $.each(markers, function (i,marker) {
            var getDate = marker.date.match(/\d/g).join('');
            var markerDate = new Date(parseFloat(getDate));
            var valDate = new Date(startValue[2], startValue[1] - 1, startValue[0]);
            if (markerDate.getDate() === valDate.getDate() && (marker.imei === imei || imei === null)) {
                filtered.push(marker);
            }
        });
        var pointArray = new google.maps.MVCArray(filtered);
        console.log(pointArray);
        heatmap = new google.maps.visualization.HeatmapLayer({
            data: pointArray
        });
        heatmap.setMap(map);

    }); //filtering by date and imei code of device
</code>```

But how I can filter data between start and end date.

SO for example I have start date 11/14/2017 and end date 11/16/2017. I need to show all data where markerDate in this range. end data will be taken from input too. Like this var endValue = $('#endDate').val().split("/");

Thank's for help.

答:
You can simply use .filter() method to do this:

```<code>var startValue = new Date($('#startDate').val());
var endValue = new Date($('#endDate').val());

var filtered = markers.filter(function(marker) {
  var markerDate = new Date(marker.date);
  return (markerDate > startValue && markerDate < endValue);
});
</code>```

Body:
I have script that show markers on heatmap

Here is script

    function getDriving() {
    markers.length = 0;
    var todayval = new Date();
    var url = $('#map').data('request-url2');
    $.getJSON(url,
        function (data) {
            $.each(data,
                function (i, item) {

                    markers.push({
                        'location': new google.maps.LatLng(item.Latitude, item.Longitude),
                        'map': map,
                        'weight': item.Speed,
                        'radius': 10,
                        'date': item.CurrentDateTime,
                        'imei': item.Imei
                    });
                });

            $.each(markers, function (i, marker) {
                var getDate = marker.date.match(/\d/g).join('');
                var markerDate = new Date(parseFloat(getDate));
                console.log(markerDate);
                if (markerDate.getDate() === todayval.getDate()) {
                    todaymarkersfiltered.push(marker);
                }
            });
            var pointArray = new google.maps.MVCArray(todaymarkersfiltered);
            console.log(pointArray);
            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });
};

In View I have startDate and EndDate

Now I filter only by startDate.

Here is script

 filtered.length = 0;
$('#filter').on('click',
    function () {
        heatmap.setMap(null);
        var startValue = $('#startDate').val().split("/");
        $.each(markers, function (i,marker) {
            var getDate = marker.date.match(/\d/g).join('');
            var markerDate = new Date(parseFloat(getDate));
            var valDate = new Date(startValue[2], startValue[1] - 1, startValue[0]);
            if (markerDate.getDate() === valDate.getDate() && (marker.imei === imei || imei === null)) {
                filtered.push(marker);
            }
        });
        var pointArray = new google.maps.MVCArray(filtered);
        console.log(pointArray);
        heatmap = new google.maps.visualization.HeatmapLayer({
            data: pointArray
        });
        heatmap.setMap(map);

    }); //filtering by date and imei code of device

But how I can filter data between start and end date.

SO for example I have start date 11/14/2017 and end date 11/16/2017. I need to show all data where markerDate in this range. end data will be taken from input too. Like this var endValue = $('#endDate').val().split("/");

Thank's for help.

Body:
You can simply use .filter() method to do this:

var startValue = new Date($('#startDate').val());
var endValue = new Date($('#endDate').val());

var filtered = markers.filter(function(marker) {
  var markerDate = new Date(marker.date);
  return (markerDate > startValue && markerDate < endValue);
});


来源: stackexchange

问:
How can I export an mp3 file from an iOS device's iPod library?
In my iOS application I'm trying to export an mp3 file from the iPod library to the app's documents directory on the device.  Currently I'm trying to use AVAssetExportSession but it's not working for mp3 files.  It works well for m4a files.

Is exporting an mp3 file possible using AVAssetExportSession?

What is the appropriate outputFileType for AVAssetExportSession? (AVFileTypeAppleM4A works for m4a files)

Thanks!

答:
here code that will help you to export an mp4 from music library</p>

```<code>func displayMediaPicker() {
        let mediaPicker = MPMediaPickerController.init(mediaTypes: .anyAudio)
        mediaPicker.delegate = self
        mediaPicker.allowsPickingMultipleItems = false
        mediaPicker.loadView();
        self.present(mediaPicker, animated: true, completion: nil)
    }

func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
        //
        self.dismiss(animated:true)

        if mediaItemCollection.count > 0 {

            let mediaItem = mediaItemCollection.items[0]
            let assetURL = mediaItem.value(forProperty: MPMediaItemPropertyAssetURL)
            let mediaAsset = AVURLAsset(url: assetURL as! URL, options: nil)

            let exporter = AVAssetExportSession.init(asset: mediaAsset, presetName: AVAssetExportPresetMediumQuality)
            exporter?.outputFileType = AVFileType.mp4

            let mediaPathToSave = //assign destination path here

            let exportURL = URL(fileURLWithPath: mediaPathToSave)
            exporter?.outputURL = exportURL

            // if incase you need first 30 seconds
            let startTime = CMTimeMake(0, 1)
            let stopTime = CMTimeMake(30, 1)
            let exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
            exporter?.timeRange = exportTimeRange

            exporter?.exportAsynchronously(completionHandler: {
                //
                let status = exporter?.status

                if status == AVAssetExportSessionStatus.completed {

                    print("AVAssetExportSessionStatus successfull")
                    //do further code for exported file here
                }
            })
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
here code that will help you to export an mp4 from music library

func displayMediaPicker() {
        let mediaPicker = MPMediaPickerController.init(mediaTypes: .anyAudio)
        mediaPicker.delegate = self
        mediaPicker.allowsPickingMultipleItems = false
        mediaPicker.loadView();
        self.present(mediaPicker, animated: true, completion: nil)
    }

func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
        //
        self.dismiss(animated:true)

        if mediaItemCollection.count > 0 {

            let mediaItem = mediaItemCollection.items[0]
            let assetURL = mediaItem.value(forProperty: MPMediaItemPropertyAssetURL)
            let mediaAsset = AVURLAsset(url: assetURL as! URL, options: nil)

            let exporter = AVAssetExportSession.init(asset: mediaAsset, presetName: AVAssetExportPresetMediumQuality)
            exporter?.outputFileType = AVFileType.mp4

            let mediaPathToSave = //assign destination path here

            let exportURL = URL(fileURLWithPath: mediaPathToSave)
            exporter?.outputURL = exportURL

            // if incase you need first 30 seconds
            let startTime = CMTimeMake(0, 1)
            let stopTime = CMTimeMake(30, 1)
            let exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
            exporter?.timeRange = exportTimeRange

            exporter?.exportAsynchronously(completionHandler: {
                //
                let status = exporter?.status

                if status == AVAssetExportSessionStatus.completed {

                    print("AVAssetExportSessionStatus successfull")
                    //do further code for exported file here
                }
            })
        }
    }


问:
C++ variadic expansion using deduction
I'm developing a library that deals with non typed C functions (SQLite) and I want to strong typing it.

The idea is to have a FieldDef strong type that allow user to tie raw types like int, double and std::string to weak db types.
My problem is that the semantic of the library is very heavy, and I would like to add some automatic type deduction.

So I have a bunch of "basic types":

```<code>namespace FieldType {
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
  struct Blob{ using rawtype = std::vector<uint8_t>; };
}
</code>```

I also have a insert and a query functions that allow inserting and querying the tables without using SQL statements. The query will be plain select. Anyway. The intended use is:

```<code>FieldDef<FieldType::Integer> mId = makeFieldDef("id", FieldType::Integer()).primaryKey().autoincrement();
FieldDef<FieldType::Text> mName = makeFieldDef("name", FieldType::Text());
FieldDef<FieldType::Integer> mValue = makeFieldDef("value", FieldType::Integer());

SQLiteTable::insert(std::make_tuple(mName, mValue), std::make_tuple(record.name, record.value));

std::vector<Record> r;
SQLiteTable::query
            (std::make_tuple(mName, mValue), [&r](std::tuple<std::string, int> res) {
        r.push_back(Record{std::get<0>(res), std::get<1>(res)});
});
</code>```

I implemented the insert this way:

```<code>template <typename ...Ts, typename ...Us>
bool insert (std::tuple<Ts...> def, std::tuple<Us...> values) {
    std::ostringstream ss;
    ss << "INSERT INTO " << mName << "("
                                  << buildSqlInsertFieldList<0>(def)
                                  << ") VALUES ("
                                  << buildSqlInsertValuesListPlaceholder<0>(values)
                                  << ");";
    auto stmt = newStatement(ss.str());
    bindAllValues<0>(stmt.get(), values);
    return execute(stmt.get());
}
</code>```

This works fine, the problems come with query:

```<code>template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
   ...
}
</code>```

When calling it the compiler is unable to correctly deduce the types, so I guess it requires a pedantic construction:

```<code>SQLiteTable::query<FieldType::Text, FieldType::Integer, /* whatever */> (...)
</code>```

It's unpractical and verbose.

Would it be possible to simplify the query function?
Since we have a constrain in the usage, that is the Us pack can only be some type compatible with FieldType::*:rawtype, I am asking if it would be possible to use some construct that unpacks and apply a method. In case of insert, could it be simplified with something like:

```<code>template<typename Ts...>
bool insert (std::tuple<Ts...> def, std::tuple<Ts::rawtype ...> values)
</code>```

instead of using tuples, what about using Variadic Packs? I haven't tested it but I fear that using something like

```<code>template<typename Ts..., typename Us....>
bool insert (Ts... def, Us ... values)
</code>```

would confuse the compiler and would make things worse.
What do you think?

If it is possible to use the actual implementation of query, what would be a workaround to make the usage code more expressive?

Here are some details about the code, to explain:

The query function is implemented using the following pseudocode:

```<code>template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
    std::ostringstream ss;
    ss << "SELECT " << buildSqlInsertFieldList<0>(def) << " FROM " << mName <<";";
    auto stmt = newStatement(ss.str());

    auto r = execute(stmt.get());
    SQLiteException::throwIfNotOk(r, db()->handle());

    while (hasData(stmt.get())) {
        auto nColumns = columnCount(stmt.get());
        if (nColumns != sizeof...(Ts))
            throw std::runtime_error("Column count differs from data size");

        std::tuple<Us...> res;
        getAllValues<0>(stmt.get(), res);
        resultFeedbackFunc(res);
    }
};
</code>```

Statement is an opaque type that hides the sqlite statement structure, as do the other functions used in the query method newStatement, execute and columnsCount. The function getAllValues uses recursion to fill the tuple. So the functor resultFeedbackFunc() will be called for every row of the database. So the client code can, for example, fill a container (like a vector).

Update:

I followed  @bolov's solution, and added @massimiliano-jones's improvements.

This is the correct implementation of the inner call to the feedback function:

```<code>resultFeedbackFunc(getValueR<decltype (std::get<Is>(def).rawType())>
      (stmt.get(), Is)...);
</code>```

getValueR makes the internal call to sqlite_column_xxx(sqlite3_stmt *, int index). If I understand correctly, the unpacking works because the arguments list is a valid context for unpacking. If I wanted the calls to be made outside the arguments, I had to make a folding (or workaround since I'm using c++11).

答:
It's difficult to give specific help as there are important code parts missing from your post.

However here are my 2 cents. Please note I've filled with my imagination the missing parts of your code.

First of all you need to get rid of the std::function argument. Use std::function only if you need the type erasure it provides. In your case (at least from the code you've shown) you don't need it. So we replace that with a simple template <class F> parameter. This solves the deduction problem.

Now when you pass an invalid function object you will get a compilation error deep in the bowls of your query implementation. If you don't want that and you want to fail fast, then there are some options. I chose to show you a SFINAE approach with decltype.

```<code>namespace FieldType
{
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
};

template <class FT>
struct FieldDef
{
    using Type = FT;
    using RawTye = typename Type::rawtype;

    auto getRaw() -> RawTye { return {}; }
};

template <class... Args, class F, std::size_t... Is>
auto query_impl(std::tuple<Args...> def, F f, std::index_sequence<Is...>)
    -> decltype(f(std::get<Is>(def).getRaw()...), std::declval<void>())
{
   f(std::get<Is>(def).getRaw()...);
}

template <class... Args, class F>
auto query(std::tuple<Args...> def, F f)
    -> decltype(query_impl(def, f, std::make_index_sequence<sizeof...(Args)>{}))
{
   query_impl(def, f, std::make_index_sequence<sizeof...(Args)>{});
}
</code>```

```<code>auto test()
{
    FieldDef<FieldType::Text> mName = {};
    FieldDef<FieldType::Integer> mValue = {};

    query(std::make_tuple(mName, mValue), [](std::string, int) {});      // OK

    query(std::make_tuple(mName, mValue), [](std::string, int, int) {}); // Error
    query(std::make_tuple(mName, mValue), [](int, int) {});              // Error
}
</code>```

The invalid calls fail with a message akin to:

```<code>error: no matching function for call to 'query'
...
note: candidate template ignored: substitution failure [with Args = ...]:
  no matching function for call to 'query_impl'
...
</code>```

Regarding your point 2. That would be not deductible. And even if it would be, you want to group the parameters for readability. I.e. you want insert({a, b}, {c, d}) instead of insert(a, b, c, d).

I don't understand your point 3.

Title: C++ variadic expansion using deduction

Body:
I'm developing a library that deals with non typed C functions (SQLite) and I want to strong typing it.

The idea is to have a FieldDef strong type that allow user to tie raw types like int, double and std::string to weak db types.
My problem is that the semantic of the library is very heavy, and I would like to add some automatic type deduction.

So I have a bunch of "basic types":

namespace FieldType {
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
  struct Blob{ using rawtype = std::vector<uint8_t>; };
}

I also have a insert and a query functions that allow inserting and querying the tables without using SQL statements. The query will be plain select. Anyway. The intended use is:

FieldDef<FieldType::Integer> mId = makeFieldDef("id", FieldType::Integer()).primaryKey().autoincrement();
FieldDef<FieldType::Text> mName = makeFieldDef("name", FieldType::Text());
FieldDef<FieldType::Integer> mValue = makeFieldDef("value", FieldType::Integer());

SQLiteTable::insert(std::make_tuple(mName, mValue), std::make_tuple(record.name, record.value));

std::vector<Record> r;
SQLiteTable::query
            (std::make_tuple(mName, mValue), [&r](std::tuple<std::string, int> res) {
        r.push_back(Record{std::get<0>(res), std::get<1>(res)});
});

I implemented the insert this way:

template <typename ...Ts, typename ...Us>
bool insert (std::tuple<Ts...> def, std::tuple<Us...> values) {
    std::ostringstream ss;
    ss << "INSERT INTO " << mName << "("
                                  << buildSqlInsertFieldList<0>(def)
                                  << ") VALUES ("
                                  << buildSqlInsertValuesListPlaceholder<0>(values)
                                  << ");";
    auto stmt = newStatement(ss.str());
    bindAllValues<0>(stmt.get(), values);
    return execute(stmt.get());
}

This works fine, the problems come with query:

template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
   ...
}

When calling it the compiler is unable to correctly deduce the types, so I guess it requires a pedantic construction:

SQLiteTable::query<FieldType::Text, FieldType::Integer, /* whatever */> (...)

It's unpractical and verbose.

Would it be possible to simplify the query function?
Since we have a constrain in the usage, that is the Us pack can only be some type compatible with FieldType::*:rawtype, I am asking if it would be possible to use some construct that unpacks and apply a method. In case of insert, could it be simplified with something like:

template<typename Ts...>
bool insert (std::tuple<Ts...> def, std::tuple<Ts::rawtype ...> values)

instead of using tuples, what about using Variadic Packs? I haven't tested it but I fear that using something like

template<typename Ts..., typename Us....>
bool insert (Ts... def, Us ... values)

would confuse the compiler and would make things worse.
What do you think?

If it is possible to use the actual implementation of query, what would be a workaround to make the usage code more expressive?

Here are some details about the code, to explain:

The query function is implemented using the following pseudocode:

template <typename ...Ts, typename ...Us>
void query(std::tuple<Ts...> def, std::function<void(std::tuple<Us...>)> resultFeedbackFunc) {
    std::ostringstream ss;
    ss << "SELECT " << buildSqlInsertFieldList<0>(def) << " FROM " << mName <<";";
    auto stmt = newStatement(ss.str());

    auto r = execute(stmt.get());
    SQLiteException::throwIfNotOk(r, db()->handle());

    while (hasData(stmt.get())) {
        auto nColumns = columnCount(stmt.get());
        if (nColumns != sizeof...(Ts))
            throw std::runtime_error("Column count differs from data size");

        std::tuple<Us...> res;
        getAllValues<0>(stmt.get(), res);
        resultFeedbackFunc(res);
    }
};

Statement is an opaque type that hides the sqlite statement structure, as do the other functions used in the query method newStatement, execute and columnsCount. The function getAllValues uses recursion to fill the tuple. So the functor resultFeedbackFunc() will be called for every row of the database. So the client code can, for example, fill a container (like a vector).

Update:

I followed  @bolov's solution, and added @massimiliano-jones's improvements.

This is the correct implementation of the inner call to the feedback function:

resultFeedbackFunc(getValueR<decltype (std::get<Is>(def).rawType())>
      (stmt.get(), Is)...);

getValueR makes the internal call to sqlite_column_xxx(sqlite3_stmt *, int index). If I understand correctly, the unpacking works because the arguments list is a valid context for unpacking. If I wanted the calls to be made outside the arguments, I had to make a folding (or workaround since I'm using c++11).

Body:
It's difficult to give specific help as there are important code parts missing from your post.

However here are my 2 cents. Please note I've filled with my imagination the missing parts of your code.

First of all you need to get rid of the std::function argument. Use std::function only if you need the type erasure it provides. In your case (at least from the code you've shown) you don't need it. So we replace that with a simple template <class F> parameter. This solves the deduction problem.

Now when you pass an invalid function object you will get a compilation error deep in the bowls of your query implementation. If you don't want that and you want to fail fast, then there are some options. I chose to show you a SFINAE approach with decltype.

namespace FieldType
{
  struct Integer { using rawtype = int; };
  struct Real{ using rawtype = double; };
  struct Text{ using rawtype = std::string; };
};

template <class FT>
struct FieldDef
{
    using Type = FT;
    using RawTye = typename Type::rawtype;

    auto getRaw() -> RawTye { return {}; }
};

template <class... Args, class F, std::size_t... Is>
auto query_impl(std::tuple<Args...> def, F f, std::index_sequence<Is...>)
    -> decltype(f(std::get<Is>(def).getRaw()...), std::declval<void>())
{
   f(std::get<Is>(def).getRaw()...);
}

template <class... Args, class F>
auto query(std::tuple<Args...> def, F f)
    -> decltype(query_impl(def, f, std::make_index_sequence<sizeof...(Args)>{}))
{
   query_impl(def, f, std::make_index_sequence<sizeof...(Args)>{});
}

auto test()
{
    FieldDef<FieldType::Text> mName = {};
    FieldDef<FieldType::Integer> mValue = {};

    query(std::make_tuple(mName, mValue), [](std::string, int) {});      // OK

    query(std::make_tuple(mName, mValue), [](std::string, int, int) {}); // Error
    query(std::make_tuple(mName, mValue), [](int, int) {});              // Error
}

The invalid calls fail with a message akin to:

error: no matching function for call to 'query'
...
note: candidate template ignored: substitution failure [with Args = ...]:
  no matching function for call to 'query_impl'
...

Regarding your point 2. That would be not deductible. And even if it would be, you want to group the parameters for readability. I.e. you want insert({a, b}, {c, d}) instead of insert(a, b, c, d).

I don't understand your point 3.


问:
EmberJS - {{moment-format 'date' 'output' 'input'}} repeats todays date in every row when used in {{#each} block
I am using ember-moment addon in order to format the dates in the following table:

```<code><tbody>
  {{#each model as |model|}}
    <tr class="clickable-row">
      <td>{{model.id}}</td>
      <td>{{model.first_name}}</td>
      <td>{{model.last_name}}</td>
      <td>{{model.date_of_birth}}</td>
      <td>{{model.inserted_at}}</td>
      <td>{{model.departed_at}}</td>
    </tr>
  {{/each}}
</tbody>
</code>```

date_of_birth property returned from the DB ha the following format:

```<code>yyyy-mm-ddThh:mm:ss+|-hhmm
</code>```

When I try to format it like below;

```<code>{{moment-format 'model.date_of_birth' 'DD/MM/YYYY' 'yyyy-mm-ddThh:mm:ss+|-hhmm' }}
</code>```

I end up with a populated table full of unique rows, except the date of birth is just today's date on every single row.

I know I am missing something obvious and someone out there is going to make me look very silly!

答:
You should pass binding date object to the helper instead of passing its name as a string. Therefore use it like this:</p>

```<code>{{moment-format model.date_of_birth 'DD/MM/YYYY' }}
</code>```

Body:
I am using ember-moment addon in order to format the dates in the following table:

  {{#each model as |model|}}

      {{model.id}}
      {{model.first_name}}
      {{model.last_name}}
      {{model.date_of_birth}}
      {{model.inserted_at}}
      {{model.departed_at}}

  {{/each}}

date_of_birth property returned from the DB ha the following format:

yyyy-mm-ddThh:mm:ss+|-hhmm

When I try to format it like below;

{{moment-format 'model.date_of_birth' 'DD/MM/YYYY' 'yyyy-mm-ddThh:mm:ss+|-hhmm' }}

I end up with a populated table full of unique rows, except the date of birth is just today's date on every single row.

I know I am missing something obvious and someone out there is going to make me look very silly!

Body:
You should pass binding date object to the helper instead of passing its name as a string. Therefore use it like this:

{{moment-format model.date_of_birth 'DD/MM/YYYY' }}


问:
linear-gradient IE11 white space issue
I'm trying to build a css framework for myself for some status boxes on my site.

I have put up an example here:

https://jsfiddle.net/ravcg28r/

```<code>    background: -moz-linear-gradient(    left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -webkit-linear-gradient( left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -o-linear-gradient(      left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: linear-gradient(     to right,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#aeaeae', endColorstr='#aeaeae',GradientType=1 );
</code>```

It works really well in chrome and ff, but in IE 11 my linear gradient doesn't quite fill my span and I get an annoying little white space appearing around the border, see image and note the white space in the green box above the icon.

Does anyone know how to prevent this?

linear gradient issue in IE11

答:
Seems you are using two Class into one, which can be confused. IE11 can be a nightmare but I have fixed it, and it should be ok on Ie11.

as you can see it on the
https://www.codeply.com/go/8gTRzBR8Qd

Your code is

```<code><tr>
<td><span class="sb sb-check sb-red">Some information</span></td>
<td><span class="sb sb-check sb-red">Some information</span></td>
</tr>
</code>```

I  change it, There is two similar class with sb and sb-red, so it better to remove one of them. I have changed some of the CSS as well.

```<code><tr>
<td><span class="sb-red sb-check">Some information</span></td>
<td><span class="sb sb-check sb-red">Some information</span></td>
</tr>
</code>```

Title: linear-gradient IE11 white space issue

Body:
I'm trying to build a css framework for myself for some status boxes on my site.

I have put up an example here:

https://jsfiddle.net/ravcg28r/

    background: -moz-linear-gradient(    left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -webkit-linear-gradient( left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -o-linear-gradient(      left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: linear-gradient(     to right,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#aeaeae', endColorstr='#aeaeae',GradientType=1 );

It works really well in chrome and ff, but in IE 11 my linear gradient doesn't quite fill my span and I get an annoying little white space appearing around the border, see image and note the white space in the green box above the icon.

Does anyone know how to prevent this?

linear gradient issue in IE11

Body:
Seems you are using two Class into one, which can be confused. IE11 can be a nightmare but I have fixed it, and it should be ok on Ie11.

as you can see it on the
https://www.codeply.com/go/8gTRzBR8Qd

Your code is

<tr>
<td><span class="sb sb-check sb-red">Some information</span></td>
<td>&lt;span class=&quot;sb sb-check sb-red&quot;&gt;Some information&lt;/span&gt;</td>
</tr>

I  change it, There is two similar class with sb and sb-red, so it better to remove one of them. I have changed some of the CSS as well.

<tr>
<td><span class="sb-red sb-check">Some information</span></td>
<td>&lt;span class="sb sb-check sb-red"&gt;Some information&lt;/span&gt;</td>
</tr>


问:
SyntaxError: Unexpected end of input in Angular 5 service
I know that it is a common problem, but I still don't understand why it is reproduced in my case.  Сouldn't find an answer in a few days.

Folowing a part of the Angular service:

```<code>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Response, RequestOptionsArgs, ResponseContentType } from '@angular/http';
import { Http, RequestOptions, Request, RequestMethod, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

@Injectable()
export class BaseService {
    private headers: Headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Data-Type': 'json' });

    constructor(private http: Http, private router: Router, ) {
    }

    public get<T>(url: string, options?: RequestOptionsArgs): Promise<T> {
        return this.http.get(url, options)
            .toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError.bind(this));
    }

    public handleError(error: any) {
        if (error.status === 400) {
            switch (error.statusText) {
                case 'Authentication':
                    this.router.navigate(['/error/auth']);
                    break;
                default:
                    return Promise.reject(error);
            }
            return;
        }
        return Promise.reject(error.toString());
    }
}
</code>```

Folowing method called base method:

```<code>getSearchResultTable(hash: number): Promise<Prices[]> {
    const tmp = this.baseService.get<Prices[]>(this.apiUrl + hash);
     return tmp;
}
</code>```

Json that's returned from server is valid. I checked it one some online service.

But I see SyntaxError: Unexpected end of input error in Response when trying to debug.

Call Stack:

```<code>SyntaxError: Unexpected end of input
    at BaseService.get (webpack-internal:///../../../../../src/app/search-module/services/base.service.ts:36:14)
    at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:30:36)
    at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:24:34)
    at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)
    at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)
    at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)
    at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)
    at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)
    at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)
    at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)
</code>```

I'm using latest version of Angular.

答:
From angular latest update:

remove any map(res => res.json()) calls, which are no longer needed.

So try to remove .json() from .then(response => response.json() as T).

Body:
I know that it is a common problem, but I still don't understand why it is reproduced in my case.  Сouldn't find an answer in a few days.

Folowing a part of the Angular service:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Response, RequestOptionsArgs, ResponseContentType } from '@angular/http';
import { Http, RequestOptions, Request, RequestMethod, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

@Injectable()
export class BaseService {
    private headers: Headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Data-Type': 'json' });

    constructor(private http: Http, private router: Router, ) {
    }

    public get<T>(url: string, options?: RequestOptionsArgs): Promise<T> {
        return this.http.get(url, options)
            .toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError.bind(this));
    }

    public handleError(error: any) {
        if (error.status === 400) {
            switch (error.statusText) {
                case 'Authentication':
                    this.router.navigate(['/error/auth']);
                    break;
                default:
                    return Promise.reject(error);
            }
            return;
        }
        return Promise.reject(error.toString());
    }
}

Folowing method called base method:

getSearchResultTable(hash: number): Promise<Prices[]> {
    const tmp = this.baseService.get<Prices[]>(this.apiUrl + hash);
     return tmp;
}

Json that's returned from server is valid. I checked it one some online service.

But I see SyntaxError: Unexpected end of input error in Response when trying to debug.

Call Stack:

SyntaxError: Unexpected end of input
    at BaseService.get (webpack-internal:///../../../../../src/app/search-module/services/base.service.ts:36:14)
    at SearchResultService.getSearchResultTable (webpack-internal:///../../../../../src/app/search-module/services/search-result.service.ts:30:36)
    at SearchResultPageComponent.ngOnInit (webpack-internal:///../../../../../src/app/search-module/pages/search-result/search-result.component.ts:24:34)
    at checkAndUpdateDirectiveInline (webpack-internal:///../../../core/esm5/core.js:12291:19)
    at checkAndUpdateNodeInline (webpack-internal:///../../../core/esm5/core.js:13794:20)
    at checkAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:13737:16)
    at debugCheckAndUpdateNode (webpack-internal:///../../../core/esm5/core.js:14609:76)
    at debugCheckDirectivesFn (webpack-internal:///../../../core/esm5/core.js:14550:13)
    at Object.eval [as updateDirectives] (ng:///SearchModule/SearchResultPageComponent_Host.ngfactory.js:9:5)
    at Object.debugUpdateDirectives [as updateDirectives] (webpack-internal:///../../../core/esm5/core.js:14535:21)

I'm using latest version of Angular.


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答:
That's how string concatenation works.

If you need to avoid concatenating the word "null" you can do:

```<code>String s3 = (s1==null?"":s1) + (s2==null?"":s2);
</code>```

ContentLicense: CC BY-SA 2.5

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull

Body:
That's how string concatenation works.

If you need to avoid concatenating the word "null" you can do:

String s3 = (s1==null?"":s1) + (s2==null?"":s2);


问:
Sort integers and strings using the same java class (Bubble Sort)
How do I amend my code for bubble sorting integers so I can re-use it for strings too? Or do I need to create a completely new class for sorting strings exclusively. Thanks!

MAIN CLASS:

```<code>public class BubbleSortTest {

    public static void main(String[] args) {
        Integer[] integers = {25, 15, 45, 5, 40, 50, 10, 20, 35, 30};
        ArrayUtility.display(integers);
        BubbleSort.sort(integers);
        ArrayUtility.display(integers);

        String[] strings = {"def", "efg", "bcd", "abc", "fgh", "cde", null};
        ArrayUtility.display(strings);
        BubbleSort.sort(strings);
        ArrayUtility.display(strings);
    }
}
</code>```

SORT CLASS:

```<code>public class BubbleSort {

    public static void sort(Integer[] numbers) {
        Integer temp;

        for (Integer i = 0; i < numbers.length; i++) {
            for (Integer j = 1; j < (numbers.length) - i; j++) {
                if (numbers[j - 1] > numbers[j]) {

                    //SWAPPING ELEMENTS
                    temp = numbers[j - 1];
                    numbers[j - 1] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
    }
}
</code>```

答:
You can use Generic Types:

Something like this could be valid:

```<code>public static <E extends Comparable<E>> void bubbleSort(E[] unsorted) {
        for(int iter =1; iter< unsorted.length; iter++){
            for(int inner = 0; inner < (unsorted.length - iter); inner ++){
                if(unsorted[inner].compareTo(unsorted[inner+1]) > 0){
                    E tmp = unsorted[inner];
                    unsorted[inner] = unsorted[inner + 1];
                    unsorted[inner + 1] = tmp;
                }
            }
        }
    }
</code>```

What this means is, the method works with an array of any type, as long as it implements Comparable. Whatever type that is, will be used as E throughout the method. Since the compiler knows that E is a Comparable, the compiler knows that objects of this type have .compareTo(...).

Body:
How do I amend my code for bubble sorting integers so I can re-use it for strings too? Or do I need to create a completely new class for sorting strings exclusively. Thanks!

MAIN CLASS:

public class BubbleSortTest {

    public static void main(String[] args) {
        Integer[] integers = {25, 15, 45, 5, 40, 50, 10, 20, 35, 30};
        ArrayUtility.display(integers);
        BubbleSort.sort(integers);
        ArrayUtility.display(integers);

        String[] strings = {"def", "efg", "bcd", "abc", "fgh", "cde", null};
        ArrayUtility.display(strings);
        BubbleSort.sort(strings);
        ArrayUtility.display(strings);
    }
}

SORT CLASS:

public class BubbleSort {

    public static void sort(Integer[] numbers) {
        Integer temp;

        for (Integer i = 0; i < numbers.length; i++) {
            for (Integer j = 1; j < (numbers.length) - i; j++) {
                if (numbers[j - 1] > numbers[j]) {

                    //SWAPPING ELEMENTS
                    temp = numbers[j - 1];
                    numbers[j - 1] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
    }
}

Body:
You can use Generic Types:

Something like this could be valid:

public static <E extends Comparable<E>> void bubbleSort(E[] unsorted) {
        for(int iter =1; iter< unsorted.length; iter++){
            for(int inner = 0; inner < (unsorted.length - iter); inner ++){
                if(unsorted[inner].compareTo(unsorted[inner+1]) > 0){
                    E tmp = unsorted[inner];
                    unsorted[inner] = unsorted[inner + 1];
                    unsorted[inner + 1] = tmp;
                }
            }
        }
    }

What this means is, the method works with an array of any type, as long as it implements Comparable. Whatever type that is, will be used as E throughout the method. Since the compiler knows that E is a Comparable, the compiler knows that objects of this type have .compareTo(...).


问:
How can i merge the two Array JSON nested responses using NODE JS?
1. First response is categories with two fields, category and name.

```<code>categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]
</code>```

2. Second response is commits with three fields, commit, branch and Commit ID.

```<code> commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]
</code>```

3. I want to create one merged JSON, based on the category that would have the following structure:

```<code>all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]
</code>```

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

```<code>exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });
</code>```

答:
Perhaps try the following:

```<code>var all = [];

categories.forEach((e)=>{

  var myIndex = categories.indexOf(e);

  e.body=commits[myIndex];

  all.push(e);

});

console.log(all);
</code>```

You can then use JSON.stringify to get the desired output.

Body:
1. First response is categories with two fields, category and name.

categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]

2. Second response is commits with three fields, commit, branch and Commit ID.

 commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]

3. I want to create one merged JSON, based on the category that would have the following structure:

all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });

Body:
Perhaps try the following:

var all = [];

categories.forEach((e)=>{

  var myIndex = categories.indexOf(e);

  e.body=commits[myIndex];

  all.push(e);

});

console.log(all);

You can then use JSON.stringify to get the desired output.


问:
Use guzzle and promise to create a mailchimp list
Full code: https://github.com/kenpeter/test_guzzle

I try to create a mailchimp list with Guzzle, the http client.

When I am running php create_list_memeber_update.php

Error I got is:

```<code>PHP Fatal error:  Uncaught InvalidArgumentException: Invalid resource type: array in /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/functions.php:116
Stack trace:
#0 /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/Request.php(53): GuzzleHttp\Psr7\stream_for(Array)
#1 /var/www/html/test/testme/test_guzzle/create_list_memeber_update.php(49): GuzzleHttp\Psr7\Request->__construct('POST', Object(GuzzleHttp\Psr7\Uri), Array, Array)
#2 {main}
  thrown in /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/functions.php on line 116
</code>```

I think it is something to do with the headers

```<code>$headers = array(
  'User-Agent' => 'testing/1.0',
  'Accept'     => 'application/json'
);
</code>```

Code for create_list_memeber_update.php:

```<code><?php

// auto load
require 'vendor/autoload.php';

use GuzzleHttp\Psr7\Request;

// opt
$option = array(
  'base_uri' => "https://us12.api.mailchimp.com/3.0/",
  'auth' => ['apikey', '292bae37c631ac3ba03ed0640b44e6c3'],
);

// client
$client = new \GuzzleHttp\Client($option);

// data for a new list
$data = array(
  "name" => "test_mailchimp",
  "contact" => array(
    "company" => "MailChimp",
    "address1" => "675 Ponce De Leon Ave NE",
    "address2" => "Suite 5000",
    "city" => "Atlanta",
    "state" => "GA",
    "zip" => "30308",
    "country" => "US",
    "phone" => "12345678",
  ),
  "permission_reminder" => "You're receiving this email because you signed up for updates.",
  "use_archive_bar" => true,
  "campaign_defaults" => array(
    "from_name" => "test",
    "from_email" => "test@test.com",
    "subject" => "test_subject",
    "language" => "en",
  ),
    "notify_on_subscribe" => "",
    "notify_on_unsubscribe" => "",
    "email_type_option" => true,
    "visibility" => "pub",
);

$headers = array(
  'User-Agent' => 'testing/1.0',
  'Accept'     => 'application/json'
);
$body = ['json' => $data];
$req_create_list = new Request('POST', 'lists', $headers, $body);

// promise
$promise = $client
  ->sendAsync($req_create_list)
  ->then(function ($res) {
    echo $res->getBody();
  });
$promise->wait();
</code>```

答:
This is the solution I found and its working perfectly fine</p>

```<code>    // format for mail chimp data

    --url 'https://usX.api.mailchimp.com/3.0/batches' \
    --user 'anystring:apikey' \
    --header 'content-type: application/json' \
    --data '{"operations" : [{"method" : "POST","path" :
    "lists/624ea08019/members", "body": "
     {\"email_address\":\"freddie@mailchimp.com\",
     \"status\":\"subscribed\"}"},
    //end format

    $userlist = array(format array data)
    $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();
</code>```

Body:
Full code: https://github.com/kenpeter/test_guzzle

I try to create a mailchimp list with Guzzle, the http client.

When I am running php create_list_memeber_update.php

Error I got is:

PHP Fatal error:  Uncaught InvalidArgumentException: Invalid resource type: array in /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/functions.php:116
Stack trace:
#0 /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/Request.php(53): GuzzleHttp\Psr7\stream_for(Array)
#1 /var/www/html/test/testme/test_guzzle/create_list_memeber_update.php(49): GuzzleHttp\Psr7\Request->__construct('POST', Object(GuzzleHttp\Psr7\Uri), Array, Array)
#2 {main}
  thrown in /var/www/html/test/testme/test_guzzle/vendor/guzzlehttp/psr7/src/functions.php on line 116

I think it is something to do with the headers

$headers = array(
  'User-Agent' => 'testing/1.0',
  'Accept'     => 'application/json'
);

Code for create_list_memeber_update.php:

<?php

// auto load
require 'vendor/autoload.php';

use GuzzleHttp\Psr7\Request;

// opt
$option = array(
  'base_uri' => "https://us12.api.mailchimp.com/3.0/",
  'auth' => ['apikey', '292bae37c631ac3ba03ed0640b44e6c3'],
);

// client
$client = new \GuzzleHttp\Client($option);

// data for a new list
$data = array(
  "name" => "test_mailchimp",
  "contact" => array(
    "company" => "MailChimp",
    "address1" => "675 Ponce De Leon Ave NE",
    "address2" => "Suite 5000",
    "city" => "Atlanta",
    "state" => "GA",
    "zip" => "30308",
    "country" => "US",
    "phone" => "12345678",
  ),
  "permission_reminder" => "You're receiving this email because you signed up for updates.",
  "use_archive_bar" => true,
  "campaign_defaults" => array(
    "from_name" => "test",
    "from_email" => "test@test.com",
    "subject" => "test_subject",
    "language" => "en",
  ),
    "notify_on_subscribe" => "",
    "notify_on_unsubscribe" => "",
    "email_type_option" => true,
    "visibility" => "pub",
);

$headers = array(
  'User-Agent' => 'testing/1.0',
  'Accept'     => 'application/json'
);
$body = ['json' => $data];
$req_create_list = new Request('POST', 'lists', $headers, $body);

// promise
$promise = $client
  ->sendAsync($req_create_list)
  ->then(function ($res) {
    echo $res->getBody();
  });
$promise->wait();

Body:
This is the solution I found and its working perfectly fine

    // format for mail chimp data

    --url 'https://usX.api.mailchimp.com/3.0/batches' \
    --user 'anystring:apikey' \
    --header 'content-type: application/json' \
    --data '{"operations" : [{"method" : "POST","path" :
    "lists/624ea08019/members", "body": "
     {\"email_address\":\"freddie@mailchimp.com\",
     \"status\":\"subscribed\"}"},
    //end format

    $userlist = array(format array data)
    $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();


问:
std::runtime_error: resolve: Host not found (authoritative) in boost::asio
The following code:

```<code>using boost::asio::ip::tcp;

std::string ipAddress;

boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(boost::asio::ip::host_name(), "");

tcp::resolver::iterator iter = resolver.resolve(query);
</code>```

results in the following error when run on OS X High Sierra using Xcode 9.1:

```<code>std::runtime_error: resolve: Host not found (authoritative)
</code>```

The value of resolver is:

```<code>(boost::asio::ip::tcp::resolver) resolver = {
  boost::asio::basic_io_object<boost::asio::ip::resolver_service<boost::asio::ip::tcp>, false> = {
    service = 0x00000001023159a0
    implementation = nullptr {
      __ptr_ = 0x0000000000000000
      __cntrl_ = 0x00000001023156c0
    }
  }
}
</code>```

and the value of query is:

```<code>(boost::asio::ip::basic_resolver<boost::asio::ip::tcp, boost::asio::ip::resolver_service<boost::asio::ip::tcp> >::query) query = {
  hints_ = {
    ai_flags = 1024
    ai_family = 0
    ai_socktype = 1
    ai_protocol = 6
    ai_addrlen = 0
    ai_canonname = 0x0000000000000000
    ai_addr = 0x0000000000000000
    ai_next = 0x0000000000000000
  }
  host_name_ = "iMac.local"
  service_name_ = ""
}
</code>```

The resolve function looks like this:

```<code>iterator resolve(const query& q)
{
  boost::system::error_code ec;
  iterator i = this->service.resolve(this->implementation, q, ec);
  boost::asio::detail::throw_error(ec, "resolve");
  return i;
}
</code>```

so I can see that calling resolve with resolver.implementation being a nullptr is what's causing the problem. However, I don't know why it's a nullptr.

This is not a problem on different machines running OS X Yosemite or El Capitan.

答:
Posting an answer in case others have the same problem and end up here.

Finally figured it out, thanks in part to Some programmer dude asking about pinging the host and then searching based on the fact that ping failed.

This post https://discussions.apple.com/thread/7707202?start=0&tstart=0 states that for some reason .local hostname is kept turned off unless any of the sharing services is active.

Turning them on fixed the problem.

Body:
The following code:

using boost::asio::ip::tcp;

std::string ipAddress;

boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(boost::asio::ip::host_name(), "");

tcp::resolver::iterator iter = resolver.resolve(query);

results in the following error when run on OS X High Sierra using Xcode 9.1:

std::runtime_error: resolve: Host not found (authoritative)

The value of resolver is:

(boost::asio::ip::tcp::resolver) resolver = {
  boost::asio::basic_io_object<boost::asio::ip::resolver_service<boost::asio::ip::tcp>, false> = {
    service = 0x00000001023159a0
    implementation = nullptr {
      __ptr_ = 0x0000000000000000
      __cntrl_ = 0x00000001023156c0
    }
  }
}

and the value of query is:

(boost::asio::ip::basic_resolver<boost::asio::ip::tcp, boost::asio::ip::resolver_service<boost::asio::ip::tcp> >::query) query = {
  hints_ = {
    ai_flags = 1024
    ai_family = 0
    ai_socktype = 1
    ai_protocol = 6
    ai_addrlen = 0
    ai_canonname = 0x0000000000000000
    ai_addr = 0x0000000000000000
    ai_next = 0x0000000000000000
  }
  host_name_ = "iMac.local"
  service_name_ = ""
}

The resolve function looks like this:

iterator resolve(const query& q)
{
  boost::system::error_code ec;
  iterator i = this->service.resolve(this->implementation, q, ec);
  boost::asio::detail::throw_error(ec, "resolve");
  return i;
}

so I can see that calling resolve with resolver.implementation being a nullptr is what's causing the problem. However, I don't know why it's a nullptr.

This is not a problem on different machines running OS X Yosemite or El Capitan.


问:
Javafx image is not found
i have this code in my JavaFX code

```<code>Image arrowRight = new Image("/Users/murad/Desktop/arrowright.png");
ImageView arrowRightv = new ImageView(arrowRight);
</code>```

My goal is to find the image that is on my desktop and then to put it on the screen.But this code returns me this error:

```<code>java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62
)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl
.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherIm
pl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:
328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62
)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl
.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java
:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Launche
rImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at Kanban.start(Kanban.java:152)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Launch
erImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.j
ava:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:29
5)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.jav
a:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java
:95)
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:600)
    at java.net.URL.<init>(URL.java:490)
    at java.net.URL.<init>(URL.java:439)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 8 more
</code>```

I tried doing what i did above with FileInputStream,but that didn't work.Also i got the url from Mac,so it's definitely not wrong.
What am i doing wrong?

答:
The parameter is an URL,

```<code>"file:/Users/murad/Desktop/arrowright.png"
</code>```

The error show that you were on Windows with "c:/...." - hence the error that no protocol c exists. ("file:///c:/...").

Title: Javafx image is not found

Body:
i have this code in my JavaFX code

Image arrowRight = new Image("/Users/murad/Desktop/arrowright.png");
ImageView arrowRightv = new ImageView(arrowRight);

My goal is to find the image that is on my desktop and then to put it on the screen.But this code returns me this error:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62
)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl
.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherIm
pl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:
328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62
)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl
.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java
:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Launche
rImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at Kanban.start(Kanban.java:152)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Launch
erImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.j
ava:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:29
5)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.jav
a:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java
:95)
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:600)
    at java.net.URL.<init>(URL.java:490)
    at java.net.URL.<init>(URL.java:439)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 8 more

I tried doing what i did above with FileInputStream,but that didn't work.Also i got the url from Mac,so it's definitely not wrong.
What am i doing wrong?

Body:
The parameter is an URL,

"file:/Users/murad/Desktop/arrowright.png"

The error show that you were on Windows with "c:/...." - hence the error that no protocol c exists. ("file:///c:/...").


问:
Pass variable from custom Laravel Helpers to Blade file
I'm trying to create a helper to centralize a complicated Form::select.

My helper:

```<code>namespace App\Helpers;
use Log;
use App\Countries;

class Address {
    public static function country() {
        $countries = Countries::orderby('name_zh','asc');
        $form = "Form::select('countries', \$countries);";
        return $form;
    }
}
</code>```

My View:

```<code>{!! Address::country() !!}
</code>```

I would like to have this select form with $countries variable from this helper and show a Dropdown list on my view. How do I do it?

答:
Not sure to really understand your question...

But if you want to pass your $countries variable to your view, your function have to simply return this variable.

```<code>public static function country()
{
    $countries = ...;
    return $countries;
}
</code>```

Then, two choices :

Use your function into your controller

```<code>use App\Helpers\Address;
// code code code
public function controllerFunc()
{
    // code
    $countries = Address::country();

    return view('yourview', compact($countries));
}
</code>```

And get it in your view :

```<code><!-- Dump your $countries (from controller) var -->
{{ dd($countries) }}
</code>```

Use your function into your view

```<code><!-- Dump your $countries (from helper) var -->
{{ dd(\App\Helpers\Address::country()) }}
</code>```

Now, if you want to pass directly your select, then in your static function, return Form::select('countries', $countries') like Maraboc said.

Body:
I'm trying to create a helper to centralize a complicated Form::select.

My helper:

namespace App\Helpers;
use Log;
use App\Countries;

class Address {
    public static function country() {
        $countries = Countries::orderby('name_zh','asc');
        $form = "Form::select('countries', \$countries);";
        return $form;
    }
}

My View:

{!! Address::country() !!}

I would like to have this select form with $countries variable from this helper and show a Dropdown list on my view. How do I do it?

Body:
Not sure to really understand your question...

But if you want to pass your $countries variable to your view, your function have to simply return this variable.

public static function country()
{
    $countries = ...;
    return $countries;
}

Then, two choices :

Use your function into your controller

use App\Helpers\Address;
// code code code
public function controllerFunc()
{
    // code
    $countries = Address::country();

    return view('yourview', compact($countries));
}

And get it in your view :

<!-- Dump your $countries (from controller) var -->
{{ dd($countries) }}

Use your function into your view

<!-- Dump your $countries (from helper) var -->
{{ dd(\App\Helpers\Address::country()) }}

Now, if you want to pass directly your select, then in your static function, return Form::select('countries', $countries') like Maraboc said.


问:
how do i get the biggest and most frequent number in a dictionary?
i have a number
(23452)
and i what my function to return the most frequent num in this number and the highest one.
for the num above it should return '2' and for '225566' it should return '6'

i tried :

```<code>def most_popular_digit(num):
pop_dig = {}
c = str(num)
for n in range(len(c)):
    count = pop_dig.get(c[n],0)
    count += 1
    pop_dig[c[n]] = count
list_keys = pop_dig.keys()
sorted_num = sorted(list_keys, key=pop_dig.get)
</code>```

but i cant figure out how to get also the highest number with the highest apperances.

答:
managed to figure it out:</p>

```<code>def most_popular_digit(num):
pop_dig = {}
c = str(num)
for n in range(len(c)):
    count = pop_dig.get(c[n],0)
    count += 1
    pop_dig[c[n]] = count
list_keys = pop_dig.keys()
sorted_num = sorted(list_keys, key=pop_dig.get)
a = pop_dig.keys()
b = pop_dig.values()
if b.index(max(b)) == a.index(max(a)):
    return a[a.index(max(a))]
else:
    return sorted_num[-1]
</code>```

Body:
i have a number
(23452)
and i what my function to return the most frequent num in this number and the highest one.
for the num above it should return '2' and for '225566' it should return '6'

i tried :

def most_popular_digit(num):
pop_dig = {}
c = str(num)
for n in range(len(c)):
    count = pop_dig.get(c[n],0)
    count += 1
    pop_dig[c[n]] = count
list_keys = pop_dig.keys()
sorted_num = sorted(list_keys, key=pop_dig.get)

but i cant figure out how to get also the highest number with the highest apperances.

Body:
managed to figure it out:

def most_popular_digit(num):
pop_dig = {}
c = str(num)
for n in range(len(c)):
    count = pop_dig.get(c[n],0)
    count += 1
    pop_dig[c[n]] = count
list_keys = pop_dig.keys()
sorted_num = sorted(list_keys, key=pop_dig.get)
a = pop_dig.keys()
b = pop_dig.values()
if b.index(max(b)) == a.index(max(a)):
    return a[a.index(max(a))]
else:
    return sorted_num[-1]


问:
Rails controller testing: Testing in isolation or integration?
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

```<code>class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end
</code>```

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern

答:
A quintessential attribute of unit tests and automated testing in general is to be blazing fast. So, all heavyweight resources should be mocked. This includes databases.

In a well designed system, a database is yet another storage medium that should be easily changed without affecting the majority of the code base, only the connector should change. So, in this light, database is a detail that shouldn't concern the automated tests.

Another reason to abandon databases is that it's a temptation to depend on other information available in the database that should've been abstracted from the test.

In Rails, the compromise was made to run tests in an isolated database, hoping it will be fast enough not to waste a lot of time. Paying that price is reasonable given the flexibility a database would give the developer.

After the burst in adopting unit testing, many practitioners went maniac with mocking and gone to far extents with mocking everything without proper judgment regarding where to direct developers efforts and how much gain from such practice. For many ambitious developers, mocking in itself turned to a technical lust! i.e. the means became a goal.

Moral of the story is, don't overdo anything without thinking it through and making sure the expected effort will payoff.

Body:
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern


问:
Failure of creating environment with "conda env create" for the same linux-64 OS
I have exported the virtual environment on my work machine which runs Ubuntu 16.04 to an "environment.yaml" file and then tried to use the file to create the same virtual environment on my home machine which also runs Ubuntu 16.04 but I got the following error:

Using Anaconda Cloud api site https://api.anaconda.org

Fetching package metadata .......

Solving package specifications: .

Error: Packages missing in current linux-64 channels:

  - ca-certificates 2017.08.26 h1d4fec5_0

  - certifi 2017.7.27.1 py27h9ceb091_0

  - libedit 3.1 heed3624_0

  - libffi 3.2.1 hd88cf55_4

  - libgcc-ng 7.2.0 h7cc24e2_2

  - libstdcxx-ng 7.2.0 h7a57d05_2

  - ncurses 6.0 h9df7e31_2

  - openssl 1.0.2m h8cfc7e7_0

  - pip 9.0.1 py27ha730c48_4

  - python 2.7.14 ha6fc286_23

  - readline 7.0 ha6073c6_4

  - setuptools 36.5.0 py27h68b189e_0

  - sqlite 3.20.1 hb898158_2

  - tk 8.6.7 hc745277_3

  - wheel 0.29.0 py27h411dd7b_1

  - zlib 1.2.11 ha838bed_2

答:
The Conda version at my home machine was old which makes Conda look for old versions of packages. After I updating the Conda using the following command

conda update conda

The problem has been solved.

ContentLicense: CC BY-SA 4.0


问:
converting milliseconds to date in C
Is there any way of converting milliseconds to date in C?

What I am trying to do is write a small application in C that can return the financial year and the like(quarter, week) given the start month and isCurentYear bool, where the input might be milliseconds or a date!

In the first place, is there any way by which this can be achieved in C?

And if so, in the process of finding out a way of converting milliseconds to date
I have found out that the use of time_t takes the current millis of our system and by creating a structure pointing to it,it permits us to extract the year,month, date, sec etc!

Refer the below code:

```<code>#include <sys/time.h>
#include<stdio.h>
#include<time.h>

void main()
{
    time_t t = time(000);
    //time_t t = time(0);
    struct tm tm = *localtime(&t);

    printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                                       tm.tm_hour, tm.tm_min, tm.tm_sec);
}
</code>```

And also, can time_t be used to store millisecond values so that it can be converted to date using tm struct?

答:
For those of us who were searching the web for an answer to apply to embedded c applications, think pic 32 programming here is the mathematical calculation:

Date in Epoch_seconds = ( (epoch_seconds / 1000) / 86400 ) + 25569

Resulting in a 5 digit answer which is 10 bits long format dd/MM/yyyy
(Note: the slashes are encoded in the result here so when converting to human readable date please account for it)

Where one day = 86400 ms

and the date 1970/1/1 = 25569

example:=( (1510827144853/1000) / 86400 ) + 25569 = 43055

put 43055 in excel and format cell to date dd/MM/yyyy and it gives you 16/11/2017

Title: converting milliseconds to date in C

Body:
Is there any way of converting milliseconds to date in C?

What I am trying to do is write a small application in C that can return the financial year and the like(quarter, week) given the start month and isCurentYear bool, where the input might be milliseconds or a date!

In the first place, is there any way by which this can be achieved in C?

And if so, in the process of finding out a way of converting milliseconds to date
I have found out that the use of time_t takes the current millis of our system and by creating a structure pointing to it,it permits us to extract the year,month, date, sec etc!

Refer the below code:

#include <sys/time.h>
#include<stdio.h>
#include<time.h>

void main()
{
    time_t t = time(000);
    //time_t t = time(0);
    struct tm tm = *localtime(&t);

    printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                                       tm.tm_hour, tm.tm_min, tm.tm_sec);
}

And also, can time_t be used to store millisecond values so that it can be converted to date using tm struct?


问:
How to run pypy with an existing installation of Python
I am trying to run my code written in Python 3 with pypy, but I got an error :

ImportError: No module named 'osgeo'

but running it with python3 test.py works (but slow) .

My installed version of python is 3.5.2

pypy comes with it's python version 3.5.3

Is there anyway you could tell pypy to use my own version of python, and will it resolve the problem?

答:
Are you using PyPy3?

If you use PyPy it will execute your code with a Python 2.7 interpreter. And if you install a library for python3 it does not mean that the library is installed for python2 too. You need to specify for wich interpreter are you installing the library ( like using pip or pip3 )


问:
How do I open a Chrome extension in its own window?
I installed a Chrome Extension that plays the Pandora client in a web extension (Anesidora), it works fine, but I just can't seem to find a way to open this extension in its own window.

I have to fire up the Chrome browser, click on the extension next to the address bar, and then click on the extension, and as soon as I click away, the music extension disappears, having me to click on the extension and view my music controls again.

Is there a way to update the behavior of the JSON file or popup.html or even backgroud.html page, so this can be viewed all by itself in one page or something?

答:
Existing answer by McSod covers a non-invasive method to open a popup of a third-party extension.

If your goal is to permanently modify an extension so that the click opens a separate window instead, and assuming that the popup page does not change throughout the lifetime of the extension, i.e.:

It's set by browser_action.default_popup in the manifest (assume "popup.html")

Nothing in the extension code calls chrome.browserAction.setPopup to change it.

Under those conditions, you need to perform 2 actions:

Remove the default_popup key from the manifest.

Modify the background script (or add one, if needed - with "persistent": false if that's the only function) to handle the click:

```<code>chrome.browserAction.onClicked.addListener(tab => {
  chrome.windows.create({
    url: chrome.runtime.getURL("popup.html"),
    type: "popup",
    focused: true,
    /* can also set width/height here, see docs */
  });
});
</code>```

Those are the simplest changes. You can add code that checks for presence of already opened window and re-focusing it instead.

Note that depending on the function of the popup, assumptions in its code (most likely, use of tabs API) can break, because it will be the "current tab/window" for itself instead of the page on which the button was clicked.

Body:
Existing answer by McSod covers a non-invasive method to open a popup of a third-party extension.

If your goal is to permanently modify an extension so that the click opens a separate window instead, and assuming that the popup page does not change throughout the lifetime of the extension, i.e.:

It's set by browser_action.default_popup in the manifest (assume "popup.html")

Nothing in the extension code calls chrome.browserAction.setPopup to change it.

Under those conditions, you need to perform 2 actions:

Remove the default_popup key from the manifest.

Modify the background script (or add one, if needed - with "persistent": false if that's the only function) to handle the click:

chrome.browserAction.onClicked.addListener(tab => {
  chrome.windows.create({
    url: chrome.runtime.getURL("popup.html"),
    type: "popup",
    focused: true,
    /* can also set width/height here, see docs */
  });
});

Those are the simplest changes. You can add code that checks for presence of already opened window and re-focusing it instead.

Note that depending on the function of the popup, assumptions in its code (most likely, use of tabs API) can break, because it will be the "current tab/window" for itself instead of the page on which the button was clicked.


问:
Why does ARCore compiler errors with Unity3d?
I have downloaded the latest version of Unity version 5.6.1p1. Downloaded the ARcore for unity from the below website.
https://developers.google.com/ar/develop/downloads

While trying to build the example, it gives the below compiler error:

```<code>Failed to extract `GoogleAR.UnityNative`. Config class of base type `UnityEngine.XR.Tango`. `TangoConfig` when inspecting `Assets/GoogleARCore/SDK/Plugins/GoogleAR.UnityNative.dll`
`UnityEditor.AssemblyHelper:ExtractAllClassesThatInheritMonoBehaviourAndScriptableObject(String, String[]&, String[]&)`
`Assets/GoogleARCore/SDK/Scripts/SessionComponent.cs(324,28): error CS7069:` Reference to type `UnityEngine.XR.Tango.TangoConfig` claims it is defined assembly `UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'` but it could not be found.
</code>```

It will be good if I can get some pointers to resolve this issue.

答: You have to download the latest Unity beta and check the box for ARCore in XRSettings.</p>

Body:
I have downloaded the latest version of Unity version 5.6.1p1. Downloaded the ARcore for unity from the below website.
https://developers.google.com/ar/develop/downloads

While trying to build the example, it gives the below compiler error:

Failed to extract `GoogleAR.UnityNative`. Config class of base type `UnityEngine.XR.Tango`. `TangoConfig` when inspecting `Assets/GoogleARCore/SDK/Plugins/GoogleAR.UnityNative.dll`
`UnityEditor.AssemblyHelper:ExtractAllClassesThatInheritMonoBehaviourAndScriptableObject(String, String[]&, String[]&)`
`Assets/GoogleARCore/SDK/Scripts/SessionComponent.cs(324,28): error CS7069:` Reference to type `UnityEngine.XR.Tango.TangoConfig` claims it is defined assembly `UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'` but it could not be found.

It will be good if I can get some pointers to resolve this issue.


问:
Sequelize OR condition object
By creating object like this

```<code>var condition=
{
  where:
  {
     LastName:"Doe"，
     FirstName:["John","Jane"],
     Age:{
       gt:18
     }
  }
}
</code>```

and pass it in

```<code>Student.findAll(condition)
.success(function(students){

})
</code>```

It could beautifully generate SQL like this

```<code>"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in ("John","Jane") AND Age>18"
</code>```

However, It is all 'AND' condition, how could I generate 'OR' condition by creating a condition object?

答:
String based operators will be deprecated in the future (You've probably seen the warning in console).

Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.

```<code>Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
</code>```

Title: Sequelize OR condition object

Body:
By creating object like this

var condition=
{
  where:
  {
     LastName:"Doe"，
     FirstName:["John","Jane"],
     Age:{
       gt:18
     }
  }
}

and pass it in

Student.findAll(condition)
.success(function(students){

})

It could beautifully generate SQL like this

"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in ("John","Jane") AND Age>18"

However, It is all 'AND' condition, how could I generate 'OR' condition by creating a condition object?

Body:
String based operators will be deprecated in the future (You've probably seen the warning in console).

Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;


问:
What's the difference between equal and identical comparison operators in PHP?

Possible Duplicate:

  How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?

I know the basic difference between == and === , but can some experienced coders tell me some practical examples for both cases?

答:
Easiest way to display it is with using strings. Two examples:</p>

```<code>echo ("007" === "7" ? "EQUAL!" : "not equal");
echo ("007" == "7" ? "EQUAL!" : "not equal");
</code>```

Body:
Easiest way to display it is with using strings. Two examples:

echo ("007" === "7" ? "EQUAL!" : "not equal");
echo ("007" == "7" ? "EQUAL!" : "not equal");