text:
Q: Extra right margin on iPhone I'm editing our News site's mobile CSS file. On the iPhone 3gs, 4 & simulator there are some pages (not all) there is an extra right margin.
Here's an example of a page WITH the extra margin:
http://bit.ly/mMA2q7
..and here's an example of a page without it:
http://bit.ly/iQeOGY
Both pages are using the same template. I'm guessing the images are adding the extra margin.
Here is our mobile CSS file http://bit.ly/iW5JVm and viewport:
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=1;"/>

I tried applying different min-width values to the body but haven't found a solution.
Do you know how to get rid of this extra margin on the iPhone?

A: your photobanner div is too wide. It gets set to 500px which is way too much :)
try to add width:auto!important to it :)

A: Same problem, I fixed it adding this code in header:
<meta name="viewport" content="width=1100" />


text:
Q: how to calculate hours,minutes,second using javascript I have created an online examination system and I have put a countdown timer in online examination system. Below is my javascript code. Plz check

MY Question: coundown timer should start at 01:20:00 ,but in my case, countdown timer starts at 01:80:00 , why?  please check my javascript code

A: var minutes = hours * 60 + minute;
One hour and twenty minutes is 80 minutes in total. You should change that line to just have var minutes = minute;

A: In minutes, you are taking the total,
var minutes = hours * 60 + minute;
     80= 1*60 + 20

A: in less than 5 seconds i just found an answer: Javascript return number of days,hours,minutes,seconds between two dates
or JavaScript seconds to time string with format hh:mm:ss
So please just search a little bit before posting this kind of question

redpajama_set_name: RedPajamaStackExchange


text:
Q: What can I return in my transaction when no writes are made? I'm working with a database transaction in my angular/firebase project. It looks like this:
const transactionResult = await db.runTransaction(async trans => {
        // Get references:
        const parentGroupRef = db.collection('Groups').doc(parentGroupID);
        const childGroupRef = db.collection('Groups').doc(childGroupID);

        // Get documents:
        const promiseArray: Promise<any>[] = [];
        promiseArray.push(trans.get(parentGroupRef));
        promiseArray.push(trans.get(childGroupRef));
        const promiseResults: any[] = await Promise.all(promiseArray);

        // Get the group documents of the promise results:
        const parentGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === parentGroupID; })[0];
        const childGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === childGroupID; })[0];

        // Get data:
        if (parentGroupDoc && parentGroupDoc.exists && childGroupDoc && childGroupDoc.exists) {
            const parentGroupData = parentGroupDoc.data();
            const childGroupData = childGroupDoc.data();

            // Add child to parent and visa-versa:
            const results: any[] = [];
            if (parentGroupData.childGroupIDs.indexOf(childGroupID) === -1) {
                parentGroupData.childGroupIDs.push(childGroupID);
                const addChildResult = trans.set(parentGroupRef, parentGroupData, {merge: true});
                results.push(addChildResult);
            }

            if (childGroupData.parentGroupIDs.indexOf(parentGroupID) === -1) {
                childGroupData.parentGroupIDs.push(parentGroupID);
                const addParentResult = trans.set(childGroupRef, childGroupData, {merge: true});
                results.push(addParentResult);
            }

            if (results.length > 0) {
                return await Promise.all(results);
            } else {
                return Promise.reject('No changes made'); // <—- This line here
            }
        } else {
            console.log('Could not find parent or child group, or both.');
            return Promise.reject('Could not find parent or child group, or both.');
        }
    });

It essentially grabs two groups from the database—a parent group and a child group—then it attempts to add the child group to the parent group and visa-versa.
Before it does so, however, it checks to see if the parent group is already a part of the child group. If so, it skips the adding of the parent group to the child group. And similarly for add the child group to the parent group.
If both parent and child groups are already a part of each other, it doesn't add either. This is the condition I want to handle. I'm currently handling it by returning a rejected promise (the part where I commented "This line here"). But I don't want it to error in this case. If both groups are already a part of each other, I'd like it to simply return quietly. Therefore, I'd prefer to return a resolved promise. But this doesn't work. If I return a resolved promise, the transaction throws an error to the effect of:
TypeError: Cannot read property 'seconds' of null

I'm guessing if I resolve it to a transaction object (like what trans.set(…) returns), it will be happy. But how can I return a transaction object when I'm not doing any writes? Is there a null or default transaction I can create? Is there some other object I can return?
Thanks for any help.


text:
Q: How to know the device media volume is on mute or very low My App is playing sounds with Cordova media plugin and I realized I did hear nothing because the multimedia volume was on mute on my Android device! (Enabling it at the sound's settings screen fixed it)
Nevertheless, this can also happen to the end users. How can the App know the device volume is on mute or very low before playing audio for stating the user the volume is on mute or enabling it automatically?
There is a media.setVolume(1.0) method but it does not seem to work, at least in Android.

A: media.setVolume(1.0) is just the volume of the sound.
To get the device volume use https://github.com/Whebcraft/fm.radiant.cordova.utils.volume
VolumeUtils.setVolume(value, successCallback, failureCallback) - sets the volume from 0 to 100.
VolumeUtils.getVolume(function successCallback(value){
       alert(value);
       }, failureCallback);

- gets the volume from 0 to 100


text:
Q: ffmpeg time format : what does ".80" mean in 00:05:25.80 for ffmpeg? ffmpeg shows  an video duration is 00:05:25.80, what does ".80" mean in ffmpeg ?
Is it possible for ffmpeg to return the video duration in seconds rather than this format ?

A:
What does ".80" mean in ffmpeg?

Same as it does everywhere else, eight tenths and zero hundredths.
That is, the full duration is five minutes and twenty-five point eight seconds.

Is it possible for ffmpeg to return the video duration in seconds?

ffprobe uses seconds by default. What you're looking at in there in ffmpeg is just information for human convenience.
$ ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.mp4
325.800000


text:
Q: extract part of URL from parent URL For this url
"http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"

Trying to extract everything after enterprise/sites.
I want "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
I can get the filename like this:
var filename = parenturl.substring(parenturl.lastIndexOf("/") + );

But not sure how to extract from the middle..

A: Using lastIndexOf will fail for any URI reference with / in the fragment or query, as in http://example.com/foo/bar#/baz/boo.

Libraries like Google Closure's Uri module can make this easy.
new goog.Uri(parenturl).getPath()

If your library of choice doesn't have URI support, then http://www.ietf.org/rfc/rfc3986.txt appendix B suggests
var urlRegex = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var path = decodeURIComponent(urlRegex.exec(parenturl)[5]);

will get you the path part.

Once you've got the path, you can then strip off the /sites/ part by doing something like
var pathSuffix = path.replace(/^\/sites\//, '/');

A: I love Javascript with DOM element.
var link = document.createElement('a');
link.href = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";

link.protocol;
link.hostname;
link.port;
link.pathname;
link.search;
link.hash;
link.host;

link.pathname.replace(/^\/sites/,"") // "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"

A: The easiest thing might be to use javascript's Split() function and rebuild the string from the resulting array (leaving out the first couple items)
    var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
        var tokens = parenturl.split("/");

    for(var i=0;i<tokens .length;i++)
    {
        console.log(tokens [i]);
    }

A: Hows about:
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var filename = parenturl.match(/\/sites(.*)$/)[1];
alert(filename);


text:
Q: Tower of Hanoi recursive algorithm for four towers in Python I'm having a decent amount of trouble implementing the optimal algorithm for the tower of hanoi game for four stools in python.
First, in class we solved the tower of hanoi algorithm for three towers, for which we were given the following algorithm:

*

*Move all but the bottom disk from source to intermediate tower

*Move the bottom disk form the source to the destination

*Move all but the bottom disk from intermediate stool to destination tower

The actual code for this algorithm (with model being of class Model which has towers and disks, with a move method that moves disks from one tower to another) yields:
def move_disks(n, source, intermediate, destination):

    """Move n disks from source to destination
    @param int n:
    @param int source:
    @param int intermediate:

    @param int destination:
    @rtype: None
    """
    if n > 1:
        move_disks(n - 1, source, destination, intermediate)
        move_disks(1, source, intermediate, destination)
        move_disks(n - 1, intermediate, source, destination)
    else:
        model.move(source, destination)

Now for four stools, I'm given the following:

*

*Move n- i disks to intermediate stool using all four towers

*Move i disks from the original tower to the destination tower, using only three available towers

*Move n-i smallest disks from intermediate tower to destination tower

Manually playing around with disks and towers I got n-i = 2 if n>=3 and i = 1 if n =2. Since there are 4 possible sources and destinations, in my own function I have 5 arguments instead of 4:
def move_disks(n, source, intermediate, intermediate2, destination):

    """Move n disks from source to destination
    @param int n:
    @param int source:
    @param int intermediate:
    @param int intermediate2:
    @param int destination:
    @rtype: None
    """
    if n > 1:
        move_disks(n - i, source, intermediate 2 destination, intermediate)
        move_disks(1, source, intermediate, intermediate2, destination)
        move_disks(n - i, intermediate, intermediate2, source, destination)
    else:
        print("{} -> {}".format(source,destination)) # used to explicitly follow output in the console
        #model.move(source, destination) --> to be implemented when the function returns the right output

When I run it for n=3 I get:
1 -> 3
1 -> 2
3 -> 2
1 -> 4
2 -> 3
2 -> 4
3 -> 4

which gives the same number as moves as the solution for three towers.
The optimal solution for four stools should yield:
1 -> 3
1 -> 2
1 -> 4
2 -> 4
3 -> 4

The problem is definitely coming from my understanding of the algorithm so I've tried tracing function calls on a dry erasable board for a few hours to no avail.
Any tips or tricks for what else I should be doing or looking for to solve this algorithm? I'm honestly lost and a little bit discouraged.

A: I see two issues with your code.
The first is that you're using a variable i without defining it in the function. It probably has a global value in your environment, but perhaps not an appropriate one for the given n. You should probably have your function figure out what i should be and assign it as a local variable.
The second issue is that you're always recursing using the same four-tower function, while the algorithm you describe is supposed to use only three towers in the middle step. This probably means you should keep around your original function (in the first code block), and use a different name for your four-tower function.
If we name your first function move_disks3 and the second move_disks4, we can make it work:
def move_disks3(n, source, intermediate, destination):
    """Move n disks from source to destination
    @param int n:
    @param int source:
    @param int intermediate:
    @param int destination:
    @rtype: None
    """
    if n > 1:
        move_disks3(n - 1, source, destination, intermediate)
        move_disks3(1, source, intermediate, destination)
        move_disks3(n - 1, intermediate, source, destination)
    else:
        print("{} -> {}".format(source,destination))

def move_disks4(n, source, intermediate, intermediate2, destination):
    """Move n disks from source to destination
    @param int n:
    @param int source:
    @param int intermediate:
    @param int intermediate2:
    @param int destination:
    @rtype: None
    """
    if n > 1:
        if n > 2: # I'm not sure this picks the optimal i in all cases, but it does for n=3
            i = 2
        else:
            i = 1
        move_disks4(n - i, source, intermediate2, destination, intermediate)
        move_disks3(i, source, intermediate2, destination)
        move_disks4(n - i, intermediate, intermediate2, source, destination)
    else:
        print("{} -> {}".format(source,destination))

I'm not certain I understood your statements about the optimal i value, so you might need to make a few changes if I got something wrong there. But this code does work, and does give the desired results for n = 3 (and plausible results for a few higher n values I tested):
>>> move_disks4(3, 1, 2, 3, 4)
1 -> 2
1 -> 3
1 -> 4
3 -> 4
2 -> 4

A: def move4Poles(begin, end, temp1, temp2, disks):

    if disks == 1:
        print(begin, "to", end)
        return

    if disks == 2:
        move4Poles(begin, temp1, '_', '_', 1)
        move4Poles(begin, end, '_', '_', 1)
        move4Poles(temp1, end, '_', '_', 1)
        return

    if disks >= 3:
        move4Poles(begin, temp2, temp1, end, disks - 2)
        move4Poles(begin, end, temp1, '_', 2)
        move4Poles(temp2, end, temp1, begin, disks - 2)

move4Poles('A', 'D', 'B', 'C', 4)

A to B
A to C
B to C
A to B
A to D
B to D
C to B
C to D
B to D


text:
Q: JSF 2.0 dynamically add and delete a table row using a request bean I'm new to JSF (using it for my master thesis) and I'm trying to achive the following:
I want to dynamically add and delete a row from a table and to refresh only that part and not the entire page
My case:

*

*I have two h:forms in a page, the first one displays data from an object passed through views

*In the second h:form I have a p:dataTable and a input form to add data in the table. The add button is using an f:ajax event to render the second h:form after adding the input. Everything till now works...

The problem is, that everytime I want to add a new entry in the table the old ones are deleted, or I cannot add an entry to the table. The responsible bean for the page is a request scope bean and everytime I execute a render oder update for the page, a new bean is created...
How can I add a row (or delete one) without creating every time a new bean? I just want to keep the added data.
If needed I can provide the code for this stange behavior...
Thanks in advance

A: Two files....
demo.xhtml:
<h:head>

    <title> Student database </title>
</h:head>
<h:body>
    <h:form>

 The Student Database

        <h:dataTable value="#{stu.bookList}" var="o" style="color: black">

            <h:column>
                <f:facet name="header"> Student Id  </f:facet>#{o.id}
            </h:column>
            <h:column>
                <f:facet name="header"> Student Name  </f:facet>#{o.name}
            </h:column>
            <h:column>
                <f:facet name="header"> Phone No  </f:facet>#{o.phoneno}
            </h:column>
            <h:column>
                <f:facet name="header"> Address  </f:facet>#{o.address}
            </h:column>
            <h:column>
                <f:facet name="header"> Action</f:facet>
                <h:commandLink value="Delete" action="#{stu.deleteAction(o)}" /> /
                <h:commandLink value="Edit" action="#{stu.editAction(o)}" />

                    </h:column>
                 </h:dataTable>

To Add/Update Enter The Details

            Student Id :
            <h:inputText size="20" value="#{stu.book.id}" />

            Student Name :
            <h:inputText size="20" value="#{stu.book.name}" />

            Phone No:
            <h:inputText size="20" value="#{stu.book.phoneno}" />

            Address :
            <h:inputText size="20" value="#{stu.book.address}" />

            <h:commandButton value="Add" action="#{stu.addAction}" disabled="#{stu.enable}" />  <h:commandButton value="Update" action="#{stu.updateAction}" disabled="#{stu.disable}" />

    </h:form>
</h:body>

UserBean.java:
@ManagedBean(name = "stu")
@SessionScoped
public class UserBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Book book = new Book();
    private boolean disable=true;
    private boolean enable=false;
     private ArrayList<Book> bookList = new ArrayList<Book>();

    public UserBean() {
        book = new Book();

    }

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public boolean isDisable() {
        return disable;
    }

    public void setDisable(boolean disable) {
        this.disable = disable;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public ArrayList<Book> getBookList() {
        return bookList;
    }

    public void setBookList(ArrayList<Book> bookList) {
        this.bookList = bookList;
    }

    public void addAction() {

        System.out.println("Going to Add Data");

            bookList.add(book);
       book = new Book();
        System.out.println("The Data is Added Succesfully");

    }

    public String deleteAction(Book book) {
        System.out.println("Going to Delete Data");
        bookList.remove(book);
        System.out.println("The Data is Deleted Succesfully");
        return null;
    }

    public void editAction(Book book1) {
      setDisable(false);
      setEnable(true);
      book = new Book();
        book.setId(book1.getId());
        book.setName(book1.getName());
        book.setPhoneno(book1.getPhoneno());
        book.setAddress(book1.getAddress());

    }
public void updateAction(){
System.out.println("Going to update Data");
for (Iterator<Book> it = bookList.iterator(); it.hasNext();) {
          Book result = it.next();
            System.out.println(result.id);
            if (result.id == book.getId()) {
                System.out.println(result.id);
                System.out.println("address" + result.address);
                System.out.println("naame" + result.name);
                System.out.println(result.phoneno);

                result.setName(book.getName());
                result.setPhoneno(book.getPhoneno());
                result.setAddress(book.getAddress());
                book = new Book();
                 setDisable(true);
                 setEnable(false);
            }
            else{
              System.out.println("No Data To Update");
              setDisable(true);
            }


text:
Q: Rails: preloading a has_many through relation in the controller I hope I can explain this clearly.

*

*A User has_many notifications and has_many movies through
notifications. A movie has_many trailers.

*Notifications has 3 columns: user_id, movie_id, and website.

*On trailers#index, I am rendering @trailers and each @trailer renders
3 x ajax notification_forms (each form is just a single button, one for
each "website" option. When user clicks this button, an ajax request is sent to create a new notification record)

*I keep track of which buttons have been pressed (by looking up to see if a notification exists for that user/movie)

My concern is that because I'm only preloading the @trailers, I'm currently making 3 new DB calls on each iteration of a trailer.
_notification_form.html.erb (gets called 3 times on each trailer)
<% if trailer.movie.tracked?(current_user, "netflix") %>
   ## do some css stuff on the button to show notification already set

movie.rb:
def tracked?(user, website)
    user.notifications.where(movie_id: self.id, website: website).first
  end

So every time a trailer partial is rendered, I'm making 3 DB calls. What's the proper way to handle this situation?

A: Since you're only checking the status of the current_user and every Trailer knows its movie_id, you can just load the User's Notifications and check them for the Trailers' movie_ids:
tracked = current_user.notifications
tracked.detect { |n| n.movie_id == trailer.movie_id && n.website == 'netflix' }

If a User might have a ton of Notifications, you can limit the set to only Notifications for the Trailers on the page you're displaying:
tracked = current_user.notifications.where(movie_id: trailers.map(&:movie_id))

Load that up, and then just check it when you're deciding how to render your buttons. You can make it even more efficient by creating a Set containing [movie_id, website] pairs, which will do lookup in constant time.
tracked = Set.new(
  current_user.nofications
    .where(movie_id: trailers.map(&:movie_id))
    .pluck(:movie_id, :website)
)
tracked.include?([trailer.movie_id, 'netflix'])

This strategy will be fast for you because it's exactly tailored to the data you're checking. If you need something more flexible that still minimizes database queries, look into eagerly loading associations with includes, preload, and eager_load. 3 ways to do eager loading (preloading) in Rails 3 & 4 has an excellent description of the differences between those methods. Those all work during your initial relation loading (that is, if you've not yet loaded anything), but when you've already loaded part of the data (eg, you have Trailers but not Moviess or Notifications yet), you can use ActiveRecord::Associations::Preloader to efficiently load the rest.


text:
Q: Getting an error when trying to autofill input field from database based on a select option Script
$('#c1').change(function() {
                var serial = $(this).val();
                $.ajax({
                    type : "GET",
                    dataType: 'html',
                    url : "getserial.php",
                    data : {id:serial},
                    success :function(data) {
                        var result = $.parseJSON(data);
                        $('#c4').val(result.curr_serial);
                    }
                })
            })

HTML
<select name="c1" id="c1">
    <option value="">Select a type:</option>
    <option value="JC">JC - Jackets</option>
    <option value="PN">PN - Polo Neck</option>
    <option value="RN">RN - Round Neck</option>
</select>

<input type="text" class="form-control" name="c4" id="c4" maxlength="3">

PHP for getting serial number from the database.
require 'include/dbh.php';
$serial = $_REQUEST['c1'];
$sql = "Select `curr_serial` from serial where product='$serial'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
json_encode($row);

The error that I'm getting is :

Uncaught SyntaxError: Unexpected end of JSON input
   at Function.parse [as parseJSON] (<anonymous>)
   at Object.success (addproduct.php:383)

I am unable to understand where I've made the mistake.

A: Your AJAX success' callback doesn't receive any data. So $.parseJSON() fails.

*

*In your javascript, dataType: 'html' should be dataType: 'json'

*So you do not have to $.parseJSON(), and data will be an object in your success() callback function. See documentation (dataType section).

*In your PHP, write echo json_encode($row); instead of just json_encode($row);.

*Additionnaly, before to echo, apply header : header('Content-Type: application/json');


text:
Q: encrypted url in base64 i find a code to encrypt video url but only if the file is end with .mp4
so i want to make the code to work with picasa links i can do what or not??
<video controls>
   <source type="video/mp4 src="<?php echo getEncodedVideoString('mp4', 'https://lh3.googleusercontent.com/g2XMA9zsuKNRjLnid599v6HfYI-Io1TZaUDJUJskCp8=m22');?>">
</video>

<?php
function getEncodedVideoString($type, $file) {
   return 'data:video/' . $type . ';base64,' . base64_encode(file_get_contents($file));
}
?>


text:
Q: Replacement expressions I have the following expressions:
R[1, 1] R[2, 1] R[3, 1] R[4, 1]
sum[FF[3, ak[1] - ak[2], 1], EE[2, ak[2] - ak[3], 0], EE[2, ak[3] - ak[4], 0]]

By what procedure can I convert such expressions into expression:
sum[R[1, 1], FF[3, ak[2] - ak[2], 1], R[2, 1] , EE[2, ak[2] - ak[3], 0], R[3, 1] , EE[2, ak[3] - ak[4], 0] , R[4, 1]]

A: expr = R[1, 1] R[2, 1] R[3, 1] R[4, 1] sum[FF[3, ak[1] - ak[2], 1],
    EE[2, ak[2] - ak[3], 0], EE[2, ak[3] - ak[4], 0]];

expr /. a_ sum[b__] :> sum @@ Riffle[List @@ a, {b}]

sum[R[1, 1], FF[3, ak[1] - ak[2], 1], R[2, 1],
   EE[2, ak[2] - ak[3], 0], R[3, 1], EE[2, ak[3] - ak[4], 0], R[4, 1]]


text:
Q: Trouble with different kinds of polymorphism From what I learned so far, there are two kinds of polymorphism, compile-time, and runtime.
In compile-time, the polymorphed function or operator is resolved by compiler, while in runtime, its resolved at runtime.
Examples of compiile time polymorphism include function and operator overloading, and runtime polymorphism includes function overriding and virtual functions.
Additonally there are cases like Early binding and Late binding which I'm coming to later.
Consider the following code:
class base {
public:
    void Print() {
        std::cout << "This is parent class\n";
    }
};

class derived : public base {
public:
    void Print() {
        std::cout << "This is derived class\n";
    }
};

If I do this:
base b1;
b1.Print();
derived d1;
d1.Print();

the result is pretty obvious:
This is parent class
This is derived class

The real problem begins when I use a pointer to base class to operate on these functions.
base b1;
derived d1;
base* pb = &b1;
base* pb2 = &d1;
pb->Print();
pb2->Print();

The output would be:
This is parent class
This is parent class

This is due to Early binding, the compiler checks the type of object that is calling the function, not the type of object its processing. And pretty much obviously it is done in compile time. Now if I use the virtual keyword in the base class function definition, then I can do the above easily without any hassle, which is due to Late binding, which saves the function definition for runtime based on the type of object its processing. This is an example of runtime polymorphism.
Sorry for taking too long, my question is, is this the only way we can achieve runtime polymorphism? Also, if function overriding is runtime polymorphism, then the previous example (i.e, the one with Early binding) should also be runtime polymorphism since it is also doing function overriding.

A: Nothing forces you to use virtual functions in order to achieve run time polymorphism. In performance critical code often time see things like this to avoid the cost of a virtual function call:
void foo(Base * _b)
{
   if(_b->typeID == TID_BASE)
   {
       b->bar();
   }
   else if(_b->typeID == TID_DERIVED)
   {
       static_cast<Derived*>(_b)->bar();
   }
}

Where type id is either some form of enum or pointer that uniquely identifies a type. That said, I'd never recommend doing this unless you actually measured that it makes a performance difference in your case.
Regarding your last question. No, that is in no way late binding because your are not overriding any functions at all. In your example there is one Print function in the Base class and one in the Derived class. By casting your object to Base, you explicitly request the Base class Print function.


text:
Q: Can you extend a HTMLDivElement in TypeScript? I am making a DOM based game for the first time. I would like to extend HTMLDivElement, however in TypeScript, HTMLDivElement is an Interface.
I would like to do this pseudo class:
class QuizElement extends HTMLDivElement{

}

Sorry if this question is crazy. I am somewhat new to the DOM, and just thought, I can extend any visual class in any other environment so I guess it is do-able here!

A: Also you can 'extend' the HTMLDivElement interface with data members if you wish, not by using extends since it is not a class, but by adding it via the interface.  TypeScript interfaces are 'open ended', see page 85 of the spec under 'declaration merging'.
http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf
for example, the below adds the member 'mydata' of type string to the HTMLDivElement interface.
interface HTMLDivElement {

    mydata : string;

}

// now we can assign a value

 var div = <HTMLDivElement>document.getElementById("myDiv");

 div.mydata = "test";

A: A bit late, but apparently it's still not possible to extend HTMLDivElement. A simple way to solve extending a DIV: just use CSS to make a generic HTMLElement behave like a div.
CSS
 my-element {
    display:block;
 }

Javascript
class MyElement extends HTMLElement{
  constructor(){
      super()
      this.innerHTML = "I behave exactly like a div"
  }
}

window.customElements.define('my-element', MyElement);

A: Really late to the show, but these days yet another approach is possible. Rather than adding fields to the interface HTMLDivElement one can create a new interface like
interface QuizElement extends HTMLDivElement {
  quizScore: number;
  ...
}

and then create QuizElement objects like
const quizzi: QuizElement = Object.assign(document.createElement("div"), {
  quizScore: 0,
  ...
});

Compared to other proposed approaches, this does not "pollute" HTMLDivElement with additional fields in the scope of QuizElement.

A: You can't extend HTMLDivElement because it isn't declared as a class. This makes sense, because the underlying native type doesn't make sense to extend.
You have two alternative options.
Option 1: Implements!
Because HTMLDivElement is an interface, you can implement it...
class QuizElement implements HTMLDivElement {

You would have to implement all of the properties and methods of the interface. You probably don't want to do this.
Option 2: Delegation.
You can expose the specific properties and methods you want to make available on your QuizElement class and then delegate to an actual HTMLDivElement instance. Quick example below:
class QuizElement {
    private element: HTMLDivElement;

    constructor(id: string) {
        this.element = <HTMLDivElement>document.getElementById(id);
    }

    set innerHTML(content: string) {
        this.element.innerHTML = content;
    }
}

var quizElement = new QuizElement('quiz');

quizElement.innerHTML = 'Example';

A: It is not the best way but it works.
function MyElement(){
  var element = document.createElement("div");

  element.viewInner = function(){
    console.log(this, this.innerHTML)
  };

  return element;
}

var test = new MyElement();
test.innerHTML = "Hi";
test.viewInner(); // <div> Hi


text:
Q: How to create a zip installation file for a WordPress dynamic block? I've created a dynamic gutenberg block and I'm trying to create a installation zip file.
As it's a dynamic block, I need to include some PHP files which I've put in the files section of the package.json file:

    "files": [
        "/build",
        "plugin.js",
        "plugin.php",
        "functions-library.php"
    ],

If I run the npm command for the plugin-zip package, I get a zip file which includes the build directory but not the files that are also specified above.
Just wondering how I can include the specified files?
I've also tried creating the zip file manually, so it contains the above files and the build directory. The block installs OK and I've activated it. When I edit a page and try to add the block, I can't as it isn't listed as an available block. Does anyone else know what needs to be included in the zip file?
I've tried googling this but found practically nothing.


text:
Q: USB keyboard does not work for Ubuntu boot menu I wanted to perform a memory test on one of my desktop machines, but encountered a very strange problem: I can use the (usual) USB keyboard (tried Cherry Evolution Stream as well as an older one from Logitech) to open the BIOS (by pressing Del) and changing it, but not in the Ubuntu boot menu (where to select the language and keyboard type for pre-10.* Ubuntu versions). After Ubuntu booted, the keyboard is usable. I've also tried to use a different USB port, but without success.
Is this a known mainboard, BIOS or Ubuntu problem?

A: BIOS. Enable "Legacy USB Keyboard Support".


text:
Q: pygame.QUIT() - TypeError: 'int' object is not callable I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error.
import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Game")
    ship = Ship(screen)
    bg_color = (230, 230, 230)

    while True:
        gf.check_events(ship)
        ship.update()
        gf.update_screen(ai_settings, screen, ship)
        for event in pygame.event.get():
            if event.type==pygame.QUIT():
                sys.exit()
        screen.fill(ai_settings.bg_color)
        ship.blitme()
        pygame.display.flip()
run_game()

I'm aware that I'm accidentally calling some integer value but I have no clue where I'm going wrong.
I have also checked these lines

File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 25, in
run_game()
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 16, in run_game
gf.check_events(ship)
File "C:\Users\Areeb Irfan.PyCharmCE2018.3\config\scratches\game_functions.py", line 5, in check_events
if event.type==pygame.QUIT():
TypeError: 'int' object is not callable

A: As shown in your error message, this line event.type==pygame.QUIT() is the issue. The error TypeError: 'int' object is not callable means that you are trying to call an int, which means that you are trying to treat an int as a function, which in turn means that you have parentheses () after an int value. The only place you have parentheses in that line is afer pygame.QUIT, so just remove the parentheses:
if event.type==pygame.QUIT:

A: To fix that, remove the parentheses () at pygame.QUIT.
Get rid of them, and run the code again. It should work, as long as you don't have that same "if" somewhere else.

A: There is a flaw in your code. You have written as:
if event.type == pygame.QUIT():
        quit()

Better try using this code:
if event.type == pygame.QUIT():
        quit()

(or)
if event.type == pygame.QUIT():
        sys.exit()

This happens because pygame.QUIT is an integer data. Integer data is not followed by parantheses. But enclosing it with parantheses makes it to be a function which is wrong. Hope this helps you!


text:
Q: Java Runtime's exec() method is not executing correctly a shell script that invokes another shell script with redirect In my Spring-boot application, I am trying to trigger a shell script which in turns internally executes other shell script. I'm able to trigger my main script (say master.sh) using Runtime.getRuntime().exec(), but thereon any scripts being called within master.sh do not run. In fact, nothing happens (I only get the output of the master.sh script).
Inside Java code:
     Runtime rt = Runtime.getRuntime();
     Process proc = rt.exec(new String[] {"sh",
                    "/path_to_my_script/my_script.sh",
                    "--action="+action,
                    "--service="+service,
                    "--group="+groupsString,
                    "--username="+username,
                    "--desc='"+description+"'"});
            proc.waitFor();
            output = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = "";
            while ((line = reader.readLine())!= null) {
            output.append(line);
            if( line.contains("[") && line.contains("]") )
                    output.append(line.substring(line.indexOf("[") + 1, line.indexOf("]")));
            }

Inside my_script.sh I do different operations and then I finish executing the following lines:
printf "\n# -------------------------------------------- #\n"
printf "#           Executing my_script.sh script        #\n"
printf "# -------------------------------------------- #\n"

/path_to_other_script/wlst.sh <<+ > ${PWD}/output.txt
connect('username','password','10.0.0.0')
execfile('${PWD}/${pyScript}')
+

cat ${PWD}/output.txt

#rm -fr ${PWD}/${pyScript}
exit 0

Java can grab the first 3 lines (those with the printf) but the next execution /path_to_other_script/wlst.sh never executes and I don't understand why
I can call my script directly from command line and everything executes as expected and I'm able to double check the execution by doing a cat to output.txt
So, looks like exec is just understanding the execute of the "parent" process and not the child.
Any ideas?
I also tried to execute the script using ProcessBuilder with no luck:
ProcessBuilder pb = new ProcessBuilder("sh", "/u01/app/obieeWS/rest-webservices/obiee_scripts/obiee.sh",
                        "--action="+action,
                        "--service="+service,
                        "--group="+groupsString,
                        "--username="+username,
                        "--desc='"+description+"'");
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p=pb.start();

Thanks,


text:
Q: XPath evaluation in VBA (Excel) I have an xml file to be evaluated in Excel 2010.
The xml file looks as follows:
<Account>
    <Entry>
        <Value>5</Value>
    </Entry>
    <Entry>
        <Value>4</Value>
    </Entry>
    <Entry>
        <Value>-3.6</Value>
    </Entry>
</Account>

I want to sum over all values of every 'Entry' that fits some specified conditions. The evaluation which I need looks as follows:
sum(/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value)

I don't know how to get this evaluated in Excel.
What I get so far is a selection where I sum up over every item of it afterwards but there must be a better way to directly get the evaluation right? This is what I have already written:
Private Sub getSumOfValues()

Dim xmlFile As String
xmlFile = "..."

Dim xmlDoc As New MSXML2.DOMDocument60
Dim xmlSelection As IXMLDOMSelection

xmlDoc.async = False
xmlDoc.validateOnParse = True

xmlDoc.Load (xmlFile)

xmlDoc.setProperty "SelectionLanguage", "XPath"

Set xmlSelection = xmlDoc.SelectNodes("/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value")

Dim i As Integer
Dim sum As Double
sum = 0
Dim val As String

For i = 0 To xmlSelection.Length - 1
    val = xmlSelection.Item(i).Text
    val = Replace(val, ".", ",")
    sum = sum + CDbl(val)
Next i
Debug.print(sum)
End Sub

A: As far as I know, Msxml only supports evaluating XPath expressions that return a node set, there is no API to evaluate an XPath expression that returns a primitive value like a number. With MSXML, all you could is create and execute a stylesheet, that does an <xsl:value-of select="sum(...)"/>.
There are other XPath implementations like in the Microsoft .NET framework, that offer an Evaluate method. Whether you can use that from Office I am not sure.

A: Yes, there's a direct evaluation possible now via FilterXML
Using the newer FilterXML function it's possible since 2013/16

*

*to evaluate an XPath expression directly to an array and

*in a 2nd step to sum the resulting contents:

Example call
I added a further condition to sum only values greater 0; can be changed to your needs.
Sub EvalIt()
' Purp: Sum up over every <Value> node contents in a given xml file
' Help: https://learn.microsoft.com/de-de/office/vba/api/excel.worksheetfunction.filterxml

'a) get xml path
    Dim xmlfile As String
    xmlfile = "C:\Users\Admin\Documents\Stack\xml\test.xml"  ' << change to your needs
'b) define XPath (search string in XML including example condition > 0)
    Dim XPath As String
    XPath = "//Value[.>0]"
'c) show result via function getSum() ~> items greater zero: (5+4)=9
    Debug.Print "Sum of <Value> node contents greater 0 = " & _
                getSum(xmlfile, XPath)

End Sub

Function getSum()
Function getSum(ByVal xmlfile As String, ByVal XPath As String) As Double
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'   Assign xml values to 1-based 2-dim array via function FilterXML
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim arr As Variant
    arr = WorksheetFunction.FilterXML(getXMLContent(xmlfile), XPath)

''   (optional) reduction to "flat" 1-dim array
'    arr = Application.Transpose(Application.Index(arr, 0, 1))
''   (optional) display of single array values in VBE Immediate Window
'    Debug.Print Join(arr, "|")

'   return result
    getSum = Application.Sum(arr)

End Function

Help function getXMLContent() called by getSum()
This function gets the (well formed) xml content as string.
It distinguishes between
 - http:// Get calls using the WebService() function or
 - a local file path needing a direct load via MSXML (early bound in this example).
Function getXMLContent(ByVal xmlfile As String)
If Left$(xmlfile, 4) = "http" Then           ' a) URL
    getXMLContent = WorksheetFunction.WebService(xmlfile)
Else                                         ' b) a local file
    Dim xmlDoc As New MSXML2.DOMDocument60   ' early bound via Microsoft XML v6.0
    xmlDoc.Load xmlfile                      ' load xmlFile
    getXMLContent = xmlDoc.XML               ' return entire xml content string
End If
End Function

Caveat
I didn't include error handling for invalid file pathes or XPath constructions in order to allow a short, but clear view.


text:
Q: Prevent that text deselection requires double-click in NSTextView I have got a simple NSTextView inside a NSPopover. Most often selection and text editing works as suggested; i.e. i-beam cursor and current selection deselects when I click somewhere else inside the selection.
However, sometimes when the NSPopover is toggled the cursor is replaced with a pointer cursor and the selection won't disappear on click. While in this state the text is also draggable.
I want my NSTextView to behave just like in TextEdit and similar apps; the selection should never be draggable and should deselect on a single click. The cursor should also stay as i-beam.
How can I accomplish this behavior?
current and expected behavior, illustrated


text:
Q: How to close all query windows in DBeaver? DBeaver retains all results & sql editor windows when the program is closed.
The indicator showing tab overflow is easy to overlook (see pic). A user can accumulate an absurd number of tabs if they aren't paying attention & actively closing tabs after each session. I don't see an obvious way to do it and it's impractical to close them one by one.
How can I close all query windows in DBeaver?
I mean 'close' as in save nothing and close the query window completely.

A: You can right-click on any tab then choose "Close All":

In order to automatically close database object editors when exiting the application, you can uncheck this option: "Reopen database editors after restart":

Note that this will only close database editors (tables, schemas...) and it won't affect text editors. There's currently (DBeaver 5.1.2) no option to automatically close text editors when exiting the application. The feature request is tracked on this issue.


text:
Q: Invariant subspace in infinite dimensions Let $A(t)$ be a family of skew self-adjoint operator defined on some Hilbert space $H$ with common domain $D(A).$
The dependence on $t$ is in the strongly continuous sense, i.e. for all $x \in D(A)$ the map $t \mapsto A(t)x$ is continuous.
Consider the initial value problem
$$\varphi'(t)=A(t)\varphi(t)$$
with $\varphi(0)=\varphi_0.$
Assume that there is a dense subspace $X$ in $H$ that is contained in the domain of $A(t)$ for all $t$ and $A(t)X \subset X.$
I ask:
Let $\varphi_0 \in X$. Does this imply that $\varphi(t) \in X$ for all $t>0?$
This sounds very natural but I do not have any tools/ideas to show this at the moment.

A: In general, the answer is "no" even in the autonomous case, i.e. in the case where $A := A(t)$ does not depend on $t$.
First note that if $A$ generates a $C_0$-semigroup on $H$, if $X$ is a dense subspace of $H$ and if $X$ is invariant under this $C_0$-semigroup, then $X$ is even dense in $D(A)$ (which we endow with the graph norm); see for instance [Engel and Nagel: One-Parameter Semigroups for Linear Evolution Equations, Springer (2000), Proposition II.1.7].
Now let $H = L^2((0,1))$ and let $B$ be the Laplace operator on $H$ with periodic boundary conditions, i.e.
\begin{align*}
  D(B) & = \{u \in H^2((0,1)): \, u(0) = u(1) \text{ and } u'(0) = u'(1)\}, \\
  Bu & = u''.
\end{align*}
Note that $B$ is self-adjoint. Set $A := iB$ and let $X$ be the space of test functions on $(0,1)$. Then $AX \subseteq X$, but $X$ is not dense in $D(A)$ with respect to the graph norm; thus, $X$ is not invariant under the semigroup $(e^{tA})_{t \ge 0}$ generated by $A$.


text:
Q: verilog if-else error message I have a problem with verilog if-else statement. I'm trying to make a digital clock and my tick_counter module code like this. I pointed to error line with comment line. I cant find the solve, please help me.
module tick_counter(
input clk,
input tick_in,
output [3:0] ssd_2, ssd_4,
output [2:0] ssd_3
);
reg [5:0] count1, count_next1;
reg [2:0] count2, count_next2;
reg [3:0] count3, count4, count_next3, count_next4;

always@(posedge clk)
    begin
        count1 <= count_next1;
        count2 <= count_next2;
        count3 <= count_next3;
        count4 <= count_next4;
    end
//next state logic
always@*
    begin
        if(tick_in)
            begin
                if(count1==6'b111100)               //second counter
                    begin
                        count_next1 = 6'b0;
                        count_next2 = count2 + 1'b1;
                    end
                else
                    count_next1 = count1 + 1'b1;
                if(count2==4'b1001)                 //minutes counter of LSB digit
                    begin
                        count_next2 = 4'b0000;
                        count_next3 = count3 + 1'b1;
                    end
                else
                    count_next2 = count2 + 1'b1;
                if(count3==3'b101)                  //minutes counter of MSB digit
                    begin
                        count_next3 = 3'b000;
                        count_next4 = count4 + 1'b1;
                    end
                else
                    count_next3 = count3 + 1'b1;
                if(count4==4'b1001)                 //counter hour
                    begin
                        count_next4 = 4'b0000;
                    end
                else
                    count_next4 = count4 + 1'b1;
        else                                        //---THE POINT OF ERROR------
            begin
                count_next1 = count1;
                count_next2 = count2;
                count_next3 = count3;
                count_next4 = count4;
            end
    end
end

    assign ssd_2 = count2;
    assign ssd_3 = count3;
    assign ssd_4 = count4;

endmodule

A: Of course endmodule is missing. But this may be your typo mistake.
Proper indentation is greatly encouraged for large designs. Here, after indenting your code, I came to know that one end after the else part of // counter hour condition is missing. So, your main if condition's end is mis-placed. Just add end at the specified position and remove one end from the last of always block.
Kindly do proper indentation so that it becomes easy to debug.


text:
Q: Bulk update in Laravel I have a string with multiple update queries,
example:
$string = "UPDATE `student` SET `isams_id`=0001,`name`='stu name',`registration_id`='258911',`classid`=2,`section`='A',`house_name`='ELM',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258911'; UPDATE `student` SET `isams_id`=0002,`name`='xxx,`registration_id`='258912',`classid`=3,`section`='A',`house_name`='sss',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258912';"

Like this, I have around 2500 update queries in my string. For bulk update I am using DB::update( DB::raw($string));. But this returns error like,
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE `student` SET `isams_id`=0002,`name`='xxx',`registration_i' at line 1

How to resolve this. Please help me.

A: Hey you can do it like this
DB::update(DB::raw($string));

Also you have missed one single quote. It should be like this
$string = "UPDATE `student` SET `isams_id`=0001,`name`='stu name',`registration_id`='258911',`classid`=2,`section`='A',`house_name`='ELM',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258911'; UPDATE `student` SET `isams_id`=0002,`name`='xxx',`registration_id`='258912',`classid`=3,`section`='A',`house_name`='sss',`status`=1,`updated_at`='2018-06-29 06:49:15' WHERE `registration_id`='258912';"


text:
Q: Profiling .net multithreaded application (Visual Studio 2008) I recently installed (the eval of) Visual Studio 2008 TS in order to be able to get some profiling of an application done. Now I only find out how little I know about (real world) profiling, when applications are more complex than "Hello World".
My main problem is that the integrated debugger seems to add the time spent by all threads, so I get several times the total runtime, also certain functions (like sleep) show up several times, I assume since they are called by several threads.
Now my problem is: how can I make this easier to examine? There is only one thread I am interested in (the main one doing all the work), the others are simply waiting for certain stuff and are totally limited by the running time of my main thread. (They are in the same modules though and sometimes call the same functions.)
Is there any way to setup the profiling? Any way to handle the results in order to make them more meaningful for my scenario? Any other solution than VS 2008 (like 2010 or an external profiler)?
I am using instrumentation right now (gave me better results than sampling in my view) with C# under .net 3.5.

A: The ANTS Performance Profiler from Red Gate can filter profiling results by thread.
The documentation on Working with the call tree (specifically, the section "Changing the call-tree display options") shows a screenshot of where you can access the filter.


text:
Q: How to set placeholder for dropdown in react js? <select>
     <option selected disabled>Select</option

I added an extra option with a disabled property, but this gives me the following warning:

Use the defaultValue or value props on select instead of setting
  selected on option.

<select>
    {this.props.optionarray.map(function(e){
        return <option
                   value={e[self.props.unique]}
                   key={e[self.props.unique]}
               >
                   {e[self.props.name]}
               </option>
    })}
</select>

optionarray is an array which is passed through props to be mapped on each index which has an object and I pass the key through props as well which was in the array. Everything is working here, it's just showing me the warning that I mentioned above.
How do I remove that or how do I set a perfect placeholder for a dropdown in react?

A: Reason is, React provide a better way of controlling the element by using states, so instead of using selected with option use the value property of select and define its value in the state variable, use the onChange method to update the state, Use it in this way:
class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            value: '1'
        };
    }

    render(){
       return(
           <select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
              <option value='1' disabled>Select</option>
              {
                  [2,3,4].map((i,j)=>{
                      return <option key={i} value={i}>{i}</option>
                  })
              }
           </select>
       );
    }
}

How to set placeholder for dropdown?

According to Mozilla Dev Network, placeholder is not a valid attribute on a <select>. So in place of that you can you this also to render a default option:
<option default>Select</option>
Use of key as per DOC:

Keys help React identify which items have changed, are added, or are
  removed. Keys should be given to the elements inside the array to give
  the elements a stable identity.

Suggestion:
Whenever we create any ui dynamically in loop, we need to assign a unique key to each element, so that react can easily identify the element, it basically used to improve the performance.
Check the working example:

class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        value: '1'
    };
}

render(){
   return(
       <select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
          <option value='1' disabled>Select</option>
          {
              [2,3,4].map((i,j)=>{
                  return <option key={i} value={i}>{i}</option>
              })
          }
       </select>
   );
}
}

ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

Check the fiddle for working example: https://jsfiddle.net/29uk8fn0/

A: Functional Component
import { useState } from "react";

export default function DropdownComponent(props) {

  const [formData, setFromData] = useState({
    anyInput: "something",
    dropdownInput: null,
  });

  return (
          <>
            anyInput: { formData.anyInput }
            dropdownInput: { formData.dropdownInput }
            <select name={"dropdownName"} onChange={ ({target})=> {
                    setFromData((prev)=> ({...prev, dropdownInput:target?.value}) );
                }
            }>
                <option key='blankKey' hidden value >Placeholder Text for Select</option>
                {
                    [2,3,4].map((i,j)=>{
                        return <option key={i} value={i}>{i}</option>
                    })
                }
            </select>
          </>
         )
}


text:
Q: NS-3 Sniffing Passive ACKs I am editing the AODV module in NS-3.
When a node forwards a data packet to the next node, I want my AODV module to listen to overhear next node's forwarding process to make sure it is forwarding it right.
The pcap file correctly sniffs next node's transmission, but I cannot get my hands on it from the AODV module.
I am guessing that the packet is being dropped since it is not supposed to be involved on it, thus I want to know how to change that.
Can anyone give me clues on where to look to change any relevant codes?
Thanks

A: Overhearing can be accomplished by hooking one of the Wi-Fi device trace sources.  The MonitorSnifferRx in the WifiPhy object is probably what you want.  There are two steps:  1) obtain a pointer to the Wi-Fi Phy somehow, and 2) attach a callback function to that trace source.
Step 1) is already mostly done in Aodv in an existing method:
RoutingProtocol::NotifyInterfaceUp ()
...
// Allow neighbor manager use this interface for layer 2 feedback if possible
Ptr<WifiNetDevice> wifi = dev->GetObject<WifiNetDevice> ();

From this point, you can get a Phy object pointer:
Ptr<WifiPhy> phy = wifi->GetPhy();

From here, you will want to use TraceConnectWithoutContext() to hook the trace souce, with a callback that has a matching function signature to what the MonitorSniffRx trace expects.
phy->TraceConnectWithoutContext ("MonitorSniffRx", MakeCallback (&InsertYourCallbackFunctionHere));

See how the Mac-level trace source "TxErrHeader" is similarly hooked in that same method.


text:
Q: Extjs 4 FiltersFeature vs stateful grid I have a grid with some columns with filters.
columns defination:
columns:[{
                text: "Number",
                dataIndex: 'clientreference',
                width: 200,
                filter: true,
                sortable: true
            },

here is filter feature defination
features: [{
                ftype: 'filters',
                encode: true,
                local: false
            }],

The problem is: When i'm trying to save state of grid, filters are not working: When I adding this code to a grid:
stateful: true,
stateId: 'documentsGrid',

I refresh the page and all works fine, because i dont have state in my cookies.
But when I refresh the page second time - state loads from cookies and filters are not working.
If i remove stateful: true and refresh page, filters are working fine.
Any suggestions?
Also I noticed, that all examples in extjs site are only with filters or with stateful grid, but there is no one example with both.
UPDATED:
The most useful way was making my own method for saving state of elements I need and to restore it.

A: I think you are specifying features in grid.But you can specify filters in store directly.So try to define filters in store and stateful in grid config options.Hope you may get the solution to come out from this.


text:
Q: sonarqube 5.6.4- break build in preview mode I have just upgraded sonar to 5.6.4 and I want break my build through build breaker or any other way in preview mode? I checked in preview mode report-task.txt is not getting generated while in publish mode it is, can some suggest?

A: What you want is not possible.
BuildBreaker looks at the project's Quality Gate status. The Quality Gate is only updated on the server side, after the analysis report submitted to the server has been processed. Preview mode does not submit an analysis report to the server (kinda the point), so there will be no Quality Gate update.


text:
Q: horizontal responsive layout I was trying to achieve a horizontal responsive layout here http://ragzor.com/neutron for like 5 hours now lol , I could do this using jquery but i believe thats using a screwdriver to do a hammer's job :) using floats just does not do anything and I also tried using position absolute and relative , absolute breaks the slides since they are using max-width(i guess this is the reason not sure tho!)
so what will be the best way to do this?
thanks alot!!!

A: @Dinesh is right. You should start with some tutorials on Responsive Design. These are all almost guaranteed to contain CSS3 Media Queries. You can find an aggregate of Responsive Design tutorials here: http://www.hongkiat.com/blog/responsive-web-tutorials/. Using floats can be tricky / dangerous when desiring a large amount of Responsive Design because floating elements removes them from the documents flow. Hope this helps!


text:
Q: Office Excel add-in (web app) load/save document With the new Office Excel add-in model, there is a way to do the following on any platform (online, desktop and iOS):

*

*load a document from the server?

*save the document back to the server (we can use DOcument.getFileAsync, but this method is not supported on iOS host https://dev.office.com/reference/add-ins/shared/document.getfileasync)?

We have managed to successfully implement all the above for Word documents.


text:
Q: Jquery - Toggle Input text after checkbox I have this code which works perfectly, It can toggle an input when checkbox is checked.
https://jsfiddle.net/majmo6r4/
But, if one day I want to add more checkboxes, I have to duplicate my code and that's not what I want. I want to improve my code in order to have the same feature with each checkboxes without create another class and duplicate my if statement and variables on my js file.
I had an idea like this :
(function($){
function $test() {
    let $cbs = $(".cbTeam");
    $cbs.each(function () {
        let $inputs = $('.inputTeam');
        if($cbs.siblings().is(':checked')) {
            $inputs.css("display", "flex");
        } else {
            $inputs.css("display", "none");
        }
    });
}
$(this).click($test);
}(jQuery));

For each checkboxes, I can toggle his input, so I need to consider that the checkboxes has the same class name and for the inputs too.

            Jeux - Préférences

                        <input type="checkbox" class="cbTeam" value="">Hearthstone
                        <input type="text" class="form-control inputTeam" placeholder="Equipe Hearthstone">

                        <input type="checkbox" class="cbTeam" value="">League of Legends
                        <input type="text" class="form-control inputTeam" placeholder="Equipe LoL">

            <button type="submit" class="btn btn-default">S'inscrire</button>

Thank you for taking time to my problem, I hope there's enough informations and have a nice day full of code :)
P.S. I want to say "Hello" at the start of the topic but it disappear when i publish the message :(

A: You can show/hide the input text by using $(this).parent().next()
$(this) - will return to the current checkbox being clicked.
$(this).parent() - will return the parent of the checkbox. Which is  based on your html code.
$(this).parent().next() - will return the next element of the parent which is input text.
Basically, you are trying to locate the input text (one step at a time) and do some actions on it.
Since you already locate the right element(text input), you can now do actions like show() or hide(). Example: $(this).parent().next().hide()

The text input is the next element of the checkbox's parent.

$(document).ready(function() {
  $(".checkbox input[type=checkbox]").click(function() {
    if ($(this).is(":checked")) $(this).parent().next().show();
    else $(this).parent().next().hide();
  });

  //Hide inputs initially
  $(".checkbox input[type=text]").hide();
});

  Jeux - Préférences

      <input type="checkbox" class="cbHs" value="">Hearthstone

    <input type="text" class="form-control teamHs" placeholder="Equipe Hearthstone">

       <input type="checkbox" class="cbTeam" value="">League of Legends

    <input type="text" class="form-control inputTeam" placeholder="Equipe LoL">

  <button type="submit" class="btn btn-default">S'inscrire</button>


text:
Q: error C2327: not a type name, static, or enumerator I am facing "error C2327" on windows.
I reduced my code and get similar error with test program
#include <boost/intrusive/list.hpp>
#include <iostream>

class Test {
protected:
         typedef Test self_type;
         boost::intrusive::list_member_hook<> order_hook;
public:
         typedef boost::intrusive::member_hook<self_type,
                            boost::intrusive::list_member_hook<>,
                            & Test::order_hook > order_hook_type;
};

This works fine on g++ but on windows it's giving following error:
test.cpp(11) : error C2327: 'Test::order_hook' : is not a type name, static, or enumerator
test.cpp(11) : error C2065: 'order_hook' : undeclared identifier

Please help. What i am missing for windows?

A: tl;dr: Visual Studio is right — you can't put that typedef there.
The Boost documentation gets this right, but doesn't explain why.

[C++11: 14.3.2/1]: A template-argument for a non-type, non-template template-parameter shall be one of:

*

*for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

*the name of a non-type template-parameter; or

*a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

*a constant expression that evaluates to a null pointer value (4.10); or

*a constant expression that evaluates to a null member pointer value (4.11); or

*a pointer to member expressed as described in 5.3.1.

[C++11: 5.3.1/3]: The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type "pointer to member of class C of type T" and is a prvalue designating C::m. [..]

[C++11: 8.3.3/2] gives an example of a pointer-to-member for an incomplete type being valid for as long as the pointer-to-member is not actually initialised, and though not explicitly stated, the implication is that to actually take the address of some C::m, C must be a complete type. Indeed, until C is a complete type, C::m does not really exist.
There are some similar rules that are clearer:

[C++11: 9.2/10]: Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.

At the point of your typedef, Test is not a complete type:

[C++11: 9.2/2]: A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

Therefore, you cannot use that pointer-to-member at that place. You must write the typedef so that it appears after the closing } of the class definition, or make the pointed-to object non-member, or static member.
GCC must have a bug or extension in this regard, since the following testcase compiles and executes successfully:
template <typename B, int B::* PTM>
struct A {};

struct B
{
    int x;

    typedef A<B, &B::x> a;
};

int main() {
    B b;
}

whereas Visual Studio 2012 Express correctly outputs:

1>------ Build started: Project: test1, Configuration: Debug Win32 ------
1>  test.cpp
1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2327: 'B::x' : is not a type name, static, or enumerator
1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2065: 'x' : undeclared identifier
1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2975: 'PTM' : invalid template argument for 'A', expected compile-time constant expression
1>          f:\documents\visual studio 2012\projects\test1\test1\test.cpp(1) : see declaration of 'PTM'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

A: tl;dr: Visual Studio has a bug: your code is legal.

[C++11: 14.3.2/1]: A template-argument for a non-type, non-template template-parameter shall be one of:

*

*for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

*the name of a non-type template-parameter; or

*a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

*a constant expression that evaluates to a null pointer value (4.10); or

*a constant expression that evaluates to a null member pointer value (4.11); or

*a pointer to member expressed as described in 5.3.1.

  [C++11: 5.3.1/3]: The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type "pointer to member of class C of type T" and is a prvalue designating C::m. [..]
[C++11: 3.4.3.1/1]: If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class (10.2), except for the cases listed below. The name shall represent one or more members of that class or of one of its base classes (Clause 10). [ Note: A class member
  can be referred to using a qualified-id at any point in its potential scope (3.3.7). —end note ] The exceptions to the name lookup rule above are the following:

*

*a destructor name is looked up as specified in 3.4.3;

*a conversion-type-id of a conversion-function-id is looked up in the same manner as a conversion-type-id in a class member access (see 3.4.5);

*the names in a template-argument of a template-id are looked up in the context in which the entire postfix-expression occurs.

*the lookup for a name specified in a using-declaration (7.3.3) also finds class or enumeration names hidden within the same scope (3.3.10).

None of the exceptions apply here, so we look at the class member's "potential scope":

[C++11: 3.3.7/1]: The following rules describe the scope of names declared in classes.

*

*The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration, but also of all function bodies, brace-or-equal-initializers of non-static data members, and default arguments in that class (including such things in nested classes).

*[..]

GCC correctly compiles and executes the following testcase:
template <typename B, int B::* PTM>
struct A {};

struct B
{
    int x;

    typedef A<B, &B::x> a;
};

int main() {
    B b;
}

whereas Visual Studio 2012 Express incorrectly errors out:

1>------ Build started: Project: test1, Configuration: Debug Win32 ------
  1>  test.cpp
  1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2327: 'B::x' : is not a type name, static, or enumerator
  1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2065: 'x' : undeclared identifier
  1>f:\documents\visual studio 2012\projects\test1\test1\test.cpp(8): error C2975: 'PTM' : invalid template argument for 'A', expected compile-time constant expression
  1>          f:\documents\visual studio 2012\projects\test1\test1\test.cpp(1) : see declaration of 'PTM'
  ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

A: use a function_hook instead. basically this allows you to take the address of the member variable in the body of a static function which can be defined outside the body of class Test.
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/parent_from_member.hpp>

class Test {
protected:
     boost::intrusive::list_member_hook<> order_hook;
private:
     struct hook_access
     {
         typedef boost::intrusive::list_member_hook<> hook_type;
         typedef hook_type* hook_ptr;
         typedef hook_type const* const_hook_ptr;
         typedef Test value_type;
         typedef value_type* pointer;
         typedef value_type const* const_pointer;

         static hook_ptr to_hook_ptr( value_type& i_value )
         { return & i_value.order_hook; }
         static const_hook_ptr to_hook_ptr( value_type const& i_value )
         { return & i_value.order_hook; }
         static pointer to_value_ptr( hook_ptr i_hook );
         static const_pointer to_value_ptr( const_hook_ptr i_hook );
     };
     friend struct hook_access;
public:
     typedef boost::intrusive::function_hook< Test::hook_access > order_hook_type;
};

Test::hook_access::pointer
Test::hook_access::to_value_ptr
( Test::hook_access::hook_ptr i_hook )
{ return boost::intrusive::get_parent_from_member< Test >( i_hook, & Test::order_hook ); }

Test::hook_access::const_pointer
Test::hook_access::to_value_ptr
( Test::hook_access::const_hook_ptr i_hook )
{ return boost::intrusive::get_parent_from_member< Test >( i_hook, & Test::order_hook ); }


text:
Q: Solving a linear system of ODEs given by a matrix product Is there a simple way to solve the system of differential equations
$$
\mathbf{P}'(t) = \mathbf{G} \mathbf{P}(t),
$$
where $\mathbf{P}(t) = (p_{ij}(t))_{i,j \in \{1,2,\ldots, n\}}$ is an $n \times n$ matrix of functions and $\mathbf{G}$ is an $n \times n$ matrix of (real) constants? Of course, some extra hypothesis might be required of $\mathbf{G}$ (e.g. distinct eigenvalues) in order for there to be a simple (or even general) solution. Just let me know if that's the case.
I've only seen systems of the form
$$
\mathbf{x}' = \mathbf{G} \mathbf{x},
$$
where now $\mathbf{x}$ is a $n\times 1$ vector instead of an $n \times n$ matrix.

A: Your case is not more difficult than the case $x'=Gx$ since the different columns do not interfere. Just apply the theory for $x'=Gx$ column-wise.


text:
Q: React Router v4: Component and Children in the same route I am a beginner with react and have upgraded a base project to react router v4. The app seems to be working fine, but I am always getting the following warning:
Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored
This is my app (leaving some imports out for readability):
index.js
ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
        <BrowserRouter>{routes}</BrowserRouter>
    </Provider>
    , document.getElementById('root')
);

routes.js:
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Link
} from 'react-router-dom';

export default (

      <Route path="/topics/create" component={CreateTopicView}> </Route>
      <Route path="/topics/search" component={SearchTopicsView}> </Route>
      <Route path="/topics/manage" component={ManageTopicsView}> </Route>
      <Route path="/moderation/pre" component={ModerationPreView}> </Route>
      <Route path="/moderation/post" component={ModerationPostView}></Route>
      <Route path="/dashboard" component={DashboardView}> </Route>
      <Route exact={true} path="/" component={DashboardView}> </Route>

);

main.js:
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

class Main extends React.Component {
    static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }

    render() {
        let wrapperClass = "gray-bg " + this.props.location.pathname;
        return (

                <Progress />
                <Navigation location={this.props.location}/>

                    <TopHeader />

                    {this.props.children}

        )
    }
}

export default withRouter(Main)

The idea is that most components in the Main component (e.g. the Navbar) should always be loaded, also the Navbar needs to know the current path so it can display the current selection.
Then between the TopHeader and Footer the variable content should be shown based on the path.
What am I doing wrong, how can I solve the warning about Route Component and Route Children in the same path?

A: As Shubham Khatri mentioned in the comment, the warning was caused by a space I had after the route opening tag:

Thats because you have space between your Routes. which behave as a
  children and routes in v4 are not suppose to have children <Route
  path="/topics/create" component={CreateTopicView}>{/* you have space
  here */}</Route>

Changing the Route definitions to
<Route path="/topics/create" component={CreateTopicView}></Route>

or
<Route path="/topics/create" component={CreateTopicView} />

fixed the warning


text:
Q: Android listview insert the deleted Value in same position I am working in list view. In it, there are two lists such that if I select a value from base list, it will add to the child list and remove the item from base list, all are working fine. My query is delete list item from child list it will re-add to the base list.
            contacts = jsonObj.getJSONArray(TAG_PRODUCTLIST);
            for (int i = 0; i < contacts.length(); i++)
            {
                JSONObject c = contacts.getJSONObject(i);
                Object id = c.get(TAG_CATID);
                Object em = c.get(TAG_CAT);
                contact1 = new HashMap<>();
                contact1.put(TAG_CATID, id);
                contact1.put(TAG_CAT, em);
                JSONArray productss = c.getJSONArray(TAG_PRODUCT);

                worldpopulationlist.add(new QuoteSectionItem(em.toString()));//listview section

                for (int j = 0; j < productss.length(); j++)
                {
                    JSONObject d = productss.getJSONObject(j);
                    Object pid = d.get(TAG_PID);
                    Object price = d.get(TAG_PRICE);
                    Object pn = d.get(TAG_PNAME);
                    contact = new HashMap<>();

                    contact.put(TAG_PID, pid);
                    contact.put(TAG_PRICE, price);
                    contact.put(TAG_PNAME, pn);
                    contact.put(TAG_PDESC, pn);
                    Quote_Products worldpopulation = new Quote_Products(id,em,pid,pn,price);//listview item

                    worldpopulationlist.add(worldpopulation);

                } }

this is base list creation and i create child list like`                    SparseBooleanArray selected = listviewadapter.getSelectedIds();
                for (int i = (selected.size() - 1); i >= 0; i--)
                {
                    if (selected.valueAt(i))

                    {

                    QuoteItem selectedI = listviewadapter.getItem(selected.keyAt(i));

                    Quote_Products selecteditem = (Quote_Products) selectedI;

                    System.out.println("Selected Items : "+selecteditem.getCountry());
                    System.out.println("Selected Items : "+selecteditem.getRank());
                    System.out.println("Selected Items : "+selecteditem.getPopulation());

                        System.out.println("Products:"+product);
                        productList.add(product);
                        Quote_SelectedProducts worldpopulation1 = new Quote_SelectedProducts(
                                selecteditem.getCidid(),
                                selecteditem.getCname(),
                                selecteditem.getRank(),
                                selecteditem.getCountry(),
                                selecteditem.getPopulation());
                        worldpopulationlist1.add(worldpopulation1);
                        listviewadapter.remove(selecteditem);

                    }

                }

`
after this are successfully done i need to to how to to reinsert the list value once delete value form child list
                    SparseBooleanArray selected = listviewadapter1.getSelectedIds();

                    for (int i = (selected.size() - 1); i >= 0; i--)
                    {
                        if (selected.valueAt(i))
                        {
                            Quote_SelectedProducts selecteditem = listviewadapter1.getItem(selected.keyAt(i));
                            listviewadapter1.remove(selecteditem);

                            System.out.println("Delete after ignore "+selecteditem.getCidid());
                            System.out.println("Delete after ignore "+selecteditem.getCname());
                            System.out.println("Delete after ignore "+selecteditem.getRank());
                            System.out.println("Delete after ignore "+selecteditem.getCountry());
                            System.out.println("Delet after ignore "+selecteditem.getPopulation());

                            Quote_Products worldpopulation = new Quote_Products(selecteditem.getCidid(),
                            selecteditem.getCname(),selecteditem.getRank(),
                            selecteditem.getRank(),selecteditem.getPopulation());
                            System.out.println(" EEE "+String.valueOf(worldpopulation));
                            worldpopulationlist.add(worldpopulation);
                            System.out.println(" EEE "+String.valueOf(worldpopulationlist));
                        }

the value delete from child list how to re insert the child list value in the base list
Thanks in advance


text:
Q: Some images don't get linked when setting link-to to media-image When inserting images into posts I have some images which refuse to recognize their link-to setting. The setting is properly saved and I also tried switching to a none setting and back, but with no effect. This only occurs for some images, regardless of the other settings and the context where it is inserted. Any clues what my cause this?
EDIT: By some images I mean just random images. There are Jpegs (there might be some png, but this seems not to be related) like the others which work with description or without. They are all uploaded from the media library or directly from the post. Re-uploading seems to fix the issue, but it reoccurs from time to time with new images.
To make this issue even more weird: It works when I remove the description-text for those images, but when I add it again (or a single letter for testing purposes), it does not work anymore.
EDIT 2:
Also cropping, flipping or other file-modifications don't affect the described behavior for those images.
EDIT 3: Probably because of using the custom-upload-dir-extension some of my guids seem to be messed up and some of those files are the ones which are problematic.
EDIT 4: Even with removing the custom-upload-dir-extension the problem still occurs, for new and old images...


text:
Q: Full Calendar Jquery with Google calendar API v3 I am using the Jquery Full calendar plugin with Google Calendar. Google calendar returns me a Json response of Events List but Events are not displayed in my Calendar but display the success alert. i donot know why it misses my Events.
HRBC.controllers.Calendar = function () {
    this.load = function (calendarId, tempURL, tempToken) {
        $(calendarId).fullCalendar({

            eventSources: [{
                url: tempURL,
                type: 'GET',
                beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + tempToken); },
                dataType: 'json',
                success: function (response) {
                    alert('Very Good');
                    console.log(JSON.stringify(response));
                },
                error: function (response) {
                    alert('error');

                }
            }],

            cache: true,
            eventClick: function (event) {
                // opens events in a popup window
                window.open(event.url, 'gcalevent', 'width=700,height=600');
                return false;
            },

            loading: function (bool) {
                if (bool) {
                    $('#loading').show();
                    setTimeout(function () {
                        $('#calendar').fullCalendar('render');
                    }, 1);

                } else {
                    $('#loading').hide();
                }
            }

        });
    }
}


text:
Q: Convert (doublebyte) string to Hex Let's say I have the word "Russian" written in Cyrillic. This is would be the quivalent of the following in Hex:
Русский

My question is: how do I write a function which will go from "Russian" in Cyrillic to it's hex value as above? Could this same function work also for singel byte characters?

A: The 〹 thingies are called HTML Entities. In PHP there is a function that can create these: mb_encode_numericentityDocs, it's part of the Multibyte String extension (Demo):
$cyrillic = 'русский';

$encoding = 'UTF-8';
$convmap = array(0, 0xffff, 0, 0xffff);
$encoded = mb_encode_numericentity($cyrillic, $convmap, $encoding);

echo $encoded; # русский

However: You need to know the encoding of your Cyrillic string. In this case I've chosen UTF-8, depending on it you need to modify the $encoding parameter of the function and the $convmap array.

A: Your provided example isn't hex, but if you want to convert to hex, try this:
function strToHex($string)
{
    $hex='';
    for ($i=0; $i < strlen($string); $i++)
    {
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}

function hexToStr($hex)
{
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2)
    {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

echo strToHex('русский'); // d180d183d181d181d0bad0b8d0b9


text:
Q: Tizen native service app to check if another app is running In Samsung gear S3, I want to develop a Tizen native service application which continously checks if a web application is running or not and launches the web application if its not running.
By continously, I mean it can be either checking every minute or adding an event listener (for state change of application).
I wanted to do this because my web application is getting terminated after some time (may be after a day or so) but I want it to run always in background.
Right now,I was able to launch the web application from service application with the following code.
app_control_h app_control;
int ret = APP_CONTROL_ERROR_NONE;
ret = app_control_create(&app_control);

if (ret != APP_CONTROL_ERROR_NONE)
   dlog_print(DLOG_ERROR, LOG_TAG, "app_control_create() is failed. err = %d", ret);

ret = app_control_set_operation(app_control, APP_CONTROL_OPERATION_VIEW);

if (ret != APP_CONTROL_ERROR_NONE)
   dlog_print(DLOG_ERROR, LOG_TAG, "app_control_set_operation() is failed. err = %d", ret);

app_control_set_app_id(app_control, "08CCMUEFHN.ROAMMprompt");

ret = app_control_send_launch_request(app_control, NULL, NULL);
if (ret != APP_CONTROL_ERROR_NONE)
   dlog_print(DLOG_ERROR, LOG_TAG, "app_control_send_launch_request() is failed. err = %d", ret);

Please help me in developing code to continuously check if my web application is running or not.

A: Instead of Developing additional Native Service application, Your Web application can itself Do your desired task.
Tizen Alarm API enables you to schedule an application to be run at a specific time. When an alarm is triggered, the application is launched (unless it is already running).
Register a repetitive alarm using Web Alarm API that would Launch the Web app itself after your desired time frame.
var appId = "com.samsung.clocksetting";
// Your desired appId, in this case 'settings' app

var alarmR = new tizen.AlarmRelative(2* tizen.alarm.PERIOD_MINUTE, 30 * tizen.alarm.PERIOD_MINUTE);
// Set an alarm in system that would trigger after 2 minutes and then every 30 minitues

tizen.alarm.add(alarmR, appId);

Add 'alarm' privilege in your config.xml. Check out these Links for details implementation:
Tizen Web Alarm Guide
Tizen Web Alarm API References


text:
Q: How to show fullscreen get info? Once I press some key,OS X shows partition get info in fullscreen in big icon in black background,I don't know how to do it again.

A: http://osxdaily.com/2012/09/06/8-tricks-mac-os-x-full-screen-slideshow/
Select a picture or group of images from the desktop, then use the following:
Option+Spacebar to launch image(s) into the full-screen slideshow mode
Spacebar to pause/play the image slideshow
Left Arrow to go back, Right Arrow to go forward
Gesture with two-fingers left to go forward, two-finger gesture right to go back
Option to view smaller images at actual size
Click "Index Sheet" to view thumbnails of all images in the slideshow
Click "Add to iPhoto" to import the image into iPhoto
Hold Control key and use a two-fingered back or forward swipe in to zoom into the photo
Escape to exit


text:
Q: Captura select como input Estoy intentando capturar el onChange de un select y que obtengo de la siguiente manera:
@if (!Model.Id.Equals(null))
        {
        @Html.DropDownListFor(m => m.Modificar.IdClase, new SelectList(Model.ListaClases, "IdClase", "Clase", Model.Modificar.IdClase), new { @class = "input form-control input-lg", @required = "required", @style = "height: 40px; font-size:16px" })
        }
        else
        {
        @Html.DropDownListFor(m => m.ListaClases, new SelectList(Model.ListaClases, "IdClase", "Clase"), new { @class = "input form-control input-lg", @required = "required", @style = "height: 40px; font-size:16px" })
        }

Al realizar una captura del activo con:
var clases = $('#Id').val() != "" ? $('#Modificar_IdClase') : $('#ListaClases');

Me he dado cuenta que me coje el Modificar como input en vez de select entonces no me captura el cambio de opción. ¿Qué está ocurriendo y cómo lo soluciono?
Dejo captura del console.log

A: El problema que tenía era que tenia el id duplicado y capturaba el primer elemento de los dos que habia, el elemento con el mismo id era:
@Html.HiddenFor(m => m.Modificar.IdClase)

Que asp.net transforma a Modificar_IdClase, obteniendo dos elementos con el mismo id, eliminando ese intruso el problema desaparece


text:
Q: Getting Error  while hosting WEB API 2 in Hostgator I am using WEB API 2 its working in my local system,but when  WEB API 2 run in Hostgator windows server its given me error below is my error screenshot
http://prntscr.com/bc5ihv

A: As I commented, I got similar problem while hosting web api on shared hosting.
The solution is to remove Microsoft.CodeDom.Providers.DotNetCompilerPlatform package and clean and build

You can deploy even without Roslyn with no change in code. Open NuGet Package Manager window and uninstall Microsoft.CodeDom.Providers.DotNetCompilerPlatform package and rebuild & republish. This uninstallation also removes CodeDom configuration from web.config file. This will solve your purpose. Basically this will not generate any csc.exe, vbc.exe files inside bin folder.

I got it from here


text:
Q: Aestan tray menu error - wamp server I am getting the error Aestan Tray Menu from the WAMP server.
The configuration file contains a syntax error:

on line 0 [EParseError] No Tray icon was specified.
Please assign a tray icon by using one of the TrayIcon* directives in
the [Config]section

how can i fix it ?

A: This is because the wampmanager.ini file is corrupted.
You can repair it without doing a full install.

*

*Open up command crompt

*Type "cd c:/wamp/scripts"

*Type "php refresh.php" (note, for this step you'll need to have php as an environment path variable)

This should recreate wampmanager.ini and you should be good to go.

A: The threads at wampserver cover the issue - for me what fixed the problem was updating the wampmanager.ini with the following
[Config]
ImageList=images_off.bmp
ServiceCheckInterval=1
ServiceGlyphRunning=13
ServiceGlyphPaused=14
ServiceGlyphStopped=15
TrayIconAllRunning=16
TrayIconSomeRunning=17
TrayIconNoneRunning=18
ID={wampserver}
AboutHeader=WAMP5
AboutVersion=Version 2.2

[AboutText]
WampServer Version 2.2

Maintainer / Upgrade / Roadmap by Herve Leclerc (herve.leclerc@alterway.fr)

Powered by Alter Way [www.alterway.fr]

Sources are available at SourceForge

[www.wampserver.com]

[Services]
Name: wampapache
Name: wampmysqld

[Messages]
AllRunningHint=WAMP5 - All services running - server Offline
SomeRunningHint=WAMP5 - %n of %t services running - server Offline
NoneRunningHint=WAMP5 - None of %t services running - server Offline

[StartupAction]
Action: run; FileName: "c:/wamp1/bin/php/php5.4.3/php-win.exe";Parameters: "refresh.php";WorkingDir: "c:/wamp1/scripts"; Flags: waituntilterminated
Action: resetservices
Action: readconfig;
Action: service; Service: wampapache; ServiceAction: startresume; Flags: ignoreerrors
Action: service; Service: wampmysqld; ServiceAction: startresume; Flags: ignoreerrors

You will need to update the StartupAction portion with your correct paths and PHP version.  After updating save it and run the wamp manager again.  It should start.
Original threads: http://forum.wampserver.com/read.php?2,126657
Wamp broke for me during the Windows Update kb3194496 on September 30th 2016.