text:
Q: How to disable multiple-scroll effect in osx and fire scroll event once per scroll I need to organise navigation like jquery.fullPage: when I scroll once - I move to next section.
I tried to use jquery.mousewheel for it, but it fails in MacOS with touchpad or trackpad or APPLE Magic Mouse: It scrolls multiple slides per one scroll.
I tried to use this solution: https://github.com/jquery/jquery-mousewheel/issues/36#issuecomment-67648897
It works fine in Chrome, but it does not in FF and has bugs in Safari.
This is simple demonstration of issue:
http://jsfiddle.net/ss5LueLx/13/
$slider.on('mousewheel', function(event) {
    if (event.deltaY>0) {
        slider.prevSlide();
    } else {
        slider.nextSlide();
    }
});

A: I tested this statement in my SeaMonkey browser and it fails.
var delta  = e.type == 'mousewheel' ? e.originalEvent.wheelDelta * -1 : 40 * e.originalEvent.detail;

Just in case, I looked at the deltaY and it works: +1 in one direction and -1 in the other, just as you determined in the other two implementations you have.
console.log(e.deltaY); // view console in FireBug

Looking at the event structure in Firebug, I can see that the event type is "mousewheel", and yet I do not see a wheelData field in the originalEvent.
And although there is a detail field, but that one remains at zero.
I would imagine that you are attempting to go to the next item only once you reach +/-3. I would suggest something of the sort to accomplish this feat:
// somewhere, initialize to zero
var current_position = 0;

// on mousewheel events
current_position += e.deltaY;

// you had a x 40 which would indicate that the limit is about 120 / 40
// if 3 is too small, you can always increase it to 5 or event 10...
if(current_position <= -3)
{
  slider.nextSlide();
  current_position = 0;
}
else if(current_position >= 3)
{
  slider.prevSlide();
  current_position = 0;
}

Otherwise you could verify that your allowScroll flag works as expected. I do not program objects that way so I am not too sure whether it is correct or not. (I use the prototype syntax which is useful if you want to extend classes.)


text:
Q: how can I check when was my db(my sql db) last restored successfully in aws how can I check when was my db(my sql db) last restored successfully in aws?
I want to know how old db we are using , like for ec2 instances we can see the launch time of server, but how can i do that for db?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximal sum of diagonals in convex quadrilateral Among all convex quadrilaterals with given sides(and their order), which one does have maximal sum of diagonals? Does it have any other interesting properties?
I thought about something like this: let $A = (0; 0), C = (x; 0)$ (i. e. fix the length of one diagonal), then we can find points $B$ and $D$, so the desired sum is a function of $x$ with a  lot of roots, and we can just find its maximum. But:

*

*Derivative is very cumbersome.

*We need to ensure not only that $ x \le \min(a + b, c + d)$ but also that resulting quadrilateral is convex, I'm not sure what limits it puts on x.

Any thoughts? Maybe it is just cyclic quadrilateral, but it doesn't look so.

A: This is not an answer (sorry!), but may point toward an answer. A quadrilateral with all four side lengths given forms what is known as a four-bar linkage. The motions of these linkages have been heavily studied.
The paper "Simple Proofs of a Geometric Property of Four-Bar Linkages"
by Godfried Toussaint (Amer Math Monthly 2003) says in its abstract

For convex and crossing linkages, one diagonal increases if and only if the other decreases.

I cannot access the paper now, but it may point to an answer.
The cyclic quadrilateral maximizes area, but I agree, not the diagonal sum.

A: If the side lengths are given to you, you can plot a circle of the respective side lengths as radius from the two points and see where the intersect.
So you would plot circles of length $BC$ and $CD$ from $C$, and circles of length $AB$ and $DA$ from $A$, and see where these intersect with the circles from $C$ respectively, to get $B$ and $D$.
To get a convex quadrilateral, you would have to keep the points $B$ and $D$ on opposite sides  of the diagonal $AC$.
This should give you the length of the second diagonal in terms of $x$, and then you can use calculus.


text:
Q: Destroy event not propagating from Backbone model to Backbone collection I have a backbone collection of models.
MyCollection = Backbone.Collection.extend({
   model: myMymodel;
});

MyModel = Backbone.Model.extend({
...
});

Each model has a view
myView = Backbone.View.extend({
  initialize: function() {
    this.model = new MyModel();
  };
});

There is no persistence on the server-side.  This is just for structuring client-side information.  So the models do not have ids, and a url for Backbone.sync has not been configured.
From within the view, I want to remove the model from the collection.
I have tried the following:
this.model.trigger( "destroy" );

However it does not work.  The destroy event is not propagating to the collection.
Any idea what I'm doing wrong?
Thanks,

A: I think you are not instantiating the collection at all. Cant make out that from the code at least. If you are just creating a model instance but not adding it to any collection, this.model.trigger("destroy"); will do nothing.
myView = Backbone.View.extend({
  initialize: function() {
    this.coll = new MyCollection();
    this.model = new MyModel();
    this.coll.add(this.model);
  };
});

Now that the model is part of the collection:
this.model.destroy()

Makes a delete api call and gets removed from the collection
this.collection.remove(this.model)

Removes the model from the collection but does not make a delete api call.
this.model.trigger("destroy");

Triggers a destroy event on the model but does not destroy the model as such. sames as collection.remove(this.model) if model is part of the collection.

A: collection.remove(model) would be a more appropriate function to use since you're not persisting your models on the server-side. Backbone.Collection.remove


