text:
Q: Complete solution to upgrade PostgreSQL on debian production server I'm using Debian 6 (Squeeze) in production for a couple of websites. I decided to use postgresql backports so that I could use PostgreSQL 9.0 features. I thought that it would remain 9.0 and receive updates to that major version.
Unfortunetly Squueze backports were updated to PostgreSQL 9.1 so probably I won't receive updates to 9.0.
I'm planning upgrading to 9.1 but I know that it's not done automatically.
I've read about official pg_upgrade and debian's pg_upgradecluster, but I would appreciate complete guide to upgrade.

*

*What are steps to do (first apt-get install postgresql, then pg_upgradecluster, then remove old cluster)? List of steps would be nice.

*What are possible failure scenarios?

*How to prepare to failures and react on them?

I can stop database for a couple of hours only so I want to be prepared

A: It's pretty hard to give you a step-by-step upgrade process that's tailored to your situation/environment.
I've tried to hit some of the highlights below, but you really need to tailor the process to your environment.

Step Zero, decide if you need to upgrade.  Postgres 9.1 brings Synchronous Replication and a bunch of other cool stuff which is useful if you need it, but not a reason to upgrade right away if you don't.
Step 1, expect that this will take a long time if your database is big.
Even using pg_upgrade the simple process of copying the data for a backup can take a while: our 16GB databases take an hour or morefor a pg_dump/pg_restore, or about 10-20 minutes for a pg_upgrade).
Step 2, I suggest reading through the 9.1 Release Notes.  Make sure nothing you need is broken and nothing you use has changed.
There is nothing like a database upgrade that destroys your production systems to really ruin your month.
Step 3, The upgrading section of the Postgres manual is required reading.
Step 4, (insert any Debian-specific stuff here, but that's really not my bag :-)
Step 5, Create an upgrade plan.
Step 6, Test the upgrade plan (technically optional, but strongly recommended).
Step 7, Do the upgrade on your production systems.

Standard caveats apply:

*

*Upgrading could destroy your database.  Make a backup.

*

*Be sure you can restore it.

*Be sure you can restore the binaries for the database system too.
(Hang on to your old Debian packages if you can - I've seen people unable to back out of a failed upgrade because they don't have the old database binaries anymore, and it's a very sad sight indeed.)

*It will take longer than you expect.  Plan for this.
My company's DB upgrade policy is "Start at 6PM on Friday.  If it's not working by 9AM on Sunday roll back."

*Mount a scratch monkey
If your data is really important restore a copy of it elsewhere and test your upgrade path.
Yeah, I do this with 16GB databases.  I'll still do it with 160GB databases if I can find a way to make it work :-)

A: This is step 4 basically - plus the --check option to make sure  your paths are right.  My install is from the repos and has standard debian paths for the files.
postgres@example.org:~$ /usr/lib/postgresql/9.1/bin/pg_upgrade --old-datadir /var/lib/postgresql/9.0/main --new-datadir /var/lib/postgresql/9.1/main --old-bindir /usr/lib/postgresql/9.0/bin/ --new-bindir /usr/lib/postgresql/9.1/bin/ --check

This above failed - consistently said I was running both servers on the same port.
The following seemed to work:
pg_dumpall -p 5432 | psql -d postgres -p 6543

This is useful.


text:
Q: GLM prediction in r I spilt the data set into train and test as following:
splitdata<-split(sb[1:nrow(sb),], sample(rep(1:2, as.integer(nrow(sb)/2))))
test<-splitdata[[1]]
train<-rbind(splitdata[[2]])

sb is the name of original data set, so it is 50/50 train and test.
Then I fitted a glm using the training set.
fitglm<-  glm(num_claims~year+vt+va+public+pri_bil+persist+penalty_pts+num_veh+num_drivers+married+gender+driver_age+credit+col_ded+car_den, family=poisson, train)

now I want to predict using this glm, say the next 10 observations.
I have trouble to specify the newdata in predict(),
I tried:
pred<-predict(fitglm,newdata=data.frame(train),type="response", se.fit=T)

this will give a number of predictions that is equal to the number of samples in training set.
and finally, how to plot these predictions with confidence intervals?
Thank you for the help

A: If you are asking how to construct predictions on the next 10 in the test set then:
pred10<-predict(fitglm,newdata=data.frame(test)[1:10, ], type="response", se.fit=T)

Edit 9 years later:
@carsten's comment is correct regarding how to construct a confidence interval. If one has a non-linear link function for a glm-object, fitglm then this is a reasonably general method to recover the inverse of the link function and construct a two-sided 95% CI on the response scale:
pred.fit <- predict(fitglm, newdata=newdata, se.fit=TRUE)
pred.fit <- predict(fitglm, newdata=newdata, se.fit=TRUE)
CI.pred.upper <- family(fitglm)$linkinv(  # that information is in the model
                        pred.fit+  1.96*pred.fit$se.fit )

CI.pred.lower <- family(fitglm)$linkinv(  # that information is in the model
                        pred.fit$fit - 1.96*pred.fit$se.fit )

redpajama_set_name: RedPajamaStackExchange


text:
Q: scrollIntoView on element with height = 0 in angular 2+ I have the following html:

and after ajax call I have that div visible.
Then I want to scroll to that div by click:
document.getElementById('hr-data').scrollIntoView({behavior: 'smooth'});

but it doesn't work.
So, how can I fix that?

A: For some reasons, div class="row-20 st-margin" has no height.
I moved id to div class="col-md-12" and it works fine:


text:
Q: Is there any danger/risk in leaving my iMac G5 turned off and disconnected for long periods of time? As the title states, is there any danger in leaving my iMac G5 (Later 2005 model) turned off and disconnected from a power outlet for long periods of time?
I will be traveling for roughly 1 month and, during a normal week, I only intend to use it a couple of times a week. Otherwise, it will sit in my room under a full dust cover, disconnected from a power outlet.
Is there any risk to this? Specifically- could doing this alone damage the battery/system components/screen as it would damage a portable battery powered device such as an iPad or iPhone (where the battery must be charged and discharged at a fairly consistent rate)?

A: Your machine is now 10 years old, so there's definitely the risk that your PRAM backup battery has "worn out" and is nearly dead now. The life expectancy for these kinds of "coin cells" is normally about 10 years.
So if you disconnect your Mac from the power supply for an "extended time" you risk that it fails to back up the PRAM. A battery loses its charge over time, and that's especially true for worn out batteries. The more you disconnect your Mac from the mains connection the more the backup battery has to supply the PRAM with electrical current, which in turn causes the battery to wear out even more.
Disconnecting your Mac from the mains connection as such is not harmful for your Mac or any of its components.
You could have your battery replaced which should cost you about USD 100-150 (my estimation based on the effort to completely disassemble the iMac). Then leaving the iMac disconnected for a month would not be any problem at all.


text:
Q: Having difficulty finishing this time-based code snippet

var myVar = setInterval(myTimer, 1000);

var button = document.querySelector(".button");

function myVarFunction() {
 setInterval(myTimer, 1000);
}

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

function clockButton(document.querySelector(".button").toggle(".clockOn")){
 if(button.hasAttribute("class","clockOn")){
  clearInterval(myVar);
  }else{
 myVarFunction();
 }
}
<!DOCTYPE html>

A script on this page starts this clock:

<button onclick="clockButton()" class = "button clockOn" >button</button>

I'm trying to execute a code snippet that will display the time in real-time (using the setInterval() method) and a button that when clicked will stop the time running in real-time, but if clicked again the time will run in real-time as it did before(using .toggle() to achieve this).
here is a link to the w3schools exercise where I got this idea from:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval
For some reason the time completely dissapears, none of my code works and I can't work out why

A: You can check my implementation below, the time continues from the current realtimee after toggling, I guess this is what you want.

let time = document.getElementById("demo")
let myIntervalTimer;

function myStartFunction() {
 if(myIntervalTimer){
  clearInterval(myIntervalTimer)
 }
 myIntervalTimer = setInterval(myTimer, 1000)
}

function myStopFunction() {
 clearInterval(myIntervalTimer)
}

function myTimer() {
  let d = new Date();
  let t = d.toLocaleTimeString();
  time.innerHTML = t;
}

let timeClassList = time.classList
function toggleTime() {
if(timeClassList.contains('showTime')) {
 myStopFunction()
}
else {
  myStartFunction()
}
timeClassList.toggle("showTime")
}
myStartFunction()
<!DOCTYPE html>

A script on this page starts this clock:

<button onclick="toggleTime()">Toggle time</button>

A: Skip to the end if you just want the answer

First thing's first, remove your onClick event from the HTML and place it in your script. This is the recommended way to set up events.
<button class="button clockOn">button</button>

and
var myVar = setInterval(myTimer, 1000);

var button = document.querySelector(".button");

// Add the event listener here
button.addEventListener("click", clockButton);

Now there's a couple of issues, but your most prominent one is the clockButton function. What you've got here is invalid JavaScript, you cannot execute code within the parameter list of a function:
function clockButton(document.querySelector(".button").toggle(".clockOn")){
  ...
}

You need to move this code to the body of the function instead.
function clockButton () {
  document.querySelector(".button").toggle(".clockOn");
  ...
}

That fixes the first problem, which is just invalid code. But the next problem you're going to face is that toggle(...) is not a function of the button element, (You may be confusing a bit of jQuery here, which has happened to me a number of times). You don't actually need this line of code though anyway, so you can remove it, and write your own class toggle.
It's fairly straightforward to write a class toggle, and you're actually doing a check already for the buttons class in your if statement, so it's a naturally obvious place for you to write the class toggle:
if(button.hasAttribute("class","clockOn")){
  ...
}

But unfortunately, there's a problem with the code above. Calling the hasAttribute function on an element will just check whether that attribute exists, not if it actually has a certain value. So in your case it will always be true, as you're never removing the class attribute, only changing it to something different.
To fix this up, you can use the classList functionality, which is the standard these days to deal with element classes in the native DOM API. You want to check that the element has the class clockOn so you can change the if statement to this:
if (button.classList.contains("clockOn")) {
  ...
}

To remove the class, you can use the remove function on the classlist like  so:
button.classList.remove("clockOn");

And you can add the class back using
button.classList.add("clockOn");

So all in all, your function becomes this
function clockButton(){
    if(button.classList.has("clockOn"){
        clearInterval(myVar);
        button.classList.remove("clockOn");
    }
    else {
        myVarFunction();
        button.classList.add("clockOn");
    }
}

Now that you're here, your button should work to stop the clock, and restart it again when you click it a second time, but it's not working properly yet, because you'll notice if you click it again, the time does not stop.
This is because myVarFunction does not reassign the new interval handle to the myVar variable. Every time you call setInterval you should get a new handle. So as an example, imagine that the first time you call setInterval it assigns the handle of 123.
var myVar = setInterval(myTimer, 1000);
// myVar === 123

Now clearInterval(myVar) will clear the running interval.
The next time you set the interval, it is within myVarFunction, lets say for example, it returns 456 the next time it's called.
function myVarFunction() {
   // setInterval returns `456`
   setInterval(myTimer, 1000);

   // myVar is still equal to `123`
}

The next time you try to clear the interval, you are clearing 123 (since you never reassigned the myVar variable) which doesn't exist, you should be clearing 456 which was the new interval you just set up.
So it's an easy fix
function myVarFunction() {
  myVar = setInterval(myTimer, 1000);
}

TL;DR
Your code should look something like this
<!DOCTYPE html>

A script on this page starts this clock:

<button class="button clockOn" >button</button>

var myVar = setInterval(myTimer, 1000);

var button = document.querySelector(".button");

button.addEventListener('click', clockButton);

function myVarFunction() {
    myVar = setInterval(myTimer, 1000);
}

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

function clockButton(){
    if(button.classList.contains("clockOn")){
        clearInterval(myVar);
        button.classList.remove("clockOn");
    }
    else {
        myVarFunction();
        button.classList.add("clockOn");
    }
}

See it live
JSFiddle


text:
Q: v-for loop not returning data Vue.js I'm new to Vue.js and following a tutorial. I'm trying out the v-for loop using the data in the json below. However nothing is being rendered in the div and therefore the page. I can't spot any syntax errors. Can anyone help?

{{item.name}}

{{item.description}}

${{item.price}}.00

A: just change you code

var data = { ... }

To

data() { return { product: [...] } }

and it will work.

*

*in recent vue.js it is recommended to put 'v-key' when you use v-for, but it still works (no v-key is also ok when you run the program)

A: try it this way, with a container div#app and data as a function, you can verify here: https://jsfiddle.net/boilerplate/vue

{{item.name}}

{{item.description}}

${{item.price}}.00

A: Creating a separate #app div and returning the data within a function works.

{{item.name}}

{{item.description}}

${{item.price}}.00


text:
Q: How to test ejs/nodejs function with mocha/chai? I have a function in a ejs/nodejs application that I need to test. The function adds a user(name and array of 4 letter grades). I want to test the function to verify that it adds one user.
the function:
router.addUsers = (req, res) => {
  console.log("in homeController addUser");

  var newUserName = req.body.name;
  console.log("name " + newUserName);
  var newUsergrade = req.body.grade;

  var temp = 0;
  newUsergrade.forEach(letter => {
    letter = letter.toUpperCase();
    switch (letter) {
      case 'A':
        letter = 4.0
        break
      case 'A-':
        letter = 3.7
        break
      case 'B+':
        letter = 3.3
        break
      case 'B':
        letter = 3.0
        break
      case 'B-':
        letter = 2.7
        break
      case 'C+':
        letter = 2.3
        break
      case 'C':
        letter = 2.0
        break
      case 'C-':
        letter = 1.7
        break
      case 'D+':
        letter = 1.3
        break
      case 'D':
        letter = 1.0
        break
      case 'F':
        letter = 0.0
        break
    }
    temp += letter;
  });

  var valid = false;

  if (temp / 4 >= 2.5) {
    valid = true;
  } else {
    vaild = false;
  }

  col.insertOne({
    name: newUserName,
    grade: newUsergrade,
    isValid: valid
  }, function(err, r) {
    test.equal(null, err);
    test.equal(1, r.insertedCount);
    col.find({}).toArray((err, userData) => {
      console.log("record found: ", userData);
      usersArray = userData;
    });

  });

  usersArray.push({
    name: newUserName
  });
  res.render("users", {
    allUsers: usersArray,
    title: "Users List"
  });
};

What I've been trying so far:
describe("addUsers", () => {
  it("should make sure a user can be added to the array", () => {
    var usersArray = {
      name: "blake",
      grade: ["a", "a", "b", "d"]
    };
    expect(router.addUsers(usersArray)).to.deep.include({
      name: "blake",
      grade: ["a", "a", "b", "d"]
    });
  });

  it("should return an empty object with empty request body input", () => {
    var emptyBody = {};
    expect(router.addUsers(emptyBody)).to.deep.include({});
  });
});

Im getting an error that 'name' is undefined. Could this be because of the req,res or the res.render?

A:     expect(router.addUsers(usersArray)).to.deep.include({
      name: "blake",
      grade: ["a", "a", "b", "d"]
    });

Your function returns undefined but here you're checking the return value includes name. That's why it says name is undefined.
You want something like the below, you could use some sort of package to mock the request and response objects more appropriately.
const fakeReq = { body: { name: 'something', grade: 'somethingElse' }},
  fakeRes = { render: () => {}};

await router.addUsers(fakeReq, fakeRes);

expect(usersArray).to.deep.include({ name: 'something' });


text:
Q: How can I optimize this code? (JodaTime required) I'm building a Java method to sum arithmetically two time periods, using JodaTime library.
My code works fine, but I think that it's possible optimize to reduce the time execution...
Unfortunately, I'm new on JodaTime.
This is my code:
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class Test {

    public static void main(String[] args)
    {
        String time1 = "08:00";
        String time2 = "08:00";

        System.out.println(Operation_Sum(time1,time2));
    }

    private static String Operation_Sum(String time1, String time2)
    {
        String output;
        long start = System.currentTimeMillis();

        if (time1.equals("00:00") && time2.equals("00:00"))
        {
            output = "00:00";
        }
        else if (time1.equals("00:00"))
        {
            output = time2;
        }
        else if (time2.equals("00:00"))
        {
            output = time1;
        }
        else
        {
            boolean sign_time1 = false;
            boolean sign_time2 = false;
            String[] time1_out, time2_out;

            boolean negative = false;
            String output_split[];

            if (time1.contains("-"))
            {
                time1_out = time1.split(":");
                time1_out[0] = time1_out[0].replace("-", "");
                time1_out[1] = time1_out[1].replace("-", "");
                time1 = time1_out[0] + ':' + time1_out[1];
                sign_time1 = true;
            }

            if (time2.contains("-"))
            {
                time2_out = time2.split(":");
                time2_out[0] = time2_out[0].replace("-", "");
                time2_out[1] = time2_out[1].replace("-", "");
                time2 = time2_out[0] + ':' + time2_out[1];
                sign_time2 = true;
            }

            PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
            builder.minimumPrintedDigits(2);
            builder.printZeroAlways();
            builder.appendHours();
            builder.appendLiteral(":");
            builder.appendMinutes();
            PeriodFormatter pf = builder.toFormatter();

            Period period1 = pf.parsePeriod(time1);
            Period period2 = pf.parsePeriod(time2);
            Period normalized;
            Period total = null;

            if (sign_time1 && sign_time2)
            {
                total = period1.plus(period2);
                negative = true;
            }

            if (sign_time1 && !sign_time2)
            {
                total = period2.minus(period1);
            }

            if (!sign_time1 && sign_time2)
            {
                total = period1.minus(period2);
            }

            if (!sign_time1 && !sign_time2)
            {
                total = period1.plus(period2);
                negative = false;
            }

            normalized = total.normalizedStandard(PeriodType.time());
            output_split = pf.print(normalized).split(":");

            if (output_split[1].contains("-"))
            {
                output = output_split[0] + ":" + output_split[1].replace("-", "");
            }
            else
            {
                output = (negative ? "-" : "") + output_split[0] + ":" + output_split[1];
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("exec time sum1: " +(end - start) + " ms");
        return output;
    }
}

Thanks!! :)

A: The code is really in bad need for a CR.
If you want to make it faster, make it first shorter. The JVM sort of refuses to optimize overlong methods.
Concerning optimization, it looks like you're wasting most time with strings. Anyway, cleaning up the code, then profiling, and then optimizing is the proper order.
From you program isn't exactly clear what you're doing, however, it can't be really right. Doing
time1_out[0] = time1_out[0].replace("-", "");

means that you transform e.g., --12:--34--- into 12:34. Is this intended? If not, where is the dash allowed? If only at the first position like -12:34, then time1_out.substring(1) is surely cleaner and faster. And so on...

I'm using two strings because the input comes from a database

Is there any database which can't store dates or numbers? If 12:34 means about half past twelf, then store it as DATE. If it means 12 hours and 34 minutes or 12 minutes and 34 seconds, then store it as INTEGER. Never ever manipulate strings if there's a better datatype.


text:
Q: jQuery Deferred/Promise Design Patterns and use cases My question is quite general and some related questions can be found on SO, but none of those really are what I am looking for.
I have been reading up on/toying with the jQuery Deferred object and I see it is used a lot inside the library itself to handle ajax requests and animation etc. I understand the general functionality and think it has proven to be very useful in some situations. The jQuery library solves some problems quite elegantly using this concept.
Now my question is: I think it would be very useful to have an overview of distinct problem/solution scenarios that can be solved elegantly and robustly using the Deferred object.
In which situations is a solution using jQuery Deferred called for? Which general patterns in javascript software design can be distinguished that can be solved most elegantly using jQuery Deferred functionality? I'm aiming to compile a list of quite general patterns (as opposed to very specific examples), in the spirit of the gang of four design patterns every OO analyst knows about.
With such a list in the back of the head, when designing jQuery solutions it should become second nature to take advantage of these deferred patterns in just the same way the bridge, factory, ... patterns already help us to design flexible and robust solutions without having to re-invent the wheel every time.

A: Asynchronous Tasks broadly fall into 5 different problem domains.
Network/Local data requests
Probably the most common, and well covered by Fabrizio Calderan's answer. In these cases we have to handle at least 2 outcomes, and depending on granularity (various types of success or errors for a request), and then act on them.
Deferred/Promises allows us to chain, or parallelise requests, or hybrids of both to achieve the resource loading we need for our task. For example, we can wait for a range of requests to complete before we then load some more, or do something else based on those outcomes.
Animation
Chaining/Parallel animated sequences, are more easy to implement, and maintain. Conditional steps based on different outcomes (when accounting for user interaction or a random factor.) are also easy to implement and maintain.
(pseudo) Modal User Interaction
True modal operation isn't possible in the browser, and presenting dialogs, wizards etc. requires asynchronous operations provided by Deferred/Promises to act on resolved outcomes, (success, activities, options, cancellation etc.) before cleaning up the display (also simplified, as mentioned already) and resuming normal operation. Deferred/Promises allow you to act on those outcomes in a relatively simple declarative fashion.
Effectively this combines user interaction with animation/display sequences.
Hardware availability/responses
Mobile device(s) availability (for example through PhoneGap) needs to be guaranteed before calling them for services, and in many cases, provide response asynchronously.  Using Deferred /Promises simplifies and improves the code managing these device interactions.
Software component activity
SQLLite specifically, provides it's responses to JS requests asynchronously, and so doing complex query interactions, is far simpler than it would be using callbacks.
In theory this applies to any auxillary software component which provides asynchronous responses.
One more thing...
This is one of the best articles I've read on Deferred/Promises, I recommend reading it for some proper in-depth examples and explanations.

*

*http://sitr.us/2012/07/31/promise-pipelines-in-javascript.html
tl;dr
The big benefit of Deferred/Promises is that they make solutions for several domains much easier to conceive in the first place and maintain afterwards. In some cases they simplify them so much, that had they been attempted using callbacks and convoluted outcome checking, many fully grown adults (and possibly a number of small children)
...would go from this...

To this...

If a solution requires chaining, waiting for the outcome of one or more processes to resolve, or any combination of these, Deferred/Promises will save you frustration and anguish, and will do the same for anyone who inherits your code.
Now go out and prove me wrong by committing horrible abuses. No, really, don't do that. Write nice clean, maintainable code.
Disclaimer: Using Deferred/Promises in your code may not feel like you are "on a boat", but it will feel way better than a soup made of callbacks

A:
In which situations is a solution using jQuery Deferred called for

I think that as a thumb rule, every time you have both

*

*one or more asynchronous tasks

*some related callbacks depending on the success/fail of those task

you can try to refactor your code in terms of deferred objects and promises. Most common scenarios in which  deferred objects could be used at best involve

*

*An Ajax request and callback/s (a single request, parallel or chained requests)

*An asynchronous loading of assets and actions to perform at load event (e.g. an image preloader like this one: https://gist.github.com/958683)

*A callback to execute after complete of an animation or a lot of sequential animations which would require a lot of nested scopes: this can be easily achieved just chaining a promise() method to the animate() method so to return a promise to handle with done() callback (to be honest I cannot really figure out how an animation can fail)

hope this hint could be useful in some way.


text:
Q: VS Code : .net doesn't exist in "select debugger" When I try to debug C# or F# or create launch.json, the .NET I installed does not appear in "Select debugger".
In C#, if I press Yes on "Required assets to build and debug are missing from 'tutorial_vscodedotnet'. Add them?" and press Yes, a ".vscode folder" will be created and F5 will work.
If I don't press Yes and do "create a launch.json File", ".net Framework 4.x (Windows only)" appears.
In fact, there was one time on each computer when I pressed F5 and ".NET 5+ and .NET Core" showed up.
That came up when I re-installed the environment from scratch, but it never showed up again.
I've rebooted, reinstalled extensions, but that didn't work.
I tried it on several computers and the same thing happened. The dotnet command works fine.
I ask this question because I have looked into it and you guys don't seem to have stumbled on this issue.
I'm a beginner so it is possible that I haven't done the basics.
VS Code extensions:

*

*C#

*Ionide for F#

F# halloworld
Run and Debug
dotnet --info
postscript
I disabled the extension "Ionide for F#" and ".NET 5+ and .NET Core" appeared!
I think this is the solution for C#, but I need this extension for F#, right?
Is it possible to solve the problem with "Ionide for F#" enabled?(or do I not need "Ionide for F#"?)


text:
Q: Display Selected Message String I'm working on a method that goes through all of my array messages and displays the selected message. I'm new to Java so I'm still trying to figure out methods and Arrays. When I run this, it says that it's successful but it doesn't display anything. Can someone help me figure this out.
package chatbox;

import java.util.Scanner;

public class ChatBox
{
 public static void main(String[] args)
 {
 String chatMessages[] = new String[10];
 //declare arrays
 chatMessages[0]= "Pepperoni";
 chatMessages[1]= "Olives";
 chatMessages[2]= "Cheese";
 chatMessages[3]= "Onions";
 chatMessages[4]= "Bacon";
 chatMessages[5]= "Tomato sauce";
 chatMessages[6]= "Bell peppers";
 chatMessages[7]= "Mushrooms";
 chatMessages[8]= "Sausage";
 chatMessages[9]= "Beef";

 }

 Scanner scan = new Scanner (System.in);

public Scanner chatCannedMessage(String chatMessages)
          {
for (int i=0;i<chatMessages.length;i++){

     System.out.println(chatMessages[i]); //Prints Message
 }

System.out.println("Select a message");

String chatMessage = scan.next();

scan.nextLine();

 return scan;

          }
}

A: As PM 77-1 said, you never invoked your shoutOutCannedMessage method and also never print out or return any string.
I tried to minimize changes to your code, and I think this might be what you intended to do.
import java.util.Scanner;

public class ShoutBox {

    Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {

        String messages[] = new String[10];
        //declare 10 arrays
        messages[0] = "Pepperoni";
        messages[1] = "Olives";
        messages[2] = "Cheese";
        messages[3] = "Onions";
        messages[4] = "Bacon";
        messages[5] = "Tomato sauce";
        messages[6] = "Bell peppers";
        messages[7] = "Mushrooms";
        messages[8] = "Sausage";
        messages[9] = "Beef";

        String m = new ShoutBox().shoutOutCannedMessage(messages);
        System.out.println(m);
    }

    public String shoutOutCannedMessage(String[] messages) {
        for (int i = 0; i < messages.length; i++) {

            System.out.println(i+". "+messages[i]); //Should print the messages
        }

        System.out.println("Select a message");

        int idx = scan.nextInt();

        String message = messages[idx];

        return message;

    }
}


text:
Q: Mostrar el primer elemento de un array Tengo un problema con un `array, tiene el siguiente formato:
$array = [{"id": 1,"nombre": "Disco Duro"}];

Actualmente lo consumo de la siguiente manera $array[0] accediendo a la posición del array pero lo que intento es usar el $array sin la posición.
El resultado que edseo obtener es el siguiente:
$array = {"id": 1,"nombre": "Disco Duro"};

Sin los [], pero sin acceder al elemento [0]

A: Para que puedes acceder al elemento [0] puedes realizar lo siguiente.
basándome en tu ejemplo: http://sandbox.onlinephpfunctions.com/code/f8abc47768f1c86ddb773b23a222108f5d931a5f
Todo está OK, pero si solo quieres tener el elemento [0] Ya no pongas los [] dentro del foreach.
Tu codigo:
foreach (json_decode($array, true) as $value){
    $simpleArray[] = $value;
}

Nuevo codigo:
foreach (json_decode($array, true) as $value){
    $simpleArray = $value;
}

Con eso no habrá ninguna necesidad de usar acceder al elemento [0]

A: Por que no utilizar array_shift().

array_shift() Quita el primer valor del array y lo devuelve...

Ejemplo:
$array = ['{"id": 1,"nombre": "Disco Duro"}'];
$producto = json_decode(array_shift($array));

var_dump($producto);

//acceso a datos
echo 'Nombre: '.$producto->nombre;
echo 'id: '.$producto->id;

Resultado:
object(stdClass)#1 (2) { ["id"]=> int(1) ["nombre"]=> string(10) "Disco Duro" }

Nombre: Disco Duro
id: 1

A: Para pasar el JSON a un array asociativo, deberías utilizar la función de PHP llamada JSON_DECODE; te dejo el ejemplo de como debería ser
echo $array = '[{"id": 1,"nombre": "Disco Duro"}]';
$nuevo = JSON_DECODE($array, true);

Ahora para que puedas ver el contenido, usa la función var_dump(); que te devolverá la impresión de la clave y valor
echo $array = '[{"id": 1,"nombre": "Disco Duro"}]';
$nuevo = JSON_DECODE($array, true);
var_dump($nuevo);

/*imprime lo siguiente
[{"id": 1,"nombre": "Disco Duro"}]array(1) { [0]=> array(2) { ["id"]=>
int(1) ["nombre"]=> string(10) "Disco Duro" } }*/

Ahora te comento el JSON que viene en tu variable $array(); debes
  meterlo entre comillas simples para que sea válido al momento de
  transformarlo

ACTUALIZACIÓN

Para quitar los corchetes que me mencionaste en los comentarios, se me ocurre lo hagas del modo siguiente en dos pasos con la función str_replace()
$array = '[{"id": 1,"nombre": "Disco Duro"}]';

$arrayUno = str_replace("[", "", $array);

$arrayDos = str_replace("]", "", $arrayUno);

echo $arrayDos;
//{"id": 1,"nombre": "Disco Duro"}

echo "<br>";

$nuevo = JSON_DECODE($arrayDos, true);

var_dump($nuevo);
//array(2) { ["id"]=> int(1) ["nombre"]=> string(10) "Disco Duro" }

A: Debes usar un ArrayObject(); y lugo lo conviertes a formato JSON con json_encode();
$array = new ArrayObject(array(), ArrayObject::STD_PROP_LIST);
$array->id = 1;
$array->nombre = "Disco Duro";
$myJSON = json_encode($array);
echo $myJSON;

esto imprime solo el JSON
{"id":1,"nombre":"Disco Duro"}

Aqui lo puedes ver  Ejecutar!


text:
Q: Suppose $-3$ is a quadratic residue mod $p>3$, where $p$ is prime. Show that $p$ is of form $x^2+3y^2$.
Suppose $-3$ is a quadratic residue $\mod p>3$, where $p$ is prime. Show that $p$ is of form $x^2+3y^2$.

I have shown that the standard norm on $\mathbb{Z}[\sqrt{-3}]$ and the norm on $\mathbb{Z}[\zeta_3]$ given by $N(a+b\zeta_3)=a^2-ab+b^2$ have the same image. (Here, $\zeta_3$ is a primitive cubic root of unity, so $\mathbb{Z}[\zeta_3]$ is the Eisenstein integers.) I believe I am supposed to use this fact to prove my claim. In other words, given by $p\mid n^2+3$ for some $n$, I need to show that there is some polynomial in $\zeta_3$ with integer coefficients such that taking norm will yield $p$.
Any and all help would be appreciated. I know the usual argument in this kind of situation is to appeal to unique factorization and proceed without this business of showing that the norm image coincides with the norm image of the Eisenstein integers, but unfortunately $\mathbb{Z}[\sqrt{-3}]$ is not a UFD.


text:
Q: Detecting and removing substrings from string I'm working with URLs and sometimes end up with random repeated phrases in them that are throwing off my scripts. I'd like to remove the duplicates.
So, I start with something like this:
url = "https://account.live.com/consent/Manage?fn=email&uaid=51e2193a466c4846a4317b94931b9086&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&lc=1033&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&id=38936&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US&mkt=en-US"

And want to convert that to:
url = "https://account.live.com/consent/Manage?fn=email&uaid=51e2193a466c4846a4317b94931b9086&lc=1033&id=38936&mkt=en-US"

All of the solutions I've looked at rely on the spaces between words or the repeating pattern coming at the beginning of the string.  In my situation, the repeating pattern(s) don't have those boundaries to base my grouping on.
How can I do this?

A: The first step is going to be to extract the query string and split it into separate parts on the & character; the last step is going to be to join the parts back together with &.
Assuming the duplicates always appear adjacent to each other like in your example input, you can filter them out using itertools.groupby to retain the original order:
import itertools

def remove_duplicate_params(url):
    path, _, query_string = url.partition('?')
    parts = query_string.split('&')
    return path + '?' + '&'.join(k for k, _ in itertools.groupby(parts))

# 'https://account.live.com/consent/Manage?fn=email&uaid=51e2193a466c4846a4317b94931b9086&lc=1033&id=38936&mkt=en-US'

If the duplicates might not be adjacent, and you don't need to preserve the order of the parameters in the query string, you can use set to remove the duplicates:
def remove_duplicate_params(url):
    path, _, query_string = url.partition('?')
    parts = query_string.split('&')
    return path + '?' + '&'.join(set(parts))

# 'https://account.live.com/consent/Manage?fn=email&mkt=en-US&lc=1033&id=38936&uaid=51e2193a466c4846a4317b94931b9086'


text:
Q: Error executing query: Telerik.OpenAccess.RT.sql.SQLException: Invalid object name 'Employee' I am using Telerik Open Access ORM in my asp.net C# web application.
In my app, I have mapped a table entity from database named "Person"  as base class and created a Sub Domain Class named "Employee".
Then I have  applied vertical inheritance for subclass to the Base class and used "Default mapping" for the Employee Sub class.
While querying both Base/Sub class I am getting error :

Error executing query: Telerik.OpenAccess.RT.sql.SQLException: Invalid object name 'Employee'.

These are the lines added to query from the context:
       using (EntitiesModel1 obj = new EntitiesModel1())
        {
            List<Employee> lstEmp = obj.Employees.ToList();
          GridView1.DataSource = lstEmp;
          GridView1.DataBind();
        }

Please help.

A: When you specify the Inheritance strategy to be 'Vertical' this implies that each class has it's own physical table. Hence you get the error that 'Employee' table is missing.
If you want to store instances of both Person and Employee in a single table 'Person', you need to use the default Inheritance strategy, which is 'Flat'.
In case you want to create the additional 'Employee' table then you can use the Schema Handler API and let OpenAccess generate the apporpriate ddl.
var context = new EntityDiagram();
var schemaHandler = context.GetSchemaHandler();
var ddl = schemaHandler.CreateUpdateDDLScript(null);
if(string.IsNullOrEmpty(ddl) == false)
   schemaHandler.ExecuteDDLScript(ddl);


text:
Q: kops - get wrong kubectl context I use kops create kubernetes cluster in aws.
I want to validate the cluster using this command:
kops validate cluster
The stdout give me: Using cluster from kubectl context: minikube
I think the problem is the wrong context, but why I kops does not create context for me?
This is my contexts:
kubectl config get-contexts
CURRENT   NAME       CLUSTER    AUTHINFO   NAMESPACE
*         minikube   minikube   minikube

there is no aws kubernetes cluster context.
How do I solve this?

A: Works like charm
kops export kubecfg --name=clustername.com

kops has set your kubectl context to k9s.finddeepak.com

A: kops helps you to create, destroy, upgrade and maintain production-grade, highly available Kubernetes clusters from the command line. AWS (Amazon Web Services) is currently officially supported, with GCE in beta support , and VMware vSphere in alpha, and other platforms planned.
Your actual configuration uses minikube config file from the previous installation. And it is fine. It's useful  to have a few
clusters in one config and switch between them.
The extended configuration will be saved into a ~/.kube/config file, you may try:
kops export kubeconfig  ${CLUSTER_NAME}


text:
Q: Calling a webservice from Java I am trying to develop a Java program that will simply call a webservice on a target URL.
Request method is POST, (GET not supported).
For this in my program I am using java.net.* library. I want to send an xml file in the post request. Whenever i run the client program it gives me following error:
java.io.IOException:server returned response code 500
Then when I check in the server logs there is following exception:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/targetdirectory] threw exception [Request processing failed; nested exception is org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
 - with linked exception:.....

On the server side I am using jaxb2marshaller, framework is spring 3.0 mvc.
All the other clients such as in php are able to invoke the same webservice using php cURL.

A: If JAXB is unable to unmarshal your XML, then either your XML is invalid (i.e. is not really XML), or it doesn't conform with the schema expected by the server. The answer is somewhere in the stack trace of the exception, which should mention why the unmarshaller didn't like your XML.

A: Not sure how you're making the POST, but you might find things simpler if you use the Apache HttpClient library.

A: Can you provide the whole exception? Without that, it's hard to know if it's an authentication problem, a marshalling problem, etc.
HttpClient def works, checkout Play's WS library as well:
http://www.playframework.org/documentation/api/1.1.1/play%2Flibs%2FWS.html

A: For "Calling a webservice from Java" we can issue simple GET or POST requests.
Below is the code for POST (as requirement is for post):
public static void MyPOSTRequest() throws IOException {
    final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" + "    \"id\": 101,\r\n"+ "    \"title\": \"Test Title\",\r\n" + "    \"body\": \"Test Body\"" + "\n}";
    System.out.println(POST_PARAMS);
    URL obj = new URL("https://jsonplaceholder.typicode.com/posts");
    HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("userId", "a1bcdefgh");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    OutputStream outputStream = postConnection.getOutputStream();
    outputStream.write(POST_PARAMS.getBytes());
    outputStream.flush();
    outputStream.close();
    int responseCode = postConnection.getResponseCode();
    System.out.println("POST Response Code :  " + responseCode);
    System.out.println("POST Response Message : " +
    postConnection.getResponseMessage());
    if (responseCode == HttpURLConnection.HTTP_CREATED) {
        BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString()); // print result
    } else {
        System.out.println("POST NOT WORKED");
    }
}

I have used "https://jsonplaceholder.typicode.com" to achieve this POST Request. Through this website we can perform both GET and POST and test our webservices.
Output will be :
    {
      "userId": 101,
     "id": 101,
     "title": "Test Title",
     "body": "Test Body"
     }
 POST Response Code : 201
 POST Response Message : Created
 {  "userId": 101,  "id": 101,  "title": "Test Title",  "body": "Test Body"}


text:
Q: My Built Jar File not Working outside netbeans - NetBeans IDE 16 When I need to run .jar java file after build it from netbeans , the file not opening !
but I am not sure if the problem from netbeans or java , because I have old jar files built with netbeans that used to work, but after updating java, they don't all work anymore!
I tried running the file indirectly via the .bat file: java -jar myapp.jar , but it didn't work either


text:
Q: Magento taxes are not working My Magento shop has the Dutch Tax settings, but I cannot get them to work. I have enabled all the right settings but it will not make any tax changes.
When I add a product to the cart it displays:

In the backend I give the product a 21% tax rate  with it, and the tax settings are as followed:

Has anybody any clue what i am doing wrong? I have been searching through scripts but didn't edit anything. Please help, cant launch now.
TAX RATES

A: You will also need to ensure the tax class for each product is set correctly.
In your individual products ensure that under General tab that Tax Class is set to Taxable Goods.
You can also do this in bulk by multiselecting all products that don't have Tax Class set correctly and then on the actions drop down select 'Update Attributes' and set as above.

A: I see your tax calculation is based on shipping origin. If I were to guess: your origin (it's a little below these settings in System Configuration Tax) is still on US. Change that to Netherlands (put * in the rest of the fields) and you should be golden.

A: Problem has been solved. I did not use Taxable goods as title of the attribuut. It changed when i made a tax class with names taxable goods and rate 21%!
How do you set a question to answered on here?


text:
Q: Android Studio Preview 4.1 Database inspector crashes app I am getting such notice

Error reading Sqlite database: Unable to perform an operation on
  database (id=3). The database may have already been closed.

when debugging my app in Android Studio emulator
if I fast change process of Database Inspector then app work ok on emulator otherwise it immediately is diconnected and crashes.

A: I got a simple solution which doesn't use the database inspector.
Remove it from the bottom menu. If you don't click on it, then Android Studio works properly. The problem comes after you open the "Database inspector" tab.
Removal process: Right-click on Database Inspector -> Remove from Sidebar.

A: I always have this issue with an Android 11 Emulator.
Google known this issue and published an update for them. To solve this update your emulator Android 11 images to revision 9, and all things works fine.
Steps to solving this issue:

*

*Open Preferences -> Appearance & Behavior -> System Settings -> Android SDK

*Open tab SDK Platforms

*Enable Show Package Details (right bottom corner)

*Expand Android 11.0 (R)

*Update all ... System Image options to minimum Revision 9

*Restart Emulator

Now your application should work with active database inspector.

A: Please see the official solution to fix this issue:
https://developer.android.com/studio/known-issues#ki-android-11-db-inspector


text:
Q: ValueError in TensorFlow 'categorical_crossentropy' I'm trying to make a submission to the Titanic problem on kaggle, using TensorFlow.
I used categorical_crossentropy in loss, and I got a error after using fit(). The error says that my target array should be binary matrices, but my target array is a Survived column from training data. This column has only 1s and 0s. What's wrong with it?
Here's my code:
import pandas as pd
import numpy as np
import tensorflow as tf

train_data = pd.read_csv('train.csv')
x_data = train_data[['Pclass', 'Sex', 'Age', 'SibSp',
       'Parch', 'Fare']]
x_data = pd.get_dummies(x_data)
y_data = train_data[['Survived']]

X = tf.keras.layers.Input(shape=[7])
Y = tf.keras.layers.Dense(1, activation = 'softmax')(X)
model = tf.keras.models.Model(X, Y)
model.compile(loss = 'categorical_crossentropy', metrics = ['accuracy'])

model.fit(x_data, y_data, epochs=10) # The error occurred in here.

And I got this error message:
You are passing a target array of shape (891, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

from keras.utils import to_categorical
y_binary = to_categorical(y_int)

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.

A: I got it. I used StandardScaler() from sklearn for my input data and solved my problem.
Keras from TF : loss is NaN and Failed to find data adapter that can handle input: <class 'pandas.core.frame.DataFrame'>, <class 'NoneType'>


text:
Q: Where is the tasks.json file in vscode? I just start to use vscode in linux. I know that the build configuration are set in tasks.json. But where does this file locate?
I tried Ctrl-Shift-P then
tasks, no commands matching.
build, no commands matching.
I also tried to find it in ~/.vscode folder, nothing here!
Is there a way to find / open this file?

A: *

*Open a folder with vscode

*Hit F1

*Select "Tasks: Configure Task"

*Hit Enter and vscode will create a sample tasks.json for you

A: You have to create it manually. Current version of VS Code only creates launch.json automatically. The auto detect claims made in docs also don't work (for me at least).
Here is a sample file you can create in .vscode/tasks.json that defines gulpjs tasks:
{
    "version":"0.1.0",
    "command": "./node_modules/.bin/gulp",
    "isShellCommand": true,
    "tasks":[
        {
            "taskName": "test",
            "isTestCommand": true,
            "problemMatcher": "$gulp-tsc",
            "showOutput": "always"
        }
    ]
}

A:
2019 Version

New tasks version 2.0.0
Here's how to do it step by step

I compiled this from the documentation:
First i tried ⬆ ⌘ B ... This didn't work for me (I was following a YouTube tutorial... a bit outdated it seems).
After looking at the documetation i found that you have to initialize your typescript folder. To do so:
tsc --init - this will generate a file called tsconfig.json
The documentation said to run code . after you ran tsc --init. Mine worked without is as well as with it. Feel free to play with it and see what it changes cause i honestly don't know.
After that, move your mouse up to the toolbar (global Terminal menu.)... underneath the Terminal tab, click on the Configure Default Build Task...
then click on tsc: build and that will generate your tasks.json
Note that mine generated without the "version": "2.0.0" line... so if yours did the same that means your hardware is too old and you have to upgrade.... i'm kidding! ... Just add "version": "2.0.0", right above "tasks": [, and then you should be fine.
✌

A: DANGER!  All of this has changed.  Current Microsoft docs on this topic are NOT consistent.  Note the version warning at the top of this:
https://code.visualstudio.com/docs/editor/tasks
Note the conflicts between this:
https://learn.microsoft.com/en-us/visualstudio/ide/customize-build-and-debug-tasks-in-visual-studio?view=vs-2017
and this:
https://code.visualstudio.com/docs/languages/cpp
I cannot get a straight answer on what works now (12MAR2019) to save my life, but I can tell you that none of the permutations I've tried, namely:
{., .vs, .vscode} / { tasks.json, tasks.vs.json}
are working for me.  It really drives me crazy that they changed this crap without updating ALL of the pertinent documentation, and the backward-compatibility "support" is just making things MUCH WORSE.

A: Add C# extension from Microsoft. Post that open any cs file. It will install C# dependencies.The you will get a pop up

Click yes. Both tasks.json and launch .json are created.


text:
Q: When to use Bayesian Networks over other machine learning approaches? I expect there may be no definitive answer to this question. But I have used a number of machine learning algorithms in the past and am trying to learn about Bayesian Networks. I would like to understand under what circumstance, or for what types of problems would you choose to use Bayesian Network over other approaches?

A: Bayesian Networks (BN's) are generative models. Assume you have a set of inputs, $X$, and output $Y$. BN's allow you to learn the joint distribution $P(X,Y)$, as opposed to let's say logistic regression or Support Vector Machine, which model the conditional distribution $P(Y|X)$.
Learning the joint probability distribution (generative model) of data is more difficult than learning the conditional probability (discriminative models). However, the former provides a more versatile model where you can run queries such as $P(X_1|Y)$ or $P(X_1|X_2=A, X_3=B)$, etc. With the discriminative model, your sole aim is to learn $P(Y|X)$.
BN's utilize DAG's to prescribe the joint distribution. Hence they are graphical models.
Advantages:

*

*When you have a lot of missing data, e.g. in medicine, BN's can be very effective since modeling the joint distribution (i.e. your assertion on how the data was generated) reduces your dependency in having a fully observed dataset.

*When you want to model a domain in a way that is visually transparent, and also aims to capture $\text{cause} \to \text{effect}$ relationships, BN's can be very powerful. Note that the causality assumption in BN's is open to debate though.

*Learning the joint distribution is a difficult task, modeling it for discrete variables (through the calculation of conditional probability tables, i.e. CPT's) is substantially easier than trying to do the same for continuous variables though. So BN's are practically more common with discrete variables.

*BN's not only allow observational inference (as all machine learning models allow) but also causal interventions. This is a commonly neglected and underappreciated advantage of BN's and is related to counterfactual reasoning.

A: In my experience, Bayesian Networks work very well when there is high dimensional categorical data. They give interpret-able models, which (sometimes) aid in making sense of how the different variables interact.


text:
Q: PostgreSQL query fails over PGNP provider for SQL Server This query is failing in SQL Server over the PGNP provider:
SELECT      1 AS x
FROM        pg_catalog.pg_attribute a
LEFT OUTER JOIN pg_catalog.pg_index i
        ON (i.indrelid = a.attrelid
            AND a.attnum = i.indkey[a.attnum-1])

This is the error message returned:
The OLE DB provider "PGNP" for linked server "XXX" indicates that either the object has no columns or the current user does not have permissions on that object.
If I run this query directly on the PostgreSQL server with pgAdmin, it returns results. Furthermore, if I remove the clause "a.attnum = i.indkey[a.attnum-1]", the query works over the PGNP provider. (I need this clause in my original query to identify which of a table's columns is the primary key.)
What is the issue, and how do I resolve it?
For the record, this is the complete query that I am executing, from which the query above was excerpted:
SELECT      c.relname as table_name, a.attname as column_name
        ,   t.typname as type_name
        ,   i.indisunique AS is_unique_key
        ,   i.indisprimary AS is_primary_key
        ,   CASE t.typname
            WHEN 'bpchar' THEN 'char('+CAST(atttypmod - 4 AS VARCHAR)+')'
            WHEN 'numeric' THEN 'numeric('+CAST((atttypmod - 4)/65536 AS VARCHAR)
                            +','+CAST((atttypmod - 4)%65536 AS VARCHAR)
                            +')'
            WHEN 'text' THEN 'varchar(max)'
            WHEN 'varchar' THEN 'varchar('+CASE atttypmod WHEN -1 THEN 'max' ELSE CAST(atttypmod-4 AS VARCHAR) END+')'
            ELSE t.typname
            END as type_name_1
        ,   CAST(CASE atttypmod WHEN -1 THEN NULL ELSE atttypmod - 4 END AS INT4) AS type_precision_scale
FROM        pg_catalog.pg_attribute a
    JOIN    pg_catalog.pg_class c on ( a.attrelid = c.oid)
    JOIN    pg_catalog.pg_namespace n on (c.relnamespace = n.oid)
    JOIN    pg_catalog.pg_type t on (a.atttypid = t.oid)
LEFT OUTER JOIN pg_catalog.pg_index i
        ON (c.oid = i.indrelid
            AND i.indrelid = a.attrelid
            AND a.attnum = i.indkey[a.attnum-1])
WHERE       c.relkind = 'r' and a.attnum > 0
     AND    n.nspname = 'public'


text:
Q: How to add textBox to Winform dataGridView cells I want to add textBox to my column cells by for loop...
My code:
DataTable dt = new DataTable();

DataColumn dc;
dc = new DataColumn("No");
dt.Columns.Add(dc);
dc = new DataColumn("Item");
dt.Columns.Add(dc);
dc = new DataColumn("Available Stock");
dt.Columns.Add(dc);
dc = new DataColumn("Quantity");
dt.Columns.Add(dc);
dc = new DataColumn("Price");
dt.Columns.Add(dc);

// Define  rows
for (int i = 0; i < count; i++)
{
    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][2].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][3].ToString();
    string price = dtr.Rows[i][4].ToString();

    dt.Rows.Add(no, item, A_qty,"[i want to add text box here] " ,price);
}

dataGridView1.DataSource = dt;

I want to add textBoxes to 4th column and I want access that one by one.

A: You can add textBox column to DataGridView instead and loop through DataGridView like
DataTable dt=new DataTable();

dt.Columns.Add("No",typeof(int));

dt.Columns.Add("Item",typeof(string));

dt.Columns.Add("quantity",typeof(int));

dt.Columns.Add("Price",typeof(decimal));

//Add row to the datatable

for (int i = 0; i < count; i++)
{

//Not Sure what dtr is you looping through

    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][1].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][2].ToString();
    string price = dtr.Rows[i][3].ToString();

    dt.Rows.Add(no, item, A_qty, price);
}

//Create New DataGridViewTextBoxColumn
DataGridViewTextBoxColumn textboxColumn=new DataGridViewTextBoxColumn();

//Bind DataGridView to Datasource
dataGridView1.datasource=dt;

//Add TextBoxColumn dynamically to DataGridView
 dataGridView1.Columns.Add(textboxColumn);

//Loop through DataGridView
 foreach (DataGridViewRow row in dataGridView1.Rows)

{

     //Do your task here
      string fourthColumn = row.Cells[4].Value.toString();

   }

A: Not sure. But hope this code will help you. Just add column of type textbox to your datatable.
DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);


text:
Q: XML validation failing in java with schemaLocation a local file I'm attempting to validate some XML against a relative XSD file in java
input file temp.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tagname:b
        xmlns:tagname="http://my_namespace.org/v1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://my_namespace.org/v1 ./local_xsd_file.xsd">
</tagname>

java source:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));

public static class RaiseOnErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void error(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
}

The local file local_xsd_file.xsd exists and appears to be not being read.
error message
java.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 85; schema_reference.4: Failed to read schema document './local_xsd_file.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.XX$RaiseOnErrorHandler.warning(DigitalFileWriterTest.java:1114)
    at org.apache.xerces.util.ErrorHandlerWrapper.warning(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaWarning(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    ... 50 more

I have also tried using file://local_xsd_file.xsd and file://./local_xsd_file.xsd (which should be possible) as the schemaLocation, all with the same results.  If I use an "absolute path" like file:///full/path/to/local_xsd_file.xsd then it works.  If I use a URL for the schema's location it reads them off that server and works fine.
Changing my current working directory to be one where a local_xsd_file.xsd exists will make it work, so apparently this works but only relative to your current working directory?
Is it possible to use a relative path with validation in java?  It feels like an implementation detail perhaps?

A: When you build a document like this:
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));

the base URI of the document is not known (because the builder only sees an InputStream, and has no way of finding out that this is reading a particular file). Try using one of the parse() methods from which a base URI can be established, e.g. parse(file.toString()) or saxParser.parse(file, (DefaultHandler) null);.
Without a base URI, there is no sensible way to resolve a relative URI. The system might use the current directory (which seems to be happening here) or it might report an error.

A: For followers, if you are validating with an external schema file, it also seems possible, just avoid changing it to string first, ex:
public static void verifyMatchesXsd(File xmlFileToTest, File schemaFile) throws IOException, SAXException {
    Source xmlFile = new StreamSource(xmlFileToTest);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    javax.xml.validation.Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}

or version without having to specify where external XSD is (it uses the internal):
  private void assertMatchesAnyXsdsMentioned(File xmlFileLocation) throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema();
    Validator validator = schema.newValidator();
    Source xmlSource = new StreamSource(xmlFileLocation);
    validator.validate(xmlSource);
  }

You maybe could also specify your own resource resolver and have it know which subdir you want, too...
Sax parser version:
  static void assertMatchesInternalXsd(File inputFile) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(true);
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    XMLReader reader = saxParser.getXMLReader();
    reader.setErrorHandler(new RaiseOnErrorHandler());
    saxParser.parse(inputFile, (DefaultHandler) null);
  }


text:
Q: Why are discrete random measures not dominated? A statement I've seen without proof in many books and papers is that random probability measures obtained by normalizing a completely random measure, such as the Dirichlet process, are not dominated by a common $\sigma$-finite measure and therefore the posterior can't be obtained using Bayes theorem. I can intuitively grasp why is that but don't know how to prove it.

A: elaborating on my comment, I think an example can be shown for basically every mixture model.
Suppose you have a Normalized Random Measure of the form
$$
  P(\cdot) = \sum_h w_h \delta_{\phi_h}(\cdot)
$$
with the usual condition that the weights sum to $1$ and that $\phi_h$ are i.i.d from a non-atomic distribution (non atomicity is important)
Now suppose that you observe a single datum $X_1 = x^*$, living in a Polish space $(\mathbb X, \mathcal X)$.
$$X_1 \mid P \sim P \quad P \sim \Pi$$
with $\Pi$ a measure on $\mathbb P_X$ the space of all probability measures on $(\mathbb X, \mathcal X)$.
Since the $\phi_h$s come from a diffuse measure, this entails that the set $A = \{\text{random measures that have an atom in $x^*$}\} \subset \mathbb P_X$ will have $0$ prior mass, i.e. $\Pi(A) = 0$.
On the other hand, we know that if $\Pi$ is for example a Dirichlet process,
$\Pi(A \mid X_1 = x^*) = 1$.
So that the prior does not dominate the posterior, thus Bayes' theorem does not hold and the model cannot be dominated.


text:
Q: Using MacVim and surround.vim - Backspace in Visual Mode surrounds text with "" I just remapped some keys in my .vimrc and I'm getting some wierd behavior.
When I select text in visual mode, and hit the delete key, it surrounds the highlighted text with ""...
Here's the relevant pieces of my .vimrc
"Using Vundle
Bundle 'tpope/vim-surround'

let mapleader= ","
let g:mapleader= ","

set backspace=eol,start,indent

"""""""""""""""""""""""""""""""""""""""""""""""""""
" => Surround Vim Shortcuts
"""""""""""""""""""""""""""""""""""""""""""""""""""
vmap ' S'
vmap " S"
vmap { S{
vmap } S}
vmap ( S(
vmap ) S)
vmap [ S[
vmap ] S]

" tags
vmap < S<
vmap > S>

" addressing the problem introduced by tags
vnoremap << <
vnoremap >> >

map <leader>s' ysiw'
map <leader>s" ysiw"
map <leader>s( ysiw)
map <leader>s[ ysiw]
map <leader>s{ ysiw}

map <leader>d' yss'
map <leader>d" yss"
map <leader>d( yss)
map <leader>d[ yss]
map <leader>d{ yss}

vmap <Leader>S <Plug>VSurround

Example:
  def persisted?
    false
  end

# I select it in visual mode, hit delete and it becomes:

  "def persisted?
  false
end"

I know a lot of this configuration is personal preference so any advice is welcome, but more importantly, why am I getting this behavior?

A: It's working for me so it's probably some kind of conflict. I'm still relatively new to Vim but I've had to sort out plugin and config conflicts several times by now. Plugins and user configurations all may affect each other so you might encounter really bizarre behaviour sometimes.
What's been working for me is to eliminate possible causes of the problem gradually. You might rename your vimrc file to prevent Vim from finding it, and then see if the problem persists. If it doesn't, something in your vimrc is not working well with your plugins. In that case, try commenting out lines of your vimrc to narrow down the cause of the problem (make sure to create a backup).
If the problem wasn't caused by your vimrc, it's likely a plugin conflict. Try moving away plugin files from the plugin folder in Vim plugin path and see if the problem persists.

A: When I try :verbose map <BS> I get
s  <BS>        * b<BS>
    Last set from ~/<...>/after/plugin/snipMate.vim
x  <BS>          "-d

This tells me that there is a Select-mode mapping that will enter a "b" (deleting the selected text and entering Insert mode) followed by an Insert-mode <BS>; the * means that the b<BS> will not be remapped; and this mapping is defined by snipMate.vim.  There is also a Visual-mode mapping to "-d.  Since there is no *, it will be remapped.
Something is broken:  I cannot figure out where that second mapping comes from.
Maybe if I have the second mapping, so do you.  If so, then the " gets mapped (defined in your vimrc file) to S", and I guess that surround.vim does something with that.  That more or less explains what you see.  I am not sure what mode vim is in after all that, so I am not sure what the -d at the end will do.
Try :xunmap <BS> or :xnoremap <BS> "-d and see if it helps.  If so, try putting it at the end of your vimrc file.  If that does not work, try putting it inside a VimEnter autocommand.
:help :map
:help map-modes

A: For the record I'm using the newest MacVim (Snapshot 72) and when I put in :verbose map <BS> the output is:

v <BS>  "-d

I did what @benjifisher suggested and added the line:
xnoremap <BS> "-d

to my .vimrc. The output now is
x  <BS>      *"-d
s  <BS>       "-d

and delete now works the way it should. So... Thanks!


text:
Q: Can AWS Glue catalog point to a data location in Azure ADLS? We are trying configure AWS Databricks Runtime to use the AWS Glue Data Catalog as its metastore. In this environment ,Azure ADLS is one of the source system.In that case,Can AWS Glue catalog point to a data location in Azure ADLS?

A: AWS glue catalog can speak JDBC, so if you can configure Azure ADLS to speak JDBC, which it seems like you can, you should be able to do this.
glue catalog documentation


text:
Q: Como delimitar as colunas de uma matriz no Julia Tenho uma matrix 4:3 e gostaria de pegar somente 2:3.
É possivel delimitar usando o comando DelimitedFiles?
Como devo usar?
Q = convert(Matrix, ACT[2:3]) #Gostaria de omitir o 2:3


text:
Q: Display an option to upload image before click on Product images We are Providing an option for customer to upload product image from frontend.
once we visit product page , we need to click on small image present below Product base image.

Than we need to click on Product image.

than only it will display an option to upload an image below Product Name.

Instead of this what we need is by default it should display an option to upload an image if value of Input Type under "custom options" is Custom Product Preview

initPreview: function()
    {
        var scale = this.option.calcScale(),
            elementId = this.config.previewContainer,
            container = $(elementId),
            c      = this.config,
            area   = c.area,
            thumb  = c.productImage.thumb;
        this.previewScale = scale;

        var areaParams = {
            width : Math.round(area.sizeX   * scale),
            height: Math.round(area.sizeY   * scale),
            left  : Math.round(area.offsetX * scale),
            top   : Math.round(area.offsetY * scale)
        };

        var html =
                '

' +
                ''+
                '

' +
                '

';
        container.update(html);

        this._showPreviewBlock( container );

        container.observe('click', this.onPreviewClick.bind(this));

        var title         = c.editorEnabled ? c.text.thumbTooltipEdit : c.text.thumbTooltipPreview,
            viewIconClass = c.editorEnabled ? '' : 'view-icon';
        container.select('.aitcg-overlay')[0]
            .observe('mouseover', function(){Aitcg.tooltip().update(title).show()})
            .observe('mouseout', function(){Aitcg.tooltip().hide()})
            .addClassName(viewIconClass);

        var styleParams = Aitcg.addPxToValue(areaParams);
        $$('#' + elementId + ' .aitraph').each( function(element) {
            element.setStyle(styleParams);
        });

        Aitoc_Common_Events.dispatch('aitcg_option_preview_create_after_' + this.id, {element: container});

        this.preview = new Aitcg_Editor(this.option);
        this.preview.init(container, Aitcg_Editor.MODE_PREVIEW, true, this.previewScale);
        this.preview.load( $('options_' + this.id).getValue() );

    },

A: jQuery( "#aitcg_image_container1" ).trigger( "click" ); made the trick.....
 initPreview: function()
        {
            var scale = this.option.calcScale(),
                elementId = this.config.previewContainer,
                container = $(elementId),
                c      = this.config,
                area   = c.area,
                thumb  = c.productImage.thumb;
            this.previewScale = scale;

            var areaParams = {
                width : Math.round(area.sizeX   * scale),
                height: Math.round(area.sizeY   * scale),
                left  : Math.round(area.offsetX * scale),
                top   : Math.round(area.offsetY * scale)
            };

            var html =
                    '

' +
                    ''+
                    '

' +
                    '

';
            container.update(html);

            this._showPreviewBlock( container );

            container.observe('click', this.onPreviewClick.bind(this));

            var title         = c.editorEnabled ? c.text.thumbTooltipEdit : c.text.thumbTooltipPreview,
                viewIconClass = c.editorEnabled ? '' : 'view-icon';
            container.select('.aitcg-overlay')[0]
                .observe('mouseover', function(){Aitcg.tooltip().update(title).show()})
                .observe('mouseout', function(){Aitcg.tooltip().hide()})
                .addClassName(viewIconClass);

            var styleParams = Aitcg.addPxToValue(areaParams);
            $$('#' + elementId + ' .aitraph').each( function(element) {
                element.setStyle(styleParams);
            });

            Aitoc_Common_Events.dispatch('aitcg_option_preview_create_after_' + this.id, {element: container});

            this.preview = new Aitcg_Editor(this.option);
            this.preview.init(container, Aitcg_Editor.MODE_PREVIEW, true, this.previewScale);
            this.preview.load( $('options_' + this.id).getValue() );
            // jQuery( "#aitcg_image_container1" ).trigger( "click" );
        },


text:
Q: Is there a list of Guild Wars 2 servers? I'm going to start downloading the game client, and before I pick up any server I want to know if there's a list of each server available so I can run CMD on Windows and and choose the one with less ping.
Thank you!

A: Compilation of Comments:
. Here is a List of All Servers - Posted by : @Gwen
. All servers are hosted in the same area, there's no "Geografic Factor" in this case that might affect your Ping  - @DavidYell
.  PvP Areas are hosted in different hosts than the worlds are, so your PvE/Questing Ping may be different than the sPVP/WvW one - @MarcelloLins
Extra Information:
Here is a Good Article that has some useful CMD Commands to determine server ping and latency time.
Once you find the IP's in use, you might want to Traceroute the way to the server in order to be able to check how many "stops" is your conection doing from point to point (Your pc - > Their Server)
You might also try your "Resource Monitor":
Go in game. Play.
Press ALT + TAB
Press WIN + R.

Enter resmon
You can see the ressource monitor. Go to the network tab, you can see GW2.exe in TCP connections. At the right of it, you have "latency". It's your latency ;p You can get the ip from ure server too.

I Hope it helps

A: You can find a list of all servers on the official wiki. This list is sorted by language, so be sure to choose one in the language that you're most comfortable with.
Keep in mind that all North American servers are located together, and all European servers are located together, so the only significant factors in response time are going to be NA vs EU and server population. Choosing a server with a lower population may give you a few milliseconds better ping, but won't have as many others to play with and may not fare as well in WvW.
WvW and sPvP matches are also hosted on arbitrary servers, so if you're looking to minimize your ping to gain an advantage in PvP, you're out of luck.


text:
Q: Maximum number of points in a CLR chart series I am just starting out in c++ and have found a CLR chart control through visual studio.
Project->Add New Item->User Control (Under UI)->Chart (Under Data)
I know in Excel these types of charts are limited to 32,000 points. I am wondering if I create my own native app am I still going to be restrcited by this limitation? Is this limitation enforced by Excel or the Chart itself?

A: Without knowing who makes the particular chart control you're asking about, no one can tell you what its limits are.  I don't think there's any Chart control that comes with Visual Studio, most likely you're seeing an ActiveX control installed by some other piece of software on your computer.


text:
Q: Can we customize or configure RPC or method call in place of endpoint(URL) for Netflix Ribbon or Spring Cloud Gateway? In my project requirement, We need to distribute the load between two different micro services but call of the two microservices are not based on the endpoint(URL) but it is calling via it's SDK-Client.
Can we customize either of Netflix ribbon or Spring Cloud Gateway to achieve it or is there any other solution for this?
For details please refer this attachment:-enter image description here
Any feedback are greatly appreciated, Thanks a lot in advance!!!


text:
Q: @Requestbody mapping to inherited subclass I have a class Vehicle in my Java Program.
The class Cab inherits from Vehicle.
In my controller I have a post mapping for adding new cabs to the Vehicles array.
@PostMapping("/vehicles/add/cab")
public void addCab(@RequestBody Cab cab) {
    System.out.println(cab);
    cc.addVehicle(cab);
}

The contractor of Cab looks like this.
public Cab(String licensePlate, double basePricePerKm, double horsePower)

I tried printing the Object in the RequestBody to the console, it had all the properties of the constructor
{
"licensePlate": "GR-221CH",
"basePricePerKm": 3.0,
"horsePower": 25.5
}

However I get an error

JSON parse error: Cannot construct instance of com.example.demo3.Cab.Cab

How do I do it right/resolve this error?

A: It sounds like your controller consumes application/json. So behind the scenes, by default Spring is attempting to use Jackson Databind to map fields into your Cab object. Databind has requirements for how the class is written to allow values to be bound to objects.
In the simplest case, you're writing a POJO:

*

*Add a public default (no-arg) constructor. You can still have additional constructors if they suit your purposes, e.g. test fixturing.

*Add public getters and setters.  (Jackson can also bind to a public field.)

By default, Jackson will find setters from Cab and its Vehicle superclass (and any other classes above that).  So if the three POJO properties you've listed really belong to Vehicle, they should get bound there, all without using your 3-arg constructor. Then you can add Cab-specific properties to Cab, also using property binding.
There are a bunch of annotations you can use to customize how values are bound, e.g. mapping differing JSON attribute names to your POJO properties, or ignoring certain properties.
See jackson-databind for details. There is even a way to map JSON values into a constructor, though I personally wouldn't use it -- yet another thing to maintain if the object model changes, especially when inheritance is a factor.
In the case that your body isn't JSON, Spring has several other HttpMessageConverter implementations, which of course are configurable.  See Spring's Rest Message Conversion docs.


text:
Q: Is the sum of an algebraic and transcendental complex number transcendental? I was wondering if the sum of an algebraic and transcendental complex number is transcendental.
I was thinking if a is algebraic, and b is transcendental, then if a+b is algebraic, then a+b-a is also algebraic since algebraic numbers are closed under additive inverses, but b is transcendental.
Is this a correct approach?

A: Your proof is right. The sum of an algebraic and transcendental number must be transcendental, since if not, the sum minus the algebraic number would be algebraic, and can not be transcendental.


text:
Q: Collection.find returns less results when fields: {field: 1} is applied I am trying to filter the data I send to the client.
characterFields = {
    _id: 1
    userId: 1
}

Meteor.publish 'nearbyCharacters', ->
    Characters.find({}, fields: {characterFields} )

However, when I include the fields: in the find method, it returns less results that if i do
Meteor.publish 'currentCharacter', ->
    Characters.find()

which returns the correct data, although not filtered

A: If you're trying to get it so it only displays the _id field, be sure to leave the first param empty since its used for the query (which i'm assuming is all records, right?):
Meteor.publish "currentCharacter", ->
  Characters.find {},
    fields: characterFields

A: Unfortunately I could not reproduce your issue.
I've created a bare meteor 0.9.0 project (with no autopublish) with the following js:
Characters = new Meteor.Collection("items")
if Meteor.isClient
  Meteor.subscribe "items", ->
    console.log Characters.find().fetch()
    return

if Meteor.isServer
  Meteor.publish "items", ->
    Characters.find {},
      fields:
        userId: 1

  unless Characters.find().fetch().length
    Characters.insert userId: 1
    Characters.insert userIdNaN: 1

On the clientside both entries are listed as expected:

Therefore I suppose your problem might reside somewhere else, maybe related with multiple publishes of same collection, or multiple subscribes to the same publish.


text:
Q: Warning: Expected server HTML to contain a matching text node for "Bearer..." Using NextJS: I am trying to get the bearer token on my login page component after login (fetch my login endpoint), which comes from the global context of my app (React Context API). It works but I get this error on the console. I assume this is due to the disconnection between the information on the server and on the client-side. Do you know how I can get rid of this error?
CONTEXT PROVIDER :

  const [token, setToken] = useState(typeof window !== "undefined" ? localStorage.token : "")

  const [loginCredentials, setLoginCredentials] = useState({
    email: "",
    password: "",
  });

  const login = async () => {
    const res = await fetch("http://localhost:3000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        user: {
          email: loginCredentials.email,
          password: loginCredentials.password,
        },
      }),
    });
    if (res.ok) {
      console.log(res.headers.get("Authorization"));
      localStorage.setItem("token", res.headers.get("Authorization"));
      return res.json();
    }
  };

LOGIN COMPONENT
const ctx = useAppContext(AppContext);
const { loginCredentials, setLoginCredentials, login, token } = ctx;

I am new to NextJS and web development in general. Thank you!


text:
Q: Connection to .sdf database from sub dir of site in ASP.NET Razor I have a small website that I am building using ASP.NET web pages Razor Syntax. It has an SQL CE 4 database in the App_Data folder. The connection and getting records from the database works fine in pages that are in the root directory and the /Account subdirectory. However when trying to get data from the database in pages that are in other subdirectories, connection to the database does not work. I get an error: Connection string "Database.sdf" was not found.
It is using the connection string from the Web.config file in the root directory:

When I tried copying the root Web.config to the subdirectory I get the following error:
The entry 'Database' has already been added. (C:\Users\Name\Documents\Visual Studio 2010\WebSites\SmallWebsite\subdir\web.config line 11).
At the moment I'm stumped and can't seem to find an answer either in msdn or google. Any help greatly appreciated.
Thanks
nl

A: Solved! Turns out all I needed to do was actually read the error message. In the root pages I was using code:
var db = Database.Open("Database"); to connect, and in subdirectories:
var db = Database.Open("Database.sdf");
Once I removed the .sdf everything worked fine!
Thanks,
nl


text:
Q: htaccess RewriteCond issue
What Is wrong with this format ?
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^5. [OR]
RewriteCond %{REMOTE_ADDR} ^23.27. [OR]
RewriteCond %{REMOTE_ADDR} ^221.232.
RewriteRule ^(.*)$ http://www.website/junk/ [R]

the idea as you can imagine, is to redirect users whos ip starts with 5. or 23.27.
or 221.232. to the website/junk/ folder, and i would need to add more ranges to this.the problem im having with the above is that it also redirects my own ip which starts with like 24.  telling me something is wrong with the format and probably not catching just the first set of numbers yes i realize I am after ranges,and not single ip addresses, but its how i want it.thanks

A: DOT is a special character in regex that needs to be escaped otherwise it matches any character
So ^5. may also match 5.3.2.1 OR 50.40.30.20
Use this code:
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^5\. [OR]
RewriteCond %{REMOTE_ADDR} ^23\.27\. [OR]
RewriteCond %{REMOTE_ADDR} ^221\.23\.
RewriteRule ^ http://www.website/junk/ [L,R]


text:
Q: Change x-axis interval on zoom - HighCharts This is how my date format from JSON file looks: http://jsfiddle.net/6roz4ya8/
I would like my chart to show only hour and minute on x-axis in normal view  (I can trim, just how to go about in highchart), whereas minutes and seconds when zoomed. I understand we could use tick positioner when  type="datetime". How do I do the same for 'categories: dateFromJsonFile'(i.e. if using date on x-axis from json file)
For eg: If '2022-07-15T13:57:54.4919219+03:00', I want 13:57 to be shown in general (unzoomed normal view) and 57:54 to be shown when zoomed
xAxis: {
    gridLineWidth: 1,
    //I need to set categories to timeData, as this timeData comes from Json
    // categories: timeData,
    type: "datetime",
    labels: {
      rotation: 270
    },
}

Below is how I want it to be. Shows one minute interval in normal view, 10 seconds interval on Zoom - https://jsfiddle.net/BlackLabel/7qj2cLea/

A: You can use formatter function for x-axis labels and return hours and minutes in case of not zoomed chart and minutes and seconds in case of zoomed.
const formatTime = time => time > 9 ? time : '0' + time;

Highcharts.chart('container', {
    ...,
    xAxis: {
        type: 'category',
        labels: {
            rotation: 270,
            formatter: function() {
                const date = new Date(this.value);

                if (this.chart.resetZoomButton) {
                    return formatTime(date.getMinutes()) + ':' + formatTime(date.getSeconds());
                }

                return formatTime(date.getHours()) + ':' + formatTime(date.getMinutes());
            }
        },
    }
});

Live demo: http://jsfiddle.net/BlackLabel/k7nywoad/
API Reference: https://api.highcharts.com/highcharts/xAxis.labels.formatter


text:
Q: processing animation in loop so its my first day using processing and i need a bit of help to start with this is my code, im doing the selection sort:
int[] numbers; // Declare array
int currentmin;
int exchange=0;
void setup() {
  frameRate(0.1);
  size(500,500);

numbers = new int[10]; // Create array with 10 cells
   background(105);
  for (int i = 0; i < numbers.length; i++) { // random numbers from 1 to 100
     int r = int(random(1,100));  // create  random numbers

  for (int j=0; j<numbers.length; j++) { //make sure not duplications
      if(numbers[j]==r)
        {r=r+1;}
  }
   numbers[i]=r; //fill array with random numbers
  println(r);
}
 fill(255,0,0);
for (int i = 0; i < numbers.length; i++) { //draw rectangles
  rect(i*40+10,400 ,35, -numbers[i]);

}
 for (int j=0; j < numbers.length; j++){ //set pivot number

     currentmin=numbers[j];
 for (int i=j+1; i < numbers.length; i++){  //find lowest number in array

   if (numbers[i] < currentmin) {
        currentmin = numbers[i];
    }
 }
  for ( int i=j; i<numbers.length;i++){ //swap pivot with lowest number
    if ( numbers[i]==currentmin){
    exchange=numbers[j];
    numbers[j]=numbers[i];
    numbers[i]=exchange;
  //here
    }
   }
 }

}

void draw() {

   background(105);
for (int z = 0; z < numbers.length; z++) {
  rect(z*40+10,400 ,35, -numbers[z]);

    }
}

as you can see where i have the comment here im trying to make the thing animated and to see the rectangles change place on each iteration in the first loop, but its not working... any help ? i tried calling draw(); hopelessly but it didnt work... anyway i can get a help ?

A: This isn't exactly a trivial animation to execute. You should really start with something simpler.
But to answer your question, you wouldn't put your animation inside a for loop. Instead, you need to make it so the draw() function draws a single frame of the animation. Processing automatically calls the draw() function 60 times per second, so by changing what's drawn each time, you create an animation.
Shameless self-promotion: I wrote a tutorial on creating animations in Processing available here.


text:
Q: Can't get usernames to show per object javascript
var likesperimage = photo.likes.data;
console.log(likesperimage);

displays

When I try var likesperimage = JSON.stringify(photo.likes.data); inside my real coding it outputs the objects in full, but I only need usernames for each object per image. I have tried using jQuery each but this does not do what I really need.
Each grouped line which has Object in it is data from an image. so there are multiple usernames per image. And what Id like to do is show all the usernames that are tied in with the main object.

A: Why jQuery.each doesn't work for you? Try the following code:
var likesperimage = photo.likes.data;
var userList = [];
$.each(likesperimage, function(index, user) {
    userList.push(user.username);
});
console.log(userList);

A: $.each(likesperimage, function(i, obj) {
    console.log(obj.username);
});

If you wanted a collection, you should be using $.map instead of $.each.
var names = $.map(likesperimage, function(obj, i) {
                                     return obj.username;
                                 });