text:
Q: Unit testing with Jasmine and Browserify and stubbing out require()s For the below code I want to test the if/else in someMethod, but I don't have access to that require'd component. Is there any tricks to testing this stuff with Browserify? I can set baz: Foo.bar() on the proto, but then I'd have to do that for every require'd component I need to override.
var Foo = require('../foo/index.js');

var someClass = new SomeClass({
  someMethod: function () {
    var baz = Foo.bar();
    if (baz == 'hello') {
      return 1
    }
    else {
      return 0
    }
  }
});

A: You should check out rewireify or proxyquireify.  They will allow you to manipulate your "var Foo = require" statement in your test.  But yes, you will have to do this for each require statement you want to mock.  You also may want to check out Facebook's Jest, that mocks all of your require statements for you automatically.


text:
Q: 3Blue1Brown Cloudy Argument After watching 3blue1brown's video "Integration and the fundamental theorem of calculus," I got confused at around 11:00, where Grant says the derivative of the area function is exactly the function itself. The reason for this is since when dT approaches zero, the rectangular approximation $v(T)dT$ resembles $dS$ more and more, it makes sense then that at $dT=0$, the derivative of $s(T)$ is exactly $v(T)$. However, $dT=0$ invalidates the equality because a zero denominator is undefined. I think this contradiction possibly highlights a consequence of treating differentials as variables when they're actually not. Is my reasoning correct?

A: There are two things I want to say.
First of all, $ds = v(T)dT$ is literally true when you interpret what $ds$ and $dT$ stand for correctly (they are differential forms, but that's not important). However, this is a consequence of the fundamental theorem.
But, 3Blue1Brown doesn't treat $ds$ and $dT$ in this abstract sense, what they are actually doing is looking at $\Delta s = s(T+\Delta T) - s(T)$ and $\Delta T$. I suppose that for the sake of clarity of exposition, they conflate these things not to overburden viewers with too much notation. (Who said YouTube videos need to be formally correct?) However, their explanation really leads to formally correct proof that $s'(T) = v(T)$. Let's take a look.
$$\Delta s = s(T+\Delta T) - s(T) = \int_0^{T+\Delta T}v(t)\,dt - \int_0^{T}v(t)\,dt = \int_T^{T+\Delta T}v(T)\,dt.$$
By the mean value theorem for integrals, there exists some $T_1\in [T,T+\Delta T]$ such that $$\int_T^{T+\Delta T}v(T)\,dt = v(T_1)\Delta T$$
and this is formal explanation why 3Blue1Brown say $\Delta s \approx v(T)\Delta T$ when $\Delta T$ is small. This still needs more polishing to be formally correct, we need $v$ to be continuous. So far, we concluded that for some $T$ and $\Delta T$, there exists $T_1\in[T,T+\Delta T]$ such that $$\frac{\Delta s}{\Delta T} = v(T_1).$$ Now, in the last expression you obviously cannot let $\Delta T = 0$, as you say, but you can look at the limit $\lim_{\Delta T\to 0}$. We now have
$$s'(T) = \lim_{\Delta T\to 0} \frac{\Delta s}{\Delta T} = \lim_{\Delta T\to 0} v(T_1) = v(\lim_{\Delta T\to 0}T_1) = v(T),$$
where second to last equality is due to continuity of $v$ and the last equality is due to squeeze theorem, since $T\leq T_1 \leq T+\Delta T$. And this completes the proof.

The moral of the story is that YouTube videos can be great to build intuition and good ones provide sketches of formal proofs, however, they are not to be used as a substitute for textbooks when it comes to formal correctness.

A: I agree. You can use this calculation with differentials to reason and as a mental aid, but it is very dangerous to use them in formal proofs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I increase the use of RAM in Colab? I'm just using 1.49 out of 25 GB of memory from Colab while running a script? How can I use the maximum memory capacity to speed up the process?

Thanks!

A: Data processing is done using a CPU or a GPU (or both of them at the same time). For the CPU, its speed can be measured using 2 metrics : Instructions per Second (IPS), or Floating Point Operations per Second (FLOPS). The architecture of a CPU and the number of cores affect its speed. Nowadays, GPU's are heavily used in data processing due to their bandwidth advantage over CPU's, there are a lot of other reasons, you can look them up here : CPU Vs GPU
So in order to speed up the data processing, make sure you're using Colab's GPU to run tests, while RAM holds all the data and variables of your current session. If you want to use all the RAM available, you simply need to use a bigger dataset as mentionned by @AEM (more data = more RAM usage).
If you want to see the effects of more data on the RAM, you can try this simple code :
data = []
while(1):
  data.append('1234')

This infinite loop makes you add more & more data into a list until you hit the maximum usage of RAM (Colab might crash eventually), hope this helps.


text:
Q: Is it possible to create mock with multiple calls when the no. and type of arguments are unknown? I wanted to know that can we create a phpunit mock when we do not know initially the number of arguments for the method
Normally we would do something like this when we know the number of method invocations
mockResponse->expects($this->exactly(2))
    -> method('tmpFunc')
    ->withConsecutive(['header1'], ['header2']);

What I would like to do is get it to be something more dynamic
function mockMethod($n, $params) // $params is an array of strings
{
    $mockResponse = $this->getMockBuilder('PMA\libraries\Response')
        ->disableOriginalConstructor()
        ->setMethods(array('tempFunc', 'headersSent'))
        ->getMock();

    if($n > 1)
    {
        $mockResponse->expects($this->exactly($n))
            ->method('tempFunc')
            ->withConsecutive( //todo );

        $mockResponse->expects($this->any())
            ->method('headersSent')
            ->with()
            ->will($this->returnValue(false));

    }
}

So for example if $n = 2 and $params = array('HTTP/1.1 303 See Other', 'Location: index.php?lang=en') then the function should do this
$mockResponse = $this->getMockBuilder('PMA\libraries\Response')
        ->disableOriginalConstructor()
        ->setMethods(array('tempFunc', 'headersSent'))
        ->getMock();

$mockResponse->expects($this->exactly($n))
    ->method('tempFunc')
    ->withConsecutive([$params[1]], [$params[2]]);

$mockResponse->expects($this->any())
        ->method('headersSent')
        ->with()
        ->will($this->returnValue(false));

How should I replace the todo so that if $n = 2 then each string will be sent as an argument to tempFunc().
public function tempFunc($text)
{
    header($text);
}

public function headersSent()
{
    return headers_sent();
}

A: I finally got the answer from someone I knew
$header_method = $mockResponse->expects($this->exactly(count($param)))
            ->method('tmpFunc');
call_user_func_array(array($header_method, 'withConsecutive'), $param);


text:
Q: Find values of $a$ and $\lambda$ for which $Z_{0}e^{at+bW_{t}}-\lambda t$ is a martingale Find values of $a$ and $\lambda$ for which $Z(t)=Z_{0}e^{at+bW_{t}}-\lambda t$ is a martingale. In here $W_{t}$ is a Brownian motion and $a,b\in\mathbb{R}$ can be positive as well as negative, since $b$ is derived by substracting one variance from another.
I cannot find a form for which this is a martingale except the form of the exponential martingale $$C\cdot e^{\alpha W_{t}-\frac{\alpha^{2}t}{2}}$$ with $C$ a constant. This would imply that only for the values $$a=\frac{-b^{2}}{2}$$ and $$\lambda=0$$ $Z(t)$ is a martingale. Is this correct or is there another form for which $Z(t)$ is a martingale, since I have to find a solution for $\lambda\in\mathbb{R}^{+}$, but this is quite an ambiguous expression.

A: The mean of $Z(t)$ is $E[Z_0]\cdot e^{at+b^2t/2}-\lambda t$, which is constant (in $t$) if and only if $a+b^2/2=0=\lambda$.  This means that the sufficient condition you have found is also necessary, for $Z(t)$ to be a martingale.


text:
Q: typescript how to dynamically import? I had some JS that would dynamically import and add a bunch of routes like this:
let routeFiles = [
  './routes/projects',
  './routes/scraper',
  './routes/admin',
  // etc
]

initRoutes(app) {
  for (let fn of routeFiles) {
    let routes = require(fn)
    app.use('/tix', routes)
  }
  debug.info('init routes done')
}

But with typescript I get an error
An import declaration can only be used in a namespace or module.

Looking around there doesn't seem to be a clear answer
const mod = await require(fp)

this gives me an error of not being able to find the module as . even though I have checked the path being passed in:
(node:33353) UnhandledPromiseRejectionWarning: Error: Error: Cannot find module "."
    at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:843:23)
    at Generator.next (<anonymous>)
    at /Users/dc/dev/tix/recobot/stack/backend/build/server.js:800:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:796:12)
    at Object.initModels (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:821:16)
    at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:527:28)
    at Generator.next (<anonymous>)
    at fulfilled (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:497:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)

based on
https://www.typescriptlang.org/docs/handbook/modules.html#optional-module-loading-and-other-advanced-loading-scenarios
I also tried the convoluted:
  mod = await System.import(fn)
  mod.init()

same error
Error: Cannot find module './models/Projects'.

If I hoist the import outside the main code block all runs fine.
import Project from "./models/Projects"

