text:
Q: How to get data back from an okhttp call? I have a method which calls an external API using okhttp library on android, I'm able to access the data that comes back inside that method/thread but I'm not able to return the data or use it somewhere else. What's the problem?
I have tried putting the data in another class (extended from AsyncTask) and it still didn't work.
public class DisplayImage extends AppCompatActivity {

    ImageView imageView;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_image);
        imageView = findViewById(R.id.mImageView);
        textView = findViewById(R.id.textView);

        Bitmap bitmap = BitmapFactory.decodeFile(getIntent().getStringExtra("image_path"));
        imageView.setImageBitmap(bitmap);

        String imagePath = getIntent().getStringExtra("image_path");

        try {
            //map returned here
            HashMap<String, double[]> map = getCropInfo(imagePath);

            //This text view doesn't update
            textView.setText(String.valueOf(map.get("ID")[0]));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    HashMap getCropInfo(String imageUri) throws Exception {
        final HashMap<String, double[]> map = new HashMap<>();

        OkHttpClient client = new OkHttpClient();

        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");

        File file = new File(imageUri);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file))
                .build();

        Request request = new Request.Builder()
                .header("Prediction-Key", "") //predictionkey hidden
                .header("Content-Type", "application/octet-stream")
                .url("https://westeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/7f5583c8-36e6-4598-8fc3-f9e7db218ec7/detect/iterations/Iteration1/image")
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            public void onResponse(Call call, final Response response) throws IOException {
                // Read data on the worker thread
                final String responseData = response.body().string();

                // Run view-related code back on the main thread
                DisplayImage.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            JSONArray jsonArray = jsonObject.getJSONArray("predictions");
                            double highestIDProbability = 0;
                            double highestVoltageProbability = 0;

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject tempObject = jsonArray.getJSONObject(i);
                                if(tempObject.getString("tagName").equals("ID") && tempObject.getDouble("probability") > highestIDProbability) {
                                    highestIDProbability = tempObject.getDouble("probability");
                                    map.put("ID", getCoordinatesPixels(tempObject));
                                }
                                else if(tempObject.getString("tagName").equals("Voltage") && tempObject.getDouble("probability") > highestVoltageProbability) {
                                    highestVoltageProbability = tempObject.getDouble("probability");
                                    map.put("Voltage", getCoordinatesPixels(tempObject));
                                }
                            }
                            //setting text view works from here.
                            //textView.setText(String.valueOf(map.get("ID")[0]));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        //I am returning map
        return map;
    }

    static double[] getCoordinatesPixels(JSONObject object) {
        double[] arr = new double[4];
        try {
            JSONObject innerObject = object.getJSONObject("boundingBox");
            arr[0] = innerObject.getDouble("left");
            arr[1] = innerObject.getDouble("top");
            arr[2] = innerObject.getDouble("width");
            arr[3] = innerObject.getDouble("height");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return arr;
    }

}

I need the map to return so I can use the data externally.

A: I believe you're running into an issue related to the asynchronous nature of OkHttp and network requests in general. When you do a new call, that call is queued and handled asynchronously. This means that the code will most likely execute return map; before the asynchronous call has completed and before the callback modifies the map. If you need access to the map outside of the scope of the callback you have two main options.

*

*Make the call blocking. This essentially means that you will have to force the function to stall until the OkHttp callback is triggered before return map; occurs. I would absolutely not recommend doing this as it defeats the entire purpose of moving long running tasks to other threads.

*Call a function inside the onResponse() callback. Construct the map inside the callback itself, then just call a function with that map as a parameter to handle any operations you need to do on that map. Alternatively you could also make the map a global variable so you can access it from practically anywhere.
On a sidenote, if this data is going to be used to propagate changes back to the UI or other program state, I would recommend using a ViewModel (it's a model object that holds data and can outlive Activity lifecycles) paired with something like MutableLiveData (which is a data wrapper that makes basically anything observable).
Using such a setup, you would have your map object inside your ViewModel. You would then register an observer from any context (Activity, Fragment, etc) where you need to know about updates on the map. Finally, in the callback,  you would just need to update the ViewModel's map. This would automatically notify any registered observers.
Good luck!


text:
Q: Iterative method to find Ridge Regression Parameter I have seen a method whereby instead of trying to estimate the ridge parameter (k) directly from the data (using one of the many many ridge parameter estimators in the literature) you solve for it iteratively.
The method is simple enough: You simply increase k (in suitably small steps) until the condition number is reduced blow 10.
At first blush this seems like quite a nice solution to me but I've never seen a Ridge Regression paper/book that uses it.
Update OK this is basically the method suggested by Marquardt "Generalized inverses, Ridge Regression, Biased Linear Estimation and Non-linear Estimation" the only difference being he used VIF's to measure the MC while this method uses the condition number. McDonald and Galrneau "A Monte-Carlo Evaluation of some Ridge-Type Estimators" note that this method is may not be appropriate for all data sets as it does not include the y values (observations). I still have not found a paper where the Marquardt method is tested against other estimators for the ridge parameter does anybody know of such a paper?
Is this method theoretically sound though? Even if (as I suspect) it isn't does it really matter for the average practitioner who just want to produce more stable estimates of their Beta's (the weights in the regression) rather than having them "blow up" to grossly unrealistic values when they experience severe MC?
Truly I would like to find a better method than this ideally with a solid theoretical underpinning but its hard to see from a practical view point it can be improved upon?

A: Ridge regression smoothing (Tikhonov factor, shrinkage, or other synonyms) can be chosen adaptively to minimize the error of a parameter(s) of interest. That parameter need not be directly related to the parameters of the model, it is sufficient that its error can be defined by error propagation defined in terms of the parameters of the model. This is usually applied for ill-posed integrals, for example, the total area under curve from $t=${0,Infinity} extrapolated from incomplete range data.
Note, this answer has nothing whatever to do with goodness-of-fit, it is how to perform an inverse problem solution. That is, it 1) assigns a reason, goal, or target for doing regression, 2) extracts only that optimized information from the model and data, and 3) yields a goodness defined in terms of the regression target and not goodness-of-esthetically-fitting the model to the data. Example, read appendix in this. And no, it isn't perfect either, just better at finding answers.

A: I like to think of this as optimizing effective AIC.  See the following for a presentation on this topic: https://biostat.app.vumc.org/wiki/pub/Main/FHHandouts/iscb98.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert datetime in GMT+# format to GMT i have an input format like this, and i need to convert it to GMT format:
$input = array(
           "gmt" => "+7",
           "datetime" => "2017-10-10 12:10:12"
         );

the input data contain gmt array index which show the which gmt format, and the datetime index shows the date in "Y-m-d h:i:s" that needs to be convert from GMT+7 to GMT.

A: Try this:
$input = array(
  "gmt" => "+7",
  "datetime" => "2017-10-10 12:10:12"
);

$ny = new DateTimeZone("GMT+7");
$gmt = new DateTimeZone("GMT");
$date = new DateTime( $input["datetime"], $ny );
$date->setTimezone( $gmt );

echo $date->format('Y-m-d H:i:s');

A: Oneshot (not recommended):
echo date('Y-m-d h:i:s', strtotime($input['datetime'])+$input['gmt']*3600);


text:
Q: How does nonce verification work? I can see that wp_nonce_field generates a value in the hidden field.
<input type="hidden" id="message-send" name="message-send" value="cabfd9e42d" />

But wp_verify_nonce isn't using that value as far as I can tell, but I may be wrong.
It looks like it's using a session token for verification.
$expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
 if ( hash_equals( $expected, $nonce ) )
  { return 1;  }

Then what's the point of having a value attribute in the hidden field?

A: TL;DR
In short, wp_verify_nonce() uses that value because it expects that value as its first argument.
wp_verify_nonce() arguments
wp_verify_nonce() receives 2 arguments:

*

*$nonce

*$action
The value in the hidden field ('cabfd9e42d' in your example) represent the $nonce.
1st argument is the nonce, and comes from the request
In fact, wp_verify_nonce() have to be used like so:
// here I assume that the form is submitted using 'post' as method

$verify = wp_verify_nonce($_POST['message-send']);

So the first argument passed to wp_verify_nonce() is exactly the value that is present in the hidden field.
2nd argument: the wp_create_nonce() method
Regarding the second argument, it depends on how you build the nonce value.
E.g. if you did:
<?php $nonce = wp_create_nonce( 'custom-action' ); ?>
<input type="hidden" name="message-send" value="<?php echo $nonce ?>" />

Then you need to do:
$verify = wp_verify_nonce( $_POST['message-send'], 'custom-action' );

So, the second argument is what was used as argument to wp_create_nonce().
2nd argument: the wp_nonce_field() method
If you created the nonce using wp_nonce_field() like:
wp_nonce_field( 'another_action', 'message-send' );

Then you need to verify the nonce like so:
$verify = wp_verify_nonce( $_POST['message-send'], 'another_action' );

So, this time, the action is whatever passed as first argument to wp_nonce_field().
Recap
To pass wp_verify_nonce() validation you need to pass 2 arguments to the function, one is the value in the nonce hidden field, the other is the action, and depends on how the nonce value was built.


text:
Q: If the determinants of two matrices, $A$ and $B$, of order $n$, $= 0$, are they row-equivalent? Question is in the title. I'm thinking no, they aren't, and a counter-example below:
Let's say the reduced row-echelon forms of matrices $A$ and $B$ are below:
$$\text{rref}(A) = \begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 0
\end{pmatrix}\text{,} \quad \text{rref}(B) = \begin{pmatrix}
1 & 0 & 2 \\
0 & 1 & 0 \\
0 & 0 & 0
\end{pmatrix}$$
Hence, it is clear that although $\text{det}(A) = \text{det}(B) = 0$, since the reduced row-echelon forms of matrices are unique, A and B are not row-equivalent.
Is this a sufficient and logical proof?
Thanks in advance.

A: Yes, it is fine. A simpler example would be$$A=\begin{pmatrix}0&0&0\\0&0&0\\0&0&0\end{pmatrix}\text{ and }B=\begin{pmatrix}1&0&0\\0&0&0\\0&0&0\end{pmatrix}.$$


text:
Q: Git sign commit somewhere in history On a number of parts of the Internet (such as here), it is implied that git commits must be signed when being done or never.
However, technically a signature on a commit is nothing more than a signature on the commit object (as shown here), that consists of a hash of the "tree" file (that is a list of hashes of the git objects), the hash of the parent and some metadata.
As a consequence, there seems to be nothing that prevents a commit to be signed a posteriori, without rewriting the entire history.
Is it really possible? Is there a recommended way of doing so? Would such an after-the-fact signature work nicely with pushes and pulls?

A: I don't believe you can do this without rewriting history. I just cloned the same repository twice to conduct a test. I made the same change in both repositories, then committed with the same log message ("foobar"), the only difference being that one was signed and one was not.
# unsigned test
parent 50c6dd65f1d7a240cf6b5c9585ce363ef4708d1e
new    b3ff731922f80a417b84ed492537c1f7ba74715e

