text:
Q: Writing contents to json file which already has headers So I am experimenting with happybase and I want to write the contents of a scan sequence to a json document with a skeleton I've already put in. This is the skeleton for the intended output file:
[{
   "Key": "",
   "Values": ""
}]

and from the code I hope to achieve this final format for the intended json file:
[{
   "Key":"01/01/2009",
   "Values": {
                "actual:number":30000,
                "predicted:number":40000
             }
 },
 {
   "Key":"01/02/2009",
   "Values": {
                "actual:number":30000,
                "predicted:number":40000
             }
 }]....

My Hbase Table is structured this way:
'01/01/2009','actual:number',value='30000'
'01/02/2009','predicted:number',value='40000'

and this is the code I use to access the table:
import happybase

import simplejson as sjson

import json

connection = happybase.Connection('localhost')

table = connection.table('Date-Of-Repairs')

file = open('test.json','wb+')

for key, data in table.scan(row_start='01/01/2009'):
    a = key, data
    print sjson.dumps(a)
    json.dump(a,file, indent = 2)

file.close()

I want to know how I can implement my desired json output file, and also how to stop the content written to the json to be printed out like this:
[
  "01/01/2009",
   {
     "Actual:number": "10000",
     "Predicted:number": "30000"
   }
][
  "01/02/2009",
  {
    "Actual:number": "40000",
    "Predicted:number": "40000"
  }
][
  "01/03/2009",
   {
    "Actual:number": "50000",
    "Predicted:number": "20000"
   }
]

As this is the current output that is being displayed in the output file

A: Python json library uses standard formatting for JSON text it has indent parameter which can help you to control the number of spaces that should be considered for indentation.
json.dumps(pydict, indent=4)

If you need a compressed JSON, which is good to use in production you can simply ignore it and python will generate minified text which reduces network traffic and parsing time.
If you want your way to print then you will have to implement it on your own, there is a module called pjson you can take it as an example of how to do it.

A: Thanks @anand. I figured out the answer. I just had to create a dictionary for the storing the table data, then appending to a list to be stored in a file, which yield a full json file.
The code is below:
import happybase

import json

import csv

file = open('test.json','wb+')

store_file = {}
json_output = []

for key, data in table.scan(row_start='01/01/2009'):
   store_file['Key'] = key
   store_file['Value'] = data
   json_output.append(store_file.copy())
   print json_output

json.dump(json_output,file, indent = 2)

file.close()

This then yields:
[
  {
    "Key": "01/01/2009",
    "value": {
       "Actual:number": "10000",
       "Predicted:number": "30000"
    }
 },
 {
   "Key": "01/02/2009",
   "value": {
      "Actual:number": "40000",
      "Predicted:number": "40000"
   }
 },
 {
   "Key": "01/03/2009",
   "value": {
      "Actual:number": "50000",
      "Predicted:number": "20000"
   }
 }
]

I hope this helps anyone that is stuck with a problem like such.


text:
Q: I try to display next row on refresh but i get a blank page Hey I try to display next row on refresh and when it arrive at last row to take it from the beginning. Here is my table
col1 row(1)
col2 row(1)
col3 row(1)
col4 row(1)
col5 row(1)

and on refresh to get
col1 row(2)
col2 row(2)
col3 row(2)
col4 row(2)
col5 row(2)

and when it arrive at last row take it from the beginning.
col1 row(1)
col2 row(1)
col3 row(1)
col4 row(1)
col5 row(1)

Here is the code so far:
<?php
include 'connect.php';
session_start();

if(isset($_SESSION["id"])){
    $_SESSION["id"] = $_SESSION["id"] + 1;
}
else{
    $_SESSION["id"] = 1;
}

$id = $_SESSION["id"];

//Your mysql connection

$results = mysqli_query($con, "SELECT * FROM testtable WHERE `id` = $id") or die('AM error occured: ' . mysqli_error());

while($row = mysqli_fetch_array($results)){
    echo $row["content0"];
    echo "
";
    echo $row["content1"];
      echo "
";
    echo $row["content2"];
      echo "
";
    echo $row["content3"];
      echo "
";
    echo $row["content4"];
      echo "
";
    echo $row["content5"];

}

A: <?php
include 'connect.php';
session_start();

if(isset($_SESSION["id"])){
    $_SESSION["id"] = $_SESSION["id"] + 1;
}
else{
    $_SESSION["id"] = 1;
}

$id = $_SESSION["id"];

//Your mysql connection

$result=mysqli_query($con,"SELECT count(id) as total from testtable");
$data=mysqli_fetch_assoc($result);
echo $data['total'];
if($data['total']<$id )
{
$_SESSION["id"] = 1;
    $id=1;
}

$results = mysqli_query($con, "SELECT * FROM testtable WHERE `id` = $id") or die('AM error occured: ' . mysqli_error());

while($row = mysqli_fetch_array($results)){
    echo $row["content0"];
    echo "
";
    echo $row["content1"];
      echo "
";
    echo $row["content2"];
      echo "
";
    echo $row["content3"];
      echo "
";
    echo $row["content4"];
      echo "
";
    echo $row["content5"];

}

explanation:
here we are getting total records and checking with current refreshed item, if greater then that we are assigning to start(1)

A: To get next id from the table if it has gaps in id values use this query
select *
from testtable
where id >= if($id > (select max(id) from testtable), 1, $id)
order by id
limit 1

and save in session variable selected id

A: What you need is pagination, what can be done with $_SESSION. Next is an example with an array of data :
<?php
session_start();
// SAMPLE DATA.
$items = array( array( "a","b","c","d","e","f" ),
                array( "1","2","3","4","5","6" ),
                array( "+","-","*","/","&","#" )
              );

if ( ! isset( $_SESSION[ "current" ] ) ) // IF THIS IS THE FIRST TIME.
     $_SESSION[ "current" ] = 0; // FIRST ITEM TO SHOW.
else if ( $_SESSION[ "current" ] < ( count( $items )-1 ) )
          $_SESSION[ "current" ] ++; // NEXT ROW.
     else $_SESSION[ "current" ] = 0; // FIRST ROW AGAIN.
?>

    Showing items :

<?php
// DISPLAY CURRENT ROW.
foreach ( $items[ $_SESSION[ "current" ] ] as $item )
   echo $item . " row(" . $_SESSION[ "current" ] . ")
";
?>

    -- Refresh to see next page --

Copy-paste previous code in a PHP file and open it in your browser. Each time you refresh the page, the next block of items will be shown.
To adapt it to your code, we only need to fill the array of data with the sql query :
$results = mysqli_query($con, "SELECT * FROM testtable WHERE `id` = $id")
           or die('AM error occured: ' . mysqli_error());
$items = array();
while($row = mysqli_fetch_array($results)){
  array_push( $items,array( $row["content0"],
                            $row["content1"],
                            $row["content2"],
                            $row["content3"],
                            $row["content4"],
                            $row["content5"] ) );
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expectation of cross product of an MDS error and lag of an AR(1) I have the following AR(1): $y_{t}=\phi y_{t-1}+\epsilon_{t}$, where $|\phi|<1$. $\epsilon_{t}$ is assumed to be a margintale difference process, such that $\mathbb{E}[\epsilon_{t}|I_{t-1}]=0$. ($I_{t}$ is an information set containing all realisations of $y$, and $\epsilon$, in the periods up to, and including, $t$). I am trying to find $\mathbb{E}[y_{t-1}\epsilon_{t}]$. Is the following correct?
$\mathbb{E}[y_{t-1}\epsilon_{t}]=\mathbb{E}[\mathbb{E}[y_{t-1}\epsilon_{t}|y_{t-1}]]=\mathbb{E}[y_{t-1}\mathbb{E}[\epsilon_{t}|y_{t-1}]]=0$ (since, by the assumption that $\epsilon_{t}$ is an MDS, the inner conditional expectation is $0$). The first equality follows by LIE.
Thank you.


text:
Q: Export report from report viewer to memory stream and then email report I currently have a page which displays a local report (which takes parameters in a report viewer control on my webpage. I have a requirement were the user wants the report to be generated and then emailed via a button click or page load. I have the below code which I have used to try and load the report into a memory stream and then to be emailed. The email part works fine but the pdf doesn't generate. What is the best way to load the pdf and email it since it isn't a physical file as such?
    WebClient client = new WebClient();
        byte[] bytes = client.DownloadData("http://localhost:51997/ReportDetails.aspx?Report1.rdlc&rs%3aFormat=PDF");

        MemoryStream ms = new MemoryStream(bytes);

        MailMessage mailObj = new MailMessage("FromAddress", "ToAddress", "header", "body text");

        SmtpClient SMTPServer = new SmtpClient("RelayServer");
        mailObj.IsBodyHtml = true;
        mailObj.Attachments.Add(new Attachment(ms, "Reports.pdf"));
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }

A: I worked this out by loading the local report into a byte array, writing to a file stream and then loading it into memory stream where I could then email.
  Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string filenameExtension;

        byte[] bytes = ReportViewer1.LocalReport.Render(
           "PDF", null, out mimeType, out encoding, out filenameExtension,
            out streamids, out warnings);

        string filename = Path.Combine(Path.GetTempPath(), "Report2.rdlc");

        using (var fs = new FileStream(filename, FileMode.Create))
        {
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

Load into memory stream:
MemoryStream ms = new MemoryStream(bytes);

Then send as an attachment:
  MailMessage mailObj = new MailMessage("From", "To", "header", "body");

        SmtpClient SMTPServer = new SmtpClient("relayServer");
        mailObj.IsBodyHtml = true;

        mailObj.Attachments.Add(new Attachment(ms, "report.pdf"));

        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }


text:
Q: Custom datepicker binding with parent component using Angular 4 I'm trying to set up a shared DatePicker component to be used on different pages in the application.
I'm working with Angular 4 and trying to use ngbDatepicker. For some reason, the date selection after toggle does not bind with the parent component when I am using this shared directive element.
Date changed in picker from button should come in an app component. I tried with input and output also, but those did not work. I also looked at something called ControlValueAccessor which did not work well.
datepicker-poput.ts
import {Component} from '@angular/core';
import {forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

@Component({
  selector: 'ngbd-datepicker-popup',
  templateUrl: './datepicker-popup.html',
   providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NgbdDatepickerPopup),
      multi: true
    }
  ]
})
export class NgbdDatepickerPopup implements ControlValueAccessor{
  model;
  propagateChange = (_: any) => {};

  constructor() { }