const TixBot = {

  async initModels(dbc: any) {
     await Project.init(dbc)

btw I am running under webpack which had this issue:
https://github.com/webpack/webpack/issues/1599
resolved with
  node: {
    __dirname: true
  },

in the webpack.config. man, sometimes I'm afraid to look down when working on modern JS...
not very helpful: Typescript: dynamically import classes
related and interesting
https://blog.atomist.com/typescript-imports/


text:
Q: Get an array element from an array in a json attribute of a jsonb column I am using postgres database and I have an array inside a json attribute in a jsonb column and I need to get the first element of that array. The jsonb_column structure is like the below:
"IndustryCode": {
"Code": "111110",
"Keys": [
  "11",
  "111",
  "111110"
],}

So far I can get all the query elements by issuing the query below
select jsonb_array_elements(jsonb_column->'IndustryCode'->'Keys' ) from myindustry;

How can I query to get the first element?

A: If you just want the first element, there is no need to unnest the whole array. the -> operator also accepts an integer which specifies the array index.
select jsonb_column -> 'IndustryCode' -> 'Keys' ->> 0
from myindustry;

Note I used ->> to return the value as text not as jsonb


text:
Q: problem on union of connected sets for $v \in \mathbb R^2$ and $r>0$ let $D(v,r)$ denote the closed disc with center at $v$ and radius $r$ let $v=(5,0)$ for $\alpha >0$ let $X_\alpha $ be the subset
$X_\alpha =D(-v,3)\cup D(v,3)\cup \{(x,\alpha x):x\in \mathbb R\}$
find condition on $\alpha $ for $X_\alpha $ to be connected?
I know union of connected sets is connected if they have at least one point in common.Here $D(-v,3)\cap D(v,3)=\phi$
How does $\alpha $ affect the problem's solution.Any hints

A: Hint: the last part of the union is a line (going through the origin) that could connect the two disks. Think of what is the slope needed so it will touch the disks (in fact, you could only assert that one of them is intersected, the second will follow).


text:
Q: Emulate an Intersect in MySQL w/ multiple tables and Join I need to emulate an Intersect query in MySQL.
    SELECT c.cust_code, cust_fname, cust_lname
      FROM lgcustomer c JOIN lginvoice i ON c.cust_code = i.cust_code
      WHERE employee_id = 83649
    INTERSECT
    SELECT c.cust_code, cust_fname, cust_lname
      FROM lgcustomer c JOIN lginvoice i ON c.cust_code = i.cust_code
      WHERE employee_id = 83677
    ORDER BY cust_lname, cust_fname;

I have tried to use EXISTS but have not been successful. I think I am joining wrong?
    SELECT C.CUST_CODE, CUST_FNAME, CUST_LNAME
      FROM LGCUSTOMER C JOIN LGINVOICE I ON C.CUST_CODE = I.CUST_CODE
      WHERE EMPLOYEE_ID = 83649
      AND EXISTS (SELECT *
                 FROM LGCUSTOMER C JOIN LGINVOICE I ON C.CUST_CODE = I.CUST_CODE
                 WHERE EMPLOYEE_ID = 83677)
    ORDER BY CUST_LNAME, CUST_FNAME;

The tables are:
+-------------+
| Customer    |
+-------------+
| Cust_code   |
| Cust_Fname  |
| Cust_Lname  |
+-------------+
and
+--------------+
| LGINVOICE    |
+--------------+
| Cust_code    |
| Employee_ID  |
+--------------+
And I need a query to pull all the Customer codes that have an invoice from two unique Employees (83649 and 83677)

A: Hmmm . . . aggregation comes to mind:
SELECT c.cust_code, cust_fname, cust_lname
FROM lgcustomer c JOIN
     lginvoice i
     ON c.cust_code = i.cust_code
WHERE employee_id IN ( 83649, 83677 )
GROUP BY c.cust_code, cust_fname, cust_lname
HAVING COUNT(DISTINCT employee_id) = 2;

This also removes duplicates, as does INTERSECT.

A: You could emulate a intersect using the inner joij between the two subqueries
select * from  (
  SELECT c.cust_code, cust_fname, cust_lname
  FROM lgcustomer c
  JOIN lginvoice i ON c.cust_code = i.cust_code
  WHERE employee_id = 83649
) t1
INNER JOIN  (
  SELECT c.cust_code, cust_fname, cust_lname
  FROM lgcustomer c
  JOIN lginvoice i ON c.cust_code = i.cust_code
  WHERE employee_id = 83677
) t2 on t1.cust_code = t2.cust_code
ORDER BY cust_lname, cust_fname;


text:
Q: Why does the contents of this function freeze the View? iOS Swift 2 Xcode Context: Im building an app that saves a persons name & age in persistent storage then displays it on a label in a new View Controller(SecondViewController) when they re-open the app. Essentially Im trying to achieve a welcome back message that is presented through a label.
This code below is setting up myName to equal the user input from the text field, my text field is called nameEntry
Code for the Declaration of myName: NSUserDefaults.standardUserDefaults().setObject(nameEntry.text, forKey: "myName")
THIS CODE BELOW is hopefully going to take the user to the SecondViewController when the value for key myName is not equal to nothing(nil). Something within this function freezes the view, the segue identifier is called firstToSecond.
 override func viewDidAppear(animated: Bool) {
 if NSUserDefaults.standardUserDefaults().valueForKey("myName") != nil
 {

    performSegueWithIdentifier("firstToSecond", sender: nil)
 }
 }


text:
Q: Apache restart after updating php pages I have to restart apache every time i update a php file. It's not a client browser cache problem, I tried multiple browsers. The strange thing is I only need to do it with php files, html files updates fine..

A: At last... The trouble was caused by OPcache, I just deleted the config ini and now its working :)


text:
Q: Using threads and ProcessBuilder I am really unfamiliar with working with threads, so I was hoping someone could help me figure out the best way to do this.
I have a JButton in my java application...when you click on the button, I have a Process Builder that creates a process which executes some external python code. The python code generates some files, and this can take some time. When the python code is done executing, I need to load those files into an applet within my Java application.
In its current form, I have a p.waitFor() within the code that calls the external python file...so when you click on the button, the button hangs (the entire application hangs actually) until the process is done. Obviously, I want the user to be able to interact with the rest of the application while this process is going on, but as soon as it's done, I want my application to know about it, so that it can load the files into the applet.
What is the best way to do this?
Thanks for your help.

A: You should use SwingWorker to invoke the Python process on a background thread.  This way your UI will remain responsive whilst the long-running task runs.
// Define Action.
Action action = new AbstractAction("Do It") {
  public void actionPerformed(ActionEvent e) {
    runBackgroundTask();
  }
}

// Install Action into JButton.
JButton btn = new JButton(action);

private void runBackgroundTask() {
  new SwingWorker<Void, Void>() {
    {
      // Disable action until task is complete to prevent concurrent tasks.
      action.setEnabled(false);
    }

    // Called on the Swing thread when background task completes.
    protected void done() {
      action.setEnabled(true);

      try {
        // No result but calling get() will propagate any exceptions onto Swing thread.
        get();
      } catch(Exception ex) {
        // Handle exception
      }
    }

    // Called on background thread
    protected Void doInBackground() throws Exception {
      // Add ProcessBuilder code here!
      return null; // No result so simply return null.
    }
  }.execute();
}

A: You really want to create a new thread for monitoring your new process.  As you've discovered, using just one thread for both the UI and monitoring the child process will make the UI seem to hang while the child process runs.
Here's some example code that assumes the existence of a log4j logger which I think will illustrate one possible approach...
Runtime runtime = Runtime.getRuntime();
String[] command = { "myShellCommand", "firstArgument" };

try {

    boolean done = false;
    int exitValue = 0;
    Process proc = runtime.exec(command);

    while (!done) {
        try {
            exitValue = proc.exitValue();
            done = true;
        } catch (IllegalThreadStateException e) {
            // This exception will be thrown only if the process is still running
            // because exitValue() will not be a valid method call yet...
            logger.info("Process is still running...")
        }
    }

    if (exitValue != 0) {
        // Child process exited with non-zero exit code - do something about failure.
        logger.info("Deletion failure - exit code " + exitValue);
    }

} catch (IOException e) {
    // An exception thrown by runtime.exec() which would mean myShellCommand was not
    // found in the path or something like that...
    logger.info("Deletion failure - error: " + e.getMessage());
}

// If no errors were caught above, the child is now finished with a zero exit code
// Move on happily


text:
Q: How to adjust LaTeX table and format it using booktabs? I have a created a table in LaTeX which goes straight out of the page on the right side (fig shown). This is a 14 by 6 table. The kind of format I want to achieve is something like the one given in MS word.

Table in latex I've created:

The skeleton i've used:
\documentclass{article}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage[margin=1in]{geometry}
\usepackage{pdflscape}
\usepackage{graphicx}

\begin {document}
\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\begin{longtable}{@{\extracolsep{\fill}}|*{6}{c|}}
  \caption{Multipage table.}
  \label{tab:table1}\\

  \toprule
    \textbf{Author}
    & \textbf{Year of Publication}
    & \textbf{Mainly focusing problem/area}
    & \textbf{Any specific layered architecture}
    & \textbf{Main points}
    & \textbf{Any observable fault} \\

  \midrule
  \endfirsthead

 \toprule
  \textbf{Author}
    & \textbf{Year of Publication}
    & \textbf{Mainly focusing problem/area}
    & \textbf{Any specific layered architecture}
    & \textbf{Main points}
    & \textbf{Any observable fault} \\

  \midrule
  \endhead
%...My 14 rows each accommodating 6 columns…%
\bottomrule
\end{longtable}

\end{document}

How can I adjust the table in \texwidth and allow it to vertically expand? The reason I used booktabs here, is to allow the table to go on the next page (if required).
P.S.  I also used tabularx (image attached), but the problem is, table doesn't fit the whole page (last 2 rows are attached but not displayed due to margins I guess), given a reasonable format.
latex table using tabularx:

Skeleton for creating table using tabularx
\documentclass{article}

\usepackage{geometry} % more generous margins
\usepackage{tabularx}
\renewcommand*{\tabularxcolumn}[1]{>{\centering\arraybackslash}m{#1}}

\begin{document}

\begin{table}[t!]
\caption{Comparison of some unique works in IoT Transportation}
\begin{tabularx}{\textwidth}{|*{6}{X|}}
%....%
\end {tabularx}
\end{tabular}
\end{document}

For reference, ive also consulted the following links, but couldn't manage to solve my problem:
Link1
Link2
Link3


text:
Q: Adding button sound in Android I've been trying to add button sounds in my android app. They work well in all activities besides ones in which the method OnClick is separated from OnClickListener :
package com.example.quizdladzieci;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ActivityChose extends AppCompatActivity implements View.OnClickListener{
 public static final String EXTRA_NUMBER = "com.example.application.example.EXTRA_NUMBER";
 private Button buttonAdd;
 private Button buttonMinus;
 private Button buttonMultiple;
 private Button buttonDivide;
 private Button buttonDivide2;
 public int no;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_chose);

     buttonAdd = (Button) findViewById(R.id.buttonAdd);
     buttonMinus = (Button) findViewById(R.id.buttonMinus);
     buttonMultiple = (Button) findViewById(R.id.buttonMultiple);
     buttonDivide = (Button) findViewById(R.id.buttonDivide);
     buttonDivide2 = (Button) findViewById(R.id.buttonDivide2);
     final MediaPlayer mp = MediaPlayer.create(this, R.raw.sample);

     buttonAdd.setOnClickListener(this);
     buttonMinus.setOnClickListener(this);
     buttonMultiple.setOnClickListener(this);
     buttonDivide.setOnClickListener(this);
     buttonDivide2.setOnClickListener(this);

 }

 public void openActivity() {
     Intent intent;
     if(no == 1 || no == 2){
         intent = new Intent(this, CalculatorActivity.class);
         intent.putExtra(EXTRA_NUMBER, no);
         startActivity(intent);
     } else if(no == 3){
         intent = new Intent(this, ActivityMultiple.class);
         intent.putExtra(EXTRA_NUMBER, no);
         startActivity(intent);
     } else if(no == 4){
         intent = new Intent(this, ActivityDivide.class);
         intent.putExtra(EXTRA_NUMBER, no);
         startActivity(intent);
     } else if(no == 5){
        /* intent = new Intent(this, ActivityDivide2.class);
         startActivity(intent);*/
     }
 }

 @Override
 public void onClick(View v) {
     switch(v.getId()) {
         case R.id.buttonAdd:
             no = 1;
             openActivity();
             break;
         case R.id.buttonMinus:
             no = 2;
             openActivity();
             break;
         case R.id.buttonMultiple:
             no = 3;
             openActivity();
             break;
         case R.id.buttonDivide:
             no = 4;
             openActivity();
             break;
         case R.id.buttonDivide2:
             no = 5;
             openActivity();
             break;
     }
 }
}

And here's my mediaPlayer line that I put in OnCreate method:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sample);

to make the button sound working properly I put the line:
mp.start();

in the OnClick method that is usually placed inside OnClickListener, but it won't work in this specific case as you can see in the first code sample. Can you please tell me how should I reorganise the code without deleting the case method to properly put the mp.start(); so the button sound could work properly? Thank you in advance!

A:  MediaPlayer mp;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
      mp = MediaPlayer.create(this, R.raw.sample);
 }