# signed test
parent 50c6dd65f1d7a240cf6b5c9585ce363ef4708d1e
new    688b3be2e55558c45b00b6a6c02086a03768e02d

As you can see, starting from the same parent (50c6dd65), the result is a two different commit hashes. So for un-pushed commits, it's not any different than any other history rewriting (and therefore it carries the same liabilities).
In response to your comment asking if the hash changed merely because of a difference in timestamps, I don't believe so. If you inspect using cat-file:
$ git cat-file -p 688b3be2e55558c45b00b6a6c02086a03768e02d
tree 074e53e54670dea3502229e9494f3d571f5dcc16
parent 50c6dd65f1d7a240cf6b5c9585ce363ef4708d1e
author Dan Lowe <dan@XXXXXXXX.com> 1448768563 -0500
committer Dan Lowe <dan@XXXXXXXX.com> 1448768563 -0500
gpgsig -----BEGIN PGP SIGNATURE-----
 Version: GnuPG v1

 iQEVAwUAVlp0N1rGfrtJ2k+kAQIbYQf7BLx3/jqU/vwvoJOcbq5MPK0ok7B8mOaF
 VWhNCbAeOBMzXdrn8IQxY2xYcPsy+d6pNx6ZOF70L3VZm6rWFxNzZQRrjS4ByOAM
 VyoL8bXceMcrb/sQUHM5yTCaDcfoYx40K0q91XsGew2EIzNKcOraK1Ee4hEtPg1D
 ojyPVjiWz2qMJJ0YYAATSvWwlKFO2ShTC6tGZDHrx0e6BAEN5QS4KdGhNech/vpU
 IPFDjIKWtGPTbYY8Z95vKLAMYWPZDJ8j/x1gRytN8PDjRufRtpRnZMccB6JQoXNZ
 5L23WQFfUFeXRdWf0MtkrbrSwzuaaIF8l1oGYnEtYT6nOIktPT47Fw==
 =/U9b
 -----END PGP SIGNATURE-----

foobar

As I understand it, this metadata is all part of the input to the hash algorithm resulting in the commit ID. If that is the case, the presence of the gpgsig data here means it will always give you a different hash than the unsigned version of the commit.

A: Every git object is identified by it's own SHA-1 hash. So they are all immutable.
If you sign a commit you've previously done, you are, in fact, duplicating that commit, but in a signed way. So the original commit is still there - you can even git show it if you remember it's hash or have any ref pointing at it. What you'd do is to create a new commit with equivalent changes and metadata, but with a signature added, and make the ref you are currently on - ie, your current branch - point at it.
The commit's tree and every other depending object will be the same. But, as the commit itself has changed, you get a new commit object - so you are re-writing history.


text:
Q: Binding dropdown values using knockout js I have the below JS:
function RowData(Township, Range, Section,Crop, Acres) {
var self = this;

self.Township = Township;
self.Range = Range;
self.Section = Section;
self.Crop = [{ value: "1", crop: "Irrigated Corn" }, { value: "2", crop: "Irrigated Sugar Beets" }, { value: "3", crop: "Irrigated Soybeans" }, { value: "4", crop: "Irrigated Sorghum (Milo, Sudan)" }, { value: "5", crop: "Irrigated Dry Edible Beans" }, { value: "6", crop: "Irrigated Potatoes" }, { value: "7", crop: "Irrigated Alfalfa" }, { value: "8", crop: "Irrigated Small Grains" }, { value: "9", crop: "Range/Pasture/Grass (Brome, Hay, CRP)" }, { value: "10", crop: "Urban Land" }, { value: "11", crop: "Open Water" }, { value: "12", crop: "Riparian Forest and Woodlands" }, { value: "13", crop: "Wetlands" }, { value: "14", crop: "Other Agricultural Lands (Farmsteads, Feedlots, etc.)" }, { value: "15", crop: "Irrigated Sunflower" }, { value: "16", crop: "Summer Fallow" }, { value: "17", crop: "Roads" }, { value: "18", crop: "Dryland Corn" }, { value: "19", crop: "Dryland Soybeans" }, { value: "20", crop: "Dryland Sorghum" }, { value: "21", crop: "Dryland Dry Edible Beans" }, { value: "22", crop: "Dryland Alfalfa" }, { value: "23", crop: "Dryland Small Grains" }, { value: "24", crop: "Dryland Sunflower" }, { value: "25", crop: "Dryland Sugar Beets" }, { value: "26", crop: "Dryland Potatoes" }, { value: "27", crop: "Irrigated Hay" }, { value: "28", crop: "Irrigated Rotation Pasture" }];
self.Acres = Acres;
}
function PBHEPViewModel() {
var self = this;

//Present Conditions
self.present_conditions = ko.observableArray([
    new RowData()
]);
self.present_AddRow = function () {
    self.present_conditions.push(new RowData())
}
self.present_RemoveRow = function (row) { self.present_conditions.remove(row) };

//Future Conditions
self.future_conditions = ko.observableArray([
    new RowData()
]);
self.future_AddRow = function () {
    self.future_conditions.push(new RowData())
}
self.future_RemoveRow = function (row) { self.future_conditions.remove(row) };

//submit the data
self.submit_conditions = function () {

    var PC_data = ko.toJSON(self.present_conditions());
    var FC_data = ko.toJSON(self.future_conditions());

    $.post("/Home/PBHEP", { "PC": PC_data, "FC": FC_data});
}
}
ko.applyBindings(new PBHEPViewModel());

And my HTML is:

                <input class="input-small" type="text" placeholder="Township" data-bind="value: Township">

                <input class="input-small" type="text" placeholder="Range"data-bind="value: Range">

                <input class="input-small" type="text" placeholder="Section"data-bind="value: Section">

                 <select name="" data-bind="options: Crop, optionsValue: 'value', optionsText: function (i) { return i.crop }, optionsCaption: 'Choose a Crop...'"></select>

                <input class="input-small" type="text" placeholder="Acres"data-bind="value: Acres">

                <button class="btn btn-small btn btn-danger" type="button" data-bind="click: $root.future_RemoveRow"></button>

When I do the post I have all the entire array in the crop field where i only want to post the value that has been selected.
How do I achieve this where am I going wrong.
Thank you in advance

A: For a single-select list, you use the value binding to write the selected value to your viewmodel.  See the note near the top of the documentation for details.
Try the below binding:
<select name="" data-bind="options: Crop, value: Crop, optionsText: 'crop', optionsCaption: 'Choose a Crop...'"></select>

This displays the text in the drop down as the crop property of your array items.  It also assigns the selected value from the drop down to the Crop property of the RowData object.
You may want to change the name of the array, Crop, to Crops or something to differentiate it from the singular property on the RowData object.  It is a little confusing, as is.


text:
Q: How to add a table next a plotly express chart and save them to a pdf I have a dataframe
              a            b   c
0   2610.101010 13151.030303   33.000000
1   1119.459459 5624.216216    65.777778
2   3584.000000 18005.333333    3.000000
3   1227.272727 5303.272727    29.333333
4   1661.156504 8558.836558   499.666667

and I am plotting histograms using plotly.express and I am also printing a describe table with the following simple code:
import plotly.express as px
for col in df.columns:
    px.histogram(df, x=col, title=col).show()
    print(df[col].describe().T)

Is it possible to add next to each histogram the describe and save all the plots (together with their respective histograms) in a single pdf ?

A: One way to achieve this is by creating a subplot grid, the size of n_columns * 2 (one for the histogram and one for the table. For example:
from plotly.subplots import make_subplots

titles = [[f"Histogram of {col}", f"Stats of {col}"] for col in df.columns]
titles = [item for sublist in titles for item in sublist]

fig = make_subplots(rows=3,
                    cols=2,
                    specs=[[{"type": "histogram"}, {"type": "table"}]] *3,
                    subplot_titles=titles)

for i, col in enumerate(df.columns):
    fig.add_histogram(x=df[col],
                      row=i+1,
                      col=1)
    fig.add_table(cells=dict(
                        values=df[col].describe().reset_index().T.values.tolist()
                        ),
                  header=dict(values=['Statistic', 'Value']),
                  row=i+1,
                  col=2
                 )
fig.update_layout(showlegend=False)
fig.show()

fig.write_image("example_output.pdf")

In the end, you can save the full fig (6 charts together) as pdf using .write_image() as explained here. You will need to install kaleido or orca utilities to do so. The output will look like this (you can of course customize it):

If you need to save each graph + table on a separate page of the PDF, you can take advantage of the PyPDF2 library. So, first, you would save each graph + table as a single PDF (as described above, but you would save as many PDF files as numbers of columns you have, not 1), and then you could follow the instructions from this answer to merge them:


text:
Q: Updating a Drop down list with Jquery from JSON I have a  list that I need to fill using a JSON collection of object. Here is what my action is returning:
public ActionResult GetProductCategories()
        {
            var categories = _entities.ProductCategories.ToList();

            var result = new List<SelectListItem>();

            foreach (var category in categories)
            {
                result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

This is what I've come up with for my javascript, gathered from various sources:
function loadCategories() {
            $.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
                var selectList = $("#subCategories");

                $.each(data, function(index, optionData)
                {
                    var option = new Option(optionData.Text, optionData.Value);
                    selectList.add(option, null);
                });
            });
        }

But it doesn't appear to be working, and isn't giving any errors. Whats the best practice for this sort of thing?

A: I was wondering what are you trying to achieve in this next lines of codes,
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);

are you trying to create an option then add it on select? if so, do it like this, use .append()
selectList.append(option);

with that, I'm still assuming new Option(optionData.Text, optionData.Value); is creating a new option, in jQuery it would be like this var option = $('<option>').text(optionData.Text).val(optionData.Value);

added notes for .add(),
var selectList = $("#subCategories"); // creates jQuery object selectList.
selectList.add(option, null); // selectList is jQuery object,
                              // so when you call .add(), you're calling jQuery's `add()`.

a workaround is this,
selectList[0].add(option, null); // you can use [0] to convert it into DOM object.

difference between:

*

*DOM select object's .add()

*jQuery object's .add()

A: JQuery fails silently if it doesn't like the JSON data coming back from the server. Point your browser at /Admin/Product/GetProductCategories and look at the result. Make sure it doesn't have any html tags and make sure there are double quotes around the key names.