  writeValue(obj: any): void {
    console.log('writeValue', obj);
    this.model = obj;
    //this.propagateChange(this.model);
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  changeMe() {
    this.propagateChange(this.model);
  }
}


text:
Q: How to read a file and log its content in node js How to read the contents of a file by using the fs core module of Node, and log the contents into the console using events. I tried the below code but yet not worked. Is there any other way? I'm new to node
events= require('events');
var eventEmitter = new events.EventEmitter();
fs = require('fs');

var Myfunc = function () {
 fs.readFile('./new-dir/sample.txt', function(err, data){
  if(err){
   console.log(err);
  }
  else{
   console.log(data.toString());
  }
 });
}

eventEmitter.on('MyEvent', Myfunc);
eventEmitter.emit('MyEvent');


text: Q: multipeer connectivity for video streaming between iphones i've been searching on this for some days now. I've found how to connect devices with the multipeer connectivity protocol (http://techmaster.vn/2013/09/multipeer-connectivity-quick-tutorial/) and i've manage to send text or images. What i want to do is to stream video and audio from the camera of the one device (master) to the other device(slave) in real time and show it on the slave's screen. I've found ways to save the video from the camera to the device in a file but there is nothing about streaming. Any ideas? I would really appreciate it. Thanks in advance


text:
Q: How to include OpenCV dependency in library added manually to AndroidStudio project I added my own library using the following answer: How to include a library module dependency in an Android Studio project?
AndroidStudio seems to 'accepted' it, and now I can use methods from the library in my Android project. However, this library needs OpenCV. I integrated OpenCV successfully in my project, but it doesn't 'reach' the library. Therefore, in library's build.gradle I added the following, similar as in build.gradle of the app:
api project(path: ':openCVLibrary347')

in dependencies. The problem is, when I try to sync, I get:
ERROR: Failed to resolve: DegreeApp:openCVLibrary347:unspecified

I don't know what can be the problem here, there seems to be no answer for such a formulated question.
Here I enclose also my project 'situation'.


text:
Q: Add option to form element in the controller Related to this post I want to transform a manual adding of a form element to Annotations in my Entity.
The code looks like this:
$this->add(array(
    'name'       => 'formElementName',
    'type'       => 'DoctrineModule\Form\Element\ObjectSelect',
    'attributes' => array(
        'required' => true
    ),
    'options'    => array(
        'label'           => 'formElementLabel',
        'empty_option'    => '--- choose formElementName ---',
        'object_manager'  => $this->getEntityManager(),
        'target_class'    => 'Mynamespace\Entity\Entityname',
        'property'        => 'nameOfEntityPropertyAsSelect'
    )
));

As an annotation I have the problem that the object_manager is a variable which I cannot pass to annotations. Every other attribute is no problem and should work when being annotated.
I'm looking for the correct way to do this:
$form->get('formElementName').setOptions(array('object_manager'=>$entityManager)

Any ideas?

A: you have to try this it will working fine.
<!-- language-all: lang-html -->
foreach($cityArr as $city){

  $city_ar[$city['id']] = $city['city'];

}

$form->user_city->setMultiOptions($city_ar);

$form->user_city->setValue($val["user_city"]);


text:
Q: Verify condition was satisfied on scroll, then run a function only once I have code that runs a counter, counting up from 0 to a figure defined by the text inside the HTML tag. This works fine - I have four elements using the class and each will count up from 0 when the page is loaded.
But where it got tricky is that I want the respective counters to begin as each element comes into view.
What I found was that the counter kept re-starting as I scrolled. I've tried using the jQuery .one() method attached to the .scroll() event handler but I need to continually check that the condition has been satisfied with regards the element being visible, and this is where I've come unstuck.
Here's what I have:
$(window).on('scroll',function(e) {
    $('.count').each(function(i) {
        var topOfElement = $(this).offset().top;
        var bottomOfWindow = $(window).scrollTop() + $(window).height();

        if (bottomOfWindow > topOfElement) {
            $(window).one('scroll',function(e) {
                $(this).prop('Counter',0).animate({
                    Counter: $(this).text()
                }, {
                    duration: 2000,
                    easing: 'swing',
                    step: function (now) {
                        $(this).text(Math.ceil(now));
                    }
                });
            });
        }
    });
});

And the simple HTML:
4143
920
5112
76

I'm getting a "Cannot read property 'createDocumentFragment' of undefined" error.

A: The this inside the one scroll is the window element.
$('.count').each(function(i) {
  var elem = $(this);
  ...
  if (bottomOfWindow > topOfElement) {
    $(window).one('scroll',function(e) {
      $(elem).prop('Counter',0).animate({
        ...

A: As epascarello pointed out, you were re-binding the .scroll event on each .scroll event. You only need one binding.
But you also needed a way to identify that the count-up process had fired, and that it need not be run again. Simple way to do that is to add a class to the element.
I also didn't see how you were getting the maxcount value from the span tag.

$(window).on('scroll',function(e) {
    $('.count').each(function(i, e) {
        var topOfElement = $(e).offset().top;
        var bottomOfWindow = $(window).scrollTop() + $(window).height();

        if (bottomOfWindow > (topOfElement + 80)) {
        //debugger;
            if ( !$(e).hasClass('done') ){
                $(e).addClass('done');

                let maxcnt = $(e).text();
                maxcnt = parseInt(maxcnt);
                $(e).prop('Counter',0).animate({
                    Counter: $(e).text()
                }, {
                    duration: 2000,
                    easing: 'swing',
                    step: function (maxcnt) {
                        $(e).text(Math.ceil(maxcnt));
                    }
                });
            }
        }
    });
});
div{height:250px;}

4143

920

5112

76


text:
Q: Pgmpy: expectation maximization for bayesian networks parameter learning with missing data I'm trying to use the PGMPY package for python to learn the parameters of a bayesian network. If I understand expectation maximization correctly, it should be able to deal with missing values. I am currently experimenting with a 3 variable BN, where the first 500 datapoints have a missing value. There are no latent variables. Although the description in pgmpy suggests that it should work with missing values, I get an error. This error only occurs when calling the function with datapoints that have missing values. Am I doing something wrong? Or should I look into another package for EM with missing values?
#import
import numpy as np
import pandas as pd
from pgmpy.estimators import BicScore, ExpectationMaximization
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import HillClimbSearch

# Read data that does not contain any missing values
data = pd.read_csv("asia10K.csv")
data = pd.DataFrame(data, columns=["Smoker", "LungCancer", "X-ray"])
test_data = data[:2000]
new_data = data[2000:]

# Learn structure of initial model from data
bic = BicScore(test_data)
hc = HillClimbSearch(test_data)
model = hc.estimate(scoring_method=bic)

# create some missing values
new_data["Smoker"][:500] = np.NaN

# learn parameterization of BN
bn = BayesianNetwork(model)
bn.fit(new_data, estimator=ExpectationMaximization, complete_samples_only=False)

The error I get is an indexing error:
  File "main.py", line 100, in <module>
    bn.fit(new_data, estimator=ExpectationMaximization, complete_samples_only=False)
  File "C:\Python38\lib\site-packages\pgmpy\models\BayesianNetwork.py", line 585, in fit
    cpds_list = _estimator.get_parameters(n_jobs=n_jobs, **kwargs)
  File "C:\Python38\lib\site-packages\pgmpy\estimators\EM.py", line 213, in get_parameters
    weighted_data = self._compute_weights(latent_card)
  File "C:\Python38\lib\site-packages\pgmpy\estimators\EM.py", line 100, in _compute_weights
    weights = df.apply(lambda t: self._get_likelihood(dict(t)), axis=1)
  File "C:\Python38\lib\site-packages\pandas\core\frame.py", line 8833, in apply
    return op.apply().__finalize__(self, method="apply")
  File "C:\Python38\lib\site-packages\pandas\core\apply.py", line 727, in apply
    return self.apply_standard()
  File "C:\Python38\lib\site-packages\pandas\core\apply.py", line 851, in apply_standard
    results, res_index = self.apply_series_generator()
  File "C:\Python38\lib\site-packages\pandas\core\apply.py", line 867, in apply_series_generator
    results[i] = self.f(v)
  File "C:\Python38\lib\site-packages\pgmpy\estimators\EM.py", line 100, in <lambda>
    weights = df.apply(lambda t: self._get_likelihood(dict(t)), axis=1)
  File "C:\Python38\lib\site-packages\pgmpy\estimators\EM.py", line 76, in _get_likelihood
    likelihood *= cpd.get_value(
  File "C:\Python38\lib\site-packages\pgmpy\factors\discrete\DiscreteFactor.py", line 195, in get_value
    return self.values[tuple(index)]
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Thanks!

A: Since there is still no answer to your specific question, let me propose a solution with another module:
#import
import pandas as pd
import numpy as np
import pyAgrum as gum

# Read data that does not contain any missing values
data = pd.read_csv("asia10K.csv")
# not exactly the same names
data = pd.DataFrame(data, columns=["smoking", "lung_cancer", "positive_XraY"])
test_data = data[:2000]
new_data = data[2000:].copy()

# Learn structure of initial model from data
learner=gum.BNLearner(test_data)
learner.useScoreBIC()
learner.useGreedyHillClimbing()
model=learner.learnBN()

# create some missing values
new_data["smoking"][:500] = "?" # instead of NaN

# learn parameterization of BN
bn = gum.BayesNet(model)
learner2=gum.BNLearner(new_data,model)
learner2.useEM(1e-10)
learner2.fitParameters(bn)

In a notebook :


text:
Q: PostgreSQL: concatenation of pg_sleep There's this challenge from portswigger: https://portswigger.net/web-security/sql-injection/blind/lab-time-delays
I noticed that these 2 solutions work:
' || pg_sleep(10)-- , ' || (SELECT pg_sleep(10)--
But this doesn't: ' || SELECT pg_sleep(10)--
And my question is what's the different between with and without () ?

A: Because This is the syntax of the SQL:

A scalar subquery is an ordinary SELECT query in parentheses that returns exactly one row with one column.


text:
Q: C++ - multi-dimensional arrays and variable lengths? So, I am dealing with a code base where we are attempting to merge several code bases into one neat stack. I'm running into trouble with the BYTE arrays that we use. Our stuff is based around communication via byte arrays, and so each of our apps stores the messages it needs to send like so:
BYTE arr[] = {0x00, 0x01, 0x02};

So now, I am smashing all the arrays together into arrays of arrays to try to group them together, like so:
BYTE groupOneArrs[][15] =
{
   {0x01, 0x02, 0x03},
};

BYTE groupTwoArrs[][15] =
{
   {0xFF, 0xA9, 0xAA},
};

And etc. However, I am running into issues, because the sizes of the individual messages must be preserved, because in order for the messages to be considered valid, they must be the same lengths that we defined them as. I got around this by defining an int array with the actual lengths of each element, but it's dirty. Is there an easier way to store these 2D arrays, which will preserve the lengths of each individual array?
EDIT: So it's sounding like I'm SOL with VS 2008 and variable-length 2D arrays in the header files. Is there a way I could work around this with, say, a struct? something like
struct Message{
   byte message[20];
   int size;
}

And then initialize it like...
Message messages[] = {
   {{0x01, 0x02, 0x03}, 3},
};

Well, I should say, I tried something like this, and it blew up. But something like that, anyway. I just don't want to have to make variable names for each array just to preserve the size, that just seems silly.

A: Rather than making 2D array, use adjacency list. vector should be the best for this purpose. They come handy in forming adjacency lists.


text:
Q: Restricted Permutations and Combinations Tino, Colin, Candice, Derek, Esther, Mary and Ronald are famous artist. Starting next week, they will take turns to display their work
and each artist's work will be on display at the London Show for
exactly one week so that the display of the artworks will last the next seven
weeks. In how many ways can a display schedule be developed if
$(a)$. There is no restriction. ANS 7! EASY
Suppose that a revised timetable has been drawn up and the artists in $(a)$ are
to display their work in groups of twos or threes so that the entire exercise
takes at most $3$ weeks. In how many ways can Colin and Candice find themselves
in the same group?
Hint: We need to explore all possible scenarios - the possible distributions of the
teams in terms of numbers are: $2,2,3; 2,3,2;$ and $3,2,2.$ Candice and Colin can be in
the $1st, 2nd$ or $3rd$ week. This thinking gives us $9$ possible scenarios
in which Adam and Brian may end up being in the same team. Answer: $150$
How to get the $150$ I have scratched my head to no avail.
What I assumed is that if they are both in a group that has only two people, we count that group as one person and if they are in a group that has $3$ people we count the group as two people.
I tried:
In both cases the $n$ is reduced to $7-2$, and $r$ to either $3-2$ or $2-2$.
Hence: $(5C1*2!*3!*2! + 5C0*2!*2!*2!) * 3!$
and many other futile attempts.
The problem is :
1). Classification, how do I classify this problem? As a strictly permutation or strictly combination or mixed permutation or combination?
2). Is sampling with or without replacement?
3). How do I change $n$ and $r$, by subtracting one from each? Or by subtracting p, the number of objects that will always occur? $7-2=5?$ or $7-1 =6?$
The correct reasoning approach will be greatly appreciated.

A: Where do you get $2*6!$ for (a)?  I find $7!$
For the three week problem, let us start by assuming $3,2,2$.  We can multiply by $3$ at the end to take care of cyclic permutations of weeks.  The two pairs are differently named bins in this case.  The two C's can be together in one of the twos in $2\text{(which week)}*{5 \choose 3}\text{(who is in the triplet)}=20$ ways.  They can be two of the triplet in $5\text{(the other member of the triplet)}*{4 \choose 2}\text{(the first other couple)}=30$ ways.  Multiplying by $3$ gives a total of $150$ ways.


text:
Q: zoom in a CDF figure I have the below figure shows cdf. I am wondering how can I zoom in to show better the difference between four lines in the left upper part of the figure.

A: You can use coord_cartesian to zoom in. I don't know what you mean by having the zoom part and the whole in the same figure. If you want to have them side by side, you can use the multiplot function found in the Cookbook for R page. For example:
df <- data.frame(x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),
                 g = gl(2, 100))

p <- ggplot(df, aes(x, colour = g)) + stat_ecdf()
p1 <- p
p2 <- p + coord_cartesian(ylim = c(.75, 1))
multiplot(p1, p2)

Edit
Based on @Paul Lemmens' comment, you can use grid's viewport function in the following way:
pdf("~/Desktop/foo.pdf", width = 6, height = 6)
subvp <- viewport(width = .4, height = .4, x = .75, y = .25)
p1
print(p2, vp = subvp)
dev.off()

which gives the following output - adjust the details for your specific example:


text:
Q: WinForms and disposing custom controls I have the following class:
public class NewListBox : ListBox
    {
        public NewListBox()
        {
        }

        private ImageList _myImageList;

        public ImageList ImageList
        {
            get { return _myImageList; }
            set { _myImageList = value; }
        }
     }

I am interested in whether disposing of this object will trigger the disposal of fields on the object, such as the ImageList, or should i implement (override) the Dispose method and do this work myself?

A: You should add the ImageList to your control's Components collection, then the base-class implementation of Dispose will Dispose everything in that collection, and you won't have to override Dispose yourself.
If you have any members that are IDisposable but are not Components, then you will have to override Dispose in your control and Dispose them yourself.
(I am using the term Component in the strict sense of objects that derive from System.ComponentModel.Component).

A: this article is very helpful, in the Memory Disposal section.
All classes that implement IDisposable (including all Windows Forms controls) have a Dispose method.  This method must be called when an object is no longer needed in order to release resources other than memory.  There are two ways this happens:

*

*manually (by calling Dispose explicitly)

*automatically: by adding the object to a .NET container, such as a Form, Panel, TabPage or
UserControl.  The container will ensure that when it's disposed, so are all of its members.  Of course, the container itself must be disposed (or in turn, be part of another container).
In the case of Windows Forms controls, we nearly always add them to a container – and hence rely on automatic disposal.

A: Lot of different answers here ..
I strongly advise to read Garbage Collector Basics and Performance Hints
In you case you've two option:

*

*Dispose the ImageList manually, so the ressource will be released
quickly (but not immediately)

*Do nothing: the resources will be release next time the Garbage
Collector analyse the Generation where you form is. If you form is
closed, and nothing keep a reference to your form, then your form
will be disposed, and then as no reference will point to the
ImageList anymore, the ImageList will be disposed. The resources
will be released, but a bit later than the first case.

Except if you have thousand of big images in your ImageList (or if you create/close the form hundred of times), you'll not notice any difference between the 2 cases

A: Based on the code you have posted, you are not using Designer to implement this control. Thus, you will not have a designer-provided Dispose(bool disposing) method or a System.CompononetModel.IContainer components member that your extra control may be added to. I am not sure how ListBox handles its Controls property, but if it lets you register your ImageList instance there with Controls.Add(ImageList), that should get you the automatic Dispose() behavior.
Your other option is to override Control.Dispose(bool) like the following:
protected override void Dispose(bool disposing)
{
    // Only call Dispose() on members if invoked through a direct
    // call to `Dispose()`. (If disposing is false, that means
    // we are invoked through the finalizer and we should *only*
    // free up unmanaged resources that we *directly* own).
    if (disposing)
    {
        ImageList.Dispose();
    }

    base.Dispose(disposing);
}


text:
Q: php get the text into an array list I have an array in the database. When I used print_r($variable_name), I got the array like this
Array
    (
        [0] => Array
            (
                [attribute_name] => Disk space,Color,Processor
            )

    )

So to get the value of attribute_name I tried this
foreach($attributes_name as $key=>$val) {
      echo $val['attribute_name'];
    }

Here I got the result like Disk space,Color,Processor. But I want the result should come like a list

Disk Space

Color

Processor

So can someone tell me how to do this?

A: Try this :
<?php
$arr = array(array("attribute_name" => "Disk space,Color,Processor"));

foreach($arr as $val) {
    $resultArr = explode(",",$val['attribute_name']);
    foreach($resultArr as $value){
        echo "
".$value."
";

        // Add id in li
        echo "
".$value."
";
    }
}
?>


text:
Q: iTunesconnect App Preview Error I'm trying to upload an app preview video to my itunesconnect account, but i'm receiving the following error...
"This video has audio that is not two-channel, no-surround stereo"

As far as I can tell, there is not specific documentation discussing how to deal with this is issue, so any extra insight on this would be very helpful.

A: In my case I had created the video in iMovie and (intentionally) did not include any audio. To resolve the issue, I imported a silent audio track, added it to the timeline, decreased its volume to 0% just to be sure, then I shared the App Preview again. Uploading this file worked just fine. Seems the videos have to have audio included.

A: I have use this tool making the video https://handbrake.fr/ and uploaded the video in iTune . Work perfectly.


text:
Q: A question on isolated points A scattered space is a space for which every not empty subset has an isolated point.

How  to show it is equivalently for $T_1$ spaces, every not empty closed subset has an isolated point?

Thanks advance!

A: $X$ need not be $T_1$: it's true in general that if every non-empty closed subset of $X$ has an isolated point, then every non-empty subset of $X$ has an isolated point.
HINT: Suppose that every non-empty closed subset of $X$ has an isolated point, and let $A$ be any non-empty subset of $X$. Then $\operatorname{cl}A$ has an isolated point, say $x$. Now show that $x\in A$ and conclude that $x$ is an isolated point of $A$.


text:
Q: Create a primitive Type that behaves like another Type I would like to create a primitive type that behaves like let's say Int64, but named Foo. Is this possible?
I learned here that I can do something like this
# Declare the new type.
primitive type MyInt8 <: Signed 8 end

# A constructor to create values of the type MyInt8.
MyInt8(x :: Int8) = reinterpret(MyInt8, x)

# A constructor to convert back.
Int8(x :: MyInt8) = reinterpret(Int8, x)

# This allows the REPL to show values of type MyInt8.
Base.show(io :: IO, x :: MyInt8) = print(io, Int8(x))

But I do not understand why, even if MyInt8 is a subtype of Signed (MyInt8 <: Signed) there are no methods for this type:
a = MyInt8(Int8(3))
b = MyInt8(Int8(4))

a + b
ERROR: promotion of types MyInt8 and MyInt8 failed to change any arguments

I thought that as a subtype the primitive type would automatically "get" all the methods of the supertype as well.
Where am I wrong here?

A: As a subtype of Signed, MyInt8 does automatically "get" all methods defined for numbers. And there is actually quite a lot of them:
julia> methodswith(MyInt8, supertypes=true) |> length
1218

julia> methodswith(MyInt8, supertypes=true)[1:10]
[1] poll_fd(s::RawFD, timeout_s::Real; readable, writable) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:649
[2] poll_file(s::AbstractString, interval_seconds::Real) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:784
[3] poll_file(s::AbstractString, interval_seconds::Real, timeout_s::Real) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:784
[4] watch_file(s::AbstractString, timeout_s::Real) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:687
[5] watch_folder(s::String, timeout_s::Real) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:716
[6] watch_folder(s::AbstractString, timeout_s::Real) in FileWatching at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/FileWatching/src/FileWatching.jl:715
[7] randcycle(r::Random.AbstractRNG, n::T) where T<:Integer in Random at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/Random/src/misc.jl:348
[8] randcycle(n::Integer) in Random at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/Random/src/misc.jl:349
[9] randexp(rng::Random.AbstractRNG, ::Type{T}, dim1::Integer, dims::Integer...) where T in Random at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/Random/src/normal.jl:204
[10] randperm(r::Random.AbstractRNG, n::T) where T<:Integer in Random at /home/francois/.local/julia-1.5.2/share/julia/stdlib/v1.5/Random/src/misc.jl:282

Some of them don't require that MyInt8 conform to any specific interface, and will work "out of the box":
julia> a = MyInt8(Int8(3))
3

julia> conj(a)
3

But some will provide an implementation that depends on MyInt8 conforming to an interface:
# Here `imag` does not know how to build a zero of the MyInt8 type
julia> imag(a)
ERROR: MethodError: no method matching MyInt8(::Int64)
Closest candidates are:
  MyInt8(::T) where T<:Number at boot.jl:716
  MyInt8(::Int8) at REPL[7]:2
  MyInt8(::Float16) where T<:Integer at float.jl:71
  ...
Stacktrace:
 [1] convert(::Type{MyInt8}, ::Int64) at ./number.jl:7
 [2] oftype(::MyInt8, ::Int64) at ./essentials.jl:367
 [3] zero(::MyInt8) at ./number.jl:241
 [4] imag(::MyInt8) at ./complex.jl:78
 [5] top-level scope at REPL[37]:1

The addition falls into that last category:
# There is indeed a generic implementation that MyInt8 inherits
julia> which(+, (MyInt8, MyInt8))
+(a::Integer, b::Integer) in Base at int.jl:918

# But it relies on promotion features, which are not implemented for MyInt8
julia> a + a
ERROR: promotion of types MyInt8 and MyInt8 failed to change any arguments
Stacktrace:
 [1] error(::String, ::String, ::String) at ./error.jl:42
 [2] sametype_error(::Tuple{MyInt8,MyInt8}) at ./promotion.jl:306
 [3] not_sametype(::Tuple{MyInt8,MyInt8}, ::Tuple{MyInt8,MyInt8}) at ./promotion.jl:300
 [4] +(::MyInt8, ::MyInt8) at ./int.jl:921
 [5] top-level scope at REPL[41]:1

In that particular case, the inherited implementation of + is only there to handle the addition of two operands of different types; I guess you'll have to implement + for MyInt8 yourself, in much the same way as Int8 implements its own addition:
julia> which(+, (Int8, Int8))
+(x::T, y::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} in Base at int.jl:86

I'd probably go for an implementation like the following:
julia> Base.:+(a::MyInt8, b::MyInt8) = MyInt8(Int8(a)+Int8(b))

julia> a + a
6

EDIT:
This should reach the same performances as the native Int8 type:
# two Int8 vectors
julia> a1 = rand(Int8, 1000); b1 = rand(Int8, 1000);

# same vectors, as MyInt8 values
julia> a2 = MyInt8.(a1);      b2 = MyInt8.(b1);

# check that both ways of doing the calculation produce the same results
julia> @assert a1 .+ b1 == Int8.(a2 .+ b2)

# Benchmark
julia> using BenchmarkTools
julia> @benchmark $a1 .+ $b1
BenchmarkTools.Trial:
  memory estimate:  1.06 KiB
  allocs estimate:  1
  --------------
  minimum time:     145.274 ns (0.00% GC)
  median time:      176.402 ns (0.00% GC)
  mean time:        200.996 ns (4.20% GC)
  maximum time:     1.349 μs (79.34% GC)
  --------------
  samples:          10000
  evals/sample:     759

julia> @benchmark $a2 .+ $b2
BenchmarkTools.Trial:
  memory estimate:  1.06 KiB
  allocs estimate:  1
  --------------
  minimum time:     140.316 ns (0.00% GC)
  median time:      172.119 ns (0.00% GC)
  mean time:        195.947 ns (4.54% GC)
  maximum time:     1.148 μs (73.34% GC)
  --------------
  samples:          10000
  evals/sample:     750


text:
Q: Give a family of sets $\{F_a\}$ with each $F_a\subseteq (0,1)$ and $F_a \cap F_b \neq \emptyset$ but $\bigcap_aF_a = \emptyset$. Give a family of sets $\{F_a\}$ with each $F_a\subseteq (0,1)$ and $F_a \cap F_b \neq \emptyset$ but $\bigcap_aF_a = \emptyset$.
What is an example of such a family of sets?

A: A standard example in analysis is to let your $F_n = (0,1/n), n \in \mathbb{N}$. This ensures that any two $F_n$ intersect, but the intersection of all of the $F_n$ is $\emptyset$.
Specifically, for $n < m$, $F_n \cap F_m = F_m$. However, for any $a > 0$, $F_n$ does not contain $a$ when $1/n < a$.

A: You can go much easier on this. Pick any three numbers $a_1,a_2$ and $a_3$ in $(0,1)$ and let
$$F = \{\{a_1, a_2\}, \{a_1, a_3\}, \{a_2, a_3\}\}$$
The family is finite and indexed by $\{1,2,3\}$, $F_1\cap F_2 = \{a_1\}, F_1\cap F_3 = \{a_2\}, F_2\cap F_3 = \{a_3\}$ but
$$\bigcap_{i=1}^3 F_i = \emptyset$$
This example is minimal in the sense that if the index set is any smaller ($2$ sets), it doesn't work anymore and if the sets are any smaller ($1$ element per set), it doesn't work either.

For a general construction prescribed a finite index set $I \subset \mathbb N$ with $|I| \ge 3$ you can simply pick an indexed set $A$ and define
$$A(S) := \{a_s \mid s\in S\}\\
F_i := A(I \setminus \{i\})$$
Then $F_i\cap F_j = A(I\setminus\{i,j\}) \ne \emptyset$ since $|I| > 2$ and
$$\bigcap_{i\in I} F_i = A\left(I \setminus \bigcup_{i\in I} \{i\}\right) = \emptyset$$

A: Let me try.
Take the numbers $K_2 \subset \mathbb{N}$ divisible by $2$, and in general $K_n$ divisible by $n > 2$.
For any $n,m$ the intersection of $K_n, K_m$ is non-empty containing the multiples of $n\times m$.
But the intersection $\cap_a K_a = \emptyset$
Now take the set $S_2$ of the form $\frac{1}{k_2}, k_2 \in K_2$, and in general $S_n$ of the form $\frac{1}{k_n}, n > 2$, that is, the inverse of the previous sets.
They satisfy $\cap_a S_a = \emptyset$ and $S_a \subseteq (0,1)$.


text:
Q: DOMDocument loadHTMLFile() gets reformatted I have the following script:
$incldoc = new DOMDocument();

libxml_use_internal_errors(true);
$incldoc->loadHTMLFile($filename, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
libxml_use_internal_errors(false);

echo $incldoc->saveHTML();

Which loads this file:

Hello!

<monkey>test</monkey>

When It gets output it looks like this:

Hello!

    <monkey>test</monkey>

Is there anyway for me to load the file without it getting formatted?

A: It's a little long, but how about:
$doc = new DOMDocument();
$doc->loadXML('<root/>');

$fragment = $doc->createDocumentFragment();
$fragment->appendXML(file_get_contents($filename));
$doc->documentElement->appendChild($fragment);

$html = implode(
    array_map(
        function($node) use ($doc) {
            return $doc->saveHTML($node);
        },
        iterator_to_array($doc->documentElement->childNodes)
    )
);

echo $html;


text:
Q: How to do bool Queries in ElasticSearch with Java Api? iam trying to send a bool query against my elasticSearch, that filters out documents. How can i filter boolean expressions like (A AND B AND C) AND (D OR E OR F) AND G with BooleanQueryBuilder Api in Java? I tried with the filter method, but i get no results back. For example:
Imagine A, B, C, D, E, F, G are events where the attribute "name" must match "Robin" for example.
private QueryBuilder getQueryBuilder() {

        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders
                .boolQuery()
                .filter(QueryBuilders.matchQuery(D).operator(Operator.OR))
                .filter(QueryBuilders.matchQuery(E).operator(Operator.OR))
                .filter(F);

        BoolQueryBuilder boolQueryBuilder2 = QueryBuilders
                .boolQuery()
                .filter(QueryBuilders.matchQuery(A).operator(Operator.AND))
                .filter(QueryBuilders.matchQuery(B).operator(Operator.AND))
                .filter(QueryBuilders.matchQuery(C));

        BoolQueryBuilder boolQueryBuilder3 = QueryBuilders
                .boolQuery()
                .filter(G);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders
                .boolQuery()
                .filter(boolQueryBuilder1)
                .filter(boolQueryBuilder2)
                .filter(boolQueryBuilder3);

        return boolQueryBuilder;

}

I know this example is not very good, but i hope u can help me!
Thanks!

A: Is this one?
private static QueryBuilder getQueryBuilder() {
    //condition
    MatchQueryBuilder A = QueryBuilders.matchQuery("content", "A");
    MatchQueryBuilder B = QueryBuilders.matchQuery("content", "B");
    MatchQueryBuilder C = QueryBuilders.matchQuery("content", "C");
    MatchQueryBuilder D = QueryBuilders.matchQuery("content", "D");
    MatchQueryBuilder E = QueryBuilders.matchQuery("content", "E");
    MatchQueryBuilder F = QueryBuilders.matchQuery("content", "F");
    MatchQueryBuilder G = QueryBuilders.matchQuery("name", "Robin");
    //Maybe you should use TermQuery
    //TermQueryBuilder G = QueryBuilders.termQuery("name", "Robin");

    //1.(A AND B AND C)
    BoolQueryBuilder query1 = QueryBuilders.boolQuery();
    query1.must(A).must(B).must(C);

    //2.(D OR E OR F)
    BoolQueryBuilder query2 = QueryBuilders.boolQuery();
    query2.should(D).should(E).should(F);

    //3.Last
    BoolQueryBuilder lastQuery = QueryBuilders.boolQuery();
    lastQuery.must(query1).must(query2).must(G);

    //use filter
    BoolQueryBuilder filterBuiler = QueryBuilders.boolQuery().filter(lastQuery);
    return filterBuiler;
}


text:
Q: Having problems with setting up php mail() on Plesk I'm setting up an email form for a website and the mail() function just refuses to work. The server's running Plesk. I'm sure the code's fine, as it runs without a problem on a different web server.
I've set up a no-reply email account and added the from header, but that still didn't fix the issue. Here's my code:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name, $email \nMessage: $message";
$to = "myemail@differentdomain.com";
$subject = $_POST['subject'];
$headers = 'From: noreply@mydomain.com' . "\r\n" .
'Reply-To: $email' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $formcontent, $headers);

Any ideas?
Thanks,
Ilian

A: The code itself isn't enough to judge. Sending mail would depend on

*

*PHP code (it seems ok)

*PHP config (it is unknown). PHP on your server can be configured to send through command line (sendmail tool) or through SMTP. More details can be learned from description of mail() function in PHP docs

*Setup MTA (unknown) - i.e. authentication mode in remote SMTP OR availability of local unauthorized delivery via sendmail tool (which might be blocked to prevent sending spam)

*In case of remote SMTP connection availability of mail server would be important

I would recommend checking all stages.The code itself is just one of many factors
 when network communication is involved.


text:
Q: Dedicated server for running a Mail Server I was wondering what kind of server(s) do I need if I want to run a mail server that handles approx 200+ email accounts with each averaging 50 emails per day?
Mail server setup would be:

*

*Postfix: to send and receive mail via SMTP.

*Dovecot: POP and IMAP server to manage local mail directories and allows users to log in and download their mail and handle user authentication.

*Postgrey: to greylist incoming mail, requiring unfamiliar deliverers to wait for a while and then resend.

*amavisd-new: manager for organizing antivirus and spam checking content filters.

*Clam AntiVirus: virus detection suite.

*SpamAssassin: for sniffing out spam in emails.

*Postfix Admin: web front end for administering mail users and domains.

*Afterlogic WebMail Lite: beautiful webmail interface for users.

*SSL Certificate
Yes, I could use Amazon EC2 instance(s) but from what I understand, they have limitations in sending email from EC2 instances and also emails from Amazon IPs end up in Spam. Besides these, my requirement is kind of special, its not just a regular mail server that I'm looking to setup (would've use Gmail for business) so a dedicated server would probably be best solution.
So my questions:

*

*Will I still have email sending limitations using a dedicated server?

*What kind of server(s) do I need for this requirement (200 * 50)?

*Are there any cost-effective hosting providers that would set up the mail server for me at a nominal cost?

*Any other things to consider when running a mail server yourself?

A: To answer your questions:

*

*Normally you should not encounter limitations on a dedicated server, but this is dependent to the provider from which you buy the server. You should see their terms of service and contact support prior to purchase.

*For safety you should consider having at least Raid1 as storage configuration (size of HDD depends on your knowledge of the actual disk spaced used by your users, but any decent dedicated server should cover storage needs)
CPU: 1 Core should do the job, dual core better, anything larger than this would give you extra processing reserves
RAM: 4 GB would be a safe point of start with plenty of reserves.

*Usually dedicated providers do not offer this kind of assistance, at least not for free, being calculated as an additional service, but if you do some research on the internet and have a base of technical knowledge you might get along with doing it yourself.

*
*

*SPAM. Be sure your user's computers are secure, protected by an updated firewall, and that their passwords are as complex as possible. Also, always use encrypted connections, there are network sniffing malware that might capture your users email authentication details and use your server to send SPAM, this will result in listing of your server's IP address in multiple RBL's, a bad sender reputation, and your client's valid emails will no longer reach most of their recipients.

*Also you might consider using a firewall on that server (ex. CSF http://configserver.com/cp/csf.html).

*Monitor your server using specific software/solutions (zabbix/nagios and pingdom for real-time alerts)


text:
Q: How can I stop nginx from retrying PUT or POST requests on upstream server timeout? We are using nginx to load balance requests to our application. We have found that nginx switches to a different upstream server when requests time out (good). However it does this for PUT and POST requests which can cause undesirable results (data stored twice). Is it possible to configure nginx to only retry GET requests on timeout? Or is there another way to solve the problem?
Our configuration is as follows:
upstream mash {
    ip_hash;
    server 127.0.0.1:8081;
    server 192.168.0.11:8081;
}

server {
    ...
    location / {
        proxy_pass http://mash/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

A: I know i'm pretty late to the game, but for me this is the top result when searching for this problem, so i wanted to share my solution.
This uses the if directive (with one of the few valid use cases) combined with the custom error handler:
upstream backend {
    server backend1;
    server backend2;
}

server {
    server_name proxy;

    location / {
        error_page 598 = @retry;
        error_page 599 = @no_retry;
        if ($request_method = POST) {
            return 599;
        }
        return 598;
    }

    location @retry {
        proxy_pass http://backend;
    }

    location @no_retry {
        proxy_pass http://backend;
        proxy_next_upstream off;
    }
}

A: Please see here for doc: proxy_next_upstream
Please note this is an untested gist
https://gist.github.com/wojons/6154645

A: Starting in nginx 1.9.13, non-idempotent requests (PUT, POST, etc) are not retried by default. If you can upgrade to this version of later, you can obtain the desired behavior by default.
If for some reason you would like to continue retrying PUT, POST, etc (non-idempotent) requests on 1.9.13 or later, use:
proxy_next_upstream error timeout non_idempotent;

A: use proxy_method directive
refer to: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_method

A: I have same problem in my tomcat server. proxy time out when long request occur. i solved my problem by using proxy_read_timeout. when increase timeout then my request never time outed & not occurred any problem. default time out 60s. reference
location / {
    proxy_pass  http://xxxxxxxxxx.com;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
            proxy_connect_timeout      800;
            proxy_send_timeout         800;
            proxy_read_timeout         240;
}


text:
Q: Unable to extract MKV attachments with FFmpeg I'm trying to extract attachments from an MKV file by following the documentation at http://ffmpeg.org/ffmpeg.html#Main-options
Direct quote from documentation:
To extract all attachments to files determined by the filename tag:
ffmpeg -dump_attachment:t "" INPUT

The command I'm running on my computer is this:
ffmpeg -i test.mkv -dump_attachment:t "" INPUT

However I keep getting the following error:
[NULL @ 0x7f981182ae00] Unable to find a suitable output format for 'INPUT'
INPUT: Invalid argument

How can I extract attachments from my test.mkv file?  Am I misunderstanding what INPUT is supposed to be?
I've tried:
ffmpeg -dump_attachment:t "" test.mkv

and FFmpeg prompts me with this:
File 'test.mkv' already exists. Overwrite ? [y/N].

Entering y replaces test.mkv with a 0 byte file, and no attachments are extracted.

Additional Information:
I installed ffmpeg via brew using the following command:
brew install ffmpeg --with-freetype --with-libass --with-tools

A: The documentation was wrong. This bug has been fixed now. The examples were missing an -i flag to properly designate the input file:
ffmpeg -dump_attachment:t "" -i test.mkv

This worked for me in FFmpeg 1.1.2 and above. Note that FFmpeg will still complain about no output file being specified. Don't worry about this though: The attachments will still be extracted.

You can also extract attachments from MKV files with MKVToolNix.  This set of programs can be easily downloaded from the website for all operating systems, or in OS X installed with brew install mkvtoolnix.
Look at the IDs of your attachments:
mkvmerge -i <mkv-file>

Then extract them:
mkvextract attachments <mkv-file> <attachment-id>:<file-name>

See the mkvextract documentation. If the <file-name> is empty, a name will be chosen automatically. You can also specify multiple pairs of <attachment-id>:<file-name>, of course.


text:
Q: JSON deserialization error when try to reserialize restsharp response I am executing get API and want to retrieve a specific value from the JSON response. I want to get Job: URL value into a variable, but getting following error saying cannot deserialize Json object.

I am using following object model to map Json response.
class BlujayGetJobResponse
{
    public int TotalCount { get; set; }
    public string PreviousPage { get; set; }
    public string NextPage { get; set; }
    public List<Items> Items { get; set; }
}

Job and Items class objects:
 public class Job
        {
            public string Url { get; set; }
            public string Title { get; set; }
        }
        public class Items
        {
            //public List<Consignment> Consignment { get; set; }
            public string Id { get; set; }
            public string DateCreated { get; set; }
            public string Gps { get; set; }
            public string ProcessOutcome { get; set; }
            public string ProcessOutcomeInternal { get; set; }
            public string ProcessType { get; set; }
            public string ProcessTypeInternal { get; set; }
            public string CallingCard { get; set; }
            public string AdhocLocation { get; set; }
            public string ProcessOutcomeReason { get; set; }
            public string ProcessOutcomeReasonInternal { get; set; }
            public string ProcessOutcomeReasonText { get; set; }
            public string IntendedTime { get; set; }
            public string SafePlace { get; set; }
            public string DeliveredToNeighbour { get; set; }
            public string NeighbourAddress { get; set; }
            public string IdentificationDetails { get; set; }
            public List<Job> Job { get; set; }

        }

Response return from the GET API execution gives the following IResponse as content. When I try to deserialize the response to retrieve URL value getting the above error. I am new to restsharp and appreciate if anyone could help me figure this out.
JSON response:
{
  "TotalCount":2,
  "PreviousPage":null,
  "NextPage":null,
  "Items":[
    {
      "Id":"5f67fc87-4dab-4c98-bde9-8ca3ba327052",
      "DateCreated":"\/Date(1638372363000+1300)\/",
      "Gps":null,
      "ProcessOutcome":"SUC",
      "ProcessOutcomeInternal":"31",
      "ProcessType":"OFD",
      "ProcessTypeInternal":"3",
      "CallingCard":null,
      "AdhocLocation":null,
      "ProcessOutcomeReason":null,
      "ProcessOutcomeReasonInternal":null,
      "ProcessOutcomeReasonText":null,
      "IntendedTime":null,
      "SafePlace":null,
      "DeliveredToNeighbour":false,
      "NeighbourAddress":null,
      "IdentificationDetails":null,
      "Job":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Jobs/a08064c8-85fb-4e5e-8ef3-2bd24409b8d0",
        "Title":null
      },
      "Location":null,
      "Packages":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Actions/5f67fc87-4dab-4c98-bde9-8ca3ba327052/Packages/",
        "Title":null
      },
      "Signatures":null,
      "User":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Users/126",
        "Title":null
      },
      "Link":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Actions/5f67fc87-4dab-4c98-bde9-8ca3ba327052",
        "Title":null
      },
      "TransactionId":null
    },
    {
      "Id":"33b0c532-3ca5-4eee-a1db-d012cae064ea",
      "DateCreated":"\/Date(1638419167000+1300)\/",
      "Gps":null,
      "ProcessOutcome":"DELCRE",
      "ProcessOutcomeInternal":"330",
      "ProcessType":"DEL",
      "ProcessTypeInternal":"1",
      "CallingCard":null,
      "AdhocLocation":null,
      "ProcessOutcomeReason":null,
      "ProcessOutcomeReasonInternal":null,
      "ProcessOutcomeReasonText":null,
      "IntendedTime":null,
      "SafePlace":null,
      "DeliveredToNeighbour":false,
      "NeighbourAddress":null,
      "IdentificationDetails":null,
      "Job":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Jobs/d9b93ae1-2b37-400b-ad43-978bbad024d9",
        "Title":null
      },
      "Location":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Depots/53",
        "Title":null
      },
      "Packages":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Actions/33b0c532-3ca5-4eee-a1db-d012cae064ea/Packages/",
        "Title":null
      },
      "Signatures":null,
      "User":null,
      "Link":{
        "Url":"https://freightways-uat.mobilestar.blujaysolutions.net:444/API/v2/Actions/33b0c532-3ca5-4eee-a1db-d012cae064ea",
        "Title":null
      },
      "TransactionId":null
    }
  ]
}

This is how Postman response looks like:

Appreciate it if you can help me out to figure out.
Really appreciate your help.
Thank you.

A: I found the resolution for this issue. Job element is an object not a list. So changing the object model as below, the error was resolved.
public class Job
{
    public string Url { get; set; }
    public object Title { get; set; }
}


text:
Q: How does `Yacc` identifies function calls? I am trying to figure out how yacc identifies function calls in a C code. For Example: if there is a function call like my_fun(a,b); then which rules does this statement reduces to.
I am using the cGrammar present in : C Grammar
Following the Grammar given over there manually; I figured out that we only have two choices in translation unit. Everything has to either be a function definition or a declaration. Now all declaration starts type_specifiers, storage_class_specifier etc but none of them starts with IDENTIFIER
Now in case of a function call the name would be IDENTIFIER. This leaves me unclear as to how it will be parsed and which rules will be used exactly?

A: According to the official yacc specification specified here yacc, everything is handled by user given routines. When you have a function call the name of course is IDENTIFIER.It is parsed using the user defined procedures.According to the specifications, the user can specify his input in terms of individual input characters, or in terms of higher level constructs such as names and numbers. The user-supplied routine may also handle idiomatic features such as comment and continuation conventions, which typically defy easy grammatical specification.
Do have a look.By the way you are supposed to do a thorough research before putting questions here.


text:
Q: Covering Index can't optimize the limit query in mysql8.0 In < High Performance Mysql >, it uses covering index to optimize limit query like this. I used the sakila database downloaded from MySQL official web. Here is the query:
SELECT a.film_id, a.description
  from sakila.film a
  inner join (
    select film_id
      from sakila.film b
      order by title limit 50,5
  ) as lim
  USING(film_id)

But I use explain to analyze the process. It looks like this.
In the third line, it shows that it still scans all the 1000 rows.
Then I tested the subqueryselect film_id from sakila.film b order by title limit 50,5, the explain log like this .
In my opnion, the third line in the first log should be like the second log, and I don't know how to explain the first 2 rows
 in first log, why the rows are 55 and 1, I think maybe they should be 5 and 5. This is the MySQL official demo.  I guess it is because of the version of the mysql.
I update my mysql to the 8.0.11.0, it becames a little more normal like this
I tested same dataset int mysql8.0 and mysql5.6, in mysql5.6 it only need 0.2s to  retrieve data, but in mysql8.0 it need 1s to do it. What is different in them? And
The first row is still 905 rather than 5.  Can somebody tell me the reason and why the first row is 905, the second row is 1?

A: EXPLAIN is notorious for ignoring LIMIT values.
Here's a better way to get a feel for what is going on:
 FLUSH STATUS;
 SELECT ...;
 SHOW SESSION STATUS LIKE 'Handler%';

Using a similar query (on 5.6) on some data I have...
SELECT  city, province, population
    FROM  canada AS a
    JOIN ( SELECT  id
            FROM  canada
            ORDER BY  city
            LIMIT  300,20    -- I used bigger numbers
         ) AS x USING(id);

(The table has 5484 rows.)
mysql> SHOW SESSION STATUS LIKE 'Handler%';
+----------------------------+-------+
| Variable_name              | Value |
+----------------------------+-------+
| Handler_commit             | 1     |
| Handler_delete             | 0     |
| Handler_discover           | 0     |
| Handler_external_lock      | 4     |
| Handler_mrr_init           | 0     |
| Handler_prepare            | 0     |
| Handler_read_first         | 1     |
| Handler_read_key           | 21    |  -- about 20
| Handler_read_last          | 0     |
| Handler_read_next          | 319   |  -- about 300+20 (OFFSET+LIMIT)
| Handler_read_prev          | 0     |
| Handler_read_rnd           | 0     |
| Handler_read_rnd_next      | 21    |  -- about 20
| Handler_rollback           | 0     |
| Handler_savepoint          | 0     |
| Handler_savepoint_rollback | 0     |
| Handler_update             | 0     |
| Handler_write              | 20    |  -- 20  (the 'derived' table)
+----------------------------+-------+
18 rows in set (0.00 sec)

EXPLAIN:
+----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+
| id | select_type | table      | type   | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+
|  1 | PRIMARY     | <derived2> | ALL    | NULL          | NULL    | NULL    | NULL |  320 | NULL        |
|  1 | PRIMARY     | a          | eq_ref | id            | id      | 4       | x.id |    1 | NULL        |
|  2 | DERIVED     | canada     | index  | NULL          | city_id | 771     | NULL | 5484 | Using index |
+----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+

So...  No table scan.  The OFFSET is included only in the derived table.
The Using index in your EXPLAIN (and mine) confirms the use of a "covering index".
(I think...)  In older versions, EXPLAIN would actually evaluate any Derived table; 8.0 avoids that.  This could partially explain why Explain changed in your two outputs.


text:
Q: Different node tooltips in highcharts sankey diagram In a Highcharts sankey diagram, I would like to label the nodes with a tooltip. The left (sender nodes) should be labeled differently than the right ones (receiver nodes).
Example:
Left node: "CVP (Origin Party Votes): 6000"
Right node: "CVP (Receiver Party Votes): 5000"
I tried it with a nodeFormatter formatting function, but failed.
The jsfiddle is here: https://jsfiddle.net/martindfurrer/ah175o8e/
tooltip: {
    nodeFormatter:
        function() {
             if (this.point.fromNode.name != null) {
                 return (point.name +'(Origin Party Votes): '+point.sum);
             }
             else if (this.point.toNode.name != null) {
                 return (point.name +'(Receiver Party Votes): '+point.sum);
             };
        }
}

A: You can use column to identify left and right nodes (fiddle):
tooltip: {
  nodeFormatter: function() {
    if (this.column === 0) {
      return (this.name + ' (Origin Party Votes): ' + this.sum);
    } else if (this.column === 1) {
      return (this.name + ' (Receiver Party Votes): ' + this.sum);
    }
  }
}

If you put console.log(this) as the first line in the nodeFormatter function, you can explore the available properties on the node.


text:
Q: Automated script to add a comma between and organize ASCII values from a .txt file into rows? I have a list of 20,000+ ASCII values in a .txt file.
ie:
   2.4414063e-04
   3.0517578e-04
   3.6621094e-04
   4.5776367e-04
   5.4931641e-04
   6.4086914e-04
   7.3242188e-04
   8.2397461e-04
   9.1552734e-04
   1.0375977e-03
   1.1596680e-03

I need to add a comma immediately after each entry, also, I would like to organize the information in rows of 10. What is the best method for creating an automated Python script to do this?

A: Read the input_file line by line, storing each value stripped of leading / trailing whitespace in a list.  When the length of the list is equal to 10, join all 10 elements into a string (separated by a comma and space). Append the string to output_file. Reinitialize the list to empty, and repeat until there are no more lines in input_file. After exiting the for loop that reads the lines in the file check if the list has any elements that need to be written to output_file. This would occur if the number of values / lines in input_file is not a multiple of 10.
# Read values from input_file and output as comma-separated values with 10 values per row
def process_input_txt_file(input_file, output_file):
    log.debug('Enter process_input_txt_file')

    # Create / overwrite existing output_file
    open(output_file, 'w+').close()

    # Store each value stripped of leading / trailing whitespace in a list
    value_list = []
    with open(input_file, 'r') as input_fh:
        for line in input_fh:
            value = line.strip()
            value_list += [value]

            if len(value_list) == 10:
                # Store the 10 values as a string, comma-separated
                value_row = '%s' % ', '.join(map(str, value_list))
                # Empty the list
                value_list = []

                # Write the string to output_file, on one line (row)
                with open(output_file, 'a') as output_fh:
                    print(value_row, file=output_fh)

        # Check if value_list contains any elements
        if value_list:
            # Store the remaining values as a string, comma-separated
            value_row = '%s' % ', '.join(map(str, value_list))
            # Write the string to output_file, on one line (row)
            with open(output_file, 'a') as output_fh:
                print(value_row, file=output_fh)

I tested this script with 100,001 values / lines and it took just under 3 seconds:
[2019-09-23 21:52:21,639] [main] Start example.py execution
[2019-09-23 21:52:21,643] [process_input_txt_file] Enter process_input_txt_file
[2019-09-23 21:52:23,931] [main] End example.py execution


text:
Q: Failed Tensorflow Lite conversion: Unsupported data type in placeholder op System information:
Mac OS Mojave
TensorFlow installed from (source or binary):
pip install tensorflow
TensorFlow version (or github SHA if from source):
1.12
I am trying to convert a simple convolutional tensorflow model to tensorflow lite. I already have it in SavedModel format. But when I try to run the convert util on the saved model, I get:
RuntimeError: TOCO failed see console for info.
b"2018-12-30 15:40:54.449737: I tensorflow/contrib/lite/toco/import_tensorflow.cc:189] Unsupported data type in placeholder op: 2\n2018-12-30 15:40:54.450020: F tensorflow/contrib/lite/toco/import_tensorflow.cc:2137] Check failed: status.ok() Unexpected value forattribute 'T'. Expected 'DT_FLOAT'\n"

To save the model, I have:
// model is an Estimator instance
def export(model):
  model.export_saved_model("tmp/export", serving_input_receiver_fn)
and:
def serving_input_receiver_fn():
  features = { 'x': tf.placeholder(shape=[1, 100, 100, 1], dtype=tf.as_dtype(np.int32)) }
  return tf.estimator.export.ServingInputReceiver(features, features)
Input dtype is np.int32, so I attempt to cast that to a tf type here.
I can attach the full model def on request.
Thanks.

A: The solution to this was not in the placeholder op itself, but in the model declaration. I was using a float64 input type. Switching to float32, and setting dtype=float32 in the placeholder, solved my issue.


text:
Q: React web is not working properly after build (related axios api) I use
"webpack": "3.8.1" ,
"react": "^16.5.2"
when start to yarn start app is working
but after the yarn build and serve -s build, not to call api. (but react-router is working)
In other words, it does not work for the http request. After the build
But as a yarn start, http request runs well.
(I use proxy in package.json. front-end is react, backend is spring boot)

A: I suspect your issue is like this. When you are developing you are using a proxy setup in your package.json as you have stated in your question.
When you have this proxy setting, webpack dev server will proxy your request from the client to the server. This is what allows you to leave the baseurl off your request in the app. In other words, because of this proxy you can simply write /api/endpoint/.
When you build and serve using the serve module however, webpack dev server is no longer the one serving your app the the browser, which means there is no more proxying requests from client to server. This means you are making a request to just /api/endpoint/ which means there is no server actually getting your request.
Without actually changing your react code to use the full url including the base url in requests, you would need to actually have the server be responsible for serving the build folder to the web statically. By doing this, your /api/endpoint will point back the server that served the app which is also your api.


text:
Q: Saving API as environment variable (for setting up monkeylearn in R) I would like to use the named entity recognition functions in the monkeylearn package in R.
As part of the setting up process, we need to do the following:
"To get an API key for MonkeyLearn, register at http://monkeylearn.com/. Note that MonkeyLearn supports registration through GitHub, which makes the registration process really easy. For ease of use, save your API key as an environment variable as described at http://stat545.com/bit003_api-key-env-var.html. You might also want to use the usethis::edit_r_environ() function to modify .Renviron.
All functions of the package will conveniently look for your API key using Sys.getenv("MONKEYLEARN_KEY") so if your API key is an environment variable called "MONKEYLEARN_KEY" you don't need to input it manually.
Please also create a "MONKEYLEARN_PLAN" environment variable indicating whether your Monkeylearn plan is "free", "team", "business" or "custom". If you do not indicate it by default it will be "free" with a message. If your plan is "custom" you'll need a third environment variable "MONKEYLEARN_RATE" indicating the maximum amount of requests per minute that you can make to the API. If you do not indicate it, by default it will be 120 with a message."
I've gotten the API key, but as a layman, I couldn't understand the guide on saving the api key as environment variable. Could anyone provide a step by step guide for Windows please?
Thank you.

A: monkeylearn maintainer here, sorry for the unclear docs.
It means you need to add two lines in an R startup file called .Renviron.
MONKEYLEARN_KEY="blablablayourkey"
MONKEYLEARN_PLAN="free"

The last line of .Renviron has to be an empty line.
To open .Renviron to edit it, you can use usethis::edit_r_environ(). After adding the two lines with your key and plan, don't forget to restart R.
Read more about startup files in general in this resource.
I hope this helps. Note that I don't look up Stack Overflow very often as opposed to rOpenSci's forum


text:
Q: How can the Phabricator "maniphest.edit" API be used to add a ticket to a column while also using its "beforePHIDs" parameter? According to the maniphest.edit "Transaction Type: Column" documentation, the beforePHIDs parameter should be an array of PHIDs. I think this would look like the following:
curl https://5555/api/maniphest.edit \
    -d api.token=api-token \
    -d transactions[0][type]=column \
    -d transactions[0][value][0][columnPHID]=PHID-PCOL-6666 \
    -d transactions[0][value][0][beforePHIDs][0]=PHID-TASK-7777 \
    -d objectIdentifier=PHID-TASK-8888

However, when invoked as such (with beforePHIDs as an array) I get the following error, which seems to contradict the documentation:
Exception when processing transaction of type "column": Error while reading "value[0]": Expected string, got something else.
How does my curl statement need to change for this to work? I've tried every permutation I can think of. Or is this perhaps a bug?
Side note - this works fine, but it doesn't allow control for the ticket insertion point:
curl https://5555/api/maniphest.edit \
    -d api.token=api-token \
    -d transactions[0][type]=column \
    -d transactions[0][value][0]=PHID-PCOL-6666 \
    -d objectIdentifier=PHID-TASK-8888


text:
Q: JQuery Remove name/value pair from array I have an array which I populate as following. How do I remove an element from the array?
myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );

Update: I would have to remove specific element from the array, say { "name": "one", "value": "1" } element from the array.

A: You can use jQuery.grep to filter out the one you want to remove
var myArray = [];
myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );
myArray = jQuery.grep(myArray, function(value) {
  return value.name != "one"; // return only if name isn't "one"
});
console.log(myArray); // now myArray doesn't contain  { "name": "one", "value": "1" }  in the array

FIDDLE

A: You could use built-in functions (links : splice, pop, shift) :
var a = [1, 2, 3, 4, 5, 6];
a.splice(1, 1); // [2]     a -> [1, 3, 4, 5, 6]
a.splice(1, 2); // [3, 4]  a -> [1, 5, 6]
a.pop();        // 6       a -> [1, 5]
a.shift();      // 1       a -> [5]

Or create your own functions to check some criteria :
// returns the removed element

function removeFirst(array, fn) {
    var i = 0;
    while (i < array.length) {
        if (fn(array[i]) !== true) i++;
        else return array.splice(i, 1)[0];
    }
}

// returns an array containing the removed elements

function removeAll(array, fn) {
    var i = 0, removed = [];
    while (i < array.length) {
        if (fn(array[i]) !== true) i++;
        else removed.push(array.splice(i, 1)[0]);
    }
    return removed;
}

Usage examples :
var array = [
    { name: 'one', value: 11 },
    { name: 'one', value: 1 },
    { name: 'two', value: 2 },
    { name: 'three', value: 3 },
    { name: 'four', value: 4 }
];

// removed -> { name: 'one', value: 1 }

var removed = removeFirst(array, function (item) {
    return item.name === 'one' && item.value === 1;
});

// removed -> [{ name: 'two', value: 2 }, { name: 'three', value: 3 }]

var removed = removeAll(array, function (item) {
    return item.name.charAt(0) === 't';
});

// array -> [{ name: 'one', value: 11 }, { name: 'four', value: 4 }]

A: var myArray = [];
myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );

//console.log(myArray.toSource()); //FF displays output, google chrome gives error

alert(JSON.stringify(myArray));
//output   [{name:"one", value:"1"}, {name:"two", value:"2"}]

var index = myArray[ 'one' ];
myArray.splice(index, 1);

//console.log(myArray.toSource());   //FF displays output, google chrome gives error

alert(JSON.stringify(myArray));
//output  [{name:"two", value:"2"}]


text:
Q: How to make the camera follow an airplane in opengl? I'm trying to make a flight simulator in opengl but I just cannot make my camera follow the airplane properly. I thought that if I apply the same set of transformations both on the camera and on he airplane it would work but it doesn't. When I'm saying transformations I'm talking about the rotations using pith, and yaw angles (I have ignored roll angle for the moment) and the translations the are required to move the airplane around.
This is my Camera class:
namespace gps {

Camera::Camera(glm::vec3 cameraPosition, glm::vec3 cameraTarget)
{
    this->cameraPosition = cameraPosition;
    this->cameraTarget = cameraTarget;
    this->cameraDirection = glm::normalize(cameraTarget - cameraPosition);
    this->cameraRightDirection = glm::normalize(glm::cross(this->cameraDirection, glm::vec3(0.0f, 1.0f, 0.0f)));
}

glm::mat4 Camera::getViewMatrix()
{
    return glm::lookAt(cameraPosition, cameraPosition + cameraDirection , glm::vec3(0.0f, 1.0f, 0.0f));
}

glm::vec3 Camera::getCameraPosition()
{
    return cameraPosition;
}

void Camera::move(MOVE_DIRECTION direction, float speed)
{
    switch (direction) {
        case MOVE_FORWARD:
            cameraPosition += cameraDirection * speed;
            break;

        case MOVE_BACKWARD:
            cameraPosition -= cameraDirection * speed;
            break;

        case MOVE_RIGHT:
            cameraPosition += glm::normalize(glm::cross(cameraDirection, glm::vec3(0.0f, 1.0f, 0.0f))) * speed;
            break;

        case MOVE_LEFT:
            cameraPosition -= glm::normalize(glm::cross(cameraDirection, glm::vec3(0.0f, 1.0f, 0.0f))) * speed;
            break;
    }
}

void Camera::rotate(float pitch, float yaw)
{
    glm::vec3 front;
    front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    front.y = sin(glm::radians(pitch));
    front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    cameraDirection = glm::normalize(front);
}

}
I have created 2 cameras: one that is supposed to follow the airplane around and the other one that is supposed to apply the set of transformations on the plane.
gps::Camera myCamera(glm::vec3(0.0f, 0.0f, 2.5f), glm::vec3(0.0f, 0.0f, -10.0f));
gps::Camera planeCamera(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -10.0f));