put mp.start(); in your onclick() method and make sure the raw folder have the sample file.


text:
Q: Wordpress API - Ionic GET - The 'Access-Control-Allow-Origin' header contains multiple values '*, *' am currently building some custom API's using WordPress API,
and works great as calling from browser as this link:
https://laundrylocker-eg.com/wp-json/wp/v2/delivery-locations
response in JSON nothing goes wrong,
so from Ionic application i try to call this api to get callback this data but faced this CORS Issue and try to fix it nothing works like disable CORS in chrome and using plugin enabling CORS for all domains as development phase
CORS PLUGIN IMG

CONSOLE ERROR

Failed to load https://laundrylocker-eg.com/wp-json/wp/v2/pickup-locations/2018-04-03: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.
  core.js:1350 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

REQUEST INFORMATION

Request URL: https://laundrylocker-eg.com/wp-json/wp/v2/pickup-locations/2018-04-03
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 50.87.248.230:443
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Allow-Headers: Authorization, Content-Type, Content-Range,
Content-Disposition, Content-Description, Access-Control-Request-Method
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Allow: GET
Cache-Control: max-age=21600
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 116
Content-Type: application/json; charset=UTF-8
Date: Tue, 03 Apr 2018 12:02:28 GMT
Expires: Tue, 03 Apr 2018 18:02:28 GMT
Link: https://laundrylocker-eg.com/wp-json/; rel="https://api.w.org/"
Server: nginx/1.12.2

A: It's not that you are returning a single ACAO header with a value of *, * - it's that you are returning duplicate CORS headers, and the browser has merged them.
Somewhere in your code (or in the code of the packages you're using), the CORS headers are being added twice. My guess is that you have somehow added two CORS-enablement packages or something like that, and they're both adding CORS response headers...
Since the value of the two Access-Control-Allow-Headers and Access-Control-Allow-Methods headers are different, it should be easy enough to search for where they are being added and remove the duplication.


text:
Q: Can't import com.google.maps.android:android-maps-utils via gradle I tried to import com.google.maps.android:android-maps-utils to my project in Android Studio 0.5.4.
I get this Gradle Information and Error:
Information:[C:\Users\Gast1_000\android studio projects\GeoPicture\app\build\exploded-aar\com.google.maps.android\android-maps-utils\0.3\AndroidManifest.xml:2, C:\Users\Gast1_000\android studio projects\GeoPicture\app\build\exploded-aar\com.google.android.gms\play-services\4.3.23\AndroidManifest.xml:3] Main manifest has <uses-sdk android:minSdkVersion='8'> but library uses minSdkVersion='9'

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merging failed. See console for more info.

My build.gradle:
dependencies {
    compile 'com.android.support:support-v13:+'
    compile 'com.google.android.gms:play-services:4.3.+'
    compile 'com.google.maps.android:android-maps-utils:0.3'
}

Project Manifest.xml
<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="19" />

I tried to change the minSdk version manually in the manifest of the maps-utils, but with each gradle sync it chnage it back.
Is there any other possiblility to add the library in AS 0.5.4?

A: This seems to be a bug at the moment: https://github.com/googlemaps/android-maps-utils/issues/60
If Gradle overwrites you changes, just use Gradle to do these changes (as suggested in the above link) ;)
Add the following code block to your build file inside the android { .. } block.
applicationVariants.all{ variant ->
  variant.processManifest.doFirst {
    File manifestFile = file("${buildDir}/exploded-aar/com.google.maps.android/android-maps-utils/0.3/AndroidManifest.xml")
    if (manifestFile.exists()) {
      String content = manifestFile.getText('UTF-8')
      content = content.replaceAll(/minSdkVersion="8"/, 'minSdkVersion=\"9\"')
      manifestFile.write(content, 'UTF-8')
    }
  }
}

This of course isn't the best solution, but should do it until the bug is fixed:

*

*https://code.google.com/p/android/issues/detail?id=66109 (Ignore minSdkVersions when matching libraries)


text:
Q: How do I install 'containers' features on Windows server 2019 Build 1809? I recently installed Windows Server 2019, but I noticed it doesn't have an option for installing Containers.    I assumed any Windows Server OS would have the ability to add a Containers channel, however I don't see anything online to do this.
This version is actually "Microsoft Hyper-V Server", however, its not clear that Hyper-V server is fundamentally different from regular Windows Server OS installations.

*

*Is there a way to enable the 'Containers' feature on Microsoft Hyper-V Server 2019 (1809) ?

*Is there a way to upgrade Micrsoft's Hyper-V Server to a Containers compatible 1909 server ?

*What is the fundamental difference between Microsoft's Hyper-V Server and a regular Microsoft 2019 Windows Server OS?

Note: I installed this onto a laptop over a USB stick, and did a lot of work to upgrade drivers and so on to support laptop features like Wi-Fi, hence my reluctance to completely reinstall the operating system .

A: The key difference between a Windows Server and a Windows Hyper-V Server is that the latter only contains enough infrastructure to be a host to a number of Hyper-V virtual machines.
I'm afraid the upgrade path is to replace it with a full version of Windows Server 2019.


text:
Q: How to convert a pandas DataFrame to a list of dictionaries where NaN values are omitted? This question is similar to Pandas DataFrame to List of Dictionaries, except that the DataFrame is not 'full': there are some nan values in it. Suppose I generate a DataFrame from a list of dictionaries like so:
import pandas as pd

data = [{'foo': 1, 'bar': 2}, {'foo': 3}]
df = pd.DataFrame(data)

so that the resulting df looks like
   bar  foo
0  2.0    1
1  NaN    3

I would like a function which turns df back into the original data list of dictionaries. Unfortunately,
assert df.to_dict('records') == data

fails because the former is
[{'bar': 2.0, 'foo': 1.0}, {'bar': nan, 'foo': 3.0}]

with the additional 'bar': nan key-value pair in the second item. How can I get back the original data?

A: Here's another way of doing it:
df.T.apply(lambda x: x.dropna().to_dict()).tolist()

Output:
[{'bar': 2.0, 'foo': 1.0}, {'foo': 3.0}]

A: I managed to fix the problem with some 'post-processing':
import pandas as pd

data = [{'foo': 1, 'bar': 2}, {'foo': 3}]
df = pd.DataFrame(data)

result = df.to_dict('records')
result2 = [{k: v for k, v in row.items() if not pd.isnull(v)} for row in result]

assert result2 == data

More elegant solutions are welcome.

A: IIUC
1st Option
df.apply(lambda x: [x.dropna().to_dict()], axis=1).sum()
Out[860]: [{'bar': 2.0, 'foo': 1.0}, {'foo': 3.0}]

2nd Option
df.stack().groupby(level=0).apply(lambda x: [x.reset_index(level=0,drop=True).to_dict()]).sum()
Out[867]: [{'bar': 2.0, 'foo': 1.0}, {'foo': 3.0}]


text:
Q: C# Lambda Operator In C#, when writing lambda expressions, is there a single-character version of the => lambda operator?
I know that it isn't very hard to type =>, but still...

A: No.  The two characters (=>) are required.  This is the way the language was written and designed.
Just be thankful - it's far shorter than the older delegate { ... }  syntax in most cases.


text:
Q: Swift struct extension add initializer I'm trying to add an initializer to Range.
import Foundation

extension Range {
    init(_ range: NSRange, in string: String) {
        let lower = string.index(string.startIndex, offsetBy: range.location)
        let upper = string.index(string.startIndex, offsetBy: NSMaxRange(range))
        self.init(uncheckedBounds: (lower: lower, upper: upper))
    }
}

But, the last line has a Swift compiler error.

Cannot convert value of type '(lower: String.Index, upper: String.Index)' (aka '(lower: String.CharacterView.Index, upper: String.CharacterView.Index)') to expected argument type '(lower: _, upper: _)'

How do I get it to compile?

A: The problem is even though String.Index does conform to Comparable protocol, you still need to specify the Range type you want to work with public struct Range<Bound> where Bound : Comparable {}
Note: As NSString uses UTF-16, check this and also in the link you've referred to, your initial code does not work correctly for characters consisting of more than one UTF-16 code point. The following is the updated working version for Swift 3.
 extension Range where Bound == String.Index {
    init(_ range: NSRange, in string: String) {
        let lower16 = string.utf16.index(string.utf16.startIndex, offsetBy: range.location)
        let upper16 = string.utf16.index(string.utf16.startIndex, offsetBy: NSMaxRange(range))

        if let lower = lower16.samePosition(in: string),
            let upper = upper16.samePosition(in: string) {
            self.init(lower..<upper)
        } else {
            fatalError("init(range:in:) could not be implemented")
        }
    }
}

let string = "❄Let it snow! ☃"

let range1 = NSRange(location: 0, length: 1)
let r1 = Range<String.Index>(range1, in: string) // ❄

