text:
Q: How can i achieve a validation rule to ensure that the values of two columns in a database does not have duplicate using laravel This piece of code is working very well but i don't thing its efficient or clean enough if anyone has a better way of doing this please you can always help meenter image description here

A: you can do with a FormRequest and unique Rule:
class EditVmodelRequest extends FormRequest {

public function rules()
{

    $id = $this->route('id');
    $vehicle = VehicleType::findOrFail($id);

    $unique = Rule::unique($vehicle->getTable(), 'model_name')
        ->ignore($vehicle)
        ->where('model_year', $this->request->get('model_year'));

    return [
        'model_name' => ['required', $unique],
        'model_year' => ['int','required'],
    ];
}
}

then in Controller:
public function editvmodel(EditVmodelRequest $request, $id)
{
    $validated = $request->validated();
    $vmodel = VehicleType::findOrFail($id);
    $vmodel->update($validated);
}


text:
Q: MySQL join multiple tables? I have 3 tables
tblMarkers
tblReviews
tblImages
I want to return ALL the records from tblMarkers and a count of all the reviews and images for each marker.
To complicate it further it should return all the markers within a radius of a known point.
so the expected result would be
MarkerID-MarkerName-ReviewCount-ImageCount
1223-SomeName-0-1
This is what I have so far and this returns a count of reviews, but I cant get the right SQL to add the count of images
SELECT
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`,
(3959 * acos( cos( radians('45.1') ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians('6') ) + sin( radians('45.1') ) * sin( radians( Latitude ) ) ) )
AS distance,
Count(`tblReviews`.`marker_id`) As reviewCount
FROM
`tblMarkers`
LEFT JOIN `tblReviews` ON `tblMarkers`.`ID` = `tblReviews`.`marker_id`
GROUP BY
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`
HAVING
`distance` < '50'
ORDER BY
distance;

The Images table structure is
ID [primaryKey] (same as tblMarkers.ID)
file
title

How do I add a count of all the images?

A: Try this:
SELECT M.ID
    , M.Type
    , M.Name
    , M.Latitude
    , M.Longitude
    , (3959 * acos(cos(radians('45.1')) * cos(radians(M.Latitude )) * cos(radians(M.Longitude) - radians('6')) + sin(radians('45.1')) * sin(radians(M.Latitude ))))  AS distance
    , IFNULL(COUNT(DISTINCT R.review_id) , 0) AS ReviewCount
    , IFNULL(COUNT(DISTINCT I.ID), 0) AS ImageCount
    FROM tblMarkers AS M
    LEFT JOIN tblReviews AS R ON R.marker_id = M.ID
    LEFT JOIN tblImages AS I ON I.marker_id = M.ID
    GROUP BY M.ID, M.Type, M.Name, M.Latitude, M.Longitude
    HAVING distance < 50
    ORDER BY distance

I bet you already know LEFT JOIN. So I used COUNT(DISTINCT R.review_id)) to count all distinct review id's (just make sure that review_id is unique). In case there are no corresponding review and image record for a specific marker record, I used IFNULL(XXX , 0) to display 0.
I used ALIASES to make your query clean and neat. Feel free to ask.

A: IF ID field of image table is the reference of marker table ID field then the query will be:
SELECT
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`,
(3959 * acos( cos( radians('45.1') ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians('6') ) + sin( radians('45.1') ) * sin( radians( Latitude ) ) ) )
AS distance,
Count(`tblReviews`.`marker_id`) As reviewCount,
Count(`tblImage`.`ID`) As imageCount,
FROM
`tblMarkers`
LEFT JOIN `tblReviews` ON `tblMarkers`.`ID` = `tblReviews`.`marker_id`
LEFT JOIN `tblImage` ON `tblMarkers`.`ID` = `tblImages`.`ID`
GROUP BY
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`
HAVING
`distance` < '50'
ORDER BY
distance;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Website Optimiser Control Javascript Could someone explain the javascript that makes up Google's Website Optimiser Control script? Specifically: the first two lines, which seem to be empty functions, and why is the third function wrapped parentheses () ?
As far as I can tell this script is basically writing out a new <script> which presumably loads something for A/B testing.
function utmx_section(){}
function utmx(){}
(function() {
    var k='0634742331',d=document,l=d.location,c=d.cookie;
    function f(n) {
      if(c) {
        var i=c.indexOf(n+'=');
        if (i>-1) {
          var j=c.indexOf(';',i);
          return escape(c.substring(i+n.length+1,j<0?c.length:j))
        }
      }
    }
    var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
    d.write('<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'+'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+'" type="text/javascript" charset="utf-8"></sc'+'ript>')
  }
)();

I've attempted to step through with the firebug debugger but it doesn't seem to like it. Any insights much appreciated.
Many thanks

A: inside anonymous function it shortens names of document and cookies inside it at first, function f(n) gets value of cookie under name n. Then Google reads its cookies and with help of d.write it loads its scripts (as I see they are related to Google Analytic). This way it makes On-Demand JavaScript loading... Actually you load these scripts all the time, Google just needs some additional parameters in url, so this is done this way - save parameters in cookie, which next time are used to get script again.
And finally back to the first two magic lines :) After Google loads its script (after executing d.write), there are some functions which uses utmx and utmx_section, as well as definition of these functions, or better to say overriding. I think they are empty at first just because another function can execute it before its real definition, and having empty functions nothing will happen (and no JS error), otherwise script would not work. E.g. after first iteration there is some data, which is used to make real definition of these functions and everything starts to work :)

A: The first 2 functions are in fact empty, and are probably overridden later on.
The third function is an anonymous self-executing function. The brackets are a convention to make you aware of the fact that it is self executing.
the "f" function looks up the value given to it in the document's cookies and returns it. Then a new script tag is written to document (and requested from server) with these values as part of its URL.


text:
Q: Find coordinate from distance and coordinate I know that this topic has been done already but i believe that my issues is a bit more annoying.
I have a circle which I know its center's coordinate that cross a line like this :
   *****
-*-------*----  <-- The line
*         *
*         * <------ The circle
 *       *
  *******

In addition to that i know the Y coordinates of my line. My problem is the following :
x1,y1 : the coordinates of the circle's center
x2,y2 : the coordinates of the intersection between the circle and the line
r     : the radius of the circle
Knowing x1,y1,y2,r is it possible to get x2 on an equation where x2 is the only element of the right part of our equation (i mean 'x2 = ?')

A: Yes, you can use the distance between points formula
a^2 = (x2-x1)^2 + (y2-y2)^2
The solutions of this equation is the answer you are looking for.


text:
Q: Lines are visible only on the 1st page Here is my detail band:
<detail>
        <band height="20" splitType="Stretch">
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
        <printWhenExpression><![CDATA[$V{antibioResult}]]></printWhenExpression>
        <subreport>
            <reportElement mode="Opaque" x="1" y="1" width="798" height="19" forecolor="#172983" uuid="d6dabfde-0ea9-4b6b-83c4-b557815cedee">
                <property name="com.jaspersoft.studio.unit.y" value="px"/>
                <property name="com.jaspersoft.studio.unit.x" value="px"/>
            </reportElement>
            <subreportParameter name="binary_id">
                <subreportParameterExpression><![CDATA[$P{binary_id}]]></subreportParameterExpression>
            </subreportParameter>
            <dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
            <subreportExpression><![CDATA["bacreport.jasper"]]></subreportExpression>
        </subreport>
        <line>
            <reportElement style="borderLine" stretchType="ContainerHeight" mode="Opaque" x="0" y="0" width="1" height="20" uuid="d5cb2ecc-f71a-4a3c-8d27-7be4c5a86da5">
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
                <property name="com.jaspersoft.studio.unit.y" value="px"/>
                <property name="com.jaspersoft.studio.unit.width" value="px"/>
            </reportElement>
        </line>
        <line>
            <reportElement style="borderLine" stretchType="ContainerHeight" x="800" y="0" width="1" height="20" uuid="08e46ff8-8a65-406b-9164-a6737baa022e">
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
                <property name="com.jaspersoft.studio.unit.y" value="px"/>
                <property name="com.jaspersoft.studio.unit.x" value="px"/>
            </reportElement>
        </line>
    </band>
</detail>

And here is BorderLine style:
    <style name="borderLine" forecolor="#172983"/>

Two lines are visible only in 1st page and not visible in others.
How to fix that?
UPD: It's looks like the lines is not drawn after page break. So how to stretch those line to the whole subreport to several pages?

A: Found a solution: set "Details Overflows" flag to the Line element.