This is my renderScene function:
void renderScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

processMovement();

//initialize the view matrix
view = myCamera.getViewMatrix();
//send view matrix data to shader
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

//plane
model = glm::mat4(1.0f);

model = planeCamera.getViewMatrix();

glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
normalMatrix = glm::mat3(glm::inverseTranspose(view*model));
//send normal matrix data to shader
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix));
planeModel.Draw(myCustomShader);
}

processMovement goes something like this:
void processMovement()
{
if (pressedKeys[GLFW_KEY_W]) {
    myCamera.move(gps::MOVE_FORWARD, cameraSpeed);
    planeCamera.move(gps::MOVE_BACKWARD, cameraSpeed);
}

if (pressedKeys[GLFW_KEY_S]) {
    myCamera.move(gps::MOVE_BACKWARD, cameraSpeed);
    planeCamera.move(gps::MOVE_FORWARD, cameraSpeed);
}
...
}

And these are are my model, view, projection matrices:
model = glm::mat4(1.0f);
modelLoc = glGetUniformLocation(myCustomShader.shaderProgram, "model");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

view = myCamera.getViewMatrix();
viewLoc = glGetUniformLocation(myCustomShader.shaderProgram, "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

normalMatrix = glm::mat3(glm::inverseTranspose(view*model));
normalMatrixLoc = glGetUniformLocation(myCustomShader.shaderProgram, "normalMatrix");
glUniformMatrix3fv(normalMatrixLoc, 1, GL_FALSE, glm::value_ptr(normalMatrix));

projection = glm::perspective(glm::radians(45.0f), (float)retina_width / (float)retina_height, 0.1f, 1000.0f);
projectionLoc = glGetUniformLocation(myCustomShader.shaderProgram, "projection");
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));