let range2 = NSRange(location: 1, length: 2)
let r2 = Range<String.Index>(range2, in: string) // fatal error: init(range:in:) could not be implemented

To answer the OP's comment: The problem is an NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. Unicode scalar values that make up a string's contents can be up to 21 bits long. The longer scalar values may need two UInt16 values for storage.
Therefore, some letters like ❄ takes up two UInt16 values in NSString but only one in String. As you pass an NSRange argument to the initializer, you may expect it to work correctly in NSString.
In my example, the results for r1 and r2 after you convert string to utf16 are '❄' and a fatal error. Meanwhile, the results from your original solution are '❄L' and 'Le', respectively. Hopefully, you see the difference.
In case you insist with the solution without converting to utf16, you can take a look at the Swift source code to make decision. In Swift 4, you will have the initializer as a built-in lib. The code is as follows.
extension Range where Bound == String.Index {
  public init?(_ range: NSRange, in string: String) {
    let u = string.utf16
    guard range.location != NSNotFound,
      let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
      let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
      let lowerBound = String.Index(start, within: string),
      let upperBound = String.Index(end, within: string)
    else { return nil }

    self = lowerBound..<upperBound
  }
}

A: You need to constrain your range initializer to where Bound is equal to String.Index, get your NSRange utf16 indexes and find the same position of the string index in your string as follow:
extension Range where Bound == String.Index {
    init?(_ range: NSRange, in string: String) {
        guard
            let start = string.utf16.index(string.utf16.startIndex, offsetBy: range.location, limitedBy: string.utf16.endIndex),
            let end = string.utf16.index(string.utf16.startIndex, offsetBy: range.location + range.length, limitedBy: string.utf16.endIndex),
            let startIndex = start.samePosition(in: string),
            let endIndex = end.samePosition(in: string)
        else {
            return nil
        }
        self = startIndex..<endIndex
    }
}

A: The signature for that method requires a "Bound" type (at least in swift 4)
Since Bound is just an associated type of "Comparable" and String.Index conforms to it, you should just be able to cast it.
extension Range {
    init(_ range: NSRange, in string: String) {
        let lower : Bound = string.index(string.startIndex, offsetBy: range.location) as! Bound
        let upper : Bound = string.index(string.startIndex, offsetBy: NSMaxRange(range)) as! Bound

        self.init(uncheckedBounds: (lower: lower, upper: upper))
    }
}

https://developer.apple.com/documentation/swift/rangeexpression/2894257-bound


text:
Q: How to sort a single array element to an associative with the same key using PHP? I have 2 arrays.
My First array is:
$a1 = array("red010", "blue210", "green101", "black210", "orange120");

My Second array is:
$a2 = array(
    'arr1' =>
    array(
        'id' => 128,
        'level' => 1,
        'name' => 'blue210',
    ),
    'arr2' =>
    array(
        'id' => 220,
        'level' => 2,
        'name' => 'green101',
    ),
    'arr3' =>
    array(
        'id' => 124,
        'level' => 1,
        'name' => 'orange120',
    ),
    'arr4' =>
    array(
        'id' => 231,
        'level' => 1,
        'name' => 'black210',
    ),
    'arr5' =>
    array(
        'id' => 221,
        'level' => 3,
        'name' => 'red010',
    ),
);

I want to sort my second array according to the first array values. That means I need to sort my second array based on the first array values.
My result array looks like this:
$a2 = Array
        (
            [arr5] => Array
                (
                    [id] => 221
                    [level] => 3
                    [name] => red010
                )
             [arr1] => Array
                (
                    [id] => 128
                    [level] => 1
                    [name] => blue210
                )
             [arr2] => Array
                (
                    [id] => 220
                    [level] => 2
                    [name] => green101
                )
              [arr4] => Array
                (
                    [id] => 231
                    [level] => 1
                    [name] => black210
                )

              [arr3] => Array
                (
                    [id] => 124
                    [level] => 1
                    [name] => orange120
                )
    )

Is it possible to sort it like this way? One is a single-dimensional array. The second array is the associative array.


text:
Q: how can I set zoom level of map according to values of all lat long ,so I can see all that places in map iPhone? I am getting lat longs of different locations,and I want to set zoom (span) in a such a way that I can see all (locations) pins on a map.

A: Pretty much a dup of Positioning MKMapView to show multiple annotations at once.
I found https://stackoverflow.com/a/7642526/191215 the most elegant.


text:
Q: Eclipse - An internal error occurred during: "Compute launch button tooltip" I launched Eclipse earlier to jot down a snippet and was faced with the following as an error when I tried to run a fresh project:

An internal error occurred during: "Compute launch button tooltip".

That popup window shows as soon as I mouse-over the run icon in the top bar, or if I right click on the class in the explorer window and select any of the run/debug options.
After doing some research on the error, I see several people who posted similar messages but they all have been fresh installs of Eclipse. So note that this is not a fresh install, and that Eclipse was working fine earlier today. Also note that not only does my new project not run (with the normal main method), but projects I was running earlier have all stopped working with the same error.
Finally, also be aware that after seeing other people's suggestions on fixing this, one specifically said to select run configurations from the top of the page run menu. When I selected run configurations from this dropdown, I got the following message:

Exception occurred creating launch configuration tabs
  Reason: Plug-in org.eclipse.jdt.debug.ui was unable to load class org.eclipse.jdt.internal.debug.ui.launcher.LocalJavaApplicationTabGroup

After that message, the run window opens but all of the tabs are missing. Like where you can set the display width and height, and the other tabs, they are all missing from the window now.
I was using Eclipse trouble free earlier today and I am sure no updates took place between when Eclipse was working and now. My question is of multiple parts: What is wrong in a nutshell? What could have caused this?

A: Got this from another site of some guy who got this same error after upgrading.
Worked for me as well.
Apparently putting the following line in your eclipse.ini helps:
-Dcom.ibm.icu.util.TimeZone.DefaultTimeZoneType=ICU

A: Try setting the launch properties in:
Window>Preferences>Run/Debug(Expand)>Launching(Click)

Under launch Operations menu set it to:
Always launch the previously launched application

Click:
Apply>Ok

A: I never found out what went wrong, but a reinstall of eclipse fixed it. All projects survived seemingly undamaged.
 Thanks for the reply on the .ini but that did no good.

A: I had same error today - in an eclipse installation (Juno SR2 64bit) that has been running fine for months.
0: There were no changes on svn for my projects since yesterday (when it was running fine).
1: I restored the workspace from a 'Windows 7 -> Properties -> previous copy' backup. This failed because the directory structure of the '.metadata' contains folders with a deeper structure than is supported.
2: I restored the workspace from a overnight archive (gzipped so file depth is not an issue).
This had no effect.
3: I tried to restore the eclipse installation directory (which seems to be updated an awful lot) from a 'Windows 7 -> Properties -> previous copy' backup. Again this failed - because of folder-depth issues (Note: it is installed in the root directory of my disk - so there is actually no way to use a restore on this installation!)
4: Had to delete the .metadata from my workspace and reinstall eclipse (and all the additional plugins), and re-import my projects, and setup all the servers, and android, etc, which took many hours.
The moral of the story? Backup both your workspace AND the eclipse installation every night manually. Windows Restore will NOT save you. Backing up your workspace is NOT enough.

A: I had the same problem using eclipse mars. I cleared the folder .recommenders\index
And that solved my issue.
Hope it helps.

A: incase you are having the eclipse files which you have downloaded from the official site .Just extract those file in the same folder where your previous eclipse was installed and select replace all.
best solution

A: I also encountered this issue, the reason why this issue occurred on my project was due to I was missing the JRE System Library in the root folder of my project.
To solve this issue, make sure you have the libraries like JRE System Libraries on the root folder of your project.


text:
Q: Scope of imported macro-generated code in Elixir I am going through Saša Jurić's fantastic series on macros, and while running the following piece of code, I encountered something that confused me:
defmodule Plug.Router do
  defmacro get(route, body) do
    quote do
      defp do_match("GET", unquote(route), var!(conn)) do
        unquote(body[:do])
      end
    end
  end
end

defmodule MyRouter do
  import Plug.Router

  def match(type, route) do
    do_match(type, route, :dummy_connection)
  end

  get "/hello", do: {conn, "Hi!"}
  get "/goodbye", do: {conn, "Bye!"}

  MyRouter.match("GET", "/hello") |> IO.inspect
  MyRouter.match("GET", "/goodbye") |> IO.inspect
end

My questions are:

*

*in which module is the do_match/3 function injected? Is it in the Plug.Router module, or in the MyRouter one? Further down in the article, it's mentioned that use and require inject the code in the caller's module. Is this valid for imported macros too?

*where in Elixir's code should I look for the implementation of this behaviour?

*is there an easy way of inspecting the structure of a module after expansion? Something equivalent to Macro.to_string/3, but for Modules?

A: The functions generated by the macro will be defined in MyRouter
If you require a module, its macros will be made available to the caller module. If you import a module, its macros and functions will additionally be accessible without having to use the module name as prefix. See the getting started guide on alias, require and import for more details.
require and import are quite low level features of Elixir, so they are implemented in Erlang directly. A fair amount of the import and require logic can be found here.
I am not aware of a way of introspecting these things, since macros basically leave no trace in the compiled code. It's part of the beauty of macros that they will not introduce any additional overhead to your code. However, you can check which functions are in a module after macro expansion with MyRouter.__info__(:functions)


text:
Q: whether a Gramin matrics is symetric or not? A Gramin matrix is defined as
$$ G^c(t_0,t_f)=\int_{t_0}^{t_f} \exp\bigl((t_0-t)A\bigr) BB^T \Bigl(\exp\bigl((t_0-t)A)\Bigr)^T \,dt$$ where ${}^T$ is for transpose of matrices. How can i prove it?

A: Note that writing
$$ C(t) := \exp\bigl((t_0-t)A\bigr)B $$
your integrand is $I(t) := C(t)C(t)^T$, hence is symmetric as
$$ I(t)^T = \bigl(C(t)C(t)^T\bigr)^T = C(t)^{TT}C(t)^T = C(t)C(t)^T= I(t) $$
So
$$ G^c(t_0,t_f)^T = \left(\int_{t_0}^{t_f} I(t)\,dt\right)^T = \int_{t_0}^{t_f} I(t)^T\,dt = \int_{t_0}^{t_f} I(t)\, dt = G^c(t_0, t_f) $$
is symmetric.