text: Q: Restream youtube live channel wth vlc or ffmpeg` Is it possible to restream a channel with vlc or ffmpeg? I dont think neither will take youtube url as input for restreaming - would there need to be url snooping or w/e its called to get the proper input url?


text:
Q: Sql query: alter current year with DATEADD My current organization's fiscal year isn't equal to the current calendar year, so July 1 is actually month 1 in 2014.
Given the following sql:
SELECT *
FROM (
SELECT F.id, F.account, F.Pd AS Period, F.Actual AS Totals,
    C.PROJ_NAME
    FROM Foo.FinalData F
    INNER JOIN Foo.ProjectCustom C
    ON F.id = C.id
    WHERE F.id LIKE '61000.001.001.%'
    AND F.Account NOT LIKE '%-01'
    AND `F.fy = DATEADD(yy, +1, GetDate())`
) Budget
PIVOT (
    SUM(Totals) FOR Period in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS PivotTable;

How could I write the query to understand July 1 is equivalent to the new current year?

A: I am guessing F.fy column is fiscal year you want to compare with year from date?
Something like this could do the trick:
AND f.fy = YEAR(DATEADD(MM,6,GETDATE()))


text:
Q: Sonar 6.7 - Logout event filter I cannot manage to catch the logout request with a servlet filter. Both /api/authentication/logout and /sessions/logout seem to be uncatchable even though the first is the one directly called when logging out and the second is the referer of several calls after logging out, including the automatic redirection toward sonar home.
How can I catch a logout event with a servlet filter ? I need to invalidate my identity provider token upon logging out.

A: There's no way to add some hook when doing a logout from SonarQube.
In my opinion, you should not try to hack SonarQube in order to disconnect the user from the Identity Provider when he loggout from SonarQube as he may want to use his identity to authenticate on another tool.
If for any reason you really need to do this, you should do it by using a reverse proxy.


text:
Q: Jsoup 1.8.3 missing element I have been using Jsoup 1.7.2 for about a year and thought of updating to version 1.8.3.
I have stumbled across an issue, please check it out:
Here is the document:

  Total transfers

  2

  Gameweek transfers

  2

  Team value

  £99.2m

  In the bank

  £0.3m

Now when I try to select "dd" like doc.select("dd"), it returns an element with size 3 :

 2

 £99.2m

 £0.3m

Ideally in the older version it used to return all the 4 elements.
It could be because the first two "dd" are duplicates.
Is this a bug or a feature and can you tell me how to get all the 4 elements?

A: It looks like this issue has been solved and will be fixed in the next version of jsoup
Ref : https://github.com/jhy/jsoup/issues/614


text:
Q: pthreads memcpy and realloc in C I am trying my luck with pthreads for a problem -
I have two questions about that and will add some excerpts from the code:

*

*I have a struct, which contains an input array and one as output (or result) array. Where do I have to allocate the memory for this result, within the main-function or within the thread-function?

*These results shall be merged into one big result array using realloc and memcpy. I think I am using memcpy and realloc not correctly in this case, or do I?

thread-Function:
struct thread_input {
    unsigned char *buf;
    unsigned char *result;
    int start;
    int end;
    int tid;

};

void* thread_function(void* arg){
    struct thread_input *param = (struct thread_input*)arg;

    param->result = (unsigned char*)malloc((1+(param->end-param->start))*sizeof(unsigned char));

    for(int i = param->start; i <= param->end; i++){

        param->result[i] = some_function(param->buf[i]);
        printf("%d %d\n", param->tid, param->result[i]);
    }

    return NULL;
}

So the some_function is working with every unsigned char and returns it to the param->result array.
This shall be merged here (where n_elemts is the number calculated in every thread):
unsigned char* arr1 = (unsigned char*)malloc(n_elements*sizeof(unsigned char));

    for (int t = 0; t < n_threads; t++){
        pthread_join(threads[t], NULL);

        memcpy(arr1, thread_args[t].result, n_elements);
        if(t<n_threads-1){
            arr1 = (unsigned char*)realloc(arr1, (t+1)*n_elements*sizeof(unsigned char));
        }
    }

    print_function(arr1, fileSize);

The problem given by the compiler is located at the realloc and called "invalid read of size 1", I suppose it is due to a wrong file_size, or array length, after the realloc. Plus the allocation of the param->result that I could not figure out completely.
Thanks for lookin at these excerpts and for any comment! Hope this question was asked in concise enough way, if not bombard me with critic.


text:
Q: AttributeError: 'NoneType' object has no attribute 'list_middleware' in masonite\routes\Route.py", line 166 Upon running python craft migration create_a_table --create a_table I received the following traceback:
Traceback (most recent call last):
  File "SOMEPATH\craft", line 8, in <module>
    from wsgi import application
  File "SOMEPATH\wsgi.py", line 11, in <module>
    application.register_providers(Kernel, ApplicationKernel)
  File "SOMEPATH\venv\lib\site-packages\masonite\foundation\Application.py", line 32, in register_providers
    provider.register()
  File "SOMEPATH\Kernel.py", line 29, in register
    self.register_routes()
  File "SOMEPATH\Kernel.py", line 72, in register_routes
    Route.group(
  File "SOMEPATH\venv\lib\site-packages\masonite\routes\Route.py", line 166, in group
    middleware = route.list_middleware
AttributeError: 'NoneType' object has no attribute 'list_middleware'

I've had a check with the debugger and for some reason it seems that the routes don't get loaded from the routes/web.py file is there something I am missing here

A: It turns out that one of the dependencies I had somewhere had a missing dependency. I found out that the load function called in Kernel.register_routes silenced a ModuleNotFoundError. For some reason this error didn't get silenced in a fresh project that also was missing a dependency of a module. I am guessing that it is something to do with the configuration I have on this project.
For someone else that also has this error, using a debugger, set a breakpoint in masonite\utils\structures.py in the load function after except Exception as e: and you can read out the exception message to see what module is missing


text: Q: How to create custom product grid module in customer edit page in magento2? I want to create a custom tab in the customer edit page in that tab displays the product grid. I don't know how to implement this task could you please help me?


text:
Q: Where did my blog comment go? About three hours ago I commented on the blog Looking to understand which API is best for a certain task? A new study uses Stack Overflow data to rank them. I got a comment ID: 425507, but it leads to nowhere; no comments to be seen.
Of course I forgot copy my text before posting, but it was basically explaining my observations after clicking around a bit on the site mentioned in the blog.
Where are the comments?

A: I believe the blog sometimes has comment moderation turned on. I've had comments posted (almost?) instantly, and others that showed up days later and even not at all. My guess is they have gone back and forth (possibly per post) enabling and disabling moderation on comments depending on the topic, staff availability, etc. I don't think there is any feedback process for the moderation cycle, it just eventually shows up — or it doesn't. This is pretty typical of comment systems on blogs where users are not authenticated. Sometimes a message is shown informing you that your comment is awaiting moderation, but it is usually impossible to come back later to find out the status.


text:
Q: Unsupported format character when using string formatting The problem is that I'm getting this error message:
unsupported format character ',' (0x2c) at index 27

While using the string formatting on this:
v = 60 / 100.0
messenger.append("Base Skill Level +%,0f" % chop(20 + 15 * v))

messenger.append works just like the print() if someone would be curious.
The question is, how to solve this? I cant see the problem here as far as , is required here: %,0f.
I'm using Python version 2.2

A: I think you meant %.0f instead of ,0f. As far as I know, there is no such thing as ,0f


text:
Q: Problema con ORDER BY : DESC Buenas, tengo el siguiente problema, que tengo una red social donde la gente puede publicar cosas y  enviar mensajes, la cosa esta en que al hacer un select de todas las publicaciones y mostrarlas el order by UNIX_TIMESTAMP (data) DESC no me funciona, no me las ordena, lo curioso es que lo logré hacer pero con otra BBDD, que casualmente no encuentro.
BBDD:
CREATE TABLE IF NOT EXISTS `publicacions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `contingut` text NOT NULL,
  `usuari` int(11) NOT NULL,
  `imagen` varchar(255) DEFAULT NULL,
  `data` datetime NOT NULL

SQL :
$sql = "select usuaris.nom, usuaris.cognom, publicacions.contingut from usuaris, publicacions where usuaris.id = publicacions.usuari order by UNIX_TIMESTAMP (data) DESC;";

A: No veo la necesidad de usar UNIX_TIMESTAMP, el DATETIME puedes ordenarlo sin problemas mediante el DESC, y también lo que deberías usar es un INNER JOIN, así:
SELECT u.nom, u.cognom, p.contingut
FROM publicacions as p
INNER JOIN usuaris as u
ON (u.id = p.usuari)
ORDER BY p.data DESC;

Espero te sirva mi respuesta, saludos.

A: Me gustaria ver el trace del error para tener una idea mas clara del problema, sin embargo en mi experiencia yo haria el query de la siguente forma:
Usar alias es una buena practica para querys grandes ya que te ayuda a mantener organizado el query.
$sql = "SELECT usuaris.nom, usuaris.cognom, publicacions.contingut FROM usuaris as u, publicacions as p WHERE u.id = p.usuari ORDER BY nombre_tabla.nombre_columa DESC";


text:
Q: Dado enviado de uma activity para outra chega nulo Minha Activity que estou exibindo os dados do banco no listview
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela_visualizar_clientes);

    final ListView listView = (ListView) findViewById(R.id.lvItems);

    GenericDAO g = new GenericDAO(getApplicationContext());
    ArrayList<Cliente> cArray = g.getClientes();

    final List<String> itens = new ArrayList();

    for (int i = 0; i < cArray.size() ; i++) {
        Cliente c = new Cliente();
        c = cArray.get(i);
        itens.add(c.getNome());
    }

    ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itens);
    listView.setAdapter(itemsAdapter);

    //inserindo evento de click no listView e enviando os dados para a segunda activity

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View view,
                                int posicao, long id) {

            long cli = adapter.getItemIdAtPosition(posicao);
            Intent it = new Intent(getBaseContext(), Tela_Emprestimo.class);
            it.putExtra("idCliente", cli);

            startActivityForResult(it, 1);
        }
    });

minha segunda activity aonde estou recebendo os dados, só que não estou recebendo o nome do cliente
public class Tela_Emprestimo extends AppCompatActivity implements Serializable{
    Cliente cliente;
    TextView txtCliente;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tela__emprestimo);

        Intent i = getIntent();
        cliente = (Cliente)i.getSerializableExtra("idCliente");
        Toast.makeText(this, "cliente :" + cliente.getNome(), Toast.LENGTH_LONG).show();
    }
}

A classe Cliente
public class Cliente implements Serializable {
    private int id;
    private String nome;
    private String rua;
    private String bairro;
    private String numero;
    private int idcidade;
    private int idFuncionario;
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getRua() {
    return rua;
}

public void setRua(String rua) {
    this.rua = rua;
}

public String getBairro() {
    return bairro;
}

public void setBairro(String bairro) {
    this.bairro = bairro;
}

public String getNumero() {
    return numero;
}

public void setNumero(String numero) {
    this.numero = numero;
}

public int getIdcidade() {
    return idcidade;
}

public void setIdcidade(int idcidade) {
    this.idcidade = idcidade;
}

public int getIdFuncionario() {
    return idFuncionario;
}

public void setIdFuncionario(int idFuncionario) {
    this.idFuncionario = idFuncionario;
}

A: O que você está a incluir no Extra é um long, suponho que o Id do cliente, e não o Cliente(objecto).
Ao tentar fazer, na Activity Tela_Emprestimo, o cast para Cliente
cliente = (Cliente)i.getSerializableExtra("idCliente");

o resultado é null;
Veja como está a fazer:
long cli = adapter.getItemIdAtPosition(posicao);
Intent it = new Intent(getBaseContext(), Tela_Emprestimo.class);
it.putExtra("idCliente", cli);

Se quer passar um Cliente, terá de ter um método no Adapter que retorne um, qualquer coisa como Cliente getItemAtPosition(posicao){...}.
O código ficaria assim:
Cliente cli = adapter.getItemAtPosition(posicao);
Intent it = new Intent(getBaseContext(), Tela_Emprestimo.class);
it.putExtra("idCliente", cli);

Para que tudo funcione como foi dito, necessita de usar um custom adapter que possa lidar com objectos do tipo Cliente.
Como alternativa, já que a lista apenas usa o nome de cliente, use um ArrayList<Cliente>, faça o override do método toString() da classe Cliente e obtenha o Cliente do item clicado no método onClick() da seguinte forma: Cliente cli = (Cliente)parent.getAdapter().getItem(position);.
Veja um exemplo nesta resposta.
A classe Cliente deverá implementar a interface Serializable, seria preferível que ela implementasse Parcelable.

A: Como vc esta usando esta forma para adicionar os dados a intent, se usar o nome do cliente ficará mais fácil de recuperar
String cli = adapter.getItemIdAtPosition(posicao);//Pega o nome do cliente da lista, pois vc populou a lista com um List de nomes dos clientes
Intent it = new Intent(getBaseContext(), Tela_Emprestimo.class);
it.putExtra("idCliente", cli);//Adiciona o nome do cliente a Intent

A variavel cli é um String do nome do cliente, na activity seguinte vc deve procurar por um String, assim:
Intent i = getIntent();
String clienteName = i.getStringExtra("idCliente"); //Aqui vc tem o nome do cliente

E então basta instanciar sua classe de pesquisa no banco e criar um metodo para pegar o cliente a partir do nome que vc recebeu na activity
GenericDAO g = new GenericDAO(this);//usar this se estiver em uma activity
Cliente cli = g.getClienteByNome(clienteName);


text:
Q: PHPUnit test passes when it should fail I am writing a PHPUnit test suite and have run into a bit of a problem.
Here is the test:
public function testSomething(){
  $stub = $this->getMockForAbstractClass('\core\classes\ImportedFile');

  $stub->expects($this->exactly(4))
       ->method('thismethoddoesntexist');

  $this->markTestIncomplete('not finished implementing');
}

For some reason this test is not failing. It should because the method does not exist and is therefore not called even once, let alone 4 times. It doesn't matter what I put in there, even if I put in a method name that does exist and say that I'm expecting it to run 100,000 times it still passes when this is obviously wrong.
I find this very strange since I have similar checks in previous tests which work properly.
Has anyone else experienced problems like this?

A: markTestIncomplete throw special exception, witch end the test. Checks for 'expects' in mocks are skipped.
public static function markTestIncomplete($message = '')
    {
        throw new PHPUnit_Framework_IncompleteTestError($message);
    }

A: Found the cause of the problem. It seems to be caused by the call to $this->markTestIncomplete(). For some reason having this in the test causes it not to fail, at least in this case, even when it should.
Removing the call to markTestIncomplete makes it behave normally and fail when it should. I tend to leave the markTestIncomplete method in a test until it is 100% complete, and assume that if I run the test, even in its incomplete state, it should fail if an expectation is not met. Is this not a fair assumption to make? Is this a bug in PHPUnit?


text:
Q: Android M Speech volume Currently I'm learning how to use the Android Speech library. I tested it with various stream types.
This is my code:
   Bundle params = new Bundle();
   params.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_ALARM);
   params.putInt(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1);
   speech.speak(text, TextToSpeech.QUEUE_FLUSH, params, "Yow");

