text:
Q: Nodejs- Set body to Google cloud task queue I have a nodejs server in Google app engine where I want to delegate long running tasks to task queues using the Google Cloud Task queue.
Task queue not delivering request body but hitting the endpoint:
This is how I add task to task queue:

// Imports the Google Cloud Tasks library.
const cloudTasks = require('@google-cloud/tasks');

// Instantiates a client.
const client = new cloudTasks.CloudTasksClient();
const project = 'projectname';
const queue = 'queuename';
const location = 'us-central1';
const parent = client.queuePath(project, location, queue);

// Send create task request.
exports.sender = async function (options) {
// Construct the fully qualified queue name.
    let myMap = new Map();
    myMap.set("Content-Type", "application/json");
    const task = {
        appEngineHttpRequest: {
            httpMethod: 'POST',
            relativeUri: '/log_payload',
            headers: myMap,
            body: options/* Buffer.from(JSON.stringify(options)).toString('base64')*/
        },
    };

    /* if (options.payload !== undefined) {
         task.appEngineHttpRequest.body = Buffer.from(options.payload).toString(
           'base64'
         );
     }*/

    if (options.inSeconds !== undefined) {
        task.scheduleTime = {
            seconds: options.inSeconds + Date.now() / 1000,
        };
    }

    const request = {
        parent: parent,
        task: task,
    };
    client.createTask(request)
      .then(response => {
          const task = response[0].name;
          //console.log(`Created task ${task}`);
          return {'Response': String(response)}
      })
      .catch(err => {
          //console.error(`Error in createTask: ${err.message || err}`);
          return `Error in createTask: ${err.message || err}`;
      });
};

And this is the endpoint receiving:

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: String(JSON.stringify(JSON.stringify(req.body)))
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});

When the email is received, both the body is an empty Json objects.
What am I doing wrong?

A: Just to complement @Joan Grau's answer:
If you add this filter, you can assure that the result will be correctly parsed:
var bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

(idea taken from this post)
In particular, a good practice is to apply parser just to wherever you need it. And, besides that, consider to send to body content as a base64 string (this is required for cloud tasks in order to work). Rewriting your code with all these:
const task = {
        appEngineHttpRequest: {
            httpMethod: 'POST',
            relativeUri: '/log_payload',
            headers: myMap,
            body: Buffer.from(JSON.stringify(options)).toString('base64')
        },
    };

and the endpoint:
var bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use('/log_payload', bodyParser.json({ verify: rawBodySaver }));
app.use('/log_payload', bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use('/log_payload', bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: req.body //no need to parse here!
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});

A: Guided by this example, I believe the best way to parse the body from the request is to use the body-parser package.
You can implement this by changing your receiving endpoint file, by including the following:
const bodyParser = require('body-parser');

app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.text());

app.post('/log_payload', async (req, res) => {
    let mailOptions = {
        subject: 'Message Delivered',
        from: 'sender@example.com',
        to: "receiver@example.com",
        text: req.body
    };
    return await mailer.sendEmail(mailOptions).then(value => {
        return res.send(`Received task payload: ${value}`).end()
    }).catch(reason => {
        res.send(`Worker error: ${reason.message}`).end()
    });
});


text:
Q: Why does java reflection shows object method as instance's one, not static? Default java console application runs passed class with the main method that should be declared with static modifier.
So, I've tried to create such class as object instead of directly using static modifier. But surprisingly I got main method without static modifier.
$ scala
Welcome to Scala version 2.10.3-20130923-000000-e2fec6b28d (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_60).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import java.lang.reflect.Modifier
import java.lang.reflect.Modifier

scala> object Main {
     | def main(args : Array[String]) = println("hello")
     | }
defined module Main

scala> val method = Main.getClass.getMethod("main", classOf[Array[String]])
method: java.lang.reflect.Method = public void Main$.main(java.lang.String[])

scala> Modifier.isStatic( method.getModifiers )
res0: Boolean = false

So Main object contains main method that is not actually static.
I'd like to use java command for running scala classes rather that specific scala command.
How can I get static  main method out of scala object?

update:
It was suggested to search for a class with the same name except it does not have '$' symbol as suffix. So, I continued REPL session trying to find this class
scala> val loader = Main.getClass.getClassLoader
loader: ClassLoader = scala.tools.nsc.interpreter.IMain$TranslatingClassLoader@fdf3a48

scala> val mc = Class.forName("Main", true, loader)
java.lang.ClassNotFoundException: Main
    at scala.tools.nsc.interpreter.AbstractFileClassLoader.findClass(AbstractFileClassLoader.scala:69)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:734)
    at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:983)
    at scala.tools.nsc.interpreter.IMain.loadAndRunReq$1(IMain.scala:573)
    at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:604)
    at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:568)
    at scala.tools.nsc.interpreter.ILoop.reallyInterpret$1(ILoop.scala:756)
    at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:801)
    at scala.tools.nsc.interpreter.ILoop.reallyInterpret$1(ILoop.scala:774)
    at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:801)
    at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:713)
    at scala.tools.nsc.interpreter.ILoop.processLine$1(ILoop.scala:577)
    at scala.tools.nsc.interpreter.ILoop.innerLoop$1(ILoop.scala:584)
    at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:587)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:878)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:833)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:833)
    at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
    at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:833)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:83)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:96)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:105)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

I may suppose that I need to call special function from scala compiler utils to get wrapper for a defined class

solved:
I made more experiments and confirmed that scalac behavior differs from scala REPL. The first generates additional class for every object and that class have object's methods as static. If you create a class and his companion object than companion's methods would be added to the associated class without creating additional proxy. This works for any method, even those methods which signature differs from the main method signature

A: The Scala compiler does create a static main method:
$ cat Main.scala
object Main {
  def main(args: Array[String]) = println("hello")
}
$ scalac Main.scala
$ ls *class
Main.class  Main$.class
$ javap -cp . Main
Compiled from "Main.scala"
public final class Main {
  public static void main(java.lang.String[]);
}
$ javap -cp . Main$
Compiled from "Main.scala"
public final class Main$ {
  public static final Main$ MODULE$;
  public static {};
  public void main(java.lang.String[]);
}
$ java -cp /usr/local/scala/lib/scala-library.jar:. Main
hello

A: If you decompile this:
package test
import java.lang.reflect.Modifier
object Main {
  def main(args: Array[String]): Unit = {
    val method = Main.getClass.getMethod("main", classOf[Array[String]])
    println(Modifier.isStatic(method.getModifiers)) // false

    println(Main.getClass.getName()); // test.Main$

    val act = Class.forName("test.Main");
    val method2 = act.getMethod("main", classOf[Array[String]])
    println(Modifier.isStatic(method2.getModifiers)) // true !!!
  }
}

you will see two classes:
1)
public final class Main$
{
  ...
  public void main(String[] args)
  {
    ...
  }
  ...
}

2)
public final class Main
{
  public static void main(String[] paramArrayOfString)
  {
    ...
  }
}

A: I will remove this answer as soon as real one showups, but it's not that scala doesn't have static method, the problem is the [wrong?] use of java reflection for such inspection:
/tmp » echo 'object Main {  def main(args : Array[String]) = println("hello") }' > Main.scala
/tmp » scalac Main.scala
/tmp » javap Main
Compiled from "Main.scala"
public final class Main {
  public static void main(java.lang.String[]);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is $9<\sqrt{89}<10$? Explain why $9<\sqrt{89}<10$. How do you explain this? I'm doing revision and we haven't been taught it yet but it will be on the test.
$\sqrt{389}$ is also between two consecutive whole numbers.
What are the two numbers?

A: Hint: what's $9^2$, and what's $10^2$?

A: I got it, it's $19^2=361$ and $20 =400$ for the two  consecutive numbers on both sides of $\sqrt{389}$.

A: Imagine a triangle (with one corner90) (with one corner( not 90 degree) in (0,0)point )  and one edge=$\sqrt8$ then other edge=9(on HORIZONTAL  axis ) then if you imagine a CIRCLE  with center (0,0)and $r=\sqrt{89}$ you will see that length of SINEW  of triangle ($\sqrt{89}$)will be larger than length of edge=9.

A: Hints:
$$9^2=81<89<100=10^2\ldots$$
Of course, you may also want to show the square root function $\,f(x):=\sqrt x\,$ is monotone ascending, for example by means of its first derivative....

A: Hint:
You want to demonstrate -
$9<\sqrt{89}<10$
What happens when you square across these terms?
This can be done because, based on the suggested edit by Cameron Buie, each term can be squared for an equivalent chain of inequalities since $x↦x^2$ is a strictly increasing function on the positive reals.

A: Recall that the square root is monotonically increasing function so
$$81<89<100\Rightarrow\sqrt{81}=9< \sqrt{89}<10=\sqrt{100}$$

A: In addition to the excellent answers above, I'd like to add this picture. (My tikz-fu needs all the practice I can give it).

A: $f(x)=x^2$ is a strictly increasing function on the positive real numbers, meaning that $$a<b\Leftrightarrow f(a)<f(b) \hspace{30pt} \forall \hspace{5pt} 0\leq a,b\in\mathbb{R}.$$
That means that it suffices to notice that $$\color{darkblue}{9^2=81}<\color{darkred}{89}<\color{purple}{100=10^2}$$ which therefore implies that $$\color{darkblue}{9}<\color{darkred}{\sqrt{89}}<\color{purple}{10}.$$
Here is some visual intuition on why the algebra works. The thick blue represents the graph of the function $f(x)=x^2$.

A: $$\begin{align*}
9<\sqrt{89}<10&\Rightarrow \sqrt{9^2}<\sqrt{89}<\sqrt{10^2}\\\,\\&\Rightarrow\sqrt{81}<\sqrt{89}<\sqrt{100}\,\,\,\checkmark
\end{align*}$$


text:
Q: stack around array variable corrupted i am trying to pass my array through my assign and draw functions. the assign function only exists to take the wins array and assign a value of 0 for all of the elements in the array. my draw function fills the array with random numbers 1-100 with 20 numbers in the array. when i try to compile i end up with a runtime error stating that the stack around my variable (array) wins is corrupted. where should i go from here?
#include<iostream>
#include <ctime>

using std::cout; using std::cin; using std::endl;

void draw(int a[]);
void assign(int a[]);
int sizeofarray = 20;

int main() {
    int wins[20] = {};

    assign(wins);

    cout << "compiled!" << endl;

}

void assign(int a[20]) {

    a[20] = {};
    draw(a);

}

void  draw(int a[])

{
    srand(time(nullptr));
    int rannum = (1 + rand() % 100);

    for (int i = 0; i < 20; i++) {

        a[i] = 1 + rand() % 100;
    }

}

A: When you get an error with information as helpful as this, you should immediately be thinking "I have a buffer overflow".  Then go looking for it.
Sure enough, here it is:
void assign(int a[20]) {
    a[20] = {};            // <--- BOOM!
    draw(a);
}

Your array can only store 20 elements.  When you store something at the 21st element, you have undefined behavior.
Just adding some more information here.  It's possible that you thought the offending line would zero-initialize the entire array (like it does when defining the variable).  However, outside of an array definition, this is not the case.  a[20] = {} is an assignment.
If you wish to zero the array, use std::fill as follows:
std::fill(a, a+20, 0);

I should point out, however, that there's no point zeroing the array in the context of your code as written.  It's already zeroed on entry, and the draw function initializes every element anyway.


text:
Q: Any information on a Turbo Delphi 2009 release? Individually, the Turbo Delphi releases and the new improvements added in Delphi 2009 are two of the best things that have happened to Delphi in a long time.  But currently you can only get one or the other.  Does anyone know if Embarcadero has any plans to release a Turbo Delphi 2009?
I'm a paying customer with my own copy of D2009, but I'm trying to set up an open-source project that's going to use Generics quite a bit, and it would really help with getting other people on board if the language was available as a free download.

A: There's some info in this podcast. What we know now: Yes, there will probably be one. But it probably won't be as feature-rich as the last Turbo was.

A: It was mentioned in the closing keynote at CodeRage.  No official dates, but they said they definitely want have a Turbo level offering.


text:
Q: Click HTML element A and add Class on B with pure JavaScript I can't see what I'm doing wrong here.. Can anyone help please?
JavaScript:
function toggleMainNav() {
        var navLink = document.getElementsByClassName('nav_link')[0];
        var mainNav = navLink.nextSibling;
        if ( mainNav.className.match(/(?:^|\s)inactive(?!\S)/) ){
            mainNav.className = 'active';
        } else{
            mainNav.className = 'inactive';
        }
    }