text:
Q: Mapbox gl & directions API call - doesn't display routes I have an app with multiple markers, for displaying a travel. Each marker is a step, and I want to create a route between each marker with it following marker (following step).
For that, right now I have this code :
$(document).ready(function() {
  var map;
  var directions;

  // token access for MAPBOX GL
  mapboxgl.accessToken = 'pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw';

  // generate map
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [-96, 37.8],
    zoom: 5
  });

  // center map on selected marker
  map.on('click', 'markers', function (e) {
    map.flyTo({center: e.features[0].geometry.coordinates});
  });

  // change mouse action on enter / leave in marker
  map.on('mouseenter', 'markers', function () {
    map.getCanvas().style.cursor = 'pointer';
  });

  map.on('mouseleave', 'markers', function () {
    map.getCanvas().style.cursor = '';
  });

  $.ajax({
    dataType: 'json',
    url: grabTravelData(),
    success: function(data) {
        geojson = data;
        map.addSource("markers", {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": data
            }
        });
        map.addLayer({
            "id": "markers",
            "type": "circle",
            "source": "markers",
            "paint": {
                "circle-radius": 7,
                "circle-color": "#ff7e5f"
            },
        });
        // center map on markers
        var bounds = new mapboxgl.LngLatBounds();
        data.forEach(function(feature) {
            bounds.extend(feature.geometry.coordinates);
        });
        map.fitBounds(bounds);

        for(var i = 0; i < data.length; i++) {
            var last = data.length - 1
            var from = data[i];
            var to = data[i + 1];
            if(i != last) {
                apiCall(from.geometry.coordinates[0], from.geometry.coordinates[1], to.geometry.coordinates[0], to.geometry.coordinates[1], mapboxgl.accessToken, i);
            } else {
                apiCall(from.geometry.coordinates[0], from.geometry.coordinates[1], from.geometry.coordinates[0], from.geometry.coordinates[1], mapboxgl.accessToken, i);
            }
        }
    }, error: function(data) {
        console.log(data + ' error');
    }
});

function apiCall(from_one, from_two, to_one, to_two, token, number) {
  $.get("https://api.mapbox.com/directions/v5/mapbox/driving/" + from_one + "," + from_two + ";" + to_one + "," + to_two + "?access_token=" + token, function(data) {
    var naming = "route-" + number;
    map.on('load', function () {
        map.addSource(naming, {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "LineString",
                    "coordinates": data.routes[0].geometry
                }
            }
        });

        map.addLayer({
            "id": naming,
            "type": "line",
            "source": naming,
            "layout": {
                "line-join": "round",
                "line-cap": "round"
            },
            "paint": {
                "line-color": "#ff7e5f",
                "line-width": 8
            }
        });
    });
  }
}

But the routes doesn't appear on the map, and I read on the API Documentation this line : // This API is not available through the JavaScript SDK
So maybe I can't call the API.
With this code I have a good result:
with this url : https://api.mapbox.com/directions/v5/mapbox/driving/18.0944238,42.65066059999999;15.981919,45.8150108?access_token=
And the result is a json with geometry... so a good result as it's write in the documentation.
Maybe someone know how should I display routes on the map ? And if I can't with the API call, how should I modify my code to use the Directions Plugin ?

A: Your problem is that the directions API is returning by default geometries encoded in polylines, which are not geojson features.
To get around that, you can specify the &geometries=geojson query parameter to your url, and it will return you the data in the correct format you can display easily.
Also one thing, it seems better to me to do your ajax after the map has finished loaded.

// This is the token from their docs, don't be evil
mapboxgl.accessToken = 'pk.eyJ1IjoiYXBlcmN1IiwiYSI6ImNpZ3M0ZDZ2OTAwNzl2bmt1M2I0dW1keTIifQ.I5BD9uEHdm_91TiyBEk7Pw'

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v9',
  center: [18.0944238, 42.65066059999999],
  zoom: 9,
})

map.on('load', () => {

  $.get(`https://api.mapbox.com/directions/v5/mapbox/driving/18.0944238,42.65066059999999;15.981919,45.8150108?access_token=${mapboxgl.accessToken}&geometries=geojson`, data => {

    map.addLayer({
      id: 'route',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: data.routes[0].geometry,
        },
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-color': '#ff7e5f',
        'line-width': 8,
      },
    })

  })

})
html, body, #map {
  height: 100%;
}

<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css" rel="stylesheet"/>


text:
Q: function in mips that calculates the absolute value hello i have an exercise in mips that must call a function to calculates the absolute value of a number
i have write 2 codes but if you have any other solution write it
.data

message:.asciiz "give number: "

.text

main:
li $v0, 4
la $a0, message
syscall

li $v0, 5
syscall

add $t1, $v0, $zero

 jal absolute

add $v0,$t2,$zero

li $v0, 1

syscall

li $v0, 10
 syscall

absolute: ori $t2,$t1,0 #copy r1 into r2
    slt $t3,$t1, $zero      #is value < 0 ?

    beq $t3,$zero,gg #if r1 is positive, skip next inst

    sub $t2,$zero, $t0      #r2 = 0 - r1

 jr $ra

gg:

#t2

and the second code is this
.data

question: .asciiz "give number"

.text
main:
li $v0, 4

la $a0, question

syscall

li $v0, 5

syscall
jal absolute
li $v0, 1

syscall

li $v1, 1

syscall

li $v0, 10

syscall
absolute:

slti $t0,$a0,0

bne $t0,$zero,g1
add $v0,$a0,$zero

jr $ra
g1:

sub $t2,$a0,$a0

sub $v1,$t2,$a0

j absolute

A: Try this:
.data
    message:    .asciiz "Enter the number: "
.text
.globl main

main:
    # print message
    li  $v0, 4
    la  $a0, message
    syscall

    # read integer
    li  $v0, 5
    syscall

    slt  $t0, $v0, $0       # $t0 = ( $v0 < 0 ? 1 : 0 )
    bne  $t0, $0, NEGATIVE  # if($t0 != 0) goto NEGATIVE
    j    POSITIVE           # goto POSITIVE (and dose nothing)

NEGATIVE:
    # ~$v0 + 1
    nor  $v0, $v0, $0       # NOR with zero = NOT
    addi $v0, $v0, 1        # $v0 =+ 1

POSITIVE:
    # print $v0
    move $a0, $v0
    li  $v0, 1
    syscall

    # print new line '\n'
    li  $v0, 11
    addi $a0, $0, 10
    syscall

    jr  $ra

Test:
Enter the number: 10
10
Enter the number: -5
5


text:
Q: I must reconnect my mouse at boot every time, why? I have a Corsair Harpoon Wireless mouse, and when I start my computer I must reconnect it for it to work... (Doesn't matter if I use the cable or the wireless receiver)
I have checked the drivers via the iCUE software, I have tried starting in safe mode, the problem persists. I haven't tried another mouse yet...


text:
Q: Flutter post request headers do not appear on Google Cloud Function I am doing a post request in flutter to a google cloud function:
  final uri = Uri.parse(
      'https://example.cloudfunctions.net/send_to_queue');
  final bearer = 'Bearer ${await user.getIdToken()}';
  final response = await http.post(uri, body: json.encode(data),
      headers: {HttpHeaders.authorizationHeader: bearer, 'Content-Type': 'application/json'});

In the Google Cloud I print(request.headers) I see a bunch of headers but no Authorization or Content-Type headers.
What should I do?
P.S. Same issue in here Flutter calling firebase cloud function admin.auth.updateUser but I don't want to use a callable function

A: The browser was sending an OPTIONS request (preflight) before the POST.
I needed to change the Google Cloud Function to handle this:
def main(request):
    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
            'Access-Control-Max-Age': '3600'
        }
        return ('', 204, headers)
    # Get token from request
    token = request.headers.get('Authorization').split('Bearer ')[1]
    etc..


text:
Q: Can i place a fixed width div next to another one that will fill the gap similar to * Using flex box can i have 2 divs in a row, one with a fixed width (say width:200px) and then the other div fill the rest of the space in a fluid way, like asterex did in Frames?

A: Here is how you'd do it using the flexible box model:
#container {
    display: flex;
    width: 500px; /* Set the available space */
}

#container > div#first {
    width: 200px;
}

#container > div#second {
    flex-grow: 1;
}

See the fiddle here.

A: You can use float and calc to create something like that. Here is an example:
HTML

CSS
#one {
    width:200px;
    height:200px;
    background-color:red;
    float:left;
}
#two {
    width:calc(100% - 200px);
    height:200px;
    background-color:blue;
    float:left;
}

And a fiddle showing it in action: http://jsfiddle.net/mQ2JX/


text:
Q: How to get the cosine similarity between two documents in MALLET? I've an LDA topic model trained using MALLET but I want compute the cosine similarity between two documents to get the similarity but I'm not sure which file that MALLET outputs do I compute the cosine of.
My cosine similarity function is working fine but just not sure what I'm comparing in MALLET.
Any help would be appreciated!

A: Each document will be represented by its topic composition, so you have to compare those. Use the --output-doc-topics parameter in order to get the needed file.
The rows are the documents and the columns are the proportions of each topic belonging to the document. In the current version (2.0.8) the columns are sorted ascending by topic ID - otherwise they are sorted from highest to lowest probability.
You should also consider different metrics apart from cosine similiarity, e.g. the (symmetric) Kullback-Leibler divergence or the Hellinger distance.


text:
Q: projective space, quotient map, existence of a function
Let $g:\mathbb{R}P^2\to\mathbb{R}P^2$ continuous. Let $q:S^2\to\mathbb{R}P^2$ denote the quotient map.
Show: It exists a function $h: S^2\to S^2$ with $q\circ h=g\circ q$

Hello,
I really struggle with the tasks I get lately, and again I have no clue here, which is kinda embarassing.
Could you maybe give me a hint, or direction how I can solve this?
Thanks in advance.

A: $\textbf{Hint:}$ $\mathbb{S^2}$ is the universal cover of $\mathbb{R}P^2$, so it suffices to show that the map $g \circ q:\mathbb{S^2}\to \mathbb{R}P^2$ has a lift with respect to the covering map $q$. Note that $\pi_1(\mathbb{S^2})=0$.


text:
Q: How to point domain name to EC2 from registrar I have searched for that question, i find several answer but I haven't found appropriate for me.
I have created Elastic IP, and when I enter into control panel of my registrar it asks names servers, but I have found one in Public DNS, but it asks second one.
What to do?

A: It sounds like you're a little confused as to how DNS/Domain registrations are linked.
Your domain registrar handles your purchase of the domain, and pointing it to a set of domain name servers. Presuming your registrar doesn't provide DNS, you shouldn't need to tell them what IP you're hosting the site on.
You will need a DNS provider (which may or may not be the same company as your registrar, most registrars provide some kind of DNS service), who will provide 2 or more name servers on the internet, and who will keep a database of some kind which links the two things up.
For example, your domain registrar might be Acme Inc., which for some reason let's say doesn't provide a DNS service. You'd login to the website for Acme, and set your domain name servers to the DNS servers provided by Bcme, your example DNS provider (e.g ns0.bcme.com and ns1.bcme.com).
You'd need to inform Bcme that your website (domain name) is x.com, and that your IP address is whatever Amazon have given you.
Amazon provide DNS service via "Route 53" - which is $1pcm/domain, but other DNS providers are available.