Unfortunately the device seems not to use the Alarm volume. I also noticed that when I use the alarm stream in MediaPlayer, it increments the volume gradually.
Before I upgraded to Marshmallow, the volume was instantly loud enough.
How can I increase the volume of the speech engine so it instantly uses the Alarm volume?


text:
Q: How to speed up A*x if A is not a dense matrix with non-zeros entries being +1 or -1? In the question, A is a square matrix and x is a vector. The non-zero entries of A can only be 1 or -1. Then how to speed up A*x in Matlab?
I asked this question, because A*x contains multiplication operations that are computation-expensive.
However, if A only contains some +1 and -1, and assume y is a row vector from A, then y*x can avoid multiplication operations. You just need group the entries of x into 2, one is corresponding to the entries +1 of y, and the other one is corresponding to the entries -1 of y. Then do a summation of these 2 groups respectively, and do a subtraction.

A: One way to speed this up in MATLAB is to take advantage of the sparse structure of A (rather than the +1, -1 structure). You can realize huge speedups this way if A is sparse enough:
N = 1e4;
k = .0001;

% setup
x = rand(N, 1);

inds = find(rand(1,N^2) <= k);
values = 2*(randi(2, 1, length(inds))-1)-1;

% dense
fprintf('dense\n')
A = zeros(N,N);
A(inds) = values;

for i = 1:5
    tic;
    y = A*x;
    toc;
end

% sparse
fprintf('sparse\n')
A = sparse(N,N);
A(inds) = values;

for i = 1:5
    tic;
    y = A*x;
    toc;
end


text:
Q: Solving for probability in equation involving Beta function Consider the equation
$$p^\alpha(1-p)^\beta = cB(\alpha+1,\beta+1)$$
where $c,\alpha,\beta>0$ and $B(\alpha,\beta)$ is the Beta function.
Question: What is the probability $p$ as a function of $c,\alpha,\beta$?

