text:
Q: How to redirect to another page using AngularJS? I am using ajax call to perform functionality in a service file and if the response is successful, I want to redirect the page to another url. Currently, I am doing this by plain JS code window.location = response['message'];. But I need to replace it with AngularJS code. I have looked various solutions on stackoverflow, they used $location. But I am new to AngularJS and having trouble to implement it.
$http({
            url: RootURL+'app-code/common.service.php',
            method: "POST",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            dataType: 'json',
            data:data + '&method=signin'

        }).success(function (response) {

            console.log(response);

            if (response['code'] == '420') {

                $scope.message = response['message'];
                $scope.loginPassword = '';
            }
            else if (response['code'] != '200'){

                $scope.message = response['message'];
                $scope.loginPassword = '';
            }
            else {
                window.location = response['message'];
            }
            //  $scope.users = data.users;    // assign  $scope.persons here as promise is resolved here
        })

A: I faced issues in redirecting to a different page in an angular app as well
You can add the $window as Ewald has suggested in his answer, or if you don't want to add the $window, just add an timeout and it will work!
setTimeout(function () {
        window.location.href = "http://whereeveryouwant.com";
    }, 500);

A: In AngularJS you can redirect your form (on submit) to other page by using window.location.href=''; like below:
postData(email){
    if (email=='undefined') {
      this.Utils.showToast('Invalid Email');
    } else {
      var origin = 'Dubai';
      this.download.postEmail(email, origin).then(data => {
           ...
      });
      window.location.href = "https://www.thesoftdesign.com/";
    }
  }

Simply try this:
window.location.href = "https://www.thesoftdesign.com/";

A: You can use Angular $window:
$window.location.href = '/index.html';

Example usage in a contoller:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {
                if (data.isValidUser) {
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

A: The simple way I use is
app.controller("Back2Square1Controller", function($scope, $location) {
    window.location.assign(basePath + "/index.html");
});

A: A good way to do this is using $state.go('statename', {params...}) is faster and more friendly for user experience in cases when you don't have to reload and bootsraping whole app config and stuff
(function() {
    'use strict';

    angular
        .module('app.appcode')
        .controller('YourController', YourController);

    YourController.$inject = ['rootURL', '$scope', '$state', '$http'];

    function YourController(rootURL, $scope, $state, $http) {

        $http({
                url: rootURL + 'app-code/common.service.php',
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                dataType: 'json',
                data:data + '&method=signin'

            }).success(function (response) {
                if (response['code'] == '420') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else if (response['code'] != '200') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else {
                    // $state.go('home'); // select here the route that you want to redirect
                    $state.go(response['state']); // response['state'] should be a route on your app.routes
                }
            })
    }

});

// routes
(function() {
    'use strict';

    angular
        .module('app')
        .config(routes);

    routes.$inject = [
        '$stateProvider',
        '$urlRouterProvider'
    ];

    function routes($stateProvider, $urlRouterProvider) {
        /**
         * Default path for any unmatched url
        */
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '/app/home/home.html',
                controller: 'Home'
            })
            .state('login', {
                url: '/login',
                templateUrl: '/app/login/login.html',
                controller: 'YourController'
            })
            // ... more routes .state
   }

})();

A: $location.path('/configuration/streaming');
this will work...
inject the location service in controller

A: I used the below code to redirect to new page
$window.location.href = '/foldername/page.html';

and injected $window object in my controller function.

A: You can redirect to a new URL in different ways.

*

*You can use $window which will also refresh the page

*You can "stay inside" the single page app and use $location in which case you can choose between $location.path(YOUR_URL); or $location.url(YOUR_URL);. So the basic difference between the 2 methods is that $location.url() also affects get parameters whilst $location.path() does not.

I would recommend reading the docs on $location and $window so you get a better grasp on the differences between them.

A: It might help you!!
The AngularJs code-sample
var app = angular.module('app', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {

  // For any unmatched url, send to /index
  $urlRouterProvider.otherwise("/login");

  $stateProvider
    .state('login', {
      url: "/login",
      templateUrl: "login.html",
      controller: "LoginCheckController"
    })
    .state('SuccessPage', {
      url: "/SuccessPage",
      templateUrl: "SuccessPage.html",
      //controller: "LoginCheckController"
    });
});

app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);

function LoginCheckController($scope, $location) {

  $scope.users = [{
    UserName: 'chandra',
    Password: 'hello'
  }, {
    UserName: 'Harish',
    Password: 'hi'
  }, {
    UserName: 'Chinthu',
    Password: 'hi'
  }];

  $scope.LoginCheck = function() {
    $location.path("SuccessPage");
  };

  $scope.go = function(path) {
    $location.path("/SuccessPage");
  };
}

A: Using
location.href="./index.html"
or create
scope $window
and using
$window.location.href="./index.html"

A:  (function () {
"use strict";
angular.module("myApp")
       .controller("LoginCtrl", LoginCtrl);

function LoginCtrl($scope, $log, loginSrv, notify) {

    $scope.validateUser = function () {
        loginSrv.validateLogin($scope.username, $scope.password)
            .then(function (data) {
                if (data.isValidUser) {
                    window.location.href = '/index.html';
                }
                else {
                    $log.error("error handler message");
                }
            })
    }
} }());

A: If you want to use a link then: in the html have:
<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>

in the typescript file
public openLineItems() {
if (this.$stateParams.id == 0) {
    this.Flash.create('warning', "Need to save order!", 3000);
    return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);

}
I hope you see this example helpful as it was for me along with the other answers.


text:
Q: Cloud Aware VS Cloud Based Applications What will be the primary differences between Cloud Aware VS Cloud Based Applications ?
Are Cloud Based Applications purely applications deployed in cloud ?
What would be checklists for cloud aware application ? Is cloud awareness feature of the application or the cloud platform the application is deployed ?

A: i guess you should/are try to know the difference between Cloud Hosted vs Cloud Optimized vs Cloud Native
checkout this Gartner presentation http://www.gartner.com/webinar/3274118/player?commId=200333&channelId=5502&srcId=1-3478922244