text:
Q: How to use signals & slots in Qt for inter-threading communication I want to make an application where the user will hit a QPushButton and this will trigger a secondary thread which will add some text to a QListWidget in the main window. But for a reason that I cannot figure out ,although the signal from the thread to the main window is emitted it never reaches the destination. Probably because the connection fails. But why this happens here is my code(my application is compiled using Visual Studio 2010):
mythread.h
#ifndef MY_THREAD_H
#define MY_THREAD_H
#include <QThread>
#include <QString>
class mythread:public QThread
{
    Q_OBJECT

public:
    void setName(QString& name);
signals:
    void sendMsg(QString& msg);
protected:
    void run();
private:
    QString m_name;
    QString msg;
};
#endif

mythread.cpp
#include "mythread.h"
void mythread::setName(QString& name)
{
    m_name=name;
}
void mythread::run()
{
    msg="Hello "+m_name;
    emit sendMsg(msg);
}

mydialog.h:
#ifndef MY_DIALOG_H
#define MY_DIALOG_H
#include <QtGui>
#include "mythread.h"
class mydialog:public QDialog
{
    Q_OBJECT
public:
    mydialog();
public slots:
    void receiveMsg(QString& msg);
    void fillList();
private:
    QListWidget list1;
    QPushButton btn1;
    QGridLayout layout;
    mythread thread;
};
#endif

mydialog.cpp:
#include "mydialog.h"
mydialog::mydialog()
{
    layout.addWidget(&list1,0,0);
    btn1.setText("Find");
    layout.addWidget(&btn1,0,1);
    setLayout(&layout);
    QString myname="leonardo";
    thread.setName(myname);
    connect(&btn1,SIGNAL(clicked()),this,SLOT(fillList()));
    connect(&thread,SIGNAL(sendMsg(QString&)),this,SLOT(receiveMsg(Qstring&)));
}
void mydialog::fillList()
{
    thread.start();
}
void mydialog::receiveMsg(QString& msg)
{
    list1.addItem(msg);
}

find.cpp:
#include <QApplication>
#include "mydialog.h"
int main(int argc,char* argv[])
{
    QApplication app(argc,argv);
    mydialog window;
    window.setWindowTitle("Find");
    window.show();
    return app.exec();
}

find.pro:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
HEADERS += mydialog.h mythread.h
SOURCES += find.cpp mydialog.cpp mythread.cpp

A: Two things:

*

*In your second connect call, Qstring must be changed to QString

*Qt cannot deliver QString& accross threads by default. There's two ways to fix this:

*

*Change your Signals and Slots and the connect to use QString rather than QString&

*Use qRegisterMetaType in order to make QString& usable.

I still recommend reading
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
and Kari's comment
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong#commento-comment-name-a6fad43dec11ebe375cde77a9ee3c4331eb0c5f0bcac478ecbe032673e8ebc82
when working with threads, though.

A: First of all use const qualifier for arguments if you're not planning to modify it. After fixing typo in connection SLOT(receiveMsg(Qstring&)) and changing signals and slots signature to const references everything works fine


text:
Q: Separate onClick for the component as a whole and a button within the component So I am in the process of creating a todo list written in React. I have a functional component ListItem which renders an
 element with the task and a trash button.
My current functionality: When the user clicks on the actual text, the text gets struck out, and when they click on the trash button the ListItem gets deleted.
function ListItem(props) {
  return (

        {props.value}

      <button id="trash-button" onClick={props.handleTrash}>
        Trash
      </button>

  );
}

What I want my functionality to be: When the user clicks anywhere in the
 item (excluding the trash button) the text is struck out, and when they click on the trash button the ListItem gets deleted.
I thought I could achieve the above by shifting the handleItem onClick to the
 item.
function ListItem(props) {
  return (

        {props.value}

      <button id="trash-button" onClick={props.handleTrash}>
        Trash
      </button>

  );
}

However what ends up happening is that even when the trash button is clicked, the handleItem function gets called along with the handleTrash function. Is there a way I can suppress the handleItem function when handleTrash is called?
Thanks in advance!
Edit: My entire code for the Todo List. The form that takes in the task is called AddEntry and that's separate from everything else so I'm not including it.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import AddEntry from './AddEntry'

function ListItem(props) {
  return (

        {props.value}

      <button id="trash-button" onClick={props.handleTrash}>
        Trash
      </button>

  );
}

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      entries: []
    };

    this.handleItem = this.handleItem.bind(this);
    this.handleTrash = this.handleTrash.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
  }

  renderListItem(e) {
    if(e.struck) {
      return (
        <ListItem
          key={e.key}
          value={{e.item}}
          handleTrash={() => this.handleTrash(e)}
          handleItem={() => this.handleItem(e)}
        />
      );
    }

    else {
     return(
      <ListItem
          key={e.key}
          value={e.item}
          handleTrash={() => this.handleTrash(e)}
          handleItem={() => this.handleItem(e)}
        />
      );
    }
  }

  handleAdd(e) {
    const entries = this.state.entries;
    entries.push({item: e, struck: false, key: entries.length});
    this.setState({
      entries: entries
    });
  }

  handleTrash(e) {
    const entries = this.state.entries;
    for(let i = 0; i < entries.length; i++) {
      if(entries[i] === e) {
        entries.splice(i, 1);
      }
    }

    this.setState({
      entries: entries
    });
  }

  handleItem(e) {
    console.log("hi");
    const entries = this.state.entries;
    let index = entries.findIndex(ele => e.key === ele.key);
    entries[index].struck = !entries[index].struck;
    this.setState({
      entries: entries
    });
  }

  render() {
    return (

          <AddEntry handleAdd={this.handleAdd}/>

{this.state.entries.map((e) => this.renderListItem(e))}

    );
  }

}

ReactDOM.render(
  <TodoList />,
  document.getElementById('root')
);

this is how it's working with the onClick in the li element

A: keep the onClick on li itself and in your handleTrash function use preventPropogation to stop propogation.
 handleTrash(event){
   event.stopPropagation();
   // code the rest
}

here is a working example https://codesandbox.io/s/1vqwo4j0yl


text:
Q: SWIFT: Print data from firebase database in tableview I am new to firebase.
I want to make an app with data from my Firebase database to show in a tableview.
Example:
Let's say I have made a database that looks like this:
{
  "fruits": {
    "Apple": {
      "color": "Red",
      "taste": "Bla bla...",
    },
    "Banana": {
      "color": "Yellow",
      "taste": "Bla bla...",
    },
    "Pear": {
      "color": "Green",
      "taste": "Bla bla...",
    },
  }
}

Firebase automatically sort the items in my database by alphabetic order. Now I want to make a tableview with all the fruits listed in alphabetic order. When I tap on a fruit it will push to a new window with the informations about that specific fruit like "color", "taste", etc.
The important thing to keep in mind is that, whenever I'm adding items to my database (like more types of fruit), it has to keep showing in alphabetic order. I HAVE read the documentation, but without any luck.
How do I do this? I know how to make tableviews and create databases. But how do I connect my database to my tableview and make it print out my data from a-z? maybe by index number?
Thank you. :-)

A: You may want to consider a different structure
fruits
  fruit_id_0  <- key created with childByAutoId
    name: "Apple"
    color: "Red"
    taste: "blah blah"

From there you have a ton of options.
One option is to use .childAdded, which will iterate over all of your nodes, one at a time and leave an observer which notifies the app whenever a new child is added. The dataSource array is ordered by name in code.
let fruitsRef = self.ref.child("fruits")
fruitsRef.observe(.childAdded, with: { snapshot in
    let fruitDict = snapshot.value as! [String: Any]
    let fruitName = fruitDict["name"] as! String
    self.fruitArray.append(fruitName)
    self.fruitArray.sort() //sorts in place
    self.myTableView.reloadData()
})

From there, any time a new fruit is added the closure will be called. The newly added fruit is added, array sorted and UI updated.
If you have just a few entries the above is fine, but if you have a lot of fruit like I do, it would sort and update the tableView after each fruit is loaded, over and over which could cause flicker or other undesired results.
A better option would be to leverage the fact that .value observers occur after .child added observers. With that in mind, you can load up your entire initial dataset, and once that's complete, sort it and update the tableView. At the same time leaving an observer for new fruit which will add it to the dataSource, sort and update your UI.
Here's some code that would be initated with a button click
   func button0() {
      self.configureChildAdded()
      self.setInitialLoadCompleted()
   }

two class vars to keep track of where we are in the loading process and an array to store the fruit names
var initialLoad = true
var fruitArray = [String]()

and then two classes that will initially load and sort your fruits and leave a .childAdded observer which will watch for additional fruits and add them to the dataSource, sort, and update a tableView
func configChildAdded() {
    let fruitsRef = self.ref.child("fruits")
    fruitsRef.observe(.childAdded, with: { snapshot in //iterate over all fruits
        let fruitDict = snapshot.value as! [String: Any]
        let fruitName = fruitDict["name"] as! String
        self.fruitArray.append(fruitName)

        //upon first load, don't reload the tableView until all children are loaded
        if ( self.initialLoad == false ) {
            self.fruitArray.sort()
            self.myTableView.reloadData()
        }
    })
}

//this .value event fires AFTER the child added events to load the tableView the first time
//  all this does is update the UI and set the initalLoad to true and only fires once
func setInitialLoadCompleted() {
    let fruitsRef = self.ref.child("fruits")
    fruitsRef.observeSingleEvent(of: .value, with: { snapshot in
        self.myTableView.reloadData()
        self.initialLoad = false
    })
}

Note that using this method will totally avoid using any kind of Firebase ordering as it's done in code. This would make it much easier to do multi field ordering etc.


text:
Q: IronPython compiled exe still needs py modules I am compiling IronPython code using ipyc.exe with the following command:
ipyc /main:File1.py File2.py File3.py File4.py /target:winexe
and my exe runs properly! I put the Microsoft and IronPython DLLs and the Python .py modules in the same folder as my source code before compiling.
But now, when I try to run my executable, I still have to have the Python library files in the same folder for it to find the modules and not throw an error. Why can't it find them?
In the Windows path I have:
C:\Program Files (x86)\IronPython 2.7
C:\Program Files (x86)\IronPython 2.7\Lib
My PYPATH also has these locations.
I also tried adding
    clr.AddReferenceToFileAndPath("IronPython.Modules.dll")
and removing the Python Import statements, but I still get "No module named..." (and this also messes up Intelisense when I edit the code in VB).
Thanks.