A: As  @Peter Foreman commented, you only need to find the zero of function
$$f(p)=p^\alpha(1-p)^\beta-k$$ and, for the most general case, you will need some numerical method.
From a practical point of view, I think that it would be better to consider
$$g(p)=\alpha \log(p)+\beta \log(1-p)-\log(k)$$ Its derivatives
$$g'(p)=\frac{\alpha }{p}-\frac{\beta }{1-p}\qquad \text{and} \qquad g''(p)=-\frac{\alpha }{p^2}-\frac{\beta }{(1-p)^2} <0 \,\,\, \forall p$$ The first derivative cancels at
$$p_*=\frac{\alpha }{\alpha +\beta }$$ which corresponds to a maximum (by the second derivative test. So, if
$$g\left(\frac{\alpha }{\alpha +\beta }\right)=\alpha  \log \left(\frac{\alpha }{\alpha +\beta }\right)+\beta  \log
   \left(\frac{\beta }{\alpha +\beta }\right)-\log (k)$$ is positive, there will be roots to the equation. One root will be $0 < p_1 <\frac{\alpha }{\alpha +\beta }$ and the second one $\frac{\alpha }{\alpha +\beta }< p_2 <1$.
Start the search at the midpoint of the interval and use Newton method.
For example, let us use $\alpha=10$, $\beta=17$ and $c=\frac 1 {15}$. For the first root, the iterates would be
$$\left(
\begin{array}{cc}
 n & p_n \\
 0 & 0.185185 \\
 1 & 0.238691 \\
 2 & 0.258600 \\
 3 & 0.261070 \\
 4 & 0.261105
\end{array}
\right)$$ and, for the second root,
$$\left(
\begin{array}{cc}
 n & p_n \\
 0 & 0.685185 \\
 1 & 0.561947 \\
 2 & 0.503743 \\
 3 & 0.490163 \\
 4 & 0.489394 \\
 5 & 0.489392
\end{array}
\right)$$


text:
Q: Store private key on a static Angular site I have a static AngularJS file. It's deployed on Amazon S3.
I am accessing a API which has a hash authentication mechanism.
I have to use a private key in order to create a hash of the URL and send on the header. It works great, but the problem is that I have to find a way to keep the private key out of the reach of hackers.
I would like to know if anyone knows a way to keep the key secure.
I have thought about running my site on a node.js server. The only requirement is that I should be able to deploy it on Amazon web services.
Does it make sense?

A: There isn't a secure way to store secrets on client side. Private keys should always stay in the server.
The common authentication mechanism for APIs is to hash (not encrypt) authentication on client side.
But if you need encrypt something, you should use a asymmetric encryption algorithm with a public key on client.
http://searchsecurity.techtarget.com/definition/asymmetric-cryptography


text:
Q: How to have the Maven build wait for the Jetty server to start in forked mode before running the integration tests? I have a report for the code coverage by the integration test.
I do have integration tests, and these are run successfully in the Maven build.
When I click on the "Sessions" link in the top right corner of the HTML report I can see my test classes in the list, but I cannot see my main classes that are exercised by the tests now, and all coverage report percentages are at zero.
As a side note, my unit test coverage works fine, with the percentages being displayed all right.
My configuration looks like:
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
      <argLine>${surefireArgLine}</argLine>
      <excludes>
        <exclude>**/integrationtest/*.java</exclude>
      </excludes>
    </configuration>
  </plugin>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.18.1</version>
     <configuration>
       <argLine>${failsafeArgLine}</argLine>
       <skipTests>${skipIntegrationTests}</skipTests>
      <includes>
        <include>**/integrationtest/*.java</include>
      </includes>
    </configuration>
    <executions>
      <execution>
        <id>integration-test</id>
        <goals>
          <goal>integration-test</goal>
        </goals>
      </execution>
      <execution>
        <id>verify</id>
        <goals>
          <goal>verify</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <executions>
      <execution>
        <id>pre-unit-test</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
        <configuration>
          <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
          <propertyName>surefireArgLine</propertyName>
        </configuration>
      </execution>
      <execution>
        <id>post-unit-test</id>
        <phase>test</phase>
        <goals>
          <goal>report</goal>
        </goals>
        <configuration>
          <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
          <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
        </configuration>
      </execution>
      <execution>
        <id>pre-integration-test</id>
        <phase>pre-integration-test</phase>
        <goals>
          <goal>prepare-agent-integration</goal>
        </goals>
        <configuration>
          <destFile>${project.build.directory}/coverage-reports/jacoco-it.exec</destFile>
          <propertyName>failsafeArgLine</propertyName>
        </configuration>
      </execution>
      <execution>
        <id>post-integration-test</id>
        <phase>post-integration-test</phase>
        <goals>
          <goal>report-integration</goal>
        </goals>
        <configuration>
          <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
          <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.2.2.v20140723</version>
    <configuration>
      <httpConnector>
        <port>${jetty.port}</port>
      </httpConnector>
      <scanIntervalSeconds>10</scanIntervalSeconds>
      <stopPort>8805</stopPort>
      <stopKey>STOP</stopKey>
    </configuration>
    <executions>
      <execution>
        <id>start-jetty</id>
        <phase>pre-integration-test</phase>
        <goals>
          <goal>stop</goal> <!-- stop any stray process that has been running since before -->
          <goal>run-forked</goal>
        </goals>
        <configuration>
          <scanIntervalSeconds>0</scanIntervalSeconds>
          <daemon>true</daemon>
          <waitForChild>false</waitForChild>
          <maxStartupLines>200</maxStartupLines>
          <jvmArgs>${failsafeArgLine} -Djetty.port=${jetty.port}</jvmArgs>
        </configuration>
      </execution>
      <execution>
        <id>stop-jetty</id>
        <phase>post-integration-test</phase>
        <goals>
          <goal>stop</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Notice how the JaCoCo plugin is defined before the jetty one.
The console log shows a log of failed connection attempts. The integration tests cannot connect to the localhost. That is because the Jetty server hasn't had the time to start before Maven ran the tests.
org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8888 refused

Here is also another console log bit:
[STDERR] 2015-12-21 09:49:43.486:WARN:oejuc.AbstractLifeCycle:main: FAILED ServerConnector@2cd9b65d{HTTP/1.1}{0.0.0.0:8080}: java.net.BindExcep
tion: Address already in use
[STDERR] java.net.BindException: Address already in use
[STDERR]        at sun.nio.ch.Net.bind0(Native Method)
[STDERR]        at sun.nio.ch.Net.bind(Net.java:436)
[STDERR]        at sun.nio.ch.Net.bind(Net.java:428)
[STDERR]        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
[STDERR]        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
[STDERR]        at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:277)
[STDERR]        at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
[STDERR]        at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:216)
[STDERR]        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
[STDERR]        at org.eclipse.jetty.maven.plugin.MavenServerConnector.doStart(MavenServerConnector.java:120)
[STDERR]        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
[STDERR]        at org.eclipse.jetty.server.Server.doStart(Server.java:359)
[STDERR]        at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:76)
[STDERR]        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
[STDERR]        at org.eclipse.jetty.maven.plugin.Starter.run(Starter.java:401)
[STDERR]        at org.eclipse.jetty.maven.plugin.Starter.main(Starter.java:516)
[STDERR] 2015-12-21 09:49:43.486:WARN:oejuc.AbstractLifeCycle:main: FAILED org.eclipse.jetty.maven.plugin.MavenServerConnector@630b8061: java.net.BindException: Address already in use
[STDERR] java.net.BindException: Address already in use
[STDERR]        at sun.nio.ch.Net.bind0(Native Method)
[STDERR]        at sun.nio.ch.Net.bind(Net.java:436)

Having the start value instead of the run-forked for the goal has the tests run fine. But I need to have it as run-forked for the code coverage report.
Using the <waitForChild>false</waitForChild> option changed nothing to the issue.
How to have the Maven build wait for the Jetty server to start in forked mode before running the integration tests ?
UPDATE: I could have the Maven build wait for the Jetty server to start in fork mode with the following <maxStartupLines>200</maxStartupLines> option.
But now, none of my integration tests, although they are run fine, are seen in the report.
My log says:
[INFO] --- jacoco-maven-plugin:0.7.5.201505241946:prepare-agent-integration (pre-integration-test) @ rest ---
[INFO] failsafeArgLine set to -javaagent:/home/stephane/.m2/repository/org/jacoco/org.jacoco.agent/0.7.5.201505241946/org.jacoco.agent-0.7.5.201505241946-runtime.jar=destfile=/home/stephane/source/...-rest/rest/target/coverage-reports/jacoco-it.exec

[INFO] <<< jetty-maven-plugin:9.2.2.v20140723:run-forked (start-jetty) @ rest <<<
[INFO]
[INFO] --- jetty-maven-plugin:9.2.2.v20140723:run-forked (start-jetty) @ rest ---
[INFO] Configuring Jetty for project: Rest
[INFO] webAppSourceDirectory not set. Trying src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = /home/stephane/source/...-rest/rest/target/classes
[INFO] Context path = /
[INFO] Tmp directory = /home/stephane/source/...-rest/rest/target/tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = file:/home/stephane/source/...-rest/rest/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = /home/stephane/source/...-rest/rest/src/main/webapp

[INFO] Forked process starting
[INFO] Forked process started.

UPDATE: If I run the Maven command mvn jacoco:report-integration the console complains with a missing data file:
[INFO] --- jacoco-maven-plugin:0.7.5.201505241946:report-integration (default-cli) @ rest ---
[INFO] Skipping JaCoCo execution due to missing execution data file:/home/stephane/source/...-rest/rest/target/jacoco-it.exec

Indeed the data file is specified in the pom.xml file as being <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
Why is it looked up as jacoco-it.exec instead of coverage-reports/jacoco-it.exec ?
Is it because the JaCoCo report is generated before the Jetty server has had time to stop and produce the data file ? But why the different file path then ? And how to tell the JaCoCo report to wait for it ?
UPDATE: I added a stopWait of 1 to the stop goal of the integration test:
  <execution>
    <id>stop-jetty</id>
    <phase>post-integration-test</phase>
    <goals>
      <goal>stop</goal>
    </goals>
    <configuration>
      <stopWait>1</stopWait>
    </configuration>
  </execution>

But it changed nothing to the issue.
UPDATE: Running the build with the -X option showed the following:
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.5.201505241946:report-integration (post-integration-test) @ rest ---
[DEBUG] Configuring mojo org.jacoco:jacoco-maven-plugin:0.7.5.201505241946:report-integration from plugin realm ClassRealm[plugin>org.jacoco:ja
coco-maven-plugin:0.7.5.201505241946, parent: sun.misc.Launcher$AppClassLoader@5c647e05]
[DEBUG] Configuring mojo 'org.jacoco:jacoco-maven-plugin:0.7.5.201505241946:report-integration' with basic configurator -->
[DEBUG]   (f) dataFile = /home/stephane/source/...-rest/rest/target/coverage-reports/jacoco-it.exec
[DEBUG]   (f) outputDirectory = /home/stephane/source/...-rest/rest/target/site/jacoco-it
[DEBUG]   (f) outputEncoding = UTF-8
[DEBUG]   (f) project = MavenProject: no.....db:rest:1.40.0-SNAPSHOT @ /home/stephane/source/...-rest/rest/pom.xml
[DEBUG]   (f) skip = false
[DEBUG]   (f) sourceEncoding = UTF-8
[DEBUG] -- end configuration --
[INFO] Analyzed bundle 'Rest' with 50 classes
[INFO]
[INFO] --- jetty-maven-plugin:9.2.2.v20140723:stop (stop-jetty) @ rest ---
[DEBUG] Configuring mojo org.eclipse.jetty:jetty-maven-plugin:9.2.2.v20140723:stop from plugin realm ClassRealm[plugin>org.eclipse.jetty:jetty-maven-plugin:9.2.2.v20140723, parent: sun.misc.Launcher$AppClassLoader@5c647e05]
[DEBUG] Configuring mojo 'org.eclipse.jetty:jetty-maven-plugin:9.2.2.v20140723:stop' with basic configurator -->
[DEBUG]   (s) stopKey = STOP
[DEBUG]   (s) stopPort = 8805
[DEBUG]   (f) stopWait = 1
[DEBUG] -- end configuration --
[INFO] Waiting 1 seconds for jetty to stop
[INFO] Server reports itself as stopped

This tells me the report is being produced before the Jetty server has stopped. If that is the case, then it is faulty. How to have the report produced after the Jetty server stops ?

A: After reading a bit about the plugin on http://eclemma.org/jacoco/trunk/doc/report-integration-mojo.html I noticed that it said:

Binds by default to the lifecycle phase: verify.

So, change to:
    <execution>
        <id>post-integration-test</id>
        <phase>verify</phase>
        <goals>
          <goal>report-integration</goal>
        </goals>
        <configuration>
          <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
          <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
        </configuration>
    </execution>

(or just leave out the phase) and it should work.

A: You can instruct the the jetty-maven-plugin to wait for the forked process to do its startup activities (in your pom.xml):
<daemon>true</daemon>
<waitForChild>false</waitForChild>
<maxChildChecks>400</maxChildChecks>
<maxChildCheckInterval>250</maxChildCheckInterval>

The settings above will wait maximum 100 seconds, checking the forked process every 250 milliseconds.
Some Jetty versions (like 9.4) require longer startup time, especially if the classpath contains duplicated jars (this prints warning 'scanned from multiple locations' for each of them). So some of your integration tests may fail because Jetty is not ready in the moment of the test execution (Connection refused: connect).


text:
Q: How to merge two array and take only value in first array if there is no matching value in second array I have two arrays :
$array1 = [460,471];
$array2 = [193,42,471];

I want to take the value only in $array1 if there is no same value in $array2, if there is a same value in $array2 filter it out.
Expected output if no same value available in $array2:
$output = [460, 471]

Expected output is there is same value in $array2:
$output = [460]

A: Try array_diff() function
$array1 = [460,471];
$array2 = [193,42,471];

$filtered = array_diff($array1,$array2);

print_r($filtered);

A: You can achieve the same with the help of Hashing pretty easily.
First, try to map the values of array2 into a Hash.

For example, each element of $array2 = [193,42,471]; will have a value marking their presence as true.

Now, for each element is $array1, check if it has a value in the Hash. If it has one, then skip it.
So after the check, you will get all the values that are not present in the second array.


text:
Q: How to align lines with consistency? For example, if I paste this UserScript Meta perfectly aligned here on stackoverflow.com in Notepad++, I get something badly aligned.
// ==UserScript==
// @name            Example
// @description     This is an example
// @include         https://www.example.com/*
// @grant           none
// @version         0.1
// @author          user
// ==/UserScript==

Is there anything I can do to ensure consistency of alignement ?
I tried to play with both Tab and Space keys, without success.
Thank you for any help.

A: The problem starts when you use tabs. Depending on configuration, the tab size can be 2/4/8/x characters and this setting may differ on different websites and in different programs.
If you want the snippet to look exactly the same everywhere, you have to use spaces, because space is always 1 character.
Also, StackOverflow advises that you should use spaces here:

Also, don't use tabs – they may look good in your editor, but they'll just make a mess on Stack Overflow.

EDIT: But (according to your screenshot) in your case the problem is that you are using a font that is not monospaced. You need to use a monospace font, which means that every character has the same width. Monospace fonts for example: Courier New, Inconsolata.


text:
Q: Wrap an image to the right of the text I want to wrap the image with the texts at the right. The way it now appears is below the text. Any help is much appreciated.
\documentclass[12 pt]{article}
\usepackage[margin=.5in]{geometry}
\geometry{letterpaper}
\usepackage{graphicx}
\usepackage{amsmath, amssymb, amsfonts}
\usepackage{epstopdf}
\usepackage{geometry}
\usepackage{enumerate}
\usepackage{bbm}
\usepackage{relsize}
\usepackage{textcomp}
\usepackage{tcolorbox}
\usepackage{wrapfig}
\usepackage{lipsum}

\geometry{%
  letterpaper,
  lmargin=1 cm,
  rmargin=1 cm,
  tmargin=1 cm,
  bmargin=1 cm,
  footskip=20 pt,
  headheight=12pt}

\begin{document}

\begin{center}
    \textbf{Continued Fraction}
\end{center}

This is a very efficient method of finding the best rational approximations of a real number. Continued fractions are written as fractions within fractions which are added up in a special way, and which may go on indefinitely. Every number can be written as a continued fraction and the finite continued fractions are sometimes used to give approximations to numbers like $\sqrt{2}$ and $\pi$.

\medskip
\noindent
\textbf{Applications.}

\begin{enumerate}
    \item Design of a calendar : A year is the orbital period of the earth moving in its orbit  around the Sun.  For an observer on Earth, this corresponds to the period it takes to the Sun to complete one rotation, which is approximately 365.2422 days whose continued fraction expression is
            $$365.2422=[365,4,7,1,3,4,1]~.$$
The second convergent is  $\displaystyle{365.25=365+\frac{1}{4}}$, which means a calendar of 365 days per year but a leap year every 4 years. The fourth convergent gives a better approximation
$$365.2424 \dots  =[ 365,4,7,1 ]= 365+\frac{8}{33}~.$$
%\begin{wrapfigure}{R}{5.5cm}
%\caption{A wrapped figure going nicely inside the text.}\label{wrap-fig:1}
%\includegraphics[width=8.6cm]{Greg.jpg}
%\end{wrapfigure}
The most commonly used civil calendar today is known as the \textbf{Gregorian calendar}, which is also called the Western calendar, or the Christian calendar. This calendar was named after Pope Gregory XIII, who introduced it in 1582. Today, the Gregorian calendar is part of our everyday lives, and most of us use it without really knowing its backstory, the reasons for its introduction, and the effects that it had on the world.

\begin{center}
   \includegraphics[width=84 mm, height=64 mm]{Greg.jpg}
\end{center}

This is based on a cycle of 400 years: there is one leap year every year which is a multiple of 4 but not of 100 unless it is a multiple of 400.

\item Design of a planetarium : Christiaan Huygens (1629–1695) among being a mathematician was an astronomer,
physicist, probabilist, and was also a great horologist. He
designed more accurate clocks then the ones available at his time. In particular, his invention of the pendulum clock was a breakthrough in timekeeping. Huygens also built a mechanical model of the solar system. He wanted to design the gear ratios in order to produce a proper scaled version of the planetary orbits. He knew that the time required for the planet Saturn to orbit around the Sun is about

\end{enumerate}

\end{document}

A: Inserting images near list environment doesn't work well with the usual packages (wrapfig, floatflt). Here is a solution with the plain TeX macro package insbox, combined with enumitem, more powerful than enumerate. In particular, you can set the right margin of a list, and stop a list, then resume it, continuing the counter from the value for the previous list, with a different right margin (and changing other parameters if you wish).
Unrelated: I simplified your preamble, removing repeated package loading.
\documentclass[12 pt]{article}
\usepackage{geometry}
\geometry{%
  letterpaper,
  margin=1 cm,
  footskip=20 pt,
  headheight=12pt}
\usepackage[demo]{graphicx}
\usepackage{epstopdf}
\usepackage[shortlabels]{enumitem}
\usepackage{amsmath, amssymb}
\usepackage{relsize}
\usepackage{textcomp}
\usepackage{tcolorbox}

\input{insbox}

\begin{document}

\begin{center}
    \textbf{Continued Fraction}
\end{center}

This is a very efficient method of finding the best rational approximations of a real number. Continued fractions are written as fractions within fractions which are added up in a special way, and which may go on indefinitely. Every number can be written as a continued fraction and the finite continued fractions are sometimes used to give approximations to numbers like $\sqrt{2}$ and $\pi$.
\bigskip

\InsertBoxR{1}{\raisebox{0pt}[\dimexpr\height+2.5ex]{\includegraphics[width=84 mm, height=64 mm]{Greg.jpg}}}
\noindent
\textbf{Applications.}
\begin{enumerate}[rightmargin=88mm]
    \item Design of a calendar : A year is the orbital period of the earth moving in its orbit around the Sun. For an observer on Earth, this corresponds to the period it takes to the Sun to complete one rotation, which is approximately 365.2422 days whose continued fraction expression is
            $$365.2422=[365,4,7,1,3,4,1]~.$$
The second convergent is $\displaystyle{365.25=365+\frac{1}{4}}$, which means a calendar of 365 days per year but a leap year every 4 years. The fourth convergent gives a better approximation
\[ 365.2424 \dots =[ 365,4,7,1 ]= 365+\frac{8}{33}~. \]
\end{enumerate}
\begin{enumerate}[resume]
\item[]
The most commonly used civil calendar today is known as the \textbf{Gregorian calendar}, which is also called the Western calendar, or the Christian calendar. This calendar was named after Pope Gregory XIII, who introduced it in 1582. Today, the Gregorian calendar is part of our everyday lives, and most of us use it without really knowing its backstory, the reasons for its introduction, and the effects that it had on the world.

This is based on a cycle of 400 years: there is one leap year every year which is a multiple of 4 but not of 100 unless it is a multiple of 400.

\item Design of a planetarium : Christiaan Huygens (1629–1695) among being a mathematician was an astronomer,
physicist, probabilist, and was also a great horologist. He
designed more accurate clocks then the ones available at his time. In particular, his invention of the pendulum clock was a breakthrough in timekeeping. Huygens also built a mechanical model of the solar system. He wanted to design the gear ratios in order to produce a proper scaled version of the planetary orbits. He knew that the time required for the planet Saturn to orbit around the Sun is about

\end{enumerate}

\end{document}


text:
Q: Cucumber and Test Management Tool I am creating a new Automation project for which I need to come up with the Tech Stack. I am planning to opt for BDD using Cucumber and Gherkin. I wanted to know which Test management Tool I should use in this case.
I was reading few communities where people have an opinion that we do not need a Test manager tool with Cucumber but my question is there could be a scenario where we have a whole lot of test cases out of which not all of them are automated.
In that case we would require a Test Repository to keep all the test cases with some flag marked as Automated.
I read this but this did not answer my question:
https://sqa.stackexchange.com/questions/2095/what-test-management-tool-to-manage-cucumber-tests?noredirect=1&lq=1

A: I was using TestRail for managing my team's manual test processes and also for my automation projects. You can tag your automations test with @automation tag and you can map them in TestRail as automation test cases. Hope is that works for you.
You can tag, parse and map your cucumber cases with TestRail's test case id via TestRail's api.
Here is the documentation of TestRail : http://docs.gurock.com/testrail-api2/start
Edit :
Here is a link for your question's answer :Can I use MTM to execute my testcases that are wriiten in Selenium Java using Eclipse IDE

A: TestRail is a widely used test management tool nowadays, where you can add your cucumber dsl and later attach it with your automation scenarios. You can integrate it easily with the below ruby gem, if you are a Ruby user.

Ruby

testrail-cucumber
Install gem file
gem 'testrail-cucumber'

Import the library in your env file
require 'testrail-cucumber'

Sync Case ID in your BDD scenario
Prefix TestRail Case ID on start of your cucumber scenario; say, C860
  @your_tag
  Scenario: C860 Verify the home page
    Given I navigate to "home" page
    Then I verify the home page

Config TestRail details

*

*Create a testrail config file, testrail_config.yml in the project parent folder

*Fill up the testrail details on right hand side of the fields (url, user, password, and run_id); run_id is the dynamically generated id from your testrail account (say, run_id: 111)

testrail:
  url: https://your_url.testrail.io/
  user: your@email.com
  password: your_password
  run_id: your_run_id

Update the results through Hooks on end of each test
After do |scenario|
  TestrailCucumber::UpdateTestRails.new(scenario).upload_result
end


text:
Q: How can a C program on Mac OS/X learn that the user has double-clicked to open an associated file? Normally in Obj C, NSApplicationDelegate handles this. But how would I do it in C?
I guess what I am asking it, how did Mac programs do this before OS/X came along?
Thanks.

A: In Mac OS 9, applications opened documents at launch (or later on) by registering for and receiving an 'odoc' Apple Event at startup. This is nontrivial to do in C, and I'd strongly recommend you not attempt it. In particular, note that this is unlikely to work properly unless your application has a Carbon event loop.
Before even that, there was also a mechanism whereby files for an application to open at launch were specified in a block of memory at the top of the stack. This mechanism no longer exists on OS X, so it's irrelevant today.


text:
Q: How to add Authentication token in HttpRequest in Adaptive dialog? I am using Botframework adaptive dialog template (c#). I already obtained a token from a HttpRequest and saved it as a conversation state property conversation.token, now I am trying to use this token to make another API call with HttpRequest. But from the official document of HttpRequest Class, it seems there is no options to add the authentication token. I tried to add the token in the Headers, but did not work, it showed 401 Unauthorized error. How should the authorization be handled in HttpRequest in adaptive dialog?
new HttpRequest()
{
    Url = "http://example.com/json",
    ResultProperty = "conversation.httpResponse",
    Method = HttpRequest.HttpMethod.GET,
    ResponseType = HttpRequest.ResponseTypes.Json,
    Headers = new Dictionary<string, AdaptiveExpressions.Properties.StringExpression>()
    {
        {"Authorization", "Bearer ${conversation.token.content.token}"},
    },
},
new SendActivity("${conversation.httpResponse}"),

A: Instead of using HttpRequest, I made the API call inside CodeAction with custom code.
First make a POST request to get the token, then make a GET request to call the main API. In the GET request, the authorization can be added in this way: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);.
new CodeAction(async (dc, options) =>
{
    var my_jsondata = new
    {
        Username = "username",
        Password = "password"
    };
    var json = JsonConvert.SerializeObject(my_jsondata);
    var data = new StringContent(json, Encoding.UTF8, "application/json");
    var Tokenurl = "https://example.com/token?HTTP/1.1";
    using var Tokenclient = new HttpClient();
    var Tokenresponse = await Tokenclient.PostAsync(Tokenurl, data);
    string Toeknresult = Tokenresponse.Content.ReadAsStringAsync().Result;
    var Tokenjo = JObject.Parse(Tokenresult);

    using var client = new HttpClient();
    var url = "https://example.com/mainapi?HTTP/1.1";
    var accessToken = Tokenjo["token"];
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    var response = await client.GetAsync(url);
    string result = response.Content.ReadAsStringAsync().Result;

    dc.State.SetValue("conversation.httpresponse", response);
    dc.State.SetValue("conversation.result", result);

    return await dc.EndDialogAsync();
}),


text:
Q: Google Picasa API XML deserialization I'm currently working with the Google Picasa API trying to list albums.
The code to for OAuth 2.0 is written and working. I can get the XML list of albums without any issue. I have worked very little with XML in the past and I can't get it to deserialize.
I tried to use the XSD.exe tool to generate a .xsd and then classes from that but I get an error right away: A column named 'id' already belongs to this DataTable.
I can't figure out why because the second ID tag is nested in an other node. Can anyone put me in the right direction?
XML:
<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
    xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'
    xmlns:exif='http://schemas.google.com/photos/exif/2007'
    xmlns:geo='http://www.w3.org/2003/01/geo/wgs84_pos#'
    xmlns:gml='http://www.opengis.net/gml'
    xmlns:georss='http://www.georss.org/georss'
    xmlns:batch='http://schemas.google.com/gdata/batch'
    xmlns:media='http://search.yahoo.com/mrss/'
    xmlns:gphoto='http://schemas.google.com/photos/2007'
    xmlns:gd='http://schemas.google.com/g/2005'
    gd:etag='W/"CkABRXY8fip7ImA9WxVVGE8."'>
  <id>https://picasaweb.google.com/data/feed/api/user/liz</id>
  <updated>2009-03-12T01:19:14.876Z</updated>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/photos/2007#user' />
  <title>liz</title>
  <subtitle></subtitle>
  <icon>https://iconPath/liz.jpg</icon>
  <link rel='http://schemas.google.com/g/2005#feed'
    type='application/atom+xml'
    href='https://picasaweb.google.com/data/feed/api/user/liz' />
  <link rel='http://schemas.google.com/g/2005#post'
    type='application/atom+xml'
    href='https://picasaweb.google.com/data/feed/api/user/liz' />
  <link rel='alternate' type='text/html'
    href='http://picasaweb.google.com/liz' />
  <link rel='http://schemas.google.com/photos/2007#slideshow'
    type='application/x-shockwave-flash'
    href='http://picasaweb.google.com/s/c/bin/slideshow.swf?host=picasaweb.google.com&RGB=0x000000&feed=https%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2Fliz%3Falt%3Drss' />
  <link rel='self' type='application/atom+xml'
    href='https://picasaweb.google.com/data/feed/api/user/liz?start-index=1&max-results=1000&v=2' />
  <author>
    <name>Liz</name>
    <uri>http://picasaweb.google.com/liz</uri>
  </author>
  <generator version='1.00' uri='http://picasaweb.google.com/'>
    Picasaweb</generator>
  <openSearch:totalResults>1</openSearch:totalResults>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>1000</openSearch:itemsPerPage>
  <gphoto:user>liz</gphoto:user>
  <gphoto:nickname>Liz</gphoto:nickname>
  <gphoto:thumbnail>
    https://thumbnailPath/liz.jpg</gphoto:thumbnail>
  <gphoto:quotalimit>1073741824</gphoto:quotalimit>
  <gphoto:quotacurrent>32716</gphoto:quotacurrent>
  <gphoto:maxPhotosPerAlbum>500</gphoto:maxPhotosPerAlbum>
  <entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'>
    <id>https://picasaweb.google.com/data/entry/api/user/liz/albumid/albumID</id>
    <published>2005-06-17T07:09:42.000Z</published>
    <updated>2009-03-12T01:19:14.000Z</updated>
    <app:edited xmlns:app='http://www.w3.org/2007/app'>
      2009-03-12T01:19:14.000Z</app:edited>
    <category scheme='http://schemas.google.com/g/2005#kind'
      term='http://schemas.google.com/photos/2007#album' />
    <title>lolcats</title>
    <summary>Hilarious Felines</summary>
    <rights>public</rights>
    <link rel='http://schemas.google.com/g/2005#feed'
      type='application/atom+xml'
      href='https://picasaweb.google.com/data/feed/api/user/liz/albumid/albumID?authkey=authKey&v=2' />
    <link rel='alternate' type='text/html'
      href='http://picasaweb.google.com/lh/album/aFDUU2eJpMHZ1dP5TGaYHxtMTjNZETYmyPJy0liipFm0?authkey=authKey' />
    <link rel='self' type='application/atom+xml'
      href='https://picasaweb.google.com/data/entry/api/user/liz/albumid/albumID?authkey=authKey&v=2' />
    <link rel='edit' type='application/atom+xml'
      href='https://picasaweb.google.com/data/entry/api/user/liz/albumid/albumID/1236820754876000?authkey=authKey&v=2' />
    <link rel='http://schemas.google.com/acl/2007#accessControlList'
      type='application/atom+xml'
      href='https://picasaweb.google.com/data/entry/api/user/liz/albumid/albumID/acl?authkey=authKey&v=2' />
    <author>
      <name>Liz</name>
      <uri>http://picasaweb.google.com/liz</uri>
    </author>
    <gphoto:id>albumID</gphoto:id>
    <gphoto:location>Mountain View, CA</gphoto:location>
    <gphoto:access>public</gphoto:access>
    <gphoto:timestamp>1118992182000</gphoto:timestamp>
    <gphoto:numphotos>1</gphoto:numphotos>
    <gphoto:numphotosremaining>499</gphoto:numphotosremaining>
    <gphoto:bytesUsed>23044</gphoto:bytesUsed>
    <gphoto:user>liz</gphoto:user>
    <gphoto:nickname>Liz</gphoto:nickname>
    <media:group>
      <media:title type='plain'>lolcats</media:title>
      <media:description type='plain'>Hilarious
        Felines</media:description>
      <media:keywords></media:keywords>
      <media:content url='https://imagePath/Lolcats.jpg' type='image/jpeg' medium='image' />
      <media:thumbnail url='https://thumbnailPath/Lolcats.jpg' height='160' width='160' />
      <media:credit>Liz</media:credit>
    </media:group>
  </entry>
  ...more entries similar to the one above here...
</feed>

A: I don't know why xsd.exe is not working.  In my experience it's good to give you a head start but it not foolproof in generating optimized C# classes for the XML document you want to serialize. There are other code-gen tools that do similar.  XsdObjectGen is a free one, not sure if it is still around.
In my comment, I said On the other hand it's pretty mechanical to hand-code your class to work with the Xml Serializer.
This partial example ought to get you started:
[XmlType("generator", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedGenerator
{
    [XmlAttribute]
    public string version { get; set; }
    [XmlAttribute]
    public string uri { get; set; }
    [XmlText]
    public string text { get; set; }
}

[XmlType("category", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedCategory
{
    [XmlAttribute]
    public string scheme { get; set; }
    [XmlAttribute]
    public string term { get; set; }
}

[XmlType("entry", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedEntry
{
    public FeedCategory category { get; set; }
    public string title { get; set; }
    public string summary { get; set; }
}

[XmlType("author", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedAuthor
{
    public string name { get; set; }
    public string uri { get; set; }
}

[XmlType("link", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedLink
{
    [XmlAttribute]
    public string rel { get; set; }
    [XmlAttribute]
    public string @type { get; set; }
    [XmlAttribute]
    public string href { get; set; }
}

[XmlType("feed", Namespace="http://www.w3.org/2005/Atom")]
[XmlRoot("feed", Namespace="http://www.w3.org/2005/Atom")]
public partial class FeedList
{
    public string id        { get;set; }
    public string title     { get;set; }
    public string icon      { get;set; }

    [XmlElement("link")]
    public FeedLink[] links      { get;set; }
    public FeedGenerator generator      { get;set; }

    [XmlElement(Namespace="http://a9.com/-/spec/opensearch/1.1/")]
    public int totalResults      { get;set; }

    [XmlElement("entry")]
    public FeedEntry[] entries { get; set; }
}

This code de-serializes just those elements in the FeedList class.
If you want additional elements, add them in.  A text element can be deserialized as a property of a  simple type, like a string, int, or DateTime.  A complex element needs to be a property of a custom class, decorated with XmlType.
To deserialize a sequence of multiple elements, like the link elements or the entry elements, define an array, and  decorate it with XmlElement as shown.  The values inside the double-quotes are the element names used for each. Attributes in the XML get properties decorated with the XmlAttribute attribute in the C# code, and the value in the quotes is the attr name. No value means to map the attribute in the xml that has the same name as the property name, into the given property. (A property named "rel" in the C# code decorated with XmlAttribute gets mapped to the xml attribute value with the name "rel" in the XML document)
If you care about the elements from the other schema (like the opensearch schema, etc), you need to specify properties corresponding to the elements from those schema. Again, use custom classes for complex types in the XML; simple C# datatypes for simple (text only) elements in the XML.   For a simple type, the XmlElement attribute on the property, or, for a complex type, the XmlType attribute on the custom class, must specify the xmlns namespace for that element.  You need not worry about the element prefix - the namespace is what is important. See the totalResults property as an example.
When an XmlElement or XmlAttribute attribute lacks an unlabeled string value, the element name or attribute name is assumed to be the name of the property itself. So in the above, the property totalResults deserializes the openSearch:totalResults element, because I've provided the xmlns corresponding to openSearch.
To deserialize the text node of an xml element, use an XmlText attribute.
Extend the example above and you should be able to deserialize everything you need to deserialize.

EDIT
But you may wanna use a library that is already built to do this.
http://code.google.com/p/google-gdata/updates/list


text:
Q: Using LINQ, get a list of objects that contain a particular property value I have two simple models:
 public class Product()
        {
           public long CategoryId {get; set;}
           //...etc
        }

 public class ProductCategory()
        {
           public long Id {get; set;}
           //...etc
        }

I've written a query to store a list of ProductCategory.Id numbers.
List<long> activeProductCategories

Now I would like to write a Linq Query that gets a List of all of the Products that have CategoryId equal to any long in activeProductCategories.
I have started writing something like the following, but have yet to make much progress:
List<Product> activeProducts = UnitOfWork.ProductRepository.Get().Where(a=>a.CategoryId //... ?

A: You can use a linq Contains() method
List<Product> activeProducts = UnitOfWork.ProductRepository.Get()
    .Where(a => activeProductCategories.Contains(a.CategoryId)).ToList();


text:
Q: Share post via facebook php sdk version 4.0.9, Graph API v2.0 Using facebook php sdk version 4.0.9 & Graph API v2.0
Here is my application settings for publishing post.
My code is :
$requestjojo = new FacebookRequest($session, 'POST', '/me/feed', array('message' => 'testing'));
$responsejojo = $requestjojo->execute();

// get response
$graphObjectjojo = $responsejojo->getGraphObject()->asArray();

// print Graph data
echo '
' . print_r( $graphObjectjojo, 1 ) . '
';

This is not working for me, I want to know where's the bug.
Note : I am getting user data(user profile) properly from this sdk.
Using echo 'getLoginUrl(array('publish_stream')).'" target="_top">Login';
for login button, when login with Facebook, Facebook is not asking me for this extended permission(publish_stream) too.

A: The loginUrl is not build up properly.
 $helper->getLoginUrl(array(
    'scope' => 'publish_stream',
    'redirect_uri' => $your_redirect_uri
 ));

A: Finally, got the answer.
The reason is that "publish_stream" is now deprecated; use "publish_actions" instead.

From :
Error (#200) The user hasn't authorized the application to perform this action


text:
Q: .net HttpWebRequest URL encoding in url parameters Does the HttpWebRequest class automatically encode URL parameter?
I have created a HttpWebRequest with URL "http://test.com/124?param=%2Ea".
When I capture a fiddler trace, I see the HTTP get request becomes "http://test.com/124?param=.a" i.e. "%2E" becomes ".".
I have tried setting up debugger in my code and I am sure the url I passed in HttpWebRequest is "http://test.com/124?param=%2Ea"
Do you know if HttpWebRequest does that automatically? And how can I disable it?

A: The problem seems to be that, although %2e is the url encoded equivalent of .,  you want the request url to remain the exact same way you typed it, right?
It seems Uri does not allow for escaped slashes / or dots .. Apparently this is for backward compatibility purposes. You can try the workaround mentioned on this SO answer which is backed by a solution by MS themselves on this bug report on MS Connect
They suggest placing the following code in your app.config or web.config file:
<uri>
    <schemeSettings>
        <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
    </schemeSettings>
</uri>


text:
Q: Spark reader splits records when encounters control characters I am trying to read file using spark reader. Spark reader splits the records in the file when it encounters the control characters like ^M, ^H, ^O, ^P.
To debug the issue I am trying to manually removing the control characters the file and testing record length with spark shell.
I tried to remove all control characters and check the record length:
sed -i 's/^[:print:]/ /g' <filename>

I found that it is also replacing punctuation characters like ? in space.
Please suggest the command that will helpful to replace all control characters into space.

A: The ^ when used outside of a bracket expression mean start of a string. The [:print:] POSIX character class outside of a bracket expression does not match any printable chars, it matches a colon, r, p, n, i, t chars.
You can use
sed -i 's/[^[:print:]]/ /g' < filename>

It will replace every non-printable char with a literal space char.


text:
Q: how to calculate the standard deviation of the sum of multiple uniform distribution Given several independent uniform distributions, such as runif(0,5) and runif(0,50), how to calculate the sd of the sum of the two functions? And in what scenario would one needs to consider the sum of several uniform distributions

A: To answer the first question, you need the following elements:
1) The variance of a continuously uniformly distributed random variable on the interval $[a,b]$ is $\tfrac{1}{12} (b - a)^2$.
2) The variance of the sum of independent (and therefore uncorrelated) random variables is the sum of the variances.
3) The standard deviation is the square root of the variance.
As for the second question, I don't know, how did you come up with it? :)


text:
Q: Помогите найти библиотеку, реализующую функцию поиска Мне нужна библиотека, которая реализовывала бы функцию поиска как, например, в Яндексе или Гугле — начинаешь вводить символы и сразу выпадает список релевантных слов (допустим, из массива в приложении, это уже детали). С возможностью обработать тач по слову / фразе из списка.
В идеале хотелось бы увидеть библиотеку с возможностью добавления зависимости maven.

A: Этот функционал есть в SDK – AutoCompleteTextView.
Пример:
public class CountriesActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.countries);

         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, COUNTRIES);
         AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.countries_list);
         textView.setAdapter(adapter);
     }

     private static final String[] COUNTRIES = new String[] {
         "Belgium", "France", "Italy", "Germany", "Spain"
     };
 }

Как это выглядит:


text:
Q: Sympy plot function in variable space under certain conditions for variables I am still exploring sympy and wanted to use it to plot following function in 3d space.
import sympy as sym

a, h, x, b, k, y, c, l = sym.symbols("a h x b k y c l")

eq = a*h*x+b*k*y+c*l*(1-(x+y))

is it possible to do this in conjunction with following conditions (probably not in correct code, but I hope you guess what I mean):
(0<=x<=1), (0<=y<=1), ((x+y)<=1)

for plotting, I substitute all symbols with knowns, except for x and y, and I would like to have these two within their ranges, specified by above conditions...
how can I accomplish this?

A: I'm not sure how to handle the third condition (x+y<=1) but otherwise this should be a start:
import sympy as sym
import matplotlib.pyplot as plt
import numpy as np

a, h, x, b, k, y, c, l = sym.symbols("a h x b k y c l")

eq = a*h*x+b*k*y+c*l*(1-(x+y))

values = {a:1,h:2,b:3,k:4,c:5,l:6}
eqv = eq.subs(values)
f = lambdify((x, y), eqv)

xv = np.linspace(0, 1, 100)
yv = np.linspace(0, 1, 100)
X, Y = np.meshgrid(xv, yv)

Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()


text:
Q: can any one help to parse perticular row and columns from xlsx format file and rereturn in another xlsx file I am trying to parse 1st and 7th column from xlsx file, and I want to rewrite that parsed columns to another new xlsx format file as the output.
use strict;
use warnings;
use Spreadsheet::WriteExcel;
use Spreadsheet::Read;
use constant FILE_NAME => 'file1.xls';
my $workbook = ReadData ("Next seq_Run039_ Data Transfer     sheet_22.1.2015.xlsx");

$workbook = Spreadsheet::WriteExcel->new(FILE_NAME)
|| die "could not create $!";
$workbook->compatibility_mode();

my $worksheet = $workbook->add_worksheet();
#my $parser = $worksheet->"Next seq_Run039_ Data Transfer sheet_22.1.2015.xlsx";
$worksheet->write_col(0, 0,[[qw(Header)],[ qw(File_Version), 1 ],[], [qw(Data)], [qw(SampleID SampleName Index Index2)]]);
$worksheet->write_col( 5, 0,  [1 .. 100] );

$workbook->close() or die "Error closing file: $!";

My question is how to parse the data and print the same into another file?

A: I'm not sure what you are like to do with those columns and where you want to place it but this code can give you clue.
use strict;
use warnings;
use Spreadsheet::Read;
use Excel::Writer::XLSX;
use List::Util qw(max);

use constant FILE_IN   => 'Next seq_Run039_ Data Transfer     sheet_22.1.2015.xlsx';
use constant FILE_OUT  => 'file.xlsx';
use constant SHEET     => 1;
use constant COLS      => ( 1, 7 );
use constant SKIP_ROWS => 3;
use constant COL_SPACE => 0;

my $book = ReadData(FILE_IN);
my @cols = @{ $book->[SHEET]{cell} }[COLS];

# undef $book; # you can release rest of $book

# there is filler as 0. row so +1
# note splice is destructive to $book->[SHEET]{cell} }[COLS] content but not to FILE_IN
splice @$_, 0, SKIP_ROWS + 1 for @cols;
my $max_row = max map scalar @$_, @cols;

# replace any space in @cols content by single '_'
map s/\s+/_/g, @$_ for @cols;

# Create new Spreadsheet

my $workbook  = Excel::Writer::XLSX->new(FILE_OUT);
my $worksheet = $workbook->add_worksheet();

# add header
my @header = (
    [qw(Header)], [ qw(File_Version), 1 ],
    [], [qw(Data)], [qw(SampleID SampleName Index Index2)]
);
$worksheet->write_col( 0, 0, \@header );

# insert columns from 3rd column
$worksheet->write( scalar @header,
    0, [ [ 1 .. $max_row ], ( [] ) x COL_SPACE, @cols ] );

$workbook->close();


text:
Q: Can I change the system bell noise in Exceed? I'm using Hummingbird Exceed to xterm to a unix box.  The xterm and gvim both use the system bell often.  Unfortunately this is reproduced as a full volume beep in my headphones as well as the exceed tab on the task bar (not the program's tab) being highlighted.
Is there a way to adjust this behavior, at least so I don't go deaf?

A: I'm not sure about Exceed, but you can turn on the visual bell in xterm to make the window flash instead of having an audible bell:
xterm -vb

or Ctrl-Mouse-Button-2 and select "Enable Visual Bell".


text:
Q: how to do a post to url of pattern /api/{controller}/{action}/{id}? I have my controller method written as follows:
public class WorkerController : ApiController
{
    //POST
    //api/worker/unregister/<id>
    //http body:
    //status=<status>
    [HttpPost]
    public void Unregister(int status)
    {
        //stuff
    }
}

Whenever I make a request, it says resource not found (404).
What is the correct way of wiring this?
Edit: wiring the call using PostMan chrome extension - rest client:
http://localhost:xxxx/api/worker/unregister/3

...and then I pass post parameters as usual. Its x-www-form-urlencoded
Update:
Tried the following:
public class WorkerController : ApiController
{

    [HttpGet]
    public void Unregister(int id, int status)
    {
        //stuff
    }
}

...and passed the url as below:
http://localhost:xxxx/api/worker/unregister/3?status=-1

This worked!
But why didn't the other work. Here is code in the WebApiConfig.cs:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.Routes.MapHttpRoute(
            name: "ServiceApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

A: In your controller you have used status as parameter name whereas in WebApiConfig.cs you have used id as parameter name
change your WebApiConfig.cs like this
 config.Routes.MapHttpRoute(
            name: "ServiceApi",
            routeTemplate: "api/{controller}/{action}/{status}",
            defaults: new { status = RouteParameter.Optional }
        );

A: Ah, I figured it out!
You have to pass a model.
public class fooModel
{
    public int status {get; set;}
}

The action should be re-written as follows:
public void unregister(int id, fooModel m)
{
    Debug.Print(m.status);
}


text:
Q: stdClass Object In Array Iteration I've got an array of data containing stdClass Objects that looks like this if I do print_r($results):
Array (
    [0] => stdClass Object (
        [ID] => 1
    )
    [1] => stdClass Object (
        [ID] => 2
    )
    [2] => stdClass Object (
        [ID] => 3
    )
)

I need to get the values of ID as a comma seperated string. To do this, I intially tried to do implode(",", $results) but this gave errors due to the stdClass Objects. So after a reasonable amount of reading and checking SO etc, I've got to a point where I can access the value of ID on a given record: $results[0]->ID.
However, I don't know how many rows there will be due to this data coming from a DB query. So, I need to iterate through each row and add this to a string.
I -amongst other things- tried this:
$i = 0;
foreach ($results as $result){

    //$result->ID;
    $result[$i]['ID'];
    $i++

}

These return an error:

Fatal error:  Uncaught Error: Cannot use object of type stdClass as
  array

I've literally no idea at this point how to get all the ID values as a comma seperated string.
I've checked out numerous SO posts include the following:
 - 'Cannot use object of type stdClass as array' using Wordpress
 - iterating through a stdClass object in PHP
 - PHP Loop stdClass Object
UPDATE
I'm getting this data as follows:
global $wpdb;
$query = "Select wp_users.ID from wp_users where wp_users.ID not in ( select wp_usermeta.user_id from wp_usermeta where wp_usermeta.meta_key = 'grp2_profile_visiblity' and wp_usermeta.meta_value = 1 order by wp_usermeta.user_id ) order by wp_users.ID";
$results = $wpdb->get_results( $query, OBJECT );

Thanks

A: You're getting-

Fatal error: Uncaught Error: Cannot use object of type stdClass as
  array

Fatal error because PHP array's are accessible using bracket [] notation and object's are arrow ->
Let's do this way using foreach() and implode() to get comma separated id's like 1,2,3 but I also think you can fix it from your DB query end without mangling output here :) hope this helps sir.
$expected = [];
foreach ($results as $key=>$obj){
    $expected[] = $obj->ID;
}
echo implode(',',$expected);

WORKING DEMO: https://3v4l.org/oUCkL

A: This is easily enough done with array_column() to get the ID values; it works just as well with objects as it does with arrays.
<?php
// some sample data
$results = json_decode('[{"ID": 1}, {"ID": 2}, {"ID": 3}]');

$return = implode(",", array_column($results, "ID"));
echo $return;

Output:
1,2,3


text:
Q: Как задать группе кнопок атрибут name <form>
<div class="btn-group" name="gender" data-toggle="buttons">
     <label class="btn btn-default">
      <input type="radio" value="m">M
     </label>
     <label class="btn btn-default">
      <input type="radio" value="f">Ж
     </label>
    </div>
<button type="button" class="btn" id="save">Продолжить</button>
</form>

Почему атрибут name="gender" у такой формы не передается на сервер?
Как правильно задать атрибут группе кнопок?

A: Это невозможно. У каждого HTML тега есть свой набор атрибутов. Применительно к тегу div атрибут name не предусмотрен стандартом. Тег div имеет другое назначение, нежели элементы форм. Другими словами, тег div является группирующим элементом и не как не относится к элементом формы, значения которых передаются на сервер вместе с HTTP запросом.
Атрибут name применительно к формам и их полям используется для того что бы предоставить возможность программисту в коде серверной части получить доступ к значениям полей формы переданных на сервер в HTTP запросе.
Атрибут name, будет доступен на стороне сервере, только если вы будете его использовать вместе с элементами формы.
Перечень HTML элементов форм, можно посмотреть здесь: http://www.w3schools.com/html/html_form_elements.asp

A: Потому что атрибут name должен быть у input, а не у div: https://webref.ru/html/input/name


text:
Q: Tensorflow: `batch_size` or `steps` is required for `Tensor` or `NumPy` input data Consider the following TensorFlow code:
import numpy as np
import tensorflow as tf

import tensorflow_datasets as tfds

mnist_dataset, mnist_info = tfds.load(name = 'mnist', with_info=True, as_supervised=True)

mnist_train, mnist_test = mnist_dataset['train'], mnist_dataset['test']

num_validation_samples = 0.1 * mnist_info.splits['train'].num_examples
num_validation_samples = tf.cast(num_validation_samples, tf.int64)

num_test_samples = mnist_info.splits['test'].num_examples
num_test_samples = tf.cast(num_test_samples, tf.int64)

def scale(image, label):
    image = tf.cast(image, tf.float32)
    image /= 255.
    return image, label

scaled_train_and_validation_data = mnist_train.map(scale)
test_data = mnist_test.map(scale)

BUFFER_SIZE = 10_000

shuffled_train_and_validation_data = scaled_train_and_validation_data.shuffle(BUFFER_SIZE)

validation_data = shuffled_train_and_validation_data.take(num_validation_samples)
train_data = shuffled_train_and_validation_data.skip(num_validation_samples)

BATCH_SIZE = 100
train_data = train_data.batch(BATCH_SIZE)
validation_data = validation_data.batch(num_validation_samples) # Single batch, having size equal to number of validation samples
test_data = test_data.batch(num_test_samples)

validation_inputs, validation_targets = next(iter(validation_data))

input_size = 784 # One for each pixel of the 28 * 28 image
output_size = 10
hidden_layer_size = 50 # Arbitrary chosen

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28,28,1)),
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # First hidden layer
    tf.keras.layers.Dense(hidden_layer_size, activation='relu'),
    tf.keras.layers.Dense(output_size, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
NUM_EPOCHS = 5
model.fit(train_data, epochs = NUM_EPOCHS, validation_data=(validation_inputs, validation_targets), verbose=2)

On running it tf gives the error:

ValueError: batch_size or steps is required for Tensor or
  NumPy input data.

When batch_size is added in the call to fit():
model.fit(train_data, batch_size = BATCH_SIZE, epochs = NUM_EPOCHS, validation_data=(validation_inputs, validation_targets), verbose=2)

It then complains:

ValueError: The batch_size argument must not be specified for the
  given input type. Received input: , batch_size: 100

What is the error here?

A: NUM_EPOCHS=5
    model.fit(train_data,epochs= NUM_EPOCHS,
    validation_data=(validation_inputs, validation_targets),
    validation_steps=10,verbose=2)

A: The error happens because a tf.Dataset is provided to the argument validation_data of Model.fit, but Keras does not know how many steps to validate for. To solve this problem, you can just set the argument validation_steps. For example:
model.fit(train_data,
    batch_size=BATCH_SIZE,
    epochs=NUM_EPOCHS,
    validation_data=(validation_inputs, validation_targets),
    validation_steps=10)

A: If you visit this link - https://www.tensorflow.org/api_docs/python/tf/keras/Model, you will find that fit() requires the argument - validation_steps only if validation_data is provided and is a tf.data dataset. As in your code, it looks like you created the validation_data by splitting the training part of dataset.


text:
Q: How do I read the results of gradlew app:dependencies? So I'm running into an error when trying to run my project from Android Studio. I've found several answers to the issue itself, but one of them mentioned running gradlew app:dependencies from the AS terminal.
I ran it, and am not sure how to read some of the results. For example, I'm using AWS's DynamoDB, and according to their startup tutorial, I'm supposed to do this in my build file:
dependencies {
    compile 'com.amazonaws:aws-android-sdk-core:2.+'
    compile 'com.amazonaws:aws-android-sdk-cognito:2.+'
    compile 'com.amazonaws:aws-android-sdk-s3:2.+'
    compile 'com.amazonaws:aws-android-sdk-ddb:2.+'
}

The results of the app:dependencies call include this:
\--- com.amazonaws:aws-android-sdk-ddb-mapper:2.+ -> 2.2.12
     +--- com.amazonaws:aws-android-sdk-core:2.2.12 (*)
     +--- com.amazonaws:aws-android-sdk-ddb:2.2.12 (*)
     \--- com.amazonaws:aws-android-sdk-s3:2.2.12
          \--- com.amazonaws:aws-android-sdk-core:2.2.12 (*)

How do I read this? Does it mean that the ddp-mapper package lives in sdk-core, sdk-ddb, and sdk-s3, or something else entirely?

A: Here, nesting means "transitive dependencies". aws-android-sdk-ddb-mapper is pulling in three other artifacts: aws-android-sdk-core, aws-android-sdk-ddb, and
aws-android-sdk-s3. That latter one also has a transitive dependency, pulling in aws-android-sdk-core.
Now, you'll notice that aws-android-sdk-core appears a lot. Gradle knows this and nets that down to a single copy of that dependency.


text:
Q: Connect to remote Realm with nodeJS for server side and Angular for client side, good practice? I'm currently trying to figure out which technologies to use in order to maintain "realm features" in a web browser application. I've put together a rudimentary Swift app on iOS which allows for real-time updates coming from realm cloud.
I've spent the last 3-4 hours reading about Nginx, nodeJS, Angular, Express (angular framework) and other technologies.
As far as I've been able to understand, Realm can work with GraphQL which in turn lists nodeJS as a dependency (https://docs.realm.io/sync/getting-started-1/web-based-graphql).
So far I have a Debian 10 server running nginx. I have also installed nodeJS and NPM.
Assuming that I'm on the right path, where do I go from here?
It's proving to be a pretty tough challenge for me but, any help is greatly appreciated!
Thank you for your time.
Regards,
Renato


text:
Q: Is there a better method than asOpt to convert json into a model I am using JsValue's asOpt to convert a json into a model T. My issue is that the json parsing is failing and I am getting None but there is no descriptive error message which indicates what is the issue with the json. Is there a better method than asOpt which I could use?
The code which converts JsValue to model is
implicit val myDataReads:Reads[MyData] = (
    (JsPath \ "field1").readNullable[UUID] and
    (JsPath \ "field2").read[String] and
      (JsPath \ "field3").read[List[String]] and
      (JsPath \ "field4").read[Seq[Byte]] and
      (JsPath \ "field5").read[String] and
      (JsPath \ "field6").read[Set[String]] and
      (JsPath \ "field7").read[String] and
      (JsPath \ "field8").read[String]
    )(MyData.apply _)

The above isn't descriptive. I thought to create my custom Reads but I am stuck. So far I have written:
val myDataReads = new Reads[MyData] {

//the JsValue passed to this reads should conform to structure expected by MyData
def reads(jsv:JsValue) = JsResult = {
//I want to pick each field, check its value and print error is something is wrong
  val uuidOptionReads:Reads[Option[UUID]] = (JsPath \ "field1").readNullable[UUID]; //not sure if this is correct
  //now I have got new Reads but how do I get uuid from here?
uuidOptionReads.reads(/*reads expects a JsValue but I don't know what to pass here.*/)
/*I want to repeat the above logic for other fields*/
}

  }