text:
Q: Consolidate Number of Groups Separated by Zeros I am recording from an analog device, and assuming the data resembles an example vector like:
A = [1 4 2 0 4 5 8 8 1 0 0 0 4 7 1 9 0 0 0 8 1 2]

I would like to:
1) Count the number of groups of non-zero elements
2) Consolidate the groups that might belong to the same condition
For 1), we might split it into
1 4 2
4 5 8 8 1
4 7 1 9
8 1 2
However, for 2), there is a chance that the values separated by the first, single 0 is actually from the same condition compared to the values separated by more zeros, which means that the vector might be actually split into
1 4 2 4 5 8 8 1
4 7 1 9
8 1 2
A past solution for (1) can be found here, which is:
count = sum(diff([A 0]==0)==1)
a0 = (A~=0);
d = diff(a0);
start = find([a0(1) d]==1)           % Start index of each group
len = find([d -a0(end)]==-1)-start+1 % Length, number of indexes in each group
finish = find([d -a0(end)]==-1)      % Last index of each group
count = length(start);
B = cell(count,1);
for i = 1:count
B{i} = A(start(i):finish(i));

Since I didn't want to necro an old thread, I was wondering if there is a way to make the grouping more robust so that values that are separated by single or double zeros are not split off into an entirely new group.