text:
Q: ASP.NET FileUpload failure Trying to upload a large file (20MB), I set the maxRequestLength to a high enough level (and the expiration time too) in the httpRuntime entry of web.config. The Event Log stopped reporting that the post size exceeds allowed limits, but I still get the same behavior in the browser (IE or FF): "The connection to the server was reset while the page was loading." I'm using VS2008 and the built-in web server, not IIS. I've read the Q&A on this topic and even put in the check for the exception (IsMaxRequestExceededEexception) in the application global handler. This was referenced in another StackOverflow thread about this topic. Anyone had anything similar, have any ideas?
Thanks,
 Bob

A: Not come accross this myself with the built in server, however  you could try increasing the time out  too in the web.config file.
<httpRuntime executionTimeout="****" maxRequestLength="****" />

A: Figured out my problem. I put the  entry into the wrong web.config file -- I have two web apps in the same VS solution. doh!

A: Http uploads are notoriously unreliable. You should look into some other options that utilize Flash or Silverlight for file uploads.


text:
Q: C++- Duplicate data in datagridview I try to make winform to add data to database but the dat duplicated in datagridview but in the database it's not duplicated
I try data to several tables at once is there any other ways to solve?
I would like to display data in my datagridview without duplicates. I don't know how did it duplicated.
searched Stack Overflow for this kind of problem. But I found several similar problems regarding this one, but No solutions in C++

private: System::Void btnRefresh_Click(System::Object^ sender, System::EventArgs^ e) {
    MySqlConnection^ conn = gcnew MySqlConnection(ConnectionString);
    conn->Open();
    String ^ cmdString = "SELECT DISTINCT* from booking,customer,menu,menu_items,request,stuff,stuff_take_request,tables  ";
    MySqlCommand^ cmd2 = gcnew MySqlCommand(cmdString, conn);
    MySqlDataAdapter^ cmd = gcnew MySqlDataAdapter(cmd2);
    dataGridView1->ClearSelection();
    DataTable^ dt = gcnew DataTable();
    cmd->Fill(dt);
    dataGridView1->DataSource = dt;
    conn->Close();

}
private: System::Void txtserach_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
    try {
        if (e->KeyChar == (Char)13)
        {
            DataView^ dv = sqlDt->DefaultView;
            dv->RowFilter = String::Format("FirstName like '%{0}%'", txtserach->Text);
            dataGridView1->DataSource = dv->ToTable();
        }
    }
    catch (Exception^ ex)
    {
        MessageBox::Show(ex->Message, "Data Entery Form", MessageBoxButtons::YesNo, MessageBoxIcon::Information);
    }
}
private: System::Void btnSearch_Click(System::Object^ sender, System::EventArgs^ e) {
    try {

        String^ Search = txtserach->Text;
        sqlConn->ConnectionString = "Server=localhost;port=3306;username=root;password=N123;database=restaurant2";
        sqlCmd->Connection = sqlConn;
        DataTable^ adapter = gcnew DataTable();
        sqlDtA->Fill(sqlDt);
        dataGridView1->DataSource = sqlDt;

    }
    catch (Exception^ ex)
    {
        MessageBox::Show(ex->Message, "Data Entery Form", MessageBoxButtons::YesNo, MessageBoxIcon::Information);
    }
}
private: System::Void AddNew_Click(System::Object^ sender, System::EventArgs^ e) {
    String^ ID = txtID->Text;
    String^ FirstName = txtFirst->Text;
    String^ LastName = txtLast->Text;
    String^ Phone = txtmobile->Text;
    String^ ID_Booking = txtID_B->Text;

    String^ ConnectionString = "Server=localhost;port=3306;username=root;password=N123;database=restaurant2";

    MySqlConnection^ conn = gcnew MySqlConnection(ConnectionString);

    String^ Data = datam->Text;

    String^ cmdString2 = "INSERT INTO restaurant2.Booking(ID,Date) VALUES(@ID2,@Date)";
    MySqlCommand^ cmd = gcnew MySqlCommand(cmdString2, conn);

    cmd->Parameters->AddWithValue("@ID2", ID);
    cmd->Parameters->AddWithValue("@Date", Data);

    String^ cmdString = "INSERT INTO restaurant2.Customer(ID,Fname,Lname,Phone,ID_Booking) VALUES(@ID,@Fname,@Lname,@Phone,@ID_Booking)";
    MySqlCommand^ cmd2= gcnew MySqlCommand(cmdString, conn);

    cmd2->Parameters->AddWithValue("@ID", ID);
    cmd2->Parameters->AddWithValue("@Fname", FirstName);
    cmd2->Parameters->AddWithValue("@Lname", LastName);
    cmd2->Parameters->AddWithValue("@Phone", Phone);
    cmd2->Parameters->AddWithValue("@ID_Booking", ID);

    String^ Name = cboMenu->Text;
    String^ cmdString3 = "INSERT INTO restaurant2.Menu(ID,Name) VALUES(@ID3,@Name)";
    MySqlCommand^ cmd3 = gcnew MySqlCommand(cmdString3, conn);

    cmd3->Parameters->AddWithValue("@ID3", ID);
    cmd3->Parameters->AddWithValue("@Name", Name);

    String^ Item_name = txtItem->Text;
    String^ Quantity = txtQ->Text;
    String^ Price = txtPrice->Text;

    String^ cmdString4 = "INSERT INTO restaurant2.menu_items(ID, Item_name, Prices, Quantity, ID_Menu) VALUES(@ID4,@Item_name,@Prices,@Quantity,@ID_Menu)";
    MySqlCommand^ cmd4 = gcnew MySqlCommand(cmdString4, conn);

    cmd4->Parameters->AddWithValue("@ID4", ID);
    cmd4->Parameters->AddWithValue("@Item_name", Item_name);
    cmd4->Parameters->AddWithValue("@Prices", Price);
    cmd4->Parameters->AddWithValue("@Quantity", Quantity);
    cmd4->Parameters->AddWithValue("@ID_Menu", ID);

    String^ Time = txtTime->Text;

    String^ cmdString5 = "INSERT INTO restaurant2.Request(ID, Time, ID_Table) VALUES(@ID5,@Time,@ID_Table)";
    MySqlCommand^ cmd5 = gcnew MySqlCommand(cmdString5, conn);

    cmd5->Parameters->AddWithValue("@ID5", ID);
    cmd5->Parameters->AddWithValue("@Time", Time);
    cmd5->Parameters->AddWithValue("@ID_Table", ID);

    String^ cmdString6 = "INSERT INTO restaurant2.request_menu_items(ID_Request, Menu_items_id) VALUES(@ID_Request,@Menu_items_id)";
    MySqlCommand^ cmd6 = gcnew MySqlCommand(cmdString6, conn);

    cmd6->Parameters->AddWithValue("@ID_Request", ID);
    cmd6->Parameters->AddWithValue("@Menu_items_id", ID);

    String^ Fname = txtSFname->Text;
    String^ Lname = txtLname->Text;
    String^ Role = txtRole->Text;
    String^ Stuff = txtStuff->Text;

    String^ cmdString7 = "INSERT INTO restaurant2.stuff(ID, Fname, Lname, Roles) VALUES(@ID7, @Fname2, @Lname2, @Roles)";
    MySqlCommand^ cmd7 = gcnew MySqlCommand(cmdString7, conn);

    cmd7->Parameters->AddWithValue("@ID7", Stuff);
    cmd7->Parameters->AddWithValue("@Fname2", Fname);
    cmd7->Parameters->AddWithValue("@Lname2", Lname);
    cmd7->Parameters->AddWithValue("@Roles", Role);

    String^ cmdString8 = "INSERT INTO restaurant2.stuff_take_request(ID_Request, Stuff_id) VALUES(@ID_Request2, @Stuff_id)";
    MySqlCommand^ cmd8 = gcnew MySqlCommand(cmdString8, conn);

    cmd8->Parameters->AddWithValue("@ID_Request2", ID);
    cmd8->Parameters->AddWithValue("@Stuff_id", Stuff);

    String^ Type = cboMember->Text;
    String^ No_OF = TxtNO->Text;
    String^ cmdString9 = "INSERT INTO restaurant2.tables(ID, Type, Num_of_people, ID_Booking) VALUES(@ID78, @Type, @Num_of_people, @ID_Booking89)";
    MySqlCommand^ cmd9 = gcnew MySqlCommand(cmdString9, conn);

    cmd9->Parameters->AddWithValue("@ID78", ID);
    cmd9->Parameters->AddWithValue("@Type", Type);
    cmd9->Parameters->AddWithValue("@Num_of_people", No_OF);
    cmd9->Parameters->AddWithValue("@ID_Booking89", ID);

    cmd->ExecuteNonQuery();
    cmd2->ExecuteNonQuery();
    cmd3->ExecuteNonQuery();
    cmd4->ExecuteNonQuery();
    cmd9->ExecuteNonQuery();
    cmd5->ExecuteNonQuery();
    cmd6->ExecuteNonQuery();
    cmd7->ExecuteNonQuery();
    cmd8->ExecuteNonQuery();

    try {

    }

    catch (Exception^ e)
    {
        MessageBox::Show("incorrect DATA");
    }
    conn->Close();
}

private: System::Void cboMenu_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void dataGridView1_CellContentClick(System::Object^ sender, System::Windows::Forms::DataGridViewCellEventArgs^ e) {

}

A: You could refer to the following code to remove duplicate data
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
    dataGridView1->DataSource = 0;
    String^ connstr = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
    SqlConnection^ connection = gcnew SqlConnection(connstr);
    connection->Open();
    String^ sql = "Select * from QWE";
    //SqlCommand^ command = gcnew SqlCommand(sql, connection);
    SqlDataAdapter^ adapter = gcnew SqlDataAdapter(sql, connection);
    DataTable^ table = gcnew DataTable();
    adapter->Fill(table);
    DataTable ^distinctTable = table->DefaultView->ToTable( /*distinct*/ true);

    dataGridView1->DataSource = distinctTable;

    connection->Close();
}

Here is result:


text:
Q: Why doesn't OpenGL display the requested drawings correctly Greetings I'm new to OpenGL and Glut. I made a function that displays the 4 dots that make the corners of a square without uniting the dots. The problem is when I run the project, the function doesn't display anything.
I have a similar function that works with lines and displays some lines in the corners of the window which works perfectly. Please tell me what I'm doing wrong and how to fix it. Here are the two functions:

*

*Using Lines. Works perfectly
void Display2() {
    glColor3f(1,0.1,0.1);
    glBegin(GL_LINES);
        glVertex2f(1.0,1.0);
        glVertex2f(0.9,0.9);
        glVertex2f(0.8,0.8);
        glVertex2f(0.7,0.7);
        glVertex2f(0.6,0.6);
        glVertex2f(0.5,0.5);
        glVertex2f(-0.5,-0.5);
        glVertex2f(-1.0,-1.0);
    glEnd();
}

*The one with dots. Does not display anything.
void Display3() {
    glColor3f(1,0.1,0.1);
    glBegin(GL_POINTS);
        glVertex2f(100, 100);
        glVertex2f(200, 100);
        glVertex2f(100, 200);
        glVertex2f(200, 200);
    glEnd();
}