Addendum: $G^c(t_0, t_f)$ is allways positive semidefinite, as for any $\xi$:
$$\xi^T I(t)\xi = \bigl(C(t)^T\xi\bigr)^T\bigl(C(t)^T\xi\bigr) \ge 0 $$


text:
Q: How to read a string into a void pointer? I have been trying to read an input as string from the user inside a void pointer in C. SO i wrote something like the following:
void *ptr;
ptr = calloc(100,sizeof(char));
printf("Enter the string: ");
fgets(*((char *)ptr),100,stdin);
printf("You entered ");
puts(*((char *)ptr));

I know I may not be doing it the right way, so can anybody please help me show the right way of taking a string input in a void pointer?
I want something as
input:- Enter the string: welcome user
output:- You entered: welcome user

A: Just convert the void* to a char*:
void *ptr;
ptr = calloc(100,sizeof(char));
printf("Enter the string: ");
fgets((char*)ptr,100,stdin);
printf("You entered ");
puts((char*)ptr);

fgets and puts take a pointer as first argument, so you could use (char*)ptr to convert the pointer.
If you write *((char*)ptr) you treat the void pointer as a char pointer, but also dereference it with * which will give you the first character. This is not what you want here.

A: You need to remove the (char *) casts. Try this:
void *ptr;
ptr = calloc(100,sizeof(char));
printf("Enter the string: ");
fgets((char *)ptr,100,stdin);
printf("You entered ");
puts((char *)ptr);

A: You are dereferencing the pointer when you pass it to fgets and fputs which means you pass the value of the first character in the memory location. Since you used calloc for the allocation you pass '\0' (the null character, zero).
Your ptr (and also (char *)ptr) points to some memory, i.e. its value is an address, a point in the RAM of your computer. fgets will copy chars from the console input to that memory location, byte by byte. Your expression *((char *)ptr) which you pass as parameter to fgets is, by contrast, the value stored at that location. After calloc() that value is zero, i.e. the character '\0'. Fgets thinks that's a pointer, tries to access the memory at address 0, and crashes. The same would happen with fputs, because under modern PC operating systems even a read access at "weird" addresses is not allowed for user programs. The solution is, as the others pointed out correctly, to omit the dereferencing "*".
By the way, did you not get a compiler warning? While C is not really type safe, it does have function prototypes, and most compilers warn against wrong parameter types when they are called.

A: What you basically want cannot be achieved due to your arguments in fgets().
As the function fgets() take three arguments
1.pointer to the first cell of memory at where to store the data.
2.No of characters to be written to memeory.
3.stream pointer,from where to read.

But what you are doing wrong is with first argument,as you are not passing a pointer to fgets().You are passing *((char *)ptr) it is of type char because of your unnecessary derefferencing.Removing external * will cure it because its type now becomes char * and you can use it as a legal argument for fgets().


text:
Q: MySQL Sorting using Lpad + Floating Point String I have some strings that have a version number at the end of the string. I need to sort them.
i.e.
1
5
6
L1
L2
L123
L300
L500
L123.5
L300.5

If I exclude the .x rows I can get these to sort using LPAD but the version number is stumping me. Looking to get the data to be interpreted as follows so I can sort correctly but I am failing miserably.
0001.00
0005.00
0006.00
00L1.00
00L2.00
L123.00
L300.00
L500.00
L123.50
L300.50

A: Assuming that the length of version number is the same, the following will give you what you are looking for:
use DBName;
create table versions(
   Id int not null auto_increment,
   primary key(Id),
   ver varchar(20) not null
)TYPE=MyISAM;

insert into versions(ver) values('1');
insert into versions(ver) values('5');
insert into versions(ver) values('6');
insert into versions(ver) values('L1');
insert into versions(ver) values('L2');
insert into versions(ver) values('L123');
insert into versions(ver) values('L300');
insert into versions(ver) values('L500');
insert into versions(ver) values('L123.5');
insert into versions(ver) values('L300.5');

Select CONCAT( LPAD(ver, 4, '0'),
               Case
                    When dot ='.'
                    Then CONCAT('.', SUBSTRING(ver, 6, 1), '0')
               Else '.00'
               End
              ) VersionNumber
From
(
   Select ver, SUBSTRING(ver,5,1) dot From versions
) as sub
Order by VersionNumber;

This willl gives you:
0001.00
0005.00
0006.00
00L1.00
00L2.00
L123.00
L123.50
L300.00
L300.50
L500.00


text:
Q: Reduce representation of $SL_n$ Let $a$ be an arbitrary element of $SL_n$. Consider next representation of $SL_n$. $T_a: SL_n \to GL_n,\;x \mapsto axa^{-1}$. I was told that this is a reducible representation. So I need to express this representation as a sum of irreducible ones. I've read that I need to find an invariant subspaces of this representation. And this is the part where I stucked.
Thanks.

A: We can find two invariant subspaces: $<E>$ and $A=\{M\in Mat_{n\times n} : trM=0\}$.
It's easy to see that $V=<E> \oplus A$. Now we need to show that there is no proper invariant subspace in A. So we find a highest weight vector: $\begin{bmatrix}0*0 1\\ 0*00\\0*00\\0*00\end{bmatrix}$. As there is only one highest weight vector, there exist only one invariant subspace, which is our A.


text:
Q: Exchange distribution group alias restriction - can it start with an @ character? At a previous employer a few years ago, all Exchange distribution groups were created such that the first character of the alias (the name you see in Outlook) began with an @ character. The distribution group's email address was often the same name WITHOUT the leading @ character. This convention made it very easy to identify distribution groups from within Outlook.
For instance, we had a distribution group for all developers with the alias @DevelopmentTeam and the email address DevelopmentTeam@companyxyz.com.
I'm now working at a different company, and would like to implement the same kind of thing, but I'm being told that Exchange doesn't allow distribution group alias to start with an @ character.
Either I'm not remembering things correctly, I'm being mislead, and I need to know which it is.

A: AFAIK, the Alias cannot begin with nor include the @ character. The Display Name can. My guess is that you're conflating the Alias and the Display Name from your previous Exchange environment.


text:
Q: When installing Kivy on Windows 10, error message "fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory" Windows 10, Python 3.6, Kivy 1.9.1
Some of the answers on this site have been really helpful. It looks like what I need to do is to install glew, but oddly it seems harder than it looks. Here's my output on the command line when trying to install kivy with the command
python -m pip install kivy

I'm going through the installation instructions in https://kivy.org/docs/installation/installation-windows.html#installation-windows
Here is the end of the output from the command line:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\ProgramData\Anaconda3\include -IC:\ProgramData\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\winrt" /TcC:\Users\Andrew\AppData\Local\Temp\pip-build-8icy8c14\kivy\kivy\graphics\context.c /Fobuild\temp.win-amd64-3.6\Release\Users\Andrew\AppData\Local\Temp\pip-build-8icy8c14\kivy\kivy\graphics\context.obj
      context.c
      c:\users\andrew\appdata\local\temp\pip-build-8icy8c14\kivy\kivy\graphics\gl_redirect.h(8): fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory
       error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\bin\HostX86\x64\cl.exe' failed with exit status 2

Command "C:\ProgramData\Anaconda3\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Andrew\AppData\Local\Temp\pip-build-8icy8c14\kivy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Andrew\AppData\Local\Temp\pip-mpef3eip-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Andrew\AppData\Local\Temp\pip-build-8icy8c14\kivy\
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools>

I've tried installing glew from here http://glew.sourceforge.net/index.html . I have unpacked it a few times and tried to paste the relevant files in the right place a few times, but it hasn't helped. I've also tried some suggestions I found here and on other sites, but they haven't helped either.
I also tried to do this, but I'm going to need it in plain English. I don't understand a lot of it.
Help is much appreciated! I've been trying to get kivy installed for like a full day and a half, and I'm looking forward to getting it running.

A:
Python 3.6, Kivy 1.9.1
I'm going through the installation instructions in https://kivy.org/docs/installation/installation-windows.html#installation-windows

and apparently you don't see this pretty warning almost on the top of the page:

Support for Python 3.5 and higher isn't available with the current stable version (1.9.1). Compile the master branch or use the nightly wheels.

Which means that even if you had the headers that are also mentioned on the same page, but in the section for compiling which is where you get if you'd read the warning it still wouldn't compile that way because the code in version 1.9.1 doesn't support Python 3.5 or higher.
So, you want to install Kivy on Python 3.6. Let's go once again through the docs :P
The warning tells you that you need master branch (meaning a GitHub repository branch) and sends you to two parts of the docs:

*

*https://kivy.org/docs/installation/installation-windows.html#use-development-kivy

*https://kivy.org/docs/installation/installation-windows.html#nightly-wheel-installation
Using the development version requires a compiler which for 3.6 is either the whole Visual Studio or it's smaller "Build Tools" subpart. That's pretty much 4GB(or 8?) just for the option to compile. Nah, generally you don't want to go through that, but apparently you already have the beast downloaded, so... let's hope you didn't paste the glew folder right into the compiler and it'll still work. These are the headers you need:
pip install kivy.deps.glew_dev kivy.deps.sdl2_dev

If you by any change unpacked the glew files into the compiler folders directly, well, you might not be able to compile Kivy after such a step. If that's correct, then you successfully broke the compiler especially if you've overwrote some files in it.
So, the second option then! The wheels are already compiled packages of Kivy, therefore no compiler is necessary (nor the _dev headers) and the installation is like ~1 minute max with a slow connection. Let's choose the correct wheel for you - from temp.win-amd64-3.6 in the log I guess you have Python 3.6 64bit version therefore:
pip install https://kivy.org/downloads/appveyor/kivy/Kivy-1.9.2.dev0-cp36-cp36m-win_amd64.whl

If Kivy doesn't install after that, try to use pip install -I to overwrite whatever you installed.

A: On one windows 10 machine pip install of glew it worked fine. The other I had to download from glew and manually add them to the folders.


text:
Q: WordNet table explanation I'am trying to understand the table of WordNet database so I can use it in a machine learning project, I was able to understand the explanation of table that I found on this Wordnet explantion but have trouble to understand the following:
Table