A: I think there is no differences between cloud aware applications and cloud based applications.
A cloud aware application is an application that is created with cloud in mind - for example, if I work with Microsoft Azure cloud (and I personally do) and I want to create cloud aware application, I should use mechanisms implented to Azure making me able to do it. These will be mechanisms such as virtual load balancers, availability sets (making VM's immune to hypervisor updates or hardware failures), autoscaling, VM image templating and auto-provisioning new servers on demand, automation, SQL as a service, or service bus (message query like RabbitMQ) as a service. Using cloud mechanism to build applications is lifting multi-tenant apps to higher level - especially with automation and resources scalability.
The second thing is cloud based application. In my opinion it is more business term nor technical one. If we speak about cloud based application, we have fact in mind, that it is remote app (on-line) and we are not managing infrastructure beneath this app. Cloud based application is some kind of replacement for on-premise application but lifted to unmanaged "cloud" somewhere into internet. We just using it not being aware about development, maintenance and resources it needs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Canvas Rotate, toDataUrl, and then Crop is ruining image quality I have an image that I'm allowing users to rotate 90 degrees in any direction. Every time they rotate, I use canvas to perform the image manipulations and then save the data returned by the canvas.toDataURL("image/png", 1).
The problem is that the image quality decreases every time I rotate the image.
My end goal is to rotate a rectangular image without losing image quality and also saving the new data url.
function rotateAndSave(image: HTMLImageElement, degrees: number): string {
  const imageWidth = image.naturalWidth;
  const imageHeight = image.naturalHeight;
  const startedHorizontalEndedVertical = imageWidth > imageHeight;
  const canvasSize = startedHorizontalEndedVertical ? imageWidth : imageHeight;

  const canvas = document.createElement("canvas");
  canvas.width = canvasSize;
  canvas.height = canvasSize;

  const ctx = canvas.getContext("2d");
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // center and rotate canvas
  const translateCanvas = canvasSize / 2;
  ctx.translate(translateCanvas, translateCanvas);
  ctx.rotate(degrees * Math.PI / 180);

  // draw from center
  const translateImageX = startedHorizontalEndedVertical ? -translateCanvas : (-imageWidth / 2);
  const translateImageY = startedHorizontalEndedVertical ? (-imageHeight / 2) : -translateCanvas;
  ctx.drawImage(image, translateImageX, translateImageY);

  // I got 'cropPlusExport' from another stackoverflow question.
  function cropPlusExport(img, cropX, cropY, cropWidth, cropHeight) {
    // create a temporary canvas sized to the cropped size
    const canvas1 = document.createElement('canvas');
    canvas1.width = cropWidth;
    canvas1.height = cropHeight;
    const ctx1 = canvas1.getContext('2d');
    ctx1.setTransform(1, 0, 0, 1, 0, 0);
    ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
    // use the extended from of drawImage to draw the
    // cropped area to the temp canvas
    ctx1.drawImage(img, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);
    return canvas1.toDataURL("image/png", 1);
  }

  // Start Cropping
  let squareImage = new Image();
  squareImage.src = canvas.toDataURL("image/png", 1);
  squareImage.onload = () => {
    const sx = startedHorizontalEndedVertical ? ((canvasSize - imageHeight) / 2) : 0;
    const sy = startedHorizontalEndedVertical ? 0 : ((canvasSize - imageWidth) / 2);
    const sw = imageHeight;
    const sh = imageWidth;
    const data = cropPlusExport(squareImage, sx, sy, sw, sh);

    // Update DOM via angular binding...
    const dataUrl = data.split(",")[1];
    this.imageSource = dataUrl;

    squareImage = null;
  }

example html
<div class="view">
  <img [src]="imageSource" />
</div>

Keep in mind that I am cropping to the natural width and height of the image. So, what's weird is that if I don't crop, then the image quality doesn't change but when I do crop, the image quality changes.

A: Canvas drawing is lossy, and rotating an image induce hard modifications of the pixels. So indeed, if you start always from the last state, you'll end up adding more and more artifacts to your image.
Simply store the original image somewhere and always start from there instead of using the modified version.

// will fire in a loop
img.onload = e => elem.rotateAndSave(1);

const elem = {
  // store a copy of the original image
  originalimage: img.cloneNode(),
  angle: 0,
  rotateAndSave(degrees) {
    // always use the stored original image
    const image = this.originalimage;
    // keep track of current transform
    this.angle += degrees;
    const imageWidth = image.naturalWidth;
    const imageHeight = image.naturalHeight;
    const startedHorizontalEndedVertical = imageWidth > imageHeight;
    const canvasSize = startedHorizontalEndedVertical ? imageWidth : imageHeight;

    const canvas = document.createElement("canvas");
    canvas.width = canvasSize;
    canvas.height = canvasSize;

    const ctx = canvas.getContext("2d");
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // center and rotate canvas
    const translateCanvas = canvasSize / 2;
    ctx.translate(translateCanvas, translateCanvas);
    ctx.rotate(this.angle * Math.PI / 180);

    // draw from center
    const translateImageX = startedHorizontalEndedVertical ? -translateCanvas : (-imageWidth / 2);
    const translateImageY = startedHorizontalEndedVertical ? (-imageHeight / 2) : -translateCanvas;
    ctx.drawImage(image, translateImageX, translateImageY);

    // I got 'cropPlusExport' from another stackoverflow question.
    function cropPlusExport(img, cropX, cropY, cropWidth, cropHeight) {
      // create a temporary canvas sized to the cropped size
      const canvas1 = document.createElement('canvas');
      canvas1.width = cropWidth;
      canvas1.height = cropHeight;
      const ctx1 = canvas1.getContext('2d');
      ctx1.setTransform(1, 0, 0, 1, 0, 0);
      ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
      // use the extended from of drawImage to draw the
      // cropped area to the temp canvas
      ctx1.drawImage(img, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);
      return canvas1.toDataURL("image/png", 1);
    }

    // Start Cropping
    let squareImage = new Image();
    squareImage.src = canvas.toDataURL("image/png", 1);
    squareImage.onload = () => {
      const sx = startedHorizontalEndedVertical ? ((canvasSize - imageHeight) / 2) : 0;
      const sy = startedHorizontalEndedVertical ? 0 : ((canvasSize - imageWidth) / 2);
      const sw = imageHeight;
      const sh = imageWidth;
      const data = cropPlusExport(squareImage, sx, sy, sw, sh);

      // Update DOM via angular binding...
      img.src = data;
    }
  }
};
<img crossorigin src="https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg" id="img">


text:
Q: E-commerce stock management considerations I need some suggestions from ecommerce expertise developers.
I have been using Woocommerce for a shopping cart, and I have created a functionality that it kinds of works like an event manager system. Each product is an event, which has different occurrences in different states, so the metaboxes in the CMS look like this:

I know how to develop most of the stuff, the problem I am having is with the stock, since it will not come from woocommerce it needs to come from the metabox.
So for the experts on developing ecommerce systems, my question is what should I consider to do this, because the stock is not final until the order is completed, so should I manage sessions or cookies, to get the final quantities. Also what happens if there are 2 users trying to buy the same products at the same time, how this should be programmed?. I am really not sure  what stuff should i consider to do this.

A: One way to do this would be to reserve one ticket for every person viewing it. Send a heartbeat requiring input from the client back to the server every x minutes (eg 5) to indicate that the person is still interested, and have a limit at which point the ticket is no longer reserved regardless of whether the person is still indicating interest (eg 30 minutes) to guard against bots or people holding tickets for too long.
You'd then have two numbers essentially:

*

*Number of tickets in stock and freely available

*Number of tickets currently reserved that will either be bought in the near future, or released to the general stock

This prevents people going to buy a ticket and finding that you've sold out in the meantime, and should be quite a transparent system.


text:
Q: Set multiple component on click button - React I'm already develop a timer on which we can enter a name and time in seconds to start the timer.
I want now to create a button and if I click, it display another timer with name, and time in seconds.
I don't know how I can do this...
Here is the timer with the inputs... https://jsfiddle.net/q806zeps/37/
I think if I can duplicate this ReactDOM.render(<App/>, document.getElementById('timer')); but I thonk it's not possible ?
Thanks

A: Please have a look at this code, hope it solves your problem.
class App extends React.Component {
constructor(props){
        super(props)
        this.state = {
         counter : 1
        }
     }
  //add timer code by oneshubh
  addTimer(){
            this.setState({counter: this.state.counter+1})
  }
  render(){
var timerDom = [];
  for(var i = 0;i<this.state.counter;i++){
    timerDom.push(<Wrapper />)
  }
  return (
        <div>
          {timerDom}
          <button onClick={()=>this.addTimer()} >add timer</button>
        </div>);
  }
}

A: You can use an array on the state of Wrapper to track the individual timers within your application.
state: {
    timers: []
}

Clicking the button, adds an object into your state with your current keys.
{
      libelle: 'Input name',
      seconds: 10
}

Iterate over this array to render you Minuteur components by passing the correct index.
Here is an updated fork of your fiddle. Creating timers using an array


text:
Q: App crash on run Xcode 5.0 I have made a simple app using Storyboard in Xcode 4.6.2, and it has worked perfectly all the time until now. Recently i started developing in Xcode 5.0 (beta1), and it worked perfectly when running. But when I was going to submit it to the App Store I got an error message, because Apple isn't allowing apps to be published from Xcode beta version. I therefore opened the xcode project in Xcode 4.6.2, and set the storyboard to work with that version of xcode and ios 6.1. But now it crashes when i try to run the app. Both in the simulator and on my iPhones (4S running 6.1 and 5 running 7).
This is the error message I get:
http://bildr.no/view/TytRaTNN
Have someone else had problems with this? Or do someone know how to fix this? Thank you. I have already sent it to App Store, but I think I have to reject the binary because of this bug.
Thank you!

A: The operative part seems to be;
Could not find a storyboard named '<strange character>' in bundle NSBundle...

It most likely means that the name set for your main storyboard is messed up (I can repeat the exact symptoms on a new project, just changing the storyboard name to a non existing one).
Start by checking that the correct story board name is set as "Main Storyboard" (click the project, then the Summary tab, iPhone should be visible, iPad is farther down). When that is set correctly, a clean/rebuild (as Alex Blundell pointed out in the comments) is required to rebuild with the correct name.

A: This issue has a super simple solution.
The problem is that Xcode transform your Storyboard file to be edited with new Xcode version, You just need to reverse that (This is not under the NDA because that happens with every new release).
Check my answer here:
Just installed xcode 5 and have missing storyboards


text:
Q: Is there a way to get the contents of a laravel page directly, without downloading it? Let's say I have a webserver running something like Wordpress for the forward-facing interface and have Laravel in the background to generate some dynamic content.
Currently I use an iframe in Wordpress to insert the laravel page, I'd rather use file_get_contents but the server runs multiple webpages so I can't just download localhost/laravel/page, it has to be the server's URL/laravel/page
Is there a way to get the HTML/results of the Laravel page through the command line (in PHP code) without going through the internet to just download the page?
ie: the command to execute public/index.php but with the data necessary to trigger the router properly


text:
Q: Is there a word whose meaning is "to dissociate from another or others for mutual benefit"? I read that cooperate means "to associate with another or others for mutual benefit," but what is the verb, possibly a single word, that means "to dissociate from another or others for mutual benefit"?
The word that comes to mind immediately is divorce because there's a benefit at the bottom of it, but that benefit can hardly be considered mutual, and, aside its metaphorical sense, it can be applied to no more than two persons.
Thus, what is the word meaning "to dissociate from another or others for mutual benefit"?

A: There is a common phrase, to go our separate ways, that conveys this.
And Sting (a la Richard Bach) has pointed out, If you love somebody, set them free.

A: The noun spin-off, with senses such as  "An incidental benefit or unexpected pay-off" and  "a subsidiary company that continues the operations of part of the parent company", is relevant.  Apparently the verb form, spin off, isn't hyphenated, and the noun sometimes is written as spinoff.
The terms spin out and starburst also are used; for example, a three-page pdf document showing a July, 1968  "Semiconductor Family Tree" article from Electronic News shows a series of "spinouts", such as Shockley from Bell, Fairchild from Shockley, and companies such as Raytheon, Intersil, Signetics, and National Semiconductor from Fairchild.  (The article predates the formation of   Intel and AMD by Fairchild alumni.) In many industrial spin-off scenarios, the division is beneficial to all parties; in the case of the many spinoffs from Fairchild, the semiconductor industry as a whole benefited vastly, but Fairchild typically did not benefit.

A: Disengage or dissolve might fit.
You can get more words from http://www.antonymsfor.com/opposite-word-for/cooperate.

A: There is a phrase that is used to mean this.

took [himself] out of the equation

This phase is often used to indicate a complex situation of human and events, wherein all other parties benefit when one party is removed, and does so voluntarily.  People commonly hear this term in espionage movies, when a secondary character removes themselves from a team in order to benefit others or the mission.
A more specific case, which has a precise term, is:

self-sacrifice

This carries more than 'disassociation from'... it often implies death, but can also be used in corporate or criminal scenarios, where one person takes the brunt of damages in order to preserve others or an institution.  (e.g. resignation due to a scandal)
"took one for the team"
Likewise, another specific case is

Quarantine

A person can quarantine themselves in order to protect others, usually from an infection or some other non-anthropic force that cannot be reasonably controlled.

A: You could say that you have freed yourself, which implies that it's a positive. Both parties could be freed, too...doesn't necessarily imply that only one party benefits.
Related words: liberated, unbind/unbound

A: Discharge, disinvolve, and disentangle come to mind.
"Discharge" has connotations of fulfilling a duty, after which each party goes their separate ways.
"Disinvolve" seems to have the right feeling and sense about it, although if you ask the Oxford English Dictionary it doesn't seem to be a word. They've disinvolved themselves with defining it. ;)
"Disentangle" may also come close. Everyone benefits, as the "entanglement" has ended.
The idea of absolution also comes to mind. "You are hereby absolved of your duties," or, "Pray for absolution."

A: Disband, if the context had already shown that the group was suffering — otherwise neutral.

A: Divorce is probably indeed the word closest in meaning to what you want, although depending on context there is no benefit to any or either party built into the word. Contrary to what you postulated, there is no restriction on the quantity of entities involved in the use of divorce. One can even be divorced from things (usually elements of one's self, e.g., ideals, conscience, past). Disbandment, dissolution, and disassociation are similar, but to a greater degree have no implied benefit to any party.
One can be absolved or delivered from something, with an implied benefit, but these typically have a religious connotation (i.e. absolved/delivered from all your sins) and imply a greater benefit to the person receiving the absolution or deliverance.
In law, separation has a deeper meaning than in everyday English. It intimates that both parties are amicable to permanent separation, but that a divorce is not desired. In fact, divorce in this context has an obviously negative connotation. However, it is not simple to conjure this meaning of separation outside of that very specific context.
If you have a specific context in mind, it might make it easier to pinpoint the 'right' word.

A: "Amicable extrication" describes my "discrete elopement" from Facebook.

A: When a pop group decides to no longer play together these are some of the most common ways to refer to their mutual agreement:
Time Entertainment

The Beatles Although each Beatle privately "quit" the band at different times,
  Paul McCartney was the first one to go public about it. McCartney
  announced "the divorce," as Lennon called it, via press release on
  April 10, 1970, although at the time he said the split was only
  temporary.
The Pixies [...] After years of rumors and breakup threats, front man Black Francis pulled the plug, announcing on BBC radio in January 1993 that the band was done.

The Guardian

... when Supergrass announced they were breaking up after a much longer
  time together – they cited a "17-year itch" due to "musical
  differences" – fans clamoured for tickets to their farewell tour.
"Should they then split up and go solo [...]?"

From Gigwise.com

My Chemical Romance are going their separate ways as well
Underoath: The Christian metalcore band may have announced they were calling it quits in 2012...
The Mars Volta: The Texan rock band split this year after twelve years of being together...
My Chemical Romance: The band had been at the centre of sensationalism for a while, but officially announced their split
  in March 2013.
S.C.U.M [...] We'd all like to thank you for all of your support but we have chosen to part ways and work on new projects
JLS: [...] after five years of successful singles the boys announced they were calling it a day.

A: How about we just part as friends?


text:
Q: Qt - does a QTimer::timeout() signal result in a QEvent? Qt doc:

If no event loop is running, events won't be delivered to the object.
  For example, if you create a QTimer object in a thread but never call
  exec(), the QTimer will never emit its timeout() signal. Calling
  deleteLater() won't work either. (These restrictions apply to the main
  thread as well.)

Does this mean that signal void QTimer::timeout() will also issue a QEvent?
If so, where does the Qt doc state this?

A:
where does the Qt doc state this?

Nowhere, because it shouldn't matter to the user of QTimer. The timer event is an implementation detail. It is delivered to the timer object itself, so you'd really have to go out of your way to intercept it. Here's how QTimer works:
class QTimer : public QObject {
  Q_TIMER
  QBasicTimer m_timer;
protected:
  void timerEvent(QTimerEvent * ev) override {
    if (ev->timerId() == m_timer.timerId())
      emit timeout();
  }
  /*...*/
};

If you think about it, there's no way of emitting any signals without running the code that emits the signals, and the only way to safely run such code that emits things asynchronously is to code for run-to-completion chunks that cede control to the event loop at every opportunity. The event loop is notified by the platform that a timer has timed out, and emits a signal right then. You'd be in deep trouble if Qt issued signals such as timer timeouts from intrusive asynchronous callbacks like Unix signals: just read about how few things you can do while in a signal handler - it'd be no different than an interrupt handler.


text:
Q: Unable to read a text file in c++ Hi my college class was given a group assignment to read a multi-line text file, drop the lowest score, then average the score from the remaining numbers.  I've run into a problem when prompted for the filename of the text file.  Although I type it in correctly, it won't load.  I have the file in the same folder that the program is located. Please help:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int NROWS =10;
const int NCOLS =10;

void theProgram();
//Function loads immediately upon opening the program and describes the purpose of the program
//and its functionality.

int ReadTxtFile(ifstream &file, string name[], double test[][NCOLS], int ncolUsed=3);
//Function reads data from a tab delimited file, whose first column is a string and the others are
//double or int. The function returns the number of rows read. The requires three parameters to be
//passed to it. The fourth parameter is has a default value of 3.

void outPutData(string header, string name[], double test[][NCOLS], int nDataPts, int ncolUsed=3);
//The function prints out the data read from the file. The function requires four parameters to be
//passed to it. Does not return any value.

int main(){

   string name[NROWS];
   string header, filename;
   double test[NROWS][NCOLS];
   char next;
   int nDataRows;
   ifstream file; //Declares file as an input file stream

   theProgram(); //Invokes the function that displays the program information

   cout<<"Please give me the filenames containing the test scores\n";
   getline(cin,filename);

//Opens the file and checks if the file has opened correctly
   file.open(filename);
   if(file.fail()){
     cout<<"Failed to open input file "<<filename<<endl;
     exit(1);
   }

   getline(file,header);// Reads the column headers as a string
   nDataRows=ReadTxtFile(file, name, test); // Calls the function to read the file
   file.close();

   cout<< "Number of records in the file is "<<nDataRows<<endl;
   outPutData(header,name, test, nDataRows); //Calls the function to output the data read from the file

   cin>>next;
} //End of main

void theProgram(){
    cout<<"************************************************************************\n";
    cout<<"* ******************************************************************** *\n";
    cout<<"* *This program will help the faculty to analyze the test scores and * *\n";
    cout<<"* *assign grades. It reads a tab delimited file that contains the    * *\n";
    cout<<"* *raw score for different tests and drops the lowest score. It then * *\n";
    cout<<"* *calcluates the average percentage of the remaining test scores.   * *\n";
    cout<<"* *Based on the average, the program then assigns a letter grade.    * *\n";
    cout<<"* ******************************************************************** *\n";
    cout<<"************************************************************************\n";
}

void outPutData( string header, string name[], double test[][NCOLS], int nDataRows, int ncolUsed)
{
   cout<<"\t"<<header<<endl;
   for(int i=0; i<nDataRows; i++){
       cout<<i<<"\t"<<name[i]<<"\t";
       for(int j=0; j<ncolUsed; j++){
           cout<<test[i][j]<<"\t";
       }
       cout<<endl;
    }
char next;
cin>>next;
}

int ReadTxtFile(ifstream &file, string name[], double test[][NCOLS], int ncolUsed)
{
    int i=0;
    char next;
    while (!file.eof()) //repeat until end of file
    {
        file>>name[i];
        for(int j=0; j<ncolUsed; j++){
            file>>test[i][j];
        }
        file.get(next);
        if(!file.eof()){
            file.putback(next);
        }
        i++;
    }
    return(i-1);
}

A: Before C++11, file.open() accepts a char*, which is C-string containing the name of the file to be opened , however, filename is of string type, you need to do the following:
 file.open(filename.c_str());

in order to read from the file.
EDIT: thanks to Benjamin Lindley, you can pass string to open() in C++11. You may need to check the exe file generated from your code can access your file, they may not be in same directory.


text:
Q: C# classes init function I am learning c#, having used python before, and i have started to use classes in my work.
Python has the __init__() function to initialise a class, for example:
class name():

    __init__(self):

        # this code will run when the class is first made

Is there a similar function for c# classes?
currently, I am creating a normal function inside the class and having to call it straight after it is made.

A: You have to use one or more constructor for that:
see this link on learn.microsoft.com.
For example:
public class Person
{
    private string last;
    private string first;

    // This constructor is called a default constructor.
    // If you put nothing in it, it will just instanciate an object
    // and set the default value for each field: for a reference type,
    // it will be null for instance. String is a reference type,
    // so both last and first will be null.
    public Person()
    {}

    // This constructor will instanciate an object an set the last and first with string you provide.
    public Person(string lastName, string firstName)
    {
        last = lastName;
        first = firstName;
    }
}

class Program
{
    static void Main(string[] args)
    {
       // last and first will be null for myPerson1.
       Person myPerson1 = new Person();

       // last = Doe and first = John for myPerson2.
       Person myPerson2 = new Person("Doe", "John");
    }
}

A: Your talking about constructor in c#
class MyClass{

public MyClass{ //this is the constructor equals to pythons init
}

}

These concepts are available in almost all languages with different format

A: You should start building a constructor like this:
public class Car
{
   public string plateNumber {get; set;}

   public Car(string platenumber)
   {
     this.plateNumber = platenumber;
   }
}

And then initialize an instance of it in another form or class like so:
Car myCar = new Car("123abc");


text:
Q: Transform array by cutting in half but extend elements I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.
# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?

A: a = [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]
first, last = a.first(a.size / 2), a.last(a.size / 2)
#=> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]
first.zip(last).map(&:flatten)
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]