text:
Q: How to use defaultdict in dict.fromkeys? I want to count the histogram for a property value(depth here) of 3 different samples with 1 dictionary.
SamplesList = ('Sa','Sb','Sc')
from collections import defaultdict
DepthCnt = dict.fromkeys(SamplesList, defaultdict(int))

This code will make DepthCnt contains 3 defaultdict(int) of the same one, thus I cannot count different samples.
How can I do it right ?
It is OK to use either DepthCnt[sample][depth] or DepthCnt[depth][sample].

I tested these 3 ways:
from collections import defaultdict
DepthCnt = {key:defaultdict(int) for key in SamplesList}
yDepthCnt = defaultdict(lambda: defaultdict(int))

from collections import Counter
cDepthCnt = {key:Counter() for key in SamplesList}

The memory size are:
 DepthCnt[sample][depth]:  993487
yDepthCnt[depth][sample]: 1953307
cDepthCnt[sample][depth]:  994207

It seems good to change to Counter().

A: Use a dictionary expression/comprehension/display
DepthCnt = {key:defaultdict(int) for key in SamplesList}

A: It sounds like you're trying to count occurences of sammples in SamplesList. If so you're looking for a collections.Counter
Given:
SamplesList = ('Sa','Sb','Sc')

Counter:
from collections import Counter
DepthCnt = Counter(SamplesList)
print(DepthCnt)
#Counter({'Sc': 1, 'Sa': 1, 'Sb': 1})

