text:
Q: Is there a way for users of my website to invite their friends via Facebook Connect or the API? Working with the Facebook API makes my ears bleed, but nonetheless I've got a specific problem here which I'm hoping someone can find a solution for. I'm using the Facebook PHP SDK to allow users of my website to link their FB account with their website account, so they can return later and log in with one click (by storing their OAuth tokens in my database). This is all working fine - what I now want is to be able to provide users with the facility to invite/recommend their friends to my site, using a form on my site.
I've tried FBML examples from many places including here - I've managed to get an invitation form to display but try as I might, all I can get it to generate is an invitation to my application, which isn't relevant. The app exists only so that I have an OAuth ID/secret to use with the Graph API. I want to invite the user's friends to my website, or at the very least to a Facebook Page plugging my website. But seemingly including this FBML on my page will only generate application invites.
My question: is there any way to accomplish this? Can I invite the user's friends to my site (ie. to a specific URL), or invite them to my FB Page? Am I approaching this from the wrong angle?
Any advice would be much appreciated. If you'd benefit from any further info, please let me know. Many thanks,
Biggs

A: Right. It turns out after much tearing of hair, the example I gave was the right one. The invite generates an "Application Invite", but this is not like other app invites. When the recipient clicks "Accept" they are sent to the URL you specify (in this case, my website). The "App" then disappears from their request page - it does not appear in their profile like a normal app. So a horribly nonsensical process but a positive outcome. Phew!

A: It seems like sending a Facebook message is the way to go at this point (Jan 2013).
https://developers.facebook.com/docs/reference/dialogs/send/

In general, applications on Facebook should use Requests when
  communicating in game status (its your turn), inviting people to use
  an application, or sending messages to multiple people.

FB.init({appId: 'YOUR_APP_ID', xfbml: true, cookie: true});

FB.ui({
    method: 'send',
    name: 'Check out this site!',
    description: 'This is the best site ever!',
    link: 'http://www.example.com/refer',
    picture: 'http://www.example.com/image.jpg'
});

A: Why not go for this open source inviter which can get your work done quick . also if you are using a cms they might have already made the plugin for your cms. http://openinviter.com/


text:
Q: JSP File is having content but not showing content I was working in my project using netbeans 8.02
in JSP ,and i have faced a power cut and regaining the power my file is showing size of 192kb but on opening it I am not getting any content visible

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use seccomp filter with ebpf? I'm looking for an example of  eBPF to write a seccomp filter, but I can't find none. Could someone tell me if is possible to use eBPF to write seccomp filter?

A: Seccomp does not work with eBPF at the moment (only cBPF).
There was a discussion not long ago on that topic on the Linux networking mailing list. The eBPF maintainer is against adding eBPF support to seccomp.

A: Kernel Runtime Security Instrumentation (KRSI) was designed for this. It's already been merged into the kernel.


text:
Q: Show sub window in main window Can't work out how to embed a window in a main window using classes:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
Qt4 tutorial using classes

This example will be built
on over time.
"""

import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):

    def __init__(self, MainWindow):
        super(Form, self).__init__()

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.setGeometry(50, 50, 1600, 900)
        new_window = Form(self)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

This is supposed to be the single most basic bit of code using classes. How do I get the second window to show please.

A: As ekhumoro already pointed out, your widget needs to be a child of your mainWindow. However, I do not think that you need to call show for the widget, since it anyways gets called as soon as its parent (MainWindow) calls show. As mata pointed out correctly, the proper way to add a Widget to a MainWindow instance is to use setCentralWidget. Here is a working example for clarification:
import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):

    def __init__(self, parent):
        super(Form, self).__init__(parent)
        self.lbl = QtGui.QLabel("Test", self)

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow, self).__init__()
        self.setGeometry(50, 50, 1600, 900)
        new_window = Form(self)
        self.setCentralWidget(new_window)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


text:
Q: Android Dialog - confused I've been trying to get a handle on Dialogs.  I read the android dev site info and a dozen bolg's.  It seems there are several ways of doing it and I'm able to at least get a dialog with 3 buttons (not using a custom dialog with custom layout).
If I set up the positive/negative/neutral actions with something like finish(), cancel() etc, it works with those calls.
But, what I want to do is have the buttons do something more, if only display a text using a string defined in the Maincode (not a Toast).  Eventually, I want to enter some numbers in a dialog and return them in a string. Yes, I can do that from another activity screen but, prefer not to as I like the compact size of a dialog.
Even cheating and returning an integer to the Maincode to do some switch/case stuff would be okay but, I seem not able to even return an integer.
I understand that I'll need to do a customized alert dialog to do input stuff and the following is my attempt at a start by just trying to return a string or integer - it doesn't seem to be getting me there!
This code presents the dialog with 3 buttons.  This is just one of the try's I made (integer return stuff deleted)...
What can I do to return an integer to the Maincode from a dialog button?  There are no code errors or warnings, it just doesn't work as I hoped...
    public class Maincode extends Activity {
public static String rtndMessage = "Push Button";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final TextView text = (TextView) findViewById(
            R.id.TextView01);
    final Button doIt = (Button) findViewById(R.id.Button01);

    //  -----------------------------------------------------
    doIt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // do something
            Dialog1();          // call Dialog1
        }
    }); // end -----------------------------------------------
// do the rest of the code (ie, display the result of doIt)
text.setText(rtndMessage);  // set text w/result
}//end onCreate ----------------------------------------------

public void Dialog1() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Dialog Test");
builder.setIcon(R.drawable.redtest);
// chain the following together
  builder.setMessage("Send text: Yes, No, Cancel")
    // the positive action ----------------------------------
    .setPositiveButton("Yes Action", new
        DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            Maincode.rtndMessage = "sent Yes back";
        }
    })
    // The negative action ----------------------------------
    .setNegativeButton("No Action", new
            DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            Maincode.rtndMessage = "sent No back";
        }
    })
    // The negative action ------------------------------
    .setNeutralButton("Cancel", new
            DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            Maincode.rtndMessage = "sent N/A back";
            dialog.cancel();    // just return to activity
        }
});

builder.show();      // show the dialog
    }//end Dialog
    }//end activity

A: You can implement the dialog as separate Activity and get any behavior you need. Just apply standard android Theme.Dialog theme to the activity to make it look like dialog. Also you can create theme of your own pointing Theme.Dialog as parent.

A: Android 1.6+ provides an easy to use set of dialog functions for your Activity.
When you make the dialogs, just do whatever you have to do in the onClick() methods of the dialog's buttons.  You can see an example I have of this below, in the DIALOG_CONFIRM_DELETE switch where I delete a record for a local database and requery a cursor.
I'd take a look at the "Creating Dialogs" section in the dev guide on http://d.android.com  It shows you how to use the dialog functions.
http://developer.android.com/guide/topics/ui/dialogs.html
@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    switch (id) {
        case DIALOG_CONFIRM_DELETE:
            builder
                .setTitle("Confirm")
                .setMessage("Are you sure you want to delete that access point?")
                .setCancelable(true)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mDbAdapter.delete(SELECTED_AP_ID);
                        mCursor.requery();
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
            return builder.create();
        case DIALOG_EXPORTING:
            ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Exporting...");
            progressDialog.setCancelable(false);
            progressDialog.show();
            return progressDialog;
        case DIALOG_GPS_DISABLED:
            builder
                .setTitle("GPS signal not Found")
                .setMessage("GPS is not enabled, and accuracy may be effected.")
                .setCancelable(false)
                .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startService();
                        dialog.dismiss();
                    }
                });
            return builder.create();
        default:
            return null;
    }
}

A: This is VERY late, but hopefully it will help others in future.
What I did was created a custom dialog that implemented OnClickListener:
public class LoginDialog extends Dialog implements OnClickListener{

    public LoginDialog(Context context) {
    super(context);
    this.context = context;
    // TODO Auto-generated constructor stub

    }

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog);
    setTitle("Enter Login Details");
    setCancelable(true);

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    bLogin = (Button) findViewById(R.id.bDialogLogin);
    bCancel = (Button) findViewById(R.id.bDialogCancel);

    bLogin.setOnClickListener(this);
    bCancel.setOnClickListener(this);

   }

    public void onClick(View v) {

    switch (v.getId()) {
    case R.id.bDialogLogin:
        //Check credentials.  If they pass:
        cancel();

        //if they don't pass, throw an alert or something
      break;

    case R.id.bDialogCancel:
        dismiss();
      break;
    }

    }
}

Then in my main code I implemented an onCancelListener (dialogs have onCancel and onDismiss listeners all prepared for you).
//This calls my alert dialog.  Place this in the onClick of a button or something
loginDialog = new LoginDialog(this);
loginDialog.show();

loginDialog.setOnCancelListener(new OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            // TODO Auto-generated method stub

            //This code is run whenever the cancel(); function in the dialog is called.

        }
    });

Hope this helps!


text:
Q: Reading a named pipe continuosly What is the best way to read a named pipe continuously in Python?
This is my current code:
def read_commands():
    try:
        print "Creating read pipe..."
        os.mkfifo(pipe_cmd)    # Create pipe
        print "Pipe created!"
    except:
        print "Pipe already exists"

    with open(pipe_cmd, "r") as pipecmd:
        while True:
            try:
                line = pipecmd.readline()
            except:
                print "Could not read cmd pipe"

            if line != "":
                print line

        #time.sleep(1)

However, when I run this code it seems to be taking a lot of resources from my CPU (One of them will go to 100%). It works fine with the sleep of 1 second. However, I need to read the pipe continuously to make sure if there is new data. Is there a better way to accomplish this?
This is what I am sending to the pipe in C++:
void write_pipe(){
    ofstream pipe("/tmp/okccmd");  // Open the pipe
    string data = "Hi";
    pipe << data << endl;
    pipe.flush();
}

Thanks!

A: select.poll works fine (at least for Linux, not sure if Windows supports this; select.select ist afaik available, however). Just have a look at the documentation, the module is in the standard library and well documented (there is no need to know how the OS select() function actually works).
Documentation:
https://docs.python.org/3/library/select.html
Note: poll() returns a list of file descriptors, not file-objects. So, you should have a dict which maps file descriptors to the corresponding object (I would have this also if I just poll one file.
pollobj = select.poll()
polled_files = dict()

# the following two lines are reuired for every file
pollobj.register(my_file_obj, <EVENTMASK>)
polled_files[my_file_obj.fileno()] = my_file_obj

for fd, evt in pollobj.poll():
    fileobj = polled_files[fd]
    ... process event for fileobj

A: Instead of read or readline functions, you can use for..in. This will behave in a blocking manner. If the client side writing to the fifo closes, the for loop ends. The while loop will reopen the fifo and wait.
import os

FIFO = 'myfifo'
os.mkfifo(FIFO)
while True:
    with open(FIFO) as fifo:
        for line in fifo:
            print(line)


text:
Q: Objective c checking whether text field is empty Here's the code:
- (IBAction) charlieInputText:(id)sender {
    //getting value from text field when entered
    charlieInputSelf = [sender stringValue];

    if (charlieInputSelf != @"") {
        //(send field if not empty
    }
}

This sends it even when the field is empty; therefore, this does not work as I want it to.

A: Simply checks for nil and if length of text length is greater than 0 - not empty
if (textField.text && textField.text.length > 0)
{
   /* not empty - do something */
}
else
{
   /* what ever */
}

A: Joshua has the right answer in the narrow case, but generally, you can't compare string objects using the == or != operators.  You must use -isEqual: or -isEqualToString:  This is because charlieImputSelf and @"" are actually pointers to objects.  Although the two sequences of characters may be the same, they need not point at the same location in memory.

A: We already have inbuilt method that return boolean value that indicates whether the text-entry objects has any text or not.
// In Obj-C
if ([textField hasText]) {
        //*    Do Something you have text
    }else{
         /* what ever */
    }

// In Swift

if textField.hasText {
    //*    Do Something you have text
}else{
     /* what ever */
}

A: Those 'work' in a way. However, I found that the user can just fill in the box with spaces. I found using regular expressions helps (though what I use is for words without spaces) I can't really figure out how to make allow spaces.
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[ ]" options:NSRegularExpressionCaseInsensitive error:&error];

if (!([[inputField stringValue]isEqualTo:regex])) {
        NSLog(@"Found a match");
// Do stuff in here //
}

A: The Most efficent way to do this is by using this
// set it into an NSString
NSString *yourText = yourVariable.text;

if([theText length] == 0])
{
 // Your Code if it is equal to zero
}
else
{
// of the field is not empty

}

A: Check whether text field is empty in Swift
  @IBOutlet weak var textField: NSTextField!
  @IBOutlet weak var multiLineTextField: NSTextField!

  @IBAction func textChanged(sender: AnyObject) {
    //println("text changed! \(textField.stringValue)")

    if textField.stringValue.isEmpty == false {
      multiLineTextField.becomeFirstResponder()
      multiLineTextField.editable = true
    } else {
      multiLineTextField.editable = false
    }
  }

A: The easiest way to do it.
Create new NSString without " " (spaces)
NSString *textWithoutSpaces = [self.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Now you have string without spaces.
You just have to check is this string empty or not.
if (textWithoutSpaces != 0) {
 /* not empty - do something */
} else {
  /* empty - do something */
}

A: -(void)insert{

    if ([_nameofView  isEqual: @""]) {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Fill the Name Field First."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else if ([_detailofview  isEqual: @""]){

        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Fill the Details Field First."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Data Inserted Successfully."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
}


text:
Q: How to convert a Flux> to a merged Flux? While working with Project Reactor, there came a use case where I'd want to convert a Flux <List<String>> to a <Flux<String>> where all those lists are flattened to form a Flux. Is there any out of the box method for the same?

A: Use .flatMap(Flux::fromIterable)
List<String> list = new ArrayList<>();
var flux = Flux.just(list)
            .flatMap(Flux::fromIterable);


text:
Q: IF/ELSE executes both blocks The following executes both the IF and the ELSE blocks
set sqlpackage_path=%ProgramFiles(x86)%\Microsoft SQL Server\130\DAC\bin\sqlpackage.exe

if exist %sqlpackage_path% (
    echo %sqlpackage_path% exists
) else (
    echo %sqlpackage_path% does not exist
)

This is the result:

C:\temp>set sqlpackage_path=C:\Program Files (x86)\Microsoft SQL
  Server\130\DAC\bin\sqlpackage.exe
C:\temp>if exist C:\Program Files (x86)\Microsoft SQL
  Server\130\DAC\bin\sqlpackage.exe (
C:\temp>echo C:\Program Files (x86)\Microsoft SQL
  Server\130\DAC\bin\sqlpackage.exe exists C:\Program Files
  (x86)\Microsoft SQL Server\130\DAC\bin\sqlpackage.exe exists
C:\temp>echo C:\Program Files (x86)\Microsoft SQL
  Server\130\DAC\bin\sqlpackage.exe does not exist C:\Program Files
  (x86)\Microsoft SQL Server\130\DAC\bin\sqlpackage.exe does not exist

When I try putting quotes around "%sqlpackage_path%" on the IF line, I get this message:

\Microsoft was unexpected at this time

What is the right syntax for checking the existence of this file?

A: Your environment variable evaluates to a string that contains parentheses. These are taken literally as part of the syntax. You need to enclose them in quotes, especially inside the if and else blocks:
set sqlpackage_path=%ProgramFiles(x86)%\Microsoft SQL Server\130\DAC\bin\sqlpackage.exe

if exist "%sqlpackage_path%" (
    echo "%sqlpackage_path%" exists
) else (
    echo "%sqlpackage_path%" does not exist
)

If you need to avoid using quotes in the output from the echo command, use delayed expansion: add setlocal enabledelayedexpansion at the start of your file, and use !sqlpackage_path! instead of "%sqlpackage_path%".

A:
@ECHO Off
SETLOCAL
set "sqlpackage_path=%ProgramFiles(x86)%\Microsoft SQL Server\130\DAC\bin\sqlpackage.exe"

FOR /f "tokens=1*delims==" %%a IN ('set sqlpackage_path') DO IF /i "%%a"=="sqlpackage_path" (
 if exist "%%b" (
 echo %%b exists
 ) else (
 echo %%b does not exist
 )
)
GOTO :EOF

Keeping the evaluation of the actual pathname until the very last possible moment.
The fundamental problem is that the ) in the variable closes the if-true instruction.


text:
Q: How to connect dots in ordinary plot based on subject number I am very afraid that I have been trying to invent the hot water, but I would like to connect the dots in the graphs below based on the subject number. In this case the subjects are rats, they are devided in three treatment groups and their weight is measured three times.
Is there a way I can easily connect the dots based on the rat its number?
The data looks like this (first 20 lines):
   Rat Group Measurement Weight
1    1     1          M0     57
2    2     1          M0     60
3    3     1          M0     52
4    4     1          M0     49
5    5     1          M0     56
6    6     1          M0     46
7    7     1          M0     51
8    8     1          M0     63
9    9     1          M0     49
10  10     1          M0     57
11  11     2          M0     61
12  12     2          M0     59
13  13     2          M0     53
14  14     2          M0     59
15  15     2          M0     51
16  16     2          M0     51
17  17     2          M0     56
18  18     2          M0     58
19  19     2          M0     46
20  20     2          M0     53

And the graph I am talking about is this one:

Which I am making with this code:
par(mfrow=c(1,3))
plot(data=data_long[data_long$Group==1,], Weight ~ as.numeric(Measurement),
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 1")
par(new=TRUE)
grid()
plot(data=data_long[data_long$Group==2,], Weight ~ as.numeric(Measurement),
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 2")
grid()
plot(data=data_long[data_long$Group==3,], Weight ~ as.numeric(Measurement),
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 3")
grid()

How do I ask R to connect the dots based on the rat number?
Thank you!
Edit: requested dput:
structure(list(Rat = 1:20, Group = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
), .Label = c("1", "2", "3"), class = "factor"), Measurement = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("M0", "M1", "M2", "M3", "M4"), class = "factor"),
    Weight = c(57L, 60L, 52L, 49L, 56L, 46L, 51L, 63L, 49L, 57L,
    61L, 59L, 53L, 59L, 51L, 51L, 56L, 58L, 46L, 53L)), .Names = c("Rat",
"Group", "Measurement", "Weight"), row.names = c(NA, 20L), class = "data.frame")

A: I recommend using ggplot2, since it can get tedious in base graphics
# sample dataset
set.seed(12345)
data <- data.frame(
  rat = factor(rep(1:5, times=6)),
  group = factor(rep(1:2, each=15)),
  measurement = factor(rep(1:3, each=5, times=2)),
  weight = runif(30, min=20, max=60))

# require(ggplot2)
ggplot(data=data, aes(x=measurement, y=weight, col=group, group=group:rat)) +
geom_point() + geom_line() + facet_wrap(~group, ncol=2)

A: As suggested by everybody, you should use ggplot, or in case you use the base graphics, use some for loops. As I don't know ggplot yet, I used the for loops with this as a result.
It is still way easier than the struggle our professor had to go trough with SAS, so I don't mind the for loops...
Below is the code. Thanks everybody for your help.

par(mfrow=c(2,3))
lapply(1:3, function(g) {
    plot(data=data_long[data_long$Group==g,], Weight ~ as.numeric(Measurement),
         ylim=c(0,200), pch=20, xlab="Measurement",
         main=paste("Treatment group",g))
    for(j in 1:max(data_long$Rat)){
      if(data_long[j,]$Group==g){
          lines(data_long[data_long$Rat==j,]$Measurement,
                data_long[data_long$Rat==j,]$Weight)
      }
    }
    grid()
})
plot(data=data_long[data_long$Group==1,], Weight ~ Measurement,
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 1")
grid()
plot(data=data_long[data_long$Group==2,], Weight ~ Measurement,
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 2")
grid()
plot(data=data_long[data_long$Group==3,], Weight ~ Measurement,
     ylim=c(0,200), pch=20, xlab="Measurement", main="Treatment group 3")
grid()


text:
Q: Problems creating an index The question is:
Write the SQL statement to create an index on the city table for the attribute CountryCode. Name the index CountryCode_idx.
So my statement is:
CREATE INDEX city_name_countrycode_idx ON city (name, countrycode);

but the problem is, when I try to drop the index in the next question using statement
DROP INDEX city_name_countrycode_idx;

I get a syntax error expecting ON
and then I try making a statement called:
DROP INDEX city_name_countrycode_idx ON city;

but my statement affected 0 rows apparently. Can someone tell me if my create index statement is correct and why my drop index statement isn't working?

A:
DROP INDEX city_name_countrycode_idx;
   I get a syntax error expecting ON ...

As per documentation on DROP INDEX Syntax:
Name: 'DROP INDEX'
Description:
Syntax:
DROP INDEX index_name ON tbl_name
    [algorithm_option | lock_option] ...

algorithm_option:
    ALGORITHM [=] {DEFAULT|INPLACE|COPY}

lock_option:
    LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}

DROP INDEX drops the index named index_name from the table tbl_name.
Conclusion:
Hence to drop an index, you must use table name on which the index was created.
And for your index city_name_countrycode_idx to be dropped you have to use the table name city on which the said index is created.
DROP INDEX city_name_countrycode_idx ON city;

A: 0 rows affected means no change in data . Although the index is dropped.
you can cross check by desc the table before and after dropping the index
Thanks


text:
Q: Is possible to save JavaScript variable as file? Is there a way to convert a string from a JavaScrip variable, into a downloadable file that users can download when clicking a button ?
Thanks for any advice.

Lorem Ipsum

<button id="test">Download text as file !</button>

A: Yes it is, you could do something like this in HTML5, using the download attribute
function download_txt() {
  var textToSave = document.getElementById('txt').innerHTML;
  var hiddenElement = document.createElement('a');

  hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'myFile.txt';
  hiddenElement.click();
}

document.getElementById('test').addEventListener('click', download_txt);

FIDDLE

A: You can use a data: URI like in adeneo's answer, but another way is to use an HTML5 Blob and createObjectURL (similarly using the download attribute to create a download link).
The benefit of using createObjectURL is that there are severe size limits to data URIs in most browsers.
Example code taken from linked article:
var typedArray = GetTheTypedArraySomehow();
var blob = new Blob([typedArray], {type: 'application/octet-binary'});
    // pass a useful mime type here
var url = URL.createObjectURL(blob);
// url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
// now you can use the url in any context that regular URLs can be used
// in, for example img.src, etc.

A: To store a javascript variable, I suggest you to use libraries of data storage just like this one. where you can set a variable, get it , remove it ...
$.setData("key","value");
$.getData("key");
$.removeData("key");

but to store it on a file and make downloadable you have to pass by the server unless you use a javascript trick to download a file which doesn't exist, you just declare these functions
 var Download =
    {
        click : function(node) {
            var ev = document.createEvent("MouseEvents");
            ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            return node.dispatchEvent(ev);
        },
        encode : function(data) {
                return 'data:application/octet-stream;base64,' + btoa( data );
        },
        link : function(data, name){
            var a = document.createElement('a');
            a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1);
            a.href = data || self.location.href;
            return a;
        }
    };
    Download.save = function(data, name)
    {
        this.click(
            this.link(
                this.encode( data ),
                name
            )
        );
    };

and when you want to download a file, you do this
Download.save("data to be on a file","FileName.txt");

Finally, you need to combine the datastorage and the filedownload solution to get the result you're asking for


text:
Q: Different space between letters in different editors I noticed that on some editors, spaces between characters are not the same.
Here is an example white libreoffice

You can notice that, between each block of 4 or 5 i, the space is bigger.
I tested the same example on google doc and spaces seems to be the same :

I told me It was a libreoffice bug, but I tried on another online editor (onlyoffice) and I can reproduce this behavior

So the question is : It's a bug or a feature ? And, how can I disable that ?

A: Different subpixel antialiasing routines causes fonts to appear to shift. Theres little you can do about this. Different rendering engines just work out differently.
Your comment about the problem dissapearing in PDF seems to confirm this line of thinking. You might get different results by hinting the fonts differently. Plese note even the browser shows the problem in form of a constantly shifting intensity wave. Libre office just wants to hint the stem to a full pixel width. Forcing it to eventually skip a pixel.


text:
Q: Curl command does not work in powershell due to special character I am trying to run curl command in powershell console
curl.exe -v -U x7878:asdff$ -H "Content-Type: application/json" -X POST --data @login.txt https://mywebsite/ma/api/v2/user/login

anyidea where do i miss?
the error i got is:

The splatting operator '@' cannot be used to reference variables in an
  expression. '@login' can be used only as an argument to a command

I have been also trying to put into variables like
PS>$a="My above command"
PS>$b=invoke-expression $a

It does not work either, it is making worse due to "(double quotes) sign.

A: As for what you are doing in your post with curl.exe in the shell. See this answers. Thus your post falls into the possible duplicate answer based on the below and more like them on this site.

Running curl via powershell - how to construct arguments?
Powershell curl double quotes

Since this appears just to be a text file, then you just need the text file name without any special characters involved.
There are many reserved characters, and you just cannot randomly use them. The '@' is one of those.
@( )
Declare arrays.
@{ }
splatting use case, Declare hash tables..
@' ... '@
Use Multi-line string literal without embedded variables.

$ (dollar sign) Declare/use a variable and there are a boatload of
  built-in variables. Just use the consolehost/ISE/VSCode and type $
  and press the tab key to scroll through them or see:
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_automatic_variables

If you need to use special characters, you have to escape them
As far as Invoke-Command is concerned, be sure to look at the help file for the proper understanding and use via the examples provided in the help files.
Get-Help -Name Invoke-Command

NAME
    Invoke-Command

SYNOPSIS
    Runs commands on local and remote computers.

vs
Get-Help -Name Invoke-Expression

NAME
    Invoke-Expression

SYNOPSIS
    Runs commands or expressions on the local computer.


text:
Q: How to parseInt a jQuery value? I'm trying to add +1 to a value but I can't figure out how is the value define. Is it a jQuery object ?
   var value = $(this).attr('data-id'); /* return a number between 0 to xx */
   var val = (value+1);

I tried too : var val = (paseInt(value)+1); with no more effectiveness ..
It tells me that val = 0 when it should be equal to 1 and val = 1 when it should be equal to 2 etc..
A quick help would be greatly appreciate here :)

A: Try parsing to int as soon as you fetch data as below:
DEMO HERE
LOCAL DEMO

$('.specldiv').on('click',function(){
   var value = parseInt($(this).attr('data-id'));
   var vals = (value+1);
    alert(vals);
});

Div with id data-id 1

Div with id data-id 0

Div with id data-id 2

A: Try this:
var value = 0;
value = $(this).attr('data-id');

A: For data attribute you can just try $(this).data("id") than you can perform following
var value = $(this).data("id");
var val = value + 1;

A: Use this javascript hack:)
var value = +($(this).attr('data-id')); /* return a number between 0 to xx */
var val = value+1;

When you use "+" without blanks, before string that contains number, your string transforms to number.


text:
Q: Change button theme when pressed I'm trying to change the data-theme of a button when pressed.
I'm calling this JavaScript function in the button's onClick handler:
function changeNextButtonColor() {
    var nextButton = document.getElementById('next');
    nextButton.setAttribute('data-theme', 'a');
}

but the theme is not changing. Any ideas?

A: Once you've set set the theme on the button you'll need to call "refresh" on it like this below...
$("#next").attr("data-theme","a").button('refresh');

If you want to bind this kind of behavior to all "next" buttons in a process and their might be more than one then you might want to consider doing something more like this.   It will checked every page for a button that has a class of colorChangeButton and then, when clicked, change the theme to the alternate theme specified on that buttons attribute of data-theme-pressed.
Next

A: function changeNextButtonColor() {
    $('#next').attr({'data-theme': 'a'});
}

If you're using jQuery, this is your code.


text:
Q: Automating Instruments for Mac OS X? We're interested to see if we can include Instruments-based leak testing as a part of our regular application smoke testing. What kind of scriptability is available for Instruments?

A: Instruments is based on the dtrace framework. You might be able to use that directly, without the instruments GUI.


text:
Q: Why Glib::VariantBase::store method ruins the start of given buffer The fun of working with Glib::VariantBase might be priceless. But brings up many obstacles with itself as well. I am having hard time to understand why the very basic Glib::VariantBase::store method is changing the start of my buffer.
Please assume i have a buffer allocated enough, better to write it down :
my_beautiful_buffer = static_cast<char*>(std::malloc(1024));

Then i would like to add a uint64_t variable to its beginning :
uint64_t my_humble_var = 1;
*reinterpret_cast<uint64_t*>(my_beautiful_buffer) = my_humble_var;

Lets read the buffer with printf
for (int i = 0; i < 8; i++) printf("0x%x ", *(unsigned char*)(my_beautiful_buffer+i));

+++++++++my_beautiful_buffer+++
0x1 0x0 0x0 0x0 0x0 0x0 0x0 0x0

Lets create a rather complex GlibVariable
using myStrangeVarType = Glib::Variant<std::map<Glib::ustring,std::map<Glib::ustring, std::tuple<Glib::VariantBase, std::uint64_t>>>>
myStrangeVarType data = createData(); // createData method statically defines variable and and copies

Now lets store this newly created variable
data.store((my_beautiful_buffer + sizeof(std::uint64_t)));

Can we read all the data in our beautiful buffer
for (int i = 0; i < data.get_size() + sizeof(std::uint64_t); i++) printf("0x%x ", *(unsigned char*)(m_buffer+i));

    +++++++++Data Written+++++++
    0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x61 0x70 0x70 0x49 0x64 0x31 0x2f 0x64 0x61 0x74 0x61 0x62
0x61 0x73 0x65 0x31 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x6b 0x65 0x79 0x31 0x0 0x0 0x0 0x0 0x73
0x74 0x72 0x69 0x6e 0x67 0x20 0x76 0x61 0x6c 0x75 0x65 0x0 0x0 0x73 0x0 0x62 0x67 0xbc 0x0 0x0
0x0 0x0 0x0 0xf 0x5 0x0 0x0 0x0 0x0 0x0 0x0 0x6b 0x65 0x79 0x32 0x0 0x0 0x0 0x0 0xd2 0x4 0x0
0x6e 0x0 0x0 0x0 0x0 0x62 0x67 0xbc 0x0 0x0 0x0 0x0 0x0 0x4 0x5 0x22 0x42 0x11 0x0

Okay At this point what happened to my first 8 bytes, why the very first byte 0x1 is vanished ?

A: The problem has solved with some changes in the createData method.
The method was producing a Glib::VariantBase with a{sa{s(vt)}} type, apparently packing and unpacking custom types is not really strong point of Glib::Variant.
I had to convert my object into just v type. And the problem has fixed.
This is how i have changed the type:
GVariant* gVariant = g_variant_new("v", value.gobj());
Glib::VariantBase variantValue = Glib::VariantBase(gVariant);
return variantValue;

And earlier i was just returning the value without doing any of these conversions.

Another way to fix the problem was just calling value.get_size(); and return it afterwards.
value.get_size();
return value;

Apparently that call internally causes the variant to be serialized.


text:
Q: CSS shouldn't change while the screen goes down with scrollTop Something goes wrong with my CSS when I activate the ScrollTop effect on my two buttons : the  css effects apply, despite :
.hcb_link a {
    color: inherit;
}

.hcb_link a:hover, a:active {
    color: inherit;
    text-decoration: none;
}

The link becomes black and underlined when the page moves... I would like it to stay white and not underlined.
Is there something that I need to do on my JS ?
Thanks in advance.

$('a[href^="#"]').click(function(){
    var the_id = $(this).attr("href"),
        yPos = $(the_id).offset().top,
        speed = 1500;

    $('html, body').animate({
        scrollTop: yPos -71     // -71px pour prendre en compte la taille du bandeau supérieur.
    }, speed);
    return false;
});
a:hover,
a:focus {
    color: #000000;
    text-decoration: underline;
}

.carrousel {
    width: 100%;
    max-width: 1000px;
    margin: auto;

}

.hcb_link {
    background: #D5420F;
    width: 300px;
    font-size: 18px;
    padding: 10px 0px;
    margin: 10px auto 30px;
    border-radius: 2px;
    cursor: pointer;
    color: white;
}

.hcb_link:hover {
    background-color: rgba(215, 66, 34, .9);
}

.hcb_link a {
    color: inherit;
}

.hcb_link a:hover, a:active, a:focus{
    color: inherit;
    text-decoration: none;
}

                    Vous êtes un professionnel

                    Vous êtes un étudiant

Entrepreneurs, démultipliez votre force commerciale grâce à des étudiants rémunérés au succès

Étudiants des Grandes Écoles, mettez vos compétences et votre énergie à profit

Étudiants des Grandes Écoles, mettez vos compétences et votre énergie à profit

Thanks to @René and @Cthulhu, I've made some changes.
But it seams like despite everything, it is the Bootstrap that is triggered :
a:hover,
a:focus {
    color: #000000;
    text-decoration: underline;
}


text:
Q: Should "Have your peer partner send you her plans" be considered a directive? If you tell a person to have someone do something, is that considered a command?
Our boss sent an email which told us to "have your peer partner send you her plans". Should that be considered a directive?
Our union is actually filing a grievance over this language.
Our contract states that we cannot be forced to give our lesson plans to anyone. Our principal, as part of a professional development activity wrote "have your peer partner send you her plans," as opposed to "send your peer partner your plans". Since I have no means of "having" (forcing) her do this (I am not her boss), the implication to me is is that we should "request" this of our peer partners.
I think she deliberately chose "have" over "request" (in fact the union asked her to amend the email to state this was voluntary, and she refused) to confuse people into thinking she was telling them to send their plans to their partner since indeed, "have" connotes a command, but was covering herself by being able to say that she never told anybody to send their plans to the peer partner- she told us to have them send theirs to us.  Since we can't "make" our peer partners do this, in this case "have" means "ask".
It seems to me that this was a way of tricking people into thinking it was a directive, but the language was chosen carefully — so if necessary, it would prove it wasn't. I think the union will lose the grievance on these grounds, unless there are provisions in the contract against deliberately using language to mislead overworked teachers who don't have time to read emails through the lens of a lawyer.

A: Have is mostly used in English as an auxiliary verb for the perfect construction, and it's normally contracted and frequently elided completely in speech. There is also  a common (though often only metaphoric) lexical sense of 'possess' for the verb have, but its auxiliary and idiomatic uses are far more frequent.
The uncontracted verb have participates in a great many idiomatic (and often unsettled) syntactic constructions that involve other verbs, occasionally with unusual pronunciations.
For example,

*

*I had my tires slashed last night. = My tires were slashed last night (by SomeOne).
The have + PastParticiple Adversative construction: Subject = nonvolitional Patient

*I had my tires rotated yesterday. = I caused SomeOne to rotate my tires yesterday.
The have + PastParticiple Causative construction: Subject = volitional Agent

*You have to do it this way. = You must do it this way.
The periphrastic Modal have to (always pronounced with /f/)

The one you ask about is

*

*I had SomeOne rotate my tires yesterday. = I caused SomeOne to rotate my tires yesterday.
The have + Infinitive Causative: the Active form of the have + PastParticiple Causative.

The Active Infinitive Causative is used when the identity of the infinitive subject (SomeOne) is important information, and the PastParticiple Causative construction is used when it's not.
These Causative constructions mean essentially the same as get + Infinitive, but are more polite -- i.e, farther from a bald on-record imperative. In just the same way, get + Infinitive is more polite than make + Infinitive, which is more polite than force + Infinitive. All of them refer to causing somebody else to do something, by whatever means.
And, in this case, to answer the presenting question, what the boss said

*

*Have our peer partner send us his plans
is a bald on-record imperative.
So, Yes.
You had better contact your peer partner and cause him to send you his plans, because that's what your boss told you to do.

A: When you want to tell someone to do something for you, you can have them do that thing for you. For example, if I can't type my own emails (because I have injured my hand, for example), I can ask my colleague to do it for me. In other words I can have my colleague type my emails. In addition, suppose my boss knows I can't type, so he/she can say something like:
"Have your colleague type your emails since you can't do it yourself."
My boss is giving me an order with the above sentence. I must somehow arrange for my emails to be typed by my colleague.
There is an alternative to this construct with the verb get, i.e. "Get your colleague to type your emails since you can't do it yourself."
In the second example it is implied that I should talk to my colleague and perhaps persuade him/her to do it. The result is the same in both sentences: I am given an order to ask someone else to type my emails.


text:
Q: Does dark energy have gravity? So I keep running into this idea on the Internet that only mass has gravity, but isn't mass simply contained energy?
Energy bounces around, or travels at the speed of light, because it is not in the form of an atom, it is in the form of light, photons, quarks, neutrinos, and things we haven't discovered yet.
Wouldn't it make sense to say that if mass can warp space by its existence, then everything that exists must also have that effect as well, but to a much smaller degree, a square of the speed of light smaller, and we could only detect that gravity it had, if it wasn't flying around at the speed of light?
The reason this is important is that light cannot escape a black hole, and I believe that nothing can escape a black hole over time, whether it be light, dark energy, photons, neutrinos, or anything that exists at all, meaning that the fate of the universe changes.
If dark energy gets sucked into black holes because it has gravity by its existence, then the pushing effect it has turns into a pulling effect over time, and then the only logical conclusion is the universe is eternal, moving in an endless cycle of big bang, big crunch, big bang, which also explains why the Big Bang happened, and continues to happen, forever.
If you say that dark energy remains at constant density despite the expansion of the universe, explain why it does this, and why you think that, and why it doesn't have gravity. When was this proven, and what caused the Big Bang?

A: Forgive me in advance, this may get overcomplicated. I am going to give you the facts as scaled down as I can but still sufficiently detailed. I think providing you with what we have and allowing you to infer from it is the best way to avoid misrepresenting the answer.
Here is the General Relativity equation that describes how gravity interacts with everything else:
$$R_{\mu\nu}-\frac{1}{2}g_{\mu\nu}R=8\pi G_NT_{\mu\nu}$$
On the left side is gravity; it is described by terms that have to do with how space curves, expands, and contracts. On the right side is matter, radiation, etc. Pretty much all forms of energy.
It was determined through observation that the universe as we know it is expanding and that the rate of expansion is accelerating. To account for the acceleration of the expansion, the best-fitting theory includes a constant term:
$$R_{\mu\nu}-\frac{1}{2}g_{\mu\nu}(R-2\Lambda)=8\pi G_NT_{\mu\nu}$$
Alternatively, one could choose to express that constant term on the right side of the equation. It makes no physical difference. Accordingly, you can interpret this term as a modification to how gravity affects spacetime (if added to the LHS) or as an additional energy term with a negative pressure (if added to the RHS).
Now, as per original GR, we have equations describing the expansion of the universe:
$$\frac{\ddot a}{a}=-\frac{4\pi G_N}{3}\sum_i(\rho_i+3p_i)$$
$a$ represents how much the universe has expanded, $\ddot a$ is the acceleration of the expansion, and $\rho_i$ and $p_i$ are the energy density and the pressure for the $i$th form of energy (the rest are constants). We put in matter, dark matter, radiation, and we even treat the background curvature of the universe as a form of energy here. What we find is that when we treat dark energy as an energy and set its pressure to be equal to negative of its energy density, our equations very closely match the observations. That is sufficient reason to like doing that. However, we also find (via a separate equation) that the energy density of something whose pressure equals the negative of the energy density remains constant for all time. This is unavoidable, it is one of the best fitting models so far.
Furthermore, the constant energy density presents other effects. The energy density of matter or radiation decreases with time. For instance, and this should be intuitive, the energy density of matter decreases like $a^{-3}$. That is, it drops like the cube of the expansion of the universe. And why not? as the universe expands, the volume increases like the expansion cubed; energy density is energy over volume, so it decreases like expansion cubed. Radiation goes like $a^{-4}$, and other energies decrease at varying rates. A constant density means that after a long time, it becomes the dominant term in the above equation. Effectively, after a long time:
$$\frac{\ddot a}{a}=\frac{8\pi G_N}{3}\rho_{DE}$$
This barrage of equations might mean nothing at all to you. That is fine. This is an answer to what dark energy is, why it has a constant energy density, and whether it has gravity.
As for whether or not dark energy can fall into a black hole, that is more complicated. From the point of view of modifying gravity, dark energy is not something that can fall into a black hole. However, from the point of view of being an additional energy term, one might think it must be able to fall into a black hole. Truthfully, I don't know that answer but I know it makes an insignificant difference. Dark energy is too weak to have an effect on the scale of black holes. Even the small gravity of the Sun is enough to negate the effect of dark energy throughout the solar system and probably a bit further. As you can see from the last equation, at late times the acceleration of the expansion is positive. Dark energy never brings the universe to a Big Crunch. For matter, radiation, etc, the acceleration terms at late times all are negative. Dark energy is preventing a Big Crunch.
In response to your last questions. This was never "proven". It was postulated decades ago and has been confirmed by many experiments but none that prove it beyond a doubt. As for what caused the Big Bang. The Big Bang was not an event, it was a moment of time. The Big Bang represents the point in time where the equation for $a$ (remember that's the term that represents how much the universe has expanded) goes to zero. That's it. It has no more need for a cause than has any moment of time after it.

A: I am going to answer the following questions:
1) Does dark energy have gravity?
2) Why does dark energy have constant density during the expansion of the universe?
First about the term of dark energy - it is more of a label for many attempts of a solution to the problem of an accelerated expansion of the universe. One of the most promising (or say "mainstream") solutions is that of the cosmological constant or vacuum energy. Both of these concepts play an identical role in the equations of standard cosmology but their origin is either from a modified theory of relativity (the cosmological constant $\Lambda$) or particle physics (the vacuum energy). Now to the questions.
1) If we say accelerated expansion of the universe is due to a fundamental constant of the theory of gravity $\Lambda$, Dark energy indeed does not "have" gravity, because it is not really energy, it is just gravitation behaving slightly differently from what we thought on large scales.
If we say accelerated expansion is due to vacuum energy or some other "non-mainstream" energy, we are sure by observation that we do not feel it's "local" gravitational effect, that is lumps of dark energy pulling on objects in space. This means this energy must very homogeneous, ideally constant throughout the whole space. Why? Because if the distribution is completely homogeneous, there isn't any larger lump of dark energy we would be attracted to rather than anywhere else - the gravity just cancels out locally because it is equal in all directions but has an effect on cosmic scales.
2) If we consider vacuum energy, it is an energy inherent per unit volume of space even if it is completely empty (vacuous). So as the volume of a patch of the universe grows (as there is "more space"), there is always a constant energy per volume. (Notice that the overall energy of the universe grows, this is a well known result of standard cosmology.) This can be traced back to a basically postulated property of vacuum in quantum field theory and quantum field theory on curved background.
In the case of the cosmological constant, we don't need any argumentation of this sort, the constant is a property of gravitation.


text:
Q: Storing objects for a struct Just curious, how do I store this struct into a property
void CGContextAddCurveToPoint (
   CGContextRef c,
   CGFloat cp1x,
   CGFloat cp1y,
   CGFloat cp2x,
   CGFloat cp2y,
   CGFloat x,
   CGFloat y
);

like
@property (strong, nonatomic) void ??

A: What you are presenting in your question is not a struct it is a method.
It is possible to do the following though. Declare a struct first:
typedef struct
{
   CGContextRef c;
   CGFloat cp1x;
   CGFloat cp1y;
   CGFloat cp2x;
   CGFloat cp2y;
   CGFloat x;
   CGFloat y;
} yourStruct;

and secondly declare a property that will have a type specification of yourStruct
e.g: @property yourStruct yourPropertyName;


text:
Q: "'NoneType' object is not subscriptable" OR "KeyError:" with openpyxl and ipwhois I'm working on a python3 script that does the following:

*

*Open an excel file in the working directory

*Select the first sheet in the excel file

*Select all data in the third column (in this case a range of IP addresses)

*Iterate through all of the IP addresses and call the whois API for each

*Store results for each IP in variable (.json)

*Parse through the result looking for Name, IP Range, Contact Info

*Write the values from 6 above to new rows in the excel file

*Save the excel file with a new name in the current directory

The current document has a list of 427 unique IP addresses and the results from the whois api for the RIPE name are unique (sometimes within the same response).  To accommodate this, I have iterated through each RIPE name to get secondary data sets within the ['contact'] list. This works fine as long as the contact list contains the values I want.  If it does not, I get an error of NoneType.  I tried to build preventative logic around this with an if statement where result == None to assign my variables with a 'NULL' value, but then I get a KeyError exception on the RIPE name.  I'm stuck and need your help.  Here is a copy of my code:
import openpyxl

from pprint import pprint
from ipwhois import IPWhois

wb = openpyxl.load_workbook('Abuse Log with Notes FWC 2016-06-09.xlsx')#change name here to file to be used
sheet = wb.get_sheet_by_name('Sheet1') #get first sheet in workbook

#Add new column headings for API results
sheet['E1'] = 'HOST NAME'
sheet['F1'] = 'HOST COUNTRY'
sheet['G1'] = 'IP START'
sheet['H1'] = 'IP END'
sheet['I1'] = 'HOST EMAIL'
sheet['J1'] = 'HOST PHONE'
sheet['K1'] = 'HOST ADDRESS'

#Store all start range IP's for Amazon in one list variable
AmazonStartIPs = [
  '54.64.0.0', '54.160.0.0','54.144.0.0',
  '52.64.0.0','54.208.0.0','54.192.0.0',
  '54.240.0.0','54.224.0.0','54.72.0.0',
  '54.176.0.0','52.32.0.0','52.0.0.0',
  '52.192.0.0','52.84.0.0','53.32.0.0']

def checkForAmazon():
   if StartAddress in AmazonStartIPs:
      Name = 'Amazon Web Services - Elastic Compute Cloud'
      CountryCode = 'US'
      AbuseEmail = 'abuse@amazonaws.com'
      AbusePhone = '+1-206-266-4064'
      AbuseAddress = ['410 Terry Avenue','North Seattle', 'WA', '98109-5210','UNITED STATES']

iterateColumn = sheet.columns[2]#get all cell values in column C
currentRowIndex = 2

for Address in iterateColumn[1:5]:#test range 1:5 to reduce API load
   ip_address = Address.value#set var to value of item in iterateColumn
      IP = IPWhois(ip_address)#store whois call in var of IP
      results = IP.lookup_rdap(depth=1)#call whois and store .json results

      Name = results['network']['name']#set name to IP Host name
      Name=''.join(Name)#formatting for excel

      CountryCode = results['asn_country_code']#var for country code
      CountryCode=''.join(CountryCode)

      StartAddress = results['network']['start_address']#var for IP range Start
      StartAddress=''.join(StartAddress)

      EndAddress = results['network']['end_address']#var for IP range End
      EndAddress = ''.join(EndAddress)

      #write values above to iterable rows in spreadsheet
      sheet.cell(row = currentRowIndex, column = 5).value = Name
      sheet.cell(row = currentRowIndex, column = 6).value = CountryCode
      sheet.cell(row = currentRowIndex, column = 7).value = StartAddress
      sheet.cell(row = currentRowIndex, column = 8).value = EndAddress

      for key in results['objects']:#get unique key values in results object
         r = key#store as var of r to prevent having to call by ripe name

      AbuseEmail = results['objects'][r]['contact']['email'][0]['value']
      if results['objects'][r]['contact']['email'] == None:
         AbuseEmail = 'NULL'
      elif results['objects'] is None:
         AbuseEmail = 'NULL'

      sheet.cell(row = currentRowIndex, column = 9).value = AbuseEmail
      AbuseEmail = ''.join(AbuseEmail)

      if results['objects'][r]['contact']['phone'] == None:
         AbusePhone = 'NULL'
      else:
         AbusePhone = results['objects'][r]['contact']['phone'][0]['value']

      sheet.cell(row=currentRowIndex, column = 10).value = AbusePhone
      AbusePhone = ''.join(AbusePhone)

      if results['objects'][r]['contact']['address'] == None:
         AbuseAddress = 'NULL'
      else:
         AbuseAddress = results['objects'][r]['contact']['address'][0]['value']

      sheet.cell(row=currentRowIndex, column = 11).value = AbuseAddress
      AbuseAddress =''.join(AbuseAddress)

      checkForAmazon()

      currentRowIndex += 1

rowsUpdated = sheet.max_row
print('{} records have been updated.'.format(rowsUpdated))

wb.save('ABUSE_IP_LOG_HOST_DATA.xlsx')

A: As suggested by MattDMo, I added the following exception handling and that resolved the problem:
try:
   AbuseEmail = results['objects'][r]['contact']['email'][0]['value']
   AbusePhone = results['objects'][r]['contact']['phone'][0]['value']
   AbuseAddress = results['objects'][r]['contact']['address'][0]['value']
except (KeyError, TypeError):
   AbuseEmail = 'NULL'
   AbusePhone = 'NULL'
   AbuseAddress = 'NULL'


text:
Q: How to display database results from multiple tables in descending order I have a keyword search on my site that allows visitors to search for specific things.  My msysql db has 15 tables and for the search feature I use a UNION ALL  to join them all so visitor can search all the tables simultaneously. The problem is all the results are in ascending order. How do I get the results in descending order.
SELECT *
FROM table1
WHERE keyword LIKE %s OR id  LIKE %s

UNION ALL

SELECT *
FROM table2
WHERE keyword LIKE %s OR id  LIKE %s

UNION ALL

SELECT *
FROM table3
WHERE keyword LIKE %s OR id  LIKE %s

A: In such case I'd suggest you to normalize the database and put all the keywords in the same table. If you separate the keywords according to its type use a column type to indicate it.
The following query will do what you are requiring.
SELECT *
FROM   ((SELECT *
         FROM   table1
         WHERE  keyword LIKE '%s'
                 OR id LIKE '%s')
        UNION ALL
        (SELECT *
         FROM   table2
         WHERE  keyword LIKE '%s'
                 OR id LIKE '%s')
        UNION ALL
        (SELECT *
         FROM   table3
         WHERE  keyword LIKE '%s'
                 OR id LIKE '%s')) AS bigtable
ORDER  BY `id`;

A: SELECT *
FROM
  ( SELECT *
    FROM table1
    WHERE keyword LIKE '%s' OR id  LIKE '%s'    ---notice the quotes
  UNION ALL SELECT .......
  ) AS tmp
ORDER BY keyword DESC


text:
Q: connection between jdbc to mysql I have the next code. I save it in the file: 'MysqlConnect.java'.
import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
    System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "jdbctutorial";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "root";
    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,userName,password);
        System.out.println("Connected to the database");
        conn.close();
        System.out.println("Disconnected from database");
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

I know how to run it:
javac MysqlConnect.java
java MysqlConnect

I have some questions:
1) where should I save this file?
(I have a folder of: mysql-connector-java-5.1.22).
2) I created a database and a table in mysql. I don't need to insert that into the code? for example:
String dbname = "database_alon";

3) If the answer of the second question is 'YES', I only have a password to my database, not an username. so what should I insert to the parameter of userName?
so, I think that I have to change the code to:
String dbName = "database_alon";
String driver = "com.mysql.jdbc.Driver";
String userName = "";
String password = "ADMINALON";

right? and what about the question 1?

A: You can have your MysqlConnect.java file wherever you want. You should just add the folder containg the MysqlConnect.class in your classpath. Moreover, in order to run properly you should also add the mysql-connector-java-5.1.22.jar to the classpath in order to be able to find the classes you require for running your class.
In order to avoid mutiple additions in the classpath you could add the mysql-connector-java-5.1.22.jar in the folder containing the
MysqlConnect.class and make only one update of the classpath.
As for your second question YES you need to change the code and add the
String dbname="database_alon"

instead of
String dbName = "jdbctutorial";

I dont think you dont have a username in you database because it picks the root username by default. Try root for username and tell me what it gives you but make sure to update your classpath as stated above. Make also sure you are using the default port 3306 for connecting to the database.

P.S. What program you use for managing you databases? I can provide more help knowing that.
P.S.S You could use an IDE such as Eclipse or Netbeans and that could make the deployment much more easier. You will not need to touch the classpaths and other variables because the IDE will take care by just selecting the jars you want to use for your project.
P.S.S If you dont know how to add a jar in your classpath please provide your operating system in order to provide help for that.


text:
Q: Internet connection in android wear watch? Can you share the ways the android wear watch can connect to internet while it is not pared with mobile device.( Eg: is it possible to connect via wifi, or data connection).

A: It cannot and there are no Android Wear devices supporting Wi-Fi, at this time (On March 2015).
Update: Some devices (not all) should see Wi-Fi support incoming according to http://googleblog.blogspot.fr/2015/04/android-wear-wear-what-you-want-get.html


text:
Q: Django ckeditor I'm going to use ckeditor in my django platform.
My settings is:
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, '')

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

MEDIA_ROOT = os.path.join(STATIC_ROOT, 'static/media')
MEDIA_URL = "/media/"

CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, 'uploads')
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_MEDIA_PREFIX  = "/media/ckeditor/"
CKEDITOR_UPLOAD_PREFIX = "http://fortezzeimperiali/media/uploads/"
CKEDITOR_RESTRICT_BY_USER = True
CKEDITOR_IMAGE_BACKEND = "pillow"

But when I browse my image I get this error:
fortezzeimperiali/static/media/uploads/sega/2015/03/21/schermata-2014-11-30-alle-003712.png HTTP/1.1" 404 2857

A: I have a setup which always works for me, perhaps you can try:
STATIC_URL = '/static/'
MEDIA_ROOT = ''
MEDIA_URL = '/media/'
STATIC_ROOT = 'static'

# CKEditor settings
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
#This ensures you have all toolbar icons
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': None,
        },
    }

And of course, you should have ckeditor in your INSTALLED APPS
....
'ckeditor',
...

And add ckeditor to your urls:
(r'^ckeditor/', include('ckeditor.urls')),

I'm sure you've seen this page: https://github.com/django-ckeditor/django-ckeditor

A: Maybe you should use an valid domain, not fortezzeimperiali alone?
KEDITOR_UPLOAD_PREFIX = "http://fortezzeimperiali.com/media/uploads/"

A: If everything is working okay, but the image isn't being grabbed, maybe you forgot to run python manage.py collectstatic after installing?
Or, if it's just an issue of not seeing the thumbnails in the image browser (but you're getting the preview when you click on the broken-thumbnail images), then you just need to run python manage.py generateckeditorthumbnails to generate thumbnails for the images already on your server. Those not being there will causes you to see some 404's come over the network, but won't cause the site to break or anything. But running that command would make them go away, if that's the case.


text: Q: How I can export a file (Ex: *.txt) in react native(expo) in "Download" folder from Android? I want export a file with data from a app that I am creating, but I not know how do this, and after this, how I can save this archive in a folder from my choose


text:
Q: Сорри, переписать axios => fetch import React, {Component} from 'react';
import axios from 'axios';

import Cryptocurrency from './Crypto2';

class Ticker extends Component {

    fetchCryptocurrencyData() {
        axios.get('https://api.bitfinex.com/v1/tickers', {
            method: 'HEAD',
            mode: 'no-cors',
            headers: {
                'x-apikey': 'qwTOFqqg4Z3IzXIcwUTbzSgWSx7sAtn3WF1YENaSako',
                'Access-Control-Allow-Origin': '*',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
              }
        })
            .then(response => {
                var wanted = ["BTCUSD", "ETHUSD", "XRPUSD", "BCHUSD", "LTCUSD", "NEOUSD"];
                var result = response.data.filter(currency => wanted.includes(currency.pair));
                this.setState({data: result});
            })
            .catch(err => console.log(err));
    }
    componentDidMount() {
        this.fetchCryptocurrencyData();
        this.interval = setInterval(() => this.fetchCryptocurrencyData(), 60000);
    }
    state = {
        data: [
            {
                pair: "BTCUSD",
                bid: ""
            },
            {
                pair: "ETHUSD",
                bid: ""
            },
            {
                pair: "XRPUSD",
                bid: ""
            },
            {
                pair: "BCHUSD",
                bid: ""
            },
            {
                pair: "LTCUSD",
                bid: ""
            },
            {
                pair: "NEOUSD",
                bid: ""
            }
        ]
    }
    render() {
        var tickers = this.state.data.map((currency) =>
        <Cryptocurrency data={currency} key={currency.pair}/>
        )
        return(

 {tickers}

        );
    }
    componentWillUnmount() {
        clearInterval(this.interval);
      }
}

export default Ticker;

Проблема: хочу воспользоваться githubpages, cors не пропускает, нужно переписать запрос под fetch, помогите.


text:
Q: mysql safe read - update - write I'm try to understand mysql lock record mechanic, this is show case in Golang
or here https://play.golang.org/p/2fGKEyh0Wl
it run 2 concurrent transactions, and they read-update on the same row
- the first transaction will try to lock the row, do something (sleep for 3 secs)
- the second then try to read-update on the same key
the test source code
package main

import (
    "github.com/jmoiron/sqlx"
    "github.com/satori/go.uuid"
    "log"
    "sync"
    "time"
    _ "github.com/go-sql-driver/mysql"
)

type Wallet struct {
    ID      string
    Balance int64
}

func main() {
    db, err := sqlx.Connect("mysql", "root:abc123@tcp(mysql:3306)/test?parseTime=true")
    if err != nil {
        log.Println(err)
        return
    }
    db.Exec(`CREATE TABLE test_wallet (
    id varchar(64) NOT NULL,
    balance bigint(20) DEFAULT NULL,
    PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    `)
    var wg sync.WaitGroup
    wg.Add(2)

    wID := uuid.NewV4().String()
    db.Exec("INSERT INTO test_wallet (id,balance) VALUES (?,?)", wID, 10)

    go func() {
        defer wg.Done()
        tx, err := db.Beginx()
        w1 := &Wallet{}
        err = db.Get(w1, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID) // read and lock the record
        if err != nil {
            log.Println(err)
        }
        log.Printf("got %+v on r1\n", w1)
        time.Sleep(time.Second * 3)
        res, err := tx.Exec("UPDATE test_wallet SET balance=? WHERE id=?", w1.Balance+5, wID)
        if err != nil {
            log.Println(err)
        }
        n, err := res.RowsAffected()
        if n != 1 {
            log.Println("update not affected r1")
        }
        tx.Commit()
        log.Println("done on r1")
    }()

    time.Sleep(time.Second) // make sure go-routine lock `id` row

    go func() {
        defer wg.Done()
        tx, err := db.Beginx()
        w2 := &Wallet{}
        err = db.Get(w2, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID)
        if err != nil {
            log.Println(err)
        }
        log.Printf("got %+v on r2\n", w2)
        res, err := tx.Exec("UPDATE test_wallet SET balance=? WHERE id=?", w2.Balance+7, wID)
        if err != nil {
            log.Println(err)
        }
        n, err := res.RowsAffected()
        if n != 1 {
            log.Println("update not affected r2")
        }
        tx.Commit()
        log.Println("done on r2")
    }()
    wg.Wait()
    w := &Wallet{}
    err = db.Get(w, "SELECT * FROM test_wallet WHERE id=?", wID)
    if err != nil {
        log.Println(err)
    }
    log.Printf("%+v\n", w)
}

result from my terminal
2016/10/01 09:57:00 got &{ID:aab7165c-4b3b-406d-b1d0-caf3f45f72be Balance:10} on r1
2016/10/01 09:57:01 got &{ID:aab7165c-4b3b-406d-b1d0-caf3f45f72be Balance:10} on r2
2016/10/01 09:57:01 done on r2
2016/10/01 09:57:03 done on r1
2016/10/01 09:57:03 &{ID:aab7165c-4b3b-406d-b1d0-caf3f45f72be Balance:15}

it seem the second routine has not been lock ???

A: You misused the transaction. The db is not in transaction, only tx is. So, the statements in first and second go routine which are
err = db.Get(w1, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID) // read and lock the record
err = db.Get(w2, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID)

will not lock the row, because db is not wrapped in transaction. You must use tx to execute the query, i.e.
err = tx.Get(w1, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID) // read and lock the record
err = tx.Get(w2, "SELECT * FROM test_wallet WHERE id=? FOR UPDATE", wID)

After modification, I got the following result:
2016/10/01 13:26:10 got &{ID:6ff45acd-701c-458f-a17f-84cc4e982c80 Balance:10} on r1
2016/10/01 13:26:14 done on r1
2016/10/01 13:26:14 got &{ID:6ff45acd-701c-458f-a17f-84cc4e982c80 Balance:15} on r2
2016/10/01 13:26:14 done on r2
2016/10/01 13:26:14 &{ID:6ff45acd-701c-458f-a17f-84cc4e982c80 Balance:22}


text:
Q: How do I reverse an array in place in assembly? I am supposed to reverse an array in place. I have been working on it for a while and this is what I have. Can anyone tell me what I'm doing wrong?
.data
array BYTE 10h, 20h, 30h, 40h

.code
main PROC
    mov esi, 0
    mov edi, 0
    mov esi, OFFSET array
    mov edi, OFFSET array + SIZEOF array
    mov ecx, SIZEOF array/2

l1: mov al, [esi]
    mov bl, [edi]
    mov [edi], al
    mov [esi], bl
    inc esi
    dec edi
    LOOP l1

    call DumpRegs
    call DumpMem

    exit

main ENDP

END main

A: Try to declare two arrays, one intilized with your values and the other one could be like this using DUP operator 5 DUP (?)
And start moving values from first array to the second using a loop.
Example:
.data
myArr1 DWORD 5, 4, 3, 2, 1
myArr2 DWORD 5 DUP (?)
.code main proc
mov edi, offset myArr1
add edi, sizeof myArr1
mov esi, offset myArr2
mov ecx, lengthof myArr2
reverseLoop:
add ebx, [edi] mov[edi], ebx
sub edi, type myArr2
add esi, type myArr1
mov eax, [edi]
call writeint
LOOP reverseLoop
exit
main endp
end main


text:
Q: API SOAP V2 CatalogProductList Complex Filter with OR I need to set up a filter with a OR clausule and I don't know how to. Any Help?.
I need to set up the filter manufacturer to filters manufacturer number 34 and 37.
Dim pws As New MagentoService.MagentoService
Dim sesionID = pws.login("xxxxxxx", "xxxxxxxxxxx")
Dim result

Dim filters As New MagentoService.filters
Dim complexFilter(2) As MagentoService.complexFilter
complexFilter(0) = New MagentoService.complexFilter
complexFilter(0).key = "manufacturer"
Dim assEnt As New MagentoService.associativeEntity
With assEnt
    .key = "in"
    .value = ¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿"34" OR "37"?????????????????
End With
complexFilter(0).value = assEnt

complexFilter(1) = New MagentoService.complexFilter
complexFilter(1).key = "set"
Dim assEnt2 As New MagentoService.associativeEntity
With assEnt2
    .key = "eq"
    .value = "9"
End With
complexFilter(1).value = assEnt2

filters.complex_filter = complexFilter
result = pws.catalogProductList(sesionID, filters, "0")

I think I must use the key in and use an array on value, but I can't.
Thanks

A: For in complex filter you must specify value in coma separated format (without spaces): value = '34,37'.


text:
Q: using IPL_DEPTH_32f in Opencv what Does this mean "IPL_DEPTH_32F " in openCv ?
and what will happened in the picture  when we convert it to  IPL_DEPTH_8U ?
from where I know the image is "IPL_DEPTH_32F" or "IPL_DEPTH_8U" , when I use this function CVCreateImage  ?!

A: Pixel depth in opencv is specified as:
IPL_DEPTH_<bit_depth>(S|U|F)

Where S is signed, U is unsigned and F is float.
IPL_DEPTH_32F means per channel per pixel is stored as 32 bit floating point number.
When you convert it to IPL_DEPTH_8U, number of values that can be represented by each pixel per channel decreases and thus quality will decrease and the size of image buffer would be smaller.


text:
Q: GoPro Hero 2 Battery Elliminator? (3.7v versus 5v) I have an old GoPro Hero 2 who's external USB plug has failed, and I have no way of powering it externally. I need to run this GoPro using an external wired power source (available over a 5v USB).
There are battery eliminators available for the Hero 3 (example) that replace the battery unit with a USB cable connecting directly to the device's leads.
Is this product nothing more than a glorified power cable inputting 5V? Or is there a voltage regulator and thermistor dummy circuit in there? Could I build my own or modify something like this to work with a GoPro Hero 2?
For reference, the battery of the GoPro Hero 2 and 3 are 3.7v.

A: According to Benlo.com:

Figure 1. Hero 2 battery eliminator connection points.

Figure 2. Hardwired Hero 3 battery eliminator.

Using a Battery Eliminator with the Hero 3 Camera
GoPro cameras can be run off a 4 volt power source which replaces the internal battery. The voltage must be no less than 3.75V and no greater than 4.2V. The power supply must be capable of supplying 0 to 1.1 A of current without deviating from the above range. The T-sense pin on the camera is not needed with a battery eliminator power supply.

You can't supply directly from USB 5 V supply. Some form of regulation will be required.

simulate this circuit – Schematic created using CircuitLab
Figure 3. Simple "constant" voltage dropper.
You could try the circuit of Figure 3 to power the camera. The theory of operation is that

*

*each diode will drop 0.7 of a volt when even a few mA is drawn through them.

*R1 draws the small current so the voltage across the resistor should be about 3.6 V.

*Depending on your exact 5 V voltage from the USB port, the diodes and the camera this might just work. It won't cause any damage as it would be the same as a flat battery.

*If it doesn't work then you could replace one or both diodes with Schottky diodes which have a lower forward voltage drop.

Procedure:

*

*Connect up the components but not the camera.

*Plug in to USB port and measure voltage across R1.

*If voltage is about right then unplug USB, solder up and test.

A: No, directly connecting 5V to a li-ion battery connection is a bad idea. Most battery eliminator circuits will regulate to a voltage within the battery range. Use a regulator with the usb  power supply down to say 3.8 or 4 V.
Or replace the broken usb connector with a cable.


text:
Q: If $\sqrt{a}\sqrt{b}=\sqrt{ab}$ only holds for positive real $a$ & $b$, then why can we say $\sqrt{-a}=\sqrt{-1\cdot a}=\sqrt{-1}\sqrt{a}=i\sqrt{a}$? I am a little bit bummed that I have this question as I'm sure it has been asked before (I couldn't find the answer) but...

If $\sqrt{a}\sqrt{b} = \sqrt{ab}$ is only true for positive reals $a$ and $b$. Then what allows us to say the following? $$\sqrt{-a} = \sqrt{-1\cdot a} = \sqrt{-1}\sqrt{a} = i\sqrt{a}$$

I don't know what allows the second equal sign. Is this just convention?

A: The square root function is usually understood by convention to return the "principal" square root of a complex number. For real numbers, this just means that the square root of a positive real is a positive real and the square root of a negative real is imaginary with positive imaginary part. Under this convention, it happens to be valid that $\sqrt{ab}=\sqrt{a}\sqrt{b}$ if $a$ and $b$ are real with at least one of them nonnegative. But the equality fails if both are negative. For example
$$
1=\sqrt{(-1)(-1)}\neq\sqrt{-1}\sqrt{-1}=i\cdot i=-1.
$$

A: Be aware of the setting $i=\sqrt{-1}.$ The law $\sqrt{a}\sqrt{b}=\sqrt{ab}$ does only apply to real numbers. It is wrong for complex numbers because
$$
-1= i^2=i\cdot i =\sqrt{-1} \cdot \sqrt{-1}\neq \sqrt{(-1)^2}=1
$$
The best way to see it is in my opinion to operate with the equation $i^2=-1$ only; not roots. They are an abbreviation for real numbers.
Another possibility is to use Euler's formula $-1=e^{i \pi}.$ Thus
$$
-1=e^{i\pi}=\left(e^{i\pi/2}\right)^2=i^2\text{ and }\sqrt{(-1)^2}=\sqrt{\left(e^{i\pi}\right)^2}=\sqrt{e^{2i\pi}}=\sqrt{1}=1
$$
This uses the power $1/2$ instead of roots and you avoid formulas which simply do not hold for complex numbers.

A: $\DeclareMathOperator{\Log}{Log} $
Let $a \in \mathbb R$ and define a square root via $\sqrt{z} := \exp(\tfrac 12\Log z)$ with $\Log z$ having a branch cut along the negative imaginary axis, i.e. $\Log(z) := \log|z| + i \theta$ with $\log$ the real logarithm and $\theta \in [-\pi/4, 3\pi/4)$. Then your formula above says:
$$\exp(\tfrac 12\Log(-a)) = \exp(\tfrac 12\Log(-1\cdot a))= \exp(\tfrac 12\Log(-1))\exp(\tfrac{1}{2}\Log a)=i\exp(\tfrac{1}{2}\Log a)$$
Thus the two things to check here are that $\Log(-1\cdot a) = \Log(-1) + \Log a$ and that $\exp(\tfrac 12\Log(-1)) = i$. For the latter, note $\Log(-1) = \log(1) + i\pi= i\pi$ so that $\exp(\tfrac 12\Log(-1))=e^{i \pi/2}=i$. For the former, note that if $x,y \in \mathbb C$ with  $-\pi/4 \le \arg(x)+\arg(y)<3 \pi/4$ then $\arg(x)+\arg(y) = \arg(xy)$ (note this does not hold if we cross a branch... Can you see why?
) so we have:
$$\Log(x)+\Log(y)=\log|x|+\log|y|+i(\arg(x) + \arg(y)) \stackrel{!}{=}\log(|xy|)+i\arg(xy) := \Log(xy)$$
where equality $!$ follows from the multiplicativity of the real logarithm, the fact $|x||y| = |xy|$, and the fact $\arg(x) + \arg(y) = \arg(xy)$.
Applying this result with $x = -1$ and $y = a$ we see $\arg(x) = \pi$, $\arg(y) = 0$, and $\arg(xy) = \arg(-a) = \pi$ so the above lemma holds and we are done. Note the choice of the branch along the negative imaginary axis was arbitrary; the argument above holds without any problem for any branch cut from $0$ to $\infty$ lying strictly in the open lower half-plane. If you want to choose a branch intersecting the closed upper half-plane (e.g. the standard branch) you'll have to keep track of the extra $2 \pi i$ factor added or removed every time you cross the branch, though the argument will go through in essentially the same way.

Note: As @Subrosar says, we always have $\Log(x) + \Log(y) = \Log(xy)$ when one of $x$ or $y$ is nonnegative and the choice of branch cut is a straight line from $0$ to $\infty$, and this happens simply because one of $\arg(x)$ or $\arg(y)$ is zero; assuming WLOG $\arg(x) = 0$, we have $\arg(x) = 0 \le \arg(xy) = \arg(y)$, so $xy$ does not cross the branch cut since it is simply a scaled copy of $y$. Note this fails if the branch cut is not a straight line, as it could be that $y$ and $xy$ lie on separate sides of the branch cut.


text:
Q: TSP variant with a different objective I recently ran across the following problem:
There is a complete graph with edge lengths and vertex weights. The edge lengths obey the triangle inequality. There is a source node S. Find the lowest cost tour in the graph where the cost of tour is the total energy expended, that is, when a node is visited on the tour we pick up the weight from there and add to the objective that weight times the sum of the edge lengths until we get back to S.
I wonder if this TSP variant has a name, and I wonder how would you go about solving it?


text:
Q: Variable was unexpected at this time in a loop I am new to Windows shell scripting. While running the following script, I am getting an error "((j was unexpected at this time "
$ for ((j=0;j<10;j++)); do
$ rtg map -i sample1-100M -t hg19 -o map_sample1-$j --start-read=$
[j*10000000] --end-read=$[(j+1)*10000000]
$ done

A: Here is the bash script rewritten as batch script for the Windows Command Processor cmd.exe:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /L %%j in (0,1,9) do (
    set /A OffsetStart=%%j * 10000000
    set /A OffsetEnd=OffsetStart + 10000000
    rtg.exe map -i sample1-100M -t hg19 -o map_sample1-%%j --start-read=!OffsetStart! --end-read=!OffsetEnd!
)
endlocal

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

*

*echo /?

*endlocal /?

*for /?

*set /?

*setlocal /?


text:
Q: Page layout structure with multiple asp.net chart controls in iTextSharp I have multiple chart dynamically created and attaching to pdf. Currently there are printing one on one line. I want to achieve something like this.
.
I want to create a container with some background and add columns like container in it.
 byte[] GetBarChartImage(params int[] points)
    {
        using (var stream = new MemoryStream())
        {
            using (var chart = new Chart())
            {
                chart.Width = 200;
                chart.Height = 200;
                chart.ChartAreas.Add(new ChartArea());
                Series s = new Series();
                s.ChartType = SeriesChartType.Column;
                for (int i = 0; i < points.Length; ++i)
                {
                    s.Points.AddXY(points[i], points[i]);
                }
                chart.Series.Add(s);
                chart.SaveImage(stream, ChartImageFormat.Png);
            }
            return stream.ToArray();
        }
    }

and adding charts to pdf like this
pdfDoc.Add(iTextSharp.text.Image.GetInstance(GetBarChartImage(3, 5, 7)));
pdfDoc.Add(iTextSharp.text.Image.GetInstance(GetBarChartImage(2, 4, 6, 8)));

How to create this type of layout. Need help


text:
Q: What are the different nuances of "passing with distinction" in a CV? I am in the middle of translating my (German) CV to English.
In the German/Austrian school system, there is the notion of passing ...

*

*... "mit gutem Erfolg" (which is better than average, yet not the best you can achieve, roughly translating to "good success")

*... "mit ausgezeichnetem Erfolg" (which is the best you can achieve, similar to "with distinction")

What would be a good English word/expression for the former expression in my CV? Is there a grading of "passing with distinction" in British/American English or their respective school systems?

Update: I was referring to the general way of referring to "passing with distinction". Our universities give Latin grades ("cum laude", etc.), whereas schools don't.

A: In American universities, graduation honors are given in Latin. The main three are:

*

*cum laude, meaning "with honor"[1]—usually pronounced /kʊmˈlaʊdeɪ/ or /kʊmˈlɔːdeɪ/.

*magna cum laude, meaning "with high honor"

*summa cum laude, meaning "with highest honor"

The exact cutoffs for each distinction depend on the school, but the rank order (where the top is summa cum laude, and the lowest is cum laude) remains the same.
In your case, I think that mit gutem Erfolg would correlate either to cum laude or magna cum laude. Because mit ausgezeichnetem Erfolg is the best you can do, I think it correlates better to summa cum laude than magna cum laude.
I am not sure exactly how the British system ranks their degrees, but their is some discussion of it here.
Edit: In American schools (not universities), there is also the notion of graduation with honors. At the high school I attended, there were two ways to graduate: with or without honors. Based on this, the only commonly used phrase would be with honors (because after that, there was class rank). However, in order to distinguish between the two, you could use:

*

*graduation with honors

*graduation with high honors

Though the second isn't used for American high schools, most people are familiar with the Latin degree honors that confer different levels of distinction.

A: The British school system is constantly changing, and I was astonished not long ago to see photos of a friend's daughter wearing a mortarboard to "graduate" from nursery school (kindergarten). I mention this to observe that I may be out of date.
However, the whole concept of "passing" or "not passing" school doesn't exist in the British system. What you pass or fail are the individual subjects, and you receive individual grades in them. Translating between this system and the International Baccalaureate (which I believe the German system is rather closer to) is not easy, although you might be able to get a rough equivalence from the UCAS Tariff tables.
A reasonable approach for your British-English CV would be to translate "mit gutem Erfolg" as "with merit" and "mit ausgezeichnetem Erfolg" as "with distinction". Although there isn't a direct analogy with A-levels, there is an analogy with various other certificates, such as the standard music exams.
One final observation: employers don't really care much about your school grades. The only thing they're really useful for are getting into university.

A: Peter Taylor gave a good answer. For this question, it is important to distinguish between school and university systems.
From my experience, I can tell you about the British school system. It does not have a concept of "passing" or "not passing". At least not in the sense of, the Germanic system that you have described.
People do different exams for different subjects. At least one exam in each. Although, some subjects have more than one exam. These exams are generally called GCSEs. A grade is awarded for each one.
Regarding your question:

Is there a grading of "passing with distinction" in British/American
  English or their respective school systems?

The nearest equivalent to this in British English, would be the grades for GCSEs. These vary from A* (pronounced as "A star"), across the alphabet until G and U (unclassified). A* being the highest and G being the lowest. U is for people who did not do the exam for a subject.
What you pass or fail are the individual subjects, and you receive individual grades in them. Usually, C is considered the minimum pass, in a subject. Five Cs have long been considered to be the minimum standard to achieve, in GCSEs. At least they were, when I did them.
It is possible to do more than five GCSEs. How many subjects you do, is down to you. Pupils can choose how many they do but, there are normally certain subjects that are compulsory, like English and maths.

A: This is purely for school only, not if you had graduated from university.
If you passed with the best that you could achieve, you would be said to have "High Distinction" in the British/Australian system; so if you did 'better than average', but not the best, I would say you had:

Distinction/ I passed with Distinction, but not High Distinction.

A: The most widely-recognized English phrases for these are, ironically, in Latin.

*

*"mit gutem Erfolg" is equivalent to cum laude or "with honors."

*"mit ausgezeichnetem Erfolg" is equivalent to magna cum laude, or "with high honors."
You're free to use either the Latin or the English translations, as both will be understood. However, the Latin titles are what is usually written on diplomas, CVs, and other formal documents.

A: The "passing" term I've seen is "High Pass."
That means "less than the best," but higher than the usual "pass."

A: You can tell from the other answers here that this question is an example of when certain things in one language don't translate into other languages. At least into the English of the UK.
In order to talk of this to British people, you would first have to explain this Germanic school exam system  before mentioning the results.
This is just one example of when certain things in one language don't translate into other languages. There are many examples of this from other languages as well, not just German. This is something that you need to understand when you learn other languages — whatever they may be.


text:
Q: How to write WebApp to reuse source code in Ionic What should be requirements on source code of WebApp to be sure that in easy way we adopt it in Ionic's application. The question is inversion of How to use Ionic Framework for Web App Development?
There are recommended practises for Angular.JS ?

A: A good start is simply to write your angular app with good clean design and encapsulation of proper things into services and directives.
You should definitely be able to reuse many services.  I've even had a few directives work out by applying different CSS to them.


text:
Q: Lithium Ion and Lead Acid battery in series I have a 12v trolling motor (55 lb) that is rated for 50 amps. At speed I only pull < 30 amps in my inflatable boat. I know that increasing the voltage will make the prop spin faster, which will draw more amps, but also make me go faster, which is the goal.
Is it possible/safe/feasible to connect my 12v lead-acid battery in series with a 3.7v Lithium-Ion bundle (of reasonably similar C) for a 15.7 (nominal) volt setup? I have already done some hand-wavy calculations and think I will hit my amp limit (though I should probably stay around 45 to be safe) at ~14.5v, so I will use a PWM (which I already have installed) to limit my amperage... I.E., dont worry about the other factors involved;
I just want to know, is there some fundamental reason such a setup would not work?
I have already considered using step-up/boost converters to increase the voltage, but with the amperage required I would need either an expensive one or many less expensive ones, and I rather spend that money/use that space on more battery power because of the added Watt-hrs they bring onboard.
Cheers,
Bryan

A: What you propose should work technically and is probably not too hard to do "well enough" as long as you are sensible [tm].
As Peter says, mixing battery chemistries can often have bad outcomes, but as long as you do not violate basic requirements this could be reasonably problem free.
It is not obvious why you would use a LiIon second battery - lead acid will better match the cost/capacity and general cycle lifetime for given use.
If your main battery was say about 50 Ah (less than 1 hour at 50 A due to C rating usually being at 10 hour rate or even lower) and you wanted both batteries to work together throughout the LiIon battery would also need to be 50 Ah or more. That's not a small battery and you are going to need a separate specialist charger to charge it - which is OK if you have the equipment already - but otherwise adds expense and complexity. You may be able to obtain 2V indivual LA cells or a 4V battery (they do exist) but again are faced with the charging issues mentioned below.
A LiIon battery MUST have it's low voltage discharge limited to a safe voltage. It MUST be rated to discharge safely and continuously at say 50A.
Max charging current is liable to be 25A or 50A (or other - varies with manufacturer). You COULD safely enough [tm] charge a single LiIon cell by limiting Imax to at or below rated max value and setting maximum charge voltage to say 4V or slightly less. You can then allow it to charge until 4V is reached and can float it at 4V "safely". This charges to noticeably below max capacity and increases cycle life. You MUST NOT charge it all the way to 4.2V and float it there - battery death happens soonish.
Note that LiIon will have 4.2V (if fully charged) to start and 3V or so fully discharged. (Lower possible but unwise if long cell life is wanted).


text:
Q: fastested way to insert 70 milions records from xml to mysql using java I have wrote a java code to parse xml file using jaxb and then insert the data from xml file to my sql. The code does insertion to different 20 tables based on the xml tags.
My problem is that my code is running for last 3 days and it could insert 5 millions record to my sql data base!
In this way I need to wait a month to finish the job..
Can you give me some hint how can I make my code efficient?

A: MySQL supports 'LOAD DATA' command and CSV format. So converting your XMLs into prepared CSV and then load by mysql abilities will be fastest solution:
How to import CSV file to MySQL table


text:
Q: Recommendations for sysctl.conf settings to harden Linux against DDoS attacks? A recent article from UNIXy http://blog.unixy.net/2010/08/the-penultimate-guide-to-stopping-a-ddos-attack-a-new-approach/ has suggestions to harden a Linux box against DDoS attacks.
Example of sysctl.conf
net.ipv4.tcp_syncookies = 1

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.default.rp_filter = 1

kernel.pid_max = 65536

net.ipv4.ip_local_port_range = 9000 65000

Any other recommendations for hardening Linux against DDoS attacks?

A: You can also turn down the read/write socket buffers as well, which would decrease the amount of memory each inbound connection requires.
http://wwwx.cs.unc.edu/~sparkst/howto/network_tuning.php
You'll have to actually test it out for your application and your hardware (yes, those settings can cause weird side effects depending on your NIC), since you may break more than you save depending on your traffic flow.

A: You could set the following as well.
# Turn on SYN-flood protections.  Starting with 2.6.26, there is no loss
# of TCP functionality/features under normal conditions.  When flood
# protections kick in under high unanswered-SYN load, the system
# should remain more stable, with a trade off of some loss of TCP
# functionality/features (e.g. TCP Window scaling).
net.ipv4.tcp_syncookies=1

# Ignore source-routed packets
net.ipv4.conf.all.accept_source_route=0
net.ipv4.conf.default.accept_source_route=0

# Ignore ICMP redirects from non-GW hosts
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.default.accept_redirects=0
net.ipv4.conf.all.secure_redirects=1
net.ipv4.conf.default.secure_redirects=1

# Don't pass traffic between networks or act as a router
net.ipv4.ip_forward=0
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.default.send_redirects=0

# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks.
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1

# Ignore ICMP broadcasts to avoid participating in Smurf attacks
net.ipv4.icmp_echo_ignore_broadcasts=1

# Ignore bad ICMP errors
net.ipv4.icmp_ignore_bogus_error_responses=1

# Log spoofed, source-routed, and redirect packets
net.ipv4.conf.all.log_martians=1
net.ipv4.conf.default.log_martians=1

# RFC 1337 fix
net.ipv4.tcp_rfc1337=1

# Addresses of mmap base, heap, stack and VDSO page are randomized
kernel.randomize_va_space=2

# Reboot the machine soon after a kernel panic.
kernel.panic=10