A: The default visible area in OpenGL ranges from -1 to 1 on each axis (the so-called normalized device coordinates).
In your line example, all the values are in this range and thus are visible. In the point example, the coordinates are simply outside of the screen. You can either change the coordinates to fit in the [-1,1] interval, or add a projection matrix that handles that for you.


text:
Q: Theory level obtain command In a local proof block in Isabelle I can use the very convenient obtain command, which allows me to define a constant with given properties:

proof
  ...
  from `∃x. P x ∧ Q x`
  obtain x where "P x" and "Q x" by blast
  ...

What is the most convenient way to do that on the theory or locale level?
I can do it by hand using SOME, but it seems to be unnecessary complicated:

lemma ex: "∃x. P x ∧ Q x"
  sorry

definition x where "x = (SOME x. P x ∧ Q x)"
lemma P_x: "P x" and Q_x: "Q x"
  unfolding atomize_conj x_def by (rule someI_ex, rule ex)

Another, more direct, way seems to be specification:

consts x :: nat
specification (x) P_x: "P x"  Q_x: "Q x" by (rule ex)

but it requires the somewhat low-level consts command, and worse, it does not work in a local context.
Would it be possible to have something as nice as the obtain command on the theory level?


text:
Q: how will a connector affect a transmission line? I am laying out an RS485 driver and read a few design guides which recommend a 120 Ohm termination resistor. This makes sense since the characteristic impedance of twisted pair cables is in the 100 Ohm to 150 Ohm range.
However what confuses me, is how would the signal be affected by the impedance of the PCB? There is also no mention of the connector impedance?
Should I be routing the RS485 traces as short as possible to mitigate transmission line affects on the PCB?
I understand the basics of transmission line theory, however I don't think I fully understand the implications of transmitting between two mediums. Transmission lines make more sense to me when the source and load share a consistent medium.

A: Normally trace width and separation is adjusted so that the traces will have the necessary characteristic impedance, so it looks like another transmission line just like the cable does. If the PCB traces are not very long then the mismatch is minimal even if impedance is not matched. Some connectors have controlled impedanve but not all, in this case the connector shows up as short length of transmission line with a impedance mismatch so it causes reflections that degrade the signal. But for RS485 communications, sometimes it appears to work even without termination, so with proper wiring and termination, minimizing PCB trace length and not worrying too much about the connector are good suggestions. Ideally the connector would have the same impedance as well.


text:
Q: Is there a safe vga video driver that supports high resolutions? My laptop is affected by the famous "defective nVidia card" problem. It used to work fine, but since yesterday any attempt to use 3d features causes the system to BSOD (Windows) or freeze (Linux).
Actually, at first Windows wouldn't even boot anymore.
Luckily, 2d usage seems to work fine: on Linux, after disabling the nvidia proprietary driver, I'm able to work perfectly well at 1680x1050 (Compiz is disabled of course).
Likewise, on Windows, after uninstalling the nVidia driver from safe mode, I'm able to boot.
But, the "vga safe" driver that comes with Windows Vista does not support resolutions higher than 1280x1024@32 or 1400x1050@16.
Now, the question is:

*

*is it possible to add an additional mode to the safe vga driver, namely 1680x1050@32?

*if not, is there a third party generic vga driver that supports that resolution?

A: Not safely, and it needs card support anyways.


text:
Q: computing cos similarity of 2 row vectors, not all pairwise cdists I have two pandas df trigger and action that contain 25-dimensional feature vectors written in the rows and want the cosine similarity between correspondent rows. The code below produces the 20675 x 20675 matrix of pairwise cosine similarities:
trigger.shape
(20675, 25)
action.shape
(20675, 25)
from scipy.spatial.distance import cdist
result = cdist(trigger, action, metric='cosine')
result.shape
(20675, 20675)

I would like to end up with a result matrix that has shape 20675 x 1 where each row is the cosine similarity between the corresponding row vectors from trigger and action.
I've searched and can't find a way to do this.

A: You could compute the cosine similarity by yourself.
from scipy import lingalg
cosineSim1 = 1 - np.sum(a * b, axis=-1)/(linalg.norm(a,axis=-1) * linalg.norm(b,axis=-1))

Test whether you get correct values:
from scipy import spatial
cosineSim2 = []
for row_a, row_b in zip(a,b):
    cosineSim2.append(spatial.distance.cosine(row_a, row_b))
np.allclose(cosineSim1, cosineSim2). # Should output True

Timing tests:
timeit.timeit(func1, number=100)   # computes cosineSim1
0.006364107131958008

timeit.timeit(func2, number=100)  # computes cosineSim2
0.34532594680786133


text:
Q: Network adapter only works with ethernet switch I have a Dell XPS13(Win 10 Pro) and since we dont have wireless lan in the office i had to buy an external ethernet adapter (DA200).
The adapter works perfectly fine at home but it doesnt work at all in the office(not even the lights on the adapter are flashing) while i dont have any problems when connecting other computers to the ethernet socket.
However if i connect the adapter to an ethernet switch it works.
The laptop is part of a Win 2003 domain and on the server is a dhcp installed.
Is it possible that the adapter doesnt get an ip from the dhcp server?
Thanks in advance.

A: There is a chance that the network jack is wired wrong, and is acting as a crossover cable. Most modern NICs support auto MDIX, and can deal with this gracefully, but your dongle may not support this.
If you have a crossover network cable around, then put that in place between the dongle and the wall to see if that fixes it. If it does, you have wiring problems. If you do not have a crossover cable, then you'll need to verify that the terminations on both ends of the run are correct.

A: You may just have a bad (malfunctioning) adapter. I had a similar experience with a USB3 gigabit adapter I bought from Monoprice a while back.
The symptoms it displayed sound identical to what you're experiencing with yours. Basically, it was super picky about which switches/hubs it would actually work on. At home on an HP ProCurve in my office, no problem. At work directly connected to whatever switch was in the network closet, no joy. But throw a cheapo dumb switch in between it and the and the wall jack, and it works fine again. At first I chalked it up to a bad chipset. But a friend of mine got the same model and while his had its own issues, it worked where mine didn't and in some cases, vice-versa.
I ended up just buying a different model of adapter (this one) and it works great. I never did find any rhyme or reason regarding what caused it to work or not.

A: Typically, office network connections go like this:
Network /__\ Network /__\ Rack /__\  Wall /__\ Desk /__\ Network /__\ Network
Switch  \  /  Cable  \  / Port \  / Cable \  / Port \  /  Cable  \  / Adapter

Troubleshooting link-level problems usually lies in isolating each of these pieces and testing one by one. From what you've said, you've tested this as a whole, and tested switch <--> cable <--> adapter directly, bypassing the rack port, wall cabling, desk port, and far end cable. The first failed, the second succeeded. So the problem would lie in the pieces you've taken out. But I want to ensure that we've actually tested the same switch port and cable that was in the chain when it didn't work. Make sense?
If each piece tests OK, then the last thing to check would be the configuration of each.  For instance, if you've hard-set the switch port to 100-Full and the adapter is trying to autonegotiate, it could cause problems. The ethernet standard (IIRC) says it shouldn't work, but vendors sometimes try to "help" and make it work anyway, leading to different results with different gear.


text:
Q: How to host a video locally in Android I am working on a app that host a video(.mp4) from a primary
Android device.
Say in http://192.168.43.88:8080/*.mp4 and the secondary device
connected using wifi will be able to stream the video (with a MediaController object and MediaPlayer)
I am have trouble finding any such example codes for selecting a video and hosting it from the Android device.
Here are some question I looked at
Stream live video from phone to phone using socket fd
https://code.google.com/p/ipcamera-for-android/

A: it may be easier to have a webhost on your phone on said port that opens up to a flash player that plays whatever video you've linked or is in a specific folder. an ip camera would only broadcast your camera. to play or stream a video, you need a video player. either the host (your phone) would need to have a video player on a web server.. or the client's browser (your computer) would need an mp4 player, else the file would just download from your phone to the computer. for the flash player, you could make it full screen and thus make it look nice.


text:
Q: android app not able to get GPS until phone restarts I am getting multiple reports from users that they can't get GPS or location services in my app until they restart their phone, and then everything works no problem.
I only get a limited sample of android users complaints, from the set of users that use my apps but it seems shockingly similar to this issue:
https://code.google.com/p/android/issues/detail?id=39745
Google OTA updates rolled out to some additional carriers last week. Looking through my code changes over the last several months, I haven't changed any GPS/positioning stuff except in cases where I had to use the new google maps, but I can't tell if my particular user complaints are coming from a very old version or an upgrade from a very recent version or whatever version.
It appears to be related to Android 4.2 but I can't confirm that either, except the similarity of users restarting their phone and everything magically solves itself. I don't consider this a valid troubleshooting option though for my users.
Basically wondering if anyone else has solved this in code, and also putting it here in case other developers can relate to this


text:
Q: RelativeSource binding on GridViewColumnHeader not working I have a listview like below. The tool tip shows fine but the context menu does not bind. I have the reference for vw like
xmlns:vw="clr-namespace:WpfModelViewDemoApplication.Views" in Window tag.
Thanks for any help.
<ListView x:Name="lstView" Grid.Row="2" BorderBrush="White" ItemsSource="{Binding Path=Students}" HorizontalAlignment="Stretch">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Name}">
                <GridViewColumnHeader Content="Name" Style="{StaticResource GridViewHeaderStyle}"
                                      MouseDown="GridViewColumnHeader_MouseDown" MouseUp="GridViewColumnHeader_MouseDown"
                                      Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type vw:MainView}}}">
                    <GridViewColumnHeader.ContextMenu>
                        <ContextMenu Name="DisplayColumns" DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                            <MenuItem Header="Time Added" IsCheckable="True" IsChecked="True"/>
                            <MenuItem Header="{Binding Tag.Comments}" IsCheckable="True" IsChecked="True"/>
                        </ContextMenu>
                    </GridViewColumnHeader.ContextMenu>
                </GridViewColumnHeader>
            </GridViewColumn>
            <GridViewColumn Header="Score" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" DisplayMemberBinding="{Binding Path=Score}" />
            <GridViewColumn Header="TimeAdded" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Path=TimeAdded}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type vw:MainView}}}">
                            <Button.ToolTip>
                                <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                                    <TextBlock Text="{Binding Tag.Comments}"/>
                                </ToolTip>
                            </Button.ToolTip>
                        </Button>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView >
    UPDATE: Found the answer if anyone needs it

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:c="clr-namespace:WpfModelViewDemoApplication.Commands"
    xmlns:vw="clr-namespace:WpfModelViewDemoApplication.Views"
    xmlns:vm="clr-namespace:WpfModelViewDemoApplication.ViewModels"
    x:Class="WpfModelViewDemoApplication.Views.MainView"
    mc:Ignorable="d"
    d:DataContext="{DynamicResource MainViewModel}"
    x:Name="MainWindow"
    FontFamily="Verdana"
    Title="WPF MVVM Tutorial">