text:
Q: Automatically create i18n directory for VSCode extension I am trying to understand the workflow presented in https://github.com/microsoft/vscode-extension-samples/tree/master/i18n-sample for localizing Visual Studio Code extensions.
I cannot figure out how the i18n directory gets created to begin with, as well as how the set of string keys in that directory get maintained over time.
There is one line in the README.md which says "You could have created this folder by hand, or you could have used the vscode-nls-dev tool to extract it."...how would one use vscode-nls-dev tool to extract it?
What I Understand
I understand that you can use vscode-nls, and wrap strings like this: localize("some.key", "My String") to pick up the localized version of that string at runtime.
I am pretty sure I understand that vscode-nls-dev is used at build time to substitute the content of files in the i18n directory into the  transpiled JavaScript code, as well as creating files like out/extension.nls.ja.json
What is missing
Surely it is not expected that: for every file.ts file in your project you create an i18n/lang/out/file.i18n.json for every lang you support...and then keep the set of keys in that file up to date manually with every string change.
I am assuming that there is some process which automatically goes "are there any localize("key", "String") calls in file.ts for new keys not yet in file.i18n.json? If so, add those keys with some untranslated values". What is that process?

A: I have figured this out, referencing https://github.com/Microsoft/vscode-extension-samples/issues/74
This is built to work if you use Transifex for your translator. At the bare minimum you need to use .xlf files as your translation file format.
I think that this is best illustrated with an example, so lets say you wanted to get the sample project working after you had deleted the i18n folder

*

*Step 1: Clone that project, and delete the i18n directory

*Step 2: Modify the gulp file so that the compile function also generates nls metadata files in the out directory. Something like:

    function compile(buildNls) {
        var r = tsProject.src()
        .pipe(sourcemaps.init())
            .pipe(tsProject()).js
            .pipe(buildNls ? nls.rewriteLocalizeCalls() : es.through())
            .pipe(buildNls ? nls.createAdditionalLanguageFiles(languages, 'i18n', 'out') : es.through())
            .pipe(buildNls ? nls.bundleMetaDataFiles('ms-vscode.node-debug2', 'out') : es.through())
            .pipe(buildNls ? nls.bundleLanguageFiles() : es.through())

*

*Step 3: Run the gulp build command. This will generate several necessary metadata files in the out/ directory

*Step 4: Create and run a new gulp function to export the necessarry translations to the xlf file. Something like:

    gulp.task('export-i18n', function() {
        return gulp.src(['package.nls.json', 'out/nls.metadata.header.json', 'out/nls.metadata.json'])
            .pipe(nls.createXlfFiles("vscode-extensions", "node-js-debug2"))
            .pipe(gulp.dest(path.join('vscode-translations-export')));
    }

*

*Step 5: Get the resulting xlf file translated. Or, add some dummy values. I cant find if/where there is documentation for the file format needed, but this worked for me (for the extension):

    <?xml version="1.0" encoding="utf-8"?>
    <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
      <file original="package" source-language="en" target-language="ja" datatype="plaintext"><body>
        <trans-unit id="extension.sayHello.title">
          <source xml:lang="en">Hello</source>
          <target>JA_Hello</target>
        </trans-unit>
        <trans-unit id="extension.sayBye.title">
          <source xml:lang="en">Bye</source>
          <target>JA_Bye</target>
        </trans-unit>
      </body></file>
      <file original="out/extension" source-language="en" target-language="ja" datatype="plaintext"><body>
        <trans-unit id="sayHello.text">
          <source xml:lang="en">Hello</source>
          <target>JA_Hello</target>
        </trans-unit>
      </body></file>
      <file original="out/command/sayBye" source-language="en" target-language="ja" datatype="plaintext"><body>
        <trans-unit id="sayBye.text">
          <source xml:lang="en">Bye</source>
          <target>JA_Bye</target>
        </trans-unit>>
      </body></file>
    </xliff>

*

*Step 6: Stick that file in some known location, let's say /path/to/translation.xlf. Then add/run another new gulp task to import the translation. Something like:

    gulp.task('i18n-import', () => {
        return es.merge(languages.map(language => {
            console.log(language.folderName)
            return gulp.src(["/path/to/translation.xlf"])
                .pipe(nls.prepareJsonFiles())
                .pipe(gulp.dest(path.join('./i18n', language.folderName)));
        }));
    });

*

*Step 7: Run the gulp build again.

The i18n/ directory should now be recreated correctly! Running the same build/export/translate/import/build steps will pick up any new changes to the localize() calls in your TypeScript code
Obviously this is not perfect, there are a lot of hardcoded paths and such, but hopefully it helps out anyone else who hits this issue.


text:
Q: Open excel from Word and perform action I want to create a marco which enables me to add something in an excel sheet while working in Word. I managed to get something working which opens an excel file from word:
  Dim excelApp As Excel.Application
  Dim openExcel As Workbook
  Dim var1 As Integer

  Set excelApp = New Excel.Application
  Set openExcel = excelApp.Workbooks.Open("C:\Documents and Settings\aa471714\Desktop\Book1.xls")
  excelApp.Visible = True

But now I want to add the code which should happen in excel right after. But when I add the relevant code:
Sheets("Sheet2").Select
Range("A4").Select

This does not seem to work. Am I overlooking something?
Dear regards,
Marc

A: Keep in mind that in macro created in Word default application is Word Application all the time. Therefore each time you want to make any operation in Excel you need to state it by adding full references to Excel Application (or other Excel object as presented below).
Keep also in mind that you will need to add extended object hierarchy in such situation.
Back to your code- adding this kind of object references should solve the problem:
(incl. some additional re-editions)
'comments referring to Object hierarchy
openExcel.Sheets("Sheet2").Select   'OK because sheet is an object below Workbook
excelApp.Range("A4").Select    'NEW, Range is object below Application or...
openExcel.Sheets("Sheet2").Range("A4").Select   'IMPROVED, Range is object below sheet
'general- Range.Select works only for activesheet!!

Object openExcel keeps reference to Excel application which is represented by excelApp.


text:
Q: Angular5 providers based DI issue I have a custom class (non module) in angular 5, i would like to use this class implements the CanActivate interface because i would like to use this as route guard.
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { Router } from '@angular/router';

@Injectable()
export class TokenRequiredRouteGuard  implements CanActivate {

    constructor(private router: Router){}

    canActivate(){
        let token = localStorage.getItem('token');
        if(!token){
            this.router.navigate['/splashpage'];
            return false;
        }else{
            return true;
        }
    }
}

In the AppModule i add the class in the providers section so to make it picked up by angular's DI:
    NgModule({
  declarations: [
    AppComponent,
    SplashpageComponent
  ],
  imports: [
    RouterModule.forRoot(appRoutes,{ useHash: true }),
    BrowserModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    CalendarModule,

  ],
  providers: [TokenRequiredRouteGuard],
  bootstrap: [AppComponent],

})

But then when this route comes to action at run time i get:
core.js:1448 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[TokenRequiredRouteGuard]:
  StaticInjectorError(Platform: core)[TokenRequiredRouteGuard]:
    NullInjectorError: No provider for TokenRequiredRouteGuard!
Error: StaticInjectorError(AppModule)[TokenRequiredRouteGuard]:
  StaticInjectorError(Platform: core)[TokenRequiredRouteGuard]:
    NullInjectorError: No provider for TokenRequiredRouteGuard!

I have found several incidents on github opened for similar problems but they all refer to adding the import in the imports section in @NgModule but my class isn't a module.
Any idea what i am doing wrong?

A: Accoring to the documentation you posted above, you are supposed to provide the CanActivate implementation as follows:
import { TokenRequiredRouteGuard}                from '../tokenRequiredRouteGuard.service';

const routesConfig: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [TokenRequiredRouteGuard],
    children: [
      {
        path: '',
        children: [
          { path: 'test1', component: Test1},
          { path: 'test2', component: Test2}
        ],
      }
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routesConfig)
  ],
  exports: [
    RouterModule
  ]
})
export class AppModule { }

i.e. you are not supposed to declare it as a provided, but rather provide it as a router configuration for the property "canActivate"


text:
Q: why textbox is not auto update in java? below my code i code wright for gps is give me coninue data on 4800 baud rate this data display continue by "System.out.println(st)" but same data not dispaly in a.setText(st) where a is Textbox variable. some know how to my textbox update like System.out.println line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.comm.*;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * test.java
 *
 * Created on Mar 11, 2013, 9:08:52 AM
 */
/**
 *
 * @author DJ ROCKS
 */
public class test extends javax.swing.JFrame {
    public boolean bp=true;

    /** Creates new form test */
    public test() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ok = new javax.swing.JButton();
        a = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ok.setText("ok");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        a.setText(" ");
        a.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(238, 238, 238)
                        .addComponent(ok)))
                .addContainerGap(124, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(67, 67, 67)
                .addComponent(ok)
                .addContainerGap(160, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void okActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        if(evt.getSource()==ok)
        {
            CommPortIdentifier portId = null;
String wantedPortName="COM16";

 Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();

while(portIdentifiers.hasMoreElements())
{
    CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
    if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
       pid.getName().equals(wantedPortName))
    {
        portId = pid;
        break;
    }
}
if(portId == null)
{
    System.err.println("Could not find serial port " + wantedPortName);
    System.exit(1);
}
else
{
    System.out.println("system find gps reciever");
}
SerialPort port = null;
try {
    port = (SerialPort) portId.open(
        "RMC",
        1);
    System.out.println("all are ok");
} catch(PortInUseException e) {
    System.err.println("Port already in use: " + e);
    System.exit(1);
}
            try {
                //int i=Integer.parseInt(new vps().baud_rate.getItemAt(new vps().baud_rate.getItemCount()));
               port.setSerialPortParams(
                   4800,
                   SerialPort.DATABITS_8,
                   SerialPort.STOPBITS_1,
                   SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
            }

BufferedReader is = null;

try {
  is = new BufferedReader(new InputStreamReader(port.getInputStream()));
  System.out.println("data is ok");
} catch (IOException e) {
  System.err.println("Can't open input stream: write-only");
  is = null;
}

 //this is variable is ouside of class and define by public it work
    while(true)
    {

String st = null;
                try {
                    st = is.readLine();
                } catch (IOException ex) {
                    Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
                }

       System.out.println(st);
        //st = st.replace(st, "");
      a.setText(st);
      try
      {

          Thread.sleep(1000);
      }
      catch(InterruptedException ie)
      {
          System.out.printf(ie.getMessage());
      }
}
/*if (is != null) try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
            }

if (port != null) port.close();
*/
}

    }

    private void aActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField a;
    private javax.swing.JButton ok;
    // End of variables declaration
}

