Q: Should I be using static or instance methods? I'm really confused with the concept of static vs instance methods. I have created a BMR calculator. I've seperated the GUI from the calculations using different classes.
public class Calculations {

/**
 * If user input is correct, this method will calculate the BMR value of the user given their input and measurement choices.
 *
 * @param userAge, userHeight, userWeight
 * @return BMR Value as a string
 */
public static int calcBMR(int age, String gender, double height, double weight) {

    // This is the body of the calculations - different formulas used depending on gender. Conversions to kg and cm done earlier so no conversions needed here.
    if (gender.equals("M")) { // Uses male bmr formula if genderMale radiobutton is selected
        return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + 5)); // This is the Miffin St-Jeor formula, calculations done in cm/kg
    } else { // else gender.equals("F") - there are only 2 options for gender, M or F.
        return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) - 161));
    }
}

/**
 * If the user selects the TDEE option, this method will be executed after the calcBMR() method.
 * A value from the calcBMR() method will be passed down to this method, and is multiplied
 * by the activity level parameter passed into this method.
 *
 * @param selectedActivityLevel
 * @return TDEE Value (as a string)
 */
public static int calcTDEE(double activityMultiplier, int bmr) {
    System.out.println(activityMultiplier);
    return (int) Math.round(bmr * activityMultiplier);
}

}
As you can see, the methods are STATIC, however the variables being passed through (to both methods) are instance variables.
I am only calling these methods through the following lines:
            bmrValue = Calculations.calcBMR(userAge, userGender, userHeight, userWeight);
            bmrLabel.setText("
You have a BMR of: " + "" +  bmrValue + "");
            if (tdeeYes.isSelected()) {
                userActivityLevel = activityMap.get(activityLevelBox.getSelectedItem());
                // Looks up selected item from combo box, which is the KEY. Then looks up the value to this key from the map - this value is the TDEE multiplier.
                tdeeLabel.setText("
You have a TDEE of: " + "" + Calculations.calcTDEE(userActivityLevel, bmrValue) + "");
                }

The variables are defined as:
HashMap<String, Double> activityMap;
String[] activityLevels = {"Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"};

int userAge;
String userGender;
double userHeight;
double userWeight;
double userActivityLevel;

int bmrValue;

Am I using static/instance variables correctly? Earlier I had all my parameter variables as static, as I know static methods can only access static variables. I didn't know that the parameters could be instance variables until now.
Any guidance would be appreciated.

A: For starters, the difference between static and instance variables is that, only ONE static variable exists for all the instances of the class, whereas an instance variable exists for EVERY instance of the class.
Now, when you are talking about methods, in most cases you need to make a method static when you are trying to call it from another static method (such as main).
In general this practice is wrong for OOP, and chances are you should rethink the way the program is structured.
If you could provide more details about the code you use to call these methods, I would be able to help you with more details on how to fix this.
EDIT:
In light of the new info you provided:
1) I believe that bmrMain,BMRMain and Calculations can all be merged into one class. The constructor of the new class should be adjusted to read input (as well as getters and setters for each variable for added flexibility - optional)
2) Regarding the calculation of the bmr part, there are many ways to tackle this, so I will go ahead and suggest the one that is best in my opinion.
Add a Button with a text "Click to calculate" or something similar, and implement an ActionListener. The action Listener will in turn call (whenever the button is clicked) the method that calculates everything, and finally it will change the text on the JLabel.
sample code for the action Listener:
JButton button = new JButton("Text Button");
button.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    //Call the methods for the calculation
    // bmr and tdee are temporary variables to store the results from the methods
    //handle them properly, or remove them if not needed (I just wrote a sample)
    int bmr = calcBMR(...); //pass the correct variables as arguments here
    int tdee;
    if(userHasPickedTDEE) {  tdee = calcTDEE(...); }  //and here
    label.setText(....);

  }
});

These 2 steps will take care of your "static" problem.
I recommend that you do some research on event-driven programming
And here is some extra and more in-depth reading on Action Listeners
If you need further help, or clarifications let me know :)
EDIT2:
In general, yes it is a good practice to separate classes in order to keep the code manageable. But in this case I think it is a bit superfluous to create a new class just for 2 methods.
Nevertheless if you would like to keep the current structure, the way to fix the "static" is:
1) remove static from the 2 calculation methods.
2)line 332 should be
Calculations c = new Calculations();
bmrValue = c.calcBMR(userAge, userGender, userHeight, userWeight);

FINAL_EDIT:
Well, these questions can easily be transferred to a thread of their own. But here is a useful link from a quick google search I just did, that will help demistify the static keyword:
Static keyword in Java

A: My thumb rule for using static variables goes somewhat like this:

*

*Do not use static

*When it is needed to use static refer to (1)

For most cases, the above thumb rule works. But then, we have standard idioms popularized by JDK, apache-commons libraries. Looking into them you find that:

*

*It is OK to have utility classes that contain all static methods.

*It is OK to create constants using static fields in classes. Though, for this using Enum might be a better choice.

*It is OK to one off utility functions that work on the same class into the class.

As for the restructuring the code goes, you should be looking at who owns the data. In this case, both the methods from Calculations class looks to be using data from the other class. Move the methods into the other class.
The only reason for existence of Calculations class should be that if you are using the methods from multiple other classes which are not related. If they are related, you try to model their relationship and see where these methods go.

A: I use static whenever my class is just used to call those methods (i.e. my main method calls the static methods to set variables in the main class, etc). I believe that is the "utility" class that KDM mentioned. A small example of when I use static or utility classes:
class Utility {
  public static int add(int a, int b) {
    // You would, of course, put something besides simple addition here
    return a + b;
  }
}

class Main {
  public static void main(String[] args) {
    int a = 2, b = 3;
    int sum = Utility.add(a, b);
    System.out.println(sum);
  }
}

On the other hand, if you have a class that is closer to an actual object, with properties of its own, stay away from static. If you use static, then each instance of the class which you want to be separate objects will end up with same values.
Based on the name and functionality of your class, it appears you have a utility class. Static should be fine, but it may not be necessary. Hypothetically, though, if you wanted to use this class with multiple "people" class instances for which to calculate the BMR (where each instance is unique), then I would put calcBMR() in a person class and make it non-static so that each person has their own calcBMR().
Edit: Maybe this will help too:
Instance -> Instantiate: new Calculations().instanceMethod();
Static -> Class itself, the class's "state": Calculations.staticMethod();

A: If you think in terms of, do I want instance methods or static methods, you're going to be lost. Java isn't method-oriented, it's object-oriented. So for your functionality, decide whether you want an object or a pure function (where pure function means no dependencies and no side-effects, it's strictly a function that given this returns that).
It might be good to model this as an object, since you have information describing some aspect of the User and it may make sense to keep it together:
public class User {
    private int age;
    private String gender; // todo: use an Enum
    private double height;
    private double weight;
    private String activityLevel; // todo: use an Enum

    public User(int age, String gender, double height, double weight,
        String activityLevel) {
        this.age = age;
        this.gender = gender;
        this.height = height;
        this.weight = weight;
        this.activityLevel = activityLevel;
    }

    public double calculateBmr() {
        int offset = gender.equals("M") ? 5 : -161;
        return (int) (Math.round((10 * weight)
            + (6.25 * height) - (5 * age) + offset));
    }
}

etc. This way we don't have to preface the variables with "user", they're all placed together in one object. Objects are an organizational scheme for collecting related information, the instance methods are functions that use the object's information.
The alternative route is to create a utility class:
public final class UserCalcUtil {
    private UserCalcUtil() {} // no point instantiating this

    public static int calculateBmr(String gender, double height,
    double weight, int age) {
        int offset = gender.equals("M") ? 5 : -161;
        return (int) (Math.round((10 * weight)
            + (6.25 * height) - (5 * age) + offset));
    }
}

Here you're keeping track of the user data separately, and passing it in to the static method when you want to calculate something. The utility class is a dumping ground for separate static methods (which you can think of as functions).
Whether you want to use objects or utility classes depends on how you want to organize your data and do calculations on it. Packing the data for a User together with the methods that act on that data may be more convenient if you always do the calculations on the individual objects, or moving the calculations into a utility class might make sense if there are multiple unrelated classes that you want to do calculations for. Since Java has more support for object-oriented constructs it often makes sense to take the object approach.
And you can use static methods, but avoid static variables for anything but constants (public static final, with a type that's immutable).


Q: C++ - Qt QObject::connect GET request usage across classes A quick overview of what's happening: I am trying to do a GET request using Qt's QNetworkAccessManager, but the callback function on my QObject::connect(..) function is not being called. My questions is can I call QObject::connect from one object, but connect to a slot of another object (given that I have a pointer to both the object and the slot) - See below for more details.
My ultimate goal is to POST the data (seeing as it's a login function), I had POST Request code that was ultimately suffering from the same issue - callback function not being called. So I would like to be able to do a simple GET request first, once I have that, I think I'll be fine on my own from there.
I currently have a QMainWindow LoginWindow, with a button that calls a slot doLogin() in the LoginWindow class. This all works as you would expect. LoginWindow also has a public slots function called loginResponse(QNetworkReply* response).
//---LoginWindow.h

...

public slots:
    void doLogin();
    void loginResponse(QNetworkReply* response)

...

//---LoginWindow.cpp

LoginWindow::LoginWindow(QWidget *parent) :
    QMainWindow(parent),
ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
    ui->username_le->setFocus();
}

void LoginWindow::doLogin()
{
   MyProduct::Network network(this);
    qDebug() << "Logging in...";

    //Here I call network.login from LoginWindow and pass
    //references to the Slot I want to use and the LoginWindow itself
    network.login(
        ui->username_le->text(), //username
        ui->password_le->text(), //password
        this,                    //reference to this object (LoginWindow*)
        SLOT(loginResponse(QNetworkReply*)) //loginResponse slot
    );
}

void LoginWindow::loginResponse(QNetworkReply* response)
{
    qDebug() << "Log in complete";
}

Next I have another class, under the MyProduct namespace, called Network. As you can see above, Network has a function called login. Here it is:
void MyProduct::Network login(QString username, QString password, QObject *receiver, const char *slot)
{
    QNetworkRequest request(QUrl(API_ROOT + LOGIN_PATH)); //"http://localhost/basic/login.php"
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

    //nam = QNetworkAccessManager* declared in the constructor
    QObject::connect(nam,SIGNAL(finished(QNetworkReply*)), receiver, slot);

    qDebug() << "Posting login data...";
    nam->get(request);
}

The goal here is to create a login function in my Network class that can be used and connected in any number of windows (as users may log in from multiple places). But I'm getting no response - LoginWindow::loginResponse is not run.
I see "Logging in..." and "Posting login data" output in the console, but not "Log in complete".
Can anyone please point me in the right direction or tell me I'm crazy or that this is a bad idea?
Thanks in advance!

A: Note that QNetworkAccessManager operates asynchronously. The get() method does not block while the network operation occurs; it returns immediately. (See the Detailed Description section of the documentation for more info.)
This is pretty typical of Qt's network-related APIs, because you usually don't want your application to freeze while waiting for data to move across a network.
What this means is what your instance, nam, isn't alive long enough for the GET request to actually finish. Your instance of the Product::Network class is deleted immediately after the call to login() because it's allocated on the stack. Although I can't see the code, I'm guessing it cleans up the QNetworkAccessManager as well.
If you extend the lifetime of your network object, you may find that your slot will eventually be invoked.

Also, this is more a matter of preference, but I think it would be cleaner to avoid passing a receiver and a slot to your login() function. I'd recommend declaring your own signals in the Network class as part of its API, and to connect to those in the LoginWindow class.


Q: Decode hexadecimal number in IBM/360 column binary format I have this message \1004\1001\2001\1010\0900\0000\0006\2012. It's in IBM column binary format. Reading, and trying to understand, a lot of articles like the below ones can't even put me on track.
https://v8doc.sas.com/sashtml/lrcon/z0695224.htm
http://homepage.divms.uiowa.edu/~jones/cards/codes.html
May I ask for some hint on it? Obviously I want to write a decoder for future use.

A: The IBM/360 column binary format defines how a hexadecimal value is represented on a Hollerith-card (punch card). This is described e.g. in http://www.jwdp.com/colbin1.html and in https://www.masswerk.at/keypunch/
There are several versions of punch cards, see e.g. https://en.wikipedia.org/wiki/Punched_card. The very common IBM 80-column punched card has 80 colums and 12 rows. The rows are labeld from top to bottom Y, X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Using the IBM/360 column binary format it follows for your code:
hex     Byte 1 (hex)     Byte 2 (hex)     Byte 1 (cbf)     Byte 2 (cbf)     cbf (=column binary format)
\1004   10               04               X                7                X7
\1001   10               01               X                9                X9
\2001   20               01               Y                9                Y9
\1010   10               10               X                5                X5
\0900   09               00               03               0                03
\0000   00               00               0                0                blank
\0006   00               06               0                78               78
\2012   20               12               Y                58               Y58

Next, you have to apply a keypunch to map the punchcard-data to letters, digits and so on. You have not specified a special keypunch. Thus, it makes sense to use the IBM model 029 keypunch which was the most common keypunch, see e.g. https://www.masswerk.at/keypunch/ and your link
http://homepage.divms.uiowa.edu/~jones/cards/codes.html.
cbf      029 keypunch
X7       P
X9       R
Y9       I
X5       N
03       T
blank    blank
78       "
Y58      (

Altogether, the result is PRINT "(


Q: Connecting HTML/DOM with node.js I'm trying to find a way to write to a text file using node.js but I was trying to get the input from the HTML DOM. How do you write the output from the DOM to a text file using fs.writeFile?
Here's some code that doesn't work but thought it might be relevant. Thanks

A demonstration of how to access a Text Field

<input id="myText">

<button onclick="myFunction()">Try it</button>

A: You cannot write file directly from a browser to local computers.
That would be a massive security concern.
*You also cannot use fs on client-side browser
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile() on server-side, which is allowed.
What you could do is:

*

*Create a link and prompt to download.

*Send to server and response with a download.

*Use native environment like Electron to able NodeJs locally to write into local computer.

What I assume you want to do is 1
Is that case you could simply do:
function writeAndDownload(str, filename){
    let yourContent = str
    //Convert your string into ObjectURL
    let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
    let blob = new Blob([bom, yourContent], { type: "text/plain" });
    let url = (window.URL || window.webkitURL).createObjectURL(blob);
    //Create a link and assign the ObjectURL
    let link = document.createElement("a");
    link.style.display = "none";
    link.setAttribute("href", url);
    link.setAttribute("download", filename);
    //Automatically prompt to download
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

writeAndDownload("Text you want to save", "savedData")


Q: How do I draw 2 lines with 2 different colors: each set of lines has set Coordinates. the Sets are not connected How do I draw two lines not connected to each other, the two lines must have to different colors, the two lines have points from four set of coordinates. So each line has its own set of coordinates. Using Objective C iOS 7.
Tower Two does not draw right now
 if ([deg2 isEqual: @""] ) {
    //nil

}else{
    //not nil

    //Tower Two
    //draw line from lat2/long2 to finalLat2/finalLong2
    CLLocationCoordinate2D coordinateArray2[2];
    coordinateArray2[0] = CLLocationCoordinate2DMake([lat2 doubleValue], [long2 doubleValue]); //tower two
    coordinateArray2[1] = CLLocationCoordinate2DMake(finalLat2, finalLong2);
    self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray2 count:2];

}

Tower One does draw
   //tower one
  // [self.mapview setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
    //draw line from lat1/long1 to finalLat1/finalLong1
    CLLocationCoordinate2D coordinateArray[2];
    coordinateArray[0] = CLLocationCoordinate2DMake([lat1 doubleValue], [long1     doubleValue]); //tower one
    coordinateArray[1] = CLLocationCoordinate2DMake(finalLat1, finalLong1);

    self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
    [self.mapview setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
    [self.mapview addOverlay:self.routeLine];
}

Here is how Tower One gets the line color
//Tower One Line
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine)
    {
        if(nil == self.routeLineView)
        {
            self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
            self.routeLineView.fillColor = [UIColor greenColor];
            self.routeLineView.strokeColor = [UIColor greenColor];
            self.routeLineView.lineWidth = 5;
        }
        return self.routeLineView;
    }
    return nil;
}

A: I just needed to add in the .h file
@property (nonatomic, retain) MKPolyline *routeLine1; //ORGINAL LINE
@property (nonatomic, retain) MKPolylineView *routeLineView1; //ORGINAL LINE

@property (nonatomic, retain) MKPolyline *routeLine2; //ADDED LINE
@property (nonatomic, retain) MKPolylineView *routeLineView2; //ADDED LINE

This in the .m
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
if(overlay == self.routeLine1)
{
    if(nil == self.routeLineView1)
    {
        self.routeLineView1 = [[MKPolylineView alloc] initWithPolyline:self.routeLine1];
        self.routeLineView1.fillColor = [UIColor greenColor];
        self.routeLineView1.strokeColor = [UIColor greenColor];
        self.routeLineView1.lineWidth = 5;

    }

    return self.routeLineView1;
}

if(overlay == self.routeLine2)
{
    if(nil == self.routeLineView2)
    {
        self.routeLineView2 = [[MKPolylineView alloc] initWithPolyline:self.routeLine2];
        self.routeLineView2.fillColor = [UIColor orangeColor];
        self.routeLineView2.strokeColor = [UIColor orangeColor];
        self.routeLineView2.lineWidth = 5;

    }

    return self.routeLineView2;
}

return nil;

}


Q: Google maps reverse geocoding returns zero_results I have this code where I try getting address from coords in a google map,but my phone returns status error zero_results.
I am sure my location is available because if I tested via browser and my address location for coordinates is returned.
Any ideas?
<!DOCTYPE html>

    <title>Geolocation test</title>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

`

A: the geolocation service is asynchronous, you need to use the data (pos2) in the callback function when/where it is available. Currently you are calling the geocoder before that value is set.
proof of concept fiddle
// Try HTML5 geolocation.
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };
    pos2 = pos;
    latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    map.setCenter(pos);
    infoWindow.setPosition(pos);
    infoWindow.setContent('La tua posizione.');

    // call reverse geocoder with location returned by geolocation service
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({
      'latLng': pos2
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          map.setZoom(11);
          var marker = new google.maps.Marker({
            position: pos2,
            map: map
          });
        infoWindow.setContent('La tua posizione.
'+ results[0].formatted_address);
        } else {
          document.getElementById('msg').innerHTML = 'results[1].formatted_address';
          window.alert('No results found');
        }
      } else {
        document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
        window.alert('Geocoder failed due to: ' + status);
      }
    });
    map.setCenter(pos);
  }, function() {
    handleLocationError(true, infoWindow, map.getCenter());
  });

code snippet:

div#mapdiv {
  width: 500px;
  height: 300px;
  margin: 10px auto;
}


Q: Display next div only and hide other divs with same class Many versions of this question have already been asked but I can't seem to find a solution.
I'm hoping to have just one div visible at a time and to toggle an 'open' class on the correct trigger.
Here's what I have so far:

Here's a description

Here's a description

Here's a description

And the jQuery:
$(function () {
    $(".trigger").click(function (e) {
      e.preventDefault();
      $(this).next('.description').fadeToggle('fast');$(this).toggleClass('open');
    });
});

And that works to get the proper div opened and closed, but what I'm hoping for is some logic to make any other 'description' divs close so only one will be open at a time.
Any help would be much appreciated!

A: Try to hide all .description except the current element's linked .description,
  $(function () {
     $(".trigger").click(function (e) {
      e.preventDefault();
      $(".description").not($(this).toggleClass('open').next('.description').fadeToggle("slow")).fadeOut('fast');
     });
  });

DEMO

A: You need to hide the sibling elements like

$(function() {
  $(".trigger").click(function(e) {
    e.preventDefault();
    $(this).toggleClass('open').siblings('.trigger').removeClass('open');
    $(this).next('.description').stop().fadeToggle('fast').siblings('.description').stop().fadeOut('fast');
  });
});
.description {
  display: none;
}
.open {
  color: green;
}

t1

Here's a description

t2

Here's a description

t3

Here's a description


Q: getting err_too_many_redirects in laravel when I use Request for validation for validating unique it is my error page
I have used customize Request page for geting value from post request.
in that request I am validating

namespace App\Http\Requests;

use App\Http\Requests\Request;

class TaxclassRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "tax_class"=>'unique:taxes,tax_class'
        ];
    }
}

and my controller is

    function insert(TaxclassRequest $request)
    {

                $n=$request->input('number');           //total number of variable that has been created dyanamic
                $tax_class=$request->input("tax_class"); // tax_class
.
.
.
other code

I am getting error

ERR_TOO_MANY_REDIRECTS


Q: Python 2.7 mechanize library I am trying to use mechanize to access a website and submit form to login. My end goal is to login to a ticketing system, fill in the required  fields and submit which in turn would generate a ticket number which I need to grab.
I have the following code.
import urllib
import mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent','Firefox')]
br.set_handle_robots(False)
jira='jira_link'
br.open(jira)
br.select_form(nr=0)
br.form['os_username'] = 'username'
br.form['os_password']=  'password'
sub=br.submit()
print sub.geturl()

However I get the following error when I run the script
raise BrowserStateError("not viewing HTML")

mechanize._mechanize.BrowserStateError: not viewing HTML
I successfully logged into Facebook using the same code.
Checking browser console it does look like a valid html doc.


Q: How to report errors while parsing content in ES6 tagged templates? I'm working with a friend on a small Javascript experiment, which involves a basic HTML parser, implemented as a simple state machine - you can see the code here.
My question is regarding tagged template functions which involve any kind of parser, with regards to error reporting - that is, if the parser detects an invalid state, it needs to report where the error was found in the input.
My problem is tracking and/or explaining where the error was found, in a way that makes sense.
The input to a tagged template function is actually bits of source (in my case HTML) alternating with Javascript values, so you can't simply (as I'm doing now, as you would do in most normal parsers) count characters and report the position, since the alternating Javascript values may not be strings, or may be strings that don't get parsed as literal source.
Is there any way for tagged template functions to discover the source file locations of the alternating input strings/values?
Or am I right in suspecting that a run-time facility of this sort is virtually impossible? Is there literally no useful way to implement this, short of using a Javascript parser, possibly ahead-of-time, to discover and log the source locations?

A: All that can be done here is to output the expected context where the problem took place. Considering that the problem was caused by three:
const three = null;
`one${two}${three}four`

Tag function arguments can be concatenated in error message to the point where they start to make sense, e.g.
Expected a number as an expression at position 2, got `null`,
`one${...}${...}four`
            ^^^

Stack trace can also be retrieved if needed with new Error().stack.
If more precision is required, a template engine should be used instead of template literals because all necessary data is available during template compilation.
The options for tag function are same as for any other function. If foo function was called with bar variable as an argument that equals 1 (like foo(bar)), it may be impossible to figure out that it was called with bar from inside foo, because all we've got is 1 value. The fact that it was called like foo(bar) can only be found out if we have stack trace and the access to source file - which we don't have under normal circumstances.  This method can be used in cases where feedback should be provided on the context, e.g. a test runner - because it is responsible for script loading and has access to source files.


Q: Web Scraping using non-defined tags I'm trying to develop a tool to do some web scraping, I've done this before for specific websites using HTML Agility Pack, but in this case I want the user to be able to specify what information he wants to scrap by selecting the text on the website.
What I don't know is if the user selects "Product 1" is there anyway I can get the HTML tag or something so I can then feed the algorithm so I search for that same type of tag on the entire document?
Product 1
Product description
Price $0.00

A: seems like you want to query your DOM  by a specific tag, similar to jquery selectors. Take a look at the project below, it might be what you are looking for.
https://github.com/jamietre/csquery

A: Load the HTML into an HtmlDocument object, then select the first node where the text input appears. The node has everything you might need:
    var doc = new HtmlDocument();
    string input = "Product 1";
    doc.LoadHtml("Your HTML here"); //Or doc.Load(), depends on how you're getting your HTML

    HtmlNode selectedNode = doc.DocumentNode.SelectSingleNode(string.Format("//*[contains(text(),'{0}')]", input));

    var tagName = selectedNode.Name;
    var tagClass = selectedNode.Attributes["class"].Value;
    //etc

Of course this all depends on the actual page structure, whether "Product 1" is shown anywhere else, whether other elements in the page also use the same node that contains "Product 1", etc.


Q: Textarea not filled with all $_GET data, cuts off at quotation marks I have a text area page which is launched from the previous page:
$message = $_POST['editPost'];
header("location:editPost.php?msg=$message");

The editPost.php retrieves this and fills the text area like so:
echo "<form action='index.php' method='post'>
Your Post:

<textarea name='comments' cols='100' rows='100'>".$_GET["msg"]."</textarea>

<input type=submit value='submit'>
</FORM>";

The problem I'm getting is not all the data of 'msg' seems to get passed across, or the message gets cut of at the point where it reaches a quotation mark e.g. '
The text I want it to fill the textarea with this text:

So this is my second blog post for this assignment, I've progressed a bit since my previous post

however it only add this to the text area this:

So this is my second blog post for this assignment, I

As I say it seems to not contain any more of the string after the quotation mark is reached. Is there anyway around this so I can pass the whole message across?
EDIT
I might add, I'm aware a more simple solution would be to retrieve the message again from the MySQL database as that's what I'm using, but I'm just intrigued as to how this works.
if(isset($_POST['edit'])) {
//$_SESSION['postToEdit'] = $_POST['editPost'];
$message = htmlentities($_POST['editPost'], ENT_QUOTES);
header("location:editPost.php?msg=$message");

That is what I do with the data once it is posted from this form:
foreach($posts as $postid=>$post)
            {
                echo '
'.$post;
                if(isset($_SESSION['username'])) {
                    if($_SESSION['isAdmin'] == "true") {

                        echo "

<form name='adminTools' action='index.php' method='post'>
                        <input type='hidden' name='editPost' value='$post'>
                        <input type='submit' value='Edit' name='edit'/>
                        <input type='hidden' name='deletePost' value='$postid'>
                        <input type='submit' value='Delete' name='delete' /></form>

";

A: echo "<form action='index.php' method='post'>
Your Post:

<textarea name='comments' cols='100' rows='100'>".htmlspecialchars($_GET["msg"])."</textarea>

<input type=submit value='submit'>
</FORM>";

textarea seems an odd container for it, but that's your call

A: I think I get it.
header("location:editPost.php?msg=$message"); doesn't smells good.
If you simply want to fix the problem use http://php.net/manual/en/function.urlencode.php and when getting the value http://www.php.net/manual/en/function.urldecode.php
You're getting a post request and then forwarding it using header location. That's definitely a poor way to do it. The problem probably is taking place when you pass the parameter as a query string on ?msg=$message
Since MVC and alike applications (n-layered apps) is the standard now. You should not do that spaghetti code, mixing html and php and using header as your FrontController dispatcher.
I'd suggest you to use for example, the SLIM framework. If you do not want to learn this. You should at least follow the standards described here.
E.g.:
<?php
// index.php

// load and initialize any global libraries
require_once 'model.php';
require_once 'controllers.php';

// route the request internally
$uri = $_SERVER['REQUEST_URI'];
if ($uri == '/index.php') {
    list_action();
} elseif ($uri == '/index.php/show' && isset($_GET['id'])) {
    show_action($_GET['id']);
} else {
    header('Status: 404 Not Found');
    echo '
Page Not Found
';
}

In short, create a FrontController file that will map to the desired actions (controllers) according to the request without using header() to execute specific actions (the exception is only if actually the headers are needed, in fact).

A: Use addslashes($message) before passing it in querystring and stripslashe($_GET['msg']) function before displaying it.
Click addslashes() and stripslashes() for more references.


Q: Jquery Slider spacing fubar on ie7 and i6 So ive been trying to debug this friggin spacing issue for the last 4 hours.. and I cant friggin solve it!!!
If you go to http://myurbanlunchbox.com you will see right away what I am refering to.  The image slider has spacing issues, but only in IE6 and IE7.. (as usual).
Can anyone point out where im going wrong?

A: It's not the slider which is messing up.  Rather, IE isn't displaying the right border of #slider.  I think moving the border to #overview would provide the style you're looking for.  I have no idea why IE is messing up the border.


Q: Parsing XML inside JSF could anybody tell me how to parse XML file inside a JSF page?
The thing's that I've got XML file and want to put some data from it into my JSF page. My first thought was to include JSTL Core and XML libs and to do something like this:
<c:import var="some-info-doc" src="some-info.xml" />
<x:parse  var="some-info-xml" xml="some-info-doc" />

<h:outputText>
   <x:out select="$some-info-xml/a-piece-of-data" />
</h:outputText>

However, this code resulted in error. c:import was not recognized. So, I decided to play with a local piece of XML:
<x:parse var="simple">
   <child>basic</child>
</x:parse>

<h:outputText>
   <x:out select="$simple/child" />
</h:outputText>

This led to the child tag being printed in the result page. And the output came from the x:parse tag, not h:output.
So that, is there any alternative to parse XML inside a JSF page (not including XML being sent as an object from a certain by-me-written module)? Or are there any errors in my code?

A: 1. Don't try to mix JSTL tags and JSF tags; they're chalk and cheese.
2. JSF is an MVP framework, so you're going against the grain by trying to define your data sources in the view.
3. To emit data via an outputText control, bind its value attribute to the model (e.g. a managed bean).
It is probably possible to do something like this:
<!-- other code elided -->
<x:set var="x" select="$simple/child" />
<h:outputText value="#{x}" />

...but, in general, see points 1 and 2.

Just a suggestion: ensure you've added the http://java.sun.com/jsp/jstl/core namespace to the page to use JSTL core.


Q: Waiting for multiple asynchronous JSON queries to finish before running code I am looking to run multiple different JSON request simultaneously, and then only perform a function once they have either completed or returned an error message (404 etc.). Here's what I have so far, but the function finished doesn't remember the variables from either request. Any ideas?
function socialPosting(a_date,a_title,a_source,a_thumbnail,a_url) {
        socialPosts[socialPosts.length] = {date: a_date, title: a_title, source: a_source, thumbnail: a_thumbnail, url: a_url};
        //console.log(socialPosts[amount]);
        //console.log(amount);
    }

function finished(source) {
        if (source == "Twitter") {
            var Twitter = "True";
        }
        if (source == "YouTube") {
            var YouTube = "True";
        }
        console.log(source); //diagnostics
        console.log(Twitter); //diagnostics
        console.log(YouTube); //diagnostics
        if (Twitter == "True" && YouTube == "True") {
            console.log(socialPosts[0]); //Should return after both requests are complete
        }
    }

$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
        for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
            socialPosting(Date.parse(data.data.items[i].uploaded),data.data.items[i].title,"YouTube",data.data.items[i].thumbnail.hqDefault,'http://www.youtube.com/watch?v=' + data.data.items[i].id); //Add values of YouTube video to array
        }
        finished("YouTube");
    });

$.getJSON("https://api.twitter.com/1/statuses/user_timeline/twitter.json?count=5&include_rts=1&callback=?", function(data) {
        var amount = socialPosts.length;
        for(var i=0; i<data.length; i++) {
            socialPosting(Date.parse(data[i].created_at),data[i].text,"Twitter"); //Add values of YouTube video to array
        }
        finished("Twitter");
    });

A: try this, in your solution Twitter and Youtube are local variables in the function finished, after the function returns they no longer exist, if the function gets called again they are craeted again but of course they don´t have the value of last time since they are new variables, maybe google for 'javascript variable scope' for more information about this topic.
var Twitter = false;
var YouTube = false;
function finished(source) {
    if (source == "Twitter") {
        Twitter = true;
    }
    if (source == "YouTube") {
        YouTube = true;
    }
    console.log(source);
    console.log(Twitter);
    console.log(YouTube);
    if (Twitter && YouTube) {
        console.log(socialPosts[0]);
    }
}

Also add an error handler to your json-request via
$.getJSON(...).fail(function () {console.log('error');});


Q: How to change color of the left aligned text? I'm new to reactjs, i tried to change the color of the left align text using reactjs. Can anybody help me in this?
this would be jsondata in api:
{
"message": "Hello everyone",
    "isrespond": true,
},

{
"message": "hi",
    "isrespond": false,

}

Can anyone help me in this ?

A:  let leftAlignedColor
 if(element.isrespond == "left"){
    leftAlignedColor = '#000'
 }else{
    leftAlignedColor = null
 }
<Grid.Column floated={ element.isrespond ? "right" : "left"}><p style={{color: `${leftAlignedColor}`}}> {result.message}
</Grid.Column>

its better to use a ,
 inside a column as a good practice.
Hope this is helpful!

A: You should apply a conditional style. This will enable you even pass a specific class name that styles the component.
let myStyle = element.isrespond ? {float:"right",color:"blue"} : {float:"left",color:"red"};
<Grid.Column style={myStyle}> {result.message}</Grid.Column>

A:  <Grid.Column floated={ element.isrespond ? "right" : "left"}>
 {result.message}
</Grid.Column>

I think this will work. change the required colors. I added botj for color and background. In the above one. its "green" for left and "blue" for right


Q: How to display an image of expo camera in React Native I am working on camera in app, where I have took a picture and have convert into base64 now I want to display an image but did not able to display an image . Could someone please help me how to achieve this goal .
Thanks
  takePicture = async () => {
    if (this.camera) {
        let photo = await this.camera.takePictureAsync({
            base64: true,
        });
        this.props.cameraToggle(false);
        this.props.image(photo)
        console.log('@@@ take picutre', photo)
    }
}

Image Code that I want to render
<Image source={{uri:`data:image/png;base64,${cameraImage}`}} style={{width:100,height:100}}/>

A: I assume that you're using class-based components. You can render the image which is captured from camera by setting the response photo to a local state and conditionally rendering it.
import React from "react";
import { Image } from "react-native";
import { Camera } from "expo-camera";
import Constants from "expo-constants";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";

class Cameras extends React.Component(props) {
  state = {
    captures: "",
  };

  takePicture = async () => {
    if (this.camera) {
      let photo = await this.camera.takePictureAsync({
        base64: true,
      });
      this.props.cameraToggle(false);
      this.setState({ captures: photo.uri });
    }
  };

  render() {
    const { captures } = this.state;
    return (
      <View flex={1}>
        {this.state.captures ? (
          <Image source={{ uri: captures }} style={{width:50,height:50}} />
        ) : (
          <Camera {...pass in props} />
        )}
      </View>
    );
  }
}

export default Cameras;

Note:
A more clean approach would be to pass the state captures as a route param by navigating a different screen and rendering the image on that screen.

A: I am assuming you are storing value of photo in cameraImage.
I am sharing a working solution with you using expo image picker, give it a try
Your component
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';

<TouchableHighlight onPress={this._openCamera}>
    <Text>Open Camera</Text>
</TouchableHighlight>

<Image source={this.state.mainImageUrl} />

Your function
_openCamera = async () => {
    await Permissions.askAsync(Permissions.CAMERA);
    try {
        let result: any = await ImagePicker.launchCameraAsync({
            base64: true,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });
        if (!result.cancelled) {
            this.setState({
                mainImageUrl: { uri: `data:image/jpg;base64,${result.base64}` }
            });
        }
    } catch (E) {
        console.warn(E);
    }
}

A: Your code:
 let photo = await this.camera.takePictureAsync({
     base64: true,
 });
 this.props.image(photo)

The takePictureAsync return an object, so your base64 data is in the field photo.base64.
Solution 2
You can store the URI into the state without base64.
const [photoUri, setPhotoUri] = React.useState(null);
  const cameraRef = React.useRef(null);
  const takePhoto = async () => {
      setPhotoUri(null);
      const camera = cameraRef.current;
      if(!camera) return;
      try {
          const data = await camera.takePictureAsync();
          setPhotoUri(data.uri);
      } catch (error) {
          console.log('error: ', error);
      }
  }

Then use it.
return (
     <Image source={{uri: photoUri}} />
);

Hope it helps.


Q: ServiceStack OrmLite Join Issues I'm having a problem with ServiceStack OrmLite for SQL Server in a Visual Studio 2013 C# project. My problem is that I'm trying to use the SqlExpression builder and it's not capturing my table schema and the generated SQL code is not correct. When I run the code, I get a System.Data.SqlClient.SqlException that says "Invalid object name 'ReportPages'."
I'm using the latest NuGet version of ServiceStack.OrmLite, which is version 4.0.24.
Let me start with the table setup. Note that I removed the foreign keys for convenience:
-- Create the report pages table.
CREATE TABLE [MicroSite].[ReportPages](
    [ReportPageID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](200) NULL,
    [Template] [nvarchar](50) NULL,
    [AccessLevel] [int] NOT NULL,
    [AssignedEmployeeId] [int] NOT NULL,
    [Disabled] [bit] NOT NULL,
    [Deleted] [bit] NOT NULL,
    [ReportSectionID] [int] NOT NULL,
    [Index] [int] NOT NULL,
    [Cover] [bit] NOT NULL,
 CONSTRAINT [PK_dbo.ReportSections] PRIMARY KEY CLUSTERED
(
    [ReportPageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

-- Create the report sections table.
CREATE TABLE [MicroSite].[ReportSections](
    [ReportSectionID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NULL,
    [ReportID] [int] NOT NULL,
 CONSTRAINT [PK_dbo.ReportSectionGroups] PRIMARY KEY CLUSTERED
(
    [ReportSectionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

-- Create the report editables table.
CREATE TABLE [MicroSite].[Editables](
    [EditableID] [int] IDENTITY(1,1) NOT NULL,
    [Index] [int] NOT NULL,
    [Content] [nvarchar](max) NULL,
    [Styles] [nvarchar](100) NULL,
    [Type] [int] NOT NULL,
    [ReportPageID] [int] NOT NULL,
 CONSTRAINT [PK_dbo.Editables] PRIMARY KEY CLUSTERED
(
    [EditableID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

So my tables basically look like this:

Here are my POCOs:
[Alias("ReportPages")]
[Schema("MicroSite")]
public partial class MicrositeReportPage : IHasId<int>
{
    [Required]
    public int AccessLevel { get; set; }

    [Required]
    public int AssignedEmployeeId { get; set; }

    [Required]
    public bool Cover { get; set; }

    [Required]
    public bool Deleted { get; set; }

    [Required]
    public bool Disabled { get; set; }

    [Alias("ReportPageID")]
    [AutoIncrement]
    [PrimaryKey]
    public int Id { get; set; }

    [Required]
    public int Index { get; set; }

    public string Name { get; set; }

    [Alias("ReportSectionID")]
    [Required]
    public int ReportSectionId { get; set; }

    public string Template { get; set; }
}

[Alias("ReportSections")]
[Schema("MicroSite")]
public class MicrositeReportSection : IHasId<int>
{
    [Alias("ReportSectionID")]
    [AutoIncrement]
    [PrimaryKey]
    public int Id { get; set; }

    public string Name { get; set; }

    [Alias("ReportID")]
    [Required]
    public int ReportId { get; set; }
}

[Alias("Editables")]
[Schema("MicroSite")]
public partial class MicrositeEditable : IHasId<int>
{
    public string Content { get; set; }

    [Alias("EditableID")]
    [AutoIncrement]
    [PrimaryKey]
    public int Id { get; set; }

    [Required]
    public int Index { get; set; }

    [Alias("ReportPageID")]
    [Required]
    public int ReportPageId { get; set; }

    public string Styles { get; set; }

    [Alias("Type")]
    [Required]
    public int TypeId { get; set; }
}

The actual SQL statement I want to generate is this:
SELECT  e.EditableID
      , e.[Index]
      , e.Content
      , e.Styles
      , e.Type
      , e.ReportPageID
FROM
    MicroSite.ReportSections AS rs
LEFT JOIN
    MicroSite.ReportPages AS rp ON rp.ReportSectionID = rs.ReportSectionID AND rp.[Index] = 24
LEFT JOIN
    MicroSite.Editables AS e ON e.ReportPageID = rp.ReportPageID
WHERE
    rs.ReportID = 15

Here is my C# code:
var query = db.From<MicrositeReportSection>()
              .LeftJoin<MicrositeReportSection, MicrositeReportPage>((section, page) => section.Id == page.ReportSectionId)
              .LeftJoin<MicrositeReportPage, MicrositeEditable>((page, editable) => page.Id == editable.ReportPageId && page.Index == 24)
              .Where<MicrositeReportSection>(section => section.ReportId == 15);

var sql = query.ToSelectStatement();
var result = db.Select<MicrositeEditable>(query)

The generated SQL statement from the sql variable looks like this (I formatted it for readability):
SELECT
    "ReportSectionID",
    "Name",
    "ReportID"
FROM
    "MicroSite"."ReportSections"
LEFT JOIN
    "ReportPages"  ON ("ReportSections"."ReportSectionID" = "ReportPages"."ReportSectionID")
LEFT JOIN "Editables"
    ON (("ReportPages"."ReportPageID" = "Editables"."ReportPageID") AND ("ReportPages"."Index" = 24))
WHERE
    ("ReportSections"."ReportID" = 15)

First, the left joins are missing the schema name, which makes the SQL statement incorrect. Second, what's going on in the select statement? Those aren't the columns from the MicrositeEditable table. Am I doing this correctly or is this an actual bug with OrmLite?

A: I submitted a ticket with the development team and this is now fixed in version 4.0.25.


Q: How do I change user presence status in RingCentral programmatically using C#? I have created as program in C# that is designed to display the users status and availability from RingCentral.
This works brilliantly and I can sort the users by availability, name, etc.
I need to add the functionality to change the status of the user to "Offline".  When the users shift ends they would be set to receive calls when they have gone home, we need to stop that.
The problem I have is that the RingCentral SDK I am using is saying it needs a parameter which should be of type PresenceInfoResource.  here is the path I am using:
rc.Restapi().Account().Extension().Presence().Put();

I have tried various different types but I cannot seem to get, create or cast to a type of PresenceInfoResource.
Does anyone know what it is looking for, how to change the status in c# or where I am going wrong?
I have looked in the RingCentral documentation on line, but can't find anything, only a link to the update presence page which has nothing about PresenceInfoResource:
https://developers.ringcentral.com/api-reference/Presence/updateUserPresenceStatus

A: I got an answer to this from another site:
    var parameters = new PresenceInfoResource();
    parameters.userStatus = "Busy";
    parameters.dndStatus = "TakeAllCalls";
    var resp = await rc.Restapi().Account().Extension().Presence().Put(parameters);
    Console.WriteLine("User presence status: " + resp.userStatus);
    Console.WriteLine("User DND status: " + resp.dndStatus);


Q: CSS Masonry Grid with JQuery .hover hiding images in grid other than hovered image and first column I am building a custom theme for koken based on their Blueprint framework theme and have coded it so the album template loops over all images in the album and outputs the images into a 4 column masonry-like grid using CSS, and a jquery script so that when I hover over an image it changes the opacity of all other images in the grid to 0.4.
The jquery code with the grid works fine in JSFiddle, but when I bring it into the koken theme, whenever an image is hovered, the script works for a second showing all but the hovered image at reduced opacity, but then hiding all the images except for the hovered image and the first column.
The code used for the grid is as follows:
HTML

CSS
#grid {
    /* Prevent vertical gaps */
    line-height: 0;
    -webkit-column-count: 4;
    -webkit-column-gap: 0;
    -moz-column-count: 4;
    -moz-column-gap: 0;
    column-count: 4;
    column-gap: 0;
}
#grid img {
    /* Just in case there are inline attributes */
    width: 100% !important;
    height: auto !important;
}
#grid ul li {
    display: inline;
}
.gridimg {
    opacity:1;
    transition: opacity 0.5s;
}
.opaque {
    opacity:0.4;
    transition: opacity 0.5s;
}

JS
$('img.gridimg').hover(function () {
    $('img.gridimg').not(this).each(function () {
        $(this).toggleClass("opaque");
    });
});

JSFiddle is here: http://jsfiddle.net/jgYY9/3/
Is there something in the koken code that is messing this up? And does anyone know how I can fix it?
Thanks.


Q: Pyplot 3D scatter z axis issue Is there something wrong with the 3d plt.scatter(x,y,z) method?
Plots all z values at zero:
x = [1, 1]
y = [1, 1]
z = [-10, 10]

fig = plt.figure(figsize=(16, 18))
plt.axes(projection ="3d")
plt.scatter(x, y, z, color='k')

plt.show()

Working correctly:
x = [1, 1]
y = [1, 1]
z = [-10, 10]

fig = plt.figure(figsize=(16, 18))
ax = plt.axes(projection ="3d")
ax.scatter(x, y, z, color='k')

plt.show()

A: In your above examples you used the two matplotlib's interfaces: pyplot vs object oriented.
If you'll look at the source code of pyplot.scatter you'll see that even if you are going to provide 3 arguments plt.scatter(x, y, z, color='k'), it is actually going to call the 2D version, with x, y, s=z, s being the marker size.
So, it appears that you have to use the object oriented approach to achieve your goals.


Q: Remove a dead lock in the Internet Explorer on Thread.Sleep? I know all browsers are single threaded and impossible implements in JavaScript or Flash Player Thread.sleep. I decided to try using “System.Threading” library implements Thread.Sleep in the Silverlight.
App.xaml.cs
using System.Windows;
using System.Windows.Browser;
using System.Threading;

namespace ThreadSleep
{
    public partial class App : Application
    {

        public App()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("App", this);
        }

        [ScriptableMember]
        public void Sleep(int mlsec)
        {
            Thread.Sleep(mlsec);
        }
    }
}

So, from a JavaScript code I can execute a Sleep function, but my Internet Explorer freeze and not responding.
Here is my example:
Index.html

<INPUT TYPE="button" value="Pause Modal Dialog" onclick="pause1()">
<INPUT TYPE="button" value="Pause Thread Sleep" onclick="pause2()">

<object id="SleepSL" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="1" height="1">
    <param name="source" value="SleepSL.xap"/>
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.50826.0" />
    <param name="autoUpgrade" value="true" />

</object>

PauseWin.html

<title>Pause Window</title>

    The window will automatically
 close in  second(s).

By executing an index.html file I am starting a YouTube video and timer. When I pressed "Pause Modal Dialog" the timer stops, but video continue playing, after 10 seconds the Modal Popup window destroying by JS “window.close()” and in my code I am going to the next line and executing alert(“Resume”). Nothing change the video continues playing. Now if I will press "Pause Thread Sleep" button using a Silverlight Thread.Sleep function. At this time video will hang and by clicking on the Internet Explorer you may get (Not Responded) state in the Process Explorer.
I will prefer to use Thread.Sleep function in the COM, ActiveX or Silverlight objects, but I need to remove that a thread dead lock. Get the same behavior as in JavaScript Modal Dialog or Alert.
Many thanks in advance.
Regards,
David Gofman
Code:
index.html
PauseWin.html

A: Your code is doing exactly what you're telling it to do: it's sleeping your browser's UI thread, which means that your browser can't process any more messages, so it's effectively hanging your browser for the duration of the sleep.  Thread.Sleep() in a browser is death: just don't do it, whether in Silverlight or any other framework.
A better approach would be to step back and ask yourself why you want to sleep something, and then figure out a reasonable async way of doing that.  Having been thrown into the Silverlight async world several years ago, I realize that this can be disorienting at first, but I can also testify that I've always found reasonably clean ways to do it right.
Another way to put it: if you can't figure out how to do what it is that you actually need to get done, post a question about that, and you'll likely get some help here.
For instance, if you just want to wait 'n' seconds and then perform a callback, you could use a helper class like this one:
public class ThreadingHelper
{
    public static void SleepAsync(int millisecondsToSleep, Action action)
    {
        var timer = new Timer(o => action());
        timer.Change(millisecondsToSleep, Timeout.Infinite);
    }

    public static void SleepAsync(TimeSpan interval, Action action)
    {
        SleepAsync((int)interval.TotalMilliseconds, action);
    }

    public static void DispatcherSleepAsync(int millisecondsToSleep, Action action)
    {
        var interval = TimeSpan.FromMilliseconds(millisecondsToSleep);
        DispatcherSleepAsync(interval, action);
    }

    public static void DispatcherSleepAsync(TimeSpan interval, Action action)
    {
        var timer = new DispatcherTimer();
        EventHandler timerHandler = null;
        timerHandler = (s, e) =>
        {
            timer.Tick -= timerHandler;
            if (action != null)
            {
                action();
            }
        };
        timer.Tick += timerHandler;
        timer.Interval = interval;
        timer.Start();
    }

}

A: You could do this:
function begin() { /* do stuff... */ }
function afterWait() { /* rest of my code...*/ }

begin();
setTimeout(afterWait, 10000);
setTimeout has effectively stopped your javascript for 10 seconds, and the browser can still carry on working


Q: Progress bar hangs while deleting large files I have added the loading bar in below snippet.It’s worked fine which I have deleted small amount of data(say 30 to 150 mb). But the problem is when I deleted large size of data, the loading bar doesn't get loaded(approx 190mb).
dispatch_async(dispatch_get_main_queue(), ^{

    [self addloading];
    if(_isProgress)
        return;
    _lastDeleteItemIndexAsked = index;
    NSInteger catalogue_id =[[[_currentData  objectAtIndex:index%[_currentData count]] valueForKey:@"catalogue_id"] integerValue];
    BOOL update_avilable = [[[online_date_array objectAtIndex:index%[_currentData count]] valueForKey:@"update_version"] boolValue];
       if(update_avilable)
        [[self GridViewDelegate] deletecatlogue_for_update:catalogue_id];
    else
        [[self GridViewDelegate] deletecatlogue:catalogue_id];

    [online_date_array replaceObjectAtIndex:index%[online_date_array count] withObject:[NotificationHandler check_online_date_of_catalogue:catalogue_id]];

    [_gmGridView reloadObjectAtIndex:index%[_currentData count] withAnimation:GMGridViewItemAnimationFade];

    [self stopLoadingfor_delete];

});

A: Is it size or execution time?
I'm going to assume that self is a UI object. If it is, the block should be:
Controller* __weak weakSelf = self;
dispatch_async(queue, ^{
    Controller* strongSelf = weakSelf;
    if (strongSelf) {
        ...
    }
    else {
       // self has been deallocated in the meantime.
    }
});

Thus you may prefer a MVVC solution, where a view model does the hard work, not the view controller.


Q: Unable to publish dependencies into private npm repository I have created a private nexus repository to host my custom nodejs libraries. But when I publish my package, it doesn't publish any of its dependencies.
Steps:
npm set registry <registry url>
npm login
npm publish

package.json
{
  "name": "testpackage",
  "version": "1.0.0",
  "private": false,
  "dependencies": {
    "request": "^2.87.0",
    "safe-access": "0.1.0",
    "winston": "^2.4.2"
  },
  "main": "index.js",
  "directories": {
    "test": "tests"
  },
  "devDependencies": {},
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

I get this issue when I try to install my package
npm install testpackage
npm ERR! code E404
npm ERR! 404 Not Found: ieee754@1.1.8
npm ERR! A complete log of this run can be found in:
npm ERR! /<path>/.npm/_logs/2018-10-04T11_25_36_719Z-debug.log

Is there a way to publish node_modules/all transitive dependencies into nexus? (Note: I will not be having internet access in production environment. Hence I need to download all dependencies from private repo itself)

A: No.
What you're describing is exactly what Nexus Repository Manager designed groups for but your internetless scenario removes that from the equation.
Your only recourse is manual upload.

A: I have solved the issue as follows:
I used a npm-group repository and added a npm-hosted repository and a cache enabled npm-proxy (Only this repository has internet access).
Steps to add new packages to the repository:
1) Add the repo to a dummy package.json
2) npm install. (All the required packages get cached)
3) I point proxy-url to some junk url. (To avoid unwanted code to come into my environment).
Steps to use the repository:
1) npm set registry [npm-group-repo url]
2) npm install


Q: Solr-Atomic Update changes other fields While running on atomic update,language field is getting changed.We have flow as below.
During indexing object posted is
{
id:"234-567",
fileName:"file1",
content:""
}
In the pipeline we analyse content as part of language detection and create a new field "language" which is working as expected.
But while doing atomic update
{
id:"as above"
fileName:"changed"
}
to change fileName,we make use to "set" operation which is updating field correctly but language field is getting changed to fallback value.
What is happening here?Is it looking for content field to analysis again?Does atomic update also goes through processing pipeline

A: I'm guessing the language detection is run again, and there is no value available for that field for the language detection to actually detect anything for.
Run updates without language detection unless you're including the field you're running language detection on.
You might have to define a second request handler without the language detection settings if you have those defined as static settings in your request handler configuration.


Q: In Reactjs production mode, my app does not change url and not rendering component while I use Browser router, but it works fine with hashrouter index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './home'
import {Link,Switch,Route,BrowserRouter} from 'react-router-dom'

ReactDom.render(
    <BrowserRouter>
        <Link to="/home">Home</Link>
        <Switch>
            <Route path="/home" exact component={Home}/>
        </Switch>
    </BrowserRouter>, document.getElementById('root'))

HashRouter works in production mode but BrowserRouter doesn't change urls and not rendering component also


Q: X Error of failed request: GLXBadFBConfig (opengl 4.3 - ubuntu) I'm reading the last version of the OpenGL Programming guide and it is updated for OpenGL 4.3.
The first code they go through is a really simple code to make 2 triangles and of course it is the code I use to test OpenGL on my latop (running kubuntu).
The code runs but this is what happens :

X Error of failed request:  GLXBadFBConfig
Major opcode of failed request:  153 (GLX)
Minor opcode of failed request:  34 ()
Serial number of failed request:  34
Current serial number in output stream:  33
RUN FINISHED; exit value 1; real time: 200ms; user: 0ms; system: 0ms

I saw that can happend if you don't have a graphic card that can handel the version of OpenGL you are using.
But on my laptop I have a NVidia 555m so according to the nvidia website I'm good on that side but since I run ubuntu and NVidia are not really good with their drivers I'm sure not that my NVidia-current with bumblebee works for OpenGL 4.3.
How can I check the version supported by my setup ?
Is there anyway for me to make it work or do I need to install Windows :/ ?

A: glxinfo is your friend. It's a command line tool which will report the version numbers and extensions supported for server side GLX, client side GLX, and OpenGL itself.
Do you have the NVIDIA binary (proprietary) driver installed? You'll need it if you want to take advantage of OpenGL versions 3 or 4. Like every software product there are occasional glitches, but over the years I think most 3D programmers / users would agree that the NVIDIA drivers for Linux have been very solid, much better than the alternatives.


Q: jQuery hyperlinks open a link before my onclick event In my popup page, I have a link with properties:
 id="myLink" href="http://..." target="_blank"
when user click the link, it should open the link as default event and then close the popup window.
I have following jquery code in the popup page to close popup window.
 $('#myLink').click(function() {
                ClosePopupOverlay();
            });

Now it works fine in IE, but in firefox and Chrome, it just close the popup window, doesn't open the link at all.
Can we not prevent default event and add custom code in jquery in all browsers? Any ideas on how to fix this issue?
Thanks a lot for any help!

A: Have a look at this thread: event.stopPropagation() not working in chrome with jQuery 1.7
I helped him solve this exact issue.


Q: Bootstrap CSS transition onhover Hi I'm trying to replicate the beautiful CSS transition dropdown menu onhover of devdojo.com (https://devdojo.com/ebook/laravelsurvivalguide) but can't replicate it. It is the onhover of the 3 dots in the main menu. Maybe I'm missing something? Thanks!
My CSS:
.dropdown-menu-animated {
    border: 0 none;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
    display: block;
    margin-top: 0;
    opacity: 0;
    transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
    transform-origin: 100% 0 0;
    transition-delay: 0s, 0s, 0.5s;
    transition-duration: 0.5s, 0.5s, 0s;
    transition-property: opacity, transform, visibility;
    transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
    visibility: hidden;
}

.dropdown-menu {
    background-clip: padding-box;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
    display: none;
    float: left;
    font-size: 14px;
    left: 0;
    list-style: outside none none;
    margin: 2px 0 0;
    min-width: 160px;
    padding: 5px 0;
    position: absolute;
    top: 100%;
    z-index: 1000;
}
.open > .dropdown-menu-animated {
    visibility: visible;
    opacity: 1;
    transition: opacity .5s, -webkit-transform .5s;
    transition: opacity .5s, transform .5s;
    transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
    -webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
    transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}

My HTML:

                            HOVER ME

                    Sushi Points

Two

Thanks @chiller .

Updated and edited answer:

JS
$('.dropdown-toggle').hover(function() {
    $(this).parent().addClass("open");
});

$('.dropdown').mouseleave(function() {
    $(this).removeClass("open");
});

CSS
.dropdown-menu li a {
    color: white;
}
.dropdown-menu-animated {
    border: 0 none;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
    display: block;
    margin-top: 0;
    opacity: 0;
    transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
    transform-origin: 100% 0 0;
    transition-delay: 0s, 0s, 0.5s;
    transition-duration: 0.5s, 0.5s, 0s;
    transition-property: opacity, transform, visibility;
    transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
    visibility: hidden;
}
.dropdown-menu {
    background-clip: padding-box;
    background-color: #fff;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
    /*display: none;*/
    float: left;
    font-size: 14px;
    left: 0;
    list-style: outside none none;
    margin: 2px 0 0;
    min-width: 160px;
    padding: 5px 0;
    position: absolute;
    top: 100%;
    z-index: 1000;
}
.open > .dropdown-menu-animated {
    visibility: visible;
    opacity: 1;
    transition: opacity .5s, -webkit-transform .5s;
    transition: opacity .5s, transform .5s;
    transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
    -webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
    transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}

HTML

                            HOVER ME

Bulanching

Kuya Matmat

Baby

Wedding

Excited

A: this actually done with JavaScript and all you have to do is add this jquery code in your script
$('.dropdown-toggle').hover(function() {
  $(this).parent().addClass("open");
});

$('.dropdown').mouseleave(function() {
  $(this).removeClass("open");
});

and you have to remove display: none; from the class .dropdown-menu for the animation to work
see your example here
you can also make it work with CSS only by adding this code:
.dropdown:hover>.dropdown-menu-animated{

    visibility: visible;
    opacity: 1;
    transition: opacity .5s, -webkit-transform .5s;
    transition: opacity .5s, transform .5s;
    transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
    -webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
    transform: scale3d(1, 1, 1) translate3d(0, 0, 0);

}

See your example with CSS only

A: The following snippet solves your styling issue for the :hover appearance.
Add your transition effect in the .dropdown .dropdown-menu-animated rules and there you go ;)

.dropdown {
    float: left;
    cursor: pointer;
}
.dropdown .dropdown-menu-animated {
    border: 0 none;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
    margin-top: 20px;
    transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
    transform-origin: 100% 0 0;
    transition-delay: 0s, 0s, 0.5s;
    transition-duration: 0.5s, 0.5s, 0s;
    transition-property: opacity, transform, visibility;
    transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
    visibility: hidden;
}

.dropdown:hover .dropdown-menu-animated {
    visibility: visible;
}

            HOVER ME

                    Sushi Points

Two


Q: Safe truncate string contains color tag I have a string which contains color tags.
var myString = "My name is <color=#FF00EE>ABCDE</color> and I love <color=#FFEE00>music</color>";

My string becomes "My name is ABCDE*(pink)* and I love music*(yellow)*"
I want to truncate if the string reaches max length but still keep color tag
var myTruncateString = "My name is <color=#FF00EE>ABCDE</color> and I love <color=#FFEE00>mu</color>";

My string becomes "My name is ABCDE*(pink)* and I love mu*(yellow)*"
Do you have any suggestion?
var stringWithoutFormat = String.Copy(myString);
stringWithoutFormat = Regex.Replace(stringWithoutFormat, "<color.*?>|</color>", "");

var maxLength = 20;
if (stringWithoutFormat.Length > maxLength)
{
    // What should I do next?
}

A: Here's a relatively simply and NOT error-handling example of what I think you're trying to accomplish:

*

*Don't count color tags when checking maximum length

*Remove characters from the end, don't destroy color tags

*If you end up with color tags with no text between them, remove those tags

Note: This code is not thoroughly tested. Feel free to use it for whatever you want, but I would write a lot of unit-tests here. In particular I'm scared about the existance of edge-cases that lead to an infinite loop.
public static string Shorten(string input, int requiredLength)
{
    var tokens = Tokenize(input).ToList();
    int current = tokens.Count - 1;

    // assumption: color tags doesn't contribute to *visible* length
    var totalLength = tokens.Where(t => t.Length == 1).Count();

    while (totalLength > requiredLength && current >= 0)
    {
        // infinite-loop detection
        if (lastCurrent == current && lastTotalLength == totalLength)
            throw new InvalidOperationException("Infinite loop detected");
        lastCurrent = current;
        lastTotalLength = totalLength;

        if (tokens[current].Length > 1)
        {
            if (current == 0)
                return "";

            if (tokens[current].StartsWith("</") && tokens[current - 1].StartsWith("<c"))
            {
                // Remove a <color></color> pair with no text between
                tokens.RemoveAt(current);
                tokens.RemoveAt(current - 1);
                current -= 2;

                // Since color tags doesn't contribute to length, don't adjust totalLength
                continue;
            }

            // Remove one character from inside the color tags
            tokens.RemoveAt(current - 1);
            current--;
            totalLength--;
        }
        else
        {
            // Remove last character from string
            tokens.RemoveAt(current);
            current--;
            totalLength--;
        }
    }

    // If we're now at the right length, but the last two tokens are <color></color>, remove them
    if (tokens.Count >= 2 && tokens.Last().StartsWith("</") && tokens[tokens.Count - 2].StartsWith("<c"))
    {
        tokens.RemoveAt(tokens.Count - 1);
        tokens.RemoveAt(tokens.Count - 1);
    }
    return string.Join("", tokens);
}

public static IEnumerable<string> Tokenize(string input)
{
    int index = 0;
    while (index < input.Length)
    {
        if (input[index] == '<')
        {
            int endIndex = index;
            while (endIndex < input.Length && input[endIndex] != '>')
                endIndex++;
            if (endIndex < input.Length)
                endIndex++;
            yield return input.Substring(index, endIndex - index);
            index = endIndex;
        }
        else
        {
            yield return input.Substring(index, 1);
            index++;
        }
    }
}

Example code:
var myString = "My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>";
for (int length = 1; length < 100; length++)
    Console.WriteLine($"{length}: {Shorten(myString, length)}");

Output:
1: M
2: My
3: My
4: My n
5: My na
6: My nam
7: My name
8: My name
9: My name i
10: My name is
11: My name is
12: My name is <color=#ff00ee>A</color>
13: My name is <color=#ff00ee>AB</color>
14: My name is <color=#ff00ee>ABC</color>
15: My name is <color=#ff00ee>ABCD</color>
16: My name is <color=#ff00ee>ABCDE</color>
17: My name is <color=#ff00ee>ABCDE</color>
18: My name is <color=#ff00ee>ABCDE</color> a
19: My name is <color=#ff00ee>ABCDE</color> an
20: My name is <color=#ff00ee>ABCDE</color> and
21: My name is <color=#ff00ee>ABCDE</color> and
22: My name is <color=#ff00ee>ABCDE</color> and I
23: My name is <color=#ff00ee>ABCDE</color> and I
24: My name is <color=#ff00ee>ABCDE</color> and I l
25: My name is <color=#ff00ee>ABCDE</color> and I lo
26: My name is <color=#ff00ee>ABCDE</color> and I lov
27: My name is <color=#ff00ee>ABCDE</color> and I love
28: My name is <color=#ff00ee>ABCDE</color> and I love
29: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>m</color>
30: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mu</color>
31: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mus</color>
32: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>musi</color>
33: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
34: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
35: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
36: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
37: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
38: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
39: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
... and so on

A: I generate 2 lists :

*

*One that contains the indexes of the real text

*One that contains the staring and ending indexes of tags

Then I take the text until the max length in the first array.
Finally, I check if there was an opening tag and if so, I close it.
N.B. : My code doesn't handle nested tags. You'd have to change the closing tag part.
public static string Truncate(string text, int maxLength)
    {
        if (text.Length <= maxLength) return text;

        var tagIndexes = new List<int>();
        var realTextIndexes = new List<int>();
        bool isInTag = false;
        for (int i = 0; i < text.Length; i++)
        {
            if (text[i] == '<')
            {
                isInTag = true;
                tagIndexes.Add(i);
            }

            if (!isInTag)
            {
                realTextIndexes.Add(i);
            }

            if (text[i] == '>')
            {
                isInTag = false;
                tagIndexes.Add(i);
            }
        }

        if (realTextIndexes.Count <= maxLength) return text;

        string truncatedText = text.Substring(0, realTextIndexes[maxLength - 1] + 1);

        // Should we close a tag ?
        for (int i = 0; i < tagIndexes.Count; i++)
        {
            if (tagIndexes[i] > realTextIndexes[maxLength - 1])
            {
                if ((i % 4) == 2) // If the next tag is a closing tag
                {
                    truncatedText += text.Substring(tagIndexes[i], tagIndexes[i + 1] - tagIndexes[i] + 1);
                }

                break;
            }
        }

        return truncatedText;
    }


Q: Amazon ec2-get-console-output returns "File not found" I just set up a free instance of an Amazon ec2 server. I'm trying to figure out how to SSH into it. I downloaded the command line tools for ec2 and, following what was written at this page: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#EC2_LaunchInstance_Linux :
.ec2$ ec2-get-console-output [instance id]
File not found: ''
.ec2$

Where [instance id] refers to the id amazon lists in the list of instances I have. Can anyone tell me what's going on?
Edit: I might add it seems to be doing this for any binary I try to run from the command line tools... even if I call them directly.

A: I had the same problem until I specified the key and cert in my .bash_profile file:

export EC2_HOME=~/.ec2
export PATH=$PATH:$EC2_HOME/bin
export EC2_PRIVATE_KEY='ls $EC2_HOME/key.pem'
export EC2_CERT='ls $EC2_HOME/cert.pem'


Q: How to get userId for custom action in SharePoint When implementing a List Menu Custom Action in Sharepoint 2013 I have problem getting which user has actually executed the custom action. I would like to do that to check that the user has permission to do this by checking which AD-groups the user is a member of. When I try to resolve the user with the Tokenhelper class it will only return the SharePoint system account sending the query to the Host Web. Is there any way you could attach the userId in the UrlAction parameters like below?
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="77cb35d9-1bf3-4d81-91cf-8a92473a6092.MenuItemCustomAction1"
            RegistrationType="List"
            RegistrationId="101"
            Location="EditControlBlock"
            Sequence="10001"
            Title="$Resources:TogglePublic"
            HostWebDialog="TRUE"
            HostWebDialogHeight="250"
            HostWebDialogWidth="700">

<UrlAction Url="~remoteAppUrl/CustomActionTarget.aspx?StandardTokens}&SPListItemId={ItemId}&SPListId={ListId}&SPSource={Source}&SPListURLDir={ListUrlDir}&SPItemURL={ItemUrl}&SPUserId={_spPageContextInfo.userId}" />
</CustomAction>
</Elements>

On the Host Web the following code should get the SPUserId:
public partial class CustomActionTarget : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        string userId = this.Request.QueryString["SPUserId"];
    }
}

The _spPageContextInfo.userId is a javascript variable that should contain the current user, but I have not found any way to actually resolve and send the userId to the SharePoint App's Host Web using the UrlAction.


Q: Netfilter kernel module packet send I am trying to send a dummy syn packet from netfilter kernel module but i could not succeded does any body has working example or show me where i am doing the mistake
printk(KERN_ALERT "Device a");
struct sk_buff *skb = NULL;
struct iphdr *iph = NULL;
struct tcphdr *tcph = NULL;
printk(KERN_ALERT "Device index");
skb = alloc_skb(sizeof(struct iphdr) + sizeof(struct tcphdr), GFP_ATOMIC); // Allocate a new sk_buff with room for L2 header.

if (skb == NULL){
    return;
}

skb->protocol = __constant_htons(ETH_P_IP); // This is an IP packet.
skb->pkt_type = PACKET_OUTGOING; // Its outgoing.
skb->ip_summed = CHECKSUM_NONE; // No need to checksum.

skb_reserve(skb, sizeof(struct iphdr) + sizeof(struct tcphdr)); // Reserve the space for the L3, and L4 headers.
tcph = (struct tcphdr *)skb_push(skb, sizeof(struct tcphdr)); // Setup pointer for the L4 header.
iph = (struct iphdr *)skb_push(skb, sizeof(struct iphdr)); // Setup pointer for the L3 header.

iph->ihl = 5; // IP header length.
iph->version = 4; // IPv4.
iph->tos = 0; // No TOS.
iph->tot_len=htons(sizeof(struct iphdr) + sizeof(struct tcphdr)); // L3 + L4 header length.
iph->id = 0; // What?
iph->frag_off = 0; // No fragmenting.
iph->ttl = 64; // Set a TTL.
iph->protocol = IPPROTO_TCP; // TCP protocol.
iph->check = 0; // No IP checksum yet.
iph->saddr = saddr; // Source IP.
iph->daddr = daddr; // Dest IP.
tcph->check = 0; // No TCP checksum yet.
tcph->source = source; // Source TCP Port.
tcph->dest = dest; // Destination TCP Port.
tcph->seq = htonl(seq - 1); // Current SEQ minus one is used for TCP keepalives.
tcph->ack_seq = htonl( ack_seq - 1); // Ummm not sure yet.
tcph->res1 = 0; // Not sure.
tcph->doff = 5; // TCP Offset.  At least 5 if there are no TCP options.
tcph->fin = 0; // FIN flag.
tcph->syn = 0; // SYN flag.
tcph->rst = 0; // RST flag.
tcph->psh = 0; // PSH flag.
tcph->ack = 1; // ACK flag.
tcph->urg = 0; // URG flag.
tcph->ece = 0; // ECE flag? It should be 0.
tcph->cwr = 0; // CWR flag? It should be 0.

//ip_route_input(skb, daddr, saddr, iph->tos, netdevice); // Populate the skb->dst structure.
//ip_send_check(iph); // Calulcate an IP checksum.
//skb->dev = skb->dst->dev; // Populate skb->dev or it wont send.
//printk(KERN_ALERT "SKB device index: %u.\n",skb->dev->ifindex);
//printk(KERN_ALERT "Route device index: %u.\n",skb->dst->dev->ifindex);

printk(KERN_ALERT "Device index2");
struct net_device *dev;
read_lock(&dev_base_lock);
dev = first_net_device(&init_net);
while (dev) {
    printk(KERN_INFO "found [%s]\n", dev->name);
    if(dev->name=="p1p2"){printk(KERN_INFO "found [%s]\n", dev->name);break;}
    dev = next_net_device(dev);
}

read_unlock(&dev_base_lock);

//NF_HOOK(PF_INET, NF_INET_LOCAL_OUT,NULL, NULL, skb, NULL, dev, dst_output);
printk(KERN_ALERT "Device index3");
return;


Q: DICOM CINE file C#.Net I have read the first frame of a DICOM CINE image, then I want to read the second frame and so on. How much byte should I seek the file pointer to get next frame(If the frame size is width=640, height=480).

A: by DICOM cine image, you mean multi-frame DICOM files right?
May i know :
which platform you are on, which dicom lib/SDK you are using? and for your DICOM image, has it been decompressed? to BMP(32-bit/24-bit)?
If your dicom file is in 24bit(3-bytes) BMP, then your next frame of pixel data would be 640*480*3.

A: Assuming you are dealing with uncompressed (native) multi-frame DICOM. In that case, you need to extract following information before proceeding to calculate the size of each image frame.

*

*Transfer Syntax (0002, 0010) to make sure dataset set is not using
encapsulated/compressed transfer syntax.

*Sample per Pixel (0028, 0002): This represents number of samples
(planes) in this image. As for example 24-bit RGB will have value of
3

*Number of Frames (0028, 0008): total number of frames

*Rows (0028, 0010)

*Columns (0028, 0011)

*Bit Allocated (0028, 0100): Number of bits allocated for each pixel
sample.

*Planar Configuration (0028, 0006): Conditional element that indicates
whether the pixel data are sent color-by-plane or color-by-pixel.
This is required if Samples per Pixel (0028, 0002) has a value
greater than 1.

You would calculate the frame size as follows:
Frame size in bytes = Rows * Columns * (Bit Allocated* Sample per Pixel/8)


Q: Alt tag possible for inline SVG? Is there a way to give an inline SVG an alt tag? Here is the code that I have for my inline SVG, but the alt tag is not showing (and I'm not even sure the way that I coded the alt tag is valid, after searching online for clarification):
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve" alt="Hello world!">
    <path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
    <g>
    <path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
    </g>
</svg>

And here is the JSFiddle: http://jsfiddle.net/FsCMM

A: With <title> it works nice, the below example shows title (acts like alt for images) for more than one path:

<svg height="200pt" viewBox="0 0 200 200" width="200pt" style="background-color: var(--background);">
    <g>
        <title>Gray path</title>
        <path fill="none" stroke="gray" stroke-width="20" d="M 179.89754857473488 95.95256479386293 A 80 80 0 0 0 100 20">
        </path>
    </g>
    <g>
        <title>Red path</title>
        <path fill="none" stroke="red" stroke-width="20" d="M 91.90160519334194 179.58904448198567 A 80 80 0 0 0 179.89754857473488 95.95256479386293">
        </path>
    </g>
    <g>
        <title>Blue path</title>
        <path fill="none" stroke="blue" stroke-width="20" d="M 32.111795102681654 57.67752800438377 A 80 80 0 0 0 91.90160519334194 179.58904448198567">
        </path>
    </g>
    <g>
        <title>Green path</title>
        <path fill="none" stroke="green" stroke-width="20" d="M 99.99999999999999 20 A 80 80 0 0 0 32.111795102681654 57.67752800438377">
        </path>
    </g>
</svg>

A: You should use title element, not alt tag, to display tooltips:
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve">
    <title>Hello world!</title>
    <path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
    <g>
        <path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
    </g>
</svg>

for chrome34: wrap graphics by g element and insert title element to this.
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve">
<g>
    <title>Hello world!</title>
    <path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
    <g>
        <path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
    </g>
</g>
</svg>


Q: Fast associative arrays or maps in Matlab I need to build a fast one-to-one mapping between two large arrays of integers in Matlab. The mapping should take as input an element from a pre-defined array, e.g.:
in_range    = [-200   2  56   45 ... ];

and map it, by its index in the previous array, to the corresponding element from another pre-defined array, e.g.:
out_range   = [-10000 0  97   600 ... ];

For example, in the case above, my_map(-200) should output -10000, and my_map(45) should output 600.
I need a solution that

*

*Can map very large arrays (~100K elements) relatively efficiently.

*Scales well with the bounds of in_range and out_range (i.e. their min and max values)

So far, I have solved this problem using Matlab's external interface to Java with Java's HashMaps, but I was wondering if there was a Matlab-native alternative.
Thanks!

A: The latest versions of Matlab have hashes.  I'm using 2007b and they aren't available, so I use structs whenever I need a hash.  Just convert the integers to valid field names with genvarname.


Q: Can't upload images to WordPress I am trying to upload images via the dashboard but it gives me the following error,
Unable to create directory uploads/2015/03. Is its parent directory writable by the server?

I read forum posts online which guided to change the folder permissions to 777. I did so but the error is still there. Please guide me. Thanks.
Note: I have also updated to the latest version of WordPress but that does not solve the problem.

A: Many of the people face this problem this is just a permission Issue
Follow Below Step
1)Open Ftp by filezilla or any ftp client
2)Right Click on Wp_contnet Folder
3) Change Permissions From 755 TO 777(Please Make Sure That 777  permission to all in side folder's under wp_content)
4) Than Try to Upload File Agin and its'done

A: If you checked the permission then try this solution :
Please login to the wordpress dashboard ( http://www.domainname.com/wp-admin ) and access the Miscellaneous settings. Find the uploads path specified, it will most likely be specified as:
"/wp-content/uploads/
Change it to read
"wp-content/uploads/

A: change your wp-content folder's writing permission
Step 1: Open your File Manager and navigate to the file or folder that you need to change.
Step 2: Click on the name of the file or folder.
Step 3: Click on the Change Permissions link in the top menu of the File Manager page.
Step 4: Click on as many check boxes as you require to create the right permission. The permission numbers underneath the check boxes will update automatically.
Step 5: Click on the Change Permissions button when you are ready. The new permission level is saved and the display updated to show the modified file.

A: Some time when you upload image so this issue arise just try to change  permission level to 744 but select only for directories and  try to change the permission level to 644 this time for files hope this will works for you .


Q: Thread-safe classes explanation in Java Let's consider this situation:
public class A {
    private Vector<B> v  = new Vector<B>();
}

public class B {
    private HashSet<C> hs = new HashSet<C>();
}

public class C {
    private String sameString;

    public void setSameString(String s){
          this.sameString = s;
    }
}

My questions are:

*

*Vector is thread-safe so when a thread calls over it, for instance, the get(int index)method Is this thread the only owner ofHashSeths?

*If a thread call get(int index) over v and it obtains one B object. Then this thread obtains a C object and invoke setSameString(String s) method, is this write thread-safe? Or mechanism such as Lock are needed?

A: First of all, take a look at this SO on reasons not to use Vector. That being said:
1) Vector locks on every operation. That means it only allows one thread at a time to call any of its operations (get,set,add,etc.). There is nothing preventing multiple threads from modifying Bs or their members because they can obtain a reference to them at different times. The only guarantee with Vector (or classes that have similar synchronization policies) is that no two threads can concurrently modify the vector and thus get into a race condition (which could throw ConcurrentModificationException and/or lead to undefined behavior);
2) As above, there is nothing preventing multiple threads to access Cs at the same time because they can obtain a reference to them at different times.
If you need to protect the state of an object, you need to do it as close to the state as possible. Java has no concept of a thread owning an object. So in your case, if you want to prevent many threads from calling setSameString concurrently, you need to declare the method synchronized.
I recommend the excellent book by Brian Goetz on concurrency for more on the topic.

A: In case 2. It's not thread-safe because multiple threads could visit the data at the same time. Consider using read-write lock if you want to achieve better performance. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html#readLock()


Q: Using testthat with more than one expected outcome I wish to check an R function that may output one of two acceptable values using the "testthat" package.  Here's a simplified example:
Foo <- function () {
  if (uncontrolable_condition) {
    matrix(as.raw(0x0c))
  } else {
    matrix(as.raw(0x03))
  }
}

The best solution I could come up with is
result <- Foo()
expect_true(identical(result, matrix(as.raw(0x0c))) ||
            identical(result, matrix(as.raw(0x03))))

But this loses the functionality of waldo::compare: if I fail the test,
I have to manually run waldo::compare(Foo(), matrix(as.raw(0x0c))) to see how the output differs from the expectation.

A: I think you're going to need a custom expectation. Based on the testthat pkgdown site, it might look something like this:
expect_options <- function(object, options) {

  # 1. Capture object and label
  act <- quasi_label(rlang::enquo(object), arg = "object")

  # 2. Call expect()
  compResults <- purrr::map_lgl(options, ~identical(act$val, .x))
  expect(
    any(compResults),
    sprintf(
      "Input (%s) is not one of the accepted options: %s",
            toString(act$val),
            paste(purrr::map_chr(options, toString), collapse = ", ")
    )
  )

  # 3. Invisibly return the value
  invisible(act$val)

}

expect_options(result, list(matrix(as.raw(0x0c)), matrix(as.raw(0x03))))


Q: Is there a way to uniquely identify email addresses, phones, etc. with Microsoft Graph API? Trying to set up a 2-way sync with Graph contacts. When I receive a response from Graph for a specific contact I can't seem to find a way to uniquely identify the phone/email attributes.
In my use case, each email address and phone number are separate entities with a unique id identifying them. This solves for the edge case of having multiple addresses or numbers of the same type (i/e home, work, school, mobile).
In a perfect world, I would like to be able to send metadata along with each phone/email entity that uniquely identifies it on creation in Graph. That way when I set up a subscription or even query the contact, I can directly map the returned contact objects phone/email to our specific phone/email.
Is this possible? I know Google has ids that solve for this.

A: Outlook Contacts are structured a little differently than Google Contacts. Rather than having a single gd:phoneNumber property with distinct rel values, Outlook uses distinct phone number properties.
It's also important to keep in mind that some phone number properties are collections rather than single values (i.e. homePhones). These collections are ordered so these collections can be maps back to Outlook's UI pretty easily. For example, homePhones[0] holds the "Home Phone" value while homePhones[1] holes "Home Phone 2".
In terms of a 1:1 mapping:

*

*http://schemas.google.com/g/2005#home == homePhones[0]

*http://schemas.google.com/g/2005#work == businessPhones[0]

*http://schemas.google.com/g/2005#mobile == mobilePhone
Finally, Microsoft Graph only returns a limited set of phone numbers by default. In my experience, the set returned by Graph is almost always sufficient but there are certainly some edge cases (the healthcare sector still makes use of pagers for example).
You can access these additional phone numbers using Extended Properties. This is done by requesting specifically requesting a given property using the MAPI tag name.
For example, if you need to retrieve the Pager property, you can request the MAPI identifier 0x3A21 as an extended property:
/v1.0/me/contacts?$expand=singleValueExtendedProperties($filter=id eq 'String 0x3A21')

You can find the complete list of MAPI properties here.

A: "homePhones": [],
"mobilePhone": "124124124124",
"businessPhones": [
     "+86 (510) 12114142"
],
"spouseName": null,
"personalNotes": "",
"children": [],
"emailAddresses": [
   {
   "name": "Charles Test(test@microsoft.com)",
   "address": "Test.Test@microsoft.com"
   }
],
"homeAddress": {},
"businessAddress": {
   "city": "Wuxi"
},
"otherAddress": {}

As you know, the phone reference is not unique, user can share same phone number, so it cannot be used as uniquely identify in all MS Authentication API, unless the phone reference is user's id. So it is not possible for your perfect world.
For the same reason, user can share the same address reference, so it is cannot be used as uniquely identify in all MS Authentication API.  So it is not possible for your perfect world too.