text:
Q: How to persist java.lang.Object type field inside an embeddable class I have an entity like this :

@Entity(name = "A")
public class A implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String A_Id;

    private String field1;

    private String field2;

    @ElementCollection
    @CollectionTable(name = "B", joinColumns = @JoinColumn(name = "A_Id"))
    private Set<B> b;

    // getters and setters
}

@Embeddable
public class B implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;

    @Column(name = "VALUE", length = 255, columnDefinition = "TEXT")
    @Convert(converter = ObjectConverter.class)
    private Object value;

    // getters and setters
}

And the converter class looks like this :

@Converter(autoApply = true)
public class ObjectConverter implements AttributeConverter<Object, String> {

    private static String getType(Object obj) {
        if (obj instanceof Boolean) {
            return "b";
        } else if (obj instanceof Integer || obj instanceof Long) {
            return "i";
        } else if (obj instanceof Double || obj instanceof Float) {
            return "d";
        } else if (obj instanceof String) {
            return "s";
        }
    }

    public String convertToDatabaseColumn(Object anyType) {

        if (anyType == null) {
            return null;
        }

        return String.format("%s:%s", getTypeCode(anyType), anyType.toString());
    }

    public Object convertToEntityAttribute(String encoded) {

        if (encoded == null) {
            return null;
        }

        final String val = encoded.substring(2);

        switch (encoded.charAt(0)) {
            case 'b':
                return Boolean.parseBoolean(val);
            case 'i':
                return Long.parseLong(val);
            case 'd':
                return Double.parseDouble(val);
            case 's':
                return val;
            default:
                throw new IllegalArgumentException("Unexpected encoded string: " + encoded);
        }

    }

}

Now I am getting an exception from Hibernate like this :

org.hibernate.MappingException: collection element mapping has wrong number of columns: B type: component[name,value]

But if I dont keep the java.lang.Object field inside an embedded class, and keep it inside the main entity, then it is working fine.
For example this works fine :

@Entity(name = "A")
public class A implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String A_Id;

    private String field1;

    private String field2;

    @Column(name = "VALUE", length = 255, columnDefinition = "TEXT")
    @Convert(converter = ObjectConverter.class)
    private Object value;

    // getters and setters
}

How to keep the Object field inside the embeddable class and store it using Hibernate and JPA?


text:
Q: Operate on neighbor elements in RDD in Spark As I have a collection:
List(1, 3,-1, 0, 2, -4, 6)

It's easy to make it sorted as:
List(-4, -1, 0, 1, 2, 3, 6)

Then I can construct a new collection by compute 6 - 3, 3 - 2, 2 - 1, 1 - 0, and so on like this:
for(i <- 0 to list.length -2) yield {
    list(i + 1) - list(i)
}

and get a vector:
Vector(3, 1, 1, 1, 1, 3)

That is, I want to make the next element minus the current element.
But how to implement this in RDD on Spark?
I know for the collection:
List(-4, -1, 0, 1, 2, 3, 6)

There will be some partitions of the collection, each partition is ordered, can I do the similar operation on each partition and collect results on each partition together?

A: The most efficient solution is to use sliding method:
import org.apache.spark.mllib.rdd.RDDFunctions._

val rdd = sc.parallelize(Seq(1, 3,-1, 0, 2, -4, 6))
  .sortBy(identity)
  .sliding(2)
  .map{case Array(x, y) => y - x}

A: Suppose you have something like
val seq = sc.parallelize(List(1, 3, -1, 0, 2, -4, 6)).sortBy(identity)

Let's create first collection with index as key like Ton Torres suggested
val original = seq.zipWithIndex.map(_.swap)

Now we can build collection shifted by one element.
val shifted = original.map { case (idx, v) => (idx - 1, v) }.filter(_._1 >= 0)

Next we can calculate needed differences ordered by index descending
val diffs = original.join(shifted)
      .sortBy(_._1, ascending = false)
      .map { case (idx, (v1, v2)) => v2 - v1 }

So
 println(diffs.collect.toSeq)

shows
WrappedArray(3, 1, 1, 1, 1, 3)

Note that you can skip the sortBy step if reversing is not critical.
Also note that for local collection this could be computed much more simple like:
val elems = List(1, 3, -1, 0, 2, -4, 6).sorted

(elems.tail, elems).zipped.map(_ - _).reverse

But in case of RDD the zip method requires each collection should contain equal element count for each partition. So if you would implement tail like
val tail = seq.zipWithIndex().filter(_._2 > 0).map(_._1)

tail.zip(seq) would not work since both collection needs equal count of elements for each partition and we have one element for each partition that should travel to previous partition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent a bootstrap navbar from collapsing when window resizing I want my navbar to collapse on all pages except one where I want it to stay expanded at 1140px wide. How would I do this? here is a fiddle
Here is my navbar

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

      @Html.Partial("_LoginPartial")

A: The added CSS resets the navbar so it won't respond, you probably don't need all of that CSS but you can check the link below for more info.
Here's a link to the Bootstrap Docs for Non-Responsive CSS where you can pull out specifically what you may need.
Also, there seems to be a closing div tag missing from your navbar-header class in your jsfiddle.

/**FOR DEMO ONLY**/

@media (max-width: 767px) {
  .navbar-default #search-group {
    margin-top: 15px;
  }
}
/** THE ABOVE FOR DEMO ONLY**/

.navbar-default .container .navbar-header,
.navbar-default .container .navbar-collapse {
  margin-right: 0;
  margin-left: 0;
}
/* Always float the navbar header */

.navbar-default .navbar-header {
  float: left;
}
/* Undo the collapsing navbar */

.navbar-default .navbar-collapse {
  display: block !important;
  height: auto !important;
  padding-bottom: 0;
  overflow: visible !important;
  visibility: visible !important;
}
.navbar-default .navbar-toggle {
  display: none;
}
.navbar-default .navbar-collapse {
  border-top: 0;
}
.navbar-default .navbar-brand {
  margin-left: -15px;
}
/* Always apply the floated nav */

.navbar-default .navbar-nav {
  float: left;
  margin: 0;
}
.navbar-default .navbar-nav > li {
  float: left;
}
.navbar-default .navbar-nav > li > a {
  padding: 15px;
}
/* Redeclare since we override the float above */

.navbar-default .navbar-nav.navbar-right {
  float: right;
}
/* Undo custom dropdowns */

.navbar-default .navbar .navbar-nav .open .dropdown-menu {
  position: absolute;
  float: left;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, .15);
  border-width: 0 1px 1px;
  border-radius: 0 0 4px 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
  color: #333;
}
.navbar .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar .navbar-nav .open .dropdown-menu > li > a:focus,
.navbar .navbar-nav .open .dropdown-menu > .active > a,
.navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
  color: #fff !important;
  background-color: #428bca !important;
}
.navbar .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:focus {
  color: #999 !important;
  background-color: transparent !important;
}
/* Undo form expansion */

.navbar-default .navbar-form {
  float: left;
  width: auto;
  padding-top: 0;
  padding-bottom: 0;
  margin-right: 0;
  margin-left: 0;
  border: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
}
/* Copy-pasted from forms.less since we mixin the .form-inline styles. */

.navbar-default .navbar-form .form-group {
  display: inline-block;
  margin-bottom: 0;
  vertical-align: middle;
}
.navbar-default .navbar-form .form-control {
  display: inline-block;
  width: auto;
  vertical-align: middle;
}
.navbar-default .navbar-form .form-control-static {
  display: inline-block;
}
.navbar-default .navbar-form .input-group {
  display: inline-table;
  vertical-align: middle;
}
.navbar-default .navbar-form .input-group .input-group-addon,
.navbar-default .navbar-form .input-group .input-group-btn,
.navbar-default .navbar-form .input-group .form-control {
  width: auto;
}
.navbar-default .navbar-form .input-group > .form-control {
  width: 100%;
}
.navbar-default .navbar-form .control-label {
  margin-bottom: 0;
  vertical-align: middle;
}
.navbar-default .navbar-form .radio,
.navbar-default .navbar-form .checkbox {
  display: inline-block;
  margin-top: 0;
  margin-bottom: 0;
  vertical-align: middle;
}
.navbar-default .navbar-form .radio label,
.navbar-default .navbar-form .checkbox label {
  padding-left: 0;
}
.navbar-default .navbar-form .radio input[type="radio"],
.navbar-default .navbar-form .checkbox input[type="checkbox"] {
  position: relative;
  margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
  top: 0;
}

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

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

      </button>

          <input type="text" class="form-control" placeholder="Search" id="searchQuery" name="searchQuery">

About

Contact


text:
Q: Async/await: a correct way to make background task non-blocking
EDIT: from OP's comment, the goal is
  non-blocking background task so that the rest remain responsive

Say I have a function like this:
void OnFrameSampleAcquired(VideoCaptureSample sample)
{
    //Some code here

    //Here I want to introduce an Asynchrnous process
    ProcessAsynchronously(_latestImageBytes);

    //some more code here
}

In the point commented, I want to introduce a call to an asynchronous function.
Now, I can not modify OnFrameSampleAcquired (meaning I can not make it "async").
How can I do this?
I am thinking
async void ProcessAsynchronously(byte[] image)
{
    await Process1(image);
    await Process2(image);
    // ...
}

or async Task ProcessAsynchronously(byte[] image)
where ProcessX are also declared as async
Is this a good approach?
Thanks for any insight, since my practical experience with asynchronous processing is very few.

A: EDITED included all suggestions from the comments and added some background.
Background & insights
Converting one function to async won't be enough to make the whole process non-blocking. To achieve what you want, the whole processing path (call stack) should be converted to non-blocking. One blocking method on your call stack is enough to render the whole process blocking. Non-blocking does not necessarily mean async, as some of the examples below will show.
There are two steps involved in converting a method into async:

*

*Change the signature to return Task. This will allow your callers track status and outcome of your method.

*Add async keyword to the signature. This will allow await-ing other async methods in the body of your method.

CPU-bound vs IO-bound tasks
Note that even when you await for a method, it doesn't necessarily mean that you immediately release the thread back to your caller. The method being await-ed will release the thread back to you only as soon as it in turn begins await-ing for an IO-bound operation. Your thread will still block while the await-ed method performs CPU-bound operations before the first time it is await-ing for an IO-bound operation.
For example:
async Task MyAsyncMethod()
{
    Thread.Sleep(5000); // equivalent to CPU-bound operations
}

await MyAsyncMethod(); // will block for 5 seconds

On the other hand,
async Task MyAsyncMethod()
{
    await Task.Delay(5000); // equivalent to IO-bound operations
}

await MyAsyncMethod(); // will return immediately

And the workaround if you have CPU-bound tasks but still don't want to block the caller thread:
async Task MyAsyncMethod()
{
    await Task.Yield(); // this does the magic
    Thread.Sleep(5000); // equivalent to CPU-bound operations
}

await MyAsyncMethod(); // will return immediately thanks to Task.Yield()

What to do in your case
Since I'm not sure why you cannot change OnFrameSampleAcquired signature to async, I will suggest several different options.
Option 1
The simplest and the truly asynchronous approach would be this:
async Task OnFrameSampleAcquired(VideoCaptureSample sample)
{
    //Some code here

    //Here I want to introduce an Asynchrnous process
    await ProcessAsynchronously(_latestImageBytes);

    //some more code here -- provided it is either async or non-blocking!
}

async Task ProcessAsynchronously(byte[] image)
{
    await Process1(image);
    await Process2(image);
    // ...
}

If all of the methods on your processing path look like these, you have a properly implemented non-blocking background job.
Option 2
If you're absolutely unable to change the signature OnFrameSampleAcquired, there is a workaround. You can instead invoke the rest of the processing asynchronously, as suggested by @Fildor:
public void OnFrameSampleAcquired(VideoCaptureSample sample)
{
    //Some code here

    //Here I want to introduce an Asynchrnous process
    ProcessAsynchronously(_latestImageBytes).ContinueWith(task => {
        // this runs on a different thread after ProcessAsynchronously is completed
        // some more code here
    });

    // return without blocking
}

Here you win on both sides: first, you don't have to change the signature of OnFrameSampleAcquired; second, OnFrameSampleAcquired is now a non-blocking method.
Option 3
If you cannot change your signature because you must implement an interface like this:
public interface ISomeInterface
{
    void OnFrameSampleAcquired(VideoCaptureSample sample);
    // ... other members
}

then you can add the async keyword to your method and still comply with the interface:
async void OnFrameSampleAcquired(VideoCaptureSample sample)
{
    //Some code here

    //Here I want to introduce an Asynchrnous process
    await ProcessAsynchronously(_latestImageBytes);

    //some more code here
}

ISomeInterface x;                  // initialized elsewhere
x.OnFrameSampleAcquired(/*....*/); // the same as await, but no error handling

The drawback of this option is that the callers cannot track nor the status of the task (still running or completed?), neither its outcome (completed or threw exception?). You will probably have to wrap the entire body of OnFrameSampleAcquired in a try/catch, and write an exception to log.
Option 4
Technically, you can also invoke an async ProcessAsynchronously from a non-async OnFrameSampleAcquired using Wait on a Task, but it won't achieve your goal of having a non-blocking background task. The Wait() will block the thread until the async processing is done:
void OnFrameSampleAcquired(VideoCaptureSample sample)
{
    //Some code here

    //Here I want to introduce an Asynchrnous process
    ProcessAsynchronously(_latestImageBytes).Wait();

    //some more code here
}


text:
Q: How do you manage database connections and transactions across inserts in an Object Oriented way, using VB.net or C#? I'm to the point now in my programming development that I'm trying to take advantage of Object Oriented Design instead of the basic behind the button procedural stuff I have been doing.
In a current project I'm taking repeated, copy and paste sql server insert code and migrating it to classes with properties, methods, etc...
One issue I'm getting stuck at is how to keep connections to the database low, while doing inserts across multiple objects, and therefore multiple tables.
In a procedural way I've been using an ADO.net transaction to write to one table, then based on the inserted record's ID, write additional information to another table -- without closing the connection until the second job is done.  I use the transaction so if the later insert fails, the first insert can be undone, and using try, catch, finally to close the connection whether it succeeds or fails.
How do you handle this in the object oriented world?
EDIT: Thanks to everyone's answers.  I get it.  Here's another question that also helped to clarify it for me: ASP.NET/ADO.NET: Handling many database connections inside a .NET Object?

A: Hmm, not much different.
Your 'objects' (I presume you mean that you're using classes; and instances of those classes represent 'items' in your business domain), should not care about those Transactions.
That is, they should not know about transactions, and they should not be responsible for handling transactions.
Transactions should be initiated and handled by another object.  Some kind of 'Manager'.  This class starts, commits and rollbacks transactions.
You will use this manager in your Application, for instance, in your form.
To me, this is the only correct way of handling transactions, since your application knows the 'context'.  Your application knows how many roundtrips you'll have to do to the DB, the application knows how long the transaction should last.  Your objects do not know this.

A: As far as managing connections, don't.  .Net will keep a pool of them for you, and recycle them efficiently.  Trying to recycle them yourself will actually hurt performance.
Other than that, it sounds like you are doing it right, insert, get ID, insert again using same connection in that scope.


text:
Q: I have a react app and I was wondering -- do I render the navbar inside the index.js or the app.js Do I render the NavBar here or do I render it in the Index.js where the entire APP is being rendered?
I can not get the react router to work when I render it in the App.js. Once I add routing it makes the entire page disappear.
import Container from "react-bootstrap/Container";
import Button from "react-bootstrap/Button";
import Stack from "react-bootstrap/Stack";
import Total from "./components/Total";
import DailyBudget from "./components/DailyBudget";
import MonthlyIncome from "./components/MonthlyIncome";
import MonthlyBudget from "./components/MonthlyBudget";
import NavBar from "./components/NavBar";
import { BrowserRouter, Route, Router } from "react-router-dom";
import BasicExample from "./components/BasicExample";

function App() {
  return (

      <NavBar />
      <Container className="my-4">
        <Stack direction="horizontal" gap="2" className="mb-4">

Budget Breakdown

          <Button bg="dark" variant="dark">
            Add Budget
          </Button>
          <Button variant="outline-dark">Add Expense</Button>
          <Button variant="outline-dark">Add Income</Button>
        </Stack>

          <MonthlyIncome
            name="Monthly Income"
            amount={0}
            max={4200}
          ></MonthlyIncome>
          <DailyBudget name="Daily Budget" amount={50} max={250}></DailyBudget>
          <MonthlyBudget
            name="Monthly Budget"
            amount={1500}
            max={2500}
          ></MonthlyBudget>
          <Total name="Total" amount={1550} max={4200}></Total>

      </Container>

  );
}

export default App;


text:
Q: how to make a popup box using html code Ok I have not started to code my form yet I know how to build and what code I'm using
My question is,after the user has hit the submit button how can I make a pop up box appear that says for example your request has been submitted etc.etc...and they hit ok and it takes them back to the home page

A: HTML

Popup/Modal Windows without JavaScript

    Let me Pop up

Here i am

                ×

                    Thank to pop me out of that button, but now i'm done so you can close this window.

CSS
body {
  font-family: Arial, sans-serif;
  background: url(4.jpg);
  background-size: cover;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: orange;
  margin: 100px 0;
}

.box {
  width: 20%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid orange;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: orange;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: orange;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

https://jsfiddle.net/kzgjr6so/

A: The easiest way to add action events to a webpage is by using Javascript, a programming language not to be confused with Java. The code below does not take users back to the "home page", but it does show you the general layout of an .html file, and how to use a JavaScript function to make a confirm popup box. A good place to learn more about web design and coding in general is https://www.codecademy.com/.

<title></title>

Stackoverflow Answer

<button onclick="confirmBox();" class="Button"> Submit </button>


text:
Q: В чем подвох? Подсчитать количество просмотров баннера Дали тестовое задание по подсчету количества просмотров одного баннера, который включается на страницу как
<img src="image.php">

Насколько я понимаю, подвох в том как реализовать этот самый подсчет наименее затратно. У меня из идей memcache, mysql и файлы. При чем, я планирую реализовать это на mysql, но до сих пор в сомнениях. Может вы что-то подскажете? Возможно я просто все усложняю?


text:
Q: What are the functional differences in iLO 4 and iDRAC 7? What are the functional differences in iLO 4 and iDRAC 7? Mainly in the working, features and what we can do with them. Please give a formal difference between them. It would be really helpful if you can mention the uniqueness in each of them.

A: Here's the documentation for both:

*

*Dell iDrac 7: http://en.community.dell.com/techcenter/extras/m/white_papers/20065812.aspx

*HP iLO 4: http://h17007.www1.hp.com/us/en/enterprise/servers/management/ilo/index.aspx
Read both for a full comparison. It'd be rather counterproductive to copy both texts here completely.


text:
Q: javascript vs ruby image parse speed Is there a significant speed difference between using javascript as opposed to using ruby to parse image urls from a webpage?
For javascript I would look for all img tags and then send the data to the backend using ajax.
For ruby I would just use nokogiri.


text:
Q: How to use MVCMailer without breaking my service layer? I am looking into using MVcMailer to make nicer emails.
However one thing that I am unsure is how to organize the code. I currently have 2 projects. One for mvc and one for my repos and service layers.
my 2nd project has no knowledge of MVC and I would like to keep it that way.
I am thinking that my smtp code would go into a service layer or wrapper and then I would call it up from other service layers when I need to send emails out.
So where does the MVC mailer fit in? Do I generate the body in the controller then pass it to a serivce layer that passes it to my smtp class?

A: My solution was to build interfaces in the service layer that my services could then use to get a mail message, while the implementation that creates the message continues to reside in the web layer.
The interfaces are in the service layer:
public interface IMailMessage
{
    void Send();
    void SendAsync();
}

public interface IUserMailer
{
    IMailMessage Welcome(WelcomeMailModel model);
}

The implementations are then in the web (MVC) project:
public class MailMessage : MvcMailMessage, IMailMessage
{

}

public class UserMailer : MailerBase, IUserMailer
{
    public UserMailer()
    {
        MasterName = "_Layout";
    }

    public IMailMessage Welcome(WelcomeMailModel model)
    {
        var mailMessage = new MailMessage();
        mailMessage.SetRecipients(model.To);
        mailMessage.Subject = "Welcome";

        ViewData = new System.Web.Mvc.ViewDataDictionary(model);
        PopulateBody(mailMessage, "Welcome");

        return mailMessage;
    }
}

Finally in the service layer, the mailer interface is a dependency of the service:
public class UserCreationService : IUserCreationService
{
    private readonly IUserRepository _repository;
    private readonly IUserMailer _userMailer;

    public UserCreationService(IUserRepository repository, IUserMailer userMailer)
    {
        _repository = repository;
        _userMailer = userMailer;
    }

    public void CreateNewUser(string name, string email, string password)
    {
        // Create the user's account
        _repository.Add(new User { Name = name, Email = email, Password = password });
        _repository.SaveChanges();

        // Now send a welcome email to the user
        _userMailer.Welcome(new WelcomeMailModel { Name = name, To = email }).Send();
    }
}

When it's wired up in dependency injection, a Web.UserMailer object is used for the Services.IUserMail parameter to construct the UserCreationService object.
I've tried to keep the example simple so that it is easy to follow, but once you have a reference to an IMailMessage in the service layer, you can send it to your SMTP code instead of just calling Send() as I do. For your purposes, you may need to flesh out the IMailMessage interface more in order to access other parts of the MvcMailMessage class.

A: MVCMailer seems to already have support for sending email. If you setup the config correctly it should be able to email the populated MailerViews without additional implementation.
I am not sure of the role of your second project in you solution but here are two possibilities:

*

*Probably not practical ... Wait
for the version with "Email Sending
from a Background Process"

*Forget about Smtp from your second project
and using Http just call a View
which in turn would call MVCMailer


text:
Q: Managing relationship creation and deletion in a REST API We are building a REST API with the following resources: Users, UserGroups. Currently we are supporting the following URI's:
/BASEAPI/VERSION/Users/
/BASEAPI/VERSION/Users/{id}/UserGroups
/BASEAPI/VERSION/UserGroups/
/BASEAPI/VERSION/UserGroups/{id}/Users

I like this better than including references in the objects which then have to be pulled on subsequent requests. It also means that we can avoid query params to filter the results. i.e. we don't have to support:
/BASEAPI/VERSION/UserGroups/{id}?user_id={user_id}

The problem is that it doesn't make creation and deletion semantics very clear. i.e. should a DELETE request to:
/BASEAPI/VERSION/Users/{id}/UserGroups/{group_id}
remove the UserGroup, or remove the user from the user group?
We've considered adding:
/BASEAPI/VERSION/UserGroupUsers
But something doesn't quite feel right about that, but maybe it's the best way to go. What do others think are best practices?

A: You need to figure out how you intend to represent the membership relationship between user and user group. It can be an attribute of the user, an attribute of the group, or a separate resource. Those are the only choices. How users are added to and removed from groups falls out naturally from your choice. Membership management becomes a PUT/DELETE to the user, the group, or the membership resource.
Personally, I find the separate resource to be the cleanest way to handle the issue, but you then need query parameters to poll for a specific user or group. Also, you'd need to change your second-level resource names, because it makes no sense for /userGroups/{id}/users to return a collection of userGroupUsers resources.

A: A URL addresses a resource. A GET on this URL returns the resource and a DELETE deletes it. If the DELETE would delete something different than the GET is returning something really is broken.
So if /BASEAPI/VERSION/Users/4711/UserGroups would return the UserGroups with the ID 0815 and 0816 the DELETE should delete both userGroups.
Question is: Does this make sense? What is happening to the other users in both userGroups?
If you want to remove a user from a group I would provide a PATCH Method.


text:
Q: "I have managed to pull off only two topics." "I have managed to pull off only two topics."
Is this phrase correct? As manage and pull-off has the same meaning.

A: The two verbs do overlap.
To "pull something off" means to succeed in doing it; the phrase is often used in situations where the expectation was failure, not success, or where the task, when thought about, seems more daunting in retrospect than it did to begin with.
To "manage to do something" means to do it, perhaps accidentally, perhaps in a clumsy way, perhaps in a manner which could not be repeated again at will. The person who accomplished the thing has no mastery of it.


text:
Q: Regex to remove redundant multiplication/division involving zero or one? I have an odd problem where I am receiving computer generated equations (as a string) where multiplications/divisions with zero or one and lone zeros are occasionally present. These equations are to be presented to a user in string form.
I know that I can remove these redundant parts of the equation by implementing a kind of parser, but I was curious as to whether a regular expression could be used to remove them.
I came up with the following before I finally gave up on my (quite limited) regex skills:
/([^\+\-]*(?:0|0\*|\*0){1,}[^\+\-]*)|(?:1\*|\*1)/g

It seems to work only if:

*

*there are no non-zero numbers with a zero in them (ie. no 10's,20's,etc.)

*there are no negations.

It also doesn't work well with parentheses. Unfortunately parentheses are quite common.
Note that removing the redundant portions stated above may result in redundant parentheses or "zero" parentheses (ie it could turn out like ()*x, which is equivalent to 0*x). The redundant parentheses are not as much of an issue, but I assume the "zero" parentheses could be removed by a second pass similar to the first looking for (). If either of these could be done in the same regex as the one that solves the problem I would be extremely impressed.
So I turn to you regex gurus of Stack Overflow. Can it be done?
Assumptions
The following can be assumed true about the stringified equations:

*

*There are no divisions by zero, equations will not have any occurrence of [expr]/0or even expressions that evaluate to [expr]/0 such as [expr]/sin(0).

*The only operators within the equations themselves are + - * and /.

*Minus operator (-) includes both subtraction and negation, although negation is always surrounded by parentheses.

*Any operation other than the above (sin,cos, pow, etc.) will appear as a function call. (no ^ %, etc.)

Sample Equation
"(0+(0/0.5+(0+1*cos(p)+0*0+0*sin(p))*cos(k)+(0+1*0+0*1+0*0)*(-sin(k))+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*x+(0+(0+1*cos(p)+0*0+0*sin(p))*sin(k)+(0+1*0+0*1+0*0)*cos(k)+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*y+(0+(0+1*cos(p)+0*0+0*sin(p))*0+(0+1*0+0*1+0*0)*0+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*1)*z)"

Quite cluttered isn't it?

A: After leaving the comment I couldn't resist having a crack at it :)
You're biggest problem is nested parentheses. Regexes themselves are really bad at handling nested structures. This is a prime example of my mantra "Regular expressions are a tool, not a solution".
With regexes as your tool, you can apply kind of a "leaf-first" (or bottom-up) approach for this tree-structure, that's what I do in the first part while (sEq.match(...)) {...}. After that I can walk through the created array and do some simple text edits.
I've also added that 1*, *1 and /1 are deleted as they similarly don't affect the equation. You could probably expand this to make it smart enough to replace sin(0)/cos(0) with 0 and 1 respectively, then the solution would be even smaller in some cases.
(As mentioned in the comments of the code, this breaks if the equation contains stuff like 5.0*4 because JavaScript regexes don't have lookbehind so I'm trusting the \b word boundary to do that work for me. Simply adding logic that deletes unnecessary decimals would solve this though. Something like sEq = sEq.replace(/\.0+\b/g, ''); but I don't know if that's necessary for your use-case.) Edit: now fixed, 5.0*4 should remain in tact
This is not thoroughly tested though, feedback welcome.

var sEq = "(0+(0/0.5+(0+1*cos(p)+0*0+0*sin(p))*cos(k)+(0+1*0+0*1+0*0)*(-sin(k))+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*x+(0+(0+1*cos(p)+0*0+0*sin(p))*sin(k)+(0+1*0+0*1+0*0)*cos(k)+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*y+(0+(0+1*cos(p)+0*0+0*sin(p))*0+(0+1*0+0*1+0*0)*0+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*1)*z)";

var aParts = [];

document.getElementById('output').value = sEq + '\n';

while (sEq.match(/\([^()]*\)/)) {
  // while there are still "leafs", save them to aParts and replace with
  // a reference to their index in aParts, making their parent a new
  // "leaf" because it now doesn't contain the round brackets anymore
  sEq = sEq.replace(/([a-z]*)\(([^()]*)\)/gi, function(m, f, a) {
    var n = aParts.length;
    aParts[n] = {
      'found':m,
      'funct':f,
      'arith':a
    };
    return '[' + n + ']';
  });
}

for (var i = 0; i < aParts.length; i++) {

  // isolate divisions/multiplications
  var dms = aParts[i]['arith'].split(/(?=[+-])/);

  for (var j = 0; j < dms.length; j++) {
    // if the isolated part is multiplied by or divided into 0, replace with 0
    if (dms[j].match(/([^.]|^)\b0[*\/]|\*0(?!\.?0*[1-9])/)) {
      dms[j] = dms[j].replace(/([+-]?).*/, '$1'+'0');
    }
    // remove /1, *1 and 1*
    dms[j] = dms[j].replace(/[\/*]1\b(?!\.0*[1-9])(?:\.0*)?/g, '').replace(/([^.]|^)\b1\*/g, '$1');
  }

  // join back together, remove 0+, +0 and -0; 0- results in negation
  aParts[i]['arith'] = dms.join('').replace(/[+-]0(?!\.?0*[1-9])(?:\.?0*)?/g, '').replace(/([^.]|^)\b0(?:\+|(-))/g, '$1$2');

  // if after this the part contains just 0, perpetuate down to further eliminate
  if (aParts[i]['funct']=='' && aParts[i]['arith']=='0') {
    for (var j = i + 1; j < aParts.length; j++) {
      if (aParts[j]['arith'].indexOf('[' + i + ']') != -1) {
        aParts[j]['arith'] = aParts[j]['arith'].replace('[' + i + ']', '0');
        break;
      }
    }
  }
  // add back parts previously simplified by replacing [n] with the content of aParts[n]
  aParts[i]['arith'] = aParts[i]['arith'].replace(/\[(\d+)\]/g, function (m, n) {
    return aParts[parseInt(n)]['funct'] + '(' + aParts[parseInt(n)]['arith'] + ')';
  });

  // This is just to show the progress of the algorithm
  document.getElementById('parts').value += i + '\t' + aParts[i]['found'] + '\n';
  var tmp = [];
  for (var a = 0; a < aParts.length; a++) {
    tmp[a] = {
      'funct':aParts[a]['funct'],
      'arith':aParts[a]['arith'].replace(/\[(\d+)\]/g, function (m, n) {
        return tmp[parseInt(n)]['funct'] + '(' + tmp[parseInt(n)]['arith'] + ')';
      })
    };
  }
  // some steps didn't change after analysing, only append when significant
  if (document.getElementById('output').value.indexOf('\n' + tmp[tmp.length-1]['arith'] + '\n') ==-1)
    document.getElementById('output').value += tmp[tmp.length-1]['arith'] + '\n';
}

document.getElementById('solution').innerHTML =
  aParts[aParts.length-1]['funct'] +
  '(' + aParts[aParts.length-1]['arith'] + ')';

Parts isolated:

<textarea id="parts" rows="10" style="width:100%" wrap="off"></textarea>

Steps that simplified the equation:

<textarea id="output" rows="10" style="width:100%" wrap="off"></textarea>

Solution:

A: I ended up implementing a completely non-regex, recursive approach to the problem. The cleanupEqn() function essentially splits each string by operators (top level parentheses are grouped as a single operand), recursively operates on each sub part, then does another run through on the way back up the function call chain.
Comparing this with funkwurm's regex solution in jsperf shows it is significantly faster (at least in my personal chrome and firefox browsers).
It hasn't been thoroughly tested yet, and I'm sure there could be improvements made so I welcome any feedback.
Stealing funkwurm's snippet display to show my solution:

var sEq = "(0+(0/0.5+(0+1*cos(p)+0*0+0*sin(p))*cos(k)+(0+1*0+0*1+0*0)*(-sin(k))+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*x+(0+(0+1*cos(p)+0*0+0*sin(p))*sin(k)+(0+1*0+0*1+0*0)*cos(k)+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*0)*y+(0+(0+1*cos(p)+0*0+0*sin(p))*0+(0+1*0+0*1+0*0)*0+(0+1*(-sin(p))/0.5+0*0+0*cos(p))*1)*z)";

var operators = ['+','-','*','/'];
var level = 0;

var result = cleanupEqn(sEq);

document.getElementById('solution').innerHTML = result;

function cleanupEqn(eqn){
    var parts = removeRedundant(splitByParen(eqn));
    level++;
    document.getElementById('output').value += 'Level ' + level + ': Processing ' + eqn + '\n';
    for(var i=0; i < parts.length; i++){
        document.getElementById('parts').value += parts[i] + '\n';
        if(parts[i].charAt(0) === '('){
            // Clean up the expression inside the parentheses
            var tmp = cleanupEqn(parts[i].substring(1,parts[i].length-1));

            // If it was reduced to a zero, don't add the parentheses back
            if(tmp === '0'){
                parts[i] = '0';
            }
            else {
                parts[i] = '(' + tmp + ')';
            }
        }
    }
    // Finally, remove redundancies again, since some might have bubbled up.
    removeRedundant(parts);

    document.getElementById('output').value += 'Level ' + level + ': Completed ' + eqn + '\n' + JSON.stringify(parts, null, '\t') + '\n';
    level--;
    // Join it all into a string and return
    return parts.join('');
}

function splitByParen(str){
    var out = [];
    var exprStart = 0;
    var count = 0;
    var i;
    for (i = 0; i < str.length; i++) {
        var t = str.charAt(i);
        if(str.charAt(i) === '('){
            if(i > exprStart && count === 0){
                out.push(str.substring(exprStart, i));
                exprStart = i;
            }
            count++;
        }
        else if(str.charAt(i) === ')'){
            count--;
            if(count === 0){
                out.push(str.substring(exprStart, i+1));
                exprStart = i+1;
            }
        }
        else if(count === 0 && operators.indexOf(str.charAt(i)) > -1){
            if(i > exprStart){
                out.push(str.substring(exprStart, i));
            }
            out.push(str.charAt(i));
            exprStart = i+1;
        }
    }

    // Add the last part
    if(i > exprStart){
        out.push(str.substring(exprStart, i));
    }
    return out;
}

function removeRedundant(parts) {
    for(var i=0; i < parts.length; i++){
        if(parts[i] === '0'){
            if(i === 0){
                switch(parts[i+1]){
                    case '*':
                    case '/':
                        if(parts[i+1] === '*' || parts[i+1] === '/'){
                            parts.splice(i, 3, '0');
                        }
                        else {
                            parts.splice(i, 2);
                        }
                        i--;
                        break;
                    case '+':
                        parts.splice(i, 2);
                        i--;
                        break;
                    case '-':
                        parts.splice(i, 1);
                        i--;
                }
            }
            else {
                switch(parts[i-1]){
                    case '*':
                        if(parts[i+1] === '*' || parts[i+1] === '/'){
                            // Check if the prior portion is part of a function call
                            if(i > 2 && operators.indexOf(parts[i-3]) < 0){
                                // Check if the next portion is part of a function call (or undefined)
                                if(i+3 < parts.length && operators.indexOf(parts[i+3]) < 0){
                                    parts.splice(i-3, 6, '0');
                                    i -= 4;
                                }
                                else {
                                    parts.splice(i-3, 5, '0');
                                    i -= 4;
                                }
                            }
                            else {
                                parts.splice(i-2, 4, '0');
                                i -= 3;
                            }
                        }
                        else {
                            parts.splice(i-2, 3, '0');
                            i -= 3;
                        }
                        break;
                    case '+':
                    case '-':
                        if(parts[i+1] === '*' || parts[i+1] === '/'){
                            // Check if the next portion is part of a function call (or undefined)
                            if(i+3 < parts.length && operators.indexOf(parts[i+3]) < 0){
                                parts.splice(i, 4, '0');
                            }
                            else {
                                parts.splice(i, 3, '0');
                            }
                            i--;
                        }
                        else if(parts[i+1] === '+'){
                            parts.splice(i-1, 2);
                            i -= 2;
                        }
                        else {
                            parts.splice(i-1, 2);
                            i -= 2;
                        }
                }
            }
        }
        else if(parts[i] === '1'){
            if(i === 0){
                switch(parts[i+1]){
                    case '*':
                        parts.splice(i, 2);
                        i--;
                        break;
                    case '+':
                    case '-':
                        if(parts[i+1] === '*'){
                            parts.splice(i, 2);
                            i--;
                        }
                }
            }
            switch(parts[i-1]){
                case '*':
                case '/':
                    if(parts[i+1] !== '/'){
                        parts.splice(i-1, 2);
                        i -= 2;
                    }
                    break;
                case '+':
                case '-':
                    if(parts[i+1] === '*'){
                        parts.splice(i, 2);
                        i--;
                    }
            }
        }
    }
    return parts;
}

Parts isolated:

<textarea id="parts" rows="10" style="width:100%" wrap="off"></textarea>

Steps that simplified the equation:

<textarea id="output" rows="10" style="width:100%" wrap="off"></textarea>

Solution:


text:
Q: Can I use "leap" alone, meaning "leap of faith" This is a Merriam Webster definition for "leap":

: a choice made in an area of ultimate concern
a leap of faith

In the movie "The Batman" I saw someone say:

Are you sure this isn't a leap?

Edit:(some more context asked for in the comments)
The scene occurs after Batman received a cipher from a criminal who left it for him, and which, after solving it, reads "DRIVE". He takes commissioner Gordon with whom he works on this case, to a multilevel parking garage that belonged to a murdered victim, near which the cipher was found.They are entering the garage and looking at the cars when Gordon says to Batman:
Where to even start?
You sure this isn't a leap? "Drive" could mean anything.
is this just an ellipsis of the phrase "leap of faith" ?
Can I say "leap" meaning "leap of faith"?

A: It is hard to tell what the person meant without any context, but it seems as if that is what he or she meant.
Yes, you can omit "of faith" if the meaning is clear. However, you better make sure that there is no ambiguity, because otherwise people will be left scratching. (Their heads, I mean.)

Edit based on updated question: It now appears that Commissioner Gordon may mean "leap of faith". He and Batman are placing their faith in the idea that "drive" means "drive to the parking garage". However, he also might mean "leap of logic". Either interpretation would work in this context.


text:
Q: heart rate query returns empty set Trying to access my heartRate data from google fit using the History api.
The sign in and permissions are executed correctly.
But the query is the real issue here.
The Data point values always seem to return empty.
public void setFitnessOption() {
                fitnessOptions =
                        FitnessOptions.builder()
                                .addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
                                .addDataType(DataType.AGGREGATE_HEART_RATE_SUMMARY, FitnessOptions.ACCESS_READ)
                                .build();
              }

public void requestGoogleFitPermission() {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.BODY_SENSORS },
                        GOOGLE_FIT_PERMISSIONS_REQUEST_CODE);

                GoogleSignInAccount account = GoogleSignIn.getAccountForExtension(this, fitnessOptions);
                GoogleSignIn.requestPermissions(
                        this,
                        GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
                        account,
                        fitnessOptions);
              }

private Task<DataReadResponse> readHRHistoryData() {

                DataReadRequest readRequest = queryHRFitnessData();
                return Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
                        .readData(readRequest)
                        .addOnSuccessListener(
                                new OnSuccessListener<DataReadResponse>() {
                                    @Override
                                    public void onSuccess(DataReadResponse dataReadResponse) {
                                        Log.v(TAG, "Success" + dataReadResponse);
                                        printData(dataReadResponse);
                                    }
                                })
                        .addOnFailureListener(
                                new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Log.v(TAG, "Failture");
                                    }
                                });
            }

public static DataReadRequest queryHRFitnessData() {
                Calendar cal = Calendar.getInstance();
                Calendar cal1 = Calendar.getInstance();
                Date now = new Date();
                cal1.setTime(now);
                long endTime = cal1.getTimeInMillis();

                cal.add(Calendar.DATE, -1);
                long startTime = cal.getTimeInMillis();
                java.text.DateFormat dateFormat = DateFormat.getDateInstance();

                DataReadRequest readRequest =
                        new DataReadRequest.Builder()
                                .aggregate(DataType.TYPE_HEART_RATE_BPM, DataType.AGGREGATE_HEART_RATE_SUMMARY)
                                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                                .bucketByTime(1, TimeUnit.DAYS)
                                .build();

                return readRequest;
            }

public static void printData(DataReadResponse dataReadResult) {
                        Log.v(TAG, "Number of returned buckets of DataSets is: " + dataReadResult.getBuckets().size());
                        if (dataReadResult.getBuckets().size() > 0) {
                            for (Bucket bucket : dataReadResult.getBuckets()) {
                                List<DataSet> dataSets = bucket.getDataSets();
                                Log.v(TAG, "Datasets: " + dataSets);
                                for (DataSet dataSet : dataSets) {
                                    dumpDataSet(dataSet);
                                }
                            }
                        } else if (dataReadResult.getDataSets().size() > 0) {
                            System.out.print("Number of returned DataSets is: " + dataReadResult.getDataSets().size());
                            for (DataSet dataSet : dataReadResult.getDataSets()) {
                                dumpDataSet(dataSet);
                            }
                        }
                    }

private static void dumpDataSet(DataSet dataSet) {
                Log.v(TAG, "Name: " + dataSet.getDataType().getName());
                DateFormat dateFormat = DateFormat.getTimeInstance();
                Log.v(TAG, "Fields: " + dataSet.getDataSource().getDataType().getFields());

                Log.v(TAG, "Data Point Values :" + dataSet.getDataPoints());
                for (DataPoint dp : dataSet.getDataPoints()) {
                    Log.v(TAG, "Data Point:");
                    Log.v(TAG, "Type: " + dataSet.getDataType().getName());
                    Log.v(TAG, "Start: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
                    Log.v(TAG, "End: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
                    for (Field field : dp.getDataType().getFields()) {
                        Log.v(TAG, "Field: " + field.getName() + ", Value : " + dp.getValue(field).asFloat());
                    }
                }
            }

Log:
V/nativehealth: Successcom.google.android.gms.fitness.result.DataReadResponse@61ae9a7
    Number of returned buckets of DataSets is: 1
    Datasets: [DataSet{d:heart_rate.summary:gms:aggregated []}]
    Name: com.google.heart_rate.summary
V/nativehealth: Fields: [average(f), max(f), min(f)]
    Data Point Values :[]

I have maintained heart rate data on my google fit app. Yet my code returns empty set.
What am I missing out here??
Update:
I tried to insert data (HeartRate = 81) using HistoryClient and then I tried to read this data. It worked perfectly fine.
Log:
Datasets: [DataSet{d:heart_rate.summary:gms:aggregated [RawDataPoint{[81.0, 81.0, 81.0]@[1612494973714000000, 1612494973714000000](0,1)}]}]
    Name: com.google.heart_rate.summary
V/nativehealth: Fields: [average(f), max(f), min(f)]
    Data Point Values :[DataPoint{[81.0, 81.0, 81.0]@[1612494973714000000, 1612494973714000000,raw=0](d:heart_rate.summary:gms:aggregated r:heart_rate.bpm:com.nativehealth:)}]
    Data Point:
    Type: com.google.heart_rate.summary
V/nativehealth: Start: 11:16:13 AM
V/nativehealth: End: 11:16:13 AM
    Field: average, Value : 81.0
    Field: max, Value : 81.0
    Field: min, Value : 81.0

But I couldn't see this data in my google fit app!!! This entire process is so confusing. Anyone PLEASE HELP!


text:
Q: How to append to screen buffer file? If I have multiple log files open in several screens and I want to copy all useful traces to a single file, I initially copy them to the screen scrollback buffer file.
Doing ">" after selecting text will overwrite the buffer.  How do I append selected text to the buffer file?
This question concerns screen commands in Linux.

A: Basically you've got four related operators to redirect input/output:

*

*> will redirect your output and remove existing content (if possible). For example, this will overwrite existing contents of a file, but it won't clear the console contents:
command > mylog.log

*>> will append your output to existing content, which is most likely the behavior you're looking for:
command >> mylog.log

*< will read some source and treat it as input (stdin):
command < readfile.txt

*| will redirect output to the input of the following command:
command | othercommand


text:
Q: Match first few letters of a file name : Shell script I am trying to match first few letters of a file.
for entry in `ls`; do
    echo $entry
done

With the above code I get the name of all the files.
I have a few files with similar name at the start:
Beaglebone-v1
Beaglebone-v3
Beaglebone-v2

How can I compare $entry with Beaglebone* and then extract the latest version file name?

A: If you want to loop over all Beaglebone-* files:
for entry in Beaglebone-* ; do
    echo $entry
done

if you just need the file with the latest version, you can depend on the fact that ls sorts your names alphabetically, so you could just do:
LATEST_FILE_NAME=$(ls Beaglebone-* | tail -n 1)

which will just take the last one alphabetically.

A: To deal with larger numbers, you could use numeric comparison like this:
stem="Beaglebone-v"
for file in $stem*; do
    ver=${file#"$stem"}          # cut away stem to get version number
    (( ver > max )) && max=$ver  # conditionally assign `ver` to `max`
done
echo "$stem$max"

Testing it out:
bash-4.3$ ls Beaglebone-v*
Beaglebone-v1  Beaglebone-v10  Beaglebone-v2  Beaglebone-v3
bash-4.3$ stem="Beaglebone-v" &&
for file in $stem*
  do
    ver=${file#"$stem"}
    (( ver > max )) && max=$ver
  done; echo "$stem$max"
Beaglebone-v10

A: You can store the filenames matching the pattern in an array and then pick the last element of the array.
shopt -s nullglob
arr=( Beaglebone-* )
if (( ${#arr[@]} > 0 ))
then
    latest="${arr[ (( ${#arr[@]} - 1 )) ]}"
    echo "$latest"
fi

You need to enable nullglob so that if there are no files matching the pattern, you will get an empty array rather than the pattern itself.

A: If version numbers can go beyond single digits,
function version_numbers {
    typeset w; for w in $1-v*; do echo ${w#$1-v}; done
}

version_numbers "Beaglebone" | sort -n | tail -1

Or, adding function max:
# read a stream of numbers, from stdin (one per line)
# and return the largest value
function max
{
  typeset _max n
  read _max || return
  while read n; do
    ((_max < n)) && _max=$n
  done
  echo $_max
}

We can now do the whole thing without external commands:
version_numbers Beaglebone | max

Note that max will fail horribly if any one line fails the numerical comparison.


text:
Q: JQuery modal not showing the I need your help to help my jquery modal show the action result returned by my controller.
In my script, here is the code:

Action
 public ActionResult Details(int rf_id = 0)
    {
        var check = db.rms_approval_route_vw.Where(s => s.rf_id == rf_id).FirstOrDefault();

        if (check != null)
        {
            return PartialView(check);
        }
        else {
            ViewBag.message = "Waiting for regularization.";
        }

        return PartialView();
    }


text:
Q: Sending a request and response from a jsp to a servlet I am writing a validation servlet for a registration form. The form is in a .jsp file and has the following layout:

Register

            <form action="Register">

                    User name:

                    <input type="text" name="username" />
 First Name:

                    <input type="text" name="fist_name" />
 Last Name:

                    <input type="text" name="last_name" />
 Email Address:

                    <input type="text" name="email" />
 Password:

                    <input type="password" name="password" />
 Retype password:

                    <input type="password" name="password2" />
 <input
                        type="submit" value="Register" />

            </form>

The validation code should check that each field meets a set of constraints and write back to the jsp error messages if it doesn't.
ValidationServlet.java
protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // get request parameters for username and password
        String user = request.getParameter("username");
        String firstName = request.getParameter("first_name");
        String lastName = request.getParameter("last_name");
        String email = request.getParameter("email");
        String pwd = request.getParameter("password");
        String pwd2 = request.getParameter("password2");
        // Validate parameters and forward them to the ejb
        Map<String, String> messages = new HashMap<String, String>();

        if(user != null) {
            // Validate user name
            if(user.trim().isEmpty()) {
                messages.put("error", "Please enter username");
            } else if(!user.matches("^[a-zA-Z0-9]$")) {
                messages.put("error", "Invalid username.");
            } else if(user.length() > MAX_LEN){
                messages.put("error", "Invalid username");
            } else {
                // Username is valid
                messages.put("success", "good");
            }
        }
        if(firstName != null) {
            // Validate first name
            if(firstName.trim().isEmpty()) {
                messages.put("error", "Please enter your first name");
            } else if(!firstName.matches("^[a-zA-Z]$")) {
                messages.put("error", "Invalid name. Use alpha values only.");
            } else if(firstName.length() > MAX_LEN){
                messages.put("error", "Invalid name. Name should be at most " + MAX_LEN + " characters long");
            } else {
                // First name is valid
                messages.put("success", "good");
            }
        }
        if(lastName != null) {
            // Validate last name
            if(lastName.trim().isEmpty()) {
                messages.put("error", "Please enter your last name");
            } else if(!lastName.matches("^[a-zA-Z]$")) {
                messages.put("error", "Invalid name. Use alpha values only.");
            } else if(lastName.length() > MAX_LEN){
                messages.put("error", "Invalid name. Name should be at most " + MAX_LEN + " characters long");
            } else {
                // Last name is valid
                messages.put("success", "good");
            }
        }
        if (email != null) {
            // Email is specified as request parameter, do the business logic here.
            if (email.trim().isEmpty()) {
                messages.put("error", "Please enter email");
            } else if (!email.matches("([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)")) {
                messages.put("error", "Invalid email, please try again.");
            } else {
                // Email is valid
                messages.put("success", "good");
            }
        }
        if(pwd != null) {
            // Validate password
            if(pwd.trim().isEmpty()) {
                messages.put("error", "Please enter password");
            } else if(pwd.length() > MAX_LEN){
                messages.put("error", "Invalid password");
            } else {
                // Password is valid
                messages.put("success", "good");
            }
        }
        if(pwd2 != null) {
            // Validate password
            if(pwd2.trim().isEmpty()) {
                messages.put("error", "Please enter password");
            } else if(pwd2.length() > MAX_LEN){
                messages.put("error", "Invalid password");
            } else if(!pwd2.equals(pwd)) {
                messages.put("error", "Passwords do not match");
            } else {
                // Password is valid
                messages.put("success", "good");
            }
        }
        // Put messages in request scope so that it's accessible in EL by
        // ${messages}.
        request.setAttribute("messages", messages);

        // Forward request to JSP for display.
        request.getRequestDispatcher("login.jsp").forward(request,
                response);
    }

My questions is how can I access each message from the hash map and display them accordingly before the respective input field in the jsp?

A: You need to change the key for each input field
e.g. for error messages
messages.put("user", "Please enter username");  //for user
messages.put("firstName", "Please enter your first name");  //for first_name
.......
.......
.......

If you want to display success then you can set success in map otherwise do not.
To access message map on JSP
<form action="Register">

     User name:

       <input type="text" name="username" /><c:out value="${messages['user']}"/>

     First Name:

        <input type="text" name="fist_name" /><c:out value="${messages['firstName']}"/>

     .........
     .........
     .........

     <input type="submit" value="Register" />

</form>

See also

*

*EL info

A: To access messages map use the following code:
<c:set var="what" value="error"/>
error: <c:out value="${messages[what]}"/>


text:
Q: Kill ITunes Splash Screen After selecting "music" and listennig to an album, every time I wake my IPad3, there is a giant album-cover splash screen which remains until I unlock the IPad.  I really don't like that.  How do I convince the IPad to cease and desist with album-cover art when I'm waking it?
I don't mind looking at album-cover art, but only when I'm explicitly running the built-in music app.   Perhaps I just need to shut down the music app?  Is there a way to do this (to shut down an app)?

A: You can fully close an app double tapping HOME to get the recent apps list (note that unless you are at the home screen, the currently running app won't be listed) and then tap and holding on any App icon until you get the wiggles - at this point hit the minus sign against any app in your recent list.  This will either stop the app, if it is currently performing any background task, or remove the 'fast resume' saved state so that upon the next start it will not resume where it left off.


text:
Q: Solving homogeneous linear DE of n degree using Wronski determinant Here is my task:
Explain use of Wronski determinant on solving homogeneous linear DE of n degree:
$y^{(n)}=a_{n-1}(x)y^{(n-1)}+...+a_1(x)y'+a_0(x)y$
Any idea?

A: Suppose that $ y_1, y_2,..., y_n$ are $n$ solutions of the homogenous $n$th-order linear differential equation
$ y^{(n)} + a_{n-1}(x)y^{(n-1)}+ \space ... \space +a_1(x)y'+a_0(x)y = 0$
on an open interval $I$, where each $a_i(x)$ is continuous.
If Wronskian is
$ W = W(y_1, y_2,..., y_n) =
 \begin{vmatrix}
  y_{1} & y_{2} & \cdots & y_{n} \\
  y'_{1} & y'_{2} & \cdots & y'_{n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  y_{1}^{(n-1)} & y_{2}^{(n-1)} & \cdots & y_{n}^{(n-1)}
 \end{vmatrix} $
then there are two possible cases:
$\bullet \space \space y_1, y_2,..., y_n $ are linearly independent $\space \Longrightarrow \space W = 0$
$\bullet \space \space y_1, y_2,..., y_n$ are linearly dependent, $ \space \Longrightarrow \space W \neq 0 $
Thus either $ W = 0 $ everywhere on $I$, or $ W \neq 0 $ everywhere on $I$.


text:
Q: AngularJS Routing not loading view Total Angular newb here...
Just going through a Lynda course and I've got everything working until we get to routing. When all the app logic was in the controller things worked fine. But now for whatever reason my page loads completely blank now that I've added routing into the mix.
I've got an index.html file and I'm trying to pass in a view from list.html.
This is my folder structure so far.
Angular |
        |-angular.js
        |-angular-route.min.js
        |-index.html

        js |
           |-app.js
           |-controllers.js
           |-data.json

        partials |
                 |-list.html

The JS and Partials folders are both within the Angular folder.
This is my code so far...
Index
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Angular/Bootstrap Tests</title>
    <link rel="stylesheet" href="bootstrap4/css/bootstrap.css">
    <link rel="stylesheet" href="css/bands.css">

List

Band Directory

                    <input class="search-bar" ng-model="query" placeholder="Search for bands" type="text" autofocus>
                    Sort By:
                        <select ng-model="bandSort">
                            <option value="name" selected="selected">Name</option>
                            <option value="genre">Genre</option>
                            <option value="year">Year</option>
                        </select>

                        Ascending:
                        <input type="radio" ng-model="direction" name="direction" checked>

                        Descending:
                        <input type="radio" ng-model="direction" name="direction" value="reverse">

Recent Listens

{{item.album}}

{{item.name}}

Controllers
var bandControllers = angular.module('bandControllers', []);

bandControllers.controller('RecentBands', ['$scope','$http', function RecentBands($scope, $http) {
    $http.get('js/data1.json').then(function(bands) {
        $scope.bands =  bands.data;
        $scope.bandSort = 'name';
    });
}]);

App
var myApp = angular.module('myApp', [
    'ngRoute',
    'bandControllers'
]);

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/list', {
        templateUrl: 'partials/list.html',
        controller: 'RecentBands'
    }).
    otherwise({
        redriectTo:'/list'
    });
}]);

A: Try using $stateProvider
myApp.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/list");

    $stateProvider

    .state('list', {
        url: "/list",
        templateUrl: 'partials/list.html',
        controller:"RecentBands"
    })
});

The error is in your recentBands controller. Change the first line for
var app = angular.module('myApp');

There is no need of [] if you don't use any injections. It was just the name of the module, it has to be the same as the general controller.


text:
Q: How to code in a more functional style in Java? I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.
Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?

A: Many of the Gang of Four design patterns are considered to be implementing functional concepts in an object oriented language.
Functional design patterns is a useful read.  Also the series "Functional Thinking".  Both from IBM.
A presentation (I haven't watched this to verify) on Functional Design Patterns is summarized as

Aino Vonge Corry reviews a number of well known design patterns showing that their implementation is simpler in functional languages because such languages have pattern-based constructs.

Within Java, closures can be implemented as local classes within a method and make for the ability to expand much more into the functional programing realm.  Java 8 extends this functionality with lambdas.
So, to answer your question - many of the design patterns are implementing functional concepts already.  And they do make sense in Java.
If all else fails, one can always invoke Greenspun's tenth rule to get whatever functional pattern you are after.

A: Adding to what others have already said here, in Functional Programming there is a drive to separate side-effect producing / state changing code from functionally pure code and to make the separation explicit. This is achieved in e.g. Haskell through use of the IO and State Monads and in Clojure through refs.
In OOP state and state change are encapsulated in objects, so unless you go the immutable object route, this will likely be a bit more difficult to do.
Something that might help is to follow the Command/Query Separation Pinciple, which states that an operation should either be a command and cause side-effects, but not return anything, or it should be a query with a return value, causing no side-effects. Following this principle could help to get one into a more functional mindset, so far as managing side-effects is concerned.
EDIT
I don't know why this was initially down-voted; There's an article by John Carmack on Functional Programming in C++ which starts out similar what I've said above (sans the C/Q separation part) -- this is easily applicable to Java too.

A: A good start is Neal fords: functional thinking.
You should then explore libraries like:
Google guava , it's collections for essential abstractions like, function, predicate, map and filter operations.(google for functional programming with google collections, there are a couple of good blogposts)
There are couple of blogs about FP in java I read apocalisp.wordpress.com and I didn't regret it.
You may also explore functionaljava.org for more useful functional constructs like monoids.
Learning Haskell, Scala or Clojure is also a good idea but of course a bit more involved.
Good luck!

A: Functional programming has two primary qualities that define it - emphasis on immutable data and first-class functions. Both are - with some effort and within reason - achievable in Java.
You can certainly have immutable objects. Have the object state explicitly set through the constructor, do not expose setters and apply the final keyword to the fields. Whenever you would have a method modify the object's internal state, have it return a new instance with the updated state instead. An approach like this was presented in Real-World Functional Programming, a book containing examples of functional code in F# and corresponding code in C#. While C# is better suited for functional programming than Java, a similar approach could still be applied to Java.
When it comes to first-class functions, things get a bit more tricky. At the moment Java has a rather clumsy and verbose mechanism of emulating functions using anonymous nested classes, with a limited support for closures. While it's enough to write at least some pieces of code in a functional style, it would be a lackluster experience compared to using a proper functional language. There are Java libraries available, most notably guava, that introduce some of the functional programming concepts into Java, like immutable collections and some functional idioms. That would probably make the experience less gruesome - yet even the official documentation for guava states that functional idioms should only be used sparingly, as they often lead to code that is more verbose, less clear and less efficient than the corresponding imperative version.
The situation for Java is reportedly going to get better with the release of SE 8, set to include proper closures and lambda expressions, deferred from SE 7. Meanwhile you can try one of JVM's several functional languages and interop with Java when needed.

A: Java 8 will introduce Lambdas which will be a gentle (or not so gentle for some) start for developers to get into functional programming with Java.  Technically Java already has some functional programming capabilities, but they're very clumsy (anon inner classes).


text:
Q: Automate test flow changes if test response is x or y I have a test that passes if the response is x or y:
.assertThat().body("applicationStatusCode", oneOf("x", "y"))

but a third test needs to run if it's x, and cannot run if it is y
I have tried
@Test(dependsOnGroups = "XYtest")

but bc XYtest needs to pass even if value is y, it attempts to run the third test
i looked at Annotation Transformers and Beanshell but i don't think these accomplish what i want


text:
Q: ADO.NET TableAdapter parameters I have a query that I wish to run through an ASP.NET TableAdapter that contains an 'IN' clause which is to receive it's values through a parameter.
My question is, how do I specify this parameter? I thought of writing the conditional statement like this:
AND b.group_category_id in (@ParamList)

where the @ParamList is a String of the parameters, e.g. "4,12,45,23" but since the specified id is an Integer, it complains that it cannot convert String to Integer. This makes sense, but is there any way to specify such a list in a SQL statement in an ASP.NET TableAdapter?

A: You might have a look at http://dotnet.org.za/johanvw/archive/2008/06/13/mssql-split-function.aspx and pass it indeed as a string. Kind of a workaround than a solution. But that would only be usable if you use MSSQL.

A: One workaround I've seen:
WHERE charindex(',' + cast(b.group_category_id as varchar) + ',', @ParamList) > 0

In this case the @ParamList would be a string in the form ",4,12,45,23,"
It's not "pretty", but preserves the parameter and benefits of a compiled query. Since you are searching for numbers, the sub-string guarantees a unique match.

A: You could pass @ParamList through as a comma-delimited string, parse the string and insert the results into a #table, then use IN to search the #table:
AND b.group_category_id in (select group_category_id from #group_category_id_list)

Apart from this your options are limited, unless you want to use dynamic SQL (exec() statement), but I'd advise you to avoid that if possible.

A: Answering my own question with: it can't be done.


text:
Q: Google analytics with !IsPostBack We're using google analytics in our webforms site. I have the google analytics javascript loading in the head section of the masterpage like this...
    <%if (!IsPostBack)
  {%>
<script src="Content/google.js" type="text/javascript"></script>
<%} %>

my question is, will this affect the statistics on page visit duration? We are trying to analyse how long the users are on the page for.
before i did not use the !IsPostBack statement and we found that the page visits were increasing with every post back. so now we should get better data on actual page visits, but will this affect the visit duration stats?


text:
Q: R Summarize With DataTable data=data.frame("StudentID"=c(1,2,3,4,5),
                "Class"=c(1,2,2,3,3),
                "Type"=c('A','A','B','B','B'))

Say you have data as shown above and you wish for summaries like this,

What is the effective solution to do this and output to a csv in organized way such as shown above?

Example data if there is weights involved and you wanted weighted counts and porporitons.portions.
data1=data.frame("StudentID"=c(1,2,3,4,5),
                "Class"=c(1,2,2,3,3),
                "Type"=c('A','A','B','B','B'),
"Weighting"=c(10,6,13,12,2))

A: One option is map
library(dplyr)
library(purrr)
map_dfr(names(data)[2:3], ~
    data %>%
     select(.x) %>%
     group_by_at(.x) %>%
     summarise(COUNT = n()) %>%
     mutate(PROP = COUNT/sum(COUNT)))
# A tibble: 5 x 4
#  Class COUNT  PROP Type
#* <dbl> <int> <dbl> <fct>
#1     1     1   0.2 <NA>
#2     2     2   0.4 <NA>
#3     3     2   0.4 <NA>
#4    NA     2   0.4 A
#5    NA     3   0.6 B

Or with data.table by melting into 'long' format
library(data.table)
melt(setDT(data), id.var = 'StudentID')[, .(COUNT = .N),
  .(variable, value)][, PROP := COUNT/sum(COUNT),.(variable)][]

Or with base R using table and prop.table
 lapply(data[-1], function(x) {x1 <- table(x); x2 <- prop.table(x1); cbind(COUNT = x1, PROP = x2)})

A: Both summaries are simple, here I use dplyr. To combine them in the way you want, it's going to need to be slapped together in a somewhat inelegant way. You can remove the name col1 if you want
library(dplyr)

df1 <- data %>% group_by(Class) %>%
  summarise(Count = n(), Prop = n() / nrow(data))

df2 <- data %>% group_by(Type) %>%
  summarise(Count = n(), Prop = n() / nrow(data))

names(df1)[1] <- 'col1'
names(df2)[1] <- 'col1'

rbind(
  c('Class', '', ''),
  df1,
  c('Type', '', ''),
  df2
)

# A tibble: 7 x 3
  col1  Count Prop
  <chr> <chr> <chr>
1 Class ""    ""
2 1     1     0.2
3 2     2     0.4
4 3     2     0.4
5 Type  ""    ""
6 A     2     0.4
7 B     3     0.6


text:
Q: Asterisk dialplan: execute context This is my dialplan:
[default]
exten => 100,1,Background(beep)
exten => 100,n,Goto(test,1,1)
exten => 100,n,Background(beep)
exten => 100,n,Hunup()

[test]
exten => 1,1,Dial(SIP/0622423078@provider)

I want that the context default execute the context test. I gues that Goto is not the right function. So what I want is: you hear two times a beep and in the meantime it dials a phonenumber.

A: If you need on extension 1 go as described in context test you have do
[default]
exten => 100,1,Background(beep)
exten => 100,n,Goto(test,1,1)
exten => 100,n,Background(beep)
exten => 100,n,Hunup()

include =>test
[test]
exten => 1,1,Dial(SIP/0622423078@provider)

if you need on some other extension do extension 1 in context test, you can do something like this
[default]
exten => 100,1,Background(beep)
exten => 100,n,Goto(test,1,1)
exten => 100,n,Background(beep)
exten => 100,n,Hunup()

exten => 101,1,goto(test,1,1)

[test]
exten => 1,1,Dial(SIP/0622423078@provider)

Both will not realize task you described. That task is not doable this way.
You can play sound OR dial. You can't dial&play sound, except variant with Musiconhold
For musiconhold you can set music which have 2 beeps and ringing, and set that in dial command parameter.

A: I used the auto dial out.
    exten => 100,n,System(sh /root/test.sh 0622423078)

And this is the test.sh
    echo "Channel: SIP/provider/$1
    Context: fop
    Extension: 1
    " > /var/spool/asterisk/outgoing/test.call


text:
Q: All function calls are null? For some reason every time I go to call a function it is null, no matter the circumstances. It could be .set(), .set_text(), or even .connect()
I can't tell if this is the engine issue or what (I'm using the latest build...), but I can't seem to find this issue anywhere else. I don't know what to do to fix it.


text:
Q: react-bootstrap component documentation I'm looking for the documentation of react-bootstrap components. I see that on the react-boostrap site it is available the code to create the components, but what about how to use them, or the parameters they accept?
(for example, if I have a Tab, how can I intercept its onclick? or, does it have an onclick event?)

A: If you want to add an onClick event, in most cases you can just define it on the element:
<Button bsStyle="primary" onClick={alert("you clicked me")}>Default button</Button>

There is also documentation here, for how to intercept the tab onSelect event using the eventKey method.


text:
Q: StackExchange feedback: Shouldn't "3 kviews" be 3K views"?
Possible Duplicate:
100 thousand views or more: "thousand" comes below "views"
kviews should be k views?

I just noticed on StackExchange UX says 3 kviews (you can observe this by clicking "month" tab on the homepage)
I didn't catch this at first, and found myself focusing instead on the questions with hundreds of views (..."785 views" stands out more than "3 kviews")
Obviously this should be "3K views" instead of "3 kviews"
...What the hell is a kview anyway? A mistake.


text:
Q: enumerating all possible strings of length K from an alphabet in Python
Possible Duplicate:
is there any best way to generate all possible three letters keywords

how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C'] and K = 2, I'd like to enumerate all possible strings of length 2 that can be made up with the letters 'A', 'B', 'C'. They can be reused, so 'AA' is valid.
This is essentially permutations with replacement, as far as I understand. if theres a more correct technical term for this, please let me know.... its essentially all strings of length K that you can make by choosing ANY letter from the alphabet L, and possibly reusing letters, in a way that is sensitive to order (so AB is NOT identical to BA according to this.) is there a clearer way to state this?
in any case i believe the solution is:
[ ''.join(x) for x in product(L, repeat=K) ]

but i am interested in other answers to this, esp. naive approaches versus fast Pythonic ones, and discussions of speed considerations.

A: this is part of the Python Documentation
EDIT2: of course the right answer is the product, thanks for the comment
print  [''.join(x) for x in product('ABC', repeat=3)]

prints 27 elements
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB',
'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA',
'CBB', 'CBC', 'CCA', 'CCB', 'CCC']

@agf gave the right answer before

A: You can use itertools:
n = 3
itertools.product(*['abc']*n)

This gives you 27 elements as you expected.


text:
Q: What is the proper way of returning a new instance of an immutable? I would like to leave the two instances unchanged, and return a new one.
Currently I am doing it this way:
class myClass {

    public:

        myClass operator +(const myClass &obj) {

            myClass ret = *this;

            // some operation

            return ret;

        }

        // functions...

};

It works, but I am not sure, if it is the correct way

Edit
The operator + is just an example. I'm just curious, how the immutable functions/methods should be written in C++

A: If myClass is supposed to be immutable under addition, you probably want to make operator+ a free function rather than a class member.  (You might have to make it a friend function.)
myClass operator+(const myClass &lhs, const myClass &rhs) {
  return myClass( /* some operation */ );
}

Note that both operands are taken by const reference, so you know you cannot accidentally change them (maintaining the immutability property).  You're returning a new instance of myClass, which is now immutable.  You construct and return the result in one step, because, if myClass really is immutable, you might not be able to default construct one and then set its value.
Here's a stupid example:
class myClass {
  public:
    explicit myClass(int x) : m_x(x) {}
    friend myClass operator+(const myClass &lhs, const myClass &rhs);
  private:
    int m_x;
};

myClass operator+(const myClass &lhs, const myClass &rhs) {
  return myClass(lhs.m_x + rhs.m_x);
}

If you really want to implement it as a class method, the method should be marked const to ensure the implementation doesn't accidentally mutate the left-hand instance.
Binary arithmetic operators (like operator+) are often defined in terms of the arithmetic self-assignment operators (like operator+=), which are obviously not immutable.  If we add this method to myClass:
myClass &operator+=(const myClass &rhs) {
  m_x += rhs.m_x;
  return *this;
}

Then the common idiom for defining operator+ would be:
myClass operator+(const myClass &lhs, const myClass &rhs) {
  myClass result = lhs;
  result += rhs;
  return result;
}

Now the implementation of operator+ doesn't require any of the private members of the class, so it no longer needs to be declared as a friend function.


text:
Q: 13 errors for one line (***) What am i doing wrong? /**
  * getLargestOfFive method
  * input parameters: int values num1, num2, num3, num4, num5
  * return value    : largest value among 5 input parameters
  */

import java.util.Scanner;

public class LargestOfFive2{

  public static void main(String[] args){

    ***public static int getLargestOfFive(int num1, int num2, int num3, int num4, int num5, int largest){***

      largest = num1;

      if (num2 > largest){
        largest = num2;
      }
      if (num3 > largest){
        largest = num3;
      }
      if (num4 > largest){
        largest = num4;
      }
      if (num5 > largest){
        largest = num5;

      }

      return largest;

    }

  }

}

A: public static void main(String[] args){
 public static int getLargestOfFive(int agumentsHere){ // method inside method?
 }
}

You can't have nested methods in Java. Re arrange your code.
public static void main(String[] args){
  // call your method from main
  // eg
   int val=getLargestOfFive(arguments);
}
public static int getLargestOfFive(int agumentsHere){
}

Read the Java doc about methods in Java.

A: The main reason you're getting so many errors is most likely that you've put a method inside a method. You can't include getLargestOfFive in your main() method - there's no such thing as nested methods in Java. Rather, separate your methods like so:
public static void main(String[] args)
{

}

public static int getLargestOfFive(int num1, int num2, int num3, int num4 ...)
{

}

Note also that you're doing some strange stuff in terms of assigning variables. There's no point in passing largest to your method. Rather, define and assign it at the beginning of your function like so:
public static int getLargestOfFive(...)
{
    int largest = num1;
}

There's no reason to require users to pass a useless variable into your function.
Lastly, the way you're implementing this function is pretty single-purpose. If you wanted, you could pass an iterable to the function, and iterate through it within the method, and you'd be able to ascertain the largest value of any number of values. As it stands, this works if and only if the user has five values they want to check.


text:
Q: Translated Oracle ApEx app returning incorrect month abbreviation We have an ApEx data entry site that is translated into both Mexican Spanish and Canadian French. One of the critical columns on most data tables is the date associated with the data. As such, there are date picker fields for each time this value is needed.
The translations automatically display the month code based on the current language (a date picked in January on the Spanish site will display 'Ene' for enero). Before the date is recorded to the DB, the application format mask 'DD-MON-RR' is applied; this understands the current language and records the value on the DB in English.
The issue is that the month of December (diciembre) is showing the abbreviation of 'Dec' rather than 'Dic'. As a result, error ORA-01843 (not a valid month) is generated and the data is not saved. However, if the entry is manually changed to ##-Dic-##, the value is recorded correctly without error.
This makes it appear that the automatically-generated month abbreviation for this language is incorrect. Is this a known error with a solution?

A: I don't know anything about globalization, my Apex applications are in Croatian only. However, as a workaround, perhaps you could switch to another date format mask, such as DD.MM.YYYY; doing so, you wouldn't depend on language differences.


text:
Q: Is there a more detailed/up-to-date reference for parameters to Wordpress plugin API? I had tried to use the example code here to fetch a long list of plugins, with only certain fields. However, the filter doesn't work as expected. According to documentation:

"fields – an array with possible fields (listed below) as keys and
  true or false value to return data for that field or not. The fields
  that are included make up the properties of the returned object above.
  The possible fields are (default set to true, unless otherwise
  stated):"

The listed fields don't seem to work, with array values set, un-set, true, or false. It appears the API may have changed, without updated documentation? Is there any more detailed documentation, preferably one that shows how to query for multiple slugs/names/etc.?

A: The API is a bit limited, but there's one useful feature I noticed:
http://api.wordpress.org/plugins/info/1.0/nextgen-gallery will give php-variable of the data about nextgen gallery. Similarly, http://api.wordpress.org/plugins/info/1.0/nextgen-gallery.json gives it in JSON format, and http://api.wordpress.org/plugins/info/1.0/nextgen-gallery.xml gives xml format.


text:
Q: Proving a few things about $ L^{p} $-spaces I am new to $ L^{p} $-spaces and am trying to prove a few things about them. Therefore, I would like to ask you whether I have gotten the following right.

*

*Prove that $ {L^{\infty}}(I) \subseteq {L^{p}}(I) $ for all $ p \in (0,\infty) $, where $ I = [a,b] $ is a closed bounded interval, by showing that
$$
\text{$ \forall $ measurable functions $ f $ defined on $ [a,b] $}: \quad
\| f \|_{L^{p}} \le (b - a)^{\frac{1}{p}} \| f \|_{L^{\infty}}.
$$
My idea was to invoke the fact that
$$
                         \| f \|_{L^{p}}
\stackrel{\text{def}}{=} \left( \int_{I} |f|^{p} \, d{\mu} \right)^{\frac{1}{p}}
\le                      \| f \|_{\infty} \left( \int_{I} 1 \, d{\mu} \right)^{\frac{1}{p}}
$$
for all measurable functions $ f $ defined on $ [a,b] $. Is this correct?

*Prove that $ \displaystyle {L^{\infty}}(I) \subsetneq \bigcap_{p \in (0,\infty)} {L^{p}}(I) $. Inclusion is clear from (1), and a function that illustrates why the inclusion is strict is $ f(x) \stackrel{\text{def}}{=} \dfrac{1}{x^{x}} $ on the interval $ [0,1] $ (its $ L^{p} $-norm exists for each $ p \le \infty $, but it is not bounded).

*Prove that $ {L^{p}}(\mathbb{R}) $ is not a subset of $ {L^{\infty}}(\mathbb{R}) $ and vice-versa. Take the function $ f(x) \stackrel{\text{def}}{\equiv} 3 $. It is not integrable over $ \mathbb{R} $, but it is bounded. For the reverse implication, take the function
\begin{equation}
f(x) \stackrel{\text{def}}{=} \left\{
\begin{array}{ll}
\frac{1}{\sqrt{x}} & \text{if $ 0 \le x \le 1 $}; \\
0                  & \text{if $ x \in (- \infty,0) \cup (1,\infty) $}.
\end{array} \right.
\end{equation}
It is integrable over $ \mathbb{R} $, but it is not bounded.
Maybe I have made some mistakes here or maybe I am missing something, so I appreciate any kind of help!!!
P.S.: I have just noticed that my example $ \dfrac{1}{x^{x}} $ does not work, since this function is actually bounded on $ [0,1] $.

A: Number 1 is correct, and so is 3.
Can you justify why the function you wrote in #2 works using a calculation?


text:
Q: Images under WebContent folder displayed as document Spring Directory Structure :Check the image under WebContent

As depicted in the image the file ".jpg" is displayed as document. Is there any way how i could resolve it.

A: You need to change System Default Editor to External Editors
Have a look at THIS

The external program will be used as the default editor if that program is registered as the system default editor for that file type and no other editor is registered for that file type in the Workbench. For example, on most systems the default editor for JPEG files is an application for editing or viewing image files. If there is no other editor associated with .jpg or .jpeg files in the Workbench, then opening a JPEG file from the Workbench would cause the file to be opened externally, in the system default editor.


text:
Q: AzureRmRoleAssignment Access denied to the specified API version I'm getting an error running New-AzureRmRoleAssignment. I want to give an AD group access to a resource group. The script actually works-- the group gets contributor access to the resource group. It just says that it's failing with the message "Access denied to the specified API version".
My script (params not included) is here:
# Import the Task.Common dll that has all the cmdlets we need for Build
import-module Microsoft.TeamFoundation.DistributedTask.Task.Common
import-module Microsoft.TeamFoundation.DistributedTask.Task.Internal
Import-Module "Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Internal"
Import-Module "Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Azure"

Write-Output "Connecting to Azure"
Initialize-AzurePowershellSupport -ConnectedServiceName $ConnectedServiceName -ErrorAction SilentlyContinue
$subscription = (Get-AzureRmContext).Subscription.SubscriptionName #(Get-AzureRmContext).Subscription.SubscriptionName

New-AzureRmRoleAssignment -ObjectId $objID -RoleDefinitionName $roleName -ResourceGroupName $environment-$featureName

How can I fix the error? The script does what it's supposed to, but the build "fails".

A: According to the error log, do you login Azure by using  service principal. If yes, it is a know issue. Please check the issue on GitHub. The issue is solved on the latest version Azure Power Shell(4.1.0 or later).
You could use the following cmdlet to check your Azure PowerShell version.
Get-Module -ListAvailable -Name Azure -Refresh

The latest version is 4.3.1, you could download it from the link.
If you build the script on VSTS, please use Hosted 2017 build agent, it uses the latest version PowerShell. Please refer to this answer.


text:
Q: App crash while downloading large images using SDWebImage I'm using SDWebImage to download image async from server.Some images on server are of size( 1772x1476 pixels.)I'm showing these images on UICollectionView. I'm getting memory warning and app crashes after several run.Some times it happens when images downloaded first time and some time when i scroll the collection view up and down. Here is my code-
i am getting warning on my x code like below image
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

[Mainimage sd_setImageWithURL:[NSURL URLWithString: Obj.imageYH] placeholderImage:[UIImage imageNamed:@""]];

   return cell;
}

A: You can use :
[SDImageCache sharedImageCache].config.shouldDecompressImages = NO;
[[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];
In version 4.0-beta

A: If your app doesn't need to show a full sized image, then it's always a good practice to scale it down and then show. Here's an example of what to do.
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:url delegate:self options:0 success:^(UIImage *image)
{
    //Scale down the image here and then set to your view.
}

It should help you reduce the memory issues.

A: - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

            UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    [Mainimage setImageWithURL:[NSURL URLWithString: Obj.imageYH] placeholderImage:[UIImage imageNamed:@""]];

           return cell;
}

Try this


text:
Q: Web API POST Request returns 500 Error, GET Request returns 200 OK on Azure I created a web API which runs perfectly on localhost.
After publishing it to Azure
POST Request returns 500 Internal Server Error
GET Request returns 200 OK
Is there something else required to do in Azure in order to make POST requests accessible and ready to be tested in Postman?

A: @W.Gates provided a link that helped me solve my issue
I added the following line to the Program.cs file
app.UseDeveloperExceptionPage();
I sent the POST Request and saw that the JSON I provided had an error.
After correcting the JSON format, I could successfully send POST Requests.
So by adding that line of code I knew immediately where the error was.


text:
Q: How to prevent css selector from access into iframe I have an iframe.
I want to prevent access from the parent document into the iframe from css selectors and other manipulation.
How can I secure it?

A: You could kill a goat under the light of a full moon inside a pentagram made of salt. If you did that, css or js wouldn't be able to affect the contents of an iframe.
They wouldn't affect them if you didn't either.
You have to explicitly allow sites to interact with the contents of an iframe, either by setting up an api like this, or by setting up cors headers to allow interaction. According to other answers on this site, if the iframe and parent have the same domain, cors rules don't apply, so changes can be made. If you are embedding an iframe from your site on your site, you should probably trust your own code.
If you are asking how to prevent users from using the developer tools to mess around with your iframe contents, you can't. There are all sorts of things that website designers have tried to do to keep me from looking at their source. I've never found one that can keep me out.


text:
Q: Solving linear programming without solving linear programming Let $v_1, \cdots, v_n$ be vectors in $\mathbb R^k$, and let $M$ be the Gram matrix of them.
It's possible to determine from $M$ and $k$ whether the only vector that has nonnegative inner product with every $v_m$ is the zero vector. This is because $M$ determines $v_1, \cdots, v_n$ up to orthogonal transformations.
Nevertheless, the process of determining is as hard as linear programming. With this in mind, my question is:
Question: Are there sufficient conditions on $M$ and $k$ to ensure that the zero vector is the only vector that has nonnegative inner product with every $v_m$, without using linear programming?
What I would expect as answers are analytic conditions on the matrix $M$ and $k$ without quantifiers for any fixed $n$ and $k$.
Example: Assume $n=k+1$, and $X$ is the $n$-dimensional matrix with positive elements on the diagonal and negative elements elsewhere. Then $X$ as a Gram matrix satisfies the property.

A: $\newcommand\R{\mathbb R}$Suppose that $\det M_{J,J}\ne0$ for some set $J\subseteq[n]:=\{1,\dots,n\}$ of cardinality $|J|=k$, where $M_{J,J}:=(v_i\cdot v_j\colon (i,j)\in J\times J)$, the $(J\times J)$-submatrix of the Gram matrix $M$. Suppose also that $Mc=0$ for some $c=[c_1,\dots,c_n]^\top\in\mathbb R^n$ such that $c_j\ge0$ for all $j\in[n]$ and $c_j>0$ for all $j\in J$.
Then the zero vector is the only vector that has nonnegative inner product with every $v_i$.

Indeed, let $v:=\sum_{j\in[n]}c_j v_j\in\R^k$. Then
$$v_i\cdot v=\sum_{j\in[n]}c_j v_i\cdot v_j=(Mc)_i=0 \tag{1}\label{1}$$
for all $i\in[n]$. Since $\det M_{J,J}\ne0$ and $|J|=k$, the rank of the Gram matrix $M$ is $\ge k$. That is, the rank of the system $(v_1,\dots,v_n)$ of vectors is $\ge k$ (so, in fact, $=k$). So, by \eqref{1},
$$0=v=\sum_{j\in[n]}c_j v_j\in\R^k.\tag{2}\label{2}$$
Take now any $w\in\R^k$ such that $w\cdot v_j\ge0$ for all $j\in[n]$. By \eqref{2},
$$0=\sum_{j\in[n]}c_j w\cdot v_j.\tag{3}\label{3}$$
Since $c_j\ge0$ for all $j\in[n]$, all the summands in the sum in \eqref{3} are $\ge0$ and therefore $=0$. Since $c_j>0$ for all $j\in J$, it follows that $w\cdot v_j=0$ for all $j\in J$. But the rank of the system $(v_j\colon j\in J)$ of vectors is the same as the rank of $M_{J,J}$, which latter is $k$. We conclude that $w=0$, as claimed.

Letting $c_j=1$ for all $j\in[n]$ and taking any subset $J$ of $[n]$ of cardinality $k$, we see that the sufficient conditions given in beginning of this answer generalize the conditions in your Example.
I think it should be not hard to show that these sufficient conditions are also necessary. However, since you asked only for sufficient conditions, this addition should be the subject of another question, perhaps posted elsewhere.