A: It seems as though you may be trying to rewrite the same String. I would try to call a "get" method that returns a String instead of referring to the variable "st". I do this to avoid a situations in which the program will try to rewrite the String since Strings are immutable.
I would try something like this:
private String getString()
{
try {
    String st = new String(""+is.ReadLine());
    return st;
    } catch (IOException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}

Use this to refer to the new String from BufferedReader "is":
   a.setText(getString());

Also, it looks as if you have a code block within comment lines here:
/*if (is != null) try {
            is.close();
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
      if (port != null) port.close();
}*/

Please correct me if I'm wrong here.


text:
Q: How to generate a video using cv2 python I have a project to do. I have scraped some data from some website. I have to create a video using data scraped and one screenshot. One background image is also included.
an example is shown below.
Example Image
Picture of Leonel Messi or any player and the background image ofc will remain there, only stats will change as there are many.
Can somebody give me some piece of code or guide me how can I create such video?


text:
Q: Apply filter to Test-NetConnection result pipeline I'm trying to create simple "ping" job using PowerShell. And I want to do it in "pipeline" way. Though it looks like Where-Object receives strings, not objects of TestNetConnectionResult class. Could you please explain how to filter out the results of Test-NetConnection where ping was successful?
Get-Content .\adresses.txt | Test-NetConnection | Where-Object { $_.PingSucceeded } | Write-Output

A: function megaPing {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline, Mandatory, Position = 0)]
        [string]$serverName
    )
    process {
        , [PSCustomObject]@{
            serverName    = $serverName
            PingSucceeded = (Test-NetConnection $serverName).PingSucceeded
        }
    }
}

"127.0.0.1", "127.0.0.2" | megaPing

You need use pipe lines