Edit:
You can always use a counter instead of a defaultdict as well
DepthCnt = {key:Counter() for key in SamplesList}
print(DepthCnt)
#DepthCnt = {'Sa': Counter(), 'Sb': Counter(), 'Sc': Counter()}

P.S
If you're working over a large dataset as well take a look into the Counter class both Counter and defaultdict are similar below is the TLDR from this great answer to a question on Collections.Counter vs defaultdict(int)

*

*Counter supports most of the operations you can do on a multiset. So,
  if you want to use those operation then go for Counter.

*Counter won't add new keys to the dict when you query for missing
  keys. So, if your queries include keys that may not be present in the
  dict then better use Counter.

*Counter also has a method called most_common that allows you to sort items by their count. To get the same thing in defaultdict you'll have to use sorted.


text:
Q: Can a language be "complete" without explicit type casting? Can a programming language be "complete" without the existence of explicit casting? In essence, is there anything we can't do using a language that lacks explicit type casting?
For example, the post below demonstrates that Java requires explicit type casting to write customized generic-type classes.
Are there any other example use cases where we absolutely need explicit casting?

A: Here are some
To reverse automatic primative widening:
byte blammy = (byte)(schmarr & 0xF7);

Legacy code:
public void oldSchoolMethod(List oldSchoolListOfStrings)
{
    String firstValue = (String)oldSchoolListOfStrings.get(0);
}