<Window.Resources>
    <vm:MainViewModel x:Key="MainViewModel"/>
    <DataTemplate x:Key="ResourceItemTemplate">
        <GridViewColumnHeader Content="Name"  Tag="{Binding DataContext, ElementName=MainWindow}">
            <GridViewColumnHeader.ContextMenu>
                <ContextMenu s>
                    <MenuItem Header="Time Added" IsCheckable="True" IsChecked="{Binding PlacementTarget.Tag.IsTimeAddedSelected,RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                    <MenuItem Header="Comment" IsCheckable="True" IsChecked="{Binding PlacementTarget.Tag.IsCommentSelected,RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </GridViewColumnHeader.ContextMenu>
        </GridViewColumnHeader>
    </DataTemplate>
    </Window.Resources>

      <ListView x:Name="lstView" Grid.Row="2" BorderBrush="White" ItemsSource="{Binding Path=Students}" HorizontalAlignment="Stretch">
        <ListView.View>
            <GridView>
                <GridViewColumn HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" HeaderTemplate="{StaticResource ResourceItemTemplate}" DisplayMemberBinding="{Binding Path=Name}"/>
                <GridViewColumn Header="Score" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" DisplayMemberBinding="{Binding Path=Score}" />
                <GridViewColumn Header="TimeAdded" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="{Binding Path=TimeAdded}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type vw:MainView}}}">
                                <Button.ToolTip>
                                    <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                                        <TextBlock Text="{Binding Tag.Comments}"/>
                                    </ToolTip>
                                </Button.ToolTip>
                            </Button>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView >

A: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c="clr-namespace:WpfModelViewDemoApplication.Commands"
xmlns:vw="clr-namespace:WpfModelViewDemoApplication.Views"
xmlns:vm="clr-namespace:WpfModelViewDemoApplication.ViewModels"
x:Class="WpfModelViewDemoApplication.Views.MainView"
mc:Ignorable="d"
d:DataContext="{DynamicResource MainViewModel}"
x:Name="MainWindow"
FontFamily="Verdana"
Title="WPF MVVM Tutorial">
<Window.Resources>
<vm:MainViewModel x:Key="MainViewModel"/>
<DataTemplate x:Key="ResourceItemTemplate">
    <GridViewColumnHeader Content="Name"  Tag="{Binding DataContext, ElementName=MainWindow}">
        <GridViewColumnHeader.ContextMenu>
            <ContextMenu s>
                <MenuItem Header="Time Added" IsCheckable="True" IsChecked="{Binding PlacementTarget.Tag.IsTimeAddedSelected,RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                <MenuItem Header="Comment" IsCheckable="True" IsChecked="{Binding PlacementTarget.Tag.IsCommentSelected,RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
            </ContextMenu>
        </GridViewColumnHeader.ContextMenu>
    </GridViewColumnHeader>
</DataTemplate>
</Window.Resources>

  <ListView x:Name="lstView" Grid.Row="2" BorderBrush="White" ItemsSource="{Binding Path=Students}" HorizontalAlignment="Stretch">
    <ListView.View>
        <GridView>
            <GridViewColumn HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" HeaderTemplate="{StaticResource ResourceItemTemplate}" DisplayMemberBinding="{Binding Path=Name}"/>
            <GridViewColumn Header="Score" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}" DisplayMemberBinding="{Binding Path=Score}" />
            <GridViewColumn Header="TimeAdded" HeaderContainerStyle="{StaticResource GridViewHeaderStyle}">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Path=TimeAdded}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type vw:MainView}}}">
                            <Button.ToolTip>
                                <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                                    <TextBlock Text="{Binding Tag.Comments}"/>
                                </ToolTip>
                            </Button.ToolTip>
                        </Button>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView >


text:
Q: Why doesn't the fridge condense water like an air conditioner? Simple question, why doesn't the fridge condense water like an air conditioner?
I know that my ac condenses water (even in cool or heat) and don't know why the fridge doesn't. Aren't they both supposed to work the same way?
If not, then why not build ac's like fridges? I mean, they both do the same, cool some room space.
Maybe the fridge does condense water and I just don't see it, if this is the case, then where does the water go?

A: Short version: it does.
The first difference is that the fridge has a small, enclosed volume of air that it cools. There is a pretty limited amount of water vapour in the fridge to be condensed out at any time. Once it is all gone, there is no more until the fridge door is opened to let some new air in (although only some of the air will be replaced each time). The volume of air in a fridge is unlikely to contain more than a gram or two of water (a few cubic centimeters at most).
The AC on the other hand has an effectively unlimited source of water vapour.
Water that condenses out within the fridge can go on to the inner surfaces of the fridge, but can also go on to items in the fridge (and thus get taken out when items are removed). Some cardboard containers in my fridge are noticably damp when I remove them. Milk containers usually have some water condensed on them.
I've no idea whether vegetables or fruit in a fridge can account for absorbing some of the water vapour (equally they might be a source of water vapour) - they are a possible confounding factor.
Basically, the rate at which new water vapour is added to the fridge via the door opening is pretty low, and removing items from the fridge is likely to be a net removal of condensed water from the fridge, so the reservoir of water vapour condensed into liquid within the fridge at any time is pretty small, and when spread over all the potential surfaces and objects within the fridge, is not that noticable.
Plus every fridge I've ever had has also had a small drainage hole at the back of the compartment (the back wall being the coldest), although I've no idea where it drains off to.