A: The case of integer values in range [0:9]
There is a very elegant one-line solution using regular expressions.
First of all convert the vector as a string:
A = [1 4 2 0 4 5 8 8 1 0 0 0 4 7 1 9 0 0 0 8 1 2];
As=num2str(A);
As(As==' ')=[];

the last line is mandatory due to the fact that num2str() also converts blank spaces between numbers. Therefore As will have the form:
As =

1420458810004719000812

and will be a string.
Now the regexp():
out = regexp(As,'0{2,}','split');

Such expression basically says: from As grab the indices in which there are two or more consecutive zeros and return (thanks to split) the non-matching sequences (i.e. we do not what the zeros, we want the non-zeros part of the sequence).
However, out will be a cell array due to the fact that As is a string. If you want it back to numeric, just add:
out=cellfun(@str2num,out);

in order to convert the cell array with strings into a matrix (with numbers of course). Indeed now out has the form:
out =

   142045881        4719         812

The floating point case
A = [0.01 0.04 0.02 0.00 0.04 0.05 0.08 0.08 0.01 0.00 0.00 0.00 0.04 0.07 0.01 0.09 0.00 0.00 0.00 0.08 0.01 0.02];
As=num2str(A);
As(As==' ')=[];

Now As has the form:
As =

0.010.040.0200.040.050.080.080.010000.040.070.010.090000.080.010.02