HTTP Code:
public String getSchmarr(HttpServletRequest request)
{
    HttpSession session = request.getSession();
    return (String)session.getAttribute("Schmarr");
}

Edit: "type increases" corrected to "primative widening".

A: Sure, take the equals method for example - it has to get Object a parameter. (and read this great chapter of Effective Java regarding equals and friends)

A: In Java, there is no way to declare an array of a generic type T. For example, it is invalid to declare an array using new T[10]:
public class List<T> {
    T[] backing_array = new T[10]; // this line is invalid,

    public T Item(int index) {
        return backing_array[index]; // and therefore this line is invalid as well.
    }

    //etc...

The best alternative solution we have is this:
public class List<T> {
    Object[] backing_array = new Object[10];

    public T Item(int index) {
        return (T) backing_array[index]; // notice that a cast is needed here if we want the return type of this function to be T
    }

    //etc...

If explicit type casting did not exist in Java, it would be impossible to build generic array lists, since declare an array of a generic type T is not allowed.

A: I use casting frequently when dealing with libraries that aren't built with generics in mind, or when I need to down-cast some object to access functionality I know is implemented by a subclass, but not by the class that I'm otherwise using.  It's probably wise to check with an if (foo instanceof Bar)
clause before making that cast, though.

A: When we deserialize an object (for example from a string) we are required to cast the object in to the class so that we can use its methods.


text:
Q: Different between UIView and UIControl when drag inside UIScrollView I have a UIScrollView which contains some small UIView subclass. UIScrollView is scroll enabled, and I want each UIView can be dragged inside UIScrollView freely.
My UIView subclass has this method:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] != self) {
        return;
    }
    CGPoint touchPoint = [touch locationInView:self.superview];
    originalX = self.center.x;
    originalY = self.center.y;
    offsetX = originalX - touchPoint.x;
    offsetY = originalY - touchPoint.y;
    [self.superview bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == self) {
        CGPoint location = [touch locationInView:self.superview];
        CGFloat x = location.x + offsetX;
        CGFloat y = location.y + offsetY;
        self.center = CGPointMake(x, y);
        return;
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == self) {
        self.center = CGPointMake(originalX, originalY);
    }
}

I found touchesCancelled:withEvent will be called each time I just drag UIView several pixels. But these codes will work correctly if it is subclass of UIControl.
Why?
Thanks in advance!

A: UIScrollView tries to determine what kind of interaction the user has in mind. If you tap a view inside a scroll view, that view gets the touch began. If the user then drags, the scroll view decides that the user wants to scroll, so it sends touchesCancelled to the view which first got the event. It then handles the dragging itself.
To enable your own dragging of subviews, you can subclass UIScrollView and override touchesShouldBegin:withEvent:inContentView: and touchesShouldCancelInContentView:.