text:
Q: Client Side calls to Page Methods/WebMethod or Update Panel SharePoint 2010 I am trying to figure out the best practice methodology for being able to update the client in my web application. I am working on a User Administration screen and the data is very dynamic hence the need to update the client often. I am confused as to what is the prefered or best approach though. I finally got WebMethods working in my SharePoint environment and came across this video What not to do in ASP.NET. Which says don't use Page Methods anymore. However I have also come across this which states why using the Update panel is dangerous. I like the idea of using Jquery and Ajax and putting the [WebMethod] in my code behind. I know it has to be static, but that is ok for me.
   [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string JsonMSG()
    {
            string MSG = "Hey I'm not JSON";

            return MSG;

    }

Really confusing as to what is correct or prefered way. I mean, I guess I could create a WCF service, but is that old now too. Should I use ASP.NET Web API? SignalR? Also very confused as to which framework using which file extension .svc and .asmx. I wish MS would just stick to standard. If anything I think RestFul is the way I want to go.

A: That's my post about UpdatePanels that you linked to. So, you know I've been a fan of using the static [WebMethod] approach.
I think that approach still is a great improvement over an UpdatePanel when it comes to efficiency, but if ASP.NET Web API is also a choice then you should absolutely go with that. Web API is hands-down more flexible and powerful, without sacrificing very much simplicity at all.


text:
Q: AngularJS ui-router reverting to otherwise when ng-click is used I'm playing around with AngularJS as a learning exercise.  I'm trying to get to grips with AngularJS ui-router (https://github.com/angular-ui/ui-router) and I've hit a bit of a brick-wall with an issue I'm having.
I've put a plunk together to illustrate and reproduce.
http://plnkr.co/edit/OvmOKPMfeFqNWc7ToCff?p=preview
The above is a simple wizard type component with tabs across the top to move to a particular step, and some next/back buttons at the bottom to move to the next relevant page.
The tab navigation at the top works fine, and clicking along moves changes the view and URL accordingly.
However the behaviour of the next/back buttons are quite strange insofar they work the first time you click next, but not afterwards.  You should be able to see what I'm talking about in the plunk.
It's looks like it tries to navigate to the correct view, but then immediately reverts to the otherwise rule.
I've added hooks into the code to trace through in the console.  In essence all the next/back buttons do is called the relevant state so $state.go("step1"), $state.go("step3"), etc.
Hope I've provided enough info and would appreciate any insight anyone can bring.
Thanks.

A: You have to remove the '#' from the href attr on the anchors.

A: I haven't been able to figure out the exact cause, but it looks like the primary difference is with the provided relative stateObject that is passed to $state.go().
If you debug the source for ui-sref, you will notice their use of the go function:
$state.go(ref.state, params, { relative: base });
If you compare the base object used by your links, and the default ($state.$current) used by your internal controller calls to $state.go(nextStep) you will notice obvious differences.
While I don't see exactly why these are causing your issue, you can likely rectify it by updating your ui architecture. Create a parent state to which all the steps are children, nesting ui-views. Then use the parent state controller to keep track of steps, and manage forward and backward movements.


text:
Q: Proof that $a^x$ < $a^{x + \Delta x}$ How can I prove that $a^x$ < $a^{x + \Delta x}$, where $\Delta x > 0$, $a$ is a constant, and $a > 1$ (in my case, $a=2$)?
I don't want to use a graph, of course.

A: It all depends on what you know. Do you know that if $a\gt 1$ and $b\gt 0$ then $a^b\gt 1$? If so, $2^{x+\Delta x}-2^x = 2^x(2^{\Delta x}-1)$ is a product of positive numbers.


text:
Q: Open brand new $modal with Angular UI.Bootstrap every time I'm using AngularJS with ui.bootstrap and have a modal directive, which works fine.
myApp.directive("modalButton", ['$uibModal', function ($uibModal) {
    return {
        restrict: "A",
        scope: {
            modalUrl: '@',
            modalModel: '='
        },
        link: function (scope, element, attrs) {
            element.bind('click', function () {
                var modalInstance = $uibModal.open({
                    templateUrl: scope.modalUrl, // Here I want to use an url instead.
                    controller: 'editDeliveryCtrl as ctrl',
                    resolve: {
                        model: function () {
                            return scope.modalModel;
                        }
                    }
                });
            });
        }
    };
}]);

And used like:
<button type="button" class="btn btn-xs btn-default" modal-model="ctrl.currentDelivery" modal-button modal-url="@Url.Action("AddDelivery", "ProvisionContract", new {provisionContractId = Model.Id})">

</button>

When a user clicks on a button with the directive a modal is shown. However, I'm using MVC.Net and the modals I'm loading is often a form with @Html.AntiForgeryToken() or other code-behind logic. So what I really want is to reload the template every time (make a new request to the server).
I've read question below and that may be a good answer, but what I really want is to not use templates at all. I would like $uibModal to load it as brand new HTML instead.
How to remove angular $modal cache?
Can I make $uibModal reload the template as brand new HTML each time? More like $.load in jQuery?

A: All templates you load in the Angular app are stored in the $templateCache so they will not be downloaded the next time you are referring to them.
In your case, this is not the desired behavior as the HTML contents of the same URL may change over time.
Therefore, you have to remove the cached URL from the cache before opening the modal with
$templateCache.remove(scope.modalUrl);

Also, see How to remove angular $modal cache.

Another idea is to override the $templateCache's put method so it does not store some particular paths.
angular.module('yourApp').decorator('$templateCache', function($delegate) {
  var originalPut = $delegate.put;
  $delegate.put = function (templatePath, contents) {
    // specifiy conditions which would tell what paths should not be cached
    if (templatePath == '/this-should-not-be-cached.html' || templatePath.match(/some-regex/)) {
      return;
    }
    else {
      originalPut(templatePath, contents);
    }
  };
  return $delegate;
});

You can't just disable $templateCache because many libraries use it to store the templates that are shipped with them (e.g. ui-bootstrap and similar).


text:
Q: Extract data after network call in Swift This is a question about the objc.io video about networking.

Note: I have seen similar questions, but none of the suggestions worked
  for me.

In the sample code, the main call is:
Webservice().load(resource: Episode.all) { result in
    print(result!)
}

and the load function looks like this:
func load<A>(resource: Resource<A>, completion: @escaping (A?) -> ()) {
        URLSession.shared.dataTask(with: resource.url as URL) { data, _, _ in
            guard let data = data else {
                completion(nil)
                return
            }
            completion(resource.parse(data as NSData))

        }.resume()
    }

For simplicity they just print the result (an array of dictionaries), but I don't understand how I can further use it, because it is inside the closure. This way I can eg show the array in a UITableView or something like that.
So what I would like to do is something like:
var episodes = [Episode]()

Webservice().load(resource: Episode) { result in
    episodes = result!
}

print(episodes)

But this results in an empty array being printed.
I also tried using
DispatchQueue.main.async {
    episodes = result!
}

But again, nothing is printed.
How can I accomplish that?


text:
Q: Garry's Mod Private TTT Server cannot connect to MariaDB Trying to get a private Garry's Mod TTT server started to test things using publicly released code (moat.gg GitHub). Got the database setup using MariaDB and am met with errors when launching the server that I cannot figure out on my own. Zero clue what is wrong and why it isn't connecting and I am met with the error below permanently, any help is appreciated.
[moat_addons] addons/moat_addons/lua/system/app/core/datastore.lua:1: Couldn't load module
library! (The specified module could not be found.)
  1. require - [C]:-1
   2. unknown - addons/moat_addons/lua/system/app/core/datastore.lua:1
    3. include - [C]:-1
     4. unknown - addons/moat_addons/lua/system/app/core/init.lua:607
      5. include - [C]:-1
       6. unknown - addons/moat_addons/lua/autorun/init.lua:4


text:
Q: Data from database to js charts I have a javascript chart built with "highcharts" and I would display data from database in the chart.
I need to display data for each day of the week. I'm using laravel so I can use Carbon, but I don't know how.

Here is my view:

How can I do this ?

Thanks
Solved

I solved using this in the javascript:
series: [{
    name: 'Actions submitted',
    data: [<?php echo Actionshistory::whereRaw('WEEKDAY(created_at) = 0')->count() ?>,and so go on]
}

0=Monday, 1=Tuesday,ecc...
Thanks to all.


text:
Q: How to notify React components about status change Is it easier than pass argument from parent to child and turn on binding to know state of a component changed?
https://dev.to/zeyadetman/how-to-pass-state-between-components-in-reactjs-2pg1


text:
Q: Como colocar no centro 02 TextView do VideoView Tenho 02 TextView e quero coloca-los no centro de uma VideoView sendo que um texto ficara um em cima do outro.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/videoView"
        android:layout_gravity="center_horizontal" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="30º C"
        android:layout_gravity="center_horizontal"
        android:textSize="28sp"
        android:id="@+id/Temperatura" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notícias regionais"
        android:layout_gravity="center_horizontal"
        android:textSize="28sp"
        android:id="@+id/Notícia" />
</LinearLayout>

A: Você não pode definir isso em um LinearLayout por causa da necessidade de definição de orientação dele. Troque o LinearLayout por um RelativeLayout e adicione os atributos nos 2 textViews:
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"

faça da seguinte maneira:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/videoView" />
<TextView
    android:text="30º C"
    android:textSize="28sp"
    android:id="@+id/Temperatura"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
<TextView
    android:text="Notícias regionais"
    android:textSize="28sp"
    android:id="@+id/Notícia"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/></RelativeLayout>

A:
Você pode usar o RelativeLayout e colocar o atributo nos textview
  android:layout_centerInParent="true"

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <VideoView
            android:id="@+id/videoView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="text view 1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="text view 2" />

    </RelativeLayout>


text:
Q: D3 Binding Text and SVG I'm creating my first d3.js project with circles that can be dragged, added, or removed with centered text, but I can't seem to bind the text to the circle. I've seen some questions similar to mine, but I hope this is different enough because I tried applying the solutions but they didn't work. I'm not only looking for a solution but I'd like to know what I'm doing wrong here.
Any insights would be extremely helpful!
I tried creating a group variable group and assumed I could use that to bind the two elements. What's wrong with my mental model?
chart = {

  const dataset = [
  {start: new Date("2019-09-23 1:00 AM"), target: 70},
  {start: new Date("2019-09-23 8:00 AM"), target: 75},
  {start: new Date("2019-09-23 9:00 PM"), target: 70},
  {start: new Date("2019-09-23 1:00 PM"), target: 75},
  {start: new Date("2019-09-23 5:00 PM"), target: 70},
  {start: new Date("2019-09-23 6:00 PM"), target: 65},
]

  var xScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function(d) {
      return d.x_pos
    })]).range([0, width]);

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height])
      .attr("stroke-width", 2);

    svg.append("g")
      .call(xAxis)

  var group = svg.selectAll('g')
  .data(dataset)
  .enter()
  .append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")")

   group.append("circle")
     .data(dataset)
     .enter()
     .append("circle")
     .join("circle")
     .attr("cx", d => x(d.start))
     .attr("cy", 55)
     .attr("r", 30)
     .attr("fill", "red")
     .call(d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended))
    .on("click", removeElement);

  group.append("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", function(d) { return x(d.start) - 10; })
    .attr("y", function(d) { return 60; })
    .style("fill", "white")
    .text(function(d) { return d.target })
   .call(d3.drag()
    .on("drag", dragged))
   .on("click", removeElement)

  svg.on("click", function() {
    var coords = d3.mouse(this);

    var newData = {
      x: d3.event.x,
      y: d3.event.y,
      target: 0
    };

    dataset.push(newData);

    group.append("circle")
      .attr("cx", function(d) {
        return x(d.start);
      })
      .attr("cy", function(d) {
        return 55;
      })
      .attr("r", 30)
      .style("fill", "red")
      .attr('id', function(d, i) {
        return 'circle_' + i;
      })
      .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended))
      .on("click", removeElement);

    group.append("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", function(d) { return x(d.start) - 10; })
    .attr("y", function(d) { return 60; })
    .style("fill", "white")
    .text(function(d) { return d.target })
   .call(d3.drag()
   .on("drag", dragged))
   .on("click", removeElement)

  })

  function dragstarted(d) {
    d3.select(this).raise().attr("stroke", "black");
  }

  function dragged(d) {
    // tried adding .select("circle") from prior SO posts
    d3.select(this)
      .attr("cx", d.x = d3.event.x)
      .attr("cy", d.y = 55);
    d3.select(this) //.select("text")
      .attr("x", d.x = d3.event.x - 10)
      .attr("y", d.y = 60);
  }

  function dragended(d) {
       d3.select(this).attr("stroke", null);
  }

  function removeElement(d) {
    d3.event.stopPropagation()
    d3.select(this)
      .remove();
  }

  return svg.node();
}

x = d3.scaleTime()
    .domain([new Date("2019, 9, 23 12:00 AM"), new Date("2019, 9, 23, 11:59 PM")])
    .rangeRound([margin.left, width - margin.right])

interval = d3.timeHour.every(1)

xAxis = g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(g => g.append("g")
        .call(d3.axisBottom(x)
            .ticks(interval)
            .tickSize(-height + margin.top + margin.bottom)
            .tickFormat(() => null))
        .call(g => g.select(".domain")
            .attr("fill", "#ddd")
            .attr("stroke", null))
        .call(g => g.selectAll(".tick line")
            .attr("stroke", "#fff")
            .attr("stroke-opacity", d => d <= d3.timeHour(d) ? 1 : 0.5)))
    .call(g => g.append("g")
        .call(d3.axisBottom(x)
            .ticks(d3.timeHour)
            .tickPadding(0))
        .attr("text-anchor", null)
        .call(g => g.select(".domain").remove())
        .call(g => g.selectAll("text").attr("x", 6)))

margin = ({top: 10, right: 0, bottom: 20, left: 0})
height = 120
d3 = require("d3@5")

Link to notebook: https://observablehq.com/d/c0b23251c8bdafa2

A: You need to see svg as a group of elements, where the elements can also be groups of elements.
What does it looks like to have a circle with a text inside of it ?
<svg...>
    <g id="myGroup">
          <circle style="" cx="250" cy="250" r="245"></circle>
          <text x="50%" y="50%" stroke="#111"> Hello !</text>
    </g>
</svg>

Now if you want to generate this svg from scratch :
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var group = document.createElementNS("http://www.w3.org/2000/svg","g");
group.setAttribute("id","myGroup")
var newCircle = document.createElementNS(svgNS,"circle");
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x", "50%");
newText.setAttributeNS(null,"y", "50%");
document.getElementById("svg").appendChild(myGroup);
document.getElementById("myGroup").appendChild(newCircle);

The circle and the text are bind into a group. Then drag your group, and not your circle ;)


text:
Q: bootstrap columns on mobile stacking up down I am using col-auto and col to create a two column layout, where the first column behaves like the left sidebar and second column will store the content.
My problem is when I use table in the second column content area the column stacks up and down in mobile device.
below is a snippet to understand my situation.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

aaa

                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa

A: Instead of setting it to auto maybe give it a set size like this.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

aaa

                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa
                        sdasa

A: Finally I got the solution, I added d-flex and flex-nowrap in the row, now both columns are coming side by side but, on mobile devices a horizontal scroll bar is appearing. to overcome this I reduced the width of the column having content.
Below is the updated snippet

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

aaa

                          sdasa
                          sdasa
                          sdasa
                          sdasa
                          sdasa
                          sdasa
                          sdasa
                          sdasa


text:
Q: Redirect HTTP to HTTPS with htaccess and godaddy I'm new to the website, I've recently installed my SSL Certificate and the HTTPS Protocol on my website. At first, I tried to simply install the certificate by Control Panel of GoDaddy (MY Hoster) but I did not succeed in having good results. I have consulted this website finding different questions for the htaccess file, but after several tests the result is the same, do not work the HTTPS Protocol. This is my HTACCESS code:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^ index \ .php $ - [L]
RewriteCond% {REQUEST_FILENAME}! -f
RewriteCond% {REQUEST_FILENAME}! -d
RewriteRule. /web/index.php [L]
SSLOptions + StrictRequire
SSLRequireSSL
SSLRequire% {HTTP_HOST} eq "www.ipsextant.eu"
ErrorDocument 403 https://www.ipsextant.eu/web/
</ IfModule>
# END WordPress

For one second I see the https protocol but while I navigate to the site the protocol I use is HTTP.
I have tried with different codes, the .htaccess file is in the main ROOT of the site.
Can i solve the problem ??
Are there any syntax errors in the code?
Thanks in advance and sorry for my English
Bye Gianluca

A: Your website works fine for me, however, to force any page to be redirected to https://, here is 2 lines code for that!
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

And if you want to check it with PHP, you could do that,
    if ($_SERVER['HTTPS'] != "on") {
        $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        header("Location: $url");
      }

Your problem is the cache, delete your website's cache from your browser's settings/history and you will be good.
Good luck, Gianluca ;)

A: How to force SSL with .htaccess:
You can force an HTTPS connection to your website by adding these rules in your website's .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


text:
Q: Which mechanism does Canary Deployment strategy use? I am new to K8s and came across the multiple deployment strategies.
I found the theory on Canary Deployment Strategy a little unclear.
I understand that in Canary strategy the whole aim is to first test the new version on a subset of the current pod instances and then, if successful, upgrade the remaining instances.
My doubt is regarding the upgrading of the remaining instances when the tests are successful:

*

*Does the upgrade follow a Recreate type mechanism where all the pods are killed and new ones are created thus resulting in downtime?
(OR)

*Does it follow a rolling update mechanism where the remaining pods are updated one by one thus avoiding any downtime?
(OR)

*Is it like blue/green, where we already have a set of pods with newer version and we just swap thus requiring additional resources?
(OR)

*It can follow any one of these mechanisms as per specification.

A: In canary deployment strategy, the new version of the application is gradually deployed to the Kubernetes cluster while getting a very small amount of live traffic. A subset of live users are connecting to the new version while the rest are still using the previous version.
The small subset of live traffic to the new version acts as an early warning for potential problems that might be present in the new code. As our confidence grows, gradually increase the canary traffic and more users are now connecting to the updated version. In the end, all live traffic goes to canaries, and thus the canary version becomes the new "production version"
The big advantage of using canary strategy is that deployment issues can be detected very early while they still affect only a small subset of all application users. If something goes wrong with a canary, the production version is still present and all traffic can simply be reverted to it.
Canary releases are based on the following assumptions:

*

*Multiple versions of your application can exist together at the same
time, getting live traffic.

*If you don't use some kind of sticky
session mechanism, some customers might hit a production server in
one request and a canary server in another.

Consider Istio if you want to do canary deployment. following link would be helpful
https://istio.io/latest/blog/2017/0.1-canary/

A: In addition to P Ekambaram's comments:

Does the upgrade follow a Recreate type mechanism where all the pods are killed and new ones are created thus resulting in downtime?

Not normally. It does depend on how you choose to setup your canary release. If you have 10 pods and you want to test on 20% of your traffic, you would add two new pods of the new version, and terminate two of the old pods, making sure the new pods have the same labels as the old pods, to ensure it gets traffic. Normally this would be done as a second deployment or something like Spinnaker which manages the ramping up/down.

Does it follow a rolling update mechanism where the remaining pods are updated one by one thus avoiding any downtime?

Again, it depends. But normally, yes, you would ramp up the number of new version pods in the deployment and ramp down the number of old version pods, while keeping an eye on a certain metric (for example, number of 5xx errors, if the deployment is e.g. a web service). Depending on the business and the service, it may be "check 20% of traffic with new version, and if all good, do the remaining 80% in one go"

Is it like blue/green, where we already have a set of pods with newer version and we just swap thus requiring additional resources?

Blue/Green is normally having an entire set of pods of the new version to hand and flipping the DNS to the new version as a "big bang" switch.
You can Canary deploy using a weighted DNS, but that is not reliable due to different DNS caching layers which you can't control.

It can follow any one of these mechanisms as per specification.

Yes, it's entirely up to you (and/or the product/service owner) to decide how they want the application deployed.


text:
Q: How to add Round shaped image using universal image loader in android i am trying to add Round shaped image to my to my layout using Universal Image Loader below is my imageUtil.class
import android.graphics.Bitmap.Config;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import zesteve.com.myapplication.R;

public class ImageUtil {

    public static void displayImage(ImageView view, String path, ImageLoadingListener listener) {
        ImageLoader loader = ImageLoader.getInstance();
        try {
            loader.displayImage(path, view, DEFAULT_DISPLAY_IMAGE_OPTIONS, listener);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            loader.clearMemoryCache();
        }
    }

    public static void displayRoundImage(ImageView view, String path, ImageLoadingListener listener) {
        ImageLoader loader = ImageLoader.getInstance();
        try {
            loader.displayImage(path, view, ROUND_DISPLAY_IMAGE_OPTIONS, listener);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            loader.clearMemoryCache();
        }
    }

    public static void loadImage(String path, ImageLoadingListener listener) {
        ImageLoader loader = ImageLoader.getInstance();
        try {
            loader.loadImage(path, DEFAULT_DISPLAY_IMAGE_OPTIONS, listener);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
    }

    //TODO Change default image
    private static final DisplayImageOptions.Builder DEFAULT_DISPLAY_IMAGE_OPTIONS_BUIDLER = new DisplayImageOptions.Builder()
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
            .displayer(new FadeInBitmapDisplayer(300, true, false, false))
            .showImageForEmptyUri(R.drawable.applogo)
            .showImageOnLoading(R.drawable.applogo)
            .showImageOnFail(R.drawable.applogo).cacheOnDisk(true)
            .cacheInMemory(true).bitmapConfig(Config.ARGB_8888);

    private static final DisplayImageOptions DEFAULT_DISPLAY_IMAGE_OPTIONS = DEFAULT_DISPLAY_IMAGE_OPTIONS_BUIDLER
            .build();
    private static final DisplayImageOptions ROUND_DISPLAY_IMAGE_OPTIONS = DEFAULT_DISPLAY_IMAGE_OPTIONS_BUIDLER
            .displayer(new RoundedBitmapDisplayer(500)).build();
}

and my layout contain the bellow code
           <ImageView
            android:id="@+id/profimage"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:layout_margin="20dp" />

in my main activity
ImageView profilepic;

profilepic = (ImageView) findViewById(R.id.profimage);
        String imageUri = "http://pengaja.com/uiapptemplate/newphotos/profileimages/0.jpg";
        ImageUtil.displayRoundImage(profilepic,imageUri,null);

in app grandle
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

this is the code which i am having. my concern is in drawer layout i want to show a Rounded profile pic.
please comment if there any doubt.

A: Try this short code it works for me:
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(Activity.this.getResources(), yourbitmap);
roundedBitmapDrawable.setCircular(true);
your imageview.setImageDrawable(roundedBitmapDrawable);

A: As the OP wants I'm Posting the code for picasso..
Add this dependancy..
compile 'com.squareup.picasso:picasso:2.5.2'

Use this code to load image on Imageview.
Picasso.with(context)
      .load(url)              //Url in string format
      .placeholder(R.drawable.user_placeholder)
      .error(R.drawable.user_placeholder_error)
      .into(imageView);

Above code does not produce circle image its just load image from url and add to image view.. To produce circle image you can add this circle transform class to your utils
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.squareup.picasso.Transformation;

public class CircleTransform implements Transformation {
    @Override
    public Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap,
            BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "circle";
    }
}

Now just little modification in the above code for getting circle image
Picasso.with(context)
  .load(url)              //Url in string format
  .placeholder(R.drawable.user_placeholder)
  .error(R.drawable.user_placeholder_error)
  .transform(new CircleTransform())
  .into(imageView);

Now Image is load as a circle image
For more info about Picasso See this official Page


text:
Q: HTTP to HTTPS redirects on Kubernetes v1.22 running in GCP I have a GCP cluster that was running on v1.21 and I have upgraded it to v1.22. There were some deprecated API calls that I was doing and I have managed to get rid of most of them but one.
$ kubent
2:02PM INF >>> Kube No Trouble `kubent` <<<
__________________________________________________________________________________________
>>> Deprecated APIs removed in 1.22 <<<
------------------------------------------------------------------------------------------
KIND      NAMESPACE   NAME            API_VERSION                 REPLACE_WITH (SINCE)
Ingress   elastic     kibana-kibana   networking.k8s.io/v1beta1   networking.k8s.io/v1 (1.19.0)
__________________________________________________________________________________________

I am pretty sure I have found where this is defined in my terraform scripts and I have tried to upgrade it following the release notes but to no avail.
resource "kubernetes_manifest" "nginx_frontend_config" {
  manifest = {
    "apiVersion" = "networking.gke.io/v1beta1"
    "kind"       = "FrontendConfig"
    "metadata" = {
      "name"      = "nginx-frontend-config"
      "namespace" = kubernetes_namespace.nginx.metadata[0].name
    }
    "spec" = {
      "redirectToHttps" = {
        "enabled"          = true
        "responseCodeName" = "FOUND"
      }
      "sslPolicy" = google_compute_ssl_policy.default.name
    }
  }
}

I have tried to upgrade the apiVersion from .../v1beta1 to .../v1 but I get the following error when running the terraform scripts:
╷
│ Error: Failed to determine GroupVersionResource for manifest
│
│   with kubernetes_manifest.nginx_frontend_config,
│   on nginx.tf line 83, in resource "kubernetes_manifest" "nginx_frontend_config":
│   83: resource "kubernetes_manifest" "nginx_frontend_config" {
│
│ cannot select exact GV from REST mapper
╵

I have looked everywhere and I couldn't find a resource on how to define a Http -> Https redirect in Kubernetes v1.22. The official guides on GCP are referencing only the v1beta1 version. And in the Ingress Migration Guide it states to use the v1 version but that doesn't work for me.
P.S. I have also tried networking.k8s.io/v1 but it comes back with  no matches for kind "FrontendConfig" in group "networking.k8s.io" when I run the terraform scripts.
How do I define a FrontendConfig for a redirect post v1.22?


text:
Q: .NET Framework Web API, no IFormFile so what should I do? I'm trying to upload a file using swagger/postman using .net framework
The issue that I'm facing is that in .NET Core you can simply just use IFormFile within your Model class and you're basically all set
But now that I'm not using .NET Core, I'm lost
The goal is to make a POST request that contains a String and File
public class UploadDoc
{
     public string Desc { get; set; }
     public HttpRequest File { get; set; }//I've tried different things here
}

And here is the post
    public async Task<IHttpActionResult> Post(UploadDoc uploadDoc)
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var buffer = await file.ReadAsByteArrayAsync();

            File.WriteAllBytes(@"abcdef.pdf", buffer);
        }

        return Ok();
    }

Edit: Adding more clarification -- my goal is to create an API Post call and ultimately, all I want is to take 2 inputs from the user

*

*Input 1: A string

*Input 2: A PDF File

So the postman request should look like this

When using .NET Core 6, I could do this simply by creating a model class that had
public string Desc { get; set; }
public IFormFile? formFile { get; set; }

And then setting up my API Call like so:
    [HttpPost]
    public async Task<IActionResult> Post([FromForm] DummyModel dummyModel)
    {
        var uploadedDocument = await FileHelper.UploadImage(dummyModel.formFile); // this dummyModel.formFile would contain what was uploaded by the user
    }

Now I'm trying to figure out how to do something similar within .NET Framework Web API
Edit 2:
I think I need to use the multipartformdata thing but my issue is I want my end-user to always only send me 2 things
A string and a PDF File

A: public class UploadDoc
{
    public string Desc { get; set; }
    public System.Web.HttpPostedFileBase FileToUpload { get; set; }
}

public async Task<IHttpActionResult> Post(UploadDoc fileToUpload)
{
    // Does not do anything with fileToUpload.Desc
    if (fileToUpload.ContentLength > 0)
        {
            savedFile = System.IO.Path.Combine(
            "LocationToSaveTo"
            , "FileName" + System.IO.Path.GetExtension(fileToUpload.FileName));

            fileToUpload.SaveAs(savedFile);
        }

    return Ok();
}

A: Not sure I fully understand your question, but to post in .NET you could:
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
    // Call asynchronous network methods in a try/catch block to handle exceptions.
    try
    {
        var myPayload = new **whatever** // HttpContent, including System.Net.Http.MultipartContent
        HttpResponseMessage response = await client.PostAsync("http://www.contoso.com/", myPayload);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
    catch(HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ",e.Message);
    }
}

see:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=net-6.0#system-net-http-httpclient-postasync(system-uri-system-net-http-httpcontent)
and:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=net-6.0


text:
Q: how parse the string with integers? I have string
str="1Apple2Banana3Cat4Dog";

How to parse this string into
Apple
Banana
Cat
Dog

I used stringstream for this as below, but not worked
stringstream ss(str);
int i;
while(ss>>i)
{
     ss>>s;
     cout<<s<<endl;
}

the output is:
Apple2Banana3Cat4Dog

which is not the expected,
any one help?

A: You could use std::regex for this:
#include <iostream>
#include <regex>

std::string str{"1Apple2Banana3Cat4Dog"};

int main() {
    std::regex e{ "[0-9]{1}([a-zA-Z]+)" };
    std::smatch m;
    while (std::regex_search(str, m, e)) {
        std::cout << m[1] << std::endl;
        str = m.suffix().str();
    }
}

Output:
Apple
Banana
Cat
Dog

A: See this snippet ( should work for fruit quantities 0-9):
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){

    const string str = "1Apple2Banana3Cat4Dog";
    vector<int> pts;

    // marked integer locations
    for (int i = 0; i < str.size(); i++)
    {
        int r =  str[i] ;
        if (r >= 48 && r <= 57)  // ASCII of 0 = 48 and ASCII of 9 = 57
        {
            pts.push_back(i);
        }
    }

    // split string
    for (int i = 0; i < pts.size(); i++)
    {
        string st1;
        if( i == pts.size()-1)
            st1 = str.substr(pts[i] + 1, (pts.size() - 1) - (pts[i] + 1));
        else
         st1 = str.substr(pts[i]+1, (pts[i+1])-(pts[i]+1) );
        cout << st1 << "  ";
    }

    return 0;
}

Output:


text:
Q: Adjust image size to completely fit jFrame I want to adjust the size of logo2.png so that it completely fits to the jFrame. Can anyone help me out?
jLabel2 = new javax.swing.JLabel();

jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Banking/logo2.png"))); // NOI18N

JDesktopPane.add(jLabel2);
jLabel2.setBounds(0, 0, 500, 290);

A: JLabel doesn't rescale it's content (ie the image), for that, you're going to have to get you hands a little dirty...
There are a number of ways to achieve this.  Personally, I'd start with a custom component, which extends from something like JPanel which takes a base image and is capable of scaling and painting it.
Take a look at Performing Custom Painting and Painting in AWT and Swing for more details about performing custom painting.
Scaling an image is not as straightforward as it might seem, while Java does provide some APIs to scale images, generally, they don't generate fantastic results.  Take a look at Quality of Image after resize very low -- Java and The Perils of Image.getScaledInstance() for more details.
I would normally recommend taking a look at the imgscalr library, as it's results are generally quite good (better then what the base Java API provides or I've seen through most other methods), but for this example, I've included an example of a divide an conqure approach.
This example provides a "scale to fill" implementation, this ensures that the resulting image ALWAYS fills the available space while maintaining it's aspect ratio, see Java: maintaining aspect ratio of JPanel background image for more discussions on the subject
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ScaledBackground {

    public static void main(String[] args) {
        new ScaledBackground();
    }

    public ScaledBackground() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                try {
                    BufferedImage img = ImageIO.read(...);

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new ImagePane(img));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage original;
        private BufferedImage scaled;

        public ImagePane(BufferedImage img) {
            original = img;
            scaled = original;
        }

        @Override
        public Dimension getPreferredSize() {
            return original == null ? new Dimension(200, 200) : new Dimension(original.getWidth(), original.getHeight());
        }

        @Override
        public void invalidate() {
            super.invalidate();
            generateScaledInstance();
        }

        protected void generateScaledInstance() {
            if (original != null) {

                scaled = getScaledInstanceToFill(original, getSize());

            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            if (scaled != null) {
                int x = (getWidth() - scaled.getWidth()) / 2;
                int y = (getHeight() - scaled.getHeight()) / 2;
                g2d.drawImage(scaled, x, y, this);
            }
            g2d.dispose();
        }

        public BufferedImage getScaledInstanceToFill(BufferedImage img, Dimension size) {
            float scaleFactor = getScaleFactorToFill(img, size);
            return getScaledInstance(img, scaleFactor);
        }

        public float getScaleFactorToFill(BufferedImage img, Dimension size) {
            float scale = 1f;
            if (img != null) {
                int imageWidth = img.getWidth();
                int imageHeight = img.getHeight();
                scale = getScaleFactorToFill(new Dimension(imageWidth, imageHeight), size);
            }
            return scale;
        }

        public float getScaleFactorToFill(Dimension original, Dimension toFit) {
            float scale = 1f;
            if (original != null && toFit != null) {
                float dScaleWidth = getScaleFactor(original.width, toFit.width);
                float dScaleHeight = getScaleFactor(original.height, toFit.height);
                scale = Math.max(dScaleHeight, dScaleWidth);
            }
            return scale;
        }

        public float getScaleFactor(int iMasterSize, int iTargetSize) {
            float scale = 1;
            if (iMasterSize > iTargetSize) {
                scale = (float) iTargetSize / (float) iMasterSize;
            } else {
                scale = (float) iTargetSize / (float) iMasterSize;
            }
            return scale;
        }

        public BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor) {
            BufferedImage imgBuffer = null;
            imgBuffer = getScaledInstance(img, dScaleFactor, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
            return imgBuffer;
        }

        protected BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor, Object hint, boolean higherQuality) {

            BufferedImage scaled = img;
            if (dScaleFactor != 1.0) {
                if (dScaleFactor > 1.0) {
                    scaled = getScaledUpInstance(img, dScaleFactor, hint, higherQuality);
                } else if (dScaleFactor > 0.0) {
                    scaled = getScaledDownInstance(img, dScaleFactor, hint, higherQuality);
                }
            }

            return scaled;

        }

        protected BufferedImage getScaledDownInstance(BufferedImage img, double dScaleFactor, Object hint, boolean higherQuality) {

            int targetWidth = (int) Math.round(img.getWidth() * dScaleFactor);
            int targetHeight = (int) Math.round(img.getHeight() * dScaleFactor);

            int type = (img.getTransparency() == Transparency.OPAQUE)
                            ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;

            if (targetHeight > 0 || targetWidth > 0) {
                int w, h;
                if (higherQuality) {
                    w = img.getWidth();
                    h = img.getHeight();
                } else {
                    w = targetWidth;
                    h = targetHeight;
                }

                do {
                    if (higherQuality && w > targetWidth) {
                        w /= 2;
                        if (w < targetWidth) {
                            w = targetWidth;
                        }
                    }

                    if (higherQuality && h > targetHeight) {
                        h /= 2;
                        if (h < targetHeight) {
                            h = targetHeight;
                        }
                    }

                    BufferedImage tmp = new BufferedImage(Math.max(w, 1), Math.max(h, 1), type);
                    Graphics2D g2 = tmp.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                    g2.drawImage(ret, 0, 0, w, h, null);
                    g2.dispose();

                    ret = tmp;
                } while (w != targetWidth || h != targetHeight);
            } else {
                ret = new BufferedImage(1, 1, type);
            }
            return ret;
        }

        protected BufferedImage getScaledUpInstance(BufferedImage img,
                        double dScaleFactor,
                        Object hint,
                        boolean higherQuality) {

            int targetWidth = (int) Math.round(img.getWidth() * dScaleFactor);
            int targetHeight = (int) Math.round(img.getHeight() * dScaleFactor);

            int type = BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;
            int w, h;
            if (higherQuality) {

                w = img.getWidth();
                h = img.getHeight();

            } else {

                w = targetWidth;
                h = targetHeight;

            }

            do {

                if (higherQuality && w < targetWidth) {

                    w *= 2;
                    if (w > targetWidth) {

                        w = targetWidth;

                    }

                }

                if (higherQuality && h < targetHeight) {

                    h *= 2;
                    if (h > targetHeight) {

                        h = targetHeight;

                    }

                }

                BufferedImage tmp = new BufferedImage(w, h, type);
                Graphics2D g2 = tmp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                g2.drawImage(ret, 0, 0, w, h, null);
                g2.dispose();

                ret = tmp;
                tmp = null;

            } while (w != targetWidth || h != targetHeight);

            return ret;

        }

    }

}

This example will grow and shrink as the image as the amount of available space for the panel changes

A: You can use the Stretch Icon on your JLabel.
Or you could use the Background Panel to draw the image.
In both cases the Image will shrink or grow as the frame is resized.

A: First get the Image, then use this method:
yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

You can get the width and height from the JFrame. Then you can convert the Image to ImageIcon and add it.


text:
Q: I cannot Get the Background Color of my JPanel in main class The Problem is I make a class that extends JPanel with gradient Color background but the problem is when I am getting the background of it to use it to other component is I cannot get the color of it. I want to set the background color of components same to other components
I had tried to use .getBackground(); But it doesn't work on it. what should I do so that I can get the background of it?
import javax.swing.*;
import java.awt.*;

public class GradientPaintDemo extends JPanel {

private static final int scale = 2;
private static final Color c1 = Color.decode("#00F260");
private static final Color c2 = Color.decode("#0575E6");
private static final int size = (c2.getRed() - c1.getRed()) * scale;

@Override
public Dimension getPreferredSize() {
    return new Dimension(size, size);
}

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    int w = getWidth();
    int h = getHeight();
    GradientPaint gp = new GradientPaint(20, 0, c1, 20, h, c2);
    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}

then when in my Main Class
GradientPaintDemo gpd = new GradientPaintDemo();
JPanel panel1 = new JPanel();

gpd.add(panel1);

panel.getBackground();

I want that to have only one background on all of my panels and buttons I want to look like this image below

A: At a "guess" I would say you need to make the child component transparent, using panel1.setOpaque(false), so the parent will show through it.
Also, at a "guess", the use of size in your getPreferredSize method could be causing you issues.  Instead, I'd set the component's default layout manager to BorderLayout and let the child dictate the required size.
For example, opaque...

Transparent...

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() throws HeadlessException {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                GradientPaintDemo gpd = new GradientPaintDemo();
                gpd.setBorder(new EmptyBorder(20, 20, 20, 20));
                JPanel panel = new JPanel();
                panel.setBorder(new EmptyBorder(20, 20, 20, 20));
                panel.add(new JLabel("This is a test"));
                panel.setOpaque(false);
                gpd.add(panel);

                frame.add(gpd);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public static class GradientPaintDemo extends JPanel {

        private static final int scale = 2;
        private static final Color c1 = Color.decode("#00F260");
        private static final Color c2 = Color.decode("#0575E6");
        private static final int size = (c2.getRed() - c1.getRed()) * scale;

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            int w = getWidth();
            int h = getHeight();
            GradientPaint gp = new GradientPaint(20, 0, c1, 20, h, c2);
            g2d.setPaint(gp);
            g2d.fillRect(0, 0, w, h);
        }
    }
}


text:
Q: Using Pop-ups in Flows I've seen alot of answers on this subject but nothing I can use.
I've created a flow that grabs the next available phone number from a library of numbers housed in an separate object in Salesforce then populates the number in a phone field on the Account. There are two types of numbers - Standard and Toll Free. What I'm trying to accomplish is to have the user click a button that says "Assign a DID" on the Account record, have a pop-up that asks them to choose what type of number they want - Standard or Toll Free - then grab the next available number and assign it.
Does anyone know how to accomplish this without having to write Apex code?
I'd also like to have a pop-up directly before the flow grabs next available number that says "Are you sure you want to assign this number to the account?" as an extra layer of making sure users think before they get click happy.
Any suggestions on where to look to find steps or other information based on this type of scenario?
Thanks!!!


text:
Q: Show that $\sum _{n=1 } ^{\infty } (n \pi + \pi/2)^{-1 } $ diverges. Show that $\sum _{n=1 } ^{\infty } (n \pi + \pi/2)^{-1 }  $ diverges.
Both the root test and the ratio test is inconclusive. Can you suggest a series for the series comparison test?
Thanks in advance!

A: Use the limit comparison test with $\sum_{n=1}^\infty n^{-1}$.

A: $$\frac{1}{n\pi +\frac{\pi}{2}} \geq \frac{1}{n\pi +n\pi}\geq \frac{1}{8n} =\frac{1}{8}\cdot\frac{1}{n}$$

A: It is never too pretty to go for the Root and Ratio Tests on the onset. A much more elegant method would be to notice that:
$$  \dfrac{1}{n \pi + \frac{\pi }{2}} = \dfrac{2 }{ 2n \pi  + \pi  } = \dfrac{2}{\pi } \cdot \dfrac{1}{2n + 1} \ge  \dfrac{2}{\pi } \cdot \dfrac{1}{2n + n} =  \dfrac{2}{3 \pi } \cdot \dfrac{1}{n } $$
Now use the fact that the Harmonic Series $ \sum \dfrac 1 n $ diverges.

A: $\displaystyle\frac{1}{n\cdot \pi+\frac{\pi}{2}}\ge\frac{1}{n\cdot\pi+\pi} =\frac{1}{\pi}\cdot\frac{1}{n+1}$, and since $\displaystyle\sum\frac{1}{n+1}$ diverges thus $$\sum\displaystyle\frac{1}{n\cdot \pi+\frac{\pi}{2}}$$ diverges!


text:
Q: Using concat() to build a column alias name I am using concat() to create the name for a column name:
set @var = 10;
select col as concat("str1", cast(@var as CHAR), "str2") from table1;

But I get the following syntax error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ('str1', cast(@var as char), 'str2')

What am I doing wrong?

A: Try:
SET @var := 10;

SET @`sql` := CONCAT('select col as ',
                     'str1', cast(@var as CHAR), 'str2',
                     ' from table1');

PREPARE `stmt` FROM @`sql`;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;


text:
Q: Nested master pages using Razor syntax I'm trying to get nested master pages working with the new razor syntax.  Any help appreciated:
The error I'm getting is
Execute() no suitable method found to override

Delving further I have my _Site.cshtml, which is the main master page and inherits ViewMasterPage.
My nested master page is _layout.cshtml, which uses _site as a layout, uses some helpers and inherits from ViewMasterPage
I have a _ViewStart.cshtml, which points to my Layout file.
And finally I have my index page which inherits from ViewPage
So at the top of each page I have:
Site:
@inherits System.Web.Mvc.ViewMasterPage

Layout
@inherits System.Web.Mvc.ViewMasterPage<MyMasterViewModel>
@{ Layout ="~/Views/Shared/_Site.cshtml"; }

ViewStart
@{ Layout ="~/Areas/AreaName/Views/Shared/_Layout.cshtml"; }

Index
@inherits System.Web.Mvc.ViewPage<MyHomeModel>

Any ideas???
Cheers!

A: ViewMasterPage is used for WebForms views.
Razor layout pages do not inherit a special class; instead, they inherit the same ViewPage class.
You should use the @model directive instead of @inherits in all three pages.


text:
Q: UIPopover button repeats action I am creating the application for iPad with the UIPopover. I have a main view from which I am calling two popovers displaying different information. I was following the guidelines in How to Dismiss a Storyboard Popover thread and another threads, everything works fine except one thing. In my popover I have a button which triggers an action on the parent view. From time to time the action is triggered more than once even if the button was clicked just once and also popover was opened just once. My first assumption was that the popover was caching some data from several calls, but the problem seems to appear just randomly.
My configuration is: Mac OSx Snow Leopard with Xcode 4.2, iOS 5.0.
Tested in Simulator, iPad 5.1 and iPad 6.0 all the same results.
I have the main view View 1 and the popover view View 2
In my view 2 I have a method ProceedButtonClicked which sends the notification to the View 1
- (IBAction) ProceedButtonClicked{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"proceedButtonClicked" object:self];
}

The method is binded to the button in the popover view.
In view1 (parent view):
- (void)viewDidLoad
{
    [super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self   selector:@selector(ButtonClicked:) name:@"proceedButtonClicked" object:nil];
}

- (void) ButtonClicked:(NSNotification *) notification {
NSLog(@"I'm here ...");
//dismiss popover
if (paramPopover)
    [paramPopover dismissPopoverAnimated:YES];
}

I am pretty new to the iPad development, so maybe I am missing in my code something obvious, but searching until now resulted to nothing.
Any help would be appreciated.
Thank you.

A: When using notifications, you risk multiple instances of a class answering the same notification, so if you have 2 controllers alive for some reason (bad memory management?), then when pressing the button 2 controllers will answer the call and you will have a duplicate action.
Buttons can have a specific callback assigned to them, and it's very simple to set it up by code:
If your button is a UIButton, you can set your target action like this:
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

If your button is a UIBarButtonItem, you set the target when you create it
[[UIBarButtonItem alloc] initWithTitle:@"Title" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonAction:)];

Edit:
NSLog(@"I'm here ...");
That's creepy ...


text:
Q: R Markdown to PDF conversion error I am converting a long file from .rmd to .pdf
But when I try to knit it, it always shows this error:
   Error in pls::mvr(form, ncomp = ncomp, data = DCVf, validation = "none",  :
   Invalid number of components, ncomp

Before this error, this line is prompted:
Quitting from lines 395-690 (a.Rmd)

and on this line this is the code:-
After this, once these libraries are included:-

{r}
library(ElemStatLearn)
library(leaps)
library(caret)
library(bestglm)
library(glmnet)
library(pls)

we can obtain our analysis in the following manner:
```{r}

prostate = prostate
index = createDataPartition(prostate$lpsa, p = 0.7, list = FALSE)
train <- prostate[ index,]
test  <- prostate[-index,]
```

A: I realized what the issue was. As I didn't intended the code to run and it wouldn't have runned anyways - I should've surrounded the code with
```
code
```

instead of
```{r}
code
```

Once again, the error was appearing since in order for the code to run, many requisites had to be resolved. Once I did the above replacement, my document knitted easily.
PS:
```{r}
code
```

is only used when we want to execute the code.


text:
Q: Radio button style changes when clicked with React Hooks I want the radio button to change when clicked. This is what i have now image
I want it to change to this when clicked
Here's my code: `
 const [active, setIsActive] = useState(false)

<div className={`checkbox payment-radio-btn1 ${active ? "checkbox:hover" : "" }`}>
  <input type="radio" value="paystack" name='payment' onChange={handleChange}/>
  Paystack (Debit/Credit Card)

<div className={`checkbox payment-radio-btn2 ${active ? "checkbox:hover" : "" }`}>
  <input type="radio" value="wallet" name='payment' onChange={handleChange}/>
  Pay with Wallet

Here's my css code
.checkbox:hover{
border: 2px solid #00B6F0;
background: #FFFFFF;
}

.payment-radio-btn1{
position: absolute;
width: 406px;
height: 64px;
left: 10px;
top: 128px;
background: #F3F4F5;
box-shadow: 0px 24px 38px 3px rgba(0, 0, 0, 0.14);
border-radius: 4px;
margin-top: 20px;
margin-left: 6px;
display: flex;
}

A: One option is a custom Radio element that allows you to represent your radio buttons however you like. In this example we use two emoji, but you could use images, or SVG if you wanted.
function Radio({ checked, onClick, children, on = "✔", off = "" }) {
  return

    {checked ? on : off } {children}

}

We can use the Radio elements in our app like this.
function App() {
  const [radio, selectRadio] =
    useRadio(["paystack", "paypal", "wallet"], "paystack")
  return

    <Radio checked={radio == "paystack"} onClick={selectRadio("paystack")}>
      Paystack (Debit/Credit Card)
    </Radio>
    {/* more radio options ...*/}

}

This is made possible by writing useRadio which encodes the radio group logic nicely in a custom hook.
function useRadio(validStates, initState) {
  const [state, setState] = React.useState(initState)
  return [
    state,
    value => event =>
      validStates.includes(value)
        ? setState(value)
        : console.error(`invalid option: ${value}`)
  ]
}

Here's a minimal, verifiable example. Run it below and click some radio buttons to see the application state change.

function App() {
  const [radio, selectRadio] = useRadio(["paystack", "paypal", "wallet"], "paystack")
  return

    <Radio checked={radio == "paystack"} onClick={selectRadio("paystack")}>
      Paystack (Debit/Credit Card)
    </Radio>
    <Radio checked={radio == "wallet"} onClick={selectRadio("wallet")}>
      Pay with Wallet
    </Radio>
    <Radio checked={radio == "paypal"} onClick={selectRadio("paypal")}>
      PayPal
    </Radio>

{JSON.stringify({paymentOption: radio}, null, 2)}

}

function Radio({ checked, onClick, children, on = "✔", off = "" }) {
  return

    {checked ? on : off } {children}

}

function useRadio(validStates, initState) {
  const [state, setState] = React.useState(initState)
  return [
    state,
    value => event =>
      validStates.includes(value)
        ? setState(value)
        : console.error(`invalid option: ${value}`)
  ]
}

ReactDOM.render(<App/>, document.querySelector("#app"))
.radio { cursor: pointer; }
pre { padding: 0.5rem; background-color: #ffc; }


text:
Q: ERROR: No matching distribution found for apache-beam==2.34.0 I'm trying to run a simple Dataflow pipeline. After finally silencing some service account-related permission errors, my pipeline has now progressed onto the next stage of failure. This time, however, I'm even more unclear as to how I'm supposed to be reading/debugging the output log:
Running the script locally, this is my output:
ERROR: Could not find a version that satisfies the requirement apache-beam==2.34.0 (from versions: none)
ERROR: No matching distribution found for apache-beam==2.34.0
WARNING:apache_beam.runners.portability.stager:Failed to download requested binary distribution of the SDK: RuntimeError('Full traceback: Traceback (most recent call last):\n  File "/usr/local/Caskroom/miniconda/base/envs/myenv4/lib/python3.9/site-packages/apache_beam/utils/processes.py", line 89, in check_output\n    out = subprocess.check_output(*args, **kwargs)\n  File "/usr/local/Caskroom/miniconda/base/envs/myenv4/lib/python3.9/subprocess.py", line 424, in check_output\n    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,\n  File "/usr/local/Caskroom/miniconda/base/envs/myenv4/lib/python3.9/subprocess.py", line 528, in run\n    raise CalledProcessError(retcode, process.args,\nsubprocess.CalledProcessError: Command \'[\'/usr/local/Caskroom/miniconda/base/envs/myenv4/bin/python\', \'-m\', \'pip\', \'download\', \'--dest\', \'/var/folders/_3/tk69j41x2t9cvh0dbvzdmm2m0000gn/T/tmpr51_u_l1\', \'apache-beam==2.34.0\', \'--no-deps\', \'--only-binary\', \':all:\', \'--python-version\', \'39\', \'--implementation\', \'cp\', \'--abi\', \'cp39\', \'--platform\', \'manylinux1_x86_64\']\' returned non-zero exit status 1.\n \n Pip install failed for package: apache-beam==2.34.0           \n Output from execution of subprocess: b\'\'')
WARNING:root:Make sure that locally built Python SDK docker image has Python 3.9 interpreter.

On GKE, this is my output:
[server]Traceback (most recent call last):
[server]  File "/app/shared/to_db.py", line 101, in <module>
[server]    beamer()
[server]  File "/app/shared/to_db.py", line 91, in beamer
[server]    quotes | beam.io.WriteToBigQuery(
[server]  File "/usr/local/lib/python3.9/site-packages/apache_beam/pipeline.py", line 597, in __exit__
[server]    self.result.wait_until_finish()
[server]  File "/usr/local/lib/python3.9/site-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 1640, in wait_until_finish
[server]    raise DataflowRuntimeException(
[server]apache_beam.runners.dataflow.dataflow_runner.DataflowRuntimeException: Dataflow pipeline failed. State: FAILED, Error:
[server]Workflow failed.
Streaming logs from pod: python-property-tax-84ff6c46f6-qxh5h container: server
[server]/usr/local/lib/python3.9/site-packages/apache_beam/__init__.py:79: UserWarning: This version of Apache Beam has not been sufficiently tested on Python 3.9. You may encounter bugs or missing features.
[server]  warnings.warn(
[server]/usr/local/lib/python3.9/site-packages/apache_beam/io/gcp/bigquery.py:2103: BeamDeprecationWarning: options is deprecated since First stable release. References to <pipeline>.options will not be supported
[server]  is_streaming_pipeline = p.options.view_as(StandardOptions).streaming
[server]/usr/local/lib/python3.9/site-packages/apache_beam/io/gcp/bigquery_file_loads.py:1112: BeamDeprecationWarning: options is deprecated since First stable release. References to <pipeline>.options will not be supported
[server]  temp_location = p.options.view_as(GoogleCloudOptions).temp_location
[server]ERROR: Could not find a version that satisfies the requirement apache-beam==2.34.0 (from versions: none)
[server]ERROR: No matching distribution found for apache-beam==2.34.0
[server]WARNING:apache_beam.runners.portability.stager:Failed to download requested binary distribution of the SDK: RuntimeError('Full traceback: Traceback (most recent call last):\n  File "/usr/local/lib/python3.9/site-packages/apache_beam/utils/processes.py", line 89, in check_output\n    out = subprocess.check_output(*args, **kwargs)\n  File "/usr/local/lib/python3.9/subprocess.py", line 424, in check_output\n    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,\n  File "/usr/local/lib/python3.9/subprocess.py", line 528, in run\n    raise CalledProcessError(retcode, process.args,\nsubprocess.CalledProcessError: Command \'[\'/usr/local/bin/python\', \'-m\', \'pip\', \'download\', \'--dest\', \'/tmp/tmpyx3iprn_\', \'apache-beam==2.34.0\', \'--no-deps\', \'--only-binary\', \':all:\', \'--python-version\', \'39\', \'--implementation\', \'cp\', \'--abi\', \'cp39\', \'--platform\', \'manylinux1_x86_64\']\' returned non-zero exit status 1.\n \n Pip install failed for package: apache-beam==2.34.0           \n Output from execution of subprocess: b\'\'')
[server]WARNING:root:Make sure that locally built Python SDK docker image has Python 3.9 interpreter.

As you can see, I've tried running both locally and on GKE: similar errors. I don't see anything wrong in my dockerfile:
# Python image to use.
FROM python:3.9

# Set the working directory to /app
WORKDIR /app

# copy the requirements file used for dependencies
# COPY requirements.txt .

RUN apt-get update
RUN apt-get install -y gdal-bin

# Install any needed packages specified in requirements.txt
RUN pip install --upgrade pip
# If I don't redundantly install here, python gives me a "apache-beam: import not found" error
RUN pip install apache-beam
RUN pip install "apache-beam[gcp]"
RUN pip install poetry

# Copy the rest of the working directory contents into the container at /app
COPY . .

RUN poetry install

# Run app.py when the container launches
ENTRYPOINT ["python", "shared/to_db.py"]

In pyproject.toml:
[tool.poetry.dependencies]
# ...
python = ">=3.9,<3.11"
google-cloud-bigquery = "^2.30.1"
BigQuery-Python = "^1.15.0"
apache-beam = {extras = ["gcp"], version = "^2.34.0"}
wheel = "^0.37.0"

Google's own documentation says Dataflow supports beam v2.34.0. So why am I getting:
ERROR: Could not find a version that satisfies the requirement apache-beam==2.34.0 (from versions: none)
ERROR: No matching distribution found for apache-beam==2.34.0

A: Try changing the Python version to 3.8, which is the latest supported version by Apache Beam:
https://beam.apache.org/get-started/quickstart-py


text:
Q: Proving that if $f$ is equal to $g$ asymtotically then their distance tends to zero How could I prove via limit definition that from
$$
\lim_{n \to \infty} \frac{f(n)}{g(n)} = 1
$$
derives
$$
\left| f(n) - g(n) \right| \to 0
$$
?
Previous attempt took me to
$$
\left| f(n) - g(n) \right| < \varepsilon \left| g(n) \right| \qquad \forall \varepsilon \space \text{fixed}, \forall n \ge n_0
$$
which is not useful since $\varepsilon \cdot |g|$ might be not that low ceil (...I'm thinking the case when $g$ goes to infinity).

A: Are you sure you have the right question? Consider the functions $f(x) = x+1$, and $g(x) = x$.
If you assume that $|f(x) - g(x)| \rightarrow 0$, it's not terribly hard to show that their ratio tends to 1.
Hint: rewrite $\frac{f(x)}{g(x)}$ as $\frac{g(x) - (g(x) - f(x))}{g(x)}$.


text:
Q: Doctrine and MongoDb: Define required fields in MongoDb-Document ( I'm using MongoDB with Doctrine for a Symfony project.
For a document (I call it class Product) I need to define a field (e.g. name), but I want to act doctrine in a way that the document cannot be saved without defining a it. Meaning, whenever creating or updating a new Product, the property $name has to be defined.
For doctrine and MySql this is quite simple. There you have to say:
class Product {

   ...

   /** @ORM\Column(type="string", nullable=false) */
   private $name;

   ...

}

Is there a similar way in MongoDb?
The following code (which I found in a similar thread) doesn't work:
class Product {

   ...

   /**
    * @MongoDB\Field(type="string")
    * @Constraints\NotBlank
    */
   protected $name;

   ...

}


text:
Q: Serialization issues calling WCF service from iPhone MonoTouch app I have a WCF service on a Windows Server and I am trying to invoke the service from an iPhone Application in MonoDevelopment. The web service client was generated using Silverlight service generation utility and copied to the iPhone development project in the MonoTouch environment.
So the service is pretty straightforward. I have a method that calls a GetCustomers() methods and returns a List<Customer>. I can create the client successfully in the MonoTouch iPhone application code. The method does execute and if I try to do a count on the result it tells me there are 91 records (Northwind database / Customers table). So I am sure that the service is working just fine.
Problem is when I try to access any property of Customer object I get the following error:

The CustomerName property does have public getter and setter

but the following exception says it does not. I need some help if someone can walk me through what I am doing wrong!

Exception in async operation: System.Runtime.Serialization.InvalidDataContractException: DataMember property 'System.String CustomerName' on type 'NorthwindService.Customer' must have both getter and setter.
  at System.Runtime.Serialization.SharedContractMap.GetMembers (System.Type type, System.Xml.XmlQualifiedName qname, Boolean declared_only) [0x00116] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs:553
  at System.Runtime.Serialization.SharedContractMap.Initialize () [0x00053] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs:516
  at System.Runtime.Serialization.KnownTypeCollection.RegisterContract (System.Type type) [0x0004f] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs:766
  at System.Runtime.Serialization.KnownTypeCollection.TryRegister (System.Type type) [0x0002a] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs:593
  at System.Runtime.Serialization.KnownTypeCollection.RegisterCollection (System.Type type) [0x0000f] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs:666
  at System.Runtime.Serialization.KnownTypeCollection.TryRegister (System.Type type) [0x00062] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs:605
  at System.Runtime.Serialization.KnownTypeCollection.InsertItem (Int32 index, System.Type type) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs:389
  at System.Collections.ObjectModel.Collection`1[T].Add (.T item) [0x0000c] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Collections.ObjectModel/Collection.cs:72
  at System.Runtime.Serialization.DataContractSerializer.ReadObject (System.Xml.XmlDictionaryReader reader, Boolean verifyObjectName) [0x0000c] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs:267
  at System.Runtime.Serialization.XmlObjectSerializer.ReadObject (System.Xml.XmlDictionaryReader reader) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/XmlObjectSerializer.cs:74
  at System.ServiceModel.Dispatcher.DataContractMessagesFormatter.MessageToParts (System.ServiceModel.Description.MessageDescription md, System.ServiceModel.Channels.Message message) [0x000b8] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs:364
  at System.ServiceModel.Dispatcher.BaseMessagesFormatter.DeserializeReply (System.ServiceModel.Channels.Message message, System.Object[] parameters) [0x00043] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs:175
  at System.ServiceModel.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters) [0x0016a] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:500
  at System.ServiceModel.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:443
  at System.ServiceModel.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:425

A: No, the service is not working just fine. It appears it's an async method, so when your first call appears to be successful, it may not be really unless you close the async call and get the return value. The processing and counting of the result may very well have been successful, but the actual serialization of the result -- which requires the Customer type to have both a setter and getter -- is not.
This is one of the few exceptions in WCF that is almost always right and very specific. Are you sure the Customer type has both a getter and setter? Are their access levels consistent?

A: The MonoTouch linker will exclude any code that isn't used from the final native iOS binaries. In your case, the getter/setter probably isn't used in your project and so isn't getting into the native version.
To fix this, you can decorate your DataMember properties with the MonoTouch.Foundation.Preserve attribute. Or, stick the Preserve attribute on the class that is your DataContract and pass in AllMembers = true, like the example below.
[DataContract,
MonoTouch.Foundation.Preserve(AllMembers=true)]
public class EntityClass
{
    [DataMember]
    public string Field {get;set;}
}


text:
Q: PHP GET добавление значения в ссылку Добрый день!
Файл order.php (прикрепляю код ниже) подсасывает данные из html и передает их на почту (имя, телефон, адрес и прочее). Далее, после отправки данных на почту скрипт перекидывает человека на другую страницу html.
Подскажите, как сделать так, чтобы перекидывала не на страницу "/success_order1.html", а на страницу "/success_order1.html?+'.@$_POST['name'].'" и открывалась страница с URL типа: "/success_order1.html?Игорь" ?

<?php
header("Content-Type: text/html; charset=utf-8");
if($_SERVER["REQUEST_METHOD"] == "GET")
exit;

$email = "xxxxxx@bk.ru";
$title = "Новый заказ. xxxxxxxx";
$from = 'xxxxxxxxx';
$text = 'Информация о заказе:

Товар: xxxxxxxxxxxxxxxxxxxxxxx (http://xxxxxxxx/mob1/)
Имя: '.@$_POST['name'].'
Телефон: '.@$_POST['phone'].'
Адрес: '.@$_POST['address'].'
Время заказа: '.date("Y-m-d H:i:s").'

Метки:
utm_source: '.@$_POST['utm_source'].'
utm_medium: '.@$_POST['utm_medium'].'
utm_campaign: '.@$_POST['utm_campaign'].'
utm_content: '.@$_POST['utm_content'].'
utm_term: '.@$_POST['utm_term'].'';
if(mail($email, $title, $text, "Content-type:text/plain; charset = utf-8\r\nFrom:$from"))
echo
"<title>Спасибо за заказ!</title>

<meta http-equiv='refresh' content='0; url=./success_order1.html' />";
else
echo "
Ошибка! Попробуйте ещё раз!
";
?>

A: Вопрос решился заменой УРЛ на:

 url=./success_order1.html?name=" .  $_POST['name']  . "


text:
Q: Blocking socket - detect state I am developing my first c/c++ application and using sockets. This application connects to server and reads image data sent from server, the image data is preceded by a few ints which are of interest like how much data to read.
The application is using blocking sockets as I didn't think having my thread just continuously looping was better when there was the option of blocking until the data was available.
My problem now is if the server just loses connection to network my application just sits there and i have no way of triggering a notification to the user or attempt a re-connection. I don't know how to check for state of connection.
Could somebody offer me a little advice as to how to solve my problem please?
thank you. I have pasted my readImageInt() function which shows how i am reading from socket. I am developing using linux device.
int readImageInt()
{

int nb, i;
union {
    long int whole;
    char bytes[4];
} v;
memset(v.bytes, 0x00, 4);
nb = recv(imagesock, v.bytes, 4, MSG_WAITALL);
if (nb == 0||nb == -1)
 {

    return -1;
 }
else
    {
    v.whole = ntohl(v.whole);

     return v.whole;
    }

}

A: You can set SO_RCVTIMEO socket option to break out of long blocking receive operation.
Edit 0:
Alternatively, you can use a polling call like select(2), poll(2) (or epoll_wait(2) if you are on Linux) with a timeout. That would allow you to break out of in-kernel wait to check, say, some user input telling you whether to continue waiting or bail.
The more reliable way to detect broken connection though is to send data if other side supports it - you'll get a signal or an error return (though on crashed remote end that might be on the order of minutes).
Edit 1:
Take a look at select_tut(2)

A: You may consider using select function to check the state of your socket before receiving any data. See here for example http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/lr2/select.htm


text:
Q: Jquery Close menu div on a click event I have a div which opens when I click a menu button, I am trying to close it if the user clicks anywhere after it is open. The issue I am having is that with my code the show div and the close div when a user clicks I guess are firing at the same time for some reason. The code for the click event is below. How can I make it so they do not fire at the same time and when I open the div that does not fire the click function. Thanks!
//if user clicks and menu is open then hide menu div
$(document).click(function() {
       if($("menu").hasClass("menu_closed") == false ) {
           //will hide the menu div
           closeMenu();
       }
}

A: I think what you want actually is to stop propagation in the other click handler, something like:
$("your_menu_selector").bind("click", function(e){

   //your code to open the menu

   e.stopPropagation();
   return false;
})

A: You might want to consider adding the event handler to close the menu in the handler that opens the menu.  Have it execute only once using the one method. In the handler that opens the menu, simply check to see if it is open already and do a no-op if it is.
 $('.openButton').click( function() {
      var $menu = $('#menu').
      if ($menu.hasClass('menu_closed')) {
         $menu.removeClass('menu_closed').addClass('menu_open');
         $(document).one( function() {
             $menu.removeClass('menu_open').addClass('menu_closed');
         });
      }
 });


text:
Q: Error when importing SCSS in a React component rendered using HtmlWebpackPlugin We'd like to render one of our React components to static HTML, so it's in the index.html returned by the server.
Rather than the code doing this while the server is being started, we'd rather the HtmlWebpackPlugin render the React component into its generated index.html. This is possible and it works very well; however, as soon as we attempt this with a React component that imports its SCSS, we see the following error:

Error: /Users/calumjames/htmlwebpackplugin-error-react-rendering/tools/webpack/indexRenderer:5396return window && document && document.all && !window.atob;^ReferenceError: window is not defined

I've created a simple Git repo that examples the issue. As mentioned in the README file, if the line that imports the SCSS in the Loading component is commented out, this error stops appearing and the component is rendered into the index.html correctly.
We could do with not changing how the component is coded because it's an internal shared component and the coding style matches the other shared components.
Is there something wrong with my code or config, or is there an issue with one of the Webpack plugins or loaders?


text:
Q: What would happen if an object is created in non-static method of class in java? class Data {
    int x = 20; // instance variable

    public void show() // non-static method
    {
        Data d1 = new Data(); // object of same class Data
        int x = 10;
        System.out.println(x); // local x
        System.out.println(d1.x);// instance variable x
    }

    public static void main(String... args) {
        Data d = new Data();
        d.show(); // "10 20"
    }
}

So my question when an object is created in show() namely 'd1' , it must have its own set of data members and must have allocated a new stack for its show() method , which in return should create a new object and thus the cycle should go on and stack-overflow occurs??
But this is working perfectly fine??

A: Data d1=new Data();

this statement itself will not allocate a new stack for show(). show()'s stack is allocated only when it gets called, for example, when it gets called in main.

A: Your show() method will be called only once. show() is NOT called when an instance of Data is being created. So, you will not get SOE.
Try this code to get SOE :P
class Data {
    int x = 20; // instance variable

    Data() {
        show(); // This will cause SOE
    }
    public void show() // non-static method
    {
        Data d1 = new Data(); // object of same class Data
        int x = 10;
        System.out.println(x); // local x
        System.out.println(d1.x);// instance variable x
    }

    public static void main(String... args) {
        Data d = new Data();
        d.show(); // "10 20"
    }
}


text:
Q: Groovy adding primes taking forever This is Project Euler number 10. It should add all primes below two million. Anything above something like 200000 takes forever, and 200000 takes a very long time. I think the final answer is above MAXINT, but I'm dealing with that later.
Why is it so slow?
def isPrime(num, primes)
{
    primes.find { it <= Math.sqrt(num) && it != 1 && it != num && num % it == 0 } == null
}

def primes = []
def min = 2
def max = 10 - 1

(min..max).findAll { it % 2 == 1 || it == 2 }.each { i ->
    if (isPrime(i, primes))
    {
        primes.add(i);
    }
}

def sum = primes.inject { sum, item -> sum + item }

print sum

A: Well... it probably has a lot to do with iterating over the list of primes and not short circuiting it when past the square root...
With the following C# IsPrime code, the code runs in a half a second:
FAST: 0.525 seconds
static bool IsPrime(int number, List<int> primes)
{
    bool prime = true;
    for (int i = 0; i < primes.Count; i++ )
    {
        int theprime = primes[i];
        if (theprime > Math.Sqrt(number))
        {
            break;
        }

        if (number % theprime == 0)
        {
            prime = false;
            break;
        }
    }
    return prime;
}

However, with this C# IsPrime code (essentially the same as the Groovy code in the original post), the same performance issues remain:
SLOW
static bool IsPrime(int number, List<int> primes)
{
    return primes.FirstOrDefault(o => o <= Math.Sqrt(number) && o != 1 && o != number && number % o == 0) == default(int);
}

After a little more testing, the problem is related to not short circuiting at the square root. Using takeWhile in groovy also runs slowly (it is probably creating a new list).
This code does not short circuit at the square root, and runs slower than a minute (I stopped it.):
SLOW (more than a minute)
def isPrime(num, primes)
{
    def root = Math.sqrt(num)
    def prime = true
    for (int i = 0; i < primes.size(); i++)
    {
        def aprime = primes[i];
        if (aprime <= root && aprime != 1 && aprime != num && num % aprime == 0)
        {
            prime = false
            break
        }
    }
    prime
}

This also runs slower than a minute:
SLOW (more than a minute)
def isPrime(num, primes)
{
    def root = Math.sqrt(num)
    primes.takeWhile { it <= root }?.find { it != 1 && it != num && num % it == 0 } == null
}

Even though the equivalent C# code runs in 0.559 seconds (takeWhile must be implemented a lot better in C#):
FAST: 0.559 seconds
static bool IsPrime(int number, List<int> primes)
{
    int root = (int)Math.Ceiling(Math.Sqrt(number));
    return primes.TakeWhile(o => o <= root).FirstOrDefault(o => o != 1 && o != number && number % o == 0) == default(int);
}

I finally got half decent performance in Groovy by both short circuiting and not using takeWhile:
MEDIUM: 51 seconds
def isPrime(num, primes)
{
    def root = Math.sqrt(num)
    def prime = true
    for (int i = 0; i < primes.size(); i++)
    {
        def aprime = primes[i];
        if (aprime > root)
        {
            break
        }
        if (aprime != 1 && aprime != num && num % aprime == 0)
        {
            prime = false
            break
        }
    }
    prime
}

A: When I solved this problem, I did so by implementing a Sieve of Eratosthenes. I won't tell you how to implement it (that's your job), but here's some background reading. I did a good amount of tweaking to try and get the brute-force method to work, and never came up with a result in less than a few minutes. My final answer ran in less than a second.
If you DO have any problems with implementation, change the question and we can hopefully give you a hand!

A: Your code has a time complexity of order n^(3/2), which is over 10^9 if n := 2000000. A rule of thumb in programming competitions is that when your code does more than ~10^8 operations, you should consider a different approach. In your case, the famous Sieve of Eratosthenes will work fine.


text:
Q: Получить HWND по имеющемуся HANDLE процесса c++ Прошу помочь с данным вопросом, поскольку не могу найти однозначного ответа. Запускаю окно браузера функцией CreateProcessA(), после чего хочу всячески взаимодействовать с этим окном. Создав процесс, я получил его ProcessId, ThreadId и HANDLE. так каким же образом мне получить сам дескриптор окна?

A: Используйте SPY++ - чтобы посмотреть "class name" - вашего окна браузера.
А потом уже по имени класса окна через функцию FindWindow() - получайте HWND.
Но, конечно - этот метод актуален, если только Вам нужно сделать - это конкретно для браузера или запускаемого Вами окна, имя класса, которого можно посмотреть заранее.
PS:

WinMain_Console:15
WinMain_Console - Microsoft Visual Studio:41
Lofi Ghostie - YouTube - Google Chrome:38
OpenGL Tutorial 1 - Window - YouTube - Яндекс.Браузер:53
WinMain_Console:15
Почта:5
Добавить учетную запись:23
Почта:5
Microsoft Text Input Application:32
Program Manager:15
--------------------------------------------------------------------------------------------- ConsoleWindowClass:18
HwndWrapper[DefaultDomain;;ea1e768d-f160-40c7-980f-f4851b7cfe00]:64
Chrome_WidgetWin_1:18
YandexBrowser_WidgetWin_1:25
XLMAIN:6
HwndWrapper[DefaultDomain;;51c1ee7a-0173-4532-a4e1-4742864b8e4e]:64
Windows.UI.Core.CoreWindow:26
ApplicationFrameWindow:22
ApplicationFrameWindow:22
Windows.UI.Core.CoreWindow:26
Progman:7


text:
Q: Attribute access time very long with DataFrame I would like to understand why Dataframe attributes access time seems so long (often 100 x slower vs other objects). An example :
In [37]: df=pd.DataFrame([])

In [38]: a=np.array([])

In [39]: %timeit df.size
28 µs ± 4.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [40]: %timeit a.size
136 ns ± 9.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)