text:
Q: Swagger showing "Found unknown parameters" error I tried to create stubs for sample swagger specification as mentioned in Swagger CodeGen Documentation, but it  does not work as intended to.
Exception in thread "main"
io.airlift.airline.ParseArgumentsUnexpectedException:
Found unexpected parameters: [-i, http://petstore.swagger.io/v2/swagger.json, -l, java]  at io.airlift.airline.Cli.validate(Cli.java:148)
 at io.airlift.airline.Cli.parse(Cli.java:116)
 at io.airlift.airline.Cli.parse(Cli.java:97)
 at io.swagger.codegen.SwaggerCodegen.main(SwaggerCodegen.java:36)

A: The solution of this issue on Swagger Documentation for creating server stub
documentation page.
Below is the command in case the link is obsolete or does not work :
java -jar swagger-codegen-cli-2.2.1.jar generate -i http://petstore.swagger.io/v2/swagger.json -l java


text:
Q: can't push subtree branch I have a git repository containing an application, and I want to use a subdir of that repo to update a shared library repository.  I can fetch the library repo, commit an update, but I cannot make it push that commit back to the remote.  It should be a fast-forward, but it says it is not.  What am I doing wrong?
$ git remote add lib goertzen@minerva:/pub/shared_git_repositories/lib.git

$ git fetch
From minerva:/pub/shared_git_repositories/lib
 * [new branch]      master     -> lib/master

$ git checkout -b libmaster lib/master
Branch libmaster set up to track remote branch master from lib.
Switched to a new branch 'libmaster'

$ git merge --squash -s subtree -X theirs master
Auto-merging lib.yaml
Squash commit -- not updating HEAD
Automatic merge went well; stopped before committing as requested

$ git commit -m "blah blah blah"
[libmaster 4949ef3] blah blah blah
 1 files changed, 148 insertions(+), 95 deletions(-)

$ git push lib
To goertzen@minerva:/pub/shared_git_repositories/lib.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'goertzen@minerva:/pub/shared_git_repositories/lib.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

$ git pull
Already up-to-date.

$ git log --graph --all --full-history --branches --decorate
* commit 4949ef3181c21d85340b9fb16af5f9c2c58e75ae (HEAD, libmaster)
| Author: <snip>
| Date:   Tue Mar 8 15:25:03 2011 -0600
|
|     minitransfer changes
|
* commit e2dca9e2bcd28d09a455e9cc662f7eb630a0adc2 (lib/master)
  Author: <snip>
  Date:   Thu Feb 24 10:54:31 2011 -0600

      initial commit of shared lib repo

* commit b70bde69e5c4ddb079d06d7310d415fa89764b95 (origin/master, origin/HEAD, master)
| Author: <snip>
| Date:   Fri Mar 4 15:41:05 2011 -0600
|
|     fix typo
|
* commit cc64b565fbb88729e16314f76867ab24c37bfc47
| Author: <snip>
| Date:   Fri Mar 4 15:38:59 2011 -0600
|
...

I can replace the squashed subtree merge with a trivial edit, and I still have the same issues.

A: It turns out "git push lib" was actually trying to push libmaster to origin/master instead of lib/master (I experimented on some sacrificial repos).  When I spelled it all out in detail like this...
git push lib libmaster:master

...it worked.
I would of course like to be able to push without having to spell it out in detail.  This leaves me wondering if I brought lib into the repo in an odd way, or if I need to configure the branch somehow.  I have some reading to do...

A: Do as Git says and run git pull first...


text:
Q: Correct usage of a counter using arcpy.da.UpdateCursor In the Python code inside a Calculate Value tool in my model, I have the following:
getNum("%Selected Features%")

def getNum(ftr):
  lst = [4, 11, 15] #values for SQL expression
  x = 20
  fields = ('TYPE_A', 'TYPE_B', 'NUM_ID')
  for l in lst:
    y = x + 1
    whereclause = """"NUM_ID" = %s """ % l
    with arcpy.da.UpdateCursor(ftr, fields, whereclause) as cursor:
      for row in cursor:
        if row[0] ! = row[1]:
          row[2] = y
        cursor.updateRow(row)
    y += 1

What I would like to do is, for every element in lst, create a cursor based on a selection of records where NUM_ID = l. The values in TYPE_A and TYPE_B should be compared for each record and updated if necessary.
The script is failing after the cursor is created, with the error Item not in collection. If I remove the whereclause, it executes. Once the records have been selected and the values compared and updated if necessary, I need to increment the counter y by 1. I think I'm doing it in the wrong place though, because if I run the script without the whereclause it does execute correctly.When I check the records with the changed values, they are now all set to y, which indicates that y was not incremented.

A: Couple of points that might help:

*

*You redefine the value of y at the beginning of your for loop, so every time the loop is executed y is reset to x + 1. Instead set y outside the loop:

y = x + 1
for l in lst:
    #...

*

*Depending on the type of feature class you're using ArcGIS requires different delimiters around field names. For example, [PERSONAL_GDB] vs "FILE_GDB". To prevent having to worry about this you can use the AddFieldDelimiters arcpy function to get back the correctly delimited fields.

#Using dictionary string-formatting
whereclause = "%(sql_name)s = %(l)i """ % {"sql_name":arcpy.AddFieldDelimiters(ftr, "NUM_ID"), "l":l}

*

*Lastly you should probably check that NUM_ID exists in your feature class as otherwise the cursor will fall over. You can use ListFields for this.

assert "NUM_ID" in [f.name for f in arcpy.ListFields(ftr)], "NUM_ID field no in feature class"

A: In addition to @om_henners great suggestions, it seems to me like you could use an IN statement to reduce the number of queries to the database from len(lst) to 1. I have an example function to build such a WHERE clause in this answer: Select features by attribute if in Python list


text:
Q: Alice and Bob picking game Alice and Bob play the following game. There is one pile of $N$ stones. Alice and Bob take turns to pick stones from the pile. Alice always begins by picking at least one, but less than $N$ stones. Thereafter, in each turn a player must pick at least one stone, but no more stones than were picked in the immediately preceding turn. The player who takes the last stone wins. With what property of $N$, will Alice win? When will Bob win?
For odd $N$ the outcome is quite clear, as Alice will start by picking one stone and will enforce the win. But what then?

A: Alice wins when $N$ is not a power of 2.
Let $i(N)$ be the maximal $i$ such that $N$ is divisble by $2^i$.
Alice's strategy: If there are $m$ stones left, Alice picks $2^{i(m)}$ stones.
Let me explain why this strategy is winning for Alice.  Assume that Bob won by picking $b > 0$ remaining stones. Assume that before that Alice picked $2^j$ stones. By definition $j = i(2^j + b)$. Hence $2^j + b$ is divisible by $2^j$. Therefore $b$ is also divisible by $2^j$. This means that $b\ge 2^j$. On the other hand by the rules of the game $b\le 2^j$. Therefore $b = 2^j$.
But then $i(2^j + b) = i(2^j + 2^j) = j + 1$, contradiction.
This strategy is correct because (a) since $N$ is not a power of 2, Alice picks less than $N$ stones in the first turn; (b) Alice never picks more stones than Bob in the previous turn. Indeed, assume that Bob picked $b$ stones, before Alice picked $2^j$ stones, and we are left with $m > 0$ stones.
Let us verify that $2^{i(m)} \le b$. We will do it by showing that $b$ is divisble by $2^{i(m)}$.
Indeed, by definition of Alice's strategy $j = i(2^j + b + m)$ and by the rules of the game $b\le 2^j$. Let us show that $i(m) \le j$. Indeed, if $i(m) > j$, then $b$ is divisble by $2^j$, since both $2^j + b + m$ and $m$ are divisble by $2^j$. But since $b\le 2^j$, this means that $b = 2^j$. This contradicts the fact that $j = i(2^j + b + m)$. Indeed, since $i(m) > j$, we have that $i(2^j + b + m) = i(2^{j + 1} + m) \ge j + 1$.
Thus we have proved that $i(m) \le j$. This means $2^j + b + m$ is divisble by $2^{i(m)}$, as well as $m$. Hence $b$ is also divisble by $2^{i(m)}$ as required.
Bob wins when $N$ is a power of 2.  Assume that $N = 2^i$ and Alice picks $a$ stones. Then Bob can use Alice's strategy described above. We only have to check that Bob then picks at most $a$ stones. Indeed, assume that $j$ is such that $2^i - a$ is divisible by $2^j$. Then $a$ is also divisible by $2^j$ hence $2^j \le a$.

A: First, we establish that whenever $N = 2^m$, Bob wins. We'll do this by induction. Suppose Bob is guaranteed victory for $2^k$ stones. Consider a game starting with $2^{k+1}$ stones. These can be grouped into two groups of $2^k$ stones each. Since Bob has a winning strategy for $2^k$ stones, He has a strategy which will allow him to play a move which finishes the first group of $2^k$ stones, forcing Alice to play with $2^k$ stones remaining. This is a situation where Bob wins, by our hypothesis. The base case is easy - If there are only 2 stones, Bob wins.
If $N \neq 2^m$ then Alice wins . In such a case, write $N = 2^k +r$, where $2^k$ is the largest power of $2$ which is still smaller than $N$. Alice can then start by taking off $r$ stones. Now, since $r$ < $2^k$, Bob can't take away all the stones that are left. So Bob is forced to play with $2^k$ stones remaining, which Alice now wins (Bob is the one playing the move when $2^k$ stones are left.)


text:
Q: Import nested partitioned parquet file into Big Query table I have parquet files in cloud storage which are nested partitioned on year -> month ->day. I want this file to be ingested into Big query table. How do I do this? I am new to GCP.
Thanks in advance

A: You can use Cloud Shell in your GCP project and execute the following command:
bq load \
--source_format=PARQUET \
dataset.table \
"gs://mybucket/my_file.parquet"

Replacing the values with your own dataset, table and Cloud Storage URI path of your parquet file.
Alternatively, and probably simpler, you can also use the web console to load your parquet file into BigQuery.


text:
Q: Method not working completely? What could be the error? I was just working on some project and I could not find out what's wrong with the following code :

double getInterest(double amt,double tax){
        double diff=0;
        double refund=0;
        double interest=0;
        if(amt>=(tax*0.4)){
           diff=amt-(tax*0.4);
           System.out.println(" "+diff);  //This is not working.Nothing gets printed.
           refund=diff;                   //The value is not being assigned to refund.
        }                                 //refund remains to be 0 throughout.
         interest=diff*0.01*12;
         if(refund>0){
            JOptionPane.showMessageDialog(null,"Your refund is: "+refund);
         }
        return interest;
}

I can't figure out any error in the code. But it is still not working completely.
The errors are given in the code in the form of comments.
Anyone help me to figure out the errors and reslove the issue?
I don't know why the value of diff is not getting printed and why the value of diff is not being assigned to the variable refund.
I'm working in NetBeans and it's not giving any kind of compile-time error.
I've tried to check the values by using the println for both diff and refund But the values are not getting printed.

A: Well if the statements in the if block are never executed, that implies that there is never a call to this method where the arguments meet the condition amt >= (tax*0.4). So the real question is, what values are you passing to this method?

A: Your bracketing on the
if(amt>=(tax*0.4){
line is missing a closing ) bracket before the first { bracket. Make sure you check your bracketing and make sure you have all errors turned on in the options menu (if you can).
This code should not compile because of the bracketing error. Check that Netbeans is compiling the right project as this should go crazy at compile time.

A: You should always use the BigDecimal type when dealing with currency to avoid double precision issues.
Here is the code rewritten in BigDecimal
BigDecimal getInterest(final BigDecimal amount, final BigDecimal tax) {
    BigDecimal diff = BigDecimal.ZERO;
    BigDecimal refund = BigDecimal.ZERO;
    BigDecimal reducedTax = new BigDecimal("0.4").multiply(tax);
    System.out.println("Amount is " + amount + ". Tax times 0.4 is " + tax + ".");
    if (amount.compareTo(reducedTax) >= 0) {
        diff = amount.subtract(reducedTax);
        System.out.println(diff);
        refund = diff;
    }
    BigDecimal interest = diff.multiply(new BigDecimal("0.01")).multiply(new BigDecimal("12"));
    if (refund.compareTo(BigDecimal.ZERO) > 0) {
        JOptionPane.showMessageDialog(null, "Your refund is: " + refund);
    }
    return interest;
}

Yes, I know it's much uglier. It will also be much slower. But it's new correct.
Onto your issue, presumably the code is not entering the if because amount was not greater than tax * 0.4 - if you are sure that it was then maybe you have already encountered double precision issues.
I have added a println before the if so you can see what the values are before the test happens.


text:
Q: ERR_ADDRESS_INVALID trying to connect to docker container
I'm getting started with docker using  docker-toolbox on win 10 home. I'm experimenting with scrapy splash project (https://github.com/scrapy-plugins/scrapy-splash). I've installed the toolbox on a flash drive (e:)
If I understand correctly I have installed docker using the docker toolbox. When I click on the docker quickstart terminal, I get the screenshot.
I ran:
$ docker-machine start

but when I :
$ docker run -it scrapinghub/splash
2019-05-25 22:33:53+0000 [-] Log opened.
2019-05-25 22:33:53.053632 [-] Splash version: 3.3.1
2019-05-25 22:33:53.054895 [-] Qt 5.9.1, PyQt 5.9.2, WebKit 602.1, sip 4.19.4, Twisted 18.9.0, Lua 5.2
2019-05-25 22:33:53.055695 [-] Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609]
2019-05-25 22:33:53.056773 [-] Open files limit: 1048576
2019-05-25 22:33:53.057319 [-] Can't bump open files limit
2019-05-25 22:33:53.165435 [-] Xvfb is started: ['Xvfb', ':1788299128', '-screen', '0', '1024x768x24', '-nolisten', 'tcp']
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
2019-05-25 22:33:53.257636 [-] proxy profiles support is enabled, proxy profiles path: /etc/splash/proxy-profiles
2019-05-25 22:33:53.258827 [-] memory cache: enabled, private mode: enabled, js cross-domain access: disabled
2019-05-25 22:33:53.422507 [-] verbosity=1, slots=20, argument_cache_max_entries=500, max-timeout=90.0
2019-05-25 22:33:53.424799 [-] Web UI: enabled, Lua: enabled (sandbox: enabled)
2019-05-25 22:33:53.426021 [-] Site starting on 8050
2019-05-25 22:33:53.426778 [-] Starting factory <twisted.web.server.Site object at 0x7efcd8d8dcc0>
2019-05-25 22:33:53.427649 [-] Server listening on http://0.0.0.0:8050

I tried to open the browser at
http://0.0.0.0:8050

But get the error in the title. What am I doing wrong?
edit:
I had to remove prior container by :
docker container ls
docker rm -f <container-name>

Then it worked at :
http://192.168.99.100:8050/

A: You missed the publishing part.
docker run -it -p 8050:8050 scrapinghub/splash


text:
Q: python create a data frame with one row by a list (Nice way without "reshape" ) Assume  we have data, and columnNames e.g. dataExample = [1,2] columnNames = ['a','b']
we want to create a python dataframe like:
    a   b
0   1   2

Surprsingly, writting
df = pd.DataFrame( dataExample  , columns  = columnNames  )

gives  error, since data (i.e. [1,2]) is shaped like (2,1) and columns requires shape (1,2)
So the way round can be
df = pd.DataFrame( np.array([1,2]).reshape(1,-1)  , columns  = ['a','b'] )

It works,  but, it seems not quite "nice"/"one-line" as I naively expect the answer should be.
Question:
is there some "nice"/"shorter" way ?

Another way to do the same, but still not "nice"/"one line"
df = pd.DataFrame( columns  = ['a','b'], index = [0] )
df.loc[0] = [1,2]

But again it does not look like "nice"/"short" as I would expect

There is related question:
python create a data frame with one row by a list
But it does not answer my question

A: Use list of list:
dataExample = [1,2]
columnNames = ['a','b']
df = pd.DataFrame( [dataExample]  , columns  = columnNames  )
print (df)
   a  b
0  1  2