A: Just one more solution:
a.each_slice(a.size / 2).to_a.transpose.map(&:flatten)
#=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

A: Step1: Divide array into two using each_slice method of array. each_slice documentation
Step2: Use array.zip method to map self with corresponding elements of array. zip documentation
Step3: Use flatten to flatten the array. Flatten documentation
s  => [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]

s1,s2 = s.each_slice((s.length)/2).to_a

==> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]

s1.zip(s2).map(&:flatten)

=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

A: s.each_slice((s.size + 1) / 2).reduce(&:zip).map(&:flatten)

A: s = [[1, 'blue'], [2, 'red'], [3, 'yellow'], [4, 'green'], [5, 'orange'], [6, 'black']]

# Split into two sections
s1 = s[0...s.length/2]
s2 = s[s.length/2..-1]

# Compile
p s1.each_with_index.map { |x, i| x + s2[i] }
#[[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

A: a maths trick -))
s.group_by {|a| a[0]%((s.length)/2) }.values.map {|e| e.flatten }
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]


text:
Q: Array of objects cannot be modified when passed through a function? I created a custom class called Weather and declared an array of Weather objects.
import Foundation

class Weather {
    var cityName:String
    var temperature:Double
    var temperatureMax:Double
    var temperatureMin:Double

    init(cityName: String, temperature: Double, temperatureMax: Double, temperatureMin: Double) {

        self.cityName = cityName
        self.temperature = temperature
        self.temperatureMax = temperatureMax
        self.temperatureMin = temperatureMin

    }
}

import UIKit
import SwiftyJSON

class ViewController: UIViewController {
    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        var weatherArrays = [Weather]()
        findLocation(zipCode: "11210", weatherArrays: weatherArrays)
        print(weatherArrays[0].cityName)
    }

    func findLocation(zipCode: String, weatherArrays: [Weather])
    {
        let zip = zipCode
        let appID = "245360e32e91a426865d3ab8daab5bf3"
        let urlString = "http://api.openweathermap.org/data/2.5/weather?zip=\(zip)&appid=\(appID)&units=imperial"
        let request = URLRequest(url: URL(string: urlString)!)
        URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            do
            {
                let json = try JSONSerialization.jsonObject(with: data!) as! NSDictionary
                let main = json["main"] as! [String:Any]
                let temp = main["temp"]! as! Double
                let name = json["name"]! as! String
                let tempMax = main["temp_max"]! as! Double
                let tempMin = main["temp_min"]! as! Double
                weatherArrays.append(Weather(cityName: name, temperature: temp, temperatureMax: tempMax, temperatureMin: tempMin))
            }
            catch
            {
                print("Error")
            }

            }.resume()
    }

}