    document.getElementsByClassName('nav_link')[0].addEventListener( 'click' , toggleMainNav );

this is the HTML:
☰ Menu

A: nextSibling will be a text node containing whitespace. Either scan until you get nodeType === 1 or use nextElementSibling (but check whether it's supported on your target browsers).

Side note: getElementsByClassName has worse support than querySelector / querySelectorAall (IE8 has the latter but not the former, for instance), so you might consider using those instead.
Side note 2: IE8 also doesn't have addEventListener.
Side note 3: If you hook up your handler via addEventListener, within the handler this will already be the first nav_link, so you don't have to look it up again.
Side note 4: Some older browsers will fail if you don't give the third argument to addEventListener (it didn't used to be optional). To be broadly-compatible, be sure to include the false at the end.


text:
Q: Javascript selected item value not pulling correctly I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"

What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=

I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
    console.log(selection);
    $('#right').empty();
    var addNewFields = 'these will be the fields';
    $('#right').append(addNewFields);
}

Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>

This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
        var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
            $('#userSelection').append(optionTag);

A: var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';

should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';

Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
    value: $(this).find('optionID').text(),
    html: $(this).find('optionName').text()
});

A: When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
    changeFn(this.options[this.selectedIndex].value);
};


text:
Q: How can I get Jupyter '%%cython' style performance highlighting in Pycharm? Jupyter Notebook has a neat feature where it'll highlight lines of Cython code that are causing slowdown due to coupling with Python. It'd be really neat to get that kind of functionality in Pycharm when writing Cython code as well.
Is there any way to do that?

A: It appears that the best way is to do this:

*

*Open a command prompt in the same directory as your .pyx source code

*Run cython --annotate yourcode.pyx

*Open yourcode.html to see the results.

There doesn't appear to be a Pycharm extension that integrates the highlighting in to the Pycharm code view itself.

A: As @hpaulj mentions, you can use the -a option with the cython magic
eg.
%%cython -a

# your cython code here


text:
Q: Help with simplifying this MySQL query I'm setting up a system that tracks daily challenges for a video game.  There are 4 daily challenges and one weekly challenge.  Each challenge gets saved to a table with an id, which can be reused it the challenge is ever reused (which they are, about 22% of the time).  I've got another table to store each day's challenges, it looks like this:
date | daily1 | daily2 | daily3 | daily4 | expiration
Since challenges are reused, I'd like to be able to look up other days on which a challenge was used, by its ID.  I'm using this query right now:
SELECT date FROM `current_daily`
  WHERE daily1 = #
    OR daily2 = #
    OR daily3 = #
    OR daily4 = #
  ORDER BY date ASC

It works, but it's so clunky.  I'm trying to find a better was to run this query so I don't need all the ORs, but since it's getting information from multiple columns, it doesn't look like I can use IN().  Is there another way I could simplify this query and still get the same information?

A: You could use an IN to clean this up, but don't expect any performance gains from doing so.
SELECT date
    FROM `current_daily`
    WHERE # IN (daily1, daily2, daily3, daily4)
    ORDER BY date ASC


text:
Q: Sequence who converges to $\sqrt{a}$ for every $a\geq0$
If we have: $$x_n=\left\lbrace \begin{matrix} b\in\mathbb{R}\setminus \{0\} & ,n=1 \\ \dfrac{a+x_{n-1}^2}{2x_{n-1}} & , n>1\end{matrix} \right.$$

Then, is easy to prove that  $(x_n)\to +\sqrt{a}$ if $b>0$, and $(x_n)\to -\sqrt{a}$ if $b<0$.
My question is: For $a\in\mathbb{R}^+$ there exists a sequence $(x_n^p)$ wich converges to $\sqrt[p]{a}$ for every $p\in\mathbb{N}$?

A: This is a special case of Newton–Rapheson: you look at
$$ x_n = x_{n-1} - \frac{f(x_{n-1})}{f'(x_{n-1})}, $$
with $f(x) = x^p-a$. Then the iteration simplifies to
$$ x_n = x_{n-1} - \frac{x_{n-1}^p-a}{px_{n-1}^{p-1}} = \frac{a+(p-1)x_{n-1}^p}{px_{n-1}^{p-1}} $$
Certainly if it does converge, you would have $x_n , x_{n-1} \to x $, so
$$ x = \frac{a+(p-1)x^p}{px^{p-1}} \\
px^{p} = a + (p-1)x^p, $$
so $x^p$ is a $p$th root of $a$. Further, it is easy to see that choosing $x_0>0$ makes every successive $x_n>0$, so it is the positive $p$th root.
Checking it converges is explained in the linked article, but it's likely that it works in exactly the same way as the $p=2$ case. Equally, you could look at
$$ x_n = \frac{a+(k-1)x_{n-1}^p}{kx_{n-1}^{p-1}} $$
for any $k \neq 0$, although you will probably find that $k=p$ is the best option.


text:
Q: javascript: get keys containing duplicate data in an associative array I have a javascript associative array. It will be populated dynamically.
I want to find the keys which will contain the duplicate data/values.
For simplicity, it will look like this.
var p =   { };
 p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3",
        "p4": "value2",
        "p5": "value3",
        "p6": "value5"
    };

How can i do this.
Here's the js fiddle.
jsfiddle
Is there other way than using hasOwnProperty?
Any ideas to make this work?

A: var p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3",
        "p4": "value2",
        "p5": "value3",
        "p6": "value5"
    };

var q = {};
var keys = Object.keys(p);
for (var i = 0; i < keys.length; i++) {
    var currentKey = keys[i];
    var newKey = p[currentKey];
    if (q[newKey] === undefined){
        q[newKey] = [];
    }
    q[newKey].push(currentKey);
}

This will get you an object looking something like:
{
  "value1": ["p1"],
  "value2": ["p2","p4"],
  "value3": ["p3","p5"],
  "value5": ["p6"]
}

A: Simplest way I can think of is to loop through your current object, and mark each value you see.  When you see a value again, mark that key.
var tmp = {};
for(var i in p){
    var val = p[i];

    // Have we seen this value before?
    if(!tmp.hasOwnProperty(val)){
        // Mark the value as seen for the first time
        tmp[val] = []; // 0 duplicates
    }
    else{
        // We've seen it before, save the duplicate key
        tmp[val].push(i);
    }
}

// Print out values and their duplicate keys
for(var i in tmp){
    var keys = tmp[i];

    // Are there any duplicates?
    if(keys.length){
        alert(i + ' has multiple keys: '+keys.join(', '));
    }
}

DEMO: http://jsfiddle.net/bjRDK/

A: A slightly tighter version of @RocketHazmat's solution:
var values = {},
    dupes = [],
    key,
    val;
for (key in p) {
    if (p.hasOwnProperty(key)) {
        val = p[key];
        if (values[val]) dupes.push(key);
        else values[val] = true;
    }
}

This just gives you a list of keys with dupes. (Note - the first instance of a dupe value isn't considered a dupe here.)


text:
Q: Searching shared libraries in Linux please explain me why on x86_64 Scientific Linux no file under /etc/ld.so.conf.d contains the directory /usr/lib64?
The list of directories to be searched by program loader is stored in the file /etc/ld.so.conf. On my distributive, this file stores this row: include ld.so.conf.d/.conf*
And the above directory consists of:
[root@dev_host build]$ ls -la /etc/ld.so.conf.d
total 36
drwxr-xr-x.   2 root root  4096 Aug 29 23:13 .
drwxr-xr-x. 103 root root 12288 Sep 18 03:41 ..
-rw-r--r--.   1 root root    17 Mar 20  2012 atlas-x86_64.conf
-r--r--r--.   1 root root   324 May  7 23:40 kernel-2.6.32-431.17.1.el6.x86_64.conf
-r--r--r--.   1 root root   324 Nov 22  2013 kernel-2.6.32-431.el6.x86_64.conf
-rw-r--r--.   1 root root    17 Feb 12  2014 mysql-x86_64.conf
lrwxrwxrwx    1 root root    31 Aug 11 14:46 postgresql-pgdg-libs.conf -> /etc/alternatives/pgsql-ld-conf
-rw-r--r--.   1 root root    22 Sep  7  2011 qt-x86_64.conf

I examined all these files - there is no /usr/lib64. Why? Is it stored in /etc/ld.so.cache?


text:
Q: Shell operators into python scripts I don't understand the following shell operators function.
    if [ $count -lt 2 ]
    then
        echo $CLASS $TC >> $WORKSPACE/testcasestoremove.txt
    fi

what exactly -lt doing here?
and
if [ $linesToRemove -gt 0 ]
then
cat $WORKSPACE/testcasestoremove.txt
exit 1
fi

what exactly -gt is doing here?
I did some research but I can not found anything related to that. Any help will be much appreciated.

A: They are 'less than' and 'greater than' comparison operators.
From the bash manual (man bash):

arg1 OP arg2
OP is one of -eq, -ne, -lt, -le, -gt, or -ge.  These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to  arg2,  respectively.  Arg1 and arg2 may be positive or negative integers.


text:
Q: Quasi-linear PDE $xu_x+yu_y=1$ with $u=y$ over unit circle I am given the following equation.

$xu_x+yu_y=1$ with the conditions $u(x,y)=y$ for all $x^2+y^2=1$

What I got so far.
I calculated the characteristics $x'(t)=x(t),x(0)=x_0\in S_1$ which are $x(t)=\exp(t)*xo$
$U(t)=u(x(t))$
Now I need to solve the equation $U' =1$ $\implies$ $U(t)=t+w_2$ where $w_2$ is the second component of $x_0$
How can I derive the solution $u(x,y)$ from that ?

A: Provided that, for any $t,s\in\mathbb{R}$,
$$
\frac{\rm d}{{\rm d}t}u(e^{t+s},e^t)=e^{t+s}\frac{\partial u}{\partial x}(e^{t+s},e^t)+e^t\frac{\partial u}{\partial y}(e^{t+s},e^t)=\left(x\frac{\partial u}{\partial x}+y\frac{\partial u}{\partial y}\right)(e^{t+s},e^t)=1,
$$
we have
$$
u(e^{t+s},e^t)=u(e^{t_0+s},e^{t_0})+\int_{t0}^t1{\rm d}t=u(e^{t_0+s},e^{t_0})+t-t_0.
$$
Further, when $t_0<0$, set $s=-t_0+\log\sqrt{1-e^{2t_0}}\in\mathbb{R}$. This yields, as per the given boundary condition,
$$
u(e^{t-t_0+\log\sqrt{1-e^{2t_0}}},e^t)=u(\sqrt{1-e^{2t_0}},e^{t_0})+t-t_0=e^{t_0}+t-t_0.
$$
Finally, thanks to the arbitrariness of $t$, set
\begin{align}
x&=e^{t-t_0+\log\sqrt{1-e^{2t_0}}}>0,\\
y&=e^t>0,
\end{align}
whose inverse reads
\begin{align}
t&=\log y\in\mathbb{R},\\
t_0&=-\frac{1}{2}\log\left[1+\left(\frac{x}{y}\right)^2\right]<0.
\end{align}
Thus when $x,y>0$, we have
$$
u(x,y)=\left[1+\left(\frac{x}{y}\right)^2\right]^{-1/2}+\log y+\frac{1}{2}\log\left[1+\left(\frac{x}{y}\right)^2\right]=\frac{y}{\sqrt{x^2+y^2}}+\log\sqrt{x^2+y^2}.
$$
Note that the above expression satisfies the boundary condition for not only the $x,y>0$ case, but all cases. Therefore, we conclude that
$$
u(x,y)=\frac{y}{\sqrt{x^2+y^2}}+\log\sqrt{x^2+y^2}
$$
for all $\left(x,y\right)\in\mathbb{R}^2\setminus\left\{\left(0,0\right)\right\}$.

A: Considering the change of variables
$$
\begin{array}{rcl}
x & = & r\cos\theta\\
y & = & r\sin\theta
\end{array}
$$
with
$$
\begin{array}{rcl}
dx & = & dr\cos\theta-r\sin\theta d\theta\\
dy & = & dr\sin\theta+r\cos\theta d\theta
\end{array}
$$
we have
$$
\begin{array}{rcl}
u_{x} & = & u_{r}\frac{dr}{dx}+u_{\theta}\frac{d\theta}{dx}\\
u_{y} & = & u_{r}\frac{dr}{dy}+u_{\theta}\frac{d\theta}{dy}
\end{array}
$$
Here $\frac{dx}{x}=\frac{dy}{y}\Rightarrow\frac{dy}{dx}=\frac{y}{x}=\tan\theta$
so we obtain
$$
xu_{x}+yu_{y}=1\Longleftrightarrow2ru_{r}=1\Rightarrow u(r,\theta)=\ln(\sqrt{r})+\Phi(\theta)
$$
Now with the boundary conditions
$$
u(1,\theta)=\sin\theta\Rightarrow\Phi(\theta)=\sin\theta
$$
and finally
$$
u(r,\theta)=\ln(\sqrt{r})+\sin\theta
$$
or in $(x,y)$ coordinates,
$$
u(x,y)=\frac{1}{2}\ln(x^{2}+y^{2})+\frac{y}{\sqrt{x^{2}+y^{2}}}
$$


text:
Q: Laplace transform of piecewise function and its derivative I have been given this piecewise function F(t) where
$$F(t)= \left\{
\begin{array}{ll}
      2t & 0\leq t \leq 1 \\
      t & t\gt 1 \\
\end{array}
\right. $$I have to find its Laplace transform and Laplace transform of its derivative and then show that it satisfies
$$L[F'(t)]=sf(s)-F(0) \to (A)$$ where $f(s)=L[F(t)]$.
I've tried this as follows: $$f(s)= \int_0^1(2t)e^{-st}dt \, +\int_1^{\infty} t e^{-st}dt\\=\frac {2}{s^2} -\frac{e^{-s}}{s^2} -\frac{e^{-s}}{s}$$
And  $$L[F'(t)]=\frac{2}{s}- \frac{e^{-s}}{s}$$
But it doesn't satisfy the relation (A).
I've also tried writing function F(t) in terms of Heaviside's unit step function as $$F(t) = 2t-tu(t-1)$$and using this Laplace transform is $$f(s)=\frac {2}{s^2} -\frac{e^{-s}}{s^2} $$ which satisfies the relation (A).
My question is that why not the other way? And why it satisfies relation (A) this way?
Is there any mistake or some concept involved? I don't know. Thank you in advance.


text:
Q: Error while executing save command in R Just for practice purpose i was trying to use save command in RStudio and it goes in the following way:
> n<-20

> r<-1:10

> w<-data.frame(n,r)
> n
[1] 20
> r
[1]  1  2  3  4  5  6  7  8  9 10
> w
    n  r
1  20  1
2  20  2
3  20  3
4  20  4
5  20  5
6  20  6
7  20  7
8  20  8
9  20  9
10 20 10
> save(n,r,w,file="data/multiple.rdata")

After executing the above save command i get the following error:
Error in gzfile(file, "wb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file 'data/multiple.rdata', probable reason 'No such
file or directory'

What should i do?


text:
Q: unresolved external symbol structs error LNK2001: unresolved external symbol "public: static int WrappedVector::_N" (?_N@WrappedVector@@2HA)
header.h
struct WrappedVector
{
    static int _N;
    double *_x;
};

main.cpp
const int WrappedVector::_N = 3;

i don't understand whats wrong

A: Just change the definition
 int WrappedVector::_N = 3; // Note no const

see LIVE DEMO1
or the declaration
 struct WrappedVector {
    static const int _N;
        // ^^^^^
    double *_x;
 };

see LIVE DEMO2
consistently.
If you need the latter form (static const int) you can also initialize it directly in the declaration:
 struct WrappedVector {
    static const int _N = 3;
                     // ^^^
    double *_x;
 };

see LIVE DEMO3


text:
Q: Let $X= \{ A \subset \mathbb{N} : \mathbb{N} \backslash A \text{ is finite}\}$. What is the cardinality of $X$? Prove it. Let $X= \{ A \subset \mathbb{N} : \mathbb{N} \backslash A \text{ is finite}\}$. What is the cardinality of $X$? Prove it.
For me the cardinality should be the same as the natural numbers. I am trying to show a way of ordering it, the first A is one with the smallest numbers and so on.

A: Hint: Note that $f(A)=\Bbb N\setminus A$ is a bijection from $X$ to $\text{Fin}(\Bbb N)=\{A\subseteq\Bbb N\mid A\text{ is finite}\}$.
(If you haven't seen that $\text{Fin}(\Bbb N)$ is countably infinite before, you can demonstrate an injection into $\Bbb N$ by mapping $\{a_1,\ldots,a_k\}$ to $p_{a_1}\times\cdots\times p_{a_k}$, where $p_i$ is the $i$-th prime number.)

A: $X$ can be placed into 1-1 correspondence with the finite subsets of $\mathbb{N}$.  This is countable, so $X$ is countable.

A: Hint:
1) There is one subset of the naturals without the number $\,1\,$ , also one subsets of the naturals without the number $\,2\,$ ...etc.
2) There is one subset without the numbers $\,1,2\,$ ,also one without $\,1,3\,$ ...
...................................
Thus, there are $\,\aleph_0\,$ subsets of the natural without one element since if $\,S^{(1)}\,$ is the subset of $\,\mathcal P(\Bbb N)\,$ containing all these subsets,  then if
$$S_k:=N-\{k\}\Longrightarrow S^{(1)}=\bigcup_{k=1}^\infty S_k$$
...and etc.


text:
Q: why doesn't Jquery work, when js does? i am learning Jquery and i can't figure out why none of the JQuery lines execute, while javascript lines do.
When I open it whith browser, the console shows"hello world" and "undefined". If i put these lines in the console, they are executed as expected.
here is my code :`
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title> cim </title>

 blah

 blah

blah

 asd

 asd

 asd

enter code here`

A: A few of issues

*

*You are including two versions of jQuery (no need for that)

*You cannot run code and link to an external file in one script element. So the code inside the first one will be ignored

*you immediately execute the func method and the DOM is not ready so all the elements are not found

*there is not :nth selector. Either :nth-child or :eq
What you need is

A: change $(document).ready(funk()) to this $(document).ready(function () {funk();});


text:
Q: How to handle login logout session and gcache in PHP? I use gcache to cache whole website pages to HTML and next i only read it and show to the user. It looks like this:
$enableCache = true;
if ($enableCache)
{
    include("gcache.php");
    $cache = new gCache;
    $cache->folder = "temp/";
    $id = join("", $_GET);
    $id = ereg_replace("[^A-Za-z0-9]", "", $id);
    $cache->contentId=$id;
    $cache->timeout = 5;
    /* its mean gCache cached the whole page */
    /* so, gcache, decide if he must response the compressed or */
    /* uncompressed cache*/
    $cache->isPage = true;
    if ($cache->Valid()) {
        echo $cache->content;
        die;
    }
    $cache->capture();
}

And works fine. Now i've added a link "login" in the header of the site. When person clicks it it redirects person to subpage where he/she provides creditencials, session parameter is set (before is session_start called):
  $_SESSION['theUser'] = $userId;
  header( "refresh:1;url=http://mysite.com");

And person is redirected to the mysite.com. But the problem is he / she sees the site got from cache. So in upper right corner there is "log in" again, but i set that when $_SESSION['theUser'] is set it should show it and provide a link to log out. But it does not display because it returns to user the unlogged in version of website.
How to fix this?

A: I assume, that the reason of using cache in this way is to minimize server load and response times. But this can be achieved by more simple way not using third-parity plugins/classes/stuff:
<?php
    global $cachefile;
    //encode cache file name with sha1
    $cachefilename = sha1($_SERVER['REQUEST_URI']);
    //remove trailing slash
    $cachefile = rtrim(sys_get_temp_dir (),'\\/').DIRECTORY_SEPARATOR.$cachefilename.'.cache';
     // How long to keep cache file?
    $cachetime = 60*5;    //5min
    // Is cache file still fresh? If so, serve it.
    if (file_exists($cachefile) && filesize($cachefile)>100 && time() - $cachetime < filemtime($cachefile)  )  {
      readfile($cachefile);
      exit;
    }

    function cacheOutputtoFile()   {
     global $cachefile;
     $webpage = ob_get_contents();
     if ($fp = fopen($cachefile, 'w+'))
        {
            // Do an exclusive lock
            if (flock($fp, LOCK_EX))
            {
               // Truncate file
               ftruncate($fp, 0);
               fwrite($fp, $webpage);
               fclose($fp);
            }
        }
    }

    ob_start();
    register_shutdown_function("cacheOutputtoFile");

Note: You must use register_shutdown_function() instead of using cacheOutputtoFile()
as parameter of ob_start() as socket is already closed when callback function is called, then the client not get the echo $webpage output.
Usage: Put this file in your root server folder (or wherever you want) and require it one on top of every page you want to cache.
require_once("cacheable.php");


text:
Q: How to remove special characters from name excluding salutation (Mister, Ms., Mrs., Doctor )? I want to remove special characters form name excluding salutation part and Need to separate the first , last name and salutation.
Create table Employee_Name(Emp_Name varchar(20))
insert into  Employee_Name values('Dr. Sana .Singh');
insert into  Employee_Name values('Mrs. Ashley;');
insert into  Employee_Name values('Mr. Simon-');
insert into  Employee_Name values('Ms. Ale Martin galyx');
insert into  Employee_Name values('Doctor. Blank Smith&');

I need output to be

     Emp_Name            Salutation   First_Name    Last_Name
 Dr. Sana Singh              Dr.          Sana        Singh
 Mrs. Ashley                 Mrs.         Ashley
 Mr. Simon                   Mr.          Simon
 Ms. Ale Martin              Ms.          Ale         Martin
 Doctor. Blank Smith         Doctor.      Blank       Smith

Thanks in advance

A: Splitting names can be a slippery slope.  However, if you are looking for the first 3 strings, consider the following.  Easy to expand, I'm sure you can see the pattern 1,2,3,...  (I don't have much imagination)
Select A.Emp_Name
      ,Salutation = IsNull(B.Pos1,'')
      ,First_Name = IsNull(B.Pos2,'')
      ,Last_Name  = IsNull(B.Pos3,'')
 From  @Employee_Name A
 Cross Apply (
              Select Pos1 = xDim.value('/x[1]','varchar(max)')
                    ,Pos2 = xDim.value('/x[2]','varchar(max)')
                    ,Pos3 = xDim.value('/x[3]','varchar(max)')
              From (Select Cast('<x>' + Replace([dbo].[udf-Str-Strip-Non-Alphanumeric](A.Emp_Name),' ','</x><x>')+'</x>' as XML) as xDim) A
             ) B

Returns
Emp_Name                Salutation  First_Name  Last_Name
Dr. Sana .Singh         Dr          Sana        Singh
Mrs. Ashley;            Mrs         Ashley
Mr. Simon-              Mr          Simon
Ms. Ale Martin galyx    Ms          Ale         Martin
Doctor. Blank Smith&    Doctor      Blank       Smith

Now, stripping the the non-ALPHA characters would require a UDF
CREATE FUNCTION [dbo].[udf-Str-Strip-Non-Alphanumeric](@S varchar(max))
Returns varchar(max)
Begin
    Declare @RetVal varchar(max) = ''
    ;with  cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N) As (Select Top (IsNull(DataLength(@S),0)) Row_Number() over (Order By (Select NULL)) From cte1 a,cte1 b,cte1 c,cte1 d)
    Select @RetVal = @RetVal + Substring(@S,N,1)
     From  cte2
     Where Substring(@S,N,1) Like '[a-z,A-Z,0-9, ]'
    Return Replace(@RetVal,'  ',' ')
End
--Select [dbo].[udf-Str-Strip-Non-Alphanumeric]('some & text. /+= a  and zip 02806')  --Returns: some  text  a  and zip 02806

A: Try this solution, hope this helps you.
  SELECT
  Emp_Name
 ,  Reverse(ParseName(Replace(Reverse(Emp_Name), '', ''), 1)) As [Salutation]
 , Reverse(ParseName(Replace(Reverse(Emp_Name), '', ''), 2)) As [First_Name]
 , Reverse(ParseName(Replace(Reverse(Emp_Name), '', ''), 3)) As [Last_Name]

  FROM  (Select Emp_Name from Employee_Name
  ) As [x]

Output:

Do edit if you need any improvement.

A: Try as follows:
DECLARE @EMP TABLE (ID INT IDENTITY(1,1),EMP_NAME VARCHAR(100),SALUTATION VARCHAR(100),FIRST_NAME VARCHAR(100),LAST_NAME VARCHAR(100),COMMON VARCHAR(100))
DECLARE @NAME VARCHAR(100),@ID INT
INSERT INTO @EMP (EMP_NAME,SALUTATION,COMMON) SELECT EMP_NAME,SUBSTRING(EMP_NAME,0,CHARINDEX(' ',EMP_NAME)+1),REPLACE(EMP_NAME,(SUBSTRING(EMP_NAME,0,CHARINDEX(' ',EMP_NAME)+1)),'') FROM EMPLOYEE_NAME

DECLARE C CURSOR FOR
SELECT COMMON,ID FROM @EMP
OPEN C
FETCH NEXT FROM C INTO @NAME,@ID
WHILE @@FETCH_STATUS=0
BEGIN
IF(CHARINDEX(' ',@NAME))>0
BEGIN
UPDATE @EMP SET FIRST_NAME=(SELECT SUBSTRING(@NAME,0,CHARINDEX(' ',@NAME)+1)) WHERE ID=@ID
UPDATE @EMP SET LAST_NAME=(REPLACE(@NAME,(SUBSTRING(@NAME,0,CHARINDEX(' ',@NAME)+1)),'')) WHERE ID=@ID
IF(CHARINDEX(' ',(SELECT LAST_NAME FROM @EMP WHERE ID=@ID)))>0
BEGIN
    UPDATE @EMP SET LAST_NAME=(SELECT SUBSTRING(LAST_NAME,0,CHARINDEX(' ',LAST_NAME)+1) FROM @EMP WHERE ID=@ID) WHERE ID=@ID
    END
END
ELSE
BEGIN
UPDATE @EMP SET FIRST_NAME=@NAME WHERE ID=@ID
END
FETCH NEXT FROM C INTO @NAME,@ID
END
CLOSE C
DEALLOCATE C
SELECT EMP_NAME,SALUTATION,FIRST_NAME,LAST_NAME FROM @EMP


text:
Q: Can I use XText for a DSL involving an XML file type? I have defined a small DSL that is mostly written in the form of different types of XML files in conjuction with some property files. This works very well but I wish to create an Eclipse Editor to make editing these files easier for beginners (I already have a working parser).
The main XML file can reference some items from the .properties files and vice-versa. THe main xml file can also reference other XML files. Certain options should only be available in the main xml file based on the contents of the .properties files and based on some osgi plugins that can be added to the DSL project (the syntax is dynamic depending on context). The structure of the language is fixed but the options available in each attribute or the choice of attributes themselves changes depending on metadata contained in plugin .jar files.
Questions:
Does XText support dynamic syntax (validation changes depending on external factors)?
Does XText support XML files / .properties files?
Thank you very much for your help in advance.

A: Please read the Xtext documentation.

Does XText support dynamic syntax (validation changes depending on external factors)?

Xtext automatically validates the syntax using the grammar definition. Additionally, you can write arbitrary validations in Java or Check.

Does XText support XML files / .properties files?

If you define a grammar for them, of course. ;) Neither of them are too difficult.

A: I don't completely understand what you are after, but if you have an XSD, have you considering turning that into an Ecore model, and then building a Xtext grammar for that?  Or if you are starting from scratch, build your DSL Grammar first, then export the ecore as XSD, and use helpers like I've just posted in my http://blog2.vorburger.ch/2012/07/xtext-xml.html ? HTH.

A: If you don't have to have XML / XSD, and what you are after in essence really is more having a readable (say JSON-like, but strongly typed?) "generic" DSL for data structures constrained by some sort of "meta model" (say expressed in XCore, which is a DSL for an EMF Ecore model, which you can import from a XSD..), then maybe my EMF Simple Object Notation ESON (ex-EFactory) at https://github.com/vorburger/efactory is of interest to you?


text: Q: How to Differentiate mobile data used among the sims in a dual sim? I'm trying to measure mobile data used by different SIM cards in a multi SIM phone. Is there any way where I could programmatically get the data? Or Is there at least a way in which I could know on which SIM mobile data is turned on?


text:
Q: Responsive hero BG image with  on top I'm trying to create a responsive, full-page width hero img/banner, with some text on top.
Because I want a div on top of the img/banner, containing some text, I've chosen to use the CSS background-image property (rather than an HTML <img> element) for the image (I'm trying to avoid using position: absolute if possible).
After a lot of messing about, I seem to have found a great solution to get the background-image property to behave just like an HTML <img> element (which is exactly how I want the img to behave when resized)...
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bg-img {
  background-image: url('https://www.bbva.com/wp-content/uploads/2016/12/Carl-Sagan-BBVA-1920x0-c-f.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  width: 100%;
  padding-top: 40.57%;
  /* (img-height / img-width * width) */
  /* (779 / 1920 * 100) */
}

...however, this 'roundabout' solution to get the image to behave, calls upon padding to increase the height of the bg-image container, which forces the <div> containing my text content off of the image and further down the page :(
Is there any way to resolve this without using absolute positioning on the text div to get it to sit over-top of the bg-img?
I put everything into a pen to make it easier to play with:
https://codepen.io/Hacktinium/pen/VwWRBdg
Thanks in advance

A: Not sure if understood 100% your desired outcome, if you want the text to be at the top of the image without using an <img> tag, why don't put the content, and the image inside a wrapper but in different divs?
I've created this pen as an example:
https://codepen.io/mvuljevas-the-selector/pen/zYzbJgO


text:
Q: ggmap with Gauss Krueger coordinates I am using R for doing a map of groundwater levels which means I have some measurements at some coordinates in the Gauss-Krueger system and I interpolated between these measurements.
I want to plot this interpolated distribution map on top of a satellite image of that area. Using ggmap, I can only retrieve the map for the corresponding Lon-Lat coordinates, but I actually would like to plot the whole thing in the GK system. Is it possible to do this, or alternatively, convert the axes of the satellite map somehow? I thought about converting the GK coordinates to Lon-Lat, but I am not sure about the accuracy of that, since the area of interest is pretty small, maybe 300x300 meters.


text:
Q: OfficeWebApp turn off I'm trying to disabe OfficeWEbApp in SP10 farm.
Already did:
1) Disable with powershell.
2) Edit Xml.
Source (https://blogs.msdn.microsoft.com/opal/2011/02/10/uninstall-or-disable-office-web-apps/)
Still, some users are complaining that documents are opening in officeapp.

A: Reference Link :http://www.sharepointdiary.com/2014/08/disable-office-web-apps-enable-open-in-client-sharepoint.html
You need to remove WOPI bindings for the filetypes the users are still getting errors for firstly .
Secondly Change the Open in Client behavior for the sites the users are complaining by deactivating the feature needed .
If you run into issues deactivating it you refer the technet below:
https://docs.microsoft.com/en-us/previous-versions/office/office-2010/ee837418(v=office.14)#bkmk_deactiv_single


text:
Q: Having issues addressing inheritance in C# I'm having some trouble understanding how to implement inheritance.
My model is purely for demonstration's sake, but here we go:
I have a Parent Class Bus. It has two children DieselBus and ElectricBus. These are abstract classes.
I have a further two classes Coach and CityBus. How do I set those up to inherit from either DieselBus OR ElectricBus without having to define separate Coach and CityBus classes like CoachDieselBus, CoachElectricBus, CityBusDieselBus and CityBusElectricBus ? Is that even feasible/possible?
I don't have examples short of just some skeletons so far, looking for advice on this point.
What I am looking for is this:

As opposed to this:

Thanks!
EDIT (2013-07-03):
First, some code:
Bus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InheritanceTest {
    abstract class Bus {
        public Bus () {

        }

        public abstract Engine EngineType {
            get;
            set;
        }

        private int id;
        public int ID {
            get {
                return id;
            }
            set {
                id = value;
            }
        }

        private int seats;
        public int Seats {
            get {
                return seats;
            }
            set {
                seats = value;
            }
        }

        private float length;
        public float Length {
            get {
                return length;
            }
            set {
                length = value;
            }
        }

        private String colour;
        public String Colour {
            get {
                return colour;
            }
            set {
                colour = value;
            }
        }
    }
}

Coach.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InheritanceTest {
    class Coach : Bus {
        public Coach (int id, int seats, float length, String colour, String company, Engine engine) {
            this.ID = id;
            this.Seats = seats;
            this.Length = length;
            this.Colour = colour;
            this.EngineType = engine;
            this.company = company;
        }

        public override Engine EngineType {
            get;
            set;
        }

        private String company;
        public String Company {
            get {
                return company;
            }
            set {
                company = value;
            }
        }

        public override string ToString () {
            return (this.ID + "\t" + this.Seats + "\t" + this.Length + "\t" + this.Colour + "\t" + this.Company + "\t" + this.EngineType.ToString ());
        }
    }
}

Engine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InheritanceTest {
    abstract class Engine {
        public Engine () {

        }

        private float power;
        public float Power {
            get {
                return power;
            }
            set {
                power = value;
            }
        }

        private float torque;
        public float Torque {
            get {
                return torque;
            }
            set {
                torque = value;
            }
        }

        private int redline;
        public int Redline {
            get {
                return redline;
            }
            set {
                redline = value;
            }
        }
    }
}

DieselEngine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InheritanceTest {
    class DieselEngine : Engine {
        public DieselEngine (float power, float torque, int redline, float displacement, float fuelEconomy) {
            this.Power = power;
            this.Torque = torque;
            this.Redline = redline;
            this.displacement = displacement;
            this.fuelEconomy = fuelEconomy;
        }

        private float displacement;
        public float Displacement {
            get {
                return displacement;
            }
            set {
                displacement = value;
            }
        }

        private float fuelEconomy;
        public float FuelEconomy {
            get {
                return fuelEconomy;
            }
            set {
                fuelEconomy = value;
            }
        }

        public override string ToString () {
            return "Diesel Engine";
        }
    }
}

I'm having a problem in my program execution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InheritanceTest {
    class Program {
        static void Main (string[] args) {
            String line;
            var diesel = new DieselEngine (200F, 550F, 3500, 7.5F, 10F);
            var electric = new ElectricEngine (85F, 1000F, 19000, 24F, 65000F);
            var city = new CityBus (124, 75, 18.5F, "Red", "Brisbane", electric);
            var coach = new Coach (777, 120, 22.5F, "Blue", "GreyHound", diesel);
            line = new String ('-', city.ToString ().Length * 2);

            System.Console.WriteLine ("City Buses\n\nID\tSeats\tLength\tColour\tCity\t\tEngine Type");
            System.Console.WriteLine (line);
            System.Console.WriteLine (city.ToString ());

            System.Console.WriteLine ("\n\nCoach Buses\n\nID\tSeats\tLength\tColour\tCompany\t\tEngine Type");
            System.Console.WriteLine (line);
            System.Console.WriteLine (coach.ToString ());

            System.Console.ReadKey (true);
        }
    }
}

No matter how I try to, I cannot access any of the properties of either of the classes that inherit engine from their relevant buses. For example, I cannot see the Displacement of the DieselEngine I gave to Coach "coach."

A:
I have a further two classes Coach and CityBus. How do I set those up to inherit from either DieselBus OR ElectricBus without having to define separate Coach and CityBus classes like CoachDieselBus, CoachElectricBus, CityBusDieselBus and CityBusElectricBus ? Is that even feasible/possible?

No, that's not feasible. The inheritance relation must be fixed, so a Coach must always have the same parent classes.
The appropriate solution for your problem would be to use composition instead of inheritance: Coach and CityBus both inherit from Bus. Bus  has an Engine property, which can be set to either a DieselEngine or an ElectricEngine.

(Sorry for the crude diagram, I only had MS Paint available right now.)

A: As usual when this question arrives, the confusion starts with an unfeasible class tree. I personally would say that none of them is an inheritance issue.
A bus has an engine, which is a base class for DieselEngine and ElectricEngine.
A bus has a Usage which is base class for City and Coach, possibly.
Using inheritance here is a classical antipattern. A typical beginner mistake - so do not feel bad about it. The result are mostly way too complex inheritance trees.
You may alternatively use interfaces (IDieselEngine, IElectricEngine) but I would probably go with composition.

A: In C#, you can only inherit from one class, so only classes shown in the second diagram are possible.
You could use interfaces as a class can implement more than one interfaces but interfaces should really be used more to define behaviour rather then properties/qualities of classes and diesel/electric and city/coach seem more like properties of your buses.

A: Here are an example of how you could do what you want
public abstract class Engine
{
    public abstract string Name { get; set; }
}

public class DieselEngine:Engine
{
    public override string Name { get; set; }

    public string DieselEngineProperty { get; set; }
}

public class ElectricEngine : Engine
{
    public override string Name { get; set; }

    public string ElectricEngineProperty { get; set; }
}

public class HybridEngine : Engine
{
    public override string Name { get; set; }

    public string HybridEngineProperty { get; set; }
    public List<Engine> EngineList { get; set; }
}

public abstract class Bus
{
    public abstract string Name { get; set; }
    public abstract string Lengh { get; set; }
    public abstract Engine BusEngine { get; set; }
}

public class CoachBus: Bus
{
    public override string Name { get; set; }

    public string CoachBusProperty { get; set; }
}

public class CityBus:Bus
{

    public override string Name { get; set; }
    public override string Lengh { get; set; }
    public override Engine BusEngine { get; set; }

    public string CityBusProperty { get; set; }
}

and here are some buses
        var myDieselEngine = new DieselEngine();
        myDieselEngine.Name = "TöffTöff";

        var myElectricEngine = new ElectricEngine();
        myDieselEngine.Name = "SumSum";

        var myHybridEngine = new HybridEngine();
        myDieselEngine.Name = "SumTöff";

        var myDieselCityBus = new CityBus();
        myDieselCityBus.Name = "Shorty1";
        myDieselCityBus.Lengh = "5 m";
        myDieselCityBus.BusEngine = myDieselEngine;

        var myElectricCityBus = new CityBus();
        myElectricCityBus.Name = "Shorty2";
        myElectricCityBus.Lengh = "7 m";
        myElectricCityBus.BusEngine = myElectricEngine;

        var myHybridCoachBus = new CoachBus();
        myHybridCoachBus.Name = "Shorty2";
        myHybridCoachBus.Lengh = "15 m";
        myHybridCoachBus.BusEngine = myHybridEngine;


text:
Q: cannot login to sql server with new user created I created a login named  logintest (SQL Authentication) then i created a user named usertest with this login
the user creation is successful, And i changed the authentication mode to mixed mode and also restarted the services SQLSERVERAGENT and MSSQLSERVER
and still this error appear when i try to login with the new user created
Cannot connect to SARAH.

Login failed for user 'usertest'. (Microsoft SQL Server, Error: 18456)

A: The login must have CONNECT right given.
The login must be enabled.
The default database linked to the login must be a database to which the login has rights to connect (for example by default master database gives rights to guest user to connect).
USE [master]
GO
ALTER LOGIN [logintest] WITH DEFAULT_DATABASE=[master]
GO
GRANT CONNECT SQL TO [logintest]
GO
ALTER LOGIN [logintest] ENABLE
GO

Then make sure the password is correct and that guest user is enabled on master database.


text:
Q: Eiffel avoiding duplicates into ecf file I have duplicate classes into a used library. How can I specify on the ecf file that I want to exclude a path?
Error code: VD71

Configuration error

Duplicate class: BASIC
/home/pg/data/solarity/sit-dev/eiffel/lib/thirdparty/json/examples/performance/basic.e
/home/pg/data/solarity/sit-dev/eiffel/lib/thirdparty/json/examples/basic/basic.e
Configuration: /home/pg/data/solarity/sit-dev/eiffel/sit-platform/sit_platform_lib.ecf

one way I found can be
<library name="json" location=".\..\lib\thirdparty\json\library\json.ecf" readonly="false"/>
        <file_rule>
                <exclude>
                        /examples$
                </exclude>
        </file_rule>

But can't find the definition of excluding paths and its syntax

A: There is no mechanism to control source code outside a library. The file rules to include and exclude source files are supported only for clusters.
You need to fix the library configuration to make sure is has no duplicate classes.
Note. Project settings dialog is a recommended way to change project settings, because it reflects only supported options, and ensures the configuration file does not get broken. In particular, it shows that clusters have exclusion rules in Source code section, whereas libraries do not.


text:
Q: Analytic continuation of Fourier transform Let
$$h(u)= \int_{-\infty}^{\infty} g(x) \exp(iux) \, \text{d}x$$
be the Fourier transform. Then let us suppose that for $ |x| \to \infty $ the function $g$ goes as
$$g(x) = \exp(-ax) \text{ for some positive $a$}$$
Does this mean that we can analytically continue the Fourier transform $h$ to the region of the complex plane where  $-a < \mathop{Im}(z) < a$? Apart from $h(u)$ being defined for every real $u$?
If $g(x)$ tends to $0$ sufficiently fast does it mean I can define the Fourier transform $h(z)$ for every complex number $z$?
In fact if we put $u = iz$ for real $z$ then is
$$h(iz)= \int_{-\infty}^{\infty}g(x) \exp(-zx) \, \text{d}x$$
defined for every real $z$ in this case if $g$ is a Gaussian for example?

A: Yes, it is possible to continue $h$ analytically to $-a < \text{Im}(z) < a\ $ if $|g(x)| \le  C\exp(-a|x|)\ $ for some $a>0$. The function is defined by putting $z$ instead of $x$ in the Fourier transform. If $g$ satisfy this estimate for any $a>0$ then $h$ is an entire function.


text:
Q: Bash - if/elif statement logic reporting back incorrectly I have a script that checks for a list of hosts in the hosts file, connects and then checks a file to see what the output is, if the output is two specific strings, then the bash script reports that the process has failed.
I've written what looks to me like it should work no issue, I've even tried it without the script running on interpreter and it returns what I expect, however when running it in a script it does not give the desired feedback.
It instead reports that host #2's process has failed, when in reality, it can't connect to host #2.
Code
#!/bin/bash
FILE='InternalAL2'
touch $FILE
BADPROCESS=()
for ip in $(cat /etc/hosts | grep serverAL2.[9][0-9][0-9][0-9] | awk {' print $2 '})
do ssh -n -f $ip -i ~/.ssh/personal.ssh "sleep 1; cat /etc/internalstate.txt | grep Status" > $FILE.txt
if cat $FILE.txt | grep "NOT RUNNING" ; then
   echo "NOT RUNNING detected on $ip"
   BADPROCESS+=($ip)
elif cat $FILE.txt | grep "STOPPED" ; then
   echo "STOPPED detected on $ip"
   STOPPED+=($ip)
else
   echo "ALL OK ON $ip"
fi
printf "$ip checked \n"
done

Hosts file
serverAL2.9000 <--- NOT RUNNING in file
serverAL2.9001 <--- Unreachable, timed out
...

Output

*

*Inside $FILE is 'Status NOT RUNNING'

*It reports 'ALL OK on serverAL2.9000' when it should report 'NOT RUNNING'

*It then tries to connect to 'serverAL2.9001', fails and reports NOT RUNNING on 'serverAL2.9001'

*All other hosts return if the process is running or not, fine.

I don't know why it is jumping ahead before checking the file contents


text:
Q: Tool to visualize Function Hierarchy trees? Any code-analysis or "reverse-engineering" tool that can do either of these?:

*

*Calculate which classes are sub-classes of which classes

*Calculate which classes instantiate which classes -- (like VS Class Designer)

*Calculate which functions call which functions -- (much like a Call Stack)

A: Doxygen + GraphViz
(for pictures, doxygen requires GraphViz)
That has the largest languages support (since you did not specify a language) and the viewer is a browser, so once generated, anyone should be able to view it.
Configure doxygen to generate even non documented members, and to include the source code.  This way the source code will include links to function declarations for easy navigation.
There are also tools that specialize in a language, such as Understand for C++.

A:
Calculate which functions call which functions

NDepend can produce some useful methods or class call graph like for example the screenshot below (image full size here) Disclaimer: I am one of the developers of the tool

Find more explanations about how to generate call graph with NDepend here.

Calculate which classes are sub-classes of which classes

The same way NDepend can generate class inheritance graph (explanation to generate class inheritance graph here).

Calculate which classes instantiate which classes

NDepend lets write Code Query over LINQ Query (what we call CQLinq). With CQLinq, you can ask for methods or classes that creates a particular class, for example:
from m in Methods
where m.CreateA("NUnit.Core.NUnitConfiguration")
select m

Such CQLinq query result can be exported to the graph view, to get a visual representation of dependencies.
As a side note, with CQLinq one can also write code rules. More than 200 code rules are proposed by default, these include rules concerning design, architecture, code quality, code evolution, naming conventions, dead code, .NET Fx usage...
CQLinq rules can be verified live in Visual Studio, or that can be verified during build process and reported in an HTML/javascript report.

A: Understand 2.0

...shows the dependence
  between parts of the code written in
  different languages. CLA make it
  easy to follow the calls.
  ~ Combined Language Analysis

Specifically this Function Call tree image.


text:
Q: Force Method to be called after overloaded constructor is called from the Super-class I'm working on a unity3d project where I have an abstract object that I will be calling from other objects. I want all my subclasses to call a certain virtual method after they finish constructing. Essentially the base constructor will be called, then the overloaded constructor, and finally my method, but I want this behavior defined from the base object.

A: You can force your subclass to implement an abstract method called Initialize() and then choose the order of calls in your base class :
    public abstract class MyBaseClass
    {
        public abstract void Initialize();

        public MyBaseClass()
        {
            // Code of the constructor of the base class

            // Calling the subclass
            Initialize();

            // Finally call the special method
            MySpecialMethod();
        }

        private void MySpecialMethod()
        {
            // Some code here
        }
    }

    public class MySubclass : MyBaseClass
    {
        public override void Initialize()
        {
            // Some code here
        }
    }


text:
Q: Games and a "stuttering" on SSD + HDD my problem is a bit weird I guess... I have a pretty new laptop.
Specs:
Windows 10 Home,
Intel i7 - 7700 HQ (2.8 to 3.8 GHz)
16GB of ram
G-Force GTX 1070 - 8GB GDDR5
And what I think might be the most important,
2 storages.
256GB SSD and a 1TB HDD (7400 RPM)
All my game launchers are on the SSD, while most of the games are on HDD.
For example, Steam and Battle.net are on the SSD. I have Hellblade installed on my SSD and it works perfectly, even at very high details. However World of Warcraft and other games are on my HDD and they have this weird "stuttering". I use parentheses, because I'm not sure if it qualifies.
Every now and then, the game goes to very low FPS, it's either stopping completely for a period of time (I'm literally talking fractions of a second, but just enough to notice) or it happens few times in a row (over a course of maybe one second). However after that period the game works perfectly again. And it seems that the game time "has passed". If I'm driving a car and the game freezes, after the tiny freeze I'm further in the game. Then it goes to perfect framerate until the next stutter (they can happen every 30 seconds for example?).
Now, what my research has shown:
Hellblade is installed on SSD and it has NO stutters at all, even at high details with quite high CPU / GPU temp
ETS2 (much less demanding game) was installed on HDD and had terrible stutters every 30 seconds or so. I looked it up, and it turns out that it was an autosave. I found a trick to run the game with special command line options and move some files between SSD and HDD (i forgot which way. If it's important, I will find out) and that has fixed the issue. There's still a tiny stutter when this happens but it's much less and I guess it's as good as it gets and that's just an issue with the game itself.
World of Warcraft and even rise of nations (this game is more than 10 years old now...) the game has a tiny stutter with every other sound effect or anything similar. That really indicates that the HDD is the issue?
It happens in WoW and Wolfenstein: New Order cutscenes too.
And now the really weird thing - during those freezes, sound usually works perfectly, but graphics freeze. I don't have any problem with internet, watching pictures and listening to movies - or even coding or using Virtual Machines.
I checked the CPU and GPU temps on every of those games, and Hellblade is the highest but ironically it's the only one that works fine.
I checked the HDD with defraggler - health is "Good". Read and seek error rate = 0
It really seems like the problem was installing the game launchers on a drive other than the game itself... does anyone have any advice or opinion?
Is there some kind of setting in BIOS or anything else I can do?
I forgot to mention - the built in screen has G-Sync. Maybe I should / could change some Vertical Sync options... That really seems a hit and miss with every game though. I really think it's the hdd issue...
Thank you very much in advance. The problem isn't a huge issue - but it's incredibely annoying.
EDIT: a commenter asked about my hard drive type. The exact name is:
HGST HTS721010A9E630
I checked the website for it. I don't know if it counts as a Green Drive but it says:
Low power consumption
Halogen-free for eco-friendly design
Is that the problem? If yes, can I do something about it?


text:
Q: Table of tables..use SQL pivot to extract unique fields for each table new to stack overflow as my job has me doing more SQL querying than I'm use to (super basic queries). And since this is the best online resource....:)
Preamble...my company has developed an SQL database that contains a giant table of tables. In other words, they extracted a series of tables (200+) from external sources and put them all into one massive table to be used for reporting purposes in other systems. For example, if one of these external tables has 5 fields and 10 rows of data, that translates to 50 rows in this 'table of tables' (Table1, Field1, Value...Table1, Field2, Value....TableX, FieldX, Value...etc.)
Requirement...I need to 'pivot' the data for the purposes of getting a list of all the fields in all the tables. In other words ignore the values (just TableX, FieldX). I need to do this in order to find 'like' fields across all the tables. Being new to using PIVOT in SQL queries, I know the basic structure of the SQL query, but I'm getting lost in the organization of it.  Maybe I don't even use PIVOT. Here's what I have...
SELECT * from (
SELECT [FieldName],[iModelTable]
  FROM [H352090DataMart].[dbo].[HA_iModelTableData]

PIVOT (MAX([FieldName]) FOR [iTableName] IN
  (
--not sure what would go here if anything
  )
  ) AS pvt

Any help is greatly appreciated.
Austin.

A: Nevermind.  I figured it out.  Is was as simple as using the DISTINCT function. As I said, I'm a bit of a noob when it comes to scripting.  So for those who read this post, the answer is as follows (the ORDER BY is extra)...
SELECT DISTINCT
[iModelTable]
,[FieldName]
FROM [H352090DataMart].[dbo].[HA_iModelTableData]
ORDER BY iModelTable


text:
Q: error TS2304: cannot find $ in angular 5 component I have a side-navbar in angular component which expands on click similar to this. The HTML snippet used to create the navbar is :
HTML:
As the name(openNav()) suggests, the following HTML code will expand the navbar:

And the following HTML code  will close the navbar:

 Item 1

 Item 2

Typescript:
The typescript used is:
openNav()
 {
     $("#mySidenav").css("width", "50%");   // Line A
 }

 closeNav()
 {
    $("#mySidenav").css("width", "0%");   // Line B
 }

The above typescript code is not included in the ngOnInit() function.

Problem Statement :
As soon as I do ng serve on my command prompt, I get the following error:

error TS2304: Cannot find name '$'.

The $ represents the lines (Line A and Line B in the typescript above) inside openNav() and closeNav() functions above in the typescript.
I am wondering what are the primary reasons behind that error as sometimes I get the error and sometimes I don't while doing ng-serve.

A: I assume that $ is jQuery. You must add jQuery to your dependencies and imported it in the file where you're using it. I'd suggest also adding the type definitions for jQuery: npm install @types/jquery --save-dev
If you're importing jQuery in any other way, then just add the types.

A: This is a possible solution:
HTML:

And the following HTML code will close the navbar:

 Item 1

 Item 2

Typescript:
//Define a visual style variable
vstyle: = 'width:50%;';

openNav()
 {
     vstyle = 'width:50%;';   // Line A
 }

 closeNav()
 {
    vstyle = 'width:0%;';   // Line A
 }

A: If you are using the jquery in ts file, declare $ as a variable of type any, then you won't get the error.
declare  var $:any

A: Use style.width

 Item 1

 Item 2

And then set the value of "myWidthVariable" on your openNav() and closeNav() methods (just the number).


text:
Q: External table limitations Now i am working on external tables... While i do like its flexibility. I would like to know these things about external table -

*

*Like in SQL Loader we can append data to the table . Can we do that in External table ?

*In external table , we cannot create indexes neither can we perform DML operations. Is this kind of virtual table or this acquires space in the data base ?

*Also in SQL loader we can access the data from any server in external table we define the default directory. Can we in turn do the same in external table that is access the data from any server ?

A: External tables allow Oracle to query data that is stored outside the database in flat files as though the file were an Oracle table.
The ORACLE_LOADER driver can be used to access any data stored in any format that can be loaded by SQL*Loader. No DML can be performed on external tables but they can be used for query, join and sort operations. Views and synonyms can be created against external tables. They are useful in the ETL process of data warehouses since the data doesn't need to be staged and can be queried in parallel. They should not be used for frequently queried tables.
You asked:

*

*like in SQL Loader we can append data to the table . Can we do that in External table ?

Yes.

*In external table , we cannot create indexes neither can we perform DML operations. Is this kind of virtual table or this acquires space in the data basE ?

As the name suggests, it is external to the database. You use ORGANIZATION EXTERNAL syntax. The directory is created at OS level.

*Also in SQL loader we can access teh data from any server in external table we define the DEfault directory. Can we in turn do the same in external table that is access the data from any server ?

This is wrong. SQL*Loader is a client-side tool, while external table is a server-side tool. External Table can load file which is accessible from database server. You can't load External Table from file residing on your client. You need to save the files to a filesystem available to the Oracle server.
Prior to version 10g, external tables were READ ONLY. DML could not be performed. Starting with version Oracle Database 10g, external tables can be written to as well as read from.
From documentation, also read Behavior Differences Between SQL*Loader and External Tables


text:
Q: Accessing a Datastore from a GCP project in R I am trying to set up a Google Co-lab notebook that runs in R and can read a GCS bucket from a GCP project. I am using the googleCloudStorageR package. To authenticate and read the bucket, the initial Co-lab notebook runs the following Python commands:
!gcloud auth login
!gcloud config set project project_name
!gcloud sql instances describe project_name

How can I run the above commands in R using the googleCloudStorageR package ? In the documentation for the package, they mention using the gcs_auth function that reads an authentication JSON file. However, since I will be accessing the buckets through a Co-Lab notebook running on R, I do not want to use an authentication file and instead want to authenticate and connect to the GCP storage in real-time from the Co-Lab notebook. Thank you!

A: Figured this out. In a Co-lab notebook, run the following code snippet:
install.packages("httr")
install.packages("R.utils")
install.packages("googleCloudStorageR")
if (file.exists("/usr/local/lib/python3.6/dist-packages/google/colab/_ipython.py")) {
      library(R.utils)
      library(httr)
      reassignInPackage("is_interactive", pkgName = "httr", function() return(TRUE))
    }
library(googleCloudStorageR)
 options(
      rlang_interactive = TRUE,
      gargle_oauth_email = "email_address",
      gargle_oauth_cache = TRUE
    )
token <- gargle::token_fetch(scopes = "https://www.googleapis.com/auth/cloud-platform")
    googleAuthR::gar_auth(token = token)

There is an issue with gargle authentication that the googleCloudStorageR package uses. A workaround that is similar to the one listed here (https://github.com/r-lib/gargle/issues/140) is to generate a token for cloud scopes, which would give us a token object that we would then use in the gar_auth function.


text:
Q: How to sum and array's interval? import java.util.stream.*;

int[] array = {1,2,3,4,5};
int sum = IntStream.of(array).sum();

in this case "sum" = 15, but what if i wanted to sum the numbers from index[0] to [3]?

A: Use Arrays.stream():
// end index is exclusive
int sum = Arrays.stream(array, 0, 4).sum();

A: Add a limit to the stream:
int sum = IntStream.of(array).limit(4).sum();

A: In this case Use Arrays.stream(): and entre the interval you need
Exmple :
import java.util.Arrays;
import java.util.Scanner;

    public class SumInterval{

        public static void main(String[] args) {
            // TODO Auto-generated method stub
                                    int[] a = {1 ,2 ,3 ,4 ,5};
                                     // entre index
                                     int sum = Arrays.stream(a, 0, 2).sum();
                                    System.out.println("The sum is " + sum);
        }

    }

output :
`The sum is` 3


text:
Q: Как вернуть значение из then Есть функция
function get_score() {
    return new Promise(resolve => {
    fetch(this.api_url)
        .then(res => res.json())
        .then(json => resolve(json[0]) );
});

И чтобы использовать ее в коде нужно:
get_score()
    .then(score => console.log(score))

Но я хотел бы чтобы при вызове мне не было необходимости приписывать then, чтобы get_score() просто возвращал score без then => score.

A: Воспользуйтесь ASYNC/AWAIT

function get_score() {
    return new Promise(resolve =>
        setTimeout(() => resolve(Math.random()), 1000)
    );
}

(async function(){
    const result = await get_score();

    console.log(result);
})();

Так же можно видоизменить вашу функцию get_score()

const api_url = 'https://api.themoviedb.org/3/discover/movie?api_key=15d2ea6d0dc1d476efbca3eba2b9bbfb';

async function get_score() {
    try {
        const response = await fetch(api_url);
        const result = await response.json();
        return result;
    }
    catch(error) {
        console.log(error);
    }
};

(async function() {
    const getScore = await get_score();
    console.log(getScore);
})();


text:
Q: Raising compile-time errors Is there a way to raise a compile-time error when a certain specialization of a function template is attempted ?
Say
template<typename T> T Factorial(T n) { ... }

short n;
cout << Factorial(n); // Error, short is too small

And is there a way to achieve the same effect for specific methods of a templated class ?
Say
template<typename T> class Arithmetic
{
  T n;
  T GCD(T m) { ... }
  T Factorial() { ... }
};

Arithmetic<short> A;
short m;

cout << A.GCD(m); // Ok
cout << A.Factorial(); // Error, short is too small

A: This could do the trick:
template<typename T>
class Foo {
public:
  Foo() {
    static_assert(sizeof(T) > sizeof(short));
  }
};

int main() {
  Foo<short> foo;
  return 0;
}

(mind that static_assert without diagnostic message requires C++17)


text:
Q: Open a modal for a specific card from a list of cards using React hooks I am using an API to fetch and render the data it into cards. I want to render a corresponding modal for each card when the card is clicked. I am using the React modal component by material-ui (the simple modal example). The problem is that instead of the modal for the clicked card, I'm getting the modal for the last card. I managed to "capture" the data of the clicked card in a state hook, but I'm not sure how to use that to render the correct component.
This is the Home component where the cards are rendered:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { BeerCardExpanded } from './BeerCardExpanded';
import { BeerCard } from './BeerCard';

import { makeStyles } from '@material-ui/core/styles';
import Modal from '@material-ui/core/Modal';

import '../styles/Home.css';
import { DialogContent } from '@material-ui/core';

function rand() {
  return Math.round(Math.random() * 20) - 10;
}

function getModalStyle() {
  const top = 50 + rand();
  const left = 50 + rand();

  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `translate(-${top}%, -${left}%)`,
  };
}

const useStyles = makeStyles(theme => ({
  paper: {
    position: 'absolute',
    width: 400,
    backgroundColor: theme.palette.background.paper,
    border: '2px solid #000',
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3),
  },
}));

export const Home = () => {
  const ref = React.createRef();
  const classes = useStyles();
  const [modalStyle] = React.useState(getModalStyle);
  const [beers, setBeers] = useState([]);
  const [open, setOpen] = useState(false);
  const [isClicked, setIsClicked] = useState([]);

  const fetchBeerData = async () => {
    try {
      const { data } = await axios.get(
        'https://api.punkapi.com/v2/beers?per_page=9'
      );
      console.log(data);
      return data;
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    fetchBeerData().then(data => {
      setBeers(data);
    });
  }, []);

  const handleOpen = id => {
    setIsClicked(isClicked.push(beers.filter(item => item.id === id)));
    setIsClicked(id);
    setOpen(true);
    console.log(isClicked[0]);
  };

  const handleClose = () => {
    setOpen(false);
    setIsClicked([]);
  };

  return (

      {beers.map((beer, index) => (
        <>
          <BeerCard
            key={beer.name}
            beer={beer}
            id={index}
            handleOpen={handleOpen}
          />
          <Modal
            aria-labelledby='transition-modal-title'
            aria-describedby='transition-modal-description'
            open={open}
            onClose={handleClose}
          >
            <DialogContent>
              <BeerCardExpanded
                id={`${isClicked.id}-${isClicked.name}`}
                className={classes.paper}
                style={modalStyle}
                beer={beer}
                ref={ref}
              />
            </DialogContent>
          </Modal>
        </>
      ))}

  );
};

This is the BeerCard component:
import React, { useState } from 'react';
import '../styles/BeerCard.css';
import CardActions from '@material-ui/core/CardActions';
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import FavoriteIcon from '@material-ui/icons/Favorite';
import IconButton from '@material-ui/core/IconButton';

export const BeerCard = ({ beer, handleOpen }) => {
  const [isFavorite, setIsFavorite] = useState(false);

  const handleIconClick = e => {
    e.stopPropagation();
    setIsFavorite(!isFavorite);
  };

  return (

 handleOpen(beer.id)}>

{beer.name}

            {beer.tagline}

{beer.description}

      <CardActions className='favorite-icon'>
        <IconButton aria-label='add to favorites'>
          {!isFavorite ? (
            <FavoriteBorderIcon onClickCapture={e => handleIconClick(e)} />
          ) : (
            <FavoriteIcon onClickCapture={e => handleIconClick(e)} />
          )}
        </IconButton>
      </CardActions>

  );
};

And the BeerCardExpanded is the component that gets injected in the material-ui's modal component:
import React, { useState } from 'react';
import CardActions from '@material-ui/core/CardActions';
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import FavoriteIcon from '@material-ui/icons/Favorite';
import IconButton from '@material-ui/core/IconButton';

import '../styles/BeerCardExpanded.css';

export const BeerCardExpanded = React.forwardRef(({ beer }, ref) => {
  const [isFavorite, setIsFavorite] = useState(false);

  const handleIconClick = e => {
    e.stopPropagation();
    setIsFavorite(!isFavorite);
  };

  return (

      <CardActions className='favorite-icon'>
        <IconButton aria-label='add to favorites'>
          {!isFavorite ? (
            <FavoriteBorderIcon onClickCapture={e => handleIconClick(e)} />
          ) : (
            <FavoriteIcon onClickCapture={e => handleIconClick(e)} />
          )}
        </IconButton>
      </CardActions>

          {}

{beer.name}

              {beer.tagline}

{beer.description}

            Pairs best with:
            {beer.food_pairing.map((item, index) => (
               ☆{item}
            ))}

  );
});

I created a codesandbox, here's the link.

A: Looks like you were getting the beer.id mixed up with the map index. Try using the Id rather than index.
      {beers.map((beer) => (
          <BeerCard
            key={beer.name}
            beer={beer}
            id={beer.id}
            handleOpen={handleOpen}
          />
      ))}

https://codesandbox.io/s/new-tree-z3pxf
Notice the filter inside handleOpen also
   useEffect(() => {
    const fetchBeerData = async () => {
      try {
        const { data } = await axios.get(
          "https://api.punkapi.com/v2/beers?per_page=9"
        );
       setBeers(data);
      } catch (err) {
        console.log(err);
      }
    };
    fetchBeerData();
  }, []);

  const handleOpen = (id) => {
    setIsClicked(beers.find(x => x.id === id));
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
    setIsClicked({});
  };

  return (

      {beers.map((beer) => (
          <BeerCard
            key={beer.name}
            beer={beer}
            id={beer.id}
            handleOpen={handleOpen}
          />
      ))}

      <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        open={open}
        onClose={handleClose}
      >
          <DialogContent>
            <BeerCardExpanded
              id={`${isClicked.id}-${isClicked.name}`}
              className={classes.paper}
              style={modalStyle}
              beer={isClicked}
              ref={ref}
            />
          </DialogContent>
      </Modal>

  );


text:
Q: Pointers list going wrong I want to be able to access the arrays and variables with pointers. So I made an array of pointers to those arrays and variables. But it doesnt seem to compile right. Where do I go wrong? (c++, atmel, avrstudio)
volatile uint8_t    lfo1Clock = 0;
volatile uint8_t    lfo2Clock = 0;
volatile uint8_t    lfo3Clock = 0;
volatile uint8_t    lfo4Clock = 0;
volatile uint8_t    lfo5Clock = 0;
volatile uint8_t    lfo6Clock = 0;

uint8_t     lfo1[5]={4,0,0,0,0};
uint8_t     lfo2[5]={4,0,0,0,0};
uint8_t     lfo3[5]={4,0,0,0,0};
uint8_t     lfo4[5]={4,0,0,0,0};
uint8_t     lfo5[5]={4,0,0,0,0};
uint8_t     lfo6[5]={4,0,0,0,0};

uint16_t    *lfoList [] = {lfo1,lfo2,lfo3,lfo4,lfo5,lfo6};
uint16_t    *lfoClockList [] = {lfo1Clock,lfo2Clock,lfo3Clock,lfo4Clock,lfo5Clock,lfo6Clock};

Thanks for any advice.

A: Your first array is an array of uint16_t pointers, but it's pointing to uint8_t arrays. It should be something like this:
uint8_t    *lfoList [] = {lfo1,lfo2,lfo3,lfo4,lfo5,lfo6};

Your second array is also an array of pointers of the wrong type, but it also contains simple uint8_t instances which wouldn't work even if the type was correct.
If it's just meant to be an array of uint8_t instances, I suspect you want this:
uint8_t    lfoClockList [] = {lfo1Clock,lfo2Clock,lfo3Clock,lfo4Clock,lfo5Clock,lfo6Clock};

If you actually did need the second array to be an array of uint8_t pointers, then you'll need to take the address of each of those items. And I think you need to use volatile in the array definition for the type to be compatible.
volatile uint8_t    *lfoClockList [] = {&lfo1Clock,&lfo2Clock,&lfo3Clock,&lfo4Clock,&lfo5Clock,&lfo6Clock};

A: volatile int    lfo1Clock = 0;

int lfo1[5]={4,0,0,0,0};

int (*lfoList[5])[] = {&lfo1}; //   array of pointers to array of five integers

volatile int *lfoClockList [] = {&lfo1Clock};

Note: You are using uint16_t* pointer to infer uint8_t data


text:
Q: How to create a graph with all disconnected components aligned vertically? using python graphviz I am trying to render a DiGraph where there are groups of nodes connected to each other and separate from other groups. The structure is something I am creating on the fly, where I don't really have the full picture of these components before hand, it's something I am hoping the rendered graph would help me understand. I would like for these groups to be aligned vertically in the output svg file instead of all laid horizontally as it is now.
Any ideas?


text:
Q: Are rems and ems equivalent when used at root level? From this answer I see what's the definition of rem in the spec:

rem unit
Equal to the computed value of font-size on the root element. When specified in the font-size property of the root element, or in a document with no root element, 1rem is equal to the initial value of the font-size property.

And the definition of em is:

em unit
Equal to the computed value of the font-size property of the element on which it is used.

To me this implies that 1em == 1rem by definition when used at :root.
Am I correct?

A: Yes

:root {
  font-size:40px;
  border-top:   1rem solid red;
  border-bottom:1em  solid green;
}


text:
Q: jQuery selectors tool I'm looking for some kind addon for browser (firefox, opera, ie, chrome, etc...), which can easily highlight element(s), which I define by jQuery selector.

A: Are you looking for Firefinder Firebug extension?
Here's a short screencast with jQuery integration.

A: You can use firebug for firefox.

A: jQuery Selectors

*

*Extension for Chrome

A: This one is from the author of the book "jQuery in Action" which is an excellent resource.
http://www.bibeault.org/jqueryinaction/chapter2/lab.selectors.html
Also found this one which looks good:
http://codylindley.com/jqueryselectors/


text:
Q: How to consume web service from an applet using cxf framework? I´m a newbie using java and cxf framework
I´m trying to consume a web service from an applet. I create the web service client using eclipse and web service client wizard. When I run the applet from the IDE it works, but when I run the applet from the browser it doesn´t. I deploy the jar using the option export Runnable JAR file. The Error that I get is java.io.FileNotFoundException C:\testingWS\META-INF\cxf\org.apache.cxf.JDKBugHacks.all
I have been googling and what I found was this cxf/core/src/main/java/org/apache/cxf/common/logging/JDKBugHacks.java but nothing about org.apache.cxf.JDKBugHacks.all
Thanks in advance


text:
Q: C# Last DataGridView Row Value in Textbox I have a DataGridView (bound to an SQL Database Table) with a column name "order_ID". What I want is to add the last filled value in that column in the GridView/SQL Table to be shown in a textbox. How would I go about doing that? Any help would be greatly appreciated.

A: Is this what you are trying to achieve?
int lastRow = yourDataGridView.Rows.Count - 1;
object last_order_ID = yourDataGridView.Rows[lastRow].Cells["order_ID"].Value;
yourTextBox.Text = Convert.ToString(last_order_ID);

Hope it helps you.

A: next id :
int lastRow = dataGridView1.Rows.Count-1;
        int last_order_ID = Convert.ToInt32(dataGridView1.Rows[lastRow].Cells["s_id"].Value) + 1;
        txt_num.Text = Convert.ToString(last_order_ID);


text:
Q: cannot access google developer console I have a problem while accessing or creating any project on google developer console.
I also followed this link
Unable to Create Google Cloud Console Project
but still no luck as there was no option more controls when I logged in. Somebody plz explain why the hell I am getting this error

Developers Console has not been activated for your account. Your account may be suspended or disabled. If you are a Google Apps user, ask your domain administrator to enable Apphosting Admin on your account.


text:
Q: Show image if div is clicked I'm trying to show an image when a div is clicked.
The first one is working but the second one isn't.
What I've tried so far, but it didn't work:

$('#review').click(function() {
  var src = $('#review').attr('src');
  $('#result').attr('src', src);
});

John Doe

Doe John

A:
id = name [CS] This attribute assigns a name to an element. This name
  must be unique in a document.

You  have used id="review" for two elements. It is not possible.
Used this selector in the function. Otherwise the first element with the class will be used.

$('.review').click(function() {
  var src = $(this).attr('src');
  $('#result').attr('src', src);
});

John Doe

Doe John

A:

$('.review').click(function() {
  var src = $(this).attr('src');
  $('#result').attr('src', src);
});

John Doe

Doe John

*

*Use class Id should be unique

*use this context to refer to click element

A: An Id should be unique, use class to select by in this case

$('.review').click(function() {
  var src = $(this).attr('src');
  $('#result').attr('src', src);
});

John Doe

Doe John

A: Id should be unique, but by any reason if you can't change it,then you can use attribute selector like below as id selector returns first matching element!

$("[id='review']").click(function() {
  var src = $(this).attr('src');
  $('#result').attr('src', src);
});

John Doe

Doe John


text:
Q: How can I implement Https/SSL connection on Asp.Net Web API? I use Asp.net web APIs to provide apis to client (iphone, android, mac os,web,windows,...). I want to implement some API with more security, which I prevent some other understand the parameter in the link (in case they hack the link)
My question is: Can I use Https/SSL for this? Is it enough secure? If yes, Should I install any thing at client side to implement this?
Thanks

A: It depends on where you are going to host your ASP.NET Web API application. If you are going to host it under IIS, you don't need to do anything special other than configuring SSL through IIS.
One thing you should do IMO is to force HTTPS through your application. You can implement this with different ways (such as IIS URL Redirect module, etc.) but you can also do this at the application level with a message handler:
public class RequireHttpsMessageHandler : DelegatingHandler {

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

        if (request.RequestUri.Scheme != Uri.UriSchemeHttps) {

            var forbiddenResponse = request.CreateResponse(HttpStatusCode.Forbidden);
            forbiddenResponse.ReasonPhrase = "SSL Required";
            return Task.FromResult<HttpResponseMessage>(forbiddenResponse);
        }

        return base.SendAsync(request, cancellationToken);
    }
}

HttpClient also supports SSL just like any other .NET web clients. Have a look at this article: http://blogs.msdn.com/b/henrikn/archive/2012/08/07/httpclient-httpclienthandler-and-httpwebrequesthandler.aspx


text:
Q: change size of div function doesn't work I have a function that alters the size of a div when I click on it. Now I have to write the onclick command in my html page, but I want it to stand in the extern .js file.
Now in html:

 Title 1

What I want:

 Title 1

Tried something in jquery but it didn't work:

function changeSize(id) {
  var elem = document.getElementById(id);
  var currentAbsoluteElem = document.getElementById('dummy');
  var text = elem.innerHTML;
  currentAbsoluteElem.innerHTML = text;
  currentAbsoluteElem.setAttribute('style', 'display:block');
  /*Extra styling neeed  to be done here*/

}

var elems = document.getElementsByClassName('kaesten');
for (var i = 0; i < elems.length; i++) {
  elems[i].onclick = function() {
    changeSize(this.id);
  }
}

var absoluteCl = document.getElementsByClassName('absoluteclass');
absoluteCl[0].onclick = function() {
  console.log(document.getElementsByClassName('absoluteclass'))
  document.getElementsByClassName('absoluteclass')[0].setAttribute('style', 'display:none');
}
$(document).ready(function() {

$('.kaesten').click(function() {
    changeSize($(this).attr('id'));
});
});
.kaesten {
  width: 240px;
  height: 300px;
  background-color: darkgrey;
  background-position: center;
  background-repeat: no-repeat;
  text-shadow: 0px 0px 3px #000;
  border: 5px solid #F0F8ff;
  vertical-align: top;
  text-shadow: 3px 3px 4px #777;
  float: left;
  margin-left: 30px;
}

.absoluteclass {
  position: absolute;
  background-color: darkgrey;
  width: 600px;
  height: 600px;
  left: calc(30%);
  display: none;
}

title1

title2

title3

title4

I know it works in the fiddle, but I don't know why it doesn't work on my homepage without writing the function in the div's.

A: I guess the problem is that you are trying to assign the onclick event handler before the DOM is actually rendered and ready. My suggestion is to wrap your "initialization code" inside a $(document).ready() method. As follows:
$(document).ready(function() {
    // Apply the on click event handlers here, using jQuery or not
    // For instance:
    $('.kaesten').click(function() {
        changeSize($(this).attr('id'));
    });
});

A: if you want to pass the id from jquery to your function you should do it like this:
$(function(){
    $(".kaesten").click(function(){
        changeSize($(this).attr("id"));
    });
});

A: you can use .css in jquery
$(function(){
            $(".kaesten").click(function(){
                $(this).css({'width' : '600px' , 'height' : '600px'});;
            });
        });