text:
Q: Question about executing javascript post-processes in Java app Traditionally we have always used xml in the response which is parsed by a Javascript method to execute post processes.  I came up with a new, simpler implementation which uses a hidden input set by a requestAttribute and executed in an ajax callback.
JSP:
<%
    String jsPostProcess = (String)request.getAttribute("jsPostProcess");
    if (jsPostProcess!=null && jsPostProcess.trim().length()>0){
%>
        <input type="hidden" id="jsPostProcess" name="jsPostProcess"
            value="<%= jsPostProcess %> "/>
<%  } %>

AJAX CALLBACK:
var callback = {
    success: function(response) {
        var div = $(divId);
        if (div){
            div.innerHTML = response.responseText;
        }
        var jsPostProcess = $('jsPostProcess');
        if (jsPostProcess)
            eval(jsPostProcess.value);
    },
    failure: function(response) {
        alert('Something went wrong!');
    }
}

SERVLET CODE:
request.setAttribute("jsPostProcess", jsPostProcess);

It works beautifully, and it is so much simpler for adding js post processes to virtually any call no matter how simple or complex the functionality is.  No need for customized js methods for parsing.
Curious if anyone could identify any potential problems with it (such as security issues?) or make any suggestions for other alternatives.  We currently use Prototype and YUI 2 on the front-end.

A: First, there's no need for that unpleasant scriptlet code:
<c:if test='${not empty jsPostProcess}'>
  <input type='hidden' id='jsPostProcess' name='jsPostProcess' value='${jsPostProcess}'>
</c:if>

Next thing is that I hope that somewhere before this point the "jsPostProcess" value has been scrubbed so that it doesn't break the markup (like, in case it includes quotes).
Just calling eval() on the value like that seems a little dangerous, though perhaps you know  pretty well what it's going to be.
Finally I would offer the suggestion that as an alternative to that, if the "post process" code isn't too big you could send it back in a response header. Then you wouldn't have to drop any meaningless markup into your page.
Oh, also finally: you might want to make the <input> be disabled. Or, alternatively, you don't even have to use an input: you can use this trick:
<script id='jsPostProcess' type='text/plain'>
  ${jsPostProcess}
</script>

Because the "type" attribute is "text/plain" the browsers won't try to execute that code, and you can get the "text" of the <script> element whenever you want.


text:
Q: Having issue with making an object in C++ Ok so I'm working on this little code and I've made two classes, advString and advString_stream. Here are the classes:
class advString
{
public:
    string s_value;
    int i_value;
    advString(string s) : s_value(s) {}
    advString(int i)    : i_value(i) {}
};
//--------------------------------------------------------------------------------
class advString_stream
{
public:
    advString get();
    void putback(advString as);
private:
    advString buffer;
    bool full = false;
};
//--------------------------------------------------------------------------------

And then, later down in the code, I define this object:
advString_stream ads;

It seems like it should work for me, but whenever I run the code, it gives me this error:

'advStream::advStream(void)': attempting to reference a deleted function

So can someone help me? I can't seem to make an advString_stream without the compiler complaining.

A: Because the contained advString object (the buffer member) doesn't have a default constructor, you need to explicitly provide a advString_stream constructor to properly construct the buffer object.
Something like
class advString_stream
{
public:
    advString_stream()
        : buffer(someArgumentHere)  // Using constructor initializer list
    {}

    ...
};

A: You have to declare and implement a default constructor, If you declare and implement a other contructor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Polymer: Calling elements property in main app page from one of its views Im using polymer starter kit, and in my main page (my-app) i have a div element which is hidden, and which i want to display on click from one of the apps views. I used syntax this.$.elementId.style="display: block;" but it returns error element is not defined. Is there any way to reach this value from one of its views?

A: I don't know which version of polymer you are using, but this is the polymer 2.0 way of doing this. In order for an child element to communicate to the parent element, you need to use events. You need to dispatch an event within the view element and listen to the event in my-app element like this:
view element method
buttonClicked() {
    this.dispatchEvent(new CustomEvent('button-clicked'))
}

my-app element
<my-view on-button-clicked="hideDiv"></my-view>

my-app element method
hideDiv() {
    this.$.elementId.style.display = "hidden"
}


text:
Q: NodeJs - fetch request from client always returns a 200 status response from the server regardless if there was an error updating the DB I am using a fetch() request from the client to PUT updated user data to the backend, to then be saved into a DB. So far, the all of the route is working fine, verified and tested in Postman.
In this User Update route, there is an if statement that checks for an error when searching for the user in the database, and if this error is thrown, it sends a response of 404 and a message to the client.
When I make the fetch() request from the client to this route, regardless if there is an error, the response is always a status 200, and does not include any response from my route. I need the client to be able to handle the potential errors the routes might produce. For example with this user update route, if the user is not found in the database for whatever reason, an error and message is returned, so the client needs to know this.
Here is some code:
Client-side:
fetch(`http://localhost:3000/users/${userId}`, {
        method: "put",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(userData)
      }).then(response => console.log(response))
        .catch(err => console.log(err));

Here in the client, I am using console.log() to visualize everything. When the response returns, I get back:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 200, ok: true, …}

Server-side route controller:
exports.user_update = (req, res) => {
  const { params, body } = req;
  const { userid } = params;

  User.findByIdAndUpdate({ _id: userid }, body, { new: true }, (err, user) => {
    if (err)
      res.send({
        status: 404,
        message:
          "There was an issue finding and updating the user on the server."
      });
    else
      res.send({
        status: 200,
        user
      });
  });
};

Now here on the server, I anticipated the response of the fetch() to be either the 404 error or the 200 success along with their payloads. Neither are returned in a response from the server. Instead as mentioned above, I am getting a generic 200 ok response simply letting me know the fetch() made a connection to the route. This route(along with the others) has been tested in Postman, and all work as anticipated returning the expected responses.
What am I not understanding here? Is my idea of using a fetch() request in this manner wrong? I feel like I might be close, but that's just my ignorant guess. Thank for reading!

A: I figured out the solution.
The fetch request was wrong, here is the update:
fetch(`http://localhost:3000/users/${userId}`, {
        method: "put",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(userData)

      }).then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.log(err));

I had to call response.json() to parse the response as a JSON object.

A: According to express documentation you sent status as a field of JSON. To correctly send http status replace your res.send(...) with
res.status(404).send("There was an issue finding and updating the user on the server.");

and
res.send(user);

A: You are sending the status field inside your payload, which is not parsed by fetch API.
To solve this you could something as below
exports.user_update = (req, res) => {
  const { params, body } = req;
  const { userid } = params;

  User.findByIdAndUpdate({ _id: userid }, body, { new: true }, (err, user) =>
  {
    if (err)
      res.status(404).send({
        message: "There was an issue finding and updating the user on the server."
      });
    else
      res.status(200).send({
        user
      });

  });
};


text:
Q: Microsoft Access: create subdatasheet with SQL command? Microsoft Access supports "subdatasheets"

Is it possible to create this type of table from a SQL command? Or does one have to manually point and click to do it.

A: SQL commands can run scripts/manipulate data and organize it. It's a declarative language. What you're referring to is part of Access' UI features/capabilities.
Your subdatasheet link shows an Orders table with a 1:M relationship to an Order Details table. One Order record with many details about that Order.
The reference you linked shows you how to set this up; it doesn't take any SQL or even VBA to do this. This is a way to view data and it's correlated data from another table in a Datasheet view.


text:
Q: transforming URLS to active links with REGEX i have this code in php that transforms URL inside a text to active html links.
For example in a string
Hey check this cool link http://www.example.com

this transforms to:
Hey check this cool link http://www.example.com
As you can see it just adds the correct  html tag
The code is this:
$active_links_text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","\\0", $original_text);

My question is, how to do this to work EXCEPT if the URL is a youtube url.
So i want this result: In a string
Wow have you checked http://www.youtube.com/watch?v=dQw4w9WgXcQ its even better than http://www.example.com !!!

i want to be transformed to
Wow have you checked http://www.youtube.com/watch?v=dQw4w9WgXcQ its even better than http://www.example.com

As you can see the  html tag was added to the example.com's URL but NOT at the youtube's URL.
How can i make this happen???
I hope i described my problem good enough, i hope its easy to implement this! Last note: i am using this code in php 5.2.14
Thank you guys!

A: [EDIT : Wow, I had gotten your question completely wrong! Below's a better attempt at helping you.]
I gave it a go in js here, here is the original regex : /(http:\/\/(?!www.youtube)[^<>\s]+)\b/g, since i'm not a php coder. The negative lookahead prevents a litteral www.youtube match (the lookahead content can be adapted if you need a more complex pattern).
There's nothing js-specific here to my knowledge, but I don't know the ereg regex syntax. with preg functions, you would just need not to escape the slashes, the word boundaries \b and negative lookahead (?!*pattern*) are the same. The /g flag is for a global replacement, that is, not stopping on the first match, I suppose you have a kind of replaceAll function in your toolbox.
Also, I'm not sure about the global flag in php, I guess you can just call a kind of replaceAll function.

A: You've made several mistakes about valid URI components. The scheme is defined as ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ), not [[:alpha:]]+.
The part after the : of the scheme need not start with //, that's particular to http: and a few other file-oriented schemes. But the [[:alpha:]]+: start of your regex shows you weren't aiming to restrict yourself to http:. In that case, all printable ASCII characters are valid. I.e. everything from ! to ~, or [\x21-x7E]* as a regex.
To summarize: [[:alpha:]][A-Za-z0-9+-.]*:[\x21-x7E]*.


text:
Q: How to set background color for input text component's text only in angular I am using bootstrap libraries in angular for form development.
I have a readonly input text component called 'Status' in the form. The values for this field can be Open, In Progress, Closed.
To provide a visual indicator, I am looking to style the Status field's text value with appropriate background color.
Currently when I set the color to the input text field, the entire input text field is marked in the background color selected. However, I want the background color to only apply to the text.
I am struggling to get this done.
I have also attached a sample screenshot for reference.
How can we achieve this?

A: 1. Without Input element
In html
Status: {{Status}}

In CSS
.badge {
    padding: 4px;
    margin-left: 10px;
    border-radius: 4px;
    background: blue;
    color:white;
}

.badge.open {
    background: green;
}

2. With Input element
In html
Status <input class="badge" [ngClass]="{'open': status =='open'}" [size]="status.length" [(ngModel)]="status">

In CSS
input.badge {
    border: 0;
    background: blue;
    color: white;
    padding: 4px;
    margin: 0;
    display: inline-block;

}

input.badge:active, input.badge:focus {
    background: blue;
    outline: 0;
}

input.open {
    background: green;
}


text:
Q: Multiple queries on firebase database fields I'm currently working on react-native todo application, where you can add tasks, I want to only display tasks that has not been completed or archived, I'm having some difficulties on querying both fields at the same time, this is my code for querying the fields.
const { currentUser } = firebase.auth();
    // fetch all tasks
    firebase
    .database()
    .ref(`/users/${currentUser.uid}/tasks`)
    .ref.orderByChild("completed").equalTo(false)
    //.ref.orderByChild("archived").equalTo(false) - This query is not working
    .on("value", snapshot =>
      this.setState({ tasks: snapshot.val(), loading: false })
    );
  }

Can I get some assistance on how to check both fields? I'd like to check the fields because I'd like to only display the tasks on default view that has not been completed or archived, as mentioned earlier. I've taken some look at previous related threads, and i'd definitely wouldn't like to change database structure just because of that, I'm rendering the tasks to flatlist, which can be found below:
 _FlatListData = data =>
    // data recieved from firebase is (collection) an object with individual tasks
    // as separate objects with firebase-defined-id as the key and actual task object as value
    // Object.entries breaks down the collection into an array of arrays with 2 elements each
    // [0] as the key and [1] as value which is then mapped to get an array of objects combining
    // the data and the key value into a single object
    Object.entries(data)
      .map(d => {
        return { ...d[1], key: d[0] };
      })
      .reverse();

{/* render FlatList only if state.tasks is !empty*/}

        {!!this.state.tasks && (
          <FlatList
            /* Since the data fetched from firebase is not an array but an
            object it needs to be converted into a workable array first */
            data={this._FlatListData(this.state.tasks)}
            renderItem={({ item }) => (
              <TaskCard
                data={item}
                DeleteTask={this.DeleteTask}
                UpdateTask={this.UpdateTask}
              />
            )}
            keyExtractor={item => item.key.toString()}
          />
        )}

EDIT:
Here's sample json how my structure looks like:
{
  "users" : {
    "E9JRDTPLZrSAfc0ERvO0yHJw3am1" : {
      "tasks" : {
        "-LvkpiUO_uxXcf-BYZqk" : {
          "archived" : false,
          "body" : "Test",
          "completed" : true,
          "name" : "Test",
          "timestamp" : 1575998646319
        },
        "-Lvl3qzXylp5H2oOLiaE" : {
          "archived" : true,
          "body" : "Gh",
          "completed" : false,
          "name" : "Gg",
          "timestamp" : 1576002613305
        },
        "-Lvl4YE2E_omKrsOjkZs" : {
          "archived" : false,
          "body" : "Hu",
          "completed" : true,
          "name" : "Bh",
          "timestamp" : 1576002794529
        },
        "-Lvl4woHR5rhtl_JgkBP" : {
          "archived" : true,
          "body" : "Vc",
          "completed" : false,
          "name" : "Bbj",
          "timestamp" : 1576002899308
        }
      }
    },
    "ZqABgFit8YglimXPPZJNoSeea803" : {
      "tasks" : {
        "-Lvg7rT7PfFLx1nzEzgg" : {
          "archived" : false,
          "body" : "Test\nS\nS\nS\nS\nDkdndodn\n\n",
          "completed" : true,
          "name" : "Twdt",
          "timestamp" : 1575919777699
        }
      }
    }
  }
}


text:
Q: Managing object instances I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.
Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.
function pet(name)
{
       this.name= name;
}

function petFactory(textFieldInput)
{
       var x = new pet(textFieldInput)
}

Since there's no way, that I know of (besides an eval function), to dynamically use a new, unique variable name for the pet every time petFactory is called, x is reassigned to a new object and the last pet is lost. What I've been doing is pushing the pet object onto an array as soon as it's initialized.
petArray.push(this);

So if I wanted the pet named 'mrFuzzyButtoms' I could loop through an indexed array until I found the object with the instance variable 'mrFuzzyButtoms'
for (n in petArray)
{
       if (petarray[n].name == 'mrFuzzyBottoms')
       {
               // Kill mrFuzzyBottoms
       }
}

or I could use an associative array...whatever...but the array is the only method I know for doing this. Besides using an eval function to create unique variable names from strings but some languages don't have an eval function (actionscript3) and then there is the security risk.
Is there a better way to do this?
Edit:
Right now I'm working in Python, JavaScript and ActionScript.

A: "I could use an associative array" Correct.
"the array is the only method I know for doing this."
Learn about "Mappings" or "Dictionaries" as soon as you can.  You will find that it does exactly what you're asking for.
What language are you using?  If you provide a specific language, we can provide specific links to the "Map" structure in that language.

A: This what collection classes (lists, dictionaries/maps, sets) are for; to collect a number of instances. For the above case I would probably use a map (class name varies depending on language) from name to object.

A: #!/usr/bin/env python
"""Playing with pets.

"""

class Pet(object):
    """A pet with a name."""
    def __init__(self, name):
        """Create a pet with a `name`.

        """
        self._name = name

    @property
    def name(self): # name is read-only
        return self._name

    def __repr__(self):
        """
        >>> eval(repr(self)) == self
        """
        klass = self.__class__.__name__
        return "%s('%s')" % (klass, self.name.replace("'", r"\'"))

    def __eq__(self, other):
        return repr(self) == repr(other)

    name2pet = {} # combined register of all pets

    @classmethod
    def get(cls, name):
        """Return a pet with `name`.

        Try to get the pet registered by `name`
        otherwise register a new pet and return it
        """
        register = cls.name2pet
        try: return register[name]
        except KeyError:
            pet = register[name] = cls(name) # no duplicates allowed
            Pet.name2pet.setdefault(name, []).append(pet)
            return pet

class Cat(Pet):
    name2pet = {} # each class has its own registry

class Dog(Pet):
    name2pet = {}

def test():
    assert eval(repr(Cat("Teal'c"))) == Cat("Teal'c")

    pets = [Pet('a'), Cat('a'), Dog('a'), Cat.get('a'), Dog.get('a')]
    assert all(pet.name == 'a' for pet in pets)

    cat, dog = Cat.get('pet'), Dog.get('pet')
    assert repr(cat) == "Cat('pet')" and repr(dog) == "Dog('pet')"
    assert dog is not cat
    assert dog != cat
    assert cat.name == dog.name

    assert all(v == [Cat(k), Dog(k)]
               for k, v in Pet.name2pet.items()), Pet.name2pet

    try: cat.name = "cat" # .name is read-only
    except AttributeError:
        pass

    try: assert 0
    except AssertionError:
        return "OK"
    raise AssertionError("Assertions must be enabled during the test")

if __name__=="__main__":
    print test()

pet.py


text:
Q: Would changing to a different motherboard/cpu/ram conflict with Ubuntu? My buddy has been using hand me down computers for years and is due for a upgrade.  He currently has a pre-lga775 pentium 4 @ 2.8GHz and I have a Core2Duo E6400 @ 2.13Ghz with an ASUS P5LP-LE mobo.  I would like to just spend the $30 on RAM and be able to just swap it out in his current computer.  What, if anything, would I have to do to Ubuntu to play with the new hardware? He is currently running Xubuntu 12.04.
ASUS P5LP-LE MOBO
Core 2 Duo E6400

A: I do this all the time. Since Ubuntu is based on Linux, which means it is hardware independent (A whole different story if we talk about Windows) you won't have a problem in most cases. So since it is hardware independent you can just change your motherboard, cpu, ram, video card, lan card, wifi card and any other hardware without any problem.
The problems that will appear are (I will list some of them since you will get an idea with the couple I will write about):

*

*Hardware that needs Proprietary drivers - If you happen to move from a integrated video card in your motherboard (Let's say an Intel video card), to another computer with an Nvidia or Ati card, you will most likely need to install the proprietary drivers to have full features for that particular video card. Is not the same performance to compare the open sourced Nouveau with the Proprietary Nvidia drivers. Both of which are found and available to install when Ubuntu starts. This will likely not interfere with Ubuntu but will make it tough if you want to play son HD video or play a Windows game on Wine. Same goes for Wireless cards like the Broadcom Based ones.

*Moving from 64 Bit to 32 bit (Backwards Architecture). If you have a 64 bit capable hardware with an Ubuntu 64 installed on it and you move to a hardware that has no 64 Bit support, you will receive some errors. The opposite is not true on newer systems and Ubuntu versions but it is recommended to stick with the same architecture for performance and stability issues.
In the cases you are mentioning, you won't have any problems whatsoever. To test this, simply remove your hard drive and connect it to the other PC. Then boot from your hard drive. You will notice that it will boot like it was running on that computer since the beginning.
Aside from this, if you are going to use more than 4GB RAM, I recommend going for a 64 bit version, although the 32 bit will still use the additional memory with its PAE kernel.

A: From my experience it shouldn't be a problem, though I cannot really guarantee that it will work. I've only tried it once. :P Ruining your operating system with a hardware upgrade is a Windows thing as far as I heard.
But of course, making proper backups of your important information before attempting the upgrade is always a good idea.

A: You shouldn't have to do anything, other then deactivating/removing any proprietary graphics drivers, in case the graphics card on the new board is going to change.
That said, you'd probably want to swich to the 64bit version of Xubuntu, especially if the amount of RAM is going to be 4GB or more, though the 32bit version should also work.
Linux distros do not have any problems with hardware changes, as long as the new hardware is supported.


text:
Q: Using RecyclerView.OnScrollListener in RecyclerView to implement loading more items got duplicated items I was trying to fetch JSON data into a RecyclerView using Retrofit 2. I also implemented pagination. Now for testing, I changed the JSON URL as if it will only show 5items per page. The page number can be changed by adding "&page=PAGE#" at the end of the JSON URL (where PAGE# is integer value starting from 1 and if no Page no is mentioned, it will show by default the first page).
The Problem: I have successfully added every page into the Recyclerview. But, it is adding the last page items twice, sometimes it is adding 3 times. Like this:
It will add last post couple of times
I am unable to find the problem. The step by step debugging does not help. Please help me.  I am learning these so if you help me I would really appreciate it.
WPPOST POJO:
public class WPPost {

  @SerializedName("code")
  @Expose
  private String code;
  @SerializedName("id")
  @Expose
  private Integer id;
  @SerializedName("guid")
  @Expose
  private Guid guid;
  @SerializedName("title")
  @Expose
  private Title title;
  @SerializedName("content")
  @Expose
  private Content content;
  @SerializedName("post_categories")
  @Expose
  private List < String > postCategories = null;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public Guid getGuid() {
    return guid;
  }

  public void setGuid(Guid guid) {
    this.guid = guid;
  }

  public Title getTitle() {
    return title;
  }

  public void setTitle(Title title) {
    this.title = title;
  }

  public Content getContent() {
    return content;
  }

  public void setContent(Content content) {
    this.content = content;
  }

  public List < String > getPostCategories() {
    return postCategories;
  }

  public void setPostCategories(List < String > postCategories) {
    this.postCategories = postCategories;
  }
  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }
}

MODEL Class:
public class Model {

  public int postid;
  public String title;
  public String content;
  public String categoriesnames;
  public Model(int mID, String mTitle, String mContent, String mCategorynames) {
    this.postid = mID;
    this.title = mTitle;
    this.content = mContent;
    this.categoriesnames = mCategorynames;
  }
}

A: The RecyclerView's onScrolled method might be called many times during a short time, and your if statement cannot prevent the getRetrofit() from being called multiple times at a single scroll, you can print a log message with your request url to verify this.
So, you should fix the issue by eliminate the redundant duplicated requests. For example, check if a getRetrofit request is working in progress using a flag:
public void getRetrofit() {

  isLoadingData = true; // <--- flag

  // ....

  final Call < List < WPPost >> call = service.getPostInfo(url);
  call.enqueue(new Callback < List < WPPost >> () {
    @Override
    public void onResponse(Call < List < WPPost >> call, Response < List < WPPost >> response) {
      isLoadingData = false; // <--- flag
      // ...
    }

    @Override
    public void onFailure(Call < List < WPPost >> call, Throwable t) {
      isLoadingData = false; // <--- flag
    }
  });
}

Then, use this flag to determine if a next page request should be fired.


text:
Q: Object.observe() useable with Polymer? In my ideal world, I'd love for Polymer components to be able to use Object.observe() transparently to listen for changes to the properties of models, without the model objects having to themselves be custom elements.
In the example below, I have an element that has a property model of type Object. The HTML template uses {{model.name}} and I would like the element to update automatically whenever that property changes.
In my demo/example, the hacky way I accomplish this is by using Object.observe() within custom code, and when any change happens, I set model to undefined and back again. This "refreshes" the UI and picks up the changes. Of course, in any nontrivial UI, this would be very janky, so this is a bit of a "hope is not a strategy" moment....
Is there any design pattern for tersely doing this sort of thing right now, and/or a roadmap for doing such things in the future?
This is my custom element:
<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="test-view">
  <template>

Hello, I am called {{model.name}}, how are you?

  </template>
</dom-module>

and this is an HTML page that drives it through its state transitions:

    <link rel="import" href="../test-view/test-view.html">

    <test-view id="first" model='{ "name": "Wilma" }'></test-view>

A: This is probably not a complete answer to your question, more of comment, but since code does not look well in comments I'm still posting it as an answer. I think that kind of thing may even have worked in 0.5 without the additional observer. However, to improve performance this kind of behaviour was removed in 1.0. I also hope we get it back sometime.
To avoid setting the model to undefined and back to trigger a refresh, you could also just notify Polymer of the changes. I assume that this would be more efficient, especially when you have complex objects and lots of data-binding.
_observer: function(changes) {
    changes.forEach(function(change){
        this.notifyPath("model." +change.name, change.object[change.name]);
    }.bind(this));
}


text:
Q: How to make API call and pass header to it using Meteor I am trying to call one API using Meteor. The sample code given in API guide is as below:
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(userName + password)));

I have to use this code in Meteor, but I have not found any solution yet. I was able to call API which has no header using both GET and POST method. But how to pass above header to that API call?
I am using Meteor.http.post to make an API call. I am using following code by referring above code:
 return Meteor.http.post("url",
   { headers: {"Authorization": "Basic"+(new Buffer(username+password, "ascii")).toString("base64")},
   params: { name: username} } );

But it's not working.
I also have working PHP code sample to make this API call:
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $username . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);

Can anyone give me any hint about how to do it? Thank you in advance.

A: callApi: function () {
return Meteor.http.post("url",
    { headers: {"Authorization": "Basic"+(new Buffer(username+password, "ascii")).toString("base64")},
       params: { name: username} } );
}

Using above code in server side code, we can pass headers to an API.


text:
Q: aligning image with anchor in listitem I have created list of links as such

       .append() | jQuery API Documentation

       DropzoneJs + PHP: How to build a file upload form

the problem is that the a aligns with the bottom of the img. I want it to align with the top. I tried float but that messes the whole layout and then will have to apply the .clearfix hacks which does not look very nice. Is there any other solution?

A: Try vertical-align:top

a{
  vertical-align:top
    }

       .append() | jQuery API Documentation

       DropzoneJs + PHP: How to build a file upload form

A: I use a {vertical-align: top;}. Vertical-align works great for this type of issue.


text:
Q: Memory allocation error calling midiInOpen with NAudio library i'm trying to write a program that detects how many times a person hits a drum from the midi output of an electronic drumkit. I am using a NAudio to handle this. When i try to select a midi input i am being told that there has been a 'memory allocation error calling midiInOpen', i've had a look around and can't seem to find any resources that could explain my problem.
My midi device is definitely being recognised, at the moment i'm using a Yamaha piaggero NP-11 keyboard for the midi input.
The actual error is on line 25 where i'm adding the device:
midiIn = new MidiIn(0);

Here is my code that i'm using:
class Program
{
    public MidiIn midiIn;

    static void Main(string[] args)
    {
        Program program = new Program();
        program.MainRun();
    }

    void MainRun()
    {
        Console.WriteLine(GetMidiInDevices()[0]); // This is just to check that a midi device is actually plugged in.

        midiIn = new MidiIn(0); // <-- THIS IS WHERE I GET THE ERROR
        midiIn.MessageReceived += new EventHandler<MidiInMessageEventArgs>(midiIn_MessageReceived);
    }

    public string[] GetMidiInDevices()
    {
        string[] returnDevices = new string[MidiIn.NumberOfDevices];

        for (int device = 0; device < returnDevices.Length; device++)
            returnDevices[device] = MidiIn.DeviceInfo(device).ProductName;

        return returnDevices;
    }

    public void midiIn_MessageReceived(object sender, MidiInMessageEventArgs e)
    {
        if (e.MidiEvent != null && e.MidiEvent.CommandCode == MidiCommandCode.AutoSensing)
            return;

        if (e.MidiEvent.CommandCode == MidiCommandCode.NoteOn)
        {
            // As the Command Code is a NoteOn then we need
            // to cast the MidiEvent to the NoteOnEvent
            NoteOnEvent ne;
            ne = (NoteOnEvent)e.MidiEvent;
        }
        Console.WriteLine("Got input!");
    }
}

A: You may simply have another program or process running that's using that MIDI device.
That can trigger the same exception on the same line of code.
It's unfortunate that error message provides no help.


text:
Q: Switch the value appearing in Select Tag How to switch the value appearing in this select tag example...
If I've selected Code for Humans in list the value that will appear is 556, if I've selected Code for Animals the value appearing in select box will be 556. How should I do that? Do I need a javascript or something to be add in select tag?
<select name="test" id="test">
  <option value="556">Code for Humans</option>
  <option value="556">Code for Animals</option>
  <option value="556">Code for Elements</option>
</select>

A: There is no direct way because this is how select box works.
However you can try putting a text box just above the select box (put the text box without border and select box in a div and make the text box width full with margin and padding enough to make the textbox fit in the select box).
Handle the focus of text to show the dropdown and on selection, show the code in the text box. So, user sees the text box with code and not the selected value.
Demo - jsfiddle.net/5E7DS/
But ofcouse this would not behave exactly like select box. It would be easier and correct also to change the text itself to show the code.


text:
Q: Different file caching methods, pros & cons
*

*I have two websites that will share some resources, lets say, index.php, functions.js and style.css, and these scripts will be used on almost all pages on the websites.

*I have two audiences to cater for (in terms of download speed), the users within the same network that the sites hosted on (100mb/s aprx) and external users.

I am looking for the best way to cache each kind of script (.js, .css, .php) and examples of how this would be done with their pros and cons over other methods if possible. By caching I mean locally, network and server caching.
Note: index.php is a dynamic page which should be refreshed from cache every 2 hours. It would be nice if you start your answer with .js, .css, .php or a combination so I can easily see what type of script you are talking about caching.
Thanks All!

A: Performance tuning through cachine could be categorized into multi-layers:

*

*Client-side (JS and CSS): Add an Expires or a Cache-Control Header will get it done for you. But note that there are more to do than only caching to enhance client-side performance. For detailes check Best Practices for Speeding Up Your Web Site

*Server-side: this could be on many levels web server, scripting language, database, operating system, network, etc..

Good introduction and practical code examples can be found in Chapter 9 (Performance) - Developing Large Web Applications. It will talk about Caching CSS, Javascript, Modules, Pages, Ajax and Expire headers.
If we need to keep things simple on server-side do the following:

*

*Install APC extension which will make PHP faster for you through the so called opcode caching. No special configuration, it will work silently for you.

*Cache the full page for two-hours using this simple Pear library PEAR::Cache_Lite.

*For each database SELECT query cache the result in APC with a TTL of 5 Min, md5 hash the SELECT statement and use it as key for APC cache. Docs
In future if you have multiple servers and the performance becomes to be crucial before then you will need to look at:

*

*Shared memory caching between servers. Check Memecache or even Membase

*You need a reverse proxy solution: this basically layer between your user and server server so that it will serve the HTTP requests instead of your server. You can use for that Varnish, Squid or Apache Traffic Server.

*Mysql innoDB engine is slow, you may need to go for faster engine such as XtraDB

*Then maybe you will find that rational databases are stil slow for you. Then you will go for the key-value solution such as MongoDB.

Finally as references in web application performance check:

*

*Front-end Performance: High Performance Web Sites, Even Faster Web Sites and High Performance JavaScript.

*Back-end Performance: Pro PHP Application Performance and High Performance MySQL

A: Well caching is such a broad spectrum you really should be a bit more specific.
For example, if you're looking to lower the load on the server, you would want to cache the PHP files using APC (For example) [lowers disk reads of files].. or use memcache/redis/some other in-memory key-value store for relieving stress from your database server (application level caching).
If we're talking about the static files, there are a number of things you could do to gain network speed:

*

*Make sure the caching headers returned from the server are correct and that those files are cached in the client (for as long as you need/want). (clients get more responsive sites, you get less server load - but you'll still get hits on which you'll return a 304 not modified)

*If you're using Apache+mod_php... apache will start a php interpeter even for requests that are for static content (css, js). While if you place nginx before, those could be cache by the http server itself - much faster, Alternatively, go to step 3 (below)

*You could put Varnish infront of your entire(/both) websites for static content/semi-static content.
Another common "micro"-optimization... this usually effects bigger sites.. nothing i would worry about with your ~20K.. but if you want, is move the static files to a differnet domain such as some-university-static.com (not a subdomain).. that way cookies headers aren't sent with the static file's request, resulting in less incoming bandwidth and fast response for the user. (smaller request sent-fast it gets to the destination-faster it returns)
Home this gave you some initial pointers to look into.
Ken.

A: For the .js and .css files, you can simply use expires HTTP headers, which will cause browsers to cache them.
As for the .php, there are several options.
You can use memcache for specific things, for example if you're loading the same list of users over and over again from the database, and you cache the result with a specific expire time, e.g. 2 hours.
Or you can use reverse proxy such as varnish to to cache away a whole static html page, generated from the .php script


text:
Q: Which is the most accurate method of measuring distance? I aim to analyse the accuracy of the various methods of geodesic calculations (distance between two points on Earth)based on the three assumed models of Earth - flat, spherical & ellipsoidal.
I need a reliable index to compare my results to measure for accuracy. Will using the WGS84 geoid with Vincenty's formula yield the most accurate results?

A: Let me focus just on the question of the most accurate way to determine
distances on the WGS84 ellipsoid.
The accuracy of Vincenty's method is about 0.1 mm providing it converges.
It fails to converge for nearly antipodal points.
My library GeographicLib is accurate to about 15 nanometers and
converges everywhere; the algorithm is published in my paper Algorithms
for geodesics.  I've also published a Test set for geodesics
which gives the distances between selected points on the WGS84 ellipsoid
accurate to about 0.1 picometers.  For more background information see
the wikipedia page Geodesics on an ellipsoid.

A: For the sphere you can use the SLC (Spherical Law of Cosines). The HF (Haversine Formula) will work for this as well. You can use both of these on the ellipsoid and errors are typically very low (< 0.3%).
If you desire an oblate spheroid then yes use VF (Vincenty's Formula).
For flat I am not sure it matters, do you mean a plane? If so then just use planar distance.
The Geoid varies greatly so in some locations SLC or HF will be best but all other things being equal VF will be best. Basically though, no best exists.

I need a reliable index to compare my results to measure for accuracy.

I doubt one exists. You could I suppose use a calculator that accounts for the WGS 84 geoid for error measurement (http://seismo.cqu.edu.au/CQSRG/VDistance/) but this itself is bases on VF but may work if you are just using spheroids, ellipsoids, and a plane.
This answer may somewhat help deciding between SLC and HF. Why is law of cosines more preferable than haversine when calculating distance between two latitude-longitude points?

A: Regarding the case of the "flat Earth". The answer depends on three key things:

*

*the map projection used

*whether or not you apply a scale factor correction to the calculated Euclidean distance

*the separation and orientation of the two points.

Generally stated,

*

*all map projections -- transforms from geographic to planar coordinates --
introduce linear distortions (except in certain directions)

*the distortion increases with distance

*each projection is different.

Some projections have readily-obtainable corrections (scale factors) that, when applied to short distance calculations, yield results that approximate the spheroidal geodesic calculations.
See these related questions:

*

*best-formula-for-calculating-short-distances-in-utm

*influence-of-the-scale-factor-on-the-projection

*calculating-distance-scale-factor-by-latitude-for-mercator


text:
Q: Pandas: Stream real-time data -> Make a sample copy -> process data I have a websocket feed coming from a cryptocurrency exchange of all current real-time trades as they happen (tick data). I want to store (only the last 5-10 minutes is necessary) and manipulate this data in real-time (every 5seconds) to then pass it to other functions.
Each tick looks like the below:
[{'homeNotional': 0.00546742, 'foreignNotional': 49, 'trdMatchID': '61c7a96f-28f3-0df1-4223-516d695333ee', 'tickDirection': 'ZeroMinusTick', 'price': 8962, 'timestamp': '2018-03-20T22:15:27.437Z', 'side': 'Sell', 'grossValue': 546742, 'size': 49, 'symbol': 'XBTUSD'}]

Which can then produce something like the below:
    foreignNotional grossValue  homeNotional    price   side    size    symbol  tickDirection              timestamp    trdMatchID
0   2                  22316    0.000223       8962.5   Buy        2    XBTUSD  PlusTick    2018-03-20T22:15:01.614Z    a06f6302-34b8-d307-e8e6-e4e617cbedf7
0   20                 223160   0.002232       8962.0   Sell      20    XBTUSD  MinusTick   2018-03-20T22:15:01.753Z    bb68d1f9-60ff-2990-c32a-bdbd14f5d773
0   22                 245476   0.002455       8962.5   Buy       22    XBTUSD  PlusTick    2018-03-20T22:15:01.858Z    a8e69797-5940-4aa1-2ab1-dd1ccceaa181
1   65                 725270   0.007253       8962.5   Buy       65    XBTUSD  ZeroPlusTick2018-03-20T22:15:01.858Z    685851cb-fd50-583d-5895-c91bbed10c98

My current idea is:
1. Append all tick data to df1 in real time
2. Take last 5 minutes of data from df1 and save it to df2
3. Run pre-processing on df2 including converting to OHLCV values and save in df3
4. Clear df2
5. Clear old cache of df1 every 10 minutes as I can't store it all in memory
6. Run steps 2,3&4 every 5 seconds.

My questions are:
Is this approach feasible and is pandas best suited for the task?
I'm currently using Jupyter notebooks and if I run step 1 and append my data to df1 I can't run concurrent tasks such as taking a slice and saving to df2. What is the best way around that?


text: Q: How to delete user connections to my app? My app, which is unverified, has over 100 users. As per Google's policies, unverified apps with over 100 users will simply stop working. We are trying to verify the app, but cannot, since we cannot show functionality, because we have over 100 users. Does someone know how I can delete / remove all user connections from my app via the GMail API? Thanks!


text:
Q: Shadow not displayed in CardView I am developing an android application in which I have used the cardview as  the grid item of GridView.
I am facing an Issue in displaying the shadow for the cardview if I use also the background image for the cardview.
Code Snippet:
grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="@dimen/grid_item_width"
    android:layout_height="@dimen/grid_item_height"
    card_view:cardBackgroundColor="#80000000"
    card_view:cardElevation="2dp"
    card_view:cardUseCompatPadding="true">

    <LinearLayout
        android:id="@+id/profile_picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/sample_expert_prof_pic"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:background="#8525272a"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:paddingLeft="@dimen/activity_horizontal_margin"
                    android:text="Shankar Venkat"
                    android:textColor="@color/white"

                    android:textSize="@dimen/grid_name_size" />

                <TextView
                    android:id="@+id/tags"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:paddingBottom="2dp"
                    android:paddingLeft="@dimen/activity_horizontal_margin"
                    android:paddingTop="5dp"
                    android:text="#finance# accounts"
                    android:textColor="@color/white"
                    android:textSize="@dimen/grid_tags_size" />
            </LinearLayout>

        </RelativeLayout>

    </LinearLayout>
</android.support.v7.widget.CardView>

I have increased the cardElevation from 2dp to 10dp. It shows the shadow in the Design Preview in Android Studio . But not working when deployed to real device.
UPDATE :
The Screenshot of Grid Item
Please anyone help me to find the solution.

A: Perhaps your real device is Lollipop device.
Try adding card_view:cardUseCompatPadding="true" to your xml and shadows will appear.


text:
Q: Sencha Touch - deselect list item? I'm working on a Sencha Touch application, and have a list of contacts. When a list item is tapped, an ActionSheet is displayed showing some basic functions (such as call, delete and ignore). Unfortunately, when the user taps and the ActionSheet is fired, the List item remains selected underneath the overlay (see the screenshot below):

Here's the function bound to the itemTap event:
itemTap: function(list, index)
{
    // Deselect the selected record:
    var currentRecord = list.getStore().getAt(index);
    currentRecord.forename      = currentRecord.get('forename');
    currentRecord.surname       = currentRecord.get('surname');
    currentRecord.phoneNumber   = currentRecord.get('phoneNumber');
    currentRecord.shortFullName = currentRecord.forename + ' ' +  currentRecord.surname[0];

    list.getStore().deselect(index, true);

    callButton.setText('Call ' + currentRecord.shortFullName + ' (' + currentRecord.phoneNumber + ')');
    unfriendButton.setText('Remove ' + currentRecord.shortFullName + ' as friend');
    friendActionSheet.show();
}

Unfortunately, list.getStore().deselect(index, true) returns the following error: Object [object Object] has no method 'deselect'
Any ideas on what I could be doing wrong, or how I can achieve this?

A: This works for me:
    listeners: {
        itemtap: function(dv, ix, item, e) {
            // Clear the selection soon
            setTimeout(function(){dv.deselect(ix);},500);
        }
    }

A: If you want to clear the whole list:
var selModel = app.views.notesList.deselect(app.views.notesList.getSelectedRecords());

A: In Sencha Touch 2, use disableSelection: true, while creating a list
Ext.define('App.view.NewsList',{
extend: 'Ext.List',
xtype: NEWS_LIST,

config: {
    store: NEWS_FEED,
    //deselectOnContainerClick: true,// not working in Sencha Touch 2
    disableSelection: true, // since Sencha Touch 2
    itemTpl: '{heading}'
}
});

A: setTimeout is really not a good solution here. It should be like this:
 listeners: {
        itemtap: function(list, ix, item, e) {
            // Clear the selection soon
            list.deselect(list.getSelectedRecords());
        }
    }

A: I haven't tried to recreate your problem but you may want to try:
list.deselect(currentRecord, true);

After you do that you may have to call
doLayout()

or
doComponentLayout()

to refresh the view.

A: This drove me INSANE.
While the approved answer will work, its worth noting that you can do it with a delay(like nested list does too) like this:
    var selModel = app.views.VideosList.items.items[0].getSelectionModel();
    Ext.defer(selModel.deselectAll, 200, selModel);

I put that in my controller (so its called when the view changes), where app.views.VideosList is my main panel and app.views.VideosList.items.items[0] is the list in that panel.

A: this did it for me (sencha touch 2.3):
list = Ext.Viewport.down('nestedlist');
list.getActiveItem().deselectAll();


text:
Q: Test Class issue I've some troubles with my test class:
Here is my test class:
@isTest
public class AccountHierarchyCtrl_Test {

static testMethod void Costruttore_Test()
{

test.startTest();
.....Creation of test data.....
    test.stopTest();

   Test.startTest();
   PageReference page1 = Page.MyPage;
   Test.setCurrentPage(page1);
   ApexPages.currentPage().getParameters().put('accId', a.Id);
   ApexPages.StandardController controller = new ApexPages.StandardController(a);
   MYPageCtrl stdController = new MyPageCtrl(controller);

   stdcontroller.AddChild(a.id, aa, 1);
   Test.stopTest();

}
}

Here is the method I want to test
   public Boolean addChild(Id parentId, Account child, integer margin) {
    if(acc.Id == parentId) {
     children.add(new MyAccount(child, margin));

        return true;
    } else if(children != null && !children.isEmpty()) {
        Boolean result = false;
        Integer i = 0;
        do {

            MyAccount myacc = children[i];
            result = myacc.addChild(parentId,child,margin);
            i++;

        } while(!result && i < children.size());
    }
    return false;
}

When I lauch the test I get this error:

Method does not exist or incorrect signature: [AccountHierarchyCtrl].AddChild(Id, Account, Integer)

Anyone could help me??
Thanks in advance.
A

A: You've defined method as Public boolean addChild(Id parentId, Account child, integer margin) and you're calling method as stdcontroller.AddChild(a.id, aa, 1); Check both names. Method defined has small addChild while calling statement has AddChild. Uppercase and lowercase issue. That's why you're getting an error.

A: From what I can see, you have a method called addChild in the controller MyPageCtrl or in the controller MyAccount. I'm not sure if you have the same method on both. But it looks like you are trying to call the method from MyAccount from the controller instance. Obviously it will throw an error because the controller doesn't have that method. Instead, an object that is inside the controller does.
Instead of calling a controller method, you should call the object MyAccount method. If the MyAccount object is a single instance within the controller, you may call it using stdController.theMyAccountObject.addChild. If it is in a list (List<MyAccount>) then you will have to use the list instance with an index (like stdController.theList[0].addChild).
It would benefit everyone who reads your question if you provided more information regarding your controller structure and what you are trying to do. Also, posting the whole controller code wouldn't be a bad idea (that is, if it doesn't contain 500+ lines...).

A: It looks like you are calling both test.startTest() and test.stopTest() methods twice in your static testMethod void Costruttore_Test(){...} method. Per the Documentation you are only allowed to call those methods once per testMethod.
Hers's a design pattern for Unit Tests that I use religiously... mostly to defend myself from declarative changes like new required fields and validation rules. You might find it useful.


text:
Q: Why is Hazard Function called rate of failure? I am confused why Hazard Function is called rate of failure. Here is what I understood about Hazard Function.
Suppose we are dealing with Weibull and let $f(X)$ be the pdf, $F(X)$ be the cdf.
Now, I have Reliability $R(X) = 1 - F(X)$. Dividing $f(X)$ with $R(X)$ gives us the Hazard Function.
The $f(x)$ gives us the probability of failure and $R(X)$ give us the probability of success. So if we divide the probability of failure by probability of success we get $Failure/Success$. If we call Hazard is the rate of failure, then it should be $Failure/SomeInterval$.
Also, if I look at $Kaplan-Meier$ estimate, $h(t)$ i.e. the hazard function estimate is $$ \#\,Items\,failed/ \#\,Items\,in\,Risk$$ but not $$ \#\,Items\,failed/ \#\,Items\,that\, didnt\, fail$$ which I get after dividing $f(X)$ by $R(X)$
This is what I understand but in all books and journals, Hazard Function is called rate of failure. Am I missing something??

A: Let $X$ denote time to event. For notation, I'm going to use $x$ instead of $t$, and $S(x)$ ("survival function") instead of $R(x)$. Let's start with a more intuitive definition of the hazard function $h(x)$.:
$$h(x) = \lim_{\Delta x\to 0} \frac{\Pr(x \leq X < x + \Delta x \mid X \geq x)}{\Delta x}$$.
That is, it is a "conditional event rate". Take the probability that the subject experiences the event "in the next instant" (conditioned on the fact that they've survived up until this point) and divide it by the "length" of the instant to make it into a rate (hand-wavy abuse of limits, but yeah). So $h(x)\cdot \Delta x$ provides an approximation of the probability of an individual of "age" x experiencing the event in the next short time interval.
Now getting from this definition $h(x)$ to the one you're asking about is a matter of algebraic manipulation and calculus:
$$h(x) = \lim_{\Delta x\to 0} \frac{\Pr(x \leq X < x + \Delta x \mid X \geq x)}{\Delta x}$$
$$= \lim_{\Delta x\to 0} \frac{\Pr(x \leq X < x + \Delta x , \hspace{2mm}X \geq x)}{\Delta x \cdot \Pr(X \geq x)}  $$
$$ = \frac{1}{S(X)} \lim_{\Delta x\to 0} \frac{\Pr(x \leq X < x + \Delta x , X \geq x)}{\Delta x}  $$
$$ = \frac{1}{S(X)} \lim_{\Delta x\to 0} \frac{F(x + \Delta x) - F(x)}{\Delta x}$$
$$ = \frac{dF(x)}{S(x)dx} = - \frac{1}{S(X)}\frac{dS(x)}{dx} = -\frac{dlog[S(x)]}{dx}$$
$$ = \frac{f(x)}{S(x)}$$


text:
Q: Angular2,Ionic2: How to do 2way binding for radio button in nested *ngfor using ngModel? I've my API in JSON in the following format.

I want to display this in the form of question & choices format. I'm trying to display the choices using radio buttons. But my ngModel is not working. I want to access the whole object of the selected choice using ngModel in my .ts file.
Here is my ts code
export class Quiz implements OnInit {
    testcontents: Array<any>=[];
    choiceObj:any;

 constructor(public navCtrl: NavController, public navParams: NavParams,public http:Http) {}
     ngOnInit()
     {
       this.launchfunc();
     }
     launchfunc()
     {
    this.http.post('launchtest/getTestContent',this.launchtestobj).subscribe(resp=>{
         this.testcontents = resp.data.questions;
    });
     }

    selectChoice($event)
    {
      console.log("12312341234",event);
      console.log("obj",this.choiceObj);
    }

Here is my html code
<ion-content padding>

    {{i+1}} {{qContent.questionText}}

        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choice' (ngModelChange)="selectChoice(choiceObj)" />
        {{choiceObj.choiceText}}

This is the output for the above code.
I don't understand why is obj undefined.
I've a problem with the ngModel. I'm not understanding what should I put my ngModel as and how should I access the "choiceObj" in typescript file.Can someone please help me.

A: the model is choiceObj.choice which is not exist in object of choice.
you need to replace it with 'choiceObj.choiceId'
<ion-content padding>

    {{i+1}} {{qContent.questionText}}

        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choiceId' (ngModelChange)="selectChoice(choiceObj)" />
        {{choiceObj.choiceText}}


text:
Q: CSS3 Navigation Bar: Float:Right I'm creating and designing a mini social networking website for our school's Science Fair, and I already have a problem at the designing stage. :(
So I've created a few PSDs on how my website should look like, but it seems harder to translate my designs into HTML/CSS. My current trouble right now is this navigation bar that isn't cooperating with me...
In short, this navigation bar is very simple; the logo, with the title, a subtitle, and a few menu options (Login, Sign up). I'm using float:right; to float my options to the right, but that isn't working very well.
The options of my navigation bar are jutting out, below the Navigation Bar. It's really odd; when I take out the float:right; it seems perfectly fine, but is to the left. I would really like it to be on the right side.
A sample of the website is available at http://ticktalk.me.pn/. A PSD of the Sign-Up Page is available here: http://img1.imagilive.com/0314/tickTalk-signup.jpg.
Please feel free to "View Page Source" and investigate what I've done wrong. A direct link to the css is available at http://ticktalk.me.pn/css/style.css.
Thanks in advance.
EDIT:
This is my Navigation Bar HTML...

        ticktalk

        social networking around the clock

            Login

            Sign Up

and this is my CSS:
.navbar-header {
    display:block;
    background-color: rgb(0, 241, 73);
    padding:10px;
    margin-bottom:75px;
}
.navbar-logo {
    display:inline-block;
}
.navbar-title {
    display:inline-block;
    font-size: 52px;
    margin-left:10px;
    margin-right:5px;
}
.bookfont {
    font-weight: 500;
}
.navbar-subtitle {
    display:inline-block;
    font-size: 30px;
}
.navbar-menu {
    float:right;
}
.navbar-option {
    display:inline-block;
    font-size:25px;
    padding:20px;
    padding-left:30px;
    padding-right:30px;
}
.navbar-checked {
    background-color: rgb(0, 217, 63);
}

A: Put the element with that has "float: right" before the rest of the elements on that line.
Basically, move
...
 before .
Or, in the sample code of the edited question, move
...
 before
...
.
I am not sure regarding the technical justification to this, but floats are better put before the non floats.
Perhaps this is because it assumes there is no room for the floating element.

A: Try elements on the left side wrapping with another div. Like this for example:

           ticktalk

            social networking around the clock

            Login

            Sign Up

Then give that .another-div CSS property float:left, and don't forget to set a hight for the .navbar-header after this.
.another-div{
    float: left;
}
.navbar-header{
    height: 80px;
}

This should work.


text:
Q: Fundamental proof of Taylor's theorem using little-o notations Is there a fundamental proof of Taylor's theorem using little-o notation?
I assume $f:E\rightarrow F$ as a mapping between Banach spaces and write $(h^i)$ for $(h,\ldots,h)$ ($i$ times iterated).
The definition of the derivative gives $$f(x+h)=f(x)+f'(x)(h)+o(\|h\|).$$  Applying this to $f'$ I get $$f'(x+h)=f'(x)+f''(x)(h)+o(\|h\|)$$ where $o(\|h\|)$ has to be interpreted in the context of the corresponding ambient spaces, i.e. $E$ in the first line and $L(E,F)$ in the second line.  Applying the second line to $h$ I get $$f'(x+h)(h)=f'(x)(h)+f''(x)(h^2)+o(\|h\|^2)$$ where the right hand looks at least similar to the right hand side of the equation I want to derive, namely $$f(x+h)=f(x)+f'(x)(h)+\frac{f''(x)(h^2)}{2}+o(\|h\|^2).$$  I could make it even more similar by writing $$f'(x+\frac{h}{2})(h)=f'(x)(h)+\frac{f''(x)(h^2)}{2}+o(\|h\|^2)$$ but I don't know how to proceed from there...
Edit: Sorry, what I wrote in my last (deleted) edit does not apply, I misread the text and the author addressed another formula with his quote!

A: I found a proof in H Cartan's Differential Calculus.  It doesn't exactly follow the route I attempted above, but it's still pretty fundamental, i.e. it essentially only uses the mean value theorem.


text:
Q: Strange product list look : which Magento module? Does someone know which Magento module allow to do product list look like this : https://www.gemmyo.com/pour-elle/les-essentiels/bagues.html ?
Thx

A: It's not really a module, it's more of a theming - you can edit list.phtml to get the list to look like that


text:
Q: Product Safety Testing - EU I was recently hit with the thought as to what safety tests a domestic electronic product has to go through before it is sold to consumers more specifically in the EU?
I have been looking through online but there is no clear answer. It mentions CE testing, but are there any other regulations/tests before it is sold to consumers and how do they work?
For example, as I look at a USB Power Supply I see it has the CE mark and other logos as well. I should mention that I was looking into EU laws.

A: I think the best aproach is indeed to look into EU law (like you already suggested):
https://europa.eu/youreurope/business/selling-in-eu/selling-goods-services/selling-products-eu/index_en.htm
which (regarding safety) links to
https://europa.eu/youreurope/business/product/product-rules-specifications/index_en.htm
which links eventually to (only) CE marking.
Regarding those other logos: they're likely certifications for other regions (FCC for USA, CSA for Canada etc) or logos for product identification (e.g.Class II lasers) etc.

A: Or in the UK next month you'll be needing the UKCA mark.... https://www.gov.uk/government/publications/prepare-to-use-the-ukca-mark-after-brexit/using-the-ukca-marking-if-the-uk-leaves-the-eu-without-a-deal


text:
Q: node-oracledb other language encoding I'm newbie at node.js!
I'm in trouble at encoding 'Korean'.
My oracle database has Korean String data, and directly Console.log(Korean text) is worked.
but when I use execute function and select query, and Console.log(return rows), It isn't work. text is broken.
I set all encoding type in Eclipse as UTF-8. As I think, I have to set something controlling encoding type in oracledb module, But I can`t find how set it.
please help me. I have to resolve this problem at any cost!!!
I already set NLS_LANG.
I don't set it. I just check it and take picture. It is already done when I found registry.
Windows 7 64bit
node 0.10.38
Eclipse / NodeClipse

It's resloved.
I set my NLS_LANG variable, as 'original value'.UTF8 And It works.
This is from master of node-oracledb. thanks.

A: From version 1.0, node-oracledb always sets the "client" character encoding to Oracle's AL32UTF8 value. See https://github.com/oracle/node-oracledb/blob/master/CHANGELOG.md


text:
Q: Getting the most recent posts from all users using Entity Framework/LINQ Lets say I have a table called Posts which has UserId, DatePosted, PostText. How can I get Entity Framework to generate SQL to get me the list of the most recent post by all users.
In SQL I can do something like this (although if a user posts two posts at the same exact time this won't work but I think I can manage to filter out the edge cases in code)...
select * from
   Posts p,
   (select UserId, max(DatePosted) as DatePosted from Posts group by UserId) rp
   where p.UserId=rp.UserId and p.DatePosted=rp.DatePosted;

The SQL appears to be returning the correct posts but I can't figure out how to translate this into Entity Framework LINQ.

A: IEnumerable<Post> posts = db.Posts
    .GroupBy(p=>p.UserID)
    .Select(p=>p.OrderByDescending(q=>q.DatePosted).First());


text: Q: What is android ems equivalent in flutter? I want to prevent Text widget width changing when text changes, in android i used ems but it does not exist in flutter, of course i can wrap Text widget with SizedBox widget, but there might be a better way..


text:
Q: like is not working in mySql sub query I have used some sub query , its not working at all ,if i am giving hardcoded id its working .
SELECT
  (
  SELECT
    COUNT(*)
  FROM
    inventory_set_variations isv
  WHERE
    isv.c_catid LIKE '%[{"id":"c1.catid"}]%' AND isv.company_id = 1
) AS 'count_total_no_of_variations',
`c1`.`catid` AS `catid`

FROM
   category c1
WHERE
  (
    `c1`.`catsid` <> 3 AND c1.company_id = '1'
  )

this is not working ,
below code is working as i gave hard coded data
SELECT
  (
  SELECT
    COUNT(*)
  FROM
    inventory_set_variations isv
  WHERE
    isv.c_catid LIKE '%[{"id":"1000020"}]%' AND isv.company_id = 1
) AS 'count_total_no_of_variations',
`c1`.`catid` AS `catid`

FROM
   category c1
WHERE
  (
    `c1`.`catsid` <> 3 AND c1.company_id = '1'
  )

A: You can use CONCAT to form like condition
Change
LIKE '%[{"id":"c1.catid"}]%'

to
LIKE CONCAT('%[{"id":"',c1.catid,'"}]%')


text:
Q: Prove if $x,y$ integers then there are $p,q$ integers such that $xy = p^2 - q^2$.

*

*Prove that if $x$ and $y$ are any two integers which are both even or both odd then there are integers $p$ and $q$ such that $xy = p^2 - q^2$.

*Prove that if n is an integer which is $2 \mod 4$ then $n$ cannot be written in the form $p^2 - q^2$ for integers $p$ and $q$.

I'm really stuck what to do on the first one. I know its possible as $xy$ will be even and $p^2 - q^2$ will be even, but I don't know how to show it will equal. Can someone give me a hint?
For the second one, I have said this:
1) If $p,q$ are odd then we get $p,q \equiv 1 \mod 4 \implies p^2, q^2 \equiv 1 \mod 4$. So we then get $p^2 - q^2 \equiv 1 - 1 \mod 4 \equiv 0 \mod 4$.
2) If $p,q$ are even then we get $p,q \equiv 0 \mod 4 \implies p^2, q^2 \equiv 0 \mod 4$ and so $p^2 - q^2 \equiv 0 - 0 = 0 \mod 4$.
3) Finally, if one of $p,q$ is odd and the other even, then wlg, $p \equiv 1 \mod 4 \implies p^2 \equiv 0 \mod 4$ and $q \equiv 0 \mod 4 \implies q^2 \equiv 0 \mod 4$ and so we get $p^2 - q^2 \equiv 1 - 0 = 1 \mod 4$.
Which shows that with all combinations of $p,q$ even or odd, it isn't possible to get $2 \mod 4$. Is this correct?

A: For the first question, note that if $x$ and $y$ are even or odd, $$\left(\frac{x+y}{2}\right)^2 - \left(\frac{x-y}{2}\right)^2 = xy,$$ and both of $\dfrac{x+y}{2}$ and $\dfrac{x-y}{2}$ are integers.
Your argument for the second question looks mostly good: you can't claim that $p,q$ are $0$ or $1$ mod $4$, but this does always hold for their squares, so it winds up working.

A: For the first part, consider the difference of two squares: $$xy=(p-q)(p+q)$$
So let, say, $p-q=x$ and $p+q=y$. Thus $2p=x+y \implies p=\frac{x+y}{2} \implies q=\frac{y-x}{2}$
$p,q$ must be integers since, by the condition, $x+y$ and $y-x$ are even.

A: $\rm x\equiv y\,\ (mod\ 2)\:\Rightarrow\:x\, =\, y\!+\!2n\:\Rightarrow\: x\!-\!n\, =\, y\!+\!n\, =:\, z\:\Rightarrow\: x\,y\, =\, (z\!+\!n)(z\!-\!n)\, =\, z^2\!-\!n^2$


text:
Q: WSO2 MDM Encrypt sensitive information in .json configuration files I cannot find a way to encrypt the keystore password in the json configuration files that are used in the WSO2 EMM.
There is a notable documentation for encryption of the sensitive information in the xml configuration files for the EMM product, but nothing for the json configuration files.
My question is about encrypting the keystore password in the json configuration files.

A: Secure vault uses the xpath to specify the location that we want to encrypt. Therefore currently secure vault does not support encrypting .json and properties files.


text:
Q: Number of busy connections used in pool I am using connection pool in pg node js module.
As I understand when you are using connection pool, your connections created for you, and stored, when you need it, some method evoked, and you get already instantiated connection.
Now about pg:
Simple code
pg.connect(conString, function (err, client, done) {
    if (err) {
      callback(err);
    } else {
      client.query('SELECT * FROM users', function (err, result) {
        done();
        if (err) callback(err);
        callback(null, result.rows);
      });
    }
  });

When I call pg.connect method, I assume that, I get already instantiated connection from pool, when I call done I return my connection to the pool.
Now I want to debug my application, I can forgot to call done or do it not efficient way.
How can I print number of busy connections? Or another way to debug approach. Thank you in advance.
I had some problem, when request to my route hanging for 30 seconds, I suppose that it is, because I didn't return my connection to the pool.

A: From pg module documentation pages
var pg = require('pg');

pg.connect(function(err, client, done) {
  var pool = pg.pools.getOrCreate();
  console.log(pool.getPoolSize()); //1
  console.log(pool.availableObjectsCount()); //0
  done();
  console.log(pool.getPoolSize()); //1
  console.log(pool.availableObjectsCount()); //1
});

Hope this helps...


text:
Q: Программа не работает на Linux # cc.py (change case) меняет раскрадку с ENG на РУС(и наоборот) посредством буфера обмена.
import pyperclip

eng_chars = "~!@#$%^&qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>? 1234567890"
rus_chars = "ё!\"№;%:?йцукенгшщзхъфывапролджэячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ, 1234567890"

def change(s1, s2, s_main):
    s_finish = []
    for i in range(len(s_main)):
        index = s1.index(s_main[i])
        s_finish.append(s2[index])
    return ''.join(s_finish)

s = pyperclip.paste()

if s.isascii():
    print('ascii')
    s = change(eng_chars, rus_chars, s)
else:
    print('not ascii')
    s = change(rus_chars, eng_chars, s)

pyperclip.copy(s)

На винде все работает четко. Под линуксом(манжароГном) не работает. Что-то не так именно с работой с буфером обмена. Не получается у неё вставить полученый результат обратно.
Суть проги в том, что если случайно написал текст не на той раскладке, копируешь этот текст в буфер обмена, запускаешь программу и вставляешь из буфера уже нормальный текст.

A: В документации пишут:

On Linux, this module makes use of the xclip or xsel commands, which
  should come with the os. Otherwise run "sudo apt-get install xclip" or
  "sudo apt-get install xsel" (Note: xsel does not always seem to work.)
Otherwise on Linux, you will need the gtk or PyQt4 modules installed.

xclip у Вас установленна?


text:
Q: Error connecting red5 from Flash Media Live Encoder Since a couple of days I'm trying to get the red5 authdemo to work (in Eclipse Juno).
see: http://blog.infrared5.com/2012/05/red5-authentication/demo-project source: http://dl.dropbox.com/u/7316897/ir5/blog/red5-auth.zip
The red5 Server seems to work fine:
...
[INFO] [Launcher:/authdemo] org.red5.demo.auth.Application - Available auth providers: 1

But I've got the following error/exception when I try to connect rtmp://localhost/authdemo via Flash Media Live Encoder 2.3:
[INFO] [NioProcessor-2] org.red5.server.net.rtmp.codec.RTMPProtocolDecoder - Action connect
[INFO] [NioProcessor-2] org.red5.server.net.rtmp.RTMPHandler - Connecting to: [WebScope@66bfa709 Depth = 1, Path = '/default', Name = 'authdemo']
[INFO] [NioProcessor-2] org.red5.demo.auth.Application - W3C x-category:session x-event:connect c-ip:127.0.0.1 c-client-id:0
[INFO] [NioProcessor-2] org.red5.demo.auth.FMSAuthenticationHandler - appConnect
[INFO] [NioProcessor-2] org.red5.demo.auth.FMSAuthenticationHandler - Connection: RTMPMinaConnection from 127.0.0.1 : 53362 to 127.0.0.1 (in: 3259 out 3073 )
[ERROR] [NioProcessor-2] org.red5.server.net.rtmp.RTMPHandler - Error connecting {}
        java.lang.ClassCastException: org.red5.server.net.rtmp.status.StatusObject cannot be cast to java.lang.String
        at org.red5.server.net.rtmp.RTMPConnection.connect(RTMPConnection.java:284) ~[red5.jar:na]
        at org.red5.server.net.rtmp.RTMPMinaConnection.connect(RTMPMinaConnection.java:87) ~[red5.jar:na]
        at org.red5.server.net.rtmp.RTMPHandler.onInvoke(RTMPHandler.java:268) ~[red5.jar:na]

( ... lots of similar error-messages ... )

[WARN] [Red5_Scheduler_Worker-2] org.red5.server.net.rtmp.RTMPConnection - Closing RTMPMinaConnection from 127.0.0.1 : 53362 to 127.0.0.1 (in: 3259 out 3177 ), with id 1 due to long handshake

Has anyone encountered this problem before? Any ideas that might solve my problem?
Thanks in advance!


text:
Q: Assigning specific XML Elements from string to ViewModel using AutoMapper I have a database table that stores a block of XML data within a string-type field. I'd like to extract certain elements of that XML into a custom ViewModel.
In this example, the ErrorTableModel.ErrorXML holds the sample XML string. I'm attempting to get the "message" element out of that string and map it into ErrorViewModel.message.
Would this be possible to accomplish using AutoMapper?
Sample string. This data is stored in the ErrorXML property of ErrorTableModel:
<error
  application="TestApp"
  type="System.DivideByZeroException"
  message="Something wicked this way comes."
</error>

Database Model:
public class ErrorTableModel
{
    public int ErrorId { get; set; }
    public string ErrorXml { get; set; }
}

Custom ViewModel:
public class ErrorViewModel
{
    public int id { get; set; }
    public string application { get; set; }
    public string type { get; set; }
    public string message { get; set; }
}

Update:
I've created a new helper class that is intended to assist in breaking the XML apart.
protected override T ResolveCore(XElement source)
{
    if (source == null || string.IsNullOrEmpty(source.Value))
    {
        return default(T);
    }

    return (T)Convert.ChangeType(source.Value, typeof(T));
}

I'm attempting to reference that method when I perform the mapping from the ErrorViewModel.
    Mapper.CreateMap<XElement, ErrorViewModel>()
        .ForMember(
            dest => dest.ErrorXml,
            options => options.ResolveUsing<XElementResolver<string>>()
                .FromMember(source => source.Element("error")
                .Descendants("message").Single()));

Sadly, this doesn't work... but I think I'm close.
Update2:
For clarification, I'd like the resulting data to look like this:
  ErrorViewModel.application = "TestApp"
  ErrorViewModel.type = "System.DivideByZeroException"
  ErrorViewModel.message = "Something wicked this way comes."

A: Something like this:
public class ErrorConverter1 : ITypeConverter<ErrorTableModel, ErrorViewModel>
{
    public ErrorViewModel Convert(ResolutionContext context)
    {
        var dbModel = context.SourceValue as ErrorTableModel;

        if (dbModel == null)
            return null;

        var xDocument = XDocument.Parse(dbModel.ErrorXml);

        var errorElement = xDocument.Descendants(XName.Get("error")).Single();

        return new ErrorViewModel()
        {
            id = dbModel.ErrorId,
            application = errorElement.Attribute(XName.Get("application")).Value,
            type =  errorElement.Attribute(XName.Get("type")).Value,
            message = errorElement.Attribute(XName.Get("message")).Value
        };
    }
}

Or through XML deserialization. For this you need to change the ErrorViewModel class to:
[XmlRoot("error")]
public class ErrorViewModel
{
    public int id { get; set; }

    [XmlAttribute("application")]
    public string application { get; set; }

    [XmlAttribute("type")]
    public string type { get; set; }

    [XmlAttribute("message")]
    public string message { get; set; }
}

public class ErrorConverter2 : ITypeConverter<ErrorTableModel, ErrorViewModel>
{
    public ErrorViewModel Convert(ResolutionContext context)
    {
        var dbModel = context.SourceValue as ErrorTableModel;

        if (dbModel == null)
            return null;

        var serializer = new XmlSerializer(typeof(ErrorViewModel));

        var result = (ErrorViewModel) serializer.Deserialize(new StringReader(dbModel.ErrorXml));

        result.id = dbModel.ErrorId;

        return result;
    }
}

The usage is like this:
public class MappingProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<ErrorTableModel, ErrorViewModel>()
            .ConvertUsing<ErrorConverter1>()//or use the ErrorConverter2
            ;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(x => x.AddProfile<MappingProfile>());

        var dbModel = new ErrorTableModel()
        {
            ErrorId = 1,
            ErrorXml =
                "<error application=\"TestApp\" type=\"System.DivideByZeroException\" message=\"Something wicked this way comes.\"></error>"
        };

        var viewModel = Mapper.Map<ErrorTableModel, ErrorViewModel>(dbModel);

        Console.WriteLine(viewModel.id);
        Console.WriteLine(viewModel.application);
        Console.WriteLine(viewModel.type);
        Console.WriteLine(viewModel.message);

    }
}

Add guard clauses to your needs.


text:
Q: Can the 0 Gravity of a hollow shell be rephrased to "If an object has a gravitational counterpoint net forces become 0"? So the basic argument as I understand it for gravity inside a hollow shell is all gravitational forces are equal to 0, because they cancel out from the mass on the other side of the shell irrespective of location. Could that be thought of more generally as if you have a gravitational counterpoint then the force of gravity becomes 0.
Example: In deep space away from all other gravity influences & frictionless. You have 2 rocks of equal mass on either side of a 3rd rock. Do their individual gravities cancel out relative to the 3rd object in between 1 & 2.

A: Let's say you have two bodies of mass $M$ separated by a distance $d$. If you place a test body exactly in the center of the line separating the two objects, then the force on that object will be zero. However, the force will not be zero if you place the test body anywhere else. Furthermore, the test body placed at the center is not in a stable equilibrium, because any small nudge that pushes it toward one of the two other masses, will cause the gravitational force to continue to pull it toward that mass.
The situation inside a hollow sphere is quite different. There, the force is zero everywhere inside the shell. A small perturbation or nudge to the position of the object, will not lead to an unstable situation in which the force gets larger in the direction of the small perturbation.
There is more "magic" going on with a hollow shell, than simply saying that every point on the shell has a corresponding point on the opposite side of the shell. This reflection symmetry only guarantees that the force is zero at the center of the shell, which as we have seen is a much weaker condition. The cancellation that leads to zero force inside the shell crucially relies on the fact that gravity is an inverse square law (the force is proportional to $r^{-2}$, the $-2$ is very important), which ultimately is balanced by the fact that the surface area of a sphere grows as $r^2$. If you work thorugh the details, you will find you need a more sophisticated argument, than the one you present in your question, in order to conclude that the force is zero everywhere inside the shell.


text:
Q: Set up a wifi network homepage just changing the router settings I have a Netgear Aircard router with the usual configuration options (port forwarding, DMZ, port filters,...).
I am using this network to provide wireless Internet access to the customers of my coffee shop. Is there a way to set up a homepage for my network, so that when someone connects to my network is automatically redirected to my homepage? Without changing the firmware, just changing the router settings?

A: Sounds like you're looking for something called a "Captive Portal" feature. If your router doesn't come with one out of the box, you have 2 options:

*

*Get a router that does come with the feature, or

*Depending on your router's model, flash it with custom firmware, like Tomato or DD-WRT
Please note that option #2 requires quite a bit of work, depends on the model of your router (some of them won't work at all) and may result in your router getting bricked. So... proceed with caution and read the documentation carefully!


text: Q: stop laptop from going to sleep when closed? stop laptop from going to sleep when closed? i trid to search it from https://duckduckgo.com/?q=stop+laptop+from+going+to+sleep+when+closed+ubuntu&t=canonical&ia=qa&iax=qa and the first command doesent work: up sudo -H gedit /etc/systemd/logind.conf but i get error sudo: gedit: command not found


text:
Q: Capybara/Selenium test for jquery autocomplete not working if Firefox is not made active I'm running into an issue with the following code in a capybara test (covering a jquery autocomplete select)
page.evaluate_script %Q{ $('.ui-menu-item a:contains("#{target}")').trigger("mouseenter").click(); }

When Firefox is made active while the test is running, the test passes.  When it remains inactive the test fails.  This appears to be documented in this issue but I am wondering if anyone has found a work around.
I'm on OS X 10.6.7 and have tried FF 4 and 3.6.10
Thanks in advance!

A: As an alternative way I'm using the capybara-webkit gem instead of selenium together with the headless gem and that works great for me.

A: Since you're on a mac, you can work around this by using applescript to force firefox to the front. Add the following line to your ruby code wherever you need firefox to be on top:
`osascript -e \"tell application \\\"Firefox\\\" to activate\"`

Taken from here: https://gist.github.com/2427601


text:
Q: Java files are shown weird in Android Studio editor I have installed Android Studio 1.4. Unfortunately Java files are shown weird in the editor like below:

This code is fine when I open the MainActivty.java. For example: when I open with notepad it looks like this:
package com.danishjo.helloworld;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

I use Java 8 JDk version jdk1.8.0_74.
Android Studio file format is UTF8
I don't want to reinstall the Android Studio.
Any help appreciated.

A: Go to Help > Check Update >
You need to update your android studio.
OR
Try Invalidate Cache and restart


text:
Q: How to increase volume on multiple MP3s at once? I know how to use Audacity to increase the volume of one MP3 at a time.  What I have is a folder of audio files and I'd like to increase the volume of all of them without the need to open each one separately in Audacity.
Any good solutions out there?

A: There are different types of gain control:

*

*Peak normalization will search for the part of the file with the highest amplitude, amplify the file to the loudest level possible and then amplify the rest accordingly. It's a pretty "stupid" technology in the sense of not making use of any psychoacoustics.

*Loudness normalization which brings the clip to a perceived loudness. EBU-R 128 is a standard that is used primarily in the broadcasting industry, and using it makes sure that all TV programs, for example, sound equally loud. (Mostly, except for ads maybe.)

*ReplayGain is an algorithm that analyzes the files on a psychoacoustic basis and amplify them accordingly, so they all have the same perceived loudness.

Using ffmpeg-normalize
(Disclaimer: I am the author of the program)
You can install a program called ffmpeg-normalize; all you need is Python and ffmpeg installed, then:
pip install ffmpeg-normalize

Now you can run:
ffmpeg-normalize *.mp3 -c:a libmp3lame -b:a 320k

This will loudness-normalize all MP3 files to a given target, and write them to the normalized folder.
I do not recommend doing this for your music collection though, as with MP3s you would have to re-encode all files and may lose quality in the process. Rather apply ReplayGain (see below).
Batch-Normalization with Audacity
If you want to normalize using the Audacity feature, you can do so using the Macro functionality. You can find an example Macro on this page.
Similarly, I would not recommend doing this if you could use ReplayGain.
ReplayGain
I assume you are on Windows, but this works for OS X as well:

*

*MP3Gain for Windows

*MP3Gain Express for OS X

*There's also a GUI for Linux
What does it do?

MP3Gain analyzes and adjusts mp3 files so that they have the same volume.
MP3Gain does not just do peak normalization, as many normalizers do. Instead, it does some statistical analysis to determine how loud the file actually sounds to the human ear.

It will analyze your files and make them as loud as possible, thereby equalizing all of them in terms of loudness. So normally, it should be enough to let this run on your library. MP3Gain includes a batch option for your convenience. They will not be re-encoded during this process and therefore not lose quality.
However, your car audio would need to support it. Try it out and let me know if it's not working.

A: MP3-Audio-Editor-v9.0.7
Batch converter > add files or folder > next > add command > amplify


text:
Q: JCache with Redisson, how serialization / deserialization works? I am using JCache with Redisson, it's not clear to me how serialization/deserialization works while using the cache.
When I setup the Cache via configuration I didn't setup anything about this. Is this done transparently?
The objects I am storing in cache are lists, objects from java.time for example, but I require all of objects of the classes I am storing in the cache implement Serializable, is this enough?
Looking at the data on redis it seems it is storing data serialized via java default serialization, am I wrong?
Can I control this behaviour? or it's better to leave it as it is ?
Thanks for help

A: As my comment, from redisson documentation Redisson use Kryo as default data serializer/deserializer.


text:
Q: How To Connect To Remote Server IP Using MSSQL2005? I have a following details provided by our mssql2005 database provider
Server IP : 100.20.255.34
Databaase name : insss
User: nas0
password : ymkv45SEv

i have the following connectionstring in my web.config file in my offline site as :
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

I want
how to edit my web.config connection string mentioned above using the details provided above so that it connect to my MSSQl2005 hosting provider .... ?
I don't know how to edit connection string to do that !!
When i run my site www.vbi.volvobusesindia.com then the following error occurs in top of the page ...

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

A: This should work just fine:
<add name="ConnectionString" connectionString="Data Source=100.20.255.34;Initial Catalog=insss;User ID=nas0;Password=ymkv45SEv;Integrated Security=False" providerName="System.Data.SqlClient"/>


text:
Q: On click slider next and previous button i get $curr[action] is not a function I am following this Js fiddle
http://jsfiddle.net/ryt3nu1v/10/
My Result:

I am making a slider that display age as I have an array that following ages
15,25,35,45,55
I am trying to display them in slider
expected behavior is to see the next age when i click on next button
Code that I used from fiddle according to my need is
          //Age slider
          $('div.result-age:gt(0)').hide(); //Hide all but the first one

var $allSlides = $('div.result-age'),
    traverseDefault = "first", //set the defaults
    actionDefault ="arrow-next";

$('.arrow-next,.selected-arrow-left-pointer').click(function(){

    var traverse = traverseDefault,
        action = actionDefault;

    if($(this).is('.selected-arrow-left-pointer')){ //if action is prev
        traverse = "last"; //set traverse to last in case nothing is available
        action = "selected-arrow-left-pointer"; //set action to prev
    }

    var $curr = $allSlides.filter(':visible'), //get the visible slide
        $nxtTarget =  $curr[action](".result-age"); //get the next target based on the action.

    $curr.stop(true, true).fadeIn(1000).hide(); //hide current one

    if (!$nxtTarget.length){ //if no next
        $nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
    }

    $nxtTarget.stop(true, true).fadeIn(1000); //show the target

});
          //age slider end

And this is my HTML

ALL ages here currently being display all at once

My current style is that age will be displayed in center with left and right sides having next and previous button
What am I missing?

A: Your v-for is creating mutliple h4 tag but you need create result div for each numbers so move your v-for inside your div tag .Then , you are using wrong values for actionDefault and action it should be next & prev where next refer to next slide and prev refer to previous slide not the classnames .
Demo Code :

$('div.result-age:gt(0)').hide();
var $allSlides = $('div.result-age'),
  traverseDefault = "first",
  actionDefault = "next"; //use next ..refer next node

$('.arrow-next,.selected-arrow-left-pointer').click(function() {
  var traverse = traverseDefault,
    action = actionDefault;
  if ($(this).is('.selected-arrow-left-pointer')) {
    traverse = "last";
    action = "prev"; //use prev..refer prev..
  }

  var $curr = $allSlides.filter(':visible');
  $nxtTarget = $curr[action](".result-age");

  $curr.stop(true, true).fadeIn(1000).hide();
  if (!$nxtTarget.length) {
    $nxtTarget = $allSlides[traverse]();
  }

  $nxtTarget.stop(true, true).fadeIn(1000);
});
span.next,
span.prev {
  cursor: pointer;
}

    <<

1

2

3

 >>

A: I found the issue, you were using arrow-next instead of next, and selected-arrow-left-pointer instead of prev.  Check the below working snippet. The data can be provided dynamically as you wish, currently I have given static data.
The next and prev are reserved keywords and hence the $curr[action] was expecting a function in return, while in your case it was `$curr['arrow-next'] instead of $curr['next'], which was returning undefined, and hence the error occurred.

//Age slider
      $("div.result-age:gt(0)").hide(); //Hide all but the first one

      var $allSlides = $("div.result-age"),
        traverseDefault = "first", //set the defaults
        actionDefault = "next";

      $(".next,.prev").click(function () {
        var traverse = traverseDefault,
          action = actionDefault;

        if ($(this).is(".prev")) {
          //if action is prev
          traverse = "last"; //set traverse to last in case nothing is available
          action = "prev"; //set action to prev
        }
        var currentData = $allSlides.filter(":visible"), //get the visible slide
          $nxtTarget = currentData[action](".result-age"); //get the next target based on the action.

        currentData.stop(true, true).fadeIn(1000).hide(); //hide current one

        if (!$nxtTarget.length) {
          //if no next
          $nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
        }

        $nxtTarget.stop(true, true).fadeIn(1000); //show the target
      });
.next, .prev {
  cursor: pointer;
}

<

ALL ages here currently being display all at once

2

3

4

5

>


text:
Q: Send message to other devices in Google Cloud Messaging I'm migrating from the deprecated Google Cloud Messaging to the latest version of "Google Play Services".
Before sending messages to other devices using the "Sender" class was gcm.jar.
Example: sender.send (msg, reg-id-device, retries);
Now I read that to send the message is required "GoogleCloudMessaging" class, and do not know how to send the reg-id-device I want.
I found this:
gcm.send (SENDER_ID + "@ gcm.googleapis.com", id, data);
I do not know where I should put the "reg-id-device".

A: Sender class is in gcm-server.jar and it's not deprecated.
The deprecated library gcm.jar is the client side library.
It is replaced by GoogleCloudMessaging class of the Google Play Services library. While this class has a send method,  it's only used for sending device to cloud messages from a device to your server.
If you don't need device to cloud messaging, you can continue to use the Sender class.


text:
Q: Hbase 1.1.2 compatible Cassandra version - Guava Jar version issue Trying to read data from HBase table and do some process and populate the data in Cassandra.
Facing problem with Guava Jar version, we are bounded to HBase version 1.1.2, which supports Guava 12.x version, But Cassandra is expecting latest version's of Guava more than 16 Version.
Update:
The reason we need to use HBase 1.1.2 is because we are going to use HDP 2.4.2 version , which supports HBase 1.1.2 version.


text:
Q: Rest Webservice vs Web application? I have recently gone through rest web services(mainly spring). But I did not find much difference between  rest based web service and web application.
In rest based web service, we have @RestControllerand in web application we have @Controller. The one difference  from dev perspective I know is in rest that we have more
verbs like PUT, DELETE etc. but in web app we mainly use POST/GET .  That is from receiver side. Even sender will just sends the http request for rest like sent in web application
Both maps the incoming url with method , mentions return format etc.
Yes there will be difference in authentication as in web application it will be form based authentication but web service it will be different like header based or something else.
So is there any major difference in protocol/sender/receiver or any perspective ?

A: From spring-frameworkrestcontroller-vs-controller
The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML
Rest of the things are more or less same

A: Web services are typically from application to application or machine to machine to exchange data it and the raw data usually is not human or browser friendly, ( encoded in json or xml or other agreed formats).  The encoded data maybe later transformed or wrapped into pretty web pages as an output to view object data to be browser human-friendly for viewing.


text:
Q: Azure DevOps CLI or API to get Organization Groups used in Projects In Azure DevOps I got a group "[test]\PermissionChecking" at organization level and I want to move this group "[test]\PermissionChecking" from organization level to project level. To do this, first I want to figure out where and all this Group "[test]\PermissionChecking" is used in a Azure DevOps project.
Is there any API or CLI to figure, where and all these group "[test]\PermissionChecking" is used or we have check it manually only?