A: The filter is working correctly but you need a final ForEach-Object for processing results in the pipeline.
Get-Content .\adresses.txt `
    | Test-NetConnection `
    | Where-Object { $_.PingSucceeded } `
    | ForEach-Object { Write-Host "SUCCEDED: $($_.ComputerName)" }

Note: if you also want to silent warnings from Test-NetConnection please check this question.

A: Here's another approach:
Get-Content -Path '.\adresses.txt' | Test-NetConnection |
    Select-Object @{Name = 'Address'; Expression = {$_.ComputerName}},
                  @{Name = 'PingSucceeded'; Expression = {$_.PingSucceeded}}

If you don't want the Progress bar, do this:
$oldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'

Get-Content -Path '.\adresses.txt' | Test-NetConnection |
    Select-Object @{Name = 'Address'; Expression = {$_.ComputerName}},
                  @{Name = 'PingSucceeded'; Expression = {$_.PingSucceeded}}

$ProgressPreference = $oldProgress

Result will look something like
Address      PingSucceeded
---------    -------------
127.0.0.1             True
10.10.2.153          False

A: Ignore warnings?  Warnings wouldn't put objects in the pipeline anyway.
echo yahoo.com microsoft.com | set-content addresses.txt
Get-Content addresses.txt | Test-NetConnection -WarningAction SilentlyContinue |
  Where PingSucceeded

ComputerName           : yahoo.com
RemoteAddress          : 74.6.231.20
InterfaceAlias         : Wi-Fi
SourceAddress          : 192.168.1.114
PingSucceeded          : True
PingReplyDetails (RTT) : 61 ms


text:
Q: Compiler optimization or my misunderstanding Recently I was testing some C++ deep and dark corners and I got confused about one subtle point. My test is so simple actually:
// problem 1
// no any constructor call, g++ acts as a function declaration to the (howmany())
// g++ turns (howmany()) into (howmany(*)())
howmany t(howmany());

// problem 2
// only one constructor call
howmany t = howmany();

My expectation from above line was; first howmany() constructor call will produce one temporary object and then compiler will use that temporary object with copy-constructor in order to instantiate t. However, output of compiler really confused me because output shows only one constructor call. My friends mentioned me about compiler pass-by-value optimization but we are not sure about it. I want to learn what does happen here ?
Output of problem 2 is below. problem 1 is completely beyond object instantiation because compiler behaves it as a function pointer declaration.
howmany()
~howmany()

My test class is:
class howmany {
    public:
        howmany() {
            out << "howmany()" << endl;
        }
        howmany(int i) {
            out << "howmany(i)" << endl;
        }
        howmany(const howmany& refhm) {
            out << "howmany(howmany&)" << endl;
        }
        howmany& operator=(const howmany& refhm) {
            out << "operator=" << endl;
        }
        ~howmany() {
            out << "~howmany()" << endl;
        }
        void print1() {
            cout << "print1()" << endl;
        }
        void print2() {
            cout << "print2()" << endl;
        }
};

A: This is the most vexing parse here:
howmany t( howmany() );

In order to fix this you need to add an extra set of parens:
howmany t( (howmany()) );
           ^         ^

clang is very helpful here and warns you:
warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
howmany t( howmany() );
        ^~~~~~~~~~~~~
main.cpp:31:12: note: add a pair of parentheses to declare a variable
howmany t( howmany() );
          ^
          (        )

The other way to fix this is to use C++11 uniform initialization syntax:
howmany t{ howmany{} };
         ^        ^^ ^

Update
To address part 2 which you added to the question the draft standard allows for omission of the copy/move construction in some cases. We can see this from section 12.8 Copying and moving class objects paragraph 31 which says:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.122 This elision of copy/move operations, called copy elision, is permitted in the following circumstances

and includes the following bullet:

when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

A: Yes, this is one of the optimization compiler may do.
The compiler is allowed to eliminate temporary object creation even if copy constructor has side effects!

A: After getting clues from above answers I found real problem. In my case, especially problem 2, compiler eliminates the copy construction process because return value of  howmany() constructor call is completely same to the howmany t object, for that reason compiler just eliminates copy-construction process in order to make optimization.  More detail of this problem is covered in wikipedia, please look to there.Return value optimization
-fno-elide-constructors is one of g++ flags which is responsible from disabling the optimizations. In cmake we just need to set it.
set(CMAKE_CXX_FLAGS "-fno-elide-constructors")
After disabling optimizations, the output of program turned what i was expecting.
howmany()
howmany(howmany&)
~howmany()
~howmany()

Thanks :)


text:
Q: adding anchor to div via jquery Here's the fiddle: http://jsfiddle.net/sarvagnya1/ET69q/
I have a bunch of HTML code which I want to make clickable. I can't edit the HTML so adding with jquery is the only option.

 Content1

 Content 2

The div with class="cont1" has to be made clickable, please help

A: Fiddle Demo
You can wrap you div with a tag
$('.cont1').wrap('');

CSS
.link {
    color:#000;
    text-decoration:none;
}


text:
Q: Stop Callback function Javascript The user can choose a month (+1 month click, -1 month click)
Each click executes a loop of the number of days in the month choosen.
Inside the loop a function to get data from an $http request.
Problem is: (example)
-Page loads : var data = [];
-Time 1: User clicks on January:
 31 $http request are made, 15 callbacks came out.
data.length = 15;
Time 2 : User clicks on February.
variable is initialized var data = []
16 callbacks are coming from previous month + 30 callbacks from February.
I'd like a way to stop the callbacks when the user clicks on another month...
Here is a basic Fiddle for better understanding
http://jsfiddle.net/36qp9ekL/318/

A: Ah ok sorry, the fiddle was wrong ...
I guess your requests are not as fast as one request. But since angular is async and you do not "wait" in your next() and previous() functions they overlap each other when you click fast enough.
Then it will return the "rest" from the previous days left and execute the next days of the month.
You need to use promises here or change your program structure.
Edit:
You need to inject $q
Example with promises
$scope.next = function(){
    date.setDate(date.getDate() + 1);
    $scope.data = [];
    // disable previous and next button
    $scope.loadData().then(function(allDayRequestResults) {
        $scope.data = allDayRequestResults;
        // enable previous and next button
    }).catch(function(error) {
        // handle http request error here
    });
};

$scope.loadData = function(){
    var promises = [];
    for(var i = 1; i <= daysInMonth(); i++){
        promises.push(getData(i));
    }
    return $q.all(promises);
};

function getData(i){
    var deferred = $q.defer();

    $http(<yourHttpOptions>)
        .success(function(result) {
            deferred.resolve(result);
        })
        .error(function (data, status, headers, config) {
            console.log('$http-error:' + data + status + headers + config);
            deferred.reject('Error occured while retrieving day '+ i);
        });

    return deferred.promise;
}

Untestet so far ...

A: I agree requesting 1 callback with a response of 30 days is a better solution, but I believe this can be usefull for other applications.
This is not tested, but shows the way to proceed.
Global variables are the solution I found, since promises aren't crossbrowser.
<button ng-click="load()"> Load data 1.000 times </button>

<script>

var callback = true;
var count = 0;

function ajaxRequest(i){

   //AJAX REQUEST
   .success(function(){

       count++;
       if(count == 1000){
         callback = true;
         count = 0;
       }
    });

}

$scope.load = function(){

   if(callback){
     callback = false;

     for(var i = 0; i < 1001; i++){
        ajaxRequest(i);
     }

   }

}
</script>


text:
Q: Define an environment with mdframed and set default text at it's beginning I am working on a script for my students, where they can read explanations and exercises.
Hence I have defined an environment with package mdframed to use colored boxes, that float with page breaks like this:
\newmdtheoremenv[%
  backgroundcolor=black!7,
  linecolor=red,
  linewidth=1pt,
  ]{ex}{Excercise}

Now I want to set a Checkbox with hyperref, so the students can check off an exercise.
The checkbox is set with pakage marginnote at the left margin and it is working this way:
\begin{ex}
\marginnote{
\begin{Form}
    \CheckBox[width=.6cm]{~}
\end{Form}
}
\lipsum
\end{ex}

What I need is, that I can use \begin{ex} ... \end{ex} and the checkbox will be automaticly set. I don't want to set the box every time like above.
So I want something like this:
\newmdtheoremenv[%
  backgroundcolor=black!7,
  linecolor=red,
  linewidth=1pt,
  at every beginning do:
       \marginnote{
          \begin{Form}
              \CheckBox[width=.6cm]{~}
          \end{Form}
       }
  ]{ex}{Excercise}

To be precise, I want to define an environment that sets a text (or in my case a checkbox) at every beginning, with mdframed.
Is there a way?

A: The following is a solution I could come up with.
First of all, I define the new counter exercise that I will use later to number the boxes. Next I define a new environment that contains the style of the boxes, the way the title is set up and the checkboxes. To make the checkboxes individually 'tick-able' in the resulting pdf, they need a unique name. I therefore reused the counter I defined earlier.
1. Continous numbering of exercises throughout document
\documentclass[a4paper]{article}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{marginnote}
\usepackage{lipsum}
\usepackage{hyperref}

\newcounter{exercise}
\newenvironment{exercise}
{\refstepcounter{exercise}%
\mdfsetup{%
backgroundcolor=black!7,
linecolor=red,
linewidth=1pt,
frametitle=Exercise~\theexercise%
\marginnote{%
\begin{Form}%
\CheckBox[width=.6cm,name=ex\theexercise]{~}%
\end{Form}%
}%
}%
\begin{mdframed}%
}%
{\end{mdframed}}

\begin{document}

\begin{exercise}
short example entry
\end{exercise}

\begin{exercise}
\lipsum
\end{exercise}

\end{document}

2. Numbering of exercises using current chapter (or section) number
The above code numbers all exercises with continuing numbers throughout the entire document. If you prefer a numbering scheme like Exercise 3.1 with 3 being the number of the current chapter, please refer to the following MWE:
\documentclass[a4paper]{report}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{marginnote}
\usepackage{lipsum}
\usepackage{hyperref}

\newcounter{exercise}[chapter]
\makeatletter
\renewcommand{\p@exercise}{\thechapter.}
\makeatother
\newenvironment{exercise}
{\refstepcounter{exercise}%
\mdfsetup{%
backgroundcolor=black!7,
linecolor=red,
linewidth=1pt,
frametitle=Aufgabe~\thechapter.\theexercise%
\marginnote{%
\begin{Form}%
\CheckBox[width=.6cm,name=ex\thechapter\theexercise]{~}%
\end{Form}%
}%
}%
\begin{mdframed}%
}%
{\end{mdframed}}

\begin{document}
\chapter{chapter title}
\begin{exercise}
short example entry
\end{exercise}

\begin{exercise}
\lipsum
\label{ex:Kirchhof}
\end{exercise}

\ref{ex:Kirchhof}
\end{document}

If you want the numbering scheme of your exercises to be 2.1 with 2 being the current section's number, simply replace every occurence of chapter with section.

A: The following solution uses the flexible tcolorbox package. I've also added the package xsim which is very flexible in creating exercises for students (even with points etc. if you'd like to extend that; you also have a solution environment at hand, if you need it).
There's also no problem with references, you can just use a label approach.

\documentclass[a4paper]{report}
\usepackage[ngerman]{babel}
\usepackage[breakable,skins]{tcolorbox}
\tcbset{exstyle/.style={colframe=red,colback=black!7,sharp corners=all,breakable,title after break={(Aufgabe \thechapter.\theaufgabe\ Fortsetzung)}}}

\usepackage{xsim}
\xsimsetup{solution/print=false}

\usepackage{marginnote}
\usepackage{lipsum}
\usepackage{hyperref}

\DeclareExerciseEnvironmentTemplate{tcolorbox}{%
  \tcolorbox[exstyle,title = {\strut\GetExerciseName~\thechapter.\GetExerciseProperty{counter}}]
  \IfInsideSolutionF{%
     \marginnote{\vskip-3\baselineskip%
            \begin{Form}%
            \CheckBox[width=.6cm,name=ex\thechapter\theaufgabe]{~}%
            \end{Form}%
        }%
    }
}{\endtcolorbox}
\DeclareExerciseType{aufgabe}{
  exercise-env=aufgabe,
  solution-env=loesung,
  exercise-name={Aufgabe},
  solution-name={Lösung zu Aufgabe},
  exercise-template=tcolorbox,
  solution-template=tcolorbox,
  within=chapter,
}
\makeatletter
\renewcommand{\p@aufgabe}{\thechapter.}
\makeatother

\begin{document}
\chapter{chapter title}
\begin{aufgabe}\label{test}
short example entry
\end{aufgabe}
\begin{loesung}
a test
\end{loesung}
\ref{test}
\begin{aufgabe}\label{tetest}
\lipsum
\label{ex:Kirchhof}
\end{aufgabe}
\begin{loesung}
a test
\end{loesung}
\ref{ex:Kirchhof}

\printsolutions[headings=false]
\end{document}


text:
Q: Managing Auth Token using RxJava I've been wondering what's the best way to tackle the issue of token refresh.
I'm connecting to an API which supplies me with a auth-token, if sometime time during the calls i get a INVALID_AUTH i need to re-authenticate.
So for the naive implementation i did this
@SuppressWarnings("unchecked")
@Override
public Observable<User> getUsers() {
    return runCommandAndrefreshAuthIfNecessary(new RequestCommand() {
        @Override
        public Observable create() {
            return createService(UsersApi.class).getUsers();
        }
    });
}
private Observable runCommandAndrefreshAuthIfNecessary(final RequestCommand command) {
    return command.create()
          .onErrorResumeNext(new Func1<Throwable, Observable<?>>() {
        @Override
        public Observable<?> call(Throwable throwable) {
            return handleRefreshToken(command);
        }
    });
}
private Observable<?> handleRefreshToken(final RequestCommand command) {
    return refreshToken().flatMap(new Func1<Boolean, Observable<?>>() {
        @Override
        public Observable<?> call(Boolean aBoolean) {
            return command.create();
        }
    });
}

As you can see i'm just wrapping the retrofit command, if i get an error i run refreshToken(), the token refreshes and i run the retrofit command again, so finally the Observable is passed back to the subscriber. Works as expected.
The thing i'm struggling with, is what happens i a multiple calls are made, for example, i'm calling getUsers and getFlags one after another. both of them get the INVALID_AUTH, currently both of the fire refreshToken(), which is bad.
i'm looking for a rx-java way to manage the calls, meaning after the first call of getUsers fires refreshToken, any call after that needs to wait for the refreshToken to end, only then fire the retrofit command.
Any suggestion will be appreciated.

A: You can use .cache() on the Observable for the token refreshing:
http://reactivex.io/documentation/operators/replay.html


text:
Q: jQuery counter fails to show the correct value after animation I have a jQuery counter that updates every time a radio button is being checked, adding its value to the equation. So far so good. But as soon as a radio button with a high value is being checked, the counter animation fails to show the correct numbers. It will show for example 999 998 instead of 1 000 000 and so on. Here's the script:
$(window).load(function(){
  $('input[type="radio"]').change(function () {
    var total_span = 0;
    $('input[type="radio"]').each(function () {
     total_span += this.checked && +this.value;
    });
    $({counter: +$('#total').text()}).animate({counter: total_span},{
     duration: 1000,
     easing: 'swing',
     step: function () {
       $('#total').text(Math.floor(this.counter));
       $('#total-2').text(Math.floor(this.counter));
     }
   });
  });
});

Do anyone of you have a solution to this problem? Would be so grateful if anyone could help me :)
EDIT: You can see the problem in action here:
http://moodboy.se/radiobuttons/

A: The jQuery animate function is design to deal with css animations. It works by 'tweening' between two elements using a timer. The result will be different depending on the size of the tween.
This lack of precision means, when using numbers, accuracy cannot be guaranteed. One solution is to use the complete callback property of the animation function to apply the correct value on completion.
.animate( properties [, duration ] [, easing ] [, complete ] )

$(window).load(function(){
  $('input[type="radio"]').change(function () {
    var total_span = 0;
    $('input[type="radio"]').each(function () {
     total_span += this.checked && +this.value;
    });
    $({counter: + $('#total').text()}).animate({counter: total_span},{
     duration: 1000,
     easing: 'swing',
     step: function () {
       $('#total').text(Math.floor(this.counter));
       $('#total-2').text(Math.floor(this.counter));
     },
     complete : function(){
       $('#total').text(total_span);
     }
   });
  });
});

Choices 1

Choices 2

Results

  974996

Choices 1

  <input id="1001" name="choices-1" value="1195000" type="radio">1195000
  <input id="1002" name="choices-1" value="925000" type="radio">925000
  <input id="1003" name="choices-1" value="1275000" type="radio">1275000
  <input id="1004" name="choices-1" value="1195000" type="radio">1195000
  <input id="1005" name="choices-1" value="1195000" type="radio">1195000
  <input id="1006" name="choices-1" value="1295000" type="radio">1295000

    <input id="2001" name="choices-1" value="1250000" type="radio">1250000
    <input id="2002" name="choices-1" value="975000" type="radio">975000
    <input id="2003" name="choices-1" value="1295000" type="radio">1295000
    <input id="2004" name="choices-1" value="1250000" type="radio">1250000
    <input id="2005" name="choices-1" value="1250000" type="radio">1250000
    <input id="2006" name="choices-1" value="1345000" type="radio">1345000

  > Choices 2


text:
Q: What happens when one of the name servers cannot resolve a host? Let's say I assigned two different name server from two different providers for my example.org domain:
example.org NS ns.example.com
example.org NS ns.example.net

But I have put an A record only on the second one:
ns.example.com:
    ---

ns.example.net:
    site.example.org A 198.51.100.1

What will happen when users will try to reach site.example.org? Will they randomly fail to resolve the name or will all of them be able to connect?

A: If one of the authoritative name servers isn't responding, the recursive name server tries another. However, if it can reach a name server that responds with a NXDOMAIN, it will stop and the result will be that there's no such hostname. Due to Negative Caching of DNS Queries (RFC2308) this will last for the time-to-live (TTL), not just until requested again. What you suggest wouldn't work!
There is only one correct solution to this: you only configure the records on the provider that handles your primary authoritative DNS server. The other server must be configured as a secondary authoritative DNS server. The primary server notifies the secondaries it's aware of, and the secondary servers requests for a DNS Zone Transfer (AXFR) containing the entire zone.
During the zone transfer there's no management web services involved, so it doesn't matter if it's down on the secondary service, as long as you don't need to change the name servers.
Generally it's not a good idea to use different providers for authoritative name servers although network diversity is required. That's because for the zone transfer the secondary server needs special permissions, and service providers with web control panels may not have considered that. Also, any decent service provider should be able to arrange you a secondary DNS server that meet all the requirements. Those servers are configured to co-operate flawlessly.


text:
Q: Allow URL to access with Basicauthintication IIS We have a website that we added a basic authentication, to allow only specific people to have access on as it is only in beta stage.
But one of 3rd party services stop working and i understand why, because the basic authentication is restricting it. I tried to add the service URL in IP Address and Domain Restrictions as allow.
but it is not working. I've searched around but couldn't find a lead, i have no good experience in IIS can you please be patient with me.