The two or more zeros are now hard to find. However, patterns emerge: such set of zeros have a non-zero number before (the last decimal from previous number) and have another zero after (if it was a "normal" zero it'd have a decimal point)
[sID,eID]=regexp(As,'[1-9]00{2,}');

where sID and eID are the start and end indices of our substring target(s), respectively [1]. Now let's split As thanks to the above indices [2]:
C{1}=As(1:sID(1));
for ii=2:length(sID)
    C{end+1}=As(eID(ii-1):sID(ii));
end
C{end+1}=As(eID(end):end);

The cell array C now is rather messy due to the fact that there's no such thing as 0.00 or even 000 because Matlab treat 0.00 as simply 0 but we must append a .00 in order to rebuild the original sequence:
for i=1:length(C)
    idx=strfind(C{i},'00');
    if isempty(idx)==false
        C{i}=[C{i}(1:idx) '.00' C{i}(idx+1:end)];
    end
    C{i}=reshape(C{i},4,[])';
end

In the above code, we also reshaped the long strings into matrices, so now we can easily convert them into numeric
C1=cellfun(@str2num,C,'UniformOutput',0);

Now C1 is still a cell array where every cell is a chunk of sequence (in numeric array form). Obviously now we cannot rely on matrices and we are forced to use cell arrays due to the fact that chunks might have different lengths.
Final note
If A has numbers in range {0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08 0.09} you can as well multiply A by 100: in that case A will be a vector of integers and you can easily use the more elegant Integer approach. Then you can convert them back to floating point using this little snippet:
for ii=1:length(out)
    out{ii}=num2str(out{ii});                             %convert to string, so we can enumerate and treat digits separately
    out{ii}=[repmat('0.0',length(out{ii}),1) out{ii}(:)]; %put '0.0' in front of every number
    out{ii}=str2num(out{ii});                             %roll-back to numeric
end

It is finally worth noticing that given the A definition as in the beginning of The floating point case both the floating point case itself and the latter lead to the same results.
[1] suggested by @LuisMendo
[2] improved thanks to @Adiel


text:
Q: How to set 0, higher than 0 in sympy after substituting I have some lengthy expressions with symbols etc in them. After evaluating them while using .subs({...}) and substituting all variables,  I get values 10^{-18} etc which I know they should be equal to zero.
Do you have some way to set them zero without checking every variable and doing it manually?

A: You can use the chop option for evalf (aka n):
>>> ((pi + pi*I)**2).n()
-0.e-21 + 19.7392088021787*I
>>> ((pi + pi*I)**2).n(chop=True)
19.7392088021787*I

You can set the level of chopping, too:
>>> ((pi + pi*I)**2).n(chop=1e-23)
-0.e-21 + 19.7392088021787*I
>>> ((pi + pi*I)**2).n(chop=1e-20)
 19.7392088021787*I


text:
Q: Linux copy directory structure and create symlinks to existing files with different extension I have a large directory structure similar to the following
/home/user/abc/src1
                   /file_a.xxx
                   /file_b.xxx
/home/user/abc/src2
                   /file_a.xxx
                   /file_b.xxx

It contains multiple srcX folders and has many files, most of the files have a .xxx extension. These are the ones that I am interested in.
I would like to create an identical directory structure in say /tmp. This part I have been able to accomplish via rsync
rsync -av -f"+ */" -f"- *" /home/user/abc/ /tmp/xyz/

The next step is what I can't figure out. I need the directory structure in /tmp/xyz to have symlinks to all the files in /home/user/abc with a different file extension (.zzz). The directory structure would look as follows:
/tmp/xyz/src1
             /file_a.zzz -> /home/user/abc/src1/file_a.xxx
             /file_b.zzz -> /home/user/abc/src1/file_b.xxx
/tmp/xyz/src2
             /file_a.zzz -> /home/user/abc/src2/file_a.xxx
             /file_b.zzz -> /home/user/abc/src2/file_b.xxx

I understand that I could just copy the data and do a batch rename. That is not an acceptable solution.
How do I recursively create symlinks for all the .xxx files in /home/user/abc and link them to /tmp/xyz with a .zzz extension.
The find + exec seems like what I want but I can't put 2 and 2 together on this one.

A: This could work
cd /tmp/xyz/src1
find /home/user/abc/src1/ -type f -print0 | xargs -r0 -I '{}' ln -s '{}' $(basename '{}' .xxx).zzz

A: Navigate to /tmp/xyz/ then run the following script:
#!/usr/bin/env bash

# First make src* folders in present directory:
mkdir -p $(find ~/user/abc/src* -type d -name "src*" | rev | cut -d"/" -f1 | rev)

# Then make symbolic links:
while read -r -d' ' file; do
    ln -s  ${file} $(echo ${file} | rev | cut -d/ -f-2 | rev  | sed 's/\.xxx/\.zzz/')
done <<< $(echo "$(find ~/user/abc/src* -type f -name '*.xxx') dummy")

A: Thanks for the input all. Based upon the ideas I saw I was able to come up with a script that fits my needs.
#!/bin/bash

GLOBAL_SRC_DIR="/home/usr/abc"
GLOBAL_DEST_DIR="/tmp/xyz"

create_symlinks ()
{
    local SRC_DIR="${1}"
    local DEST_DIR="${2}"

    # read in our file, use null terminator
    while IFS= read -r -d $'\0' file; do

            # If file ends with .xxx or .yyy
            if [[ ${file} =~ .*\.(xxx|yyy) ]] ; then
                    basePath="$(dirname ${file})"
                    fileName="$(basename ${file})"
                    completeSourcePath="${basePath}/${fileName}"
                    #echo "${completeSourcePath}"

                    # strip off preceding text
                    partialDestPath=$(echo ${basePath} | sed -r "s|^${SRC_DIR}||" )
                    fullDestPath="${DEST_DIR}/${partialDestPath}"

                    # rename file from .xxx to .zzz. don't rename just link .yyy
                    cppFileName=$(echo ${fileName} | sed -r "s|\.xxx$|\.zzz|" )
                    completeDestinationPath="${fullDestPath}/${cppFileName}"

                    $(ln -s ${completeSourcePath} ${completeDestinationPath})
            fi
    done < <(find ${SRC_DIR} -type f -print0)
}

main ()
{
    create_symlinks ${GLOBAL_SRC_DIR} ${GLOBAL_DEST_DIR}
}

main


text:
Q: Virtual Interface Not Showing up in ifconfig? I am trying to create a virtual interface for the purpose of NameBased Virtual Hosting on my CentOS linux box; please find below is the devices' information:-
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=00:0c:29:4e:1c:14
MTU=1500
NM_CONTROLLED=yes
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
PEERDNS=yes
IPV6INIT=no

DEVICE=eth0:1
BOOTPROTO=none
IPADDR=192.168.1.5
NETMASK=255.255.255.0
NM_CONTROLLED=yes
ONBOOT=no
HWADDR=00:0C:29:4E:1C:14
TYPE=Ethernet
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0:1"
UUID=7758ac79-c4a2-dd87-1760-71284a316d00

Running ifconfig doesn't show the virtual device eth0:1;
[root@centos network-scripts]# ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:0C:29:4E:1C:14
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe4e:1c14/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:24368 errors:0 dropped:0 overruns:0 frame:0
          TX packets:21884 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:9793531 (9.3 MiB)  TX bytes:4460526 (4.2 MiB)
          Interrupt:19 Base address:0x2000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:799 errors:0 dropped:0 overruns:0 frame:0
          TX packets:799 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:82196 (80.2 KiB)  TX bytes:82196 (80.2 KiB)

pan0      Link encap:Ethernet  HWaddr EE:75:AD:75:9C:84
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

sit0      Link encap:IPv6-in-IPv4
          NOARP  MTU:1480  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

Any ideas what I might be missing.
----------Edit 1:-
Restarted my linux box and could see all the configured virtual interfaces as below:-
After System Restart:-
[root@centos ~]# date
Tue Apr 30 21:25:16 PDT 2013
[root@centos ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:4E:1C:14
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe4e:1c14/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:97 errors:0 dropped:0 overruns:0 frame:0
          TX packets:117 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:9756 (9.5 KiB)  TX bytes:17204 (16.8 KiB)
          Interrupt:19 Base address:0x2000

eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:4E:1C:14
          inet addr:192.168.1.10  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:19 Base address:0x2000

eth0:2    Link encap:Ethernet  HWaddr 00:0C:29:4E:1C:14
          inet addr:192.168.1.40  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:19 Base address:0x2000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:4 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:240 (240.0 b)  TX bytes:240 (240.0 b)

But after doing system-network-restart all my settings are gone: Please find below is the result after running the command:-
[root@centos ~]# service network restart
Shutting down interface eth0:  Device state: 3 (disconnected)
                                                           [  OK  ]
Shutting down loopback interface:                          [  OK  ]
Bringing up loopback interface:                            [  OK  ]
Bringing up interface eth0:  Active connection state: activating
Active connection path: /org/freedesktop/NetworkManager/ActiveConnection/1
state: activated
Connection activated

[root@centos ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:4E:1C:14
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe4e:1c14/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:290 errors:0 dropped:0 overruns:0 frame:0
          TX packets:292 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:25640 (25.0 KiB)  TX bytes:41720 (40.7 KiB)
          Interrupt:19 Base address:0x2000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:4 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:240 (240.0 b)  TX bytes:240 (240.0 b)

A: You need to set
ONBOOT=yes

then that interface will Up when you start/restart network service
Or you can manually Up that interface using
ifup eth0:1

for down
ifdown eth0:1

A: The virtual interface (aka. alias device) needs to be in it's own separate file ifcfg-eth0:1 like so:
# /etc/sysconfig/network-scripts/ifcfg-eth0:1
DEVICE=eth0:1
BOOTPROTO=static
IPADDR=192.168.1.5
NETMASK=255.255.255.0
NM_CONTROLLED=yes
ONBOOT=yes
HWADDR=00:0C:29:4E:1C:14
TYPE=Ethernet
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0:1"
UUID=7758ac79-c4a2-dd87-1760-71284a316d00

References

*

*Adding Virtual Network Interfaces on CentOS 5.x

A: You must change BOOTPROTO=none to BOOTPROTO=static.


text:
Q: Discovering component identifiers of a SAP transaction' fields to utilize Through a lot of Googling I managed to connect to SAP and open a transaction from VBA code. This is not part of the problem, so I won't include it here.
My problem is as follows: Now that I have the transaction open, I want to enter values into the fields of the transaction from my code.
I assume this is done by code similar to this:
session.findById("wnd[0]/usr/ctxtVendor").Text

However, the /usr/ctxtVendor part is obviously wrong. If I understand correctly, this is pretty much different on a company basis.
One solution is to use the "SAP Script Recording & Playback" utility to generate VBA code and extract the variablenames. Unfortunately I am not authorized to use this, and I won't be any time soon so that is not an option.
EDIT: I found a second solution:but it doesn't seem as if I have access to this.
Are there other ways of discovering the identifiers for this and other transactions?
Thank you for reading and hopefully for providing an answer.

A: Sorry i gave you the wrong info for VBA scriptable names. Make your window a variable like so:
Dim window As SAPFEWSELib.GuiFrameWindow
Set window = session.FindById("wnd[0]")

Then you go to the Locals window in your VBEditor, and see it here:

For me, the /usr area is Item 5 of the window children, open it up and look for all the fields listed. You can use the path provided. E.g. Below i have opened up Item 2 which is Account number, and you see the string needed in Id property.

Then you use it like so:
window.FindById("usr/ctxtRACCT-LOW").Text = "A123456"