I pass the array into a function and I append the values to the weatherArrays parameter. However, when I compile I get the error, "Cannot use mutating member on immutable value: 'weatherArrays' is a 'let' constant."
The Weather class was originally a struct but I got this same error and I read up and found that struct values cannot be edited in a function because it is pass by value.
I changed the struct to a class and I am still getting this same error? Why is it saying "'weatherArrays' is a 'let' constant" when I declared weatherArrays as a var?

A: Here is a better Approach for your code
import UIKit
import SwiftyJSON

struct Weather {
    let cityName:String
    let temperature:Double
    let temperatureMax:Double
    let temperatureMin:Double
}
class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!

    var array = [Weather]()
    let appID = "245360e32e91a426865d3ab8daab5bf3"

    override func viewDidLoad() {
        super.viewDidLoad()

        findLocation(zipCode: "11210"){ array in
            guard let array = array else {
                print("Error")
                return
            }
            print(array.first?.cityName ?? "no city name found")
        }

    }

    func buildUrl(queryItems: [URLQueryItem]) -> URL?{
        var components = URLComponents()
        components.scheme = "http"
        components.host = "api.openweathermap.org"
        components.path = "/data/2.5/weather"
        components.queryItems = queryItems
        return components.url
    }

    func findLocation(zipCode: String, completionHandler: @escaping (_ array: [Weather]?) -> ()){

        guard let url = buildUrl(queryItems: [URLQueryItem(name: "zip", value: zipCode), URLQueryItem(name: "appID", value: appID), URLQueryItem(name: "units", value: "imperial")]) else {
            print("Error in building url")
            return
        }

        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            guard let data = data else {
                print(error?.localizedDescription ?? "")
                completionHandler(nil)
                return
            }
            do{
                var array = [Weather]()
                let json = try JSON(data: data)
                if json["cod"].intValue == 200{
                    let main = json["main"]
                    let temp = main["temp"].doubleValue
                    let name = json["name"].stringValue
                    let tempMax = main["temp_max"].doubleValue
                    let tempMin = main["temp_min"].doubleValue
                    array.append(Weather(cityName: name, temperature: temp, temperatureMax: tempMax, temperatureMin: tempMin))
                    completionHandler(array)
                }else{
                    completionHandler(nil)
                }

            } catch let error{
                print(error)
            }
            }.resume()
    }

}

Use struct for models, we don't have to write init method
Use let instead of var when you know that the data is not going to be changed
Do not use NSDictionary.
You've written print statement right after calling the function where as the array would've been filled only after the call to server is completed. so I have used completion handler
I saw you have installed SwiftyJSON but you weren't actually using the benefits of it. Look at the parsing section.
About the error you were getting is because Swift is pass by value i.e. when you are passing array object you were actually passing a copy of it not the actual array. if you want the same array to be modified, you need to us inout. A great tutorial can be found for that
Edit: As suggested by @rmaddy to make the code much safer by returning a new array. Please see his comment for more information.

A: Because when you pass a parameter in the function it always passes let type. Type following code maybe it's help
import Foundation

class Weather {
    var cityName:String
    var temperature:Double
    var temperatureMax:Double
    var temperatureMin:Double

    init(cityName: String, temperature: Double, temperatureMax: Double, temperatureMin: Double) {

        self.cityName = cityName
        self.temperature = temperature
        self.temperatureMax = temperatureMax
        self.temperatureMin = temperatureMin

    }
}

import UIKit
import SwiftyJSON

class ViewController: UIViewController {

    var weatherArrays = [Weather]()
    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        findLocation(zipCode: "11210")

    }

    func findLocation(zipCode: String)
    {
        let zip = zipCode
        let appID = "245360e32e91a426865d3ab8daab5bf3"
        let urlString = "http://api.openweathermap.org/data/2.5/weather?zip=\(zip)&appid=\(appID)&units=imperial"
        let request = URLRequest(url: URL(string: urlString)!)
        URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            do
            {
                let json = try JSONSerialization.jsonObject(with: data!) as! NSDictionary
                let main = json["main"] as! [String:Any]
                let temp = main["temp"]! as! Double
                let name = json["name"]! as! String
                let tempMax = main["temp_max"]! as! Double
                let tempMin = main["temp_min"]! as! Double
                self.weatherArrays.append(Weather(cityName: name, temperature: temp, temperatureMax: tempMax, temperatureMin: tempMin))
            }
            catch
            {
                print("Error")
            }

            }.resume()
    }

}

A: First of all as rmaddy said in comment you should not do this.But if you are still interested to know how to make passed parameter mutable, below is an example.
// function should accept parameter as inout
func test(arr: inout [String]){
arr.append("item3")
print(arr) // ["item1", "item2", "item3"]
}
// you should pass mutable array
var item = ["item1", "item2"]
test(arr: &item)

Note from Swift doc
Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can't change the value of a parameter by mistake. If you want a function to modify a parameter's value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
For more info refer to this link.  https://docs.swift.org/swift-book/LanguageGuide/Functions.html


text:
Q: Elasticsearch javascript file could not load I have written a javascript function that calculates the closest distance between one point with multiple locations and put it into /etc/elasticsearch/scripts/my_file.javascript and using script mode to perform this function in elasticsearch, but unfortunately, I get an error.

u'search_phase_execution_exception', u'script_score: the script could not be loaded'

Anyone can help me! Thanks in advance
Here is code in my script file
(function(){
var i, locations, arcDist, closest, distance;
arcDist = function( lat1, lat2, lon1, lon2 ){
    var R = 6371 // earth radius
      , CI = 0.017453292519943295 // pi/180
      , dLat = (lat2-lat1) * CI / 2
      , dLon = (lon2-lon1) * CI / 2
      , sinDLat = Math.sin(dLat)
      , sinDLon = Math.sin(dLon)
      , a = sinDLat*sinDLat + sinDLon*sinDLon * Math.cos(lat1*CI)*Math.cos(lat2*CI)
      , c = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
}
locations = doc["locations"].getValues();
closest = arcDist( lat, locations[0].lat(), lon, locations[0].lon() );
for( i=1; i < locations.length; i++ ) {
    distance = arcDist( lat, locations[i].lat(), lon, locations[i].lon() );
    if(distance < closest) {
      closest = distance;
    }
}
return closest;

})();
and here is a part of whole code I use to call my script file
search_term["query"]["function_score"] = {
            "query": {
                "bool": bool_filter,
            },
            "script_score": {
                "script": {
                    "file": "my_file",
                    "lang": "javascript"
                }
            }
        }


text:
Q: why not supported font style works in windows 10? System.Drawing.Font font = new Font("Aharoni", 20f, FontStyle.Regular);

Above code works in windows 10 but fails in windows 7.
Can anyone please provide root cause why this works in windows 10?

A: That can be missing from windows 7
here font list in windows 7
To fix the problem you can add fonts you want to Resources like


text:
Q: Ionic 2 ion-segment, how to get the segment html? I have this simple ion-segment
html
<ion-segment [(ngModel)]="type" (ionChange)="selectedTabChanged($event)">
    <ion-segment-button value="a">a</ion-segment-button>
    <ion-segment-button value="b">b</ion-segment-button>
</ion-segment>

 <div [ngSwitch]="type">
    <div *ngSwitchCase="'a'">

        <ion-select #typeSelect (ionChange)="setMake($event)">
            <ion-option value="x">x</ion-option>
        </ion-select>

    </div>

    <div *ngSwitchCase="'b'">b</div>
</div>

js
export class MyPage {
    @ViewChild('typeSelect') typeSelect;

    ionViewDidEnter() {
        this.type = 'a';
    }

    selectedTabChanged($event): void {
        console.log(this.typeSelect);
    }
}

Expectation:

*

*when I tap on a i expect to get this.typeSelect

*when I tap on b i expect to get this.typeSelect as undefined, because ion-select is only in the a view

But I get the value backwards. I think that when I tap on b it looks for the html from a and vice-versa.
Any ideas?
edit:
looks like if I wrap the change in a timeout it works fine. But the problem is that I don't know how link it takes for the DOM elements to get un-hidden by the ngSwitch
setTimeout(() => {
    console.log(this.typeSelect);
}, 1000);


text:
Q: Java - How to Mock impl via using Mockito I have this repository created in my class as such:
    private static ModuleRepository repository = new ModuleRepository();

its called via:
  repository.isModuleCached(moduleType,taxModuleInfo.getModuleYear(), taxModuleInfo.getModuleVersion()

However when I try to mock it in my test class, I cannot actually return the mocked result I want, instead it calls the actual repository, as if my mockito call is ignored.
My Test case setup includes:
@Mock
private ModuleRepository repository;

my Test classs:
when(repository.isModuleCached(anyString(), anyString(), anyString())).thenReturn(resp);

The actualy repository in the class isn't autowired, it's instantiated, maybe that could be it?

A: Use @MockBean instead of @Mock. It tells Spring Boot that you're mocking an autowired bean.
@MockBean
private ModuleRepository repository;

Your test will also have to be annotated with @SpringBootTest
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.mocking-beans

A: If ModuleRepository is from a library you don't control, then define a Spring Bean for it as follows:
@Configuration
public class RepoConfig {
    @Bean
    public ModuleRepository getModuleRepository() {
        return new ModuleRepository();
    }
}

Now you can inject it as a Spring Bean using @Autowired, or better yet, using construction injection.
After you do this, you can use @MockBean in your test:
@MockBean
private ModuleRepository repository;

A: You should initialize all of your non-bean mock objects during the test setup
  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

A: Avoid when(xxx.xxx()).thenReturn(xxx).
Try doReturn(xxx).when(xxx).xxx() instead.
Here is an example:
doReturn(resp).when(repository).isModuleCached(anyString(), anyString(), anyString());
Also, the repository value is not injected.
Here is your example code:
private static ModuleRepository repository = new ModuleRepository();
Because you are initializing the variable by hand,
you must replace it with a Mock object, by hand, using Reflection.
Spring provides ReflectionTestUtils which will help.


text:
Q: Is there an automatic way to create a diverging colour scale centered around zero? I'm trying to plot a map of the residuals of a linear model. My residuals centre around zero and can obviously go in either direction.
Is there an easy way to apply a graduated colour scale to these values in QGIS, one that centres on zero and then shades in red above zero and blue below (or whatever colour ramp you choose) without having to manually set the upper and lower limits of each category?

A: Kludgy method:
Suppose your residuals go from -1 to +2 (use the "Statist" plugin to get the range of your attribute)
Create a dummy point (or other geometry) with residual -2.
Style as normal with an odd number of categories, white in the middle.
Make your dummy point invisible with some other style rule, or maybe delete it (but don't reclassify!). Or put it far away from your data and zoom until it's not visible.
If residuals go from -2 to +1 the dummy point needs value +2.

A: You can assign a graduated color ramp to a layer in QGIS by choosing it under Layer Properties > Style.
Here you can choose a given color ramp with three colors and set the offset of the middle color according to your dataset by editing the color ramp. Now you only have to set the number of classes and it classifies your data automatically.
If this doesn't produce the results you want, another possibility is to split the data layer into two layers, one with the negative values and the other one with the positive ones. Then you can assign each one a separate color ramp which goes only e.g. from red to white.

A: I wanted to provide an update on the thread. I don't know since when, but QGIS now allows for the use of symmetric classification. This probably solves the problem of locating the middle value at zero.

A: Try adjusting the breaks in the histogram once you've set a graduated colour scheme in the Layer Properties:
Here is the basic symbolization:

Then click the 'histogram' tab and click the 'load values' button:

Now click the histogram above the 0 value on the X axis - this adds a class to your graduated scheme that will start at 0:

That's the closest and easiest way to add a break at 0 - play around with the colour palette you want to use, but that might get you close...


text:
Q: Why doesn't updating this model trigger validations? With Rails 3.1, I have:
class Status < ActiveRecord::Base
  has_many :participations, :dependent => :destroy
  has_many :users, :through => :participations

  validates :users, :presence => true
end

In my unit test, I do:
user = User.create(:name => "Bob")
status1 = Status.create(:description => "available")
user.statuses << status1

and get:

ActiveRecord::RecordInvalid: Validation failed: users can't be blank

but, if instead of the last line I do:
status1.users << user

it works fine.
Why does the validation get triggered for:
user.statuses << status1

UPDATE:
the test in full
 test "Return all statuses associated with the manager" do
    manager = Manager.create(:email => "foo@bar.com", :password => "password", :password_confirmation => "password")

    workshop = Workshop.create(:name => "Bob Autos")
    manager.workshop = workshop
    manager.save

    user = User.create(:name => "a customer")

    workshop.users << user

    status1 = Status.create(:description => "Car is ready")
    status2 = Status.create(:description => "problem with exhaust")
    status3 = Status.create(:description => "parts delivered")

    user.statuses << status1
    user.statuses << status2

    assert_equal([status1, status2], manager.statuses)

    user.statuses << status3

    assert_equal([status1, status2, status3], manager.statuses)
  end

A: The validation is on Status, not on User. A model's validation is only triggered when that model is updated, and you didn't actually update the User model (since statuses is an association, not a field).
If you want validation on one object to trigger validation on another, you should use validates_associated:
class Status
  validates_associated :users
end

(On a related note, though, why does a Status have many users? Seems like a Status should only be on one user.)

A: Because the status1.users collection isn't automatically updated when you do user.statuses << status1


text:
Q: trying to get wordpress comments to show comment content inside On my home page. I want the a list of comments to show with the users comment, attached with their avatar, name and what category the comment is attached to.
At this moment i have these results from the below image

I cant seem to get the actual content of the message to appear in the loop along with the category that the post is attached to.
<?php
$total_comments = $wpdb->get_results("SELECT comment_date_gmt, comment_author, comment_ID, comment_post_ID, comment_author_email FROM $wpdb->comments WHERE comment_approved = '1' and comment_type != 'trackback' ORDER BY comment_date_gmt DESC LIMIT 10");
$comment_total = count($total_comments);
echo '
';
for ($comments = 0; $comments < $comment_total; $comments++) {
echo "

";
echo get_avatar($total_comments[$comments]->comment_author_email,$size='32',$default='<path_to_url>' );
echo "

";
echo '
';
echo $total_comments[$comments]->comment_author . ' says ';
echo 'comment_post_ID) . '#comment-' . $total_comments[$comments]->comment_ID . '">';
echo get_the_title($total_comments[$comments]->comment_post_ID);
echo '

';
}
echo '
'
?>

How would i go about adding the comment_content and its category?
EDIT. Here is what i have found that shows something close to my prefeered answer
<?php
$comments = get_comments('status=approve&number=5');
  foreach($comments as $comment) :?>

  <?php $my_id = $comment->comment_post_ID ; $post_id_comms = get_post($my_id); $title = $post_id_comms->post_title;?>

    Who: <?php echo($comment->comment_author);?>

    About: <a href="<?php echo get_permalink($my_id) ?>#comment-<?php echo $comment->comment_post_ID?>" title="on <?php echo $title ?>"><?php echo $title ?>

    What they said: <?php echo($comment->comment_content);?>

    When they said it: <?php echo($comment->comment_date);?>

  <?php endforeach;?>

A: Try get_comments() instead, it'll give you most of the information you need and to  get the category of a post from comment you can use get_the_category function inside the loop, for example
$comments = $comments = get_comments( array('status') => 'approve' );
foreach($comments as $comment) {
    echo $comment->comment_content;
    $categories = get_the_category( $comment->comment_post_ID );
    foreach($categories as $category) {
        echo $category->cat_name;
    }
}


text:
Q: In PostgreSQL, how to query for a computed results by the grouping of a field? In my PostgreSQL database I have an invitations table like so:
Invitations Table:
id, created_at, source, completed_at

Fields Details
id: integer
created_at: timestamp
source: varchar
completed_at: timestamp

I'd like to query the Invitations table and group by unique sources. And then per source, include the total # of records and the total of those completed. Completed being where complated_at is NOT NULL.
Desired Results:
columns: source, total, total_completed

source_a | 100 | 50
source_b | 200 | 33
source_c | 301 | 3

Suggestions?

A: You can do aggregation like so:
select source,  count(*) total, count(completed_at) total_completed
from invitations
group by source

count(*) counts all records in the group, while count(completed_at) counts only records whose completed_at is not null.


text:
Q: Xamarin wont build Android application I'm an android newbie, Installed Xamarin for visual studio, also Installed Android SDK and loads of stuff on there, however I get this error when building:
1>------ Build started: Project: WordSolverO, Configuration: Debug Any CPU ------
1>    Processing: obj\Debug\res\layout\main.xml
1>    Processing: obj\Debug\res\values\strings.xml
1>  WordSolverO -> C:\Users\Elmeri\Documents\WordSolverO\WordSolverO\bin\Debug\WordSolverO.dll
1>    Processing: obj\Debug\res\layout\main.xml
1>    Processing: obj\Debug\res\values\strings.xml
1>    Processing: obj\Debug\res\layout\main.xml
1>    Processing: obj\Debug\res\values\strings.xml
1>C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(1868,3): error MSB6006: "javac.exe" exited with code 2.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Heres the Xamarin Diagnostics:
[I:sdk]:                    Key HKCU\SOFTWARE\Novell\Mono for Android\AndroidSdkDirectory found:
    Path contains adb in \platform-tools (C:\Program Files (x86)\Android\android-sdk).
[I:sdk]:                    Key HKCU\SOFTWARE\Novell\Mono for Android\AndroidNdkDirectory found:
    Path contains ndk-stack in \. (C:\ProgramData\Microsoft\AndroidNDK64\android-ndk-r11c\).
[I:sdk]:                    Key HKCU\SOFTWARE\Novell\Mono for Android\JavaSdkDirectory found:
    Path contains jarsigner.exe in \bin (C:\Program Files\Java\jdk-9.0.1).
[I:Unknown]:              Found Xamarin.Android 7.0.2
[I:Unknown]:              Found Android SDK. API levels: 19, 20, 21, 23
[I:]:                     Tracking android devices started
[D:]:                     TrackDeviceTask got:
[D:]:                     Tracking avd started
[I:]:                     Got new device list from adb with 0 devices
[D:]:                     avd watcher *.ini path: 'C:\Users\Elmeri\.android\avd'
[D:]:                     avd watcher android path: 'C:\PROGRA~2\Android\ANDROI~1\tools\android.BAT'
[D:]:                     avd watcher: got device list from avd with 1 devices

I've checked the JDK & SDK locations, and theyre fine it seems
https://i.imgur.com/M4DtPh3.png
So I have no Idea whats wrong, I dont see any descriptive error here..

A: I bet that source of all these problems is DEX 64K limit + old proguard version (in case of multidex enabled).
You should upgrade Proguard, according to this topic (procedure has to be performed after each Built-Tools update by SDK-Manager):
http://stackoverflow.com/questions/39514518/xamarin-android-proguard-unsupported-class-version-number-52-0
Also check that you have only Java SDK 1.8 installed (remove any 1.7 versions if installed).
PS Don't forget to modify your mainClassesDex.bat (or your app will crash at startup @ Android 4.4 and lower, but work well @ newer versions):
http://www.jon-douglas.com/2016/09/05/xamarin-android-multidex/

A: I too faced this issue and later found "javac.exe" exited with code 2 occurs when multidex support is not enabled.
When your app and libraries it references exceed 65,536 methods, you encounter this build error. This means that your app has reached the limit of the Android build architecture.
Please enable the multidex for your android project and you should be able to build and deploy the app. (You can do this by right clicking on Android project, then navigating to project settings/options. In the "build" tab you should have option to enable multidex)
Refer : https://developer.android.com/studio/build/multidex.html


text:
Q: jquery mobile login form with php I have struggled with the code forever!! I keep getting the invalid password error and however many times I adjust where the hashing is or where to check the password I still get it even though i place the correct password for different users...I really need some help!
The table of 'users' in my db is
        id
        username
        password (sha1)
        fullnames
        mobile_no
        usertype
Here is the code I am currently trying to get to work!

Sign In

          <form name="login" class="ui-corner-all" method="post" action="">
            Username:
            <input type="text" id="username" name ="username" placeholder="Username" required>

            Password:
            <input type="password" id="password" name ="password" placeholder="Password"  required>

            <fieldset class="ui-grid-a">

          <input name="login" type="submit"  id="login" formmethod="POST"          value ="login" data-ajax="false" data-theme="b">

          Not a user? Sign Up

      </fieldset>
          </form>
          <?php
      if (isset($_POST["login"]) && !empty($_POST["login"])) {

      $user = stripslashes($_POST['username']);
      $pass = stripslashes($_POST['password']);
      $user = mysqli_real_escape_string($link, $_POST['username']);
      $pass = mysqli_real_escape_string($link, hash("SHA1",($_POST['password'])));

      if ($user && $pass) {  // CHECK ALL FIELD HAS BEEN FILLED UP

      // QUERY FROM DATABASE
      $sql = "SELECT * FROM users WHERE username='".$user."'";
      $query =mysqli_query($link,$sql) or die(mysqli_error($link));

      $numrows = mysqli_num_rows($query);

      if($numrows !== 0)
      {
      while ($row = mysqli_fetch_assoc($query))
      {
          $username = $row['username'];
          $password = $row['password'];

          }

          if($user==$username && $pass==$password)
          {
              echo "you are logged in";
              @$_SESSION['username'] = $username;
              }

              else {
                  echo "your password is incorrect";
                  }
      }
                  else
                      die ("that user doesn't exist!");
                  }
                  else
                      die ("Please enter a username and password");
      }

          ?>

A: Your code is working fine. I am getting "you are logged in".
I just added session_start() and replaced variable in mysqli_real_escape_string()

                Sign In

            <form name="login" class="ui-corner-all" method="post" action="">
                Username:
                <input type="text" id="username" name="username"
                    placeholder="Username" required>

 Password: <input
                    type="password" id="password" name="password"
                    placeholder="Password" required>

                <fieldset class="ui-grid-a">

                        <input name="login" type="submit" id="login" formmethod="POST"
                            value="login" data-ajax="false" data-theme="b">

                        Not a user? Sign Up

                </fieldset>
            </form>
            <?php
            $link = new mysqli("localhost", "root", "root", "test");
            /* check connection */
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                exit();
            }

            if (isset($_POST["login"]) && !empty($_POST["login"]))
            {
                $user = stripslashes($_POST['username']);
                $pass = stripslashes($_POST['password']);
                $user = mysqli_real_escape_string($link, $user);
                $pass = mysqli_real_escape_string($link, hash("SHA1",($pass)));

                if ($user && $pass) {  // CHECK ALL FIELD HAS BEEN FILLED UP

                    // QUERY FROM DATABASE
                    $sql = "SELECT * FROM users WHERE username='".$user."'";
                    $query =mysqli_query($link,$sql) or die(mysqli_error($link));

                    $numrows = mysqli_num_rows($query);

                    if($numrows !== 0)
                    {
                        while ($row = mysqli_fetch_assoc($query))
                        {
                            $username = $row['username'];
                            $password = $row['password'];
                        }

                        if($user==$username && $pass==$password)
                        {
                            session_start();
                            echo "you are logged in";
                            @$_SESSION['username'] = $username;
                        }
                        else
                        {
                            echo "your password is incorrect";
                        }
                    }
                    else
                        die ("that user doesn't exist!");
                }
                else
                    die ("Please enter a username and password");
            }
            ?>


text: Q: Kubernetes not restarting failed pods on another docker node I have a 4 node kubernetes cluster with 3 minions. I am running the application with 2 replica pods on the two minion node. When the docker engine on one of the minion stops, kubernetes shows the status of pods running on that docker node as error and does not restart the pod on the other minion node. Is there any way, kubernetes will try to restart failed pods on the nodes available in the cluster?


text:
Q: How to find equidistant colors in different colorspaces? I can find equidistant colors in the LAB colorspace. Since, it is complicated, I first calculated the values of a and b for equidistant points on the AB plane and incremented the L values gradually for each point. Below is what I've done so far:
getLABColors[n_] := (
      RM = {{Cos[\[Theta]], -Sin[\[Theta]]}, {Sin[\[Theta]],
            Cos[\[Theta]]}};
      coord = {{1}, {1}};
      l = Table[x, {x, 0, 1, 1/(n - 1)}];
      ab = Table[RM.coord, {\[Theta], 0, 2 Pi , 2 Pi /(n - 1)}];
      a = Table[ab[[i]][[1]][[1]], {i, 1, n, 1}];
      b = Table[ab[[i]][[2]][[1]], {i, 1, n, 1}];
      labcolors =
          Table[LABColor[N[l[[i]]], N[a[[i]]], N[b[[i]]]], {i, 1, n, 1}]
     );

Using this, I can find 6 equidistant colors:
labcolors = getLABColors[6]

and the result is:
{LABColor[0., 1., 1.], LABColor[
 0.2, -0.6420395219202061, 1.260073510670101], LABColor[
 0.4, -1.3968022466674206`, -0.22123174208247431`], LABColor[
 0.6, -0.22123174208247431`, -1.3968022466674206`], LABColor[
 0.8, 1.260073510670101, -0.6420395219202061], LABColor[1., 1., 1.]}

When I tried to visualise the points on the 3D Gamut, I found the point lie on the surface of the gamut in the form of a spiral of one complete turn as I wanted.
Show[ChromaticityPlot3D["LAB", FillingStyle -> Opacity[0.2]],
 ChromaticityPlot3D[labcolors, PlotStyle -> PointSize[.02]]]

I tried to do the same with RGB colorspace but did not get the expected result.
getRGBColors[n_] := (
   RM = {{Cos[\[Theta]], -Sin[\[Theta]]}, {Sin[\[Theta]],
   Cos[\[Theta]]}};
   coord = {{1}, {1}};
   b = Table[x, {x, 0, 1, 1/(n - 1)}];
   rg = Table[RM.coord, {\[Theta], 0, 2 Pi , 2 Pi /(n - 1)}];
   r = Sort[Rescale[Table[N[rg[[i]][[1]][[1]]], {i, 1, n, 1}]]];
   g = Sort[Rescale[Table[N[rg[[i]][[2]][[1]]], {i, 1, n, 1}]]];
   rgbcolors =
   Table[RGBColor[N[r[[i]]], N[g[[i]]], N[b[[i]]]], {i, 1, n, 1}]
 );

 rgbcolors = getRGBColors[6];

Show[ChromaticityPlot3D["RGB", FillingStyle -> Opacity[0.5]],
ChromaticityPlot3D[rgbcolors, PlotStyle -> PointSize[.02]]]

(a) What is the correct way to fix this?
(b) How can I extend this to other color spaces?
(c) Is it possible to achieve this in a far better and faster way than the approach I have followed?
[It will be a bonus if the color values for the points can be displayed on the chromaticity plot either statically or on mouse hover.]


text:
Q: $f(n) = \Omega(n), g(n) = \mathcal O(n), h(n)= \theta(n) \implies f(n).g(n)+h(n)=\Omega(n)$
Let $f(n) = \Omega(n), g(n) = \mathcal O(n), h(n)= \theta(n) \implies f(n).g(n)+h(n)=\Omega(n)$

We get
$g(n) \leq [n ==h(n)] \leq f(n)$
$f(n).g(n)+h(n) \geq n+n \cdot g(n)$
But problem gives upper bound of g but not lower bound. To get greatest lower bound, i can put $g(n)$'s max value as $n$. Then $f(n).g(n)+h(n) \geq n+n\cdot n = n^2 \geq n$ PLease correct me if wrong.

A: I assume that there is an implicit assumption that $g(n)\geq 0$; without this the statement would not be correct, e.g. by taking $f(n)=h(n)$ and $g(n)=-1$.
With this assumption, we simply have $f(n)g(n)+h(n)\geq h(n)=\Omega(n)$.
(The fact that $f(n)$ and $h(n)$ are positive, at least for $n$ sufficiently large, does follow from the given conditions.)
Incidentally, when you talk about "putting $g(n)$'s greatest value as $n$", don't forget the constant: we only know $g(n)\leq cn$ for some $c>0$ (and $n$ sufficiently large).


text:
Q: Does light change color on its way through a window? Looking at the refractive index of glass, it's around $1.6$.
Then the speed of light $x$ through light should be given by
$$ 1.6 = \frac{3.0\times10^8}{x}, $$
so $x$ is about $2\times10^8~\mathrm{m}~\mathrm{s}^{-1}$
The frequency is kept constant, so the wavelength must adapt to suit the slower speed, giving a wavelength of $2/3$ the original.
Does this mean that when passing through glass, say red light (wavelength $650~\mathrm{nm}$) changes to indigo ($445~\mathrm{nm}$), as $650 \times 2/3 = 433~\mathrm{nm}$, or is my logic flawed somewhere?

A: I've had the same question some time ago, and discussed it with some friends.
First of all: yes, this question is fairly ill-defined, since you only observe color through your eyes, meaning the lightbeam will always be travelling through the eye-fluid when it strikes your photoreceptors, so it's kind of hard to define precisely define the color of light in any other context than when travelling through your eye.
That being said, it turns out what your eyes percieve are the excitations of molecules in your photoreceptors, i.e., the frequency (energy) of the light. Hence, should one try to "translate" the light from the interior of the glass to what your eyes would see, the color would be identical.

A: Do not try to characterize light by it's colour. Colour is something that is defined only in vacuum! Light is characterized by it's wavelength or frequency, one is enough. You additionally have to have the knowledge of the refractive index though. So you are right about how the wavelength is changing but the frequency stays constant.
To the question what we will see as an observer: We would see red light. Because when the light quits the glass, the wavelength will experience the reverse change than as when it entered. You would see the exact same light that entered the glass which was described by you as red.
An interesting question though is what would we see if we were able to put our eyes INTO the glass, so that the light is not transformed back to it's initial state. Well then SamRoelants pointed out what we would see.

A: What do you take to define "red" light: a wavelength of $650~\mathrm{nm}$ or a frequency of $460~\mathrm{THz}$? On the one hand, this borders on being an ill-defined question, but I suppose it can be massaged into something answerable.
I would argue that frequency is more fundamental to describing the light. After all, it is the frequency that is constant throughout all this, as you noted. When a photon strikes a receptor in your eye, it doesn't matter whether it did so after just passing through glass or through vacuum - the biochemical response is dictated by the frequency/energy of the photon. Thus it would be more appropriate to say red light stays red, but the wavelength corresponding to red shifts in glass.


text:
Q: Child Theme Translations with PoEdit What I'm doing
I am translating a child theme and followed the instructions on https://developer.wordpress.org/themes/advanced-topics/child-themes/#internationalization.
What I did so far
Step 0
All the text strings in my php files follow the structure of
_e('this string needs translation', 'my_text_domain')

Also there are currently no php files from the parent theme in my child theme's folder. I just mention that in case someone thinks that this could be the problem:

In the event that a template file from the parent them has been included, the textdomain should be changed from the one defined in the parent theme to the one defined by the child theme.

Step 1
I created a "/lang/" folder in my child theme folder
Step 2
I used poedit in order to create a new wp theme translation, so de_DE.mo as well as de_DE.po files were created and saved to my child themes lang folder.
Step 3
I have included in my child themes functions.php:
add_action('after_setup_theme', 'my_lang_setup');
function my_lang_setup()
{
    $lang = get_stylesheet_directory() . '/lang';
    load_child_theme_textdomain('my_text_domain', $lang);
}

Result of Step 0 - 3
All the strings of my child theme ARE translated and show up correctly in my front end!
The issues I am trying to solve

*

*All the strings of the parent theme aren't translated anymore and just show up in english

*When updating (or loading) the translations in poedit it removes all the strings from the parent theme (which might be the major issue)

Questions

*

*Of course, how to solve my issues?

*Does the child theme's text domain have to be the same as the parent theme's text domain? I found different statements / "How to's" so I am a bit confused.

*Is there anything I am missing?

*There are four options in order to translate with poedit:

*

*Edit translation

*Create new translation

*Translate Wordpress theme or plugin

*Translate together with others (not relevant)

I tried I guess all of the above mentioned options with the same result. Is there a way to include the parent themes language files / catalogue?

A: Found a solution that works for me:
add_action( 'after_setup_theme', 'avia_lang_setup' );
function avia_lang_setup() {
    $lang = apply_filters('parent-theme-slug', get_template_directory()  . '/lang');
    load_theme_textdomain('avia_framework', $lang);
    load_child_theme_textdomain( 'child-theme-text-domain', get_stylesheet_directory() . '/lang' );
}

Note:
Exchange "parent-theme-slug" (typically the parent theme name in small letters) and "child-theme-text-domain" (child theme text domain of your choice)

A:
Does the child theme's text domain have to be the same as the parent
  theme's text domain?

It must NOT be the same.
Text domains must be unique. If the parent theme loads a file into "my_text_domain" and then your child theme loads a file into "my_text_domain", it will overwrite the previous one.


text:
Q: Rancher in Docker doesn't create snapshot data to host I am running Rancher 1.6 in Docker on VPS with CentOS 7. I would like to share configuration data with host (don't loose data if docker container failed).
Before starting rancher container, I create folder on host:
HOST_VOLUME=$HOME/rancher-data/mysql
mkdir -p $HOST_VOLUME

Then start rancher server:
sudo docker run -d \
-v $HOST_VOLUME:/var/lib/mysql \
--restart=unless-stopped \
-p 8080:8080 \
rancher/server

I setup Rancher - authentication, added couple of hosts and containers which are now running. But the folder on host ($HOME/rancher-data/mysql) is empty. If I switch inside container with cmd, I can see in /var/lib/mysql a lot of files which Rancher is using, but they are not mirrored to host.

A: I tested this out on an Ubuntu system, and I'm not able to duplicate what you're experiencing. My thought was that this was related to sudo not passing the environment from your local use to root due to env_reset in /etc/sudoers, but I removed that from my sudoers file and it still worked fine.
To further test this on your system, I would do the following:

*

*If there's a problem, it's with Docker, not with Rancher, so test it with busybox instead of the rancher/rancher container. Run the same command like this: sudo docker run -it --rm -v $HOST_VOLUME:/var/lib/mysql busybox ash. This will drop you into a shell in the container - use df -h to see if the volume from your host is mounted on /var/lib/mysql in the container. If so, then the command itself is working, and we just need to find out where that mount is.

*From another login to the same system (while the above container is running), look at it with docker inspect <container_id> and look for the HostConfig section. You should see your volume mount under Binds.

"HostConfig": {
    "Binds": [
        "/home/ubuntu/test:/test"
    ],

*If you don't see it there, then Docker is ignoring your request to mount that. Try it again with an absolute path, as @nischay-goyal suggested. You can also look in the system log for error output about why Docker won't mount a volume as requested. I would expect it to error out and fail, but maybe there's something else acting as a noop and it's continuing anyway. Logs will give you more information.

*If nothing above works, rule out the "dual user environment" issue that sudo is bringing by adding your local user to the docker group. Log out and back in. Re-run your docker run command without sudo and see if it works as expected.


text:
Q: How to add php to a linux (ubuntu) server already running nginx + gunicorn + django I have been running a django app on nginx using gunicorn on Ubuntu (now version 12.04) for some time now, and have been pleased with the results. My issue is that I have inherited a php site which I want to run on the same server.
Can anyone give me some advice on what might be the best way to add php to my server setup?

A: *

*sudo apt-get install php-fpm

*Set up your new virtual host.

*Enjoy.


text:
Q: Equivalence relations regarding binary relations Let $R \subseteq X \times X$ be a binary relation for $X = \{a, b, c, d\}$.
$R = \{(a, a), (b, c), (c, d), (b, d)\}$. Is the relation an equivalence relation? I don't know if I am proving it correctly by using a formal proof?
Proof:
a)$R \subseteq X \times X$, thus reflexive holds.
b)$R \subseteq X \times X$ then $X \times X \subseteq R$, thus symmetric holds.
c)I don't know how to formally prove it correctly.
Is this correct? Thanks.

A: No, what you have is not correct.

*

*For $R$ to be reflexive, it must contain $(x, x)$ for every $x \in X$.

*For $R$ to be symmetric, it must contain $(x, y)$ if it contains $(y, x)$.

*For $R$ to be transitive, it must contain $(x, z)$ if it contains $(x, y)$ and $(y, z)$.

In this case, $R$ is not reflexive or symmetric, but it is transitive.

*

*Not reflexive: $R$ does not contain $(b, b)$, $(c, c)$ or $(d, d)$.

*Not symmetric: $R$ contains $(b, c)$ but does not contain $(c, b)$.  Similarly, $R$ contains $(c, d)$ but not $(d, c)$ and $(b, d)$ but not $(d, b)$.

*Transitive: There is no triple of elements $x, y, z \in X$ such that $R$ contains $(x, y)$ and $(y, z)$ but not $(x, z)$.

It might help to think of $R$ as defining a binary operator $\sim$: for each pair of elements $x, y \in X$, $x \sim y$ if and only if $(x, y) \in R$.

*

*The reflexive property means that every element is related to itself: $x \sim x$ for every $x \in X$.

*The symmetric property means that you can switch the order of the operands: $x \sim y \iff y \sim x$.

*The transitive property means that you can "chain" the relation: $x \sim y \text{ and } y \sim z \implies x \sim z$.


text:
Q: Correlation in matlab not working as expected I am using matlab to implement a program that does OCR
I've build a template for each english letter + the numbers.
now I am trying to open an image and recognize the letters in it, for the basic start I've tried to load an image that is one of the letters template, the input image and the template image are the same in all parameters.
Now I passed the template array and compared each letter\number template to the input image (using corr2 function), I expected to get the right result because the images are the same, but other letter was found as better match.
what can be the problem?
*I am using the bwlabel to find the letter itself, and then cutting the image around it, and i'm working on binary images
thank you

A: perhaps you need to do some preprocessing before calculating the correlation?
suggestions: convert to b&w, bump up the contrast, straighten the image, perhaps even resize to match size of templates

A: If your images are binary with the only values being zero and one, correlation probably isn't doing what you expect. That's because correlation involves multiplying, and anything multiplied by zero gives zero. To get correlation working how you expect, try changing all zeros to negative ones.


text:
Q: Running my Oracle DB query through Jenkins I'm automating my deployment process with the help of Jenkins.
Running my bat file and I've done all the code deployment process.
Now I want to deploy my DB scripts to the corresponding DB servers.
Is there any Plugin or can I do it through my bat file itself which one is easier and best.
Can someone give me an idea.
I searched the solution on online all referring to SQLPlus Script Runner Plugin
I'm not aware of that plugin is that good. Can I use the same for my deployment.
For deploying the DB scripts through SQLPlus Script Runner plugin is that alone or I've to install oracle client on my build server.

A: You will have to install the Oracle Instantclient with Sqlplus.


text:
Q: Java.IO.FileNotFoundException: Xamarin.Forms I'm working on a Xamarin.Forms Project
I'm trying to play an .mp3 file with the plugin Xam.Plugin.SimpleAudioPlayer.
I am attempting to do this out of the Assets folder of my Xamarin.Forms Project
When I use the following code:
            var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
            player.Load("select.mp3");

I receive this error:

Java.IO.FileNotFoundException

However If I use the AssetManager class to open the .mp3 file I receive the same error:
        AssetManager assets = Android.App.Application.Context.Assets;
        //var filename = assets.Open("select.mp3");
        Stream input = assets.Open("select.mp3");

        //var newfile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "select.mp3");

Some code is commented out to show the different variations I have tried.

A: First of all, create an interface in the PCL.
    public  interface IReadStream
    {
        Stream ReadStreamFromAsset();
    }

Then  achieve the interface in the android platform.

[assembly: Dependency(typeof(ReadStreamService))]
namespace MyPopUpPageDemo.Droid
{
    class ReadStreamService : IReadStream
    {
        public Stream ReadStreamFromAsset()
        {

            AssetManager assets = Android.App.Application.Context.Assets;

            return assets.Open("app_sound.mp3");
        }
    }
}

Please notice mp3 file Build Action to AndroidAsset

Then use dependenceService in the PCL.
           ISimpleAudioPlayer player;
        Stream stream;
        public MainPage()
        {

            InitializeComponent();

            player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
            stream = DependencyService.Get<IReadStream>().ReadStreamFromAsset();
            player.Load(stream);

        }

When button is clicked it, play the audio
 private void Button_Clicked(object sender, EventArgs e)
        {
            player.Play();

        }


text:
Q: Webpack "cannot find module" error, path is wrong I am trying to publish my application and I am getting the following webpack error:

Error: Cannot find module 'C:\Users\User\source\repos\DDvwn\node_modules\webpack\bin\webpack.js'

The path it provides is wrong. The correct path to the file should be C:\Users\User\source\repos\DDvwn\DDvwn\node_modules\webpack\bin\webpack.js, with another "DDVwn" subfolder present in the hierarchy. I am not seeing a place to change this in the config file and my searches online haven't been fruitful.
Anyone know how to fix this?


text:
Q: How are the classical and quantum picture of electromagnetic radiation related?
*

*The classical picture of EM radiation is the picture of a wave with electric and magnetic field oscillating perpendicularly to each other and to the direction of propagation. Let us neglect the magnetic field part. The energy carried per unit time by such a wave is proportional to the intensity of the wave which is defined as E^2. Here E is the electric field. Away from the source, E of the EM wave falls off by (1/r) where r is the distance from the source. So the energy carried by the EM radiation falls off by (1/r^2).

*The quantum picture of EM radiation is the picture of a Photon. The energy of a photon is defined as (h*f) where h is Plank's constant and f is the frequency of the radiation. So the energy of Photon is fixed.
Correspondence If in in classical description, one says that an EM wave has high amplitude or high intensity or high energy then the quantum mechanical way of interpreting is to say that the EM wave has high number of photons. So amplitude/intensity/energy of EM wave corresponds to number of photons.
Question: It is possible that at a point far away from the source, the electric field which falls of as (1/r) will attain a value such that k*(E^2)=h*f. where k is the proportionality constant between energy and intensity of the EM radiation. i.e. the energy of EM radiation will correspond to single photon. What will happen beyond this particular distance r? Beyond this distance E will fall off as (1/r) and energy will fall off as (1/r^2) in the classical picture. But the energy of the photon which only depends on frequency should remain constant (there can be no division or waning of the photon). How then is it possible to have the classical and quantum pictures consistent to each other beyond the distance r ?.


text:
Q: Non-static methods used in a static context error I keep getting two errors for this bit of code about non-static methods used in a static context.  This code uses an ArrayList of different objects of birds, cats, and dogs and puts them in the ArrayList called petList using an interface called Pet.
I get the same errors on the 4th and 6th line.
    public static void Feed(ArrayList petList){
        Scanner input = new Scanner(System.in);
        String petName = input.next();
        contains(petName, petList);

        if(ifThere == true){
            String feed = Pet.feed();
            System.out.println(petName + feed);
        }
        else{
            System.out.println("Unknown pet");
        }
    }

  public boolean contains (String petName, ArrayList petList){

    boolean ifThere = false;
    int sizeList = petList.size() -1;
    for(int i=0; sizeList > i; i++){
      Pet booleanPet = petList.get(i);
      String booleanName = booleanPet.getName();
      if (booleanName.equals(petName)){
        ifThere = true;
      }
}
return ifThere;

}

A: In short : You can not call non static method from static method.
Solution :  1) Make  your "contains" method as Static and it will solve the problem.
OR
    2) (Assume the name of the class is Pet then create an instance of Pet class and call contains method :
your line 4 can be replaced by below code(C# style code) :
Pet somePet = new Pet ();
somePet.contains(petName, petList);

-- Extra Details:
Static method is a method which is never specific to any object. e.g. Addtion of 2 number. You
dont need to instantiate any class to call Math.Add() method because Add is static method.
You can also say that Static is a method which is not a virtual meaning you definitely know
which method is being called.


text:
Q: Loading model function inside a webservice function I'm working in a codeigniter based project with integrated SOAP webservices, and I fail to load a model function inside a registered webservice function.
I have this 2 functions in SOAP webservice: hello and addcontact.
function hello($name) {
            return 'Hello, ' . $name;
    }

and
function addcontact($nombre, $apellido, $ciudad) {
        $resultado=$this->modelo_turismo->addcontact($nombre, $apellido, $ciudad);

        if($resultado){
            return "Bienvenido $nombre $apellido. Tu eres de $ciudad.";
        }else{
            return "No se pudo agregar contacto.";
        }
    }

Function hello is simple and its working fine when service is consumed by client, unlike function addcontact that is showing this message when trying to be consumed:
Response not of type text/xml: text/html

As you can see, I'm loading a function within model that inserts a contact to database, but im not even returning any database data to echo or print.
As well I've tried some other things trying to load the model, I cant get rid of that message, so I tried this (I know its weird to use a function to insert like this in CodeIgniter but im trying to learn why that message come):
function addcontact($nombre, $apellido, $ciudad) {
        $conexion = new mysql ("localhost","root","","turismo");
        if ($conexion->connect_errno){
            return "Failed to connect to MySQL: " . $conexion->connect_error;
        }
        $query = "INSERT INTO contactos (nombre, apellido, ciudad) VALUES ('$nombre', '$apellido', '$ciudad')";
        $resultado = $conexion->query($query);
        if($resultado){
            return "Bienvenido $nombre $apellido. Tu eres de $ciudad.";
        }else{
            return "No se pudo agregar contacto.";
        }

    }

with that function I get this error again:

Response not of type text/xml: text/html

But if I change the in the connection line 'mysql' to 'mysqli' like this:
$conexion = new mysqli ("localhost","root","","turismo");

I get the expected result when loading client:

Bienvenido John Travolta. Tu eres de California.

I then suspected that the error I was getting loading the model was because in my database config file I had this line:
$db['default']['dbdriver'] = 'mysql';

so I tried to change the driver to 'mysqli' and no good results. I keep getting the same error:

Response not of type text/xml: text/html

BTW, this is the way im registering 'addcontact' function:
$this->nusoap_server->register('addcontact',                // method name
        array('nombre' => 'xsd:string',
            'apellido' => 'xsd:string',
            'ciudad' => 'xsd:string'),        // input parameters
        array('return' => 'xsd:string'),      // output parameters
        'urn:Turismo_WSDL',                      // namespace
        'urn:Turismo_WSDL#addcontact',                // soapaction
        'rpc',                                // style
        'encoded',                            // use
        'Agregar reservacion'            // documentation
    );

and this is the client function, that consumes the function above:
function addcontact() {

    $wsdl = site_url('Webservice/wsdl');
    $client = new nusoap_client($wsdl, true);
    $client-> soap_defencoding='UTF-8';
    $client->decode_utf8 = true;

    $err = $client->getError();
    if ($err) {
        echo '
Constructor error

' . $err . '
';

    }

    $result = $client->call('addcontact', array('nombre' => 'John', 'apellido'=>'Travolta', 'ciudad'=>'California'));

    // Check for a fault
    if ($client->fault) {
        echo '
Fault

';
        print_r($result);
        echo '
';
    } else {
        // Check for errors
        $err = $client->getError();
        if ($err) {
            // Display the error
            echo '
Error

' . $err . '
';
        } else {
            // Display the result
            echo '
Result

';
            print_r($result);
        echo '
';
        }
    }
}

So my question is, what I'm doing wrong? I can do the work with a manual connection like described above, but I want to work with the model as in CodeIgniter.

A: We can call the codeigniter models using instance variable
$ci =& get_instance();
Class soap
{
    private $ci;

    // set the CI classes to  $CI
    function __constuct(){
       $this->ci = & get_instance ();
    }

    function callone(){
      $resultado=$this->ci->modelo_turismo->addcontact($nombre, $apellido, $ciudad);
    }

}

ci-> will provide the models from CI
Please refer this for more about codeigniter Instance variables
Codeigniter: Get Instance


text:
Q: passing part of constructor parameters to castle windsor container I have constructor
Foo(IColor c , int someNumber)

and I know the some number only during the run time, and I want to call this constructor during the resolving and to pass someNumber value and the IColor to be resolved autocratically.
Something like this:
container.Resolve<IFoo>(someNumber);

Is it possible to be done ?

A: You should prefer Typed Factory instead of using container like service locator. Just define factory interface:
public interface IFooFactory {
    IFoo Create(int somenumber);
}

and register it as typed factory:
container.Register(Component.For<IFooFactory>().AsFactory());

Then use dependency injection to inject factory and use it:
var foo = fooFactory.Create(desiredArgumentValue);

For more info read Windsor documentation

A: Yes, pass the constructor arguments in an instance of an anonymous type; the property names must match the constructor parameter names:
IColor desiredColor = //whatever
int desiredNumber = //whatever else
IFoo foo = container.Resolve<IFoo>(new { c = desiredColor, somenumber = desiredArgumentValue });

If you are using an older version of C# that does not support anonymous types (or even if you're not), you can do the same with a dictionary:
IColor desiredColor = //whatever
int desiredNumber = //whatever
Dictionary<string, object> arguments = new Dictionary<string, object>();
arguments.Add("c", desiredColor);
arguments.Add("somenumber", desiredNumber);
IFoo foo = container.Resolve<IFoo>(arguments);


text:
Q: Restart Nautilus-Instaling Dropbox I'm new with Ubuntu so I hope you can help me. I installed Dropbox using the terminal. Now when I open dropbox to try to log in this message apears:

restart nautilus

I do it but nothing happens. I tried this but nothing changed:
sudo add-apt-repository ppa:gnome3-team/gnome3-staging
sudo apt-get update
sudo apt-get install nautilus
sudo apt-get -f install

How can I proceed?

A: Try nautilus -q or sudo nautilus -q. Logging out and back in should also restart nautilus.

A: Start Nautilus and close it and start it again.
As soon as my first restart finished following my upgrade from 14.04 to 16.04.1, my machine displayed a dialog box with the message "Nautilus Restart Required Dropbox requires Nautilus to be restarted to function properly."
There was a "Restart Nautilus" button and a "Close" button.
The "restart" button did nothing, but after I clicked "close", I started Nautilus and closed it and started it again, from the Launcher, and Dropbox worked just fine.


text:
Q: Can posterior become tractable if we know p(x)? In the VAE framework where x is an input data (a vector) and z is a vector of continuous latent variables,
the posterior p(z|x) is intractable because p(x) is intractable, so we approximate it using an approximate posterior q(z|x).
But, what happens if we know p(x)?

*

*e.g., if p(x) = N(mu, covariance mtx) is known, does this make the posterior tractable?

*If yes, does this also apply even if the covariance mtx has off-diagonal terms (i.e., elements in the vector x are correlated) - or does it not matter?

A: Bayes theorem is
$$
p(z|x) = \frac{p(x|z)\, p(z)}{p(x)}
$$
so if you know all the components, it's just a multiplication and division. If you don't, you usually need to take the integral
$$
p(x) = \int \, p(x|z)\, p(z) \,dz
$$
and the integral is often intractable. Correlated elements have nothing to do with that.