text:
Q: Mysql query to get columns from 2 Tables into one result set I am trying to create a query that displays a4, a2, a3 from TableA and date from
TableC for all Items connected by b.b1 = 2. The output should be in
chronological order by date descending.
TableA
___________________________________________
| a1   | a2   | a3   | a4   | a5   | a6   |
-------------------------------------------
| 1    |  222 | 333  | 444  | 555  | 665  |
-------------------------------------------
| 2    |  asd | sdf  | ert  | jkl  | xcv  |
-------------------------------------------
| 3    |  111 | tyu  | bnm  | abc  | xyz  |
-------------------------------------------
| 4    |  222 | yyy  | dfd  | hgg  | 544  |
-------------------------------------------
| 5    |  222 | y56  | df5  | hg7  | 234  |
-------------------------------------------

TableB
___________________
| b1  | b2  | b3  |
-------------------
| 1   | 717 | c   |
-------------------
| 2   | 727 | d   |
-------------------
| 3   | 737 | c   |
-------------------
| 4   | 747 | d   |
-------------------

TableC - c2 is foreign key to a.a1 - c3 is foreign key to b.b1
_____________________________
| c1  | c2  | c3  |  date   |
-----------------------------
| 1   | 2   | 2   |12-01-12 |
-----------------------------
| 2   | 1   | 1   |12-05-12 |
-----------------------------
| 3   | 5   | 2   |12-07-12 |
-----------------------------
| 4   | 3   | 1   |12-14-12 |
-----------------------------
| 5   | 4   | 2   |12-18-12 |
-----------------------------

It should look Like this...
____________________________
| a4  | a2  | a3  |  date  |
----------------------------
| ert | 222 | 333 |12-01-12|
----------------------------
| df5 | 222 | y56 |12-07-12|
----------------------------
| dfd | 222 | yyy |12-18-12|
----------------------------

I got it down to the point that If I split my query into two pieces I get the info from the two tables, and the "UNION ALL"
makes my date add rows at the bottom of the table (with two other columns I dont want, c2 and c1), I actually want a column
called date next to a3 in my results. How do I get that column "date" into the result set?
SELECT a.a4, a.a2, a.a3
FROM TableA a
JOIN TableC c ON c.c2 = a.a1
JOIN TableB b ON b.b1 = c.c3 and c.c3 = 2
UNION ALL
SELECT d.date,d.c2,d.c1
From TableC d
JOIN TableB b ON b.b1 = d.c3 and d.c3 = 2

Please ask any questions you need to, this is killing me.

A: There are other confusing items here, but without digging too deep this is as easy as:
SELECT a.a4, a.a2, a.a3, c.date
FROM TableA a
JOIN TableC c ON c.c2 = a.a1
JOIN TableB b ON b.b1 = c.c3 and c.c3 = 2

The UNION does not do you were thinking it did.
Also, is there any need to join table b?
SELECT a.a4, a.a2, a.a3, c.date
FROM TableA a
JOIN TableC c ON c.c2 = a.a1 and c.c3 = 2


text:
Q: Scrape script tag with python selenium xpath Let's say I would like to scrape some metadata from a website:
https://www.diepresse.com/4913597/autocluster-buhlt-um-osterreich-teststrecke-fur-google-autos
To be more precise, i.e. from the Key fullChannel the Value /home/wirtschaft/international from this <script> tag:
<script>
let pageBreakpoint = 'desktop';
let _screen = window.innerWidth;
if (_screen < 640) {
    pageBreakpoint = 'mobile';
} else if (_screen < 1024) {
    pageBreakpoint = 'tablet';
}

var dataLayer = window.dataLayer || [];
    dataLayer.push({
        'siteId': 'dpo',
        'contentId': '4913597',
        'pageType': 'article',
        'contentTitle': 'Autocluster buhlt um Österreich-Teststrecke für Google-Autos',
        'contentAuthor': '',
        'contentElements': '',
        'contentType': 'default',
        'pageTags': '',
        'wordCount': '264',
        'wordCountRounded': '400',
        'contentSource': '',
        'contentPublishingDate': '',
        'contentPublishingDateFormat': '28/01/2016',
        'contentPublishingTime': '08:52',
        'contentPublishingTimestamp': '28/01/2016 08:52:00',
        'contentRepublishingTimestamp': '28/01/2016 08:52:00',
        'contentTemplate': 'default',
        'metaCategory': '',
        'channel': 'international',
        'fullChannel': '/home/wirtschaft/international',
        'canonicalUrl': '',
        'fullUrl': window.location.href,
        'oewaPath': 'RedCont/Wirtschaft/Wirtschaftspolitik',
        'oewaPage': 'homepage',
        'isPremium':'no',
        'isPremiumArticle': 'free',
        'pageBreakpoint': pageBreakpoint,
        'userId': ''
    });
</script>

Right now I am using Selenium and Xpath and can't really figure out how to use regex on this:
#this doesnt work
driver.find_element_by_xpath("//script[text()]")

Any suggestions?

A: Your XPath to find script seems to be wrong -- try this:
script = driver.find_element_by_xpath("//script[contains(text(), 'let pageBreakpoint')]")

Then, you can use some string parsing methods to extract the value from fullChannel:
# Get index of string 'fullChannel'
fullChannelTextIndex = script.index('\'fullChannel\': ')

# Shorten script string by removing everything before 'fullChannel'
simplifiedScript = script[fullChannelTextIndex : len(script)-1]

# Call split on 'canonicalUrl', which appears AFTER 'fullChannel'
# Then replace 'fullChannel' text to get just the field value
fullChannelValue = simplifiedScript .split('\'canonicalUrl\': ')[0].replace('\'fullChannel\': ', '').replace(',', '')

print(fullChannelValue)

This produces the output '/home/wirtschaft/international'

There are likely more efficient ways to do this than through Selenium, but I will leave my Selenium answer here in case you want to go this route.

A: Use JavaScript Executor to Get the var value datalayer.It will return as json array.
Then get the value of key fullChannel.
driver.get("https://www.diepresse.com/4913597/autocluster-buhlt-um-osterreich-teststrecke-fur-google-autos")
datalayer=driver.execute_script("return dataLayer")
print(datalayer)
print(datalayer[0]['fullChannel'])

Output:
[{'oewaPage': 'homepage', 'contentTitle': 'Autocluster buhlt um Österreich-Teststrecke für Google-Autos', 'userId': '', 'wordCount': '264', 'contentSource': '', 'contentPublishingDate': '', 'contentElements': '', 'contentAuthor': '', 'fullUrl': 'https://www.diepresse.com/4913597/autocluster-buhlt-um-osterreich-teststrecke-fur-google-autos', 'wordCountRounded': '400', 'contentTemplate': 'default', 'canonicalUrl': '', 'contentPublishingTime': '08:52', 'metaCategory': '', 'siteId': 'dpo', 'contentPublishingDateFormat': '28/01/2016', 'isPremium': 'no', 'oewaPath': 'RedCont/Wirtschaft/Wirtschaftspolitik', 'contentRepublishingTimestamp': '28/01/2016 08:52:00', 'contentPublishingTimestamp': '28/01/2016 08:52:00', 'pageTags': '', 'pageBreakpoint': 'desktop', 'contentType': 'default', 'fullChannel': '/home/wirtschaft/international', 'isPremiumArticle': 'free', 'contentId': '4913597', 'channel': 'international', 'pageType': 'article'}, {'faktorVendorData4': 'notset', 'event': 'faktorData', 'faktorData4': 'notset', 'gtm.uniqueEventId': 9, 'faktorData1': 'notset', 'faktorData2': 'notset', 'faktorData5': 'notset', 'faktorData3': 'notset'}, {'gtm.uniqueEventId': 3, 'gtm.start': 1569877670044, 'event': 'gtm.js'}, {'aboStatus': '', 'userId': '', 'userType': 'default', 'userStatus': 'logout'}, {'gtm.uniqueEventId': 6, 'event': 'gtm.dom'}, {'gtm.uniqueEventId': 14, 'gtm.start': 1569877672926, 'event': 'gtm.js'}, {'faktorGdprApplies': 1}, {'gtm.uniqueEventId': 15, 'event': 'gtm.load'}]

Key value fullChannel
/home/wirtschaft/international

redpajama_set_name: RedPajamaStackExchange


text:
Q: kill running command using the name of the command My problem is that I have a command running in the shell and I want to stop it from PHP (using shell_exec ).
I found this

pkill [name of command]

and it works fine when the command is composed of one word.
shell_exec('pkill ping');

but my command is 'npm run test bla bla bla '
I tried also to get the pid of my running process using

pgrep [name of command]

and then use kill -9 but this doesn't work because I have also a command with more than 1 word.
Thank you


text:
Q: I get strange error while using package" Exception in thread "main" java.lang.NoClassDefFoundError. " I get "Exception in thread "main" java.lang.NoClassDefFoundError" while using "package"

*

*if I comment "//package com.kevin.corejava; " it would run successfully;

*Or, I delete the "main" method in "Employee.java", and add a class "Test.java" in folder "E:\Space\java" which imports "Employee.java" (import com.kevin.corejava.*), and reference Employee int its main method, it would still run successfully.

Why the "main" method in Employee could not run by itself when I add the sentence "package com.kevin.corejava" (Employee.java is put in path E:\Space\java\com\kevin\corejava\Employee.java)
package com.kevin.corejava;
import java.util.*;
import static java.lang.System.*;

public class Employee
{
    public Employee(String n, double s, int year, int month, int day)
    {
        name = n;
        salary = s;
        GregorianCalendar calendar = new GregorianCalendar(year, month-1,day);
        hireDay = calendar.getTime();
    }

    public String getName()
    {
        return name;
    }

    public double getSalary()
    {
        return salary;
    }
    public Date getHireDay()
    {
        return hireDay;
    }
    public void raiseSalary(double byPercent)
    {
        double raise = salary *byPercent/100;
        salary+=raise;
    }

    private String name;
    private double salary;
    private Date hireDay;

    public static void main(String[] args)
    {
        System.out.println("This is main ,I won't say 'Hello World'!");
    }

}

A: Just make sure you follow the below things :

*

*"package com.kevin.corejava;" It should be a valid path.

*Your package path must be executed by JDK, and JRE must access its class file. (Make Sure your JDK and JRE paths are right to access this
  file).

*The class name must be same as the file name as the main method is in your Employee class.

*Your project's Build path is right. If you use Eclipse or other IDE, just right click and configure your build path.


text:
Q: How to create new NSMutableArrays on the fly I want to create some NSMutableArrays. The numbers of arrays I want to create depends on another variable.  Since I don't know how many arrays will be created, can I create these arrays on the fly and assign the array name with a variable?

A: Yes, you can create NSMutableArrays on the fly; you just have to store them within a dynamically expandable data structure. I suggest either storing them within their own NSMutableArray or, if it's absolutely necessary for you to associate each with its own variable, you can store the arrays within an NSMutableDictionary.


text:
Q: Adding an asp.net label in between the tags of a parent label control when adding from the code-behind I am adding a parent asp.net label to my page in the code-behind like this:
Label lbl = new Label();
lbl.ID = "lblPrimary";
lbl.Text = "Testing";
placeholder.Controls.Add(lbl);

I need the end output to look as if I did the following in the aspx:
<asp:Label ID="lblPrimary" runat="server" Text="Testing">
     <asp:Label runat="server" SkinID="Required"></asp:Label>
</asp:Label>

How can I add the required label in between from the code-behind like above?

A: You can try the following code. The Text property of the outer Label is set with a Literal control, otherwise the text is overwritten when the inner Label is added to the Controls collection. If you want the exact result specified in your question, you can forget the Literal control but "Testing" will not be displayed in the outer Label.
Literal literalInner = new Literal();
literalInner.Text = "Testing";

Label lblInner = new Label();
lblInner.Attributes.Add("SkinID", "Required");

Label lblOuter = new Label();
lblOuter.ID = "lblPrimary";
lblOuter.Controls.Add(literalInner);
lblOuter.Controls.Add(lblInner);

placeholder.Controls.Add(lblOuter);


text:
Q: QSerialPort readings refresh too fast for the Qt widget I am using QSerialPort to read from a device connected to a COM port on my computer, and it sends characters every half a second to my computer. I can read them from the qDebug window, so I know the connection works and Qt receives the data.
However I continuously read from the serial port and refresh a label widget on my GUI. The label becomes blank when I run the app, I think this problem is caused by the label name constantly refreshing.
My QserialPort is managed in the mainwindow constructor, closed in destructor, and the readings are done in a function called serialReceived(), which I believe is called (or causes the label to refresh) too often
    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serial = new QSerialPort(this);

    qDebug() << "nb ports: " << QSerialPortInfo::availablePorts().length();
    foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
    {
qDebug() << "name" << serialPortInfo.portName();
    }

    serial->setPortName("COM11");
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    qDebug() << "is " << serial->open(QSerialPort::ReadOnly);
    qDebug() << "err " << serial->error();
    //serial->write("ok");

    // Create the signal and slot
    connect(serial, SIGNAL(readyRead()), this, SLOT(serialReceived()));
}

MainWindow::~MainWindow()
{
    delete ui;
    serial->close(); // instance is closed when mainwindow destroyed
}

void MainWindow::serialReceived()
{
    QByteArray ba;
    ba = serial->readAll();
    ui->label->setText(serial->readAll());
    qDebug()<<ba;
}

A: You just can read data at any time you want, not only by readyRead signal. The QSerialPort class will buffer all received data until you read it.
You also can append every received part of data to some scrollable QPlainTextEdit. I recommend this way.
void MainWindow::serialReceived()
{
    QByteArray ba;
    ba = serial->readAll();

    ui->plainTextEdit->appendPlainText(ba);
}

Using timer:
connect(&m_timer, &QTimer::timeout, this, &MyClass::onTimer);
...
m_timer->start(5000);
...

void MyClass::onTimer()
{
    if(serial->bytesAvailable() > 0)
    {
         QByteArray ba;
         ba = serial->readAll();
         ui->label->setText(ba);
         qDebug() << ba;
    }
}

You can also temporary disable visual updates of a widget using QWidget::setUpdatesEnabled(), but seems you should not miss part of the data.
Be note,  QIODevice (and QSerialPort as its sublass, too) class makes no guarantee that a certain amount of data will be available on the readyRead event. For example, if you wrote 10 bytes to the port at a time on the other end, in some cases you will receive the signal that will allow less data to be available at the monent, that is, before all the transmitted bytes arrives.

A: void MainWindow::serialReceived()
{
    QByteArray ba;
    ba = serial->readAll();
    ui->label->setText(serial->readAll());
    qDebug()<<ba;
}

You're first reading the data into ba, then you try to read again but since readAll() already read the data there is nothing left. You want
void MainWindow::serialReceived()
{
    QByteArray ba = serial->readAll();
    ui->label->setText(ba);
    qDebug() << ba;
}


text:
Q: Where should i store token on the client I have a slight problem understanding where i should store my token (client side). So it is sent every time i change page on the server.
     @Override
    public User getValue(HttpContext c) {
      // This is where the credentials are extracted from the request
      final String header = c.getRequest().getHeaderValue(CUSTOM_HEADER);
      try {
        if (header != null) {
          final Optional<User> result = authenticator.authenticate(new Credentials(header,"",""));
          if (result.isPresent()) {
            return result.get();
          }
        }
      } catch (AuthenticationException e) {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

      if (required) {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
      }

      System.out.println("NO TOKEN RETURNING NULL");

      return null;
    }
  }

This is how my authentication looks like in dropwizard. I need the token to be sent with the HttpContext.
So if i try to go into adress/securedpage. Then the HttpContext should have this token. So the server knows if the user is authorized to access or not
So after a successful login from the clientside. Where should i put the token that is received from the server?

A: You have many options. This is a good link to understand pros and cons
https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/

*

*Store it in local browser storage. As described in the previous link it has some risks.

*Store it in a cookie in client side, it can be safer than local browser storage.

*Don't store the token but store username and password in the browser or client-side cookie, and then retrieve a new token by sending credentials silently.

*Use a client side javascript library like https://github.com/IdentityModel/oidc-token-manager to rely on its token management features. By default it stores the retrieved token in localStorage (available throughout all the tabs) and it can be configured with silent_renew:true so that it automatically refreshes the token prior to its expiration using an iframe (without explicit browser redirection).


text:
Q: How does "knife ec2 server create"'s expansion of --run-list work? I'm unable to bootstrap my server because "knife ec2 server create" keeps expanding my runlist  to "roles".
knife ec2 server create \
    -V \
    --run-list 'role[pgs]' \
    --environment $1 \
    --image $AMI \
    --region $REGION \
    --flavor $PGS_INSTANCE_TYPE \
    --identity-file $SSH_KEY \
    --security-group-ids $PGS_SECURITY_GROUP \
    --subnet $PRIVATE_SUBNET \
    --ssh-user ubuntu \
    --server-connect-attribute private_ip_address \
    --availability-zone $AZ \
    --node-name pgs \
    --tags VPC=$VPC

Consistently fails because 'roles[pgs]' is expanded to 'roles'. Why is this? Is there some escaping or alternative method I can use?
I'm currently working around this by bootstrapping with an empty run-list and then overriding the runlist by running chef-client once the node is registered.

A: This is a feature of bash. [] is a wildcard expander. You should can escape the brackets using "\".


text:
Q: Trying to POST data with $resource in Angular I'm worried that I am just making a really stupid mistake, but I've been at this for a few hours to no avail.
I'm in the process of learning the MEAN stack, and I am making progress. Right now I am making a little fake TaskList CRUD app to get all the basics down, and so far I can GET no problem, but that's it.
My factory:
.factory('Tasks', function ($resource) {

    var tasks = $resource('tasks',{},{update:{method: 'POST', isArray:true}});
    return tasks;
}

My controller:
.controller('TasklistCtrl', function ($scope, Tasks) {

    $scope.taskList = Tasks.query();

    $scope.addTask = function(){

        $scope.taskList.push($scope.newTask);
        Tasks.update({}, $scope.newTask);

};

And my html is pretty straight forward for now

Fun Practice Task List!

{{ task.title }}

{{ task.task }}

<form>
    <input type="text" ng-model="newTask.title"/>
    <input type="text" ng-model="newTask.task"/>

{{ newTask }}

    <button type="submit" ng-click="addTask()" class="btn btn-default">Submit</button>
</form>

The backend has express working it's magic, tied to mongodb.
Right now a POST is being sent successfully, but it's just sending the original GET right back to the server. Originally I just had
Tasks.save(); instead of
Tasks.update({}, $scope.newTask);
But that didn't work either. I am pretty sure I'm just not understanding something fundamental, and I am going to go through reading more of the documentation/watching more tutorials/practicing - but hopefully someone can give me some advice in the meantime! Using Angular 1.2 btw.
edit:
So taking Zack's suggestion, my controller now looks like:
.controller('TasklistCtrl', function ($scope, Tasks) {

  $scope.taskList = Tasks.query();

  $scope.addTask = function(){

    Tasks.save($scope.newTask, function(data) {
      $scope.taskList.push(data);
    });

};

However, while I see successful posts being sent, on observation the post is just the exact same data I get from Tasks.query(). 'data' in the save callback is the same data, unchanged. Where am I going wrong here, why is scope.newTask not being sent back?

A: Try something like this:
Tasks.save($scope.newTask, function(data) {
    $scope.taskList.push(data);
});

In place of these two:
$scope.taskList.push($scope.newTask);
Tasks.update({}, $scope.newTask);


text:
Q: RestHeart-replicaset - The connection string contains an invalid option 'readPreference= I have RH 3.6 installed and I try to configure it to work with replicaset
but something is wrong because it doesn't work:
mongodb://user:password@ip:27017,ip:27017,ip:27017/?readPreference=primary&replicaSet=rsdigital&authSource=userManagement

Does anyone know what's wrong with the format?

A: You are setting the mongo-uri in the env properties file.
The mongo-uri variable in the yml configuration file is defined as {{mongo-uri}}. This way special chars (as the equal sign =) are escaped leading to the error.
Just define the variable as {{{mongo-uri}}} to fix it.
The conf file is being fixed (with triple {{{var}}} declarations) in upcoming RESTHeart version 3.6.3
More information on https://github.com/SoftInstigate/restheart/issues/327


text:
Q: C++ template with float arguments
Possible Duplicate:
C++: Why can't I use float value as a template parameter?

I have this class:
template<typename ValueType, ValueType DefaultValue>
class SomeClass
{
    public:
        SomeClass() : m_value(DefaultValue){}

        ValueType m_value;
};

I want to use it like this:
SomeClass<int, 1> intObj; //ok
SomeClass<float, 1.f> floatObj; //error: 'float' : illegal type for non-type template parameter 'DefaultValue'

Can you please explain me why I get this error when using float?
I want to use something similar to represent RGBA colors and to initialize the channels with default value for different color representations(White for example).

A: The language does not allow the use of floating-point types as non-type template arguments. For an extensive discussion, see Why can't I use float value as a template parameter?

A: § 14.1/7 (C++11 N3485) explicitly forbids this:

A non-type template-parameter shall not be declared to have floating point, class, or void type. [ Example:

template<double d> class X; // error
template<double* pd> class Y; // OK
template<double& rd> class Z; // OK

A: C++ doesn't support floating-point non-type template parameters unfortunately.

A: You get that error because non-type template parameters cannot be of type float. They may only be integrals, enumerations, member-pointers or addresses.

A: That's simple: nontype template parameters have to be compiletime constants of integral type or pointer type, i.e. bool, enums, pointers, pointer-to-members, long, int, short, char. Floating point parameters are not allowed in the current standard.


text:
Q: How to check a value and change other key in JSON with jq? [
    {
        "name": "user1",
        "status": "off"
    },
    {
        "name": "user2",
        "status": "off"
    },
    {
        "name": "user3",
        "status": "on"
    }
]

I want to know how I can search a JSON file recursively for the value of status, for example, off, and get all the name values for which the status is off.
Also, how can I change the value for user1 and user2 to on?
I am using jq and bash.

A: To apply an expression to all elements of an array, and get an altered array out, use map(expression).
Extracting all entries that have off status:
$ jq 'map(select(.status == "off"))' file
[
  {
    "name": "user1",
    "status": "off"
  },
  {
    "name": "user2",
    "status": "off"
  }
]

Mapping select(.status == "off") will alter the array by extracting (selecting) only the elements for which .status == "off" is true.
Extracting only the decoded names from the above:
$ jq -r 'map(select(.status == "off"))[].name' file
user1
user2

Tucking on [].name at the end of the previous expression will first expand the array into a set of individual entries (that's what [] does) and then extract the .name value from each of those.
You could also have used
jq -r 'map(select(.status == "off").name)[]' file

... which creates an array of names from which you then extract all elements.
Setting the status to on for all entries that have an off status:
$ jq 'map(select(.status == "off").status = "on")' file
[
  {
    "name": "user1",
    "status": "on"
  },
  {
    "name": "user2",
    "status": "on"
  },
  {
    "name": "user3",
    "status": "on"
  }
]

By mapping select(.status == "off").status = "on", we modify our array by setting the status to on for any element whose status is off.
Setting the status to on for entries based on explicit names:
$ jq 'map(select(.name == "user1" or .name == "user2").status = "on")' file
[
  {
    "name": "user1",
    "status": "on"
  },
  {
    "name": "user2",
    "status": "on"
  },
  {
    "name": "user3",
    "status": "on"
  }
]

The same thing, but don't hard-code the names inside the expression.  Rather, give them as a list at the end of the command line (note that --args and the list of names must be the last thing on the command line):
$ jq 'map(select(IN(.name; $ARGS.positional[])).status = "on")' file --args user1 user2
[
  {
    "name": "user1",
    "status": "on"
  },
  {
    "name": "user2",
    "status": "on"
  },
  {
    "name": "user3",
    "status": "on"
  }
]

The list of names given to --args is found in the array called $ARGS.positional.
The IN(a; b) thing returns true if a appears in the set b. We're using $ARGS.positional[] as the set to search, which is the set of the names given on the command line.  This means our select() here will extract only the elements whose names occur in the list on the command line, and these will have their status set to on.
Note that IN(a; b) differs from the similarly named in(a), which returns true if a given value occurs as a key or index in the object or array a.
Setting all entries' status to on:
$ jq 'map(.status = "on")' file
[
  {
    "name": "user1",
    "status": "on"
  },
  {
    "name": "user2",
    "status": "on"
  },
  {
    "name": "user3",
    "status": "on"
  }
]

Follow-up question in comments:

And If I want to match like NOT IN(a, b), then? Clearly, I am asking if I pass value like user1 and it turns off all other than user1. How can I do so?

The following uses an explicit if statement to change the status to on for the given names and to off for all others:
jq '
    map(
        if IN(.name; $ARGS.positional[]) then
            .status = "on"
        else
            .status = "off"
        end
    )' file --args user1

Or, in a one-line layout:
jq 'map(if IN(.name; $ARGS.positional[]) then .status = "on" else .status = "off" end)' file --args user1

If I instead interpret the follow-up as not wanting to change the status of the given names, no matter what their statuses are, but to change all other statuses to off. In that case, we can negate the condition used in a previous variation:
jq 'map(select(IN(.name; $ARGS.positional[]) | not).status = "off")' file --args user1

Note the added | not after IN(...; ...).
Of course, you could have used an if statement in most of the above variations too, but I like using select() when I'm able to.


text:
Q: How can I perform algebra such as apple + apple = 2 apple? Is its possible to define an algebra for string objects?
For example:

*

*apple + apple = 2 apple

*apple + orange = orange + apple

*apple + 3.5 apple = 4.5 apple

Are there built-in functions that could do that? Is the creation of a class structure necessary?

A: You could use SymPy to define symbolic variables for this type of algebra.
>>> from sympy import *
>>> apple = symbols('apple')
>>> orange = symbols('orange')
>>> apple + apple
2*apple
>>> apple + orange
apple + orange
>>> apple + 3.5 * apple
4.5*apple


text:
Q: Oracle : Update data How I can  Update data with these procedure parameters.
 1. p_id_book IN NUMBER;
 2. p_column_name VARCHAR2;
 3. p_value VARCAHR2;

If I try updating like this :
CREATE OR REPLACE PROCEDURE uptade_book(p_id_book IN NUMBER,
   p_column varchar2, p_value varchar2)
AS
  begin
    UPDATE book SET  p_column = p_value WHERE id_book = p_id_book;
  END;

These errors occur:

PL/SQL: SQL Statement ignored.
PL/SQL: ORA-00904: "p_column: invalid identifier.

Any ideas ?

A: i dont know your structure of book table, but what happen in your procedure that show to you in error :
PL/SQL: SQL Statement ignored : You tried to execute an invalid block of PLSQL code (like a stored procedure or function), but a compilation error occurred.
Oracle / PLSQL: ORA-06550 Error Message
PL/SQL: ORA-00904: "p_column: invalid identifier : You tried to execute a SQL statement that included an invalid column name or the column name is missing. This commonly occurs when you reference an invalid alias in a SELECT statement.
Oracle / PLSQL: ORA-00904 Error Message

A: You would need dynamic sql for such purposes. The update could be run in an EXECUTE IMMEDIATE. It is a good practice to use <column>%type for parameters referring to column names.
CREATE OR replace PROCEDURE update_book(p_id_book book.id_book%TYPE,
                                        p_column  VARCHAR2,
                                        p_value   VARCHAR2)
AS
BEGIN
    EXECUTE IMMEDIATE 'UPDATE book SET  '||p_column||' = :p_value
    WHERE id_book = :p_id_book'
    USING p_value, p_id_book;
END;

An important point to note here is that since p_value is defined as VARCHAR2, it will work fine if you pass strings or numbers. For date and timestamp types, you should take special care with respect to passing proper formats. esp. if you pass strings(instead of date), to avoid errors due to implicit conversion.


text:
Q: Plotting a graph with multiple columns I have a data set with 20 years in the first column (1990,1991,etc..) and each of the next 5 columns is a different state (CA,CO,PA,NY,TX). I am trying to create a plot with year along the x-axis, and the totals for each state along the y-axis, with each state being represented on the plot with a different color line.
I can do this fine using matplot:
matplot(population$Year,popAmount,type="l")

Where popAmount is a variable containing just the 5 state columns. Using the matplot code above, I can achieve what I am looking for.
I am wondering how to do this using plot() though, because whenever I try the same code using plot(), I receive this error:
Error in xy.coords(x, y, xlabel, ylabel, log) :
  'x' and 'y' lengths differ

My population$Year variable is just 20 years, and popAmount has data for each of those 20 years. Here is a snippet of my data:
Year    CA   CO   PA   NY   TX
1990    1234 1234 1234 1234 1234
1991    5678 5678 5678 5678 5678
1992    9876 9876 9876 9876 9876

Why am I able to successfully do this in matplot but not plot?


text:
Q: How to preserve group order in TestNG I have two classes that each implement something differently but the tests are the same for both. Each class does some things that would affect the other class if they run in parallel, so they can't run in parallel. (that's the rationale behind the code below)
If you run the class Both, see below, in Eclipse, as a TestNG test, one would expect it to run tests test1 and test2 of class ClassAAA first and then the same test methods for ClassBBB, because ClassBBB's group annotations specify that it depends on ClassAAA's annotation.
However, what you find out is that, seemingly, TestNG has a different way of looking at it, and, "seemingly",  it ignores the group order and runs the tests of the two clases in parallel.
class Both {

    @Test(groups={"base"})
    public static abstract class BothBase {

        @Test public void test1() { System.out.println("test1"+name()); }
        @Test public void test2() { System.out.println("test2"+name()); }

        protected String name() {
            String s = getClass().getName();
            s = s.substring( 1 + s.lastIndexOf("$"));
            return " - " + s;
        }
    }

    @Test(groups={"gr1"})
    public static class ClassAAA extends BothBase { }

    @Test(groups={"gr2"},dependsOnGroups={"gr1"})
    public static class ClassBBB extends BothBase { }
}

The output is:
test1 - ClassAAA
test1 - ClassBBB
test2 - ClassAAA
test2 - ClassBBB

One way, which i don't like, to try to "force" it to honor the desired group order, is to add a dummy test method to the leaf classes, as follows:
    @Test(groups={"gr1"})
    public static class ClassAAA extends BothBase {
        @Test public void dummyTestMustBeInAllLeavesToEnforceGroupOrder() {
            System.out.println("dummyTestMustBeInAllLeavesToEnforceGroupOrder"+name());
        }
    }

    @Test(groups={"gr2"},dependsOnGroups={"gr1"})
    public static class ClassBBB extends BothBase {
        @Test public void dummyTestMustBeInAllLeavesToEnforceGroupOrder() {
            System.out.println("dummyTestMustBeInAllLeavesToEnforceGroupOrder"+name());
        }
    }

This still doesn't completely do what one would expect. The output is:
test1 - ClassAAA
test2 - ClassAAA
test2 - ClassBBB
dummyTestMustBeInAllLeavesToEnforceGroupOrder - ClassAAA
test1 - ClassBBB
dummyTestMustBeInAllLeavesToEnforceGroupOrder - ClassBBB

This means that it started running the tests of ClassBBB before finishing the tests of ClassAAA.
I don't like the fact that i have to add a dummy/unrelated method to each, to get TestNG to understand that they cannot be run in parallel. In fact, i don't care which class runs first... And, i didn't really accomplish what i wanted because they are still running in parallel.
The stupidest way to do this, which would accomplish my goal is to move the tests from the base class to each of the leaf classes - is that how you are suppose to do these things in TestNG?
Is there another way of doing that? i'm sure someone is going to suggest priorities - but again, that does not convey the true intention - i don't have any priority - just don't want them to run in parallel. Also i don't want to write XML files...

A: This problem is coming due to static inner classes. Try below code you will get required output
import org.testng.annotations.Test;

    @Test(groups={"base"})
    public abstract  class BothBase {

        @Test public void test1() { System.out.println("test1"+name()); }
        @Test public void test2() { System.out.println("test2"+name()); }

        protected String name() {
            String s = getClass().getName();
            s = s.substring( 1 + s.lastIndexOf("$"));
            return " - " + s;
        }
    }

    @Test(groups={"gr1"})
      class ClassAAA extends BothBase { }

    @Test(groups={"gr2"},dependsOnGroups={"gr1"})
      class ClassBBB extends BothBase { }

A: Many ways
Simplest - priority
Bit harder( groups)
Check testng manual(for ex. this http://www.mkyong.com/tutorials/testng-tutorials/).


text:
Q: java.io.File.setReadable(false) has no effect inside docker The following code succeeds on Ubuntu 18.04 with OpenJDK 8, but fails inside the Docker image maven:3-jdk-8-slim which is based on OpenJDK 8:
String userHome = System.getProperty("user.home");
System.out.println(String.format("system property user.home: %s",
        userHome));
File file = new File(userHome, "file");
if(!file.createNewFile()) {
    throw new IOException("test arrangement failed");
}
if(!file.setReadable(false)) {
    throw new IOException("test arrangement failed");
}
assertFalse(file.canRead());

Failure details:
java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)
    at org.junit.Assert.assertFalse(Assert.java:64)
    at org.junit.Assert.assertFalse(Assert.java:74)
    at de.richtercloud.docker.java.file.readability.TheTest.testSomeMethod(TheTest.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

which refers to the assertFalse(file.canRead()) assertion. This assertion should pass because file.setReadable(false) returned true and thus succeeded.
I reproduced the issue in a SSCCE with the Docker-based GitLab CI, so that detailed output can be found at https://gitlab.com/krichter/docker-java-file-readability/-/jobs/203311757. The SSCCE does not contain more information than the above code excerpt, but makes local investigation easier.
I'm looking for an explanation, not a workaround.

A: I've seen similar results. Files.getPosixFilePermissions will return the expected values, but Files.isReadable and File canRead will return true when false is "expected"
Adding the userID to the docker command line fixes it for me. Possibly it;s the default user of root that's the issue

A: The documentation of File.canRead() contains a note that its result may be confusing:

public boolean canRead()
Tests whether the application can read the file denoted by this
  abstract pathname. On some platforms it may be possible to start the
  Java virtual machine with special privileges that allow it to read
  files that are marked as unreadable. Consequently this method may
  return true even though the file does not have read permissions.

Under docker processes usually run as root giving them privileges unseen by regular users.
Proof that root can read files lacking read permission:
$ echo abcd > somefile
$ ls -l somefile
-rw-rw-r-- 1 leon leon 5 Aug 26 21:43 somefile

$ cat somefile
abcd

$ chmod a-rw somefile
$ ls -l somefile
---------- 1 leon leon 5 Aug 26 21:43 somefile

$ cat somefile
cat: somefile: Permission denied

$ sudo cat somefile
abcd

A: I found a work arround for this issue.
In your docker, if it's possible with your linux image, you will have to create a non admin user, then 'su' with this user and launch all your commands you need as this user.
Here is an exemple that only work if you are not an admin or root user:
# useradd -m myUser
# su - myUser
$ pwd
/home/myUser
$ cat <<EOF > Test.java
> import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Test {
  public static void main(String[] args) throws IOException {
    Path tempDir = Files.createTempDirectory("Test");
    final File nonReadableFile = new File(tempDir.toFile(), "nonReadableFile.txt");
    System.out.println(nonReadableFile.getAbsolutePath());

    nonReadableFile.createNewFile();
    System.out.println(nonReadableFile.canRead());
    nonReadableFile.setReadable(false);
    System.out.println(nonReadableFile.canRead());
  }
}
> > > > > > > > > > > > > > > > > > > EOF
$ javac Test.java
$ java Test
/tmp/Test2125736191041151487/nonReadableFile.txt
true
false


text:
Q: SPF google mail + MY IP So this TEXT record response hardfail
XX.XX.XX.XX => my mail server
v=spf1 ip4:XX.XX.XX.XX include:aspmx.googlemail.com ~all

Question is how to create valid SPF record for sending e-mail

*

*for my server IP

*and using google mail servers, i thin problem is witch -all ~all

A: I used to work for a company that had Google as their main email provider and this is an example of the SPF record.
v=spf1 a mx ip4:X.X.X.X ip4:Y.Y.Y.Y include:_spf.google.com include:blackberryservers.domain.com -all

So we could definite additional static IPs that we want to relay through us as well as the Google servers. We also did a lot of Blackberry email so we had a dig command set up to pull the SPF servers for the Blackberry servers. From here we put them in a separate spf record and then included it on the main SPF record. If you don't trust the _spf.google.com you can create a similar dig script to show all of the IPs and then cron it and diff the results on an hourly or daily basis.
Below is a small part of that code. I haven't used this in a while but I believe the output should still be the same.
PREVIOUS=/home/user/google_ips
NEW=`dig txt _spf.google.com | grep _spf | grep -ve ";" | awk -F\" '{print $2}' | tr ' ' '\n' | sort`
if [ "$PREVIOUS" != "$NEW" ]; then
echo $NEW | nail -r your@email.com
fi


text:
Q: Java - How to open a file located in a jar file I'm using eclipse.  I put a .pdf file in my src folder, i want to open it with the default OS program. The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this :
File memo=new File("src/chap.pdf");
         try {
            Desktop.getDesktop().open(memo);
        } catch (IOException e) {
            e.printStackTrace();
        }

However, after exporting the project to a jar file, this isn't working anymore. So is there a problem in my code or is there another way to get the file to open when it's in the jar file ?

A: The src path will not be available after you have exported your program and you should never reference it in any way.
You need to extract the resource from the Jar file and write it to the local disk...
try (InputStream is = getClass().getResourceAsStrea("/chap.pdf")) {
    try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(...)) {
        // Write contents like you would any file
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

Then you can use the extracted file with Desktop


text:
Q: Read\write to a file: heavily used application I had asked a question here: The process cannot access the file because it is being used by another process: Correct way to read\write to a file: heavily used application-Part II.
We have a heavily used .Net 3.5 application that reads "expensive to create" data and caches it. However we are getting a lot of errors around both reading the cache file and writing to the cache file. I have a single process, multiple threads and I want the application to synchronize access to a resource. I was advised to use a simple locking mechanism like lock or ReaderWriterLockSlim (see: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx). This however seems to have made the problem much much worse in production.
EDIT
After the change was implemented, a lot of the cache files have a ">" tag in the end. Due to this the files are no longer xml files.
Can someone look at the code and advise what could I be doing wrong?
Code before change:
private XmlDocument ReadFromFile()
{
    XmlDocument result=null;
    string fileSystemPath=FileSystemPath();
    try
    {
        result=new XmlDocument();
        using (StreamReader streamReader = new StreamReader(fileSystemPath))
        {
            result.Load(streamReader);
        }
    }
    catch (FileNotFoundException)
    {
        result=null;
    }
    return result;
}

private object thisObject= new object();
private void WriteToFile(string siteID, XmlDocument stuff)
{
    string fileSystemPath=FileSystemPath();
    lock(thisObject)
    {
        using (StreamWriter streamWriter = new StreamWriter(fileSystemPath))
        {
            stuff.Save(streamWriter);
        }
    }
}

Code after change:
private readonly ReaderWriterLockSlim readerWriterLockSlim = new ReaderWriterLockSlim();
private XmlDocument ReadFromFile()
{
    XmlDocument result = null;
    var fileSystemPath = FileSystemPath();
    readerWriterLockSlim.EnterReadLock();
    try
    {
        result = new XmlDocument();
        using (var fileStream = new FileStream(fileSystemPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var streamReader = new StreamReader(fileStream))
        {
            result.Load(streamReader);
        }
    }
    catch (FileNotFoundException)
    {
        result = null;
    }
    finally
    {
        readerWriterLockSlim.ExitReadLock();
    }
    return result;
}

private void WriteToFile()
{
    var fileSystemPath = FileSystemPath();
    readerWriterLockSlim.EnterWriteLock();
    try
    {
        using (var fileStream = new FileStream(fileSystemPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
        using (var streamWriter = new StreamWriter(fileStream))
        {
            stuff.Save(streamWriter);
        }
    }
    finally
    {
        readerWriterLockSlim.ExitWriteLock();
    }
}

A: This code with some little changes should work
private readonly ReaderWriterLockSlim readerWriterLockSlim = new ReaderWriterLockSlim();
private XmlDocument ReadFromFile()
{
    XmlDocument result = null;
    var fileSystemPath = FileSystemPath();
    readerWriterLockSlim.EnterReadLock();
    try
    {
        result = new XmlDocument();
        using (var streamReader = new StreamReader(fileStream))
        {
            result.Load(streamReader);
        }
    }
    catch (FileNotFoundException)
    {
        result = null;
    }
    finally
    {
        readerWriterLockSlim.ExitReadLock();
    }
    return result;
}

private void WriteToFile(XmlDocument stuff)
{
    var fileSystemPath = FileSystemPath();
    readerWriterLockSlim.EnterWriteLock();
    try
    {
        using (var streamWriter = new StreamWriter(fileSystemPath))
        {
            stuff.Save(streamWriter);
        }
    }
    finally
    {
        readerWriterLockSlim.ExitWriteLock();
    }
}


text:
Q: Out-line for virtual method in C# I have an example of code in C#
using System;
class A
{
  public virtual void F() { Console.WriteLine("A.F"); }
}
class B: A
{
  public override void F() { Console.WriteLine("B.F"); }
}
class C: B
{
  new public virtual void F() { Console.WriteLine("C.F"); }
}
class D: C
{
   public override void F() { Console.WriteLine("D.F"); }
}
class Test
{
static void Main() {
  D d = new D();
  A a = d;
  B b = d;
  C c = d;
  a.F();
  b.F();
  c.F();
  d.F();
}
}

This code outline
B.F
B.F
D.F
D.F

I do not understand why in case a.F();
There is B.F ?
how MS said the virtual methods is represended by type of object in real time

A:
I do not understand why in case a.F(); There is B.F ?

MSDN #

When a virtual method is invoked, the run-time type of the object is
  checked for an overriding member. The overriding member in the most
  derived class is called, which might be the original member, if no
  derived class has overridden the member.

Bold content will explain to you why B.F  is printed when A.F() is called.

A: The call to method F() from your inherited class object prints B.F for the object of type D downcasted to type A, because you override the method in class B (and class D).
Your test is an almost exact copy of the example provided in this MSDN post on virtual methods:
using System;
class A
{
   public void F() { Console.WriteLine("A.F"); }
   public virtual void G() { Console.WriteLine("A.G"); }
}
class B: A
{
   new public void F() { Console.WriteLine("B.F"); }
   public override void G() { Console.WriteLine("B.G"); }
}
class Test
{
   static void Main() {
      B b = new B();
      A a = b;
      a.F();
      b.F();
      a.G();
      b.G();
   }
}

In the example, A introduces a non-virtual method F and a virtual
  method G. The class B introduces a new non-virtual method F, thus
  hiding the inherited F, and also overrides the inherited method G. The
  example produces the output:
A.F
  B.F
  B.G
  B.G
Notice that the statement
  a.G() invokes B.G, not A.G. This is because the run-time type of the
  instance (which is B), not the compile-time type of the instance
  (which is A), determines the actual method implementation to invoke.
  Because methods are allowed to hide inherited methods, it is possible
  for a class to contain several virtual methods with the same
  signature. This does not present an ambiguity problem, since all but
  the most derived method are hidden. In the example

A: In case of a.F() there is B.F because virtual void F in class A is override in B.
It is not override by C, because there is a new operator which does not override the virtual base method.
So if there is an instance of type D typed to A and you call F(), virtual method from the class A is called, but the latest override is taken into account. That is B.F.


text:
Q: Sending email directly using MailKit All the examples I've seen on using MimeKit/MailKit to send an email has the SMTP client logging into a SMTP server and sending the email through that server.  Is it possible to have MimeKit/MailKit send the email directly to the recipient?
In other words, if my app wishes to send an email to friend@hisdomain.com, is it possible to get the MailKit SMTP client to communicate directly to the SMTP server at hisdomain.com and send the email without having to go through my SMTP server?  Or, if I have an app programmed to send me the daily whatever, to send the email to my SMTP server without having to actually log into the SMTP server.

A: Sure, it's possible to get MailKit to connect directly to hisdomain.com to send an email, but you need to tell MailKit to connect to hisdomain.com's SMTP server/port.
To do that, you'll need to find a suitable DNS library and query the MX records for hisdomain.com to figure out what the mail server hostname/ip is and what port to connect to, etc.
Once you have that information, you can tell MailKit to connect directly to that SMTP server and send the message.


text:
Q: Disable swipe on some fragments in ViewPager I have a ViewPager that can disable or enable swipe touches:
public class ConfigurablePager extends ViewPager {

    private final AtomicBoolean touchesAllowed = new AtomicBoolean();

    ...

    private boolean touchesAllowed() {
        return touchesAllowed.get();
    }

    public void enableTouches() {
        touchesAllowed.set(true);
    }

    public void disableTouches() {
        touchesAllowed.set(false);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return touchesAllowed() && super.onTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return touchesAllowed() && super.onInterceptTouchEvent(ev);
    }
}

Some fragments can be swiped but other can't. Pager adapter aware of swipe behaviour for each fragment. This behaviour can be changed in ViewPager.OnPageChangeListener:
@Override
public void onPageSelected(int position) {
    if (adapter.isTouchesAllowed(position)) {
        views.pager.enableTouches();
    } else {
        views.pager.disableTouches();
    }
}

The problem

Sometimes, when I swipe fragments very fast and click on tab for other fragment simultaneously viewpager can throw IllegalArgumentException:

FATAL EXCEPTION:
  main java.lang.IllegalArgumentException: pointerIndex out of range
      at android.view.MotionEvent.nativeGetAxisValue(Native Method)
      at android.view.MotionEvent.getX(MotionEvent.java:1979)
      at android.support.v4.view.MotionEventCompatEclair.getX(MotionEventCompatEclair.java:32)
      at android.support.v4.view.MotionEventCompat$EclairMotionEventVersionImpl.getX(MotionEventCompat.java:110)
      at android.support.v4.view.MotionEventCompat.getX(MotionEventCompat.java:462)
      at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2080)
      at com.test.debugpager.ConfigurablePager.onTouchEvent(ConfigurablePager.java:39)
      at android.view.View.dispatchTouchEvent(View.java:7384)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2203)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1938)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2231)
      at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1952)
      at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2209)

It's happend because ViewPager save last pointerId and get inconsistent state (some touch events dropped by onInterceptTouchEvent) e.g. ACTION_MOVE with incorrect mActivePointerId from last touch event (see sources of ViewPager.java)
The question

Is it posible to disable swipe on some fragments in other way, maybe without overriding onInterceptTouchEvent?
ViewPager sources (onTouchEvent):
case MotionEvent.ACTION_MOVE:
    if (!mIsBeingDragged) {
        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        final float x = MotionEventCompat.getX(ev, pointerIndex);
        final float xDiff = Math.abs(x - mLastMotionX);
        final float y = MotionEventCompat.getY(ev, pointerIndex);
        final float yDiff = Math.abs(y - mLastMotionY);
        if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
        if (xDiff > mTouchSlop && xDiff > yDiff) {
            if (DEBUG) Log.v(TAG, "Starting drag!");
            mIsBeingDragged = true;
            requestParentDisallowInterceptTouchEvent(true);
            mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :
            mInitialMotionX - mTouchSlop;
            mLastMotionY = y;
            setScrollState(SCROLL_STATE_DRAGGING);
            setScrollingCacheEnabled(true);

            // Disallow Parent Intercept, just in case
            ViewParent parent = getParent();
            if (parent != null) {
                parent.requestDisallowInterceptTouchEvent(true);
            }
        }
    }

A: Solved
I've read intently android guide about gesture recognizing in a ViewGroup and analyzed ViewPager onTouchEvent sources. Here I recognize that ViewPager do swipe only for ACTION_MOVE event so we shouldn't call touch callbacks only for this action and we should obey base ViewGroup onInterceptTouchEvent result before calling base class onTouchEvent.

According to this rules I changed my ViewPager code:
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (touchesAllowed()) {
        return super.onInterceptTouchEvent(ev);
    } else {
        if (MotionEventCompat.getActionMasked(ev) == MotionEvent.ACTION_MOVE) {
            // ignore move action
        } else {
            if (super.onInterceptTouchEvent(ev)) {
                super.onTouchEvent(ev);
            }
        }
        return false;
    }
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (touchesAllowed()) {
        return super.onTouchEvent(ev);
    } else {
        return MotionEventCompat.getActionMasked(ev) != MotionEvent.ACTION_MOVE && super.onTouchEvent(ev);
    }
}


text:
Q: Input using scanner class in java I was making a program to reduce given integers to their simplest ratio.But an error is occurring while taking inputs through Scanner class in a sub-method of program.Here is the code :
package CodeMania;

import java.util.Scanner;

public class Question5
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    int T=sc.nextInt();// number of test cases
    sc.close();
    if(T<1)
    {
        System.out.println("Out of range");
        System.exit(0);
    }
    for(int i=0;i<T;i++)
    {
    ratio();//line 19
    }

}
static void ratio()
{
    Scanner sc1=new Scanner(System.in);
    int N=sc1.nextInt();//line 26
    if((N>500)||(N<1))
    {
        System.out.println("Out of range");
        System.exit(0);
    }
    int a[]=new int[N];
    for(int i=0;i<N;i++)
    {
        a[i]=sc1.nextInt();
    }
    int result = a[0];
   for(int i = 1; i < a.length; i++)
        {
    result = gcd(result, a[i]);
    }
    for(int i=0;i<N;i++)
    {
        System.out.print((a[i]/result)+" ");
    }
    sc1.close();
}
static int gcd(int a, int b)
{
    while (b > 0)
    {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
}

The error is--
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at CodeMania.Question5.ratio(Question5.java:26)
    at CodeMania.Question5.main(Question5.java:19)

Here I have used 2  seperate scanner objects sc in main function and sc1 in ratio function to take input from console.
However if I am declaring a public static type Scanner object in class scope and then using only one Scanner object throughout the program to take input then program is working as required without error.
Why this is happening...?

A: The reason for this error is that calling .close() on the scanner also closes the inputStream System.in, but instantiating a new Scanner will not re-open it.
You need to either pass a single Scanner around in your method parameters, or make it a static global variable.

A: Since your main() and your ratio() method are using Scanners they throw exceptions,when an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
 An exception can occur for many different reasons, below given are some scenarios where exception occurs.
A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

You can handle these exceptions by using Try/Catch blocks,or you can handle them by using the word throws after your method's definition,
in your case these two approaches are going to be like this:
With Try/Catch :
  public static void main()
  {
    try{
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();// number of test cases
        sc.close();
       }
    catch(NoSuchElementException e){
    System.out.print("Exception handled" + e);
    //rest of method
    }
    static void ratio(){
    try{
    Scanner sc1=new Scanner(System.in);
    int N=sc1.nextInt();}
    catch(NoSuchElementException e){
    System.out.print("Exception handled" + e);}
    //rest of method
    }

With "throws":
  public static void main()throws Exception{

       //rest of method
     }
   static void ratio()throws Exception
   {
    //rest of method
   }

A: Try this one. You can pass the scanner as argument
package stack.examples;

import java.util.Scanner;

public class Question5 {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();// number of test cases
    if (T < 1) {
        System.out.println("Out of range");
        System.exit(0);
    }
    for (int i = 0; i < T; i++) {
        ratio(sc);// line 19
    }
    sc.close();
}

static void ratio(Scanner sc1) {
    int N = sc1.nextInt();// line 26
    //Your Logic
}

static int gcd(int a, int b) {
    while (b > 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

}

A: import java.util.*;
public class Understanding_Scanner
{
public static void main()
{
Scanner sc= new Scanner(System.in);
System.out.println("Please enter your name");
String name=sc.next();
System.out.println("Your name is:"+name);
}
}

Now to explain this thing so we have to import a scanner class from the Java Utility package so this can be achieved by the code on the first line
the second line is creating a class NOTE (THE NAME OF THE CLASS NEED NOT START WITH CAPITAL) now coming to the main topic Scanner class so for this we must create a scanner class within the program with the code that's been given in the 4th line... in this statement 'sc' is an object which stores the values of the scanner class so if you want to do any operation in the scanner class you can do it via the object 'sc' *NOTE(You can name ur object as anything eg:poop,bla etc)...
then we have this interesting command which says System.in now this allows users to write any statement through the keyboard or any such input devices during run time....
String name=sc.next() this line helps us to write any string that we want to write during the run time, which will b stored in the name variable
So that's it, this is the scanner class for u. Hope its easy to understand.
cheers!! Keep coding :-)


text:
Q: Delete / backspace within dbaccess will not delete characters Using dbaccess via SSH into a fedora server.  When I go to Query - New, both backspace and delete do not have an effect.
How can I set up the environment to work with delete/backspace?  They work fine in vi.
Edit: Some more info.  CTRL-H in vi deletes the previous characer (same as backspace).  CTRL-H in dbaccess moves the cursor left one character but does not delete anything.

A: Finally found the solution!  I was using Putty, and the default settings under Terminal-Keyboard was Control-? (127) for backspace.  When I set this to Control-H, the cursor in DBAccess goes left one character.  It does not remove the character, but this is better than doing nothing at all.


text:
Q: How to upload a django file in memory to S3 I am trying to upload a fil to S3 without using a custom backend. This is what I have so far:
conn=boto.connect_s3(settings.AWS_KEY, settings.AWS_SECRET)
bucket=conn.get_bucket(settings.AWS_BUCKET)
k = Key(bucket)

filename = f.name
keyname = str(int(uuid.uuid4()))[:10] + filename
k.key = keyname
k.set_contents_from_filename(f)
url = "https://s3.amazonaws.com/.../" + keyname

And I get the following error:
TypeError at /qc/86/
coercing to Unicode: need string or buffer, InMemoryUploadedFile found

How would I correctly upload a file from request['FILES'] to s3 without using a custom storage backend?

A: I faced a similar issue a while back instead of using set_contents_from_filename(f) try k.set_contents_from_string(f.read())
I did the same thing in this project here: https://github.com/buddylindsey/developerrage/blob/master/developerrage/comic/views.py


text:
Q: Imagine (imagick) can't open pdf with page parameter I use Imagine in a Silex environment,
In a main objective to create thumbnails from PDF files, I choose the romainneutron/Imagine-Silex-Service-Provider to do this kind of PHP  ImageMagick conversion.
Everything is OK when I use the Imagick driver and when I open a pdf file without parameter :
bootstrap.php :
$app->register(new ImagineServiceProvider(), array('imagine.driver' => 'Imagick'));

aController.php :
 $path = "/path/to/file/";
 $filename = "aFileame";

 $image = $app['imagine']->open(dirname(dirname(__DIR__)).$path.$filename.".pdf")
                         ->resize(new Box(160, 240))
                         ->save(dirname(dirname(__DIR__)).$path."/thumb/".$fileName."_thumb@2x.png")
                         ->resize(new Box(80, 120))
                        ->save(dirname(dirname(__DIR__)).$path."/thumb/".$filename."_thumb.png");

But if I I try to just open the first page of the document ( .pdf[0] ) :
$image = $app['imagine']->open(dirname(dirname(__DIR__)).$path.$filename.".pdf[0]")

I have got an exception :
InvalidArgumentException in AbstractImagine.php line 67:
File /path/to/file/aFileame[0] does not exist.

Thanks for the help.
Julien


text:
Q: Is there a way to escape mystery room fights in Disgaea 5? So I've been playing Disgaea 5 for a while, got into the Item World, and after roughly 20 floors I found a mystery room (a bank robbery one). I talked twice to the NPC and I got stuck in a fight with level 3000+ foes. Lost my progress.
Is there a way to escape mystery room fights? Mr. Gency won't work either.

A: This one looks like it's either bugged, or intentionally very evil.
The exit portal is there, right under the cat, you just can't see it but it works as normal.
As far as I've seen, there are no actual trap rooms in this one.  You can always escape.
Furthermore, the bank girl is random.  You can safely talk to her between 1 and 4 times before she summons backup, each with more money rewarded.

A: You can punch the cat off the exit portal. Triple Strike, or Hurricane Blow both work. It will still be pushed off even if your attack does no damage or even misses.

A: Both of the previous answers are half-right, but Omega, the room you are talking about I have come across.  I did the same thing to end up finding myself fighting multiple level 9999 guardians at a low level.
This mystery room you cannot escape from.  It may be 1 of a few (or the only one) that you cannot escape from, because they are trap rooms.  Most rooms you can escape from by killing or knocking off the Slumber Cat from the exit portal and enter it.  The only other option is to finish the room, usually by clearing the room of everything except the slumber cat.
All you can do in the trap rooms is remember what happens in each room and avoid them, or grow strong enough to kill the NPCs next time that happens.  So far the only one I know of is the bank, and is only triggered if you talk to the NPC twice.

A: There's a way to get out the room. They hid the skip portal underneath the cat thing that takes you around the item world!
Even if portal was gone, if you hover over it the description was still there. I got on it like normal and escaped with my 1 million HL. I'm so happy I didn't lose all that damn work too!

A: You can escape in the bank robbery by pushing the cat away, the warp is invisible, but if you step on the cell you actually get out of the room, just did in , in this exact moment, because i had the same problem, and went looking for solutions XD So escape from that room confirmed, there is no need to make a video.

A: You can if you realize in bank robbery room the cat is not protected.  Kill him fast if you can if not attack him using range unit  to make him move. When he move send fresh unit from your gate to where he used to stand. And walla 11.110.000 + HL. at least those are the lowest amount from gate key tutorial bank robery room.
P. S.  You cant lift the cat so the only way to move him is fist move or agro him.


text:
Q: Efficient Least Squares for $ A = B X + C X D $ with the Minimization Argument $ X $ I am interested in solving a least-squares solution of the form
$$ \operatorname{argmin}_X \| A - BX - CXD \|_F^2 $$
for large (rank in hundreds to thousands)  matrices $A,B,C,D,X$
I know this is possible if I treat $X$ as a vector, but the Kronecker product $\operatorname{kron}(I,B)+\operatorname{kron}(D^T,C)$ is huge.
Is there an easier way?
I am initially interested in a Matlab solution, but one that I can migrate into c++.
edit...
So this looks is related to the  Sylvester Equation, but I cannot see how to map my problem to AX+XB=C, at least not without assumptions about the Spans of the matrices.

A: The problem is given by:
$$ \arg \min_{X} f \left( X \right) = \arg \min_{X} \left\| A - B X - C X D \right\|_{F}^{2} = \arg \min_{X} \left\| B X  + C X D - A \right\|_{F}^{2} $$
The derivative is given by:
$$ \frac{d}{d X} f \left( X \right) = 2 {B}^{T} \left( B X  + C X D - A \right) + 2 {C}^{T} \left( B X  + C X D - A \right) {D}^{T} $$
Now you can use Gradient Descent (I'm not sure what's the right way to solve the vanishing point of the gradient directly).


text:
Q: Better solution to copy IEnumerable to IList using reflection I have provided a dotnetfiddle to show the issue.
I try to copy object from a source that have the same property names and type except some  properties that have IEnumerable  and target object has
IList using reflection.
public T CopyTo<T>(object src)
        where T : new()
    {
        var targetObj = new T();
        //Getting Type of Src
        var sourceType = src.GetType();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty;
        var sourcePi = sourceType.GetProperties(flags);
        foreach (var property in sourcePi)
        {
            var pi = targetObj.GetType().GetProperty(property.Name);
            if (pi == null || !pi.CanWrite)
                continue;
            object sourceValue = property.GetValue(src, null);
            //var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);
            //this works, but hard wired
            if (sourceValue is IEnumerable<string> i)
                sourceValue = ((IEnumerable<string>)i).Cast<string>().ToList();
            pi.SetValue(targetObj, sourceValue, null);
        }

        return targetObj;
    }

It raises an error:

System.ArgumentException: 'Object of type 'System.String[]' cannot be
converted to type 'System.Collections.Generic.List`1[System.String]'.'

I tried to convert:
    var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);

but also get error
System.InvalidCastException: Object must implement IConvertible.
this issue can't help.
My workaround solution is casting :
    sourceValue = ((IEnumerable<string>) sourceValue).Cast<string>().ToList();

The disadvantage is hard wiring the cast to IEnumerable<string>
Is there a better way to copy  IEnumerable<T> to IList<T>  or any generic collection using reflection.

A: A simple approach would be to check if IEnumerable<T> is assignable from the source property's type, check if the destination property's type is assignable from List<T>, and if so then assign a new List<T> to the destination property passing the source property's value into the constructor.
public T CopyTo<T>(object src) where T : new()
{
    var targetObj = new T();
    var sourceType = src.GetType();
    BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty;
    var sourcePi = sourceType.GetProperties(flags);
    foreach (var property in sourcePi)
    {
        var pi = targetObj.GetType().GetProperty(property.Name);
        if (pi == null || !pi.CanWrite)
            continue;
        object sourceValue = property.GetValue(src, null);
        //var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);
        //this works, but hard wired
        if (property.PropertyType.IsGenericType)
        {
            Type enumerable = typeof(IEnumerable<>).MakeGenericType(property.PropertyType.GenericTypeArguments);
            if (enumerable.IsAssignableFrom(property.PropertyType))
            {
                Type list = typeof(List<>).MakeGenericType(property.PropertyType.GenericTypeArguments);
                if (pi.PropertyType.IsAssignableFrom(list))
                {
                    var pValue = Activator.CreateInstance(list, new[] { sourceValue });
                    pi.SetValue(targetObj, pValue, null);
                }
            }
        }
        else
        {
            pi.SetValue(targetObj, sourceValue, null);
        }
    }

    return targetObj;
}

It isn't hard to imagine situations where this wouldn't work... for example if the destination type's property is LinkedList<T> or T[] then the properties won't copy. You'd have to modify it further to handle cases like this.
This would also create a new List<T> for the destination object even if the properties on the two objects are both exactly the same type. It isn't clear if that is what you want or not, but it is different from how other properties are copied by this method so it is worth mentioning.

A: I think you need to add a check of the destination type too.
And then, With the two different type (source and destination),
You can create a function that will handle the conversion/cast.
Something like this:
1. Source IEnumerable<T>, Destination: List<T> => Create New list and put in CTOR

2. Source List<T>, Destination: List<T> => Just Copy

3. Source List<T>, Destination: IEnumerable<T> => Create a list

4. Source IEnumerable<T> ,Destination: IEnumerable<T> => Made a copy?


text:
Q: android: calculate double percentage? I want to calculate percentage. But it's giving me wrong result(2.78674E7).
Following's my code:
public class DetailActivity extends AppCompatActivity {

    private Button btn_pre_payment;
    private EditText et_pre_payment;

    private double monthlyPayment;
    private double allPayment = 139337000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        btn_pre_payment = (Button)findViewById(R.id.bt_prepayment);
        et_pre_payment = (EditText)findViewById(R.id.et_prepayment);

        btn_pre_payment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(et_pre_payment.getText().length() > 0){

                    float value = Float.valueOf(et_pre_payment.getText().toString());
                    if(value >= 10){

                        InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        in.hideSoftInputFromWindow(et_pre_payment.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

                            **monthlyPayment = (allPayment / 100f) * value;
                            tvMonthlyPaymentH.setText(String.valueOf(monthlyPayment));
                            remainderPayment -= monthlyPayment;**

                        }

                    } else Toast.makeText(DetailActivity.this, "Low is 10%!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(DetailActivity.this, "Enter value!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Why can't it calculate correct result? It gives me 2.78674E7. I want to calculate percentage.

A: For starters, your math is wrong.  It should be value/total*100, not value*total/100.

A: The value is given in scientific notation  you can try using
String.format("%.0f", YourValue)
to get correct value .
check out this question and this question


text:
Q: place results in a textbox after click i'm working on an auto complete with jquery which is working perfectly. the results get displayed as the user types. Now the problem is when the user starts typing and the results appear, when the user clicks on the desired results, it doesn't get placed in the textbox
JS
$(function(){
$(".search_tab").keyup(function()
{

var searchid = $(this).val();
var dataString = 'fname='+ searchid;
if(searchid!='')
{
    $.ajax({
    type: "POST",
    url: "http://localhost/myapp/search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    //console.log(html)
    $("#result").html(html).show();
    }
    });
}return false;
});

$('.search_tab').click(function(){
    jQuery("#result").fadeIn();
});
});

HTML
  <input type="text" class="search_tab" placeholder="Search" autocomplete="off">

A: You'll need to do some event delegation over the items that get placed into the div#result element. You'll want something like this:
$('#result').on('click', 'RESULT_ITEM', function (event) {
  $('input.search_tab').val(event.target.innerHTML);
});

Where RESULT_ITEM is a selector that matches the individual items that are listed in the autocomplete results.

A: While i dig into this have you considered using jQuery UI to acomplish this?
https://jqueryui.com/autocomplete/
This is a nice and polished way of doing exactly what you are wanting.
Not quite sure why I am getting down voted really as my suggestion is a perfectly valid solution to this problem...
That being said here is a working fiddle for you.
https://jsfiddle.net/wxr5y5gu/
The main part you seem to be missing is something like this:
$('#result').on('click','li',function(){
    /* I used li as the element as im unsure what your response html looks like */
    let newValue = $(this).text();
    $('.search_tab').val( newValue );
    $('#result').html('').hide();
});

That will clear the results, set the clicked value, and hide the results box for you.
That contains a working soution for you. As i dont have access to AJAX your local resources I had to extrapolate and create my own auto fill to show how it works in principal however i can certainly help you tailor the solution to your needs.
This solution uses your code and is compatible with all current jQuery versions.


text:
Q: How would kinetic bombardment look like on impact to an observer on Earth's surface? To be clear, I do want to know this because on the Worldbuilding Stack Exchange's chat room and on the Discord servers I am in, I have been told conflicting accounts about how such bombardment would look like to an observer.
Assumptions are as follows:
We have a 2 stage kinetic rod which is 20 meters long and 2 meters in diameter, with a first stage to deorbit from a 1,500 km altitude above the Earth's surface, accelerate to a terminal velocity of Mach 25 from an 80 km altitude using the remaining delta v from a fusion thermal rocket engine, which gives me ~11 kt of TNT equivalent on impact. From there, the engine stage separates and the main rod speeds towards its target.
The problem? How would that look like to an observer on the ground and what would happen on impact?
Bonus points if the observer is in a major metropolitan area of 1,000,000 or more inhabitants, just for good measure.
WARNING: I am unsure if this is the place for this kind of question. You have been warned.

A: The question is somewhat underconstrained because we do not know how streamlined the rod is. There will be supersonic shock heating of air. The naively calculated adiabatic stagnation temperature at Mach 25 is about 126 times ambient temperature (~300 K), 37,800 K. This model is obviously not right at this speed, so I think we are talking about temperatures merely around 3,000-6,000 K (this is the figure from actual meteorite impacts). Somewhat obviously the rod will be very bright on descent. However, were it streamlined enough the plasma will likely be more dispersed - it will not be so much a point but a long trail.
In any case, given the speed of about 8.5 km/s and an assumed 90 degree angle it will basically descend from the stratosphere within a second, becoming brighter as it approaches the ground.
The effect will be somewhat different from a normal meteorite impact since the impactor is elongated (and a bit higher density than a normal iron meteorite), but a rough estimate can be done using the formulas in the Earth impact effects program (graphical version). Basically it is a pretty tiny impactor: using their formula for crater size $D\approx 1.161 (\rho_i/\rho_t)^{1/3} L^{0.78} v_i^{0.44} g^{-0.22} \sin^{1/3}\theta$ with $\rho_i/\rho_t=6.9$, $L=7.8$ (i.e. converting the cylinder into a sphere), $v_i=8.5$ km/s, $g=9.82$ and $\theta=\pi/2$ gives $D\approx 356$ meters.
Since the impactor is elongated and hypersonic it will continue according to Newton's approximation of impact depth, $L\rho_i/\rho_t
 \approx 142$ meters.
So the actual effect will be a bright (color may range between red to actinic white depending on size and temperature of the plasma in front of it) line descending over a span of less than a second. It will penetrate the ground fairly deep, and there release its kinetic and thermal energy as a pretty powerful explosion. Since it is so fast and deep the thermal effects are negligible (in fact, there won't be a fireball since the speed is a bit too low): it will be all about a pressure wave, although there will presumably be a bit of a mushroom cloud afterward. The seismic effects will likely be bigger than the impact program predicts because more energy gets deposited deep, but the exact change is beyond me. Overall, the effects are going to be a major earthquake and likely a lot ejecta - like parts of buildings - flying through the region. The crater will likely be smaller and initially deeper than the above calculation since the penetration is deep, but will soon start to fill out as the rim avalanches in.
As a final note, from a military standpoint this might be a reasonable futuristic bunker-buster. But as a weapon of mass destruction against a city it is over-engineered compared to a vanilla fusion warhead. Also, if it was faster it would be far more damaging: the classic orbital kinetic missile really suffers from the limitations imposed by deorbiting.


text:
Q: Setting up the triple integral in spherical coordinates in a different order
Let D be the region bounded below by the plane $z=0$, above by the sphere $x^2+y^2+z^2 = 4$ and on the sides by the cylinder $x^2+y^2 = 1$
  Set up the triple integral in spherical coordinates that give the volume of D using the following order of integration:
  $\mathrm{d\phi d\rho d\theta}$

I am able to set the integral easily for the normal order of integration in spherical coordinates but am facing lot of trouble in setting the integral for the given order.
So could anyone help with it?
I tried with the range of $\phi$ as $[0,\pi/6]$ and then $[\pi/6,\pi/2]$, $\theta$ will obviously vary from 0 to $2\pi$ but I am not able to decide the limits of $\rho$ in either case.

A: The inequalities describing the region in spherical coordinates are
$$
0 \le \rho \le 2
,\quad
0 \le \rho \sin\phi \le 1
,\quad
0 \le \phi \le \pi/2
,\quad
0 \le \theta \le 2\pi
.
$$
When you're doing the $\rho$ integral first (innermost), what you call the "usual order", you rewrite the inequalities for $\rho$ and $\phi$ as
$$
0 \le \rho \le \min(2,1/\sin\phi)
,\qquad
0 \le \phi \le \pi/2
,
$$
and set up the bounds for the integrals accordingly (split into cases depending on whether $1/\sin\phi$ is less than or greater than 2), as in your comment above:
$$
\int_{\phi=0}^{\pi/6}
\int_{\rho=0}^2
+
\int_{\phi=\pi/6}^{\pi/2}
\int_{\rho=0}^{1/\sin\phi}
.
$$
To do the $\phi$ integral first instead, write the inequalities for $\rho$ and $\phi$ as
$$
0 \le \rho \le 2
,\quad
0 \le \sin\phi \le 1/\rho
,\quad
0 \le \phi \le \pi/2
.
$$
Here you split into cases depending on whether $1/\rho$ is less than or greater than 1 (since $\sin \phi \le 1$ automatically, which renders the middle inequality inactive if $1/\rho>1$). Like this:
$$
\int_{\rho=0}^1 \int_{\phi=0}^{\pi/2}
+
\int_{\rho=1}^2 \int_{\phi=0}^{\arcsin(1/\rho)}
.
$$
Geometrically, when you're doing the $\phi$ integral first, you are integrating over a circular arc in space (with a fixed radius $\rho$ and a fixed longitude $\theta$), starting on the $z$ axis, and stopping either when you hit the $xy$ plane or when you hit the cylinder (whichever happens first, and this depends on the value of $\rho$).


text:
Q: Android & Bundles what is the difference between: myBundle & the one returned by getArguments()
@Override
public void onCreate(Bundle myBundle) { //on create() belonging to a Fragment
    super.onCreate(myBundle);
    // So myBundle vs getArguments()
}

From my simple test they are not the same object, tested this with:
private void compareThem(Bundle myBundle, Bundle arguments) {
    Log.d("---myBundle==null: ", " " + (myBundle==null));
    Log.d("---arguments==null: ", " " + (arguments==null));

    if(myBundle!=null && arguments!=null) {
    Log.d("---myBundle==arguments: ", " " + (myBundle==arguments));
    Log.d("---myBundle.equals(arguments): ", " " + (myBundle.equals(arguments)));
    }
}

Sometimes I receive: false, true, false, false sometimes: false, false, false, false
Anyways.. ??

A: Bundle passed in onCreate() (myBundle in your code) is so called savedInstanceState. You can save some data ("state") from the fragment in the bundle in the method onSaveInstanceState() and later this bundle will be available in onCreate() and in some other methods.
Bundle returned by getArguments() method is the bundle passed from caller of the fragment. This bundle is provided via setArguments() method.


text:
Q: ColdFusion Rest API not working Previously I was running ColdFusion 10 configured with Apache on my localhost. I am using a different machine now and I am now using ColdFusion 11's built in web server. I have imported settings from an archived ".car" file. My app uses ColdFusion Rest services which were working on my previous machine. I have setup the rest service on this new machine and I am using the same service name but with a different absolute path to directory.
for example:
previous directory: - D:/foo/bar/api/v2
current directory: - C:/foo/bar/baz/api/v2
The rest service is registered and gets refreshed successfully in the ColdFusion Administrator. But when I try to access the API path on localhost, I get this 500 error :

This page isn't working
localhost is currently unable to handle this request.
HTTP ERROR 500
Application v2 could not be found. The specific sequence of files included or processed is: ''''


text:
Q: Actionscript 3 vs Haxe: Which to chose for new Flash project? I am in the planning stages of a new Flash game project and was wondering which language would be better to use? I already have a strong understanding of Actionscript 3, and have not worked with Haxe yet, but I have read the language reference docs and it seems that Haxe has some of the features from my other favorite languages, C# and Ruby.
So my question has two parts:
1) Can Haxe interop with flash components (swc files)? Like for instance if i use the Flash IDE to skin some controls, can i import those controls and use them in Haxe?
2) Are there any performance benefits to the Haxe compiler? or any gotchas?

A: You can find a lot of helpful stuff on lib.haxe.org ... (checkout haxelib for that matter (a bit like ruby gems, one could say)) ... there's also an AS3 to Haxe converter ... so could try translating relevant parts of the corelib to Haxe ... some manual fixing will be required though, i guess ...
when it comes to controls, just check out the Haxe gui libraries ... there's a couple of them floating around the web ...
Now Haxe pros:
a good thing about Haxe is, that the compiler is much faster, so you don't spend a lot of time compiling ... seriously, it makes a difference ...
Also, Haxe is a much richer language, as branden already implicitely stated ... I just wanna add, you should really check out enums ...
Still, the best thing about Haxe is, that when i comes to write a server, you can stay with the same language, plus things like Haxe remoting make your life super easy ...
There are some AS3 pros, but the thing is, that most of them are just related to the fact, that if you try solving problems in Haxe the way you would in AS3, the language seems quirky and shows unexpected behaviour at runtime ... if you stay strict and typed, everything turns out perfect ...
Hope that helps ... ;)
greetz
back2dos

A: New release of Haxe today. Adds official target of C++.
So now you can target ActionScript and C++ with the same source.

A: NME improves on Haxe's cross-platform support to provide a single API for Windows, Mac, Linux, Android, iOS, webOS, Flash and HTML5 applications without fuss.
The Haxe compiler is notably faster than MXMLC, especially if you are used to compiling from the Flash IDE, instead of an IDE that hosts the Flex compiler shell, like FlashDevelop. As mentioned, there are also a number of added language features, like iterators, typedefs, structs, macros and other nice-to-haves.
The great thing is that since you can always target Flash, there's little risk. The Haxe language is very similar, and if you don't mind supporting a single platform, you can target all of Flash's supported features. However, to the degree that you stick with NME's cross-platform API, you can experience huge performance and feature benefits for mobile and desktop platforms, or experiment with HTML5 support.
Lastly, there's a SWF library that makes it possible to access SWF content from C++. This has always been possible on the Flash target, of course, but soon it should be reasonable to be able to define an interface in the Flash IDE, and use this in mobile or desktop C++ applications as well as the Flash/AIR target.

A: 1) Yes, and no. As of 2.03 Haxe can export SWCs. This means you can write your code in Haxe , compile to a SWC and then utilize that SWC with Flash. Right now Haxe does not support SWC input, only output (though I believe they are working on this).
2) Yes, there are benefits to using Haxe - unlike Adobe's compilers Haxe actually does some optimizations during compilation (this has been a major bone of contention in the community for a while). In addition, Haxe utilizes some "hidden" new bytecodes that came into being with Flash Player 10 that currently neither Flash or Flex utilize - only Adobe's Alchemy (which cross-compiles from C/C++ source into SWCs).
The only "gotcha" that I know of is that it's kind of bizzaro ActionScript - things are just enough different that it will trip you up a fair amount. That being said, with features like generics and faster code that's small price to pay!

A: 1) You can include one swf library (instead of a swc) while compiling using the -swf-lib compiler argument and if you need more than one lib you can merge multiple using the swfmill tool. There's an example of this in the Haxe docs.
2) Branden answered this one perfectly :) Although I might add that one feature that does improve performance, in flash applications especially, is "inlining". Since Nicolas (the creator of Haxe) added even more byte code optimizations on inlined functions. And there's also even more of those optimizations planned.


text:
Q: Webgl FTP error Im having problems with a webgl build for unity that uses a ftp connection to store and load .xml files. Everything works fine in the editor and on a local ftp server (using Xlight). But when I build a webgl solution and try to save a .xml file I get the following error:
> Uncaught abort() at Error
    at jsStackTrace (http://localhost:8080/Development/WebGL.js:875:12)
    at stackTrace (http://localhost:8080/Development/WebGL.js:889:21)
    at abort (http://localhost:8080/Development/WebGL.js:3830852:24)
    at _pthread_create (http://localhost:8080/Development/WebGL.js:13183:2)
    at __ZN6il2cpp2os10ThreadImpl3RunEPFvPvES2_ [il2cpp::os::ThreadImpl::Run(undefined?F?*, void, void*)] (http://localhost:8080/Development/WebGL.js:3596270:50)
    at Array.__ZN6il2cpp2os6Thread3RunEPFvPvES2_ [il2cpp::os::Thread::Run(undefined?F?*, void, void*)] (http://localhost:8080/Development/WebGL.js:3746555:7)
    at Object.dynCall_iiii (http://localhost:8080/Development/WebGL.js:3807075:39)
    at invoke_iiii (http://localhost:8080/Development/WebGL.js:16008:32)
    at Array.__ZN6il2cpp6icalls8mscorlib6System9Threading6Thread15Thread_internalEP12Il2CppThreadP14Il2CppDelegate [il2cpp::icalls::mscorlib::System::Threading::Thread::Thread_internal(Il2CppDelegate?**)] (http://localhost:8080/Development/WebGL.js:2708698:6)
    at Object.dynCall_iii (http://localhost:8080/Development/WebGL.js:3813716:38)

I have absolutley no idea what this means or how to remotely fix this. My interests in server techs wasn't really at an all time high so some help on this matter would be greatly appreciated.
This is my xml upload code I'm currently using:
 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost/construct.xml");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential("name", "password");

    string xml = xmlDoc.OuterXml;
    byte[] bytes = Encoding.UTF8.GetBytes(xml);

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    response.Close();

If there is anything else I've left out than please let me know. Thanks in advance!

A: It is not possible to use WebRequest with Unity HTML5 exported projects, since WebRequest relies on threads. Unity's export to HTML5 option does not support threads (yet). The key part of the stack trace is this:
at _pthread_create (http://localhost:8080/Development/WebGL.js:13183:2)

None of the pthread API methods are implemented by emscripten. At some point in the future we may have thread support in JavaScript from various browsers, but it is not available now.
Note that this does work in the editor, even with the WebGL platform selected, because Unity is not limiting the .NET profile for the WebGL platform as it does for the Web player. We're looking at using profiles to provide earlier error information for platforms like WebGL, but we haven't implemented it yet.


text:
Q: Testing share Function across view I create a class "Helper.cshtml" in my App_Code folder that containt some Helper function in order to reuse somme logic accros different view.
Here is the code in my Helper.cshtml class:
@using System.Web.Mvc.Html
@using System.Web.Mvc

@functions
{
    public static bool DisplaySectionGestionnaireExterne(string individusParRole)
    {
        if (individusParRole != new RoleIndividuGestionnaireExterne().Code)
            return true;

        return (Model.IsInvestissementInterne || Model.IsInvestissementExterne || Model.IsInvestissementFondsExterne);
    }
}

Is there a way to unit test that function, without testing the entire view who use that function?

A: I think you should ask yourself if this logic belong to the view or not. A rule of thumb is that any logical operation with model data should be considered as business logic and remain outside the view. This way, you could unit test these conditions without problem inside a unit test.
Since it seems that it is a logic that takes an action on the view, I think you might want to have this code with a view model (if you are using view model approach). Your view model could be used by your view by only invoking the DisplaySectionGestionnaireExterne that would be the boolean you want to use in your view. The view remains clean and the logic elsewhere.
I know that I am not answering your question directly but testing views requires to have several other objects to be instantiated and add a lot of overwhelming mocking and codes.


text:
Q: Is it possible to have line chart with 'markers' for one data point in C# Charting? My objective is to plot a live Time vs Temperature (Line chart) from a device. In that I'm checking each temperature value with a logic to find out my appropriate temperature value.
After finding the appropriate temperature, how to highlight/mark that particular point only in my Line chart and continue reading my temperature?
livedataChart.Series.Add("Temperature");
livedataChart.Series["Temperature"].ChartType = SeriesChartType.Line;
for ()
    {
     Check(maintemperature);
     livedataChart.Series["Temperature"].Points.AddXY(time, maintemperature);
    }

private void Check(double temp)
    {
        if (somelogic with temp)
        {
            MessageBox.Show("Appropriate Temperature is calculated");
        }
    }

I have tried adding another series (Chart Type as Points) and gave the appropriate temperature in the point series. I got a point near to the Y-axis which is of no use. All i want is to have a point in the running Temperature Line graph.