text:
Q: How to make cardview responsive?    ]2]2
this is NamazActivity.java In java class i just add cardview click listener and open a toast message. Every click listener shows the iteam ID with simple text
package com.example.shakeelmughal.assanislam;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridLayout;
import android.widget.Toast;

public class NamazActivity extends AppCompatActivity {

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

        //back button
        if(getSupportActionBar()!= null)
        {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        gridLayout = findViewById(R.id.gridlayout);
        setSingleClick(gridLayout);
    }

    //function for going back to previous activity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home)
            finish();
        return super.onOptionsItemSelected(item);
    }

    private void setSingleClick(GridLayout gridLayout) {
        for (int i = 0; i < gridLayout.getChildCount(); i++) {
            CardView cardView = (CardView) gridLayout.getChildAt(i);
            final int s = i;
            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(NamazActivity.this, "Item " + s + " Clicked", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

this is nazamactivity.xml In XML class i use gridlayout and inside it i use cardview with a text view and a image view. I have make 3 card in it...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.shakeelmughal.assanislam.NamazActivity"
    android:orientation="vertical"
    android:weightSum="5">

    <RelativeLayout
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <TextView
            android:id="@+id/textGrid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="40sp"
            android:textColor="#000"
            android:layout_centerInParent="true"
            android:text="نماز"/>
    </RelativeLayout>

    <GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_weight="4"
        android:alignmentMode="alignMargins"
        android:columnCount="1"
        android:columnOrderPreserved="false"
        android:padding="14dp"
        android:rowCount="3">

        <!-- Row 1 -->
        <!-- Col 1 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_rowWeight="1"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:src="@drawable/tahart"
                    android:paddingRight="70dp"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text= " Ùرض نمازیں"
                    android:textAlignment="center"
                    android:textColor="#000"
                    android:textSize="25sp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="25sp"
                    android:textColor="#000"
                    android:text="5"
                    android:paddingLeft="10dp"/>
            </LinearLayout>
        </android.support.v7.widget.CardView>

        <!-- Row 2 -->
        <!-- Col 1 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_rowWeight="1"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:src="@drawable/namaz"
                    android:paddingRight="70dp"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="واجب نمازیں"
                    android:textAlignment="center"
                    android:textColor="#000"
                    android:textSize="25sp" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:text="3"
                    android:textSize="25sp"
                    android:paddingLeft="10dp"/>
            </LinearLayout>
        </android.support.v7.widget.CardView>

        <!-- Row 3 -->
        <!-- Col 1 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_rowWeight="1"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:paddingLeft="10dp"
                    android:paddingRight="80dp"
                    android:src="@drawable/namaz" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Ù†ÙÙ" نمازیں"
                    android:textAlignment="center"
                    android:textColor="#000"
                    android:textSize="25sp"
                    android:paddingRight="20dp"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="4"
                    android:textSize="25sp"
                    android:textColor="#000"/>
            </LinearLayout>
        </android.support.v7.widget.CardView>

    </GridLayout>

</LinearLayout>

A: Try this Make ScrollView as your parent layout it will work
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="5">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <TextView
                android:id="@+id/textGrid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="نماز"
                android:textColor="#000"
                android:textSize="40sp" />
        </RelativeLayout>

        <GridLayout
            android:id="@+id/gridlayout"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_alignParentTop="true"
            android:layout_weight="4"
            android:alignmentMode="alignMargins"
            android:columnCount="1"
            android:columnOrderPreserved="false"
            android:padding="14dp"
            android:rowCount="3">

            <!-- Row 1 -->
            <!-- Col 1 -->
            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_columnWeight="1"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_rowWeight="1"
                app:cardCornerRadius="8dp"
                app:cardElevation="8dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="16dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:paddingRight="70dp"
                        android:src="@drawable/ic_message" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text=" Ùرض نمازیں"
                        android:textAlignment="center"
                        android:textColor="#000"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="10dp"
                        android:text="5"
                        android:textColor="#000"
                        android:textSize="25sp" />
                </LinearLayout>
            </android.support.v7.widget.CardView>

            <!-- Row 2 -->
            <!-- Col 1 -->
            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_columnWeight="1"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_rowWeight="1"
                app:cardCornerRadius="8dp"
                app:cardElevation="8dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="16dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:paddingRight="70dp"
                        android:src="@drawable/ic_message" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="واجب نمازیں"
                        android:textAlignment="center"
                        android:textColor="#000"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="10dp"
                        android:text="3"
                        android:textColor="#000"
                        android:textSize="25sp" />
                </LinearLayout>
            </android.support.v7.widget.CardView>

            <!-- Row 3 -->
            <!-- Col 1 -->
            <android.support.v7.widget.CardView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_columnWeight="1"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_rowWeight="1"
                app:cardCornerRadius="8dp"
                app:cardElevation="8dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_margin="16dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:paddingLeft="10dp"
                        android:paddingRight="80dp"
                        android:src="@drawable/ic_message" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingRight="20dp"
                        android:text="Ù†ÙÙ" نمازیں"
                        android:textAlignment="center"
                        android:textColor="#000"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="4"
                        android:textColor="#000"
                        android:textSize="25sp" />
                </LinearLayout>
            </android.support.v7.widget.CardView>

        </GridLayout>

    </LinearLayout>
</ScrollView>


text:
Q: Google Cloud Platform: SSH to Google cloud instance will have "Permission denied (publickey)" I have come across the  issue as below when I use ssh login google cloud instance
$ ssh -i DD2 root@35.237.32.84
Permission denied (publickey).

After some testing, I found that the cause of the error is that public key signature is not consistent with the account for google cloud:
For example :
scuio33@chef-server:~$

here you account is scuio33
then your pub file will be :
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBpNeFZyXXXehjPuGCkEjb/t
laNQt0fztORSCFFQIoKHkQzi7SNhp48kagyOHDNj6mY1LmVZB/sIj2oCa1AFupoFuBYc/XILP
rTX60fIlnBYkHl+6Kq/TX2hzKv scuio33

scuio33 will be exactly same as your google account, or there will have the issue  "Permission denied (publickey)". Only google cloud has this restriction.
This is not a "question". But a hint for ssh to google cloud failure.

A: You have to make sure that the same username you used to generate the key matches the one from your local cpu.

Step-by-steps:
1/ Generate the key (no paraphrase)
On local cpu:
By default on linux $USER will give you your username (echo $USER), so you don't even need to specify it.
ssh-keygen -t rsa -f ~/.ssh/my_google_cloud_key -C $USER

2/ Copy the key to Google Cloud metadata
cat /home/$USER/.ssh/my_google_cloud_key.pub

Select and copy it in https://console.cloud.google.com/compute/metadata/sshKeys (add key, then save)
3/ Connect to your VM
Get the external IP of your instance at https://console.cloud.google.com/compute/instances
EXTERNAL_IP={{input your external ip}}
ssh-i ~/.ssh/my_google_cloud_key $USER@$EXTERNAL_IP

A: Connecting with an SSH key to a Google Cloud Compute Engine instance is not limited to the users of the project the instance belongs to. You can generate an SSH key and as long as it's added to the instance and the user exists on the OS, you should be able to SSH. You can connect with other usernames. Make sure that:

*

*You add the public key to the instance via the Google Cloud Console [1]

*Your username exists on the OS of your instance

*If you want to SSH as "root", change the configuration in your /etc/ssh/sshd_config file.

A: I experienced this issue when trying to set up Kubernetes for the first time on Google Cloud Platform.
I was running into the error below each time I tried to SSH into my instance from my terminal:
promisepreston@52.174.274.72: Permission denied (publickey)

Here's how I solved it:
Open a terminal on your workstation and use the ssh-keygen command to generate a new key. Specify the -C flag to add a comment with your username.
ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]

In my case it was:
ssh-keygen -t rsa -f ~/.ssh/kubernetes-trial -C promisepreston

Navigate into the .ssh directory:
cd ~/.ssh

Restrict access to your private key so that only you can read it and nobody can write to it.
chmod 400 [KEY_FILENAME]

In my case it was:
chmod 400 kubernetes-trial

Double click on kubernetes-trial.pub to open it OR print it on the console using the cat command:
sudo cat kubernetes-trial.pub

The public SHH key should be of this format:
ssh-rsa [KEY_VALUE] [USERNAME]

OR
ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}

In my case it was:
ssh-rsa AAAAB3MzaC1yc2EAAAADAQABAAABAQDdLjLb2b97m9NSK5Z8+j6U8awAwIx1Sbn9o4cEpYT2USYlFhJPRckgnmCQ+Eaim/sgL40V2v3Jwt6HVAY0L9bl84jmvox9QP4FOY7+LM02ZqfRB6LaEukM1tGdObVr+HBvhOwrxGCI06GFjnD3vVzW4jEsK75Y7MPzXd5YSpebGvU+7ZOuEcuSKp/R9dJcJn4kdXeaqor4gh8uTKQ43PGPTEvyoNlCWLkwSgy8khbo2BpoChLA7B53pVEhviMvVVIbmwpc6V2AIhRYY7ppR8oBzklLgh8CtTBPXtQRYiahLOIhds6ORf7wGNFI+A4sbBqwEL3J6av5fE1+zkUBhAHX promisepreston

Copy its contents and paste in the SSH Section of your instance under the Metadata section
Adding or removing instance-level public SSH keys

In a local terminal, navigate to the directory where you have the private SSH key file, use the ssh command along with your private SSH key file, the username, and the external IP address of the instance to connect. For example:
ssh -i private-key username@external-ip-of-the-virtual-instance

In my case it was:
ssh -i kubernetes-trial promisepreston@52.174.274.72

After you connect, run commands on your instance using this terminal. When you finish, disconnect from the instance by running the exit command.
Note:

*

*Ensure that you added the instance-level public SSH keys
Adding or removing instance-level public SSH keys

*Ensure that you are not blocking project-wide public SSH keys from the Linux instance
Allowing or blocking project-wide public SSH keys from a Linux instance

*Ensure that OS Login is not enabled
Enabling or disabling OS Login
That's all.
I hope this helps

A: Promise Preston`s solution works, just make sure you disable "ENABLE-OSLOGIN" or remove this from the metadata settings.

A: promise-preston's answer works for me. The problem is that the name not match google account name.
Take into consideration that, if not specified, the name google ssh server recognize is automatically generated based on your email address BUT not necessarily the same. In my case my email address is wenzhan.main@gmail.com, and the user name is actually wenzhan_main. Double check that trick.
One more small thing i want to add on is that, something like ssh -i kubernetes-trial promisepreston@52.174.274.72, will only work if you are already in .ssh/ directory.

A: Had the same error. try to add --tunnel-through-iap
gcloud compute ssh --zone "%zone%" "%instanaceName%" --project "%projectName%"  --tunnel-through-iap

Replace the following:

*

*%zone% - Enter the zonal (location) name of the compute engine

*%instanceName% - Name of the instance(compute engine)

*%projectName% - Google cloud current project name

A: Ran into the same error and resolved by unchecking "Block project-wide SSH keys" on the "VM instance details" settings page. Apparently this blocks ssh-ing from your local to GCE instances.

A: Go to project-level metadata (Compute Engine -> Metadata) and ensure that you have either no enable-oslogin key or that it is set to FALSE.This worked for windows powershell

A: For what it's worth I had to add the SSH key inside of "edit [name] instance"-> Security and access --> SSH Keys, I added the .pub key as mentioned above.

A: I know there are similar answers but I am lost in the answers, easly;
for the existing ssh key
1- Copy your public key like the following format, i.e:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAu5kKQCPF... hbceylan
2- GCP > Edit VM > add SSH key > SAVE

3- SSH to the instance
ssh -i /path-to-private-key/id_rsa hbceylan@1.2.3.4
for a new ssh-key
1- Create an ssh key, i.e:
ssh-keygen -t rsa -f ~/.ssh/x-poject-hbceylan -C hbceylan -b 2048
2- GCP > Edit VM > add SSH key > SAVE (see picture)
3- SSH to the instance
ssh -i /path-to-private-key/id_rsa hbceylan@1.2.3.4

A: In my case, despite uploading the public key to the VM and configuring ssh file in Visual Studio with private key, I was unable to connect, for the same reason.
For me, this is what solved. You follow the steps of adding .pub file to instance metadata, hold you private key in the ssh config file, then run:
gcloud compute ssh --zone "your-vm-zone" "your-instance"  --project "your_project"

This will generate a id_rsa file recognized by the Google Cloud VM. Then you can connect regularly using SSH, in my case, in Visual Studio Code.

A: I was trying to do this as user jupyter. Prompted by @maximusX3's answer, which suggested to make a change in the Metadata, I pulled up my GCP metadata's SSH keys subpage.
Interestingly, when I loaded the page, I had duplicate SSH keys for the jupyter user, and the interface automatically prompted me to delete duplicate SSH keys. (You can do this through the GCP interface with one click.) After doing so, I was able to ssh in as jupyter using the usual gcloud compute ssh jupyter@machine command without any other local or remote changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select random item from drop-down list using Cypress? In the site: https://www.testandquiz.com/selenium/testing.html there is a drop down located here
enter image description here
The html is like the following:

<select id="testingDropdown">
<option id="automation" value="Automation">Automation Testing</option>
<option id="performance" value="Performance">Performance Testing</option>
<option id="manual" value="Manual">Manual Testing</option>
<option id="database" value="Database">Database Testing</option>
</select>

I would like to:

*

*Click on the mentioned drop down

*Count the number of items

*Select the random item from the list

How to deal with that usuing cypress ?
I tried by the following but the test failed

describe('Cypress.io tests', function() {
    it('Open cypress.io page', function() {
      var cypressPage = 'https://www.testandquiz.com/selenium/testing.html'

cy.visit(cypressPage)
     cy.xpath("//[@id='testingDropdown']").click();

    })
  })

A: So for example we have a select with three options.
HTML code:
<select id="selectId">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

javascript code:
  //Random int number generator between min and max
  function getRandomInt(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  cy.get(`#selectId> option`) // we get the select/option by finding the select by id
  .then(listing => {
    const randomNumber = getRandomInt(0, listing.length-1); //generate a rendom number between 0 and length-1. In this case 0,1,2
    cy.get(`#selectId> option`).eq(randomNumber).then(($select) => {              //choose an option randomly
      const text = $select.text()       //get the option's text. For ex. "A"
      cy.get(`#selectId`).select(text)       // select the option on UI
    });
  })

A: Why don't you use .get() to reach your element?
With .children() you can get the amount of elements within your dropdown.
cy.get('#testingDropdown').children()

Or do you want it as a variable?

A: A bit late to the party.
Cypress will not allow you to use click() for select elements. You will need to use select function for this.
You will  also need two xpaths:

*

*For the drop down element

*For the drop down options that will be selected at random.

This is the working code
describe('Cypress.io tests', function() {
it('Open cypress.io page', function() {
  var cypressPage = 'https://www.testandquiz.com/selenium/testing.html';

cy.visit(cypressPage);
   // Get the array of options
   cy.xpath('//*[@id="testingDropdown"]//option').then(($elements) => {
  const randomOption = Math.floor(Math.random() * $elements.length);
  // select option from drop down
  cy.xpath('//*[@id="testingDropdown"]').select(`${$elements[randomOption].innerText}`);
  cy.log(`random option selected is ${$elements[randomOption].innerText}}`);
})
})


text:
Q: Reading a csv file with spaces into Octave I have some Pose Update rostopic data that I wrote onto a csv file using rostopic echo /foo > foo.csv
foo.csv looks like:
%time,field
1539675906586600065,0.157465848996
1539675906587352037,0.160723703902
1539675906587656974,0.161057770877
1539675906587693929,0.161579636574

I'm trying to import this into Octave for further processing but it's not exactly a constant delimiter and I have had no luck with dlmread or dlmwrite.
I tried
nsec = dlmread (nsecval,"\n",r1,c1)

 error: 'nsecval' undefined near line 1 column 17 error: evaluating argument list element number 1`

I need to:

*

*Ignore the first row with %time, field

*Take only the second part of each row e.g. 0.157465848996

*Convert the spaces into a format that dlmread or csvread can work with

*Convert all of those values into a column of a
matrix.

E.g.
0.157465848996
0.160723703902
0.161057770877
0.161579636574

I'm really new to Octave and scientific computing in general and would really appreciate some help.

A: If you are using linux, I recommend a small preprocessing with sed to replace all commas with space:
 sed  -i "s#,# #g"  your_file

If you are using windows or anything else, replacing the commas should be equally easy. Once you have this, in octave, just use
i=load("your_file");
vec=i(:,2);

to get the second column into a column vector.

A: Firstly, the tried issue with nsec = dlmread (nsecval,"\n",r1,c1):
The octave error is telling you that it doesn't know what 'nsecval' is.
Next using dlmread, the function is expecting the filename, the delimiter value, start row, start column (from 0) so something like:
nsec = dlmread ("foo.csv", ",", 1, 1)

will get the data you require.


text:
Q: Maven rpm plugin secondary artefact not uploaded to repo I have implemented the maven rpm plugin in the "RPM as Secondary Artifact" style configuration (http://mojo.codehaus.org/rpm-maven-plugin/usage.html)
    <execution>
        <id>attach-rpm</id>
        <phase>deploy</phase>
        <goals>
            <goal>attached-rpm</goal>
        </goals>
    </execution>

We have distribution management configured in our parent, and this deploys the war to nexus fine.
The rpm is created, but does not get uploaded to nexus however.
I was asked to invoke the rpm plugin in the deploy phase. Could this be why the rpm is not uploaded to nexus? Does it have to be created during package?

A: You indeed answered your question. The rpm needs to be created as part of the packaging phase so that is available during the deploy phase.
Likely what is occurring is that the actual deploy work of pushing out to the repository is occurring before the rpm plugin is being invoked.


text:
Q: Symfony - App uses wrong database name, CLI uses the correct one hoping to get help with possibly a silly problem. I can't get Symfony to connect to the correct database.
My config line in .env is as follows
DATABASE_URL="mysql://root:root@127.0.0.1:3306/main?serverVersion=mariadb-10.4.27"

Creating a database using CLI works just fine and the database named "main" is created
bin/console doctrine:database:create
Created database `main` for connection named default

Running migration works OK and a table is created in the database
bin/console doctrine:migrations:migrate

 WARNING! You are about to execute a migration in database "main" that could result in schema changes and data loss. Are you sure you wish to continue? (yes/no) [yes]:
 > yes

[notice] Migrating up to DoctrineMigrations\Version20230117183120
[notice] finished in 28.6ms, used 22M memory, 2 migrations executed, 3 sql queries

Yet, when I try to access the site from the browser I get the following error
An exception occurred in the driver: SQLSTATE[HY000] [1049] Unknown database 'root'

Clearing the cache doesn't seem to help, I don't see any reference in the code to a database named root. Any clues on how to make Symfony to connect to the "main" database?
Cheers
P.


text:
Q: How to create focus effect for QTreeView while it does not have focus?
I am creating a completer as above, which is combination of QTreeView (for the content) and QLabel (for the title). I built the list myself, did not inherit from QCompleter, but from QWidget.
Completer::Completer( QWidget *p_parent ) : QWidget( p_parent )
{
  setWindowFlags( Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Popup );
  QGridLayout *tableViewLayout = new QGridLayout( this );
  tableViewLayout->setSpacing( 0 );
  tableViewLayout->setMargin( 0 );
  m_title = new QLabel;
  .....
  tableViewLayout->addWidget( m_title );

  m_view = new CompleterView();
  m_style = new CompleterStyle();
  m_view->setStyle( m_style );
  m_view->setItemDelegate( new CompleterDelegate( m_view ) );

  m_sourceModel = new CompleterSourceModel( this );
  m_proxyModel = new CompleterProxyModel( this );
  m_proxyModel->setSourceModel( m_sourceModel );
  m_view->setModel( m_proxyModel );
  tableViewLayout->addWidget( m_view );
}

Above the completer is a QLineEdit. When I click on the bulb or write something in the LineEdit, the completer will be shown. Theoretically, the completer should have focus because I set in the constructor above setWindowFlags( Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Popup );. But I want the LineEdit always has focus, so i can continue to write. I used the method mentioned here and the focus remains at LineEdit.
Now as you see there is mouse over effect for the QTreeView above, when I move the mouse over a line, there is a orange background for that line. I did it in function paint of delegate. Now I want to do the same effect but from keyboard. I don't know how to do it because the completer has now no focus anymore (focus remains in LineEdit). I debugged (pressed up and down key on the keyboard), sometimes the scrollbar shifts and the index coordinate is always (-1, -1). I don't know why because how can I control the Completer meanwhile it does not has focus ????? (but that is another problem, i should figure out).
How can I create the same effect here from the keyboard? Could you give me a hint or a direction for that?


text:
Q: Level curve and a surface How to make the following picture using tikz
Surface is easy to draw but the level curve is difficult.

A: I feel you'd be better off if you try to build on other posts, including answers that you got.
\documentclass[tikz,border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16,width=7cm,height=11cm}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines=middle,ymin=0,xmin=0,zmin=0,smooth,
    colormap/hot,view={115}{20},
    xtick=\empty,ytick=\empty,ztick=\empty,
    declare function={f(\x)=15+\x*\x;k=3;}]
  \draw[blue] plot[variable=\y,domain=0:360,smooth cycle]
  ({7+k*cos(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{7+k*sin(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{0});
  \fill[blue,fill opacity=0.5] plot[variable=\y,domain=290:97]
  ({7+k*cos(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{7+k*sin(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{f(k)})
  -- (7,12.5,{f(k)}) -- (1.5,12.5,{f(k)}) -- (1.5,1.5,{f(k)}) -- (7,1.5,{f(k)}) -- cycle;
  \addplot3[surf,shader=interp,domain y=0:360,samples y=51,domain=0:4,z buffer=sort]
   ({7+x*cos(y)*(1-0.2*cos(2*y)-0.2*cos(y))},{7+x*sin(y)*(1-0.2*cos(2*y)-0.2*cos(y))},{f(x)});
  \fill[blue,fill opacity=0.5] plot[variable=\y,domain=-70:97]
  ({7+k*cos(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{7+k*sin(\y)*(1-0.2*cos(2*\y)-0.2*cos(\y))},{f(k)})
  -- (7,12.5,{f(k)}) -- (12.5,12.5,{f(k)}) -- (12.5,1.5,{f(k)}) -- (7,1.5,{f(k)}) -- cycle;
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Laravel Pusher Error "No Callback" Error I am trying to build real time Notifications using Laravel 5.3 and Pusher for my Web-Applicatin. I am able to push messages to Pusher debug console.
My Server-side script:
$options = array(
                    'cluster' => 'ap2',
                    'encrypted' => true
            );
            $pusher = new Pusher(
                    'xxxxxxxxxx', // removed for safety
                    'xxxxxxxxxx', // removed for safety
                    'xxxxx', // removed for safety
                    $options
            );

            $data['message'] = ($user->name)." like your status";
            $pusher->trigger('my-channel', 'PusherEvent', $data);

And my Client-side Script:
<script src="https://js.pusher.com/4.0/pusher.min.js"></script>

// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('xxxxxxxxx', {
  cluster: 'ap2',
  encrypted: true
});

var channel = pusher.subscribe('my-channel');
channel.bind('PusherEvent', function(data) {
  alert(data.message);
});

I want to get alert on my webpage.Javascript is enabled in my browser.My browser console shows something like this:
Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"my-channel"}} pusher.min.js:8:2594
Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"my-channel"}
Pusher : No callbacks on my-channel for pusher:subscription_succeeded

What might be the reason for this ??

A: You don't have any bindings for an event called pusher_internal:subscription_succeeded. This is normal and nothing to worry about. When you subscribe to a channel an event is fired which you aren't listening for.
If you got an event called PusherEvent and got that callback message you should be concerned.


text:
Q: Combinatorial Proof of Multinomial Theorem - Without Induction or Binomial Theorem I've been trying to rout out an exclusively combinatorial proof of the Multinomial Theorem with bounteous details but only lighted upon this one - see P2. Any other helpful ones?

$(x_1+\cdots+x_k)^n =$ Top of Page 39 from UNC:
  $\sum\limits_{\large{(a_1, ..., a_{k - 1}) \; \ni \; 0 \le a_1+...+ a_{k - 1} \le n}}\dbinom{n}{a_1,...,a_{k-1}}\cdot x_1^{a_1} \cdots x_{k-1}^{a_{k-1}}x_k^{\large{n - a_1 - \cdots - a_{k-1}}}$
  $= \sum\limits_{\large{a_1+...+a_k = n \; \& \; a_i \ge 0 }}\dbinom{n}{a_1,...,a_k} x_1^{a_1} \cdots x_k^{a_k}$ Bottom of P1 from MSU.

I see that both are the Multinomial Theorem but which one is better?
I thought to try this myself, following the combinatorial proof of the Binomial Theorem. So  esteem each term (in green) in $(x_1+\cdots+x_k)^n = \underbrace{\color{green}{[x_1+\cdots+x_k]...[x_1+\cdots+x_k]}}_{\text{n terms}}$ as one box from which to choose $x_1, ..., x_k$.
Since each term/box (in green) contains $k$ terms, the total number of terms $ = k^n$.
First, consider $x_1$.
● For $x_1^n$, must have $a_ 1 = n\qquad \& \qquad a_2 = ... = a_k = 0$.
● For $x_1^{n - 1}$, must have $a_1 = n - 1 \qquad \& \qquad a_2 \text{ OR } ... \text{ OR } a_k = 1$
(the latter due to $a_1+...+a_k = n$ in definition from P1 of MSU)
...
● For $x_1^{1},$ must have $a_1 = 1 \qquad \& \qquad a_2 \text{ OR } ... \text{ OR } a_k = n - 1$
● For $x_1^{0},$ must have $a_1 = 0 \qquad \& \qquad a_2 \text{ OR } ... \text{ OR } a_k = n$
The above extends to and must hold for all $x_1, ..., x_k$.
How to translate all this into combinatorial notation? How to forge ahead and complete please?

A: This is one approach: When you expand $(x_1+x_2+....+x_k)^n$ , you will have a collection of terms $c_ix_1^{n_1}x_2^{n_2}......x_k^{n_k}$ for each "box"/factor $i$ in your green, so that $n_1+n_2+..+n_k=n$.
For  a  fixed given $k$-tuple $(n_1,..,n_k)$ , the assignment of the $n_1, ..., n_k$ can be chosen in:
$\dbinom {n}{n_1} \times \dbinom {n-n_1}{n_2} \times.....\dbinom{n-n_1-....-n_{k-1}}{n_k}$  ways. The $n_1$ balls can be chosen from the original $n$. After having used up $n_1$ balls, you only have $n-n_1$ balls left, which you can use to choose the $n_2$ balls for $x_2$, etc.. This expansion is precisely the multinomial coefficient: $$\dbinom {n}{n_1,n_2,....,n_k} $$
The above is true only for the given $k$-tuple $(n_1,..,n_k)$. Now, we do the sum over all $k$-ples  $(n_1, n_2,....,n_k)$ with  $n_1+n_2+...+n_k=n$
The reason why we sum over all $k$-ples is that, when we expand the product :
$$ (x_1+x_2+...+ x_k)^n= \underbrace{(x_1 + x_2+...+x_k) (x_1+x_2...+x_k)....(x_1+x_2+..+x_k)}_{n \text{ times }}$$
, you will ultimately multiply one element $x_{j1}$ from the first copy of $(x_1+x_2+..+x_k)$ with one element $x_{j2}$ in the second copy,... with an $x_{jk}$ from the $k$-th copy of $(x_1+...+x_k)$,
i.e., the product will have one element of each copy of the sum.
Notice some specific cases/examples, for $k=n=3$; I think this will be clearer than
a more formal argument:
$(\color{green}{x_1}+x_2+x_3)(x_1+x_2+x_3)(x_1+x_2+x_3)$ : We start with $\color{green}{x_1}$, multiply by some element $x_{j2}$ in the second parenthesis to get $x_1x_{j2}$, and then we multiply this $x_1x_{j2}$ by some element $x_{j3}$ in the third parenthesis (notice that we may have $x_{j2}=x_1, x_2$ or $x_3$). How many different monomials can we have? Well, each monomial will contain 3 terms, possibly repeated, so that the sum of the exponents of $x_1x_{j2}x_{j3}$ will add up to 3, e.g., we will have terms like $x_1x_1x_2=x_1^2x_2$, or $x_1^3$, or $x_1x_2x_3$, etc.
How many monomials of this sort can we have? Well, we can have as many as the number of all the 3-tuples (ie triples) of the exponents, $(n_1, n_2, n_3)$ chosen with ordering and with replacement, for the respective terms $x_1,x_2,x_3$, such that $n_1+n_2+n_3=3$ (because each monomial contains $k = 3$ terms).
Basically, we are summing over all strings $(x_1^{n_1}x_2^{n_2}...x_k^{n_k})$ , where all the exponents add-up to $n$; this amount of terms is equivalent to the number of solutions of the equation $x_1+ x_2+....+x_k =n$

A: The multinomial theorem says that for commuting quantities $X_1,\ldots,X_n$ in a ring one has
$$
  (X_1+\cdots+X_k)^n=\sum_{\substack{a_1,\ldots,a_k\in\Bbb N\\a_1+\cdots+a_k=n}}
  \binom n{a_1,\ldots,a_k}X_1^{a_1}\ldots X_k^{a_k}
$$
where the multinomial coefficient $\binom n{a_1,\ldots,a_k}$ can be defined (under the hypothesis $a_1+\cdots+a_k=n$, without which it is either left undefined, or maybe set to$~0$), either combinatorially as the number of words (of length$~n$) over the alphabet $\{A_1,\ldots,A_k\}$ containing $a_i$ copies of the letter$~A_i$ for $i=1,\ldots,k$, or algebraically as $\frac{n!}{a_1!\ldots a_k!}$.
A combinatorial proof of the multinomial theorem would naturally use the combinatorial description of multinomial coefficients. It is almost a triviality: without assuming that the $X_i$ commute, the $n$-th power can be expanded by the distributive laws to a sum of $k^n$ distinct monomials in the $X_i$, which are just all distinct words of length $n$ that can be formed from them; now assuming commutation, one groups together all words that have the same number of copies of each$~X_i$, and if those multiplicities are $a_1,\ldots,a_k$ respectively, then one gets $\binom n{a_1,\ldots,a_k}$ times the monomial $X_1^{a_1}\ldots X_k^{a_k}$.
The equivalence of the combinatorial and algebraic description of multinomial coefficients is another matter, but also quite simple. For a word of length$~n$ with given multiplicities $a_1,\ldots,a_k$ of individual letters, the $n!$ permutations of the letters of the word certainly generate all words that can be made from that multiset of letters, but each word is obtained multiple times. To obtain from one way to generate a word all other ways to generate the same word, one can independently permute all copies of a same letter among each other, which can be done in $a_1!\ldots a_k!$ ways. This means there are$\frac{n!}{a_1!\ldots a_k!}$ distinct words.

A: Let $n$ be a positive integer. For all $x_1$, $x_2$,..., $x_k$, $$(x_1+x_2+\cdots +x_k)^n=\sum {n\choose n_1,n_2,...,n_k}x_1^{n_1}x_2^{n_2}\cdots x_k^{n_k},$$ where the summation extends over all non-negative integral solutions $n_1,n_2,...,n_k$ of $n_1+n_2+\cdots +n_k=n$.
Write $(x_1+x_2+\cdots +x_k)^n$ as the product of $n$ factors where each factor is $(x_1+x_2+\cdots +x_k)$. Using the distributive law we can expand this product and collect like terms. For each of the n factors we can choose one of the the $k$ numbers $x_1,x_2,...,x_k$ and form their product for $k^n$ terms. Each of these terms can be arranged in the form $x_1^{n_1}x_2^{n_2}\cdots x_k^{n_k}$, where the non-negative integer exponents $n_1,n_2,...,n_k$ sum to $n$ We obtain this by noticing that we can choose $x_1$ in $n_1$ ways of the $n$ factors, $x_2$ in $n_2$ ways of the remaining $n-n_1$ factors,..., $x_k$ in $n_k$ ways of the remaining $n-n_1-\cdots -n_k-1$ factors. Using the Multiplication Principle, we see that the number of times the term $x_1^{n_1}x_2^{n_2}\cdots x_k^{n_k}$ occurs is $${n\choose n_1}{n-n_1\choose n_2}\cdots {n-n_1-\cdots {n_{k-1}}\choose n_k}={n\choose n_1,n_2,...,n_k}.$$ Thus $$(x_1+x_2+\cdots +x_k)^n=\sum {n\choose n_1,n_2,...,n_k}x_1^{n_1}x_2^{n_2}\cdots x_k^{n_k}.$$


text:
Q: Identifier is Null or empty, entity framework, Update data base I'm trying to update my model to add a new stored proc. However, I get the following error message when I try to.

This is the stored proc I'm trying to add
    BEGIN

        SET @result = 1;

        /* Execute first-pass validation rules. */
        EXECUTE [RulesEngine].[LGC_Validate_Rules] @passLevel = '1', @currentUserID = @current_user_id;

        /* Execute transformation rules. */
        -- None

        /* Execute second-pass validation rules. */
        EXECUTE [RulesEngine].[LGC_Validate_Rules] @passLevel = '2', @currentUserID = @current_user_id;

        RETURN
    END

GO

Any clues?


text:
Q: Actionscript 3 Centering a Moving Object on stage resize I want to center a big movieclip (1400 px wide) on my stage on stage resize. This big movieclip moves to the right on certain events so I can't use code like this:
currentPage.x = ((stage.stageWidth/2) - (currentPage.width/2))

Is there a way to maybe use its offset from 0 (the left side of the stage 'viewport') and use that offset in centering?
The movieclip only changes in x.

A: When a object is resized, we can say its scale has changed. Scales are nice because they allow us to work in percentages. Given any percentage change, we can apply the same change to any other object to get a relative position. Look here:
var previousStageWidth:Number;

public function handleResize():void {
    //calculate the difference in stage with as a percentage
    var widthScale:Number = previousStageWidth / stage.stageWidth;

    //scale the x value by the same amount
    myDisplayObject.x *= widthScale;

    //update the previous value for the next resize
    previousStageWidth = stage.stageWidth;
}

Hopefully that works out for you.

A: I'm prefer to make container sprite for all contents. Inside of container, everything is measured as if scene was always 400x300 (or any other fixed size, whatever aspect ratio you need). When scene is resized, I'm resizing and centering only the container to fit inside:
//not really tested because my real code is more complex, so watch out...
var bounds:Rectangle = container.getRect(null);
//scale factor to fit inside
var scaleFactor:Number = Math.min(stage.stageWidth / bounds.width, stage.stageHeight / bound.height);
container.scaleX = container.scaleY = scaleFactor; //scaling
//centering
container.x = (stage.stageWidth - container.width) * 0.5;
container.y = (stage.stageHeight - container.height) * 0.5;

This way you can handle any number of clips in container, not just one. Container not uses all screen space, but preserves aspect ratio. If you want to use all screen space, you have to think out dynamic layout of your stage - something only you can do properly.


text:
Q: Как оптимзировать изображения PyQt Библиотека PyQt5 позволяет вставлять изображения через виджет QLabel. Выглядит это примерно так:
Image = QtWidgets.QLabel(window)                   # Создаём объект QLabel
Image.setGeometry(QtCore.QRect(50, 50, 100, 100))  # Конфигурация объекта (x, y, width, height)
Image.setPixmap(QtGui.QPixmap('image.png'))        # Присваиваем объекту QLabel Изобржаение
Image.setScaledContents(True)  # Данный метод растягивает изображение на весь объект

Такой метод очень прост, но при этом, как оказалось, он тратит огромное количество оперативной памяти.
Дело в том, что я работаю с достаточно большими изображениями (до 5000 на 5000 точек). Из-за этого программа использует 90 Мб ОЗУ вместо 25 (без использования картинок).
Есть ли какие-нибудь способы сделать так, чтобы поместить большие изображения в QLabel, при этом не затратив много ОЗУ?
Думаю, может помочь Pillow, но не знаю как его использовать...
Вот рабочий пример:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(350, 250)
        self.Image = QtWidgets.QLabel(MainWindow)
        self.Image.setGeometry(QtCore.QRect(50, 50, 100, 100))
        self.Image.setPixmap(QtGui.QPixmap("image.png"))
        self.Image.setScaledContents(True)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

A: Попробуйте так:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(350, 250)
        self.Image = QtWidgets.QLabel(MainWindow)
        self.Image.setGeometry(QtCore.QRect(50, 50, 145, 100))

        self.Image.setPixmap(
            QtGui.QPixmap(
                "photo-1493976040374-85c8e12f0c0e.jpg"
            ).scaled(145, 100))                                  # + scaled(145, 100)

# -        self.Image.setScaledContents(True)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

photo-1493976040374-85c8e12f0c0e.jpg
Ваше изображение слишком велико для загрузки (более 2 МБ).
photo-1493976040374-85c8e12f0c0e.jpg  --> 7360x4912  -->

Update
Вот результат работы вашего приложения с моим изображением.
Что значит не помогло? Посмотрите на результат и объясните лучше что не помогло, какие у вас результаты?
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(350, 250)
        self.Image = QtWidgets.QLabel(MainWindow)
        self.Image.setGeometry(QtCore.QRect(50, 50, 145, 100))

        self.Image.setPixmap(
            QtGui.QPixmap(
                "photo-1493976040374-85c8e12f0c0e.jpg"
            ))                                          # - scaled(145, 100)

        self.Image.setScaledContents(True)              # +

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


text:
Q: Error when trying to run import pytube with aws lambda Hello I'm trying to import pytube in my lambda function but i get the following error when I try to run the code:

Response {
      "errorMessage": "Unable to import module 'index'" }
Function Logs Unable to import module 'index': No module named
  'pytube'

Here is my code:
import boto3
from pytube import YouTube

s3 = boto3.resource('s3')

URL = ''
PATH = ''

def handler(event, context):
    YouTube(URL).streams.first().download(PATH)

And my IDE says pytube is already installed:

Requirement already satisfied: pytube in
  /home/ec2-user/.local/lib/python2.7/site-packages

What could be the problem?

A: The problem is that you are not including your dependencies in your deployment package.
See https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#deployment-pkg-for-virtualenv for full details, but effectively you must do:
pip install pytube -t /path/to/project-dir

Before making the zip file for uploading.
(Note that boto3 is an exception to this rule, as AWS automatically include it for you, on the assumption that your lambda probably works with AWS services!)


text:
Q: PHP Mess Detector for Eclipse I have the PTI Eclipse plugin installed.
There is a possibility to change PDepend, CodeSniffer and UnitTest
When I try right-clicking on any file I have a Mess Detector option as well but nothing happens when I click it. And after searching all configuration options, I and can't find any settings for PHPMD.
Does anyone know how to solve it?

A: Old question but since there still seems to be interest in it... I just installed the PTI plugin and there was no mention of PHPMD so I wonder where you get the "Mess Detection" menu item from?
For me actually nothing of PTI works with Eclipse Kepler SR2. Whatever I try just nothing happens.
I'd recommend you MakeGood for running PHPUnit tests in Eclipse and setting up Jenkins (including PHPMD) for your project, it takes a bit time to set up but once it is running it is just great: Template for Jenkins Jobs for PHP Projects

A: When PHPMD runs, it first searches for a default PHP executable which must exist, and this is not set in "PHP Tools" but in "PHP":
Window > Preferences > PHP > PHP Executables > (choose one) > [SET DEFAULT]

But if you had not done this, you would have gotten an error.
At this point PHPMD runs, and places its output in the PHPMD view (not in the Console view), which is usually displayed at the bottom. If it does not appear at all, it might have been closed or ignored. So:
Window > Show View > PHP Tools (Others?) > PHPMD

Another thing that may happen is that PHPMD detects nothing (the view appears but it is empty). In that case you can check the Console view to see what happened. Otherwise, you could try and modify the phpmd.php script which is run by PTI so that it logs what it's doing (you might for example wrap the main routine in a try/catch), either to stdout or by opening a temporary file somewhere on your system.


text:
Q: How to get number of customer and total amount for time range? I want to have the result of the table below, I have two tables, one for the clients and one for the transactions made by the clients.Someone can help me to achieve that!Thank's in advance
here is what i want to return

This the query i write to get the result.
 $customers_trans = DB::table('contacts as c')
        ->select(
            DB::raw('SUM(tr.final_total) AS total_customer'),
            DB::raw('COUNT(c.id) AS customercount'),
            DB::raw('COUNT(c.id) AS average')
        )
        ->whereBetween('tr.transaction_date', [$date_debut,  $date_fin])
        ->groupBy('c.id')
        ->join('transactions as tr', 'tr.contact_id', '=', 'c.id')
        ->get()->toArray();

A: I think this is what you want:
$customers_trans = DB::table('contacts as c')
    ->select(
        DB::raw('SUM(tr.final_total) AS total_customer'),
        DB::raw('COUNT(*) AS customer_count'),
        DB::raw('AVG(tr.final_total) AS average')
    )
    ->join('transactions as tr', 'tr.contact_id', '=', 'c.id')
    ->whereBetween('tr.transaction_date', [$date_debut,  $date_fin])
    ->groupByRaw('HOUR(tr.transaction_date)')
    ->get()
    ->toArray();


text:
Q: Multi category database schema with repeated data Here's the data involved,

Here's the schema I have come up with
Scope
id
name (example : regional ...)
Category
id,
name (example : resources),
scope_id
SubCategory
id,
name (example : legal, sponsored ...),
category_id
The problem is, as you can see, there are a lot of repeated data as the same category appears under all scopes, same sub categories appear under all categories. Of course, there will a few unique values in the case but they are very few. Also, even though the name of the category/sub category is same they will be holding references to different set of data depending on their parent scope/category. This will be used in segregating the content and generating a menu to browse those contents. What I want to know is if this is a proper way to address this or there are better ways/schema anyone can suggest me?

A: Based on the limited information you've provided, this is what I'd do:
categories
    id                  unsigned int(P)
    name                varchar(15)

+----+-----------+
| id | name      |
+----+-----------+
|  1 | Assets    |
|  2 | Resources |
| .. | ......... |
+----+-----------+

categories_subcategories
    id                  unsigned int(P)
    category_id         unsigned int(F categories.id)
    subcategory_id      unsigned int(F subcategories.id)

+----+-------------+----------------+
| id | category_id | subcategory_id |
+----+-------------+----------------+
|  1 |           1 |              4 |
|  2 |           1 |              1 |
| .. | ........... | .............. |
+----+-------------+----------------+

levels
    id                  unsigned int(P)
    name                varchar(15)

+----+----------+
| id | name     |
+----+----------+
|  1 | National |
|  2 | Regional |
|  3 | Zonal    |
| .. | ........ |
+----+----------+

levels_categories
    id              unsigned int(P)
    level_id        unsigned int(F levels.id)
    category.id     unsigned int(F category.id)

+----+----------+-------------+
| id | level_id | category_id |
+----+----------+-------------+
|  1 |        1 |           1 |
|  2 |        1 |           2 |
| .. | ........ | ........... |
+----+----------+-------------+

subcategories
    id                  unsigned int(P)
    name                varchar(15)

+----+-------------+
| id | name        |
+----+-------------+
|  1 | Contributed |
|  2 | Financial   |
|  3 | Legal       |
|  4 | Sponsored   |
| .. | ........... |
+----+-------------+


text:
Q: PyAutoit : OSError: Cannot load AutoItX from path: C:\Users\User\AppData\Local\Temp\_MEI152482\autoit\lib\AutoItX3_x64.dll I been trying to compile this program for quite some time but can't seem to figure out what is going on. From just reading the error code I'm assuming pyinstaller cannot or does not know where the needed AutoitX3_64.dll file. I've read other questions but cant seem to find a detailed answer explain how to tell my installer where the files are located.
I've tried:
pyinstaller --onefile main.py (Fail)
pyinstaller -w --onefile --add-data C:\Users\User\AppData\Local\Programs\Python\Python310\Lib\site-packages\autoit\lib\AutoItX3_x64.dll;autoit\lib main.py (Fail)
I've also dumped autoit folder in my build / dist with no success.
Any help would be greatly apriciated!
[error1][error2]

A: After searching this site and countless others i managed to figure out how to fix the error:
OSError: Cannot load AutoItX from path:
C:\Users\myusername\AppData\Local\Temp\_MEI152482\autoit\lib\AutoItX3_x64.dll

The answer would be to make a spec file and tell it where the autoit files are located. Here is how!
When you run pyinstaller command it will automatically generate a filename.spec in your home dir. For example:
pyinstaller -w --onefile main.py

-w is no console --onefile is to compress all files into one executable. main.py is the file you are going to make into exe. Now you will see a filename.spec in your home dir. Edit that with the following datas and hiddenimports
datas=
[["C:\\Users\\myusername\\AppData\\Local\\Programs\\Python\\Python310\\Lib\\site-packages\\autoit\\lib\\AutoItX3_x64.dll", "autoit\\lib"]],

hiddenimports=["autoit.init", "autoit.autoit", "autoit.control", "autoit.process", "autoit.win" ],

Here is an example and don't forget to copy and paste the autoit\lib into your dist folder.


text:
Q: I have a plano convex lens and I want to increase the magnification I have a plano convex  lens and I want to increase the magnification but I cannot increase the focal length can I do this by increasing the curvature and dome height of the lens?

A: Increasing the curvature of the lens will decrease the focal length and increase the magnification. You would have to grind and polish it to a new shape.
It is hard to see how you would increase the thickness of a lens. If you did, you would find that it has a much smaller effect for most single element lenses, and none for a plano convex. Google the Lens Makers Equation for more. Here is the first result from a search I did. It gives
$$P = 1/f = (n-1)\left(\frac{1}{R1} - \frac{1}{R2} + \frac{(n-1)d}{R1R2}\right)$$
where
P is the power of the lens
f is the focal length
R1 and R2 are the radii of the two sides
d is the thickness
n is the index of refraction
For a plano-convex lens, $R2 = \infty$. So the equation reduces to
$$P = 1/f =(n-1)\left(\frac{1}{R1}\right)$$


text:
Q: how to show events in fullcalendar using PHP hello please this is my first time using Fullcalendar, i add some events and there are stocked in the database but i can't display them in my calendar.
please can some one help me to fix that problem. i read the documentation of the full calendar but i did not understand how to use it:
my calendar code :
<?php
require_once('bdd.php');

$sql = "SELECT id, title, start, end,  FROM reservation_client ";

$req = $bdd->prepare($sql);
$req->execute();

$events = $req->fetchAll();

?>

<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Bare - Start Bootstrap Template</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" >

    <link href='css/fullcalendar.css' rel='stylesheet' >

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Free Calendar

                        Menu

FullCalendar BS3 PHP MySQL

Complete with pre-defined file paths that you won't have to change!

            <form class="form-horizontal" method="POST" action="addEvent.php">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Ajouter un evenement

                    Title

                      <input type="text" name="title" class="form-control" id="title" placeholder="Title">

                     date debut

                      <input type="text" name="start" class="form-control" id="start" readonly>

                    date fin

                      <input type="text" name="end" class="form-control" id="end" readonly>

                  Clients

                      <select class="form-control" name="id_client">
                        <option>Selectionnez un client </option>

                           <?php
                            $req=$bdd->query('SELECT * FROM customers' )/*or die (print_r($bdd->errorinfo()))*/;
                                while ($donnees = $req->fetch()) {

                                echo'<option value='.$donnees['ID'].'>'.($donnees['NAME']) .'</option> '  ;
                                  }
                          ?>

                      </select>

                  Chambre

                      <select class="form-control" name="id_chambre">
                        <option>Selectionnez une chambre</option>

                           <?php
                            $req=$bdd->query('SELECT * FROM chambre' )/*or die (print_r($bdd->errorinfo()))*/;
                                while ($donnees = $req->fetch()) {

                                echo"<option value='".$donnees['id']."'>".($donnees['libelle']) ."</option> "  ;
                                  }
                          ?>

                      </select>

                <button type="button" class="btn btn-default" data-dismiss="modal">fermer</button>
                <button type="submit" class="btn btn-primary">enregistrer</button>

            </form>

            <form class="form-horizontal" method="POST" action="editEventTitle.php">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit Event

                    Title

                      <input type="text" name="title" class="form-control" id="title" placeholder="Title">

                            <input type="checkbox"  name="delete"> Delete event

                  <input type="hidden" name="id" class="form-control" id="id">

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>

            </form>

my add events code:
<?php

// Connexion à la base de données
require_once('bdd.php');
//echo $_POST['title'];
if (isset($_POST['title']) && isset($_POST['start']) && isset($_POST['end']) ){

    $title = $_POST['title'];
    $start = $_POST['start'];
    $end = $_POST['end'];

    $sql = "INSERT INTO reservation_client(title, start, end) values ('$title', '$start', '$end')";
    //$req = $bdd->prepare($sql);
    //$req->execute();

    echo $sql;

    $query = $bdd->prepare( $sql );
    if ($query == false) {
     print_r($bdd->errorInfo());
     die ('Erreur prepare');
    }
    $sth = $query->execute();
    if ($sth == false) {
     print_r($query->errorInfo());
     die ('Erreur execute');
    }

}
header('Location: '.$_SERVER['HTTP_REFERER']);

?>

A: Fix the select query issue. Remove the comma after end column, otherwise you will get an error 'An expression was expected.'
SELECT id, title, start, end FROM reservation_client

convert the events data into JSON formatted string using json_encode and use.
like.
events: <?php print json_encode($events);?>,


text:
Q: ThreadPool with MvvmCross I have this situation: a list with N events, where N can be big, like 100,200... So I want to be able to offer to the user a refreshButton, that should refresh all N events. For this, it would have to make a GET Request in server, passing the event's code for each one of the N events.
The problem is, the server is not mine, so i can't change it, the api only supports get one event at a time. So, if I make it synchronized, refresh a list of 200 events, would take forever. So I thought in a ThreadPool, that I could request T threads to make the request simultaneoulsy, and divide the time t for the T number of threads.
But, when I tried to do it in the PCL project (Core), i found out that a PCL can't use ThreadPool. What should I do in this case?
Thanks in regards,
Gabriel


text:
Q: Qt C++ QTcp как определить что приходит клиенту сообщение или картинка Разбираюсь с Tcp протоколом в Qt. Есть сервер он передаёт сообщение клиенту.
void Server::sendToClientMessage()
{
if (socket != NULL)
{
    // Заранее размер блока неизвестен, мы не можем записать данные сразу в сокет,
    // так как размер блока должен быть выслан в первую очередь
    QByteArray  arrBlock;
    QDataStream out(&arrBlock, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_7);
    // Записываем все данные блока, размер 0
    out << quint16(0);
    out << QTime::currentTime() << ui->lineEdit_message->text();
    // Вывод вашего сообщения в историю сообщений
    ui->textEdit_allMessage->append(QTime::currentTime().toString() + " - Ваше сообщение: " + ui->lineEdit_message->text());
    // Перемещение указателя на начало блока
    out.device()->seek(0);
    // Вычисление размера блока arrSize уменьшенный на sizeof(quint16)
    // запись в поток out с текущей позиции, которая уже перемещена в начало блока
    out << quint16(arrBlock.size() - sizeof(quint16));

    // Созданный блок записывается в сокет
    socket->write(arrBlock);
    ui->lineEdit_message->clear();
}
else
{
    return;
}
}

Он же отправляет картинку клиенту по кнопке pushButton
void Server::transferImage()
{
QBuffer buffer;
QImageWriter writer(&buffer, "jpg");
writer.write(imageJPEG);

QByteArray barr;
QDataStream stream(&barr, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_5_7);
stream << (quint32)buffer.size();
barr.append(buffer.data());

socket->write(barr);
}

Как на стороне клиента определить, что приходит? сообщение или картинка?
Тут есть 2 коннекта
// Передача сообщения клиенту
connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
// Передача картинки клиенту
connect(socket, SIGNAL(readyRead()), this, SLOT(receivingImage()));

Сейчас отрабатывают 2 метода и это не правильно. Если мы передаем картинку он пытается отобразить и сообщение тоже, хотя мы его не передавали и наоборот. Из за этого ни один из методов не работает. Если же закомментировать один из коннектов и соответствующий слот то всё норм. Т.е либо сообщение либо картинка. Можно было бы запихнуть в один метод и внутри уже разбирать, но как внутри метода определять картинка там или только сообщение?
Метод подключения к серверу
void Client::connectedToServer()
{
// Если клиент уже подключен
if(socket != NULL)
{
    // Отключить клиента клиента
    disconnectFromServer();
}
else
{
    socket = new QTcpSocket(this);
    // Подключение к серверу
    socket->connectToHost(ui->lineEdit_ipAddress->text(),ui->spinBox_port->value());

    // оповестить пользователя что он подключён
    connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
    //connect(sock)
    // Возможные ошибки при подключении
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError)));

    // Передача сообщения клиенту
    connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
    // Передача картинки клиенту
    connect(socket, SIGNAL(readyRead()), this, SLOT(receivingImage()));

}
}

Получение сообщения
void Client::slotReadyRead()
{
// Считывание в двоичный поток данных, объект класса socket унасследованный от QIODevice
QDataStream in(socket);

// Так как формат постоянно изменяется,  и в разных версиях он может работать по разному.
// Установка формата обмена данных на версию Qt 5.7.
in.setVersion(QDataStream::Qt_5_7);

// Не все высланные клиентом данные могут прийти одновременно.
// Сервер должен уметь получать, как весь блок целиком, так и только часть блока,
// а так же и все блоки сразу.
for (;;)
{
    // Размер блока заранее неизвестен, сравниваем с нулём.
    if (nextBlockSize == 0)
    {
        // Если пришло меньше 2-х байт, ждём пока будет 2 байта.
        // Первые 2 байта это размер блока
        if (socket->bytesAvailable() < (int)sizeof(quint16))
        {
            break;
        }
        // Блок получен целиком. Считываем размер блока (2 байта)
        in >> nextBlockSize;
    }
    // Ждём пока блок придёт полностью
    if (socket->bytesAvailable() < nextBlockSize)
    {
        break;
    }

    // Вот тут можно было бы определять картинка здесь или сообщение, но как?

    // Определяем дату и строку, они в сообщении сервера
    QTime   time;
    QString str;
    // Считывание данных из потока в переменные
    in >> time >> str;

    ui->textEdit_allMessage->append(time.toString() + " - Сообщение от сервера: " + str);

    // Каждый раз обнуляем блок, для принятия следующего
    nextBlockSize = 0;
}
}

Получение картинки
void Client::receivingImage()
{
if (nextBlockSize == 0)
{
    QDataStream stream(socket);

    if (socket->bytesAvailable() < sizeof(quint32))
        return;

    stream >> nextBlockSize;
}

if (nextBlockSize > socket->bytesAvailable())
    return;

QByteArray barr = socket->read(nextBlockSize);
QBuffer buffer(&barr);
buffer.open(QIODevice::ReadOnly);

QImageReader reader(&buffer, "jpg");
receivingImageJPG = reader.read();

if (!receivingImageJPG.isNull())
{
    ui->label_reciveImageJPG->setPixmap(QPixmap::fromImage(receivingImageJPG).scaled(ui->label_reciveImageJPG->size(),
                                                                                Qt::KeepAspectRatio,
                                                                                Qt::SmoothTransformation));

    nextBlockSize = 0;
}
else
{
    ui->label_reciveImageJPG->setText("Возникла ошибка при передачи картинки.");
}
}

Вот что то типо такого нужно. Но тут жесткое ограничение если приходит более 10 килобайт считаем, что это картинка и отображаем. Если меньше, то сообщение. Как заранее распознать что хранится в QDataStream сообщение или картинка?
void Client::slotReadyRead()
{
// Считывание в двоичный поток данных, объект класса socket унасследованный от QIODevice
QDataStream in(socket);

// Так как формат постоянно изменяется,  и в разных версиях он может работать по разному.
// Установка формата обмена данных на версию Qt 5.7.
in.setVersion(QDataStream::Qt_5_7);

// Не все высланные клиентом данные могут прийти одновременно.
// Сервер должен уметь получать, как весь блок целиком, так и только часть блока,
// а так же и все блоки сразу.
for (;;)
{
    // Размер блока заранее неизвестен, сравниваем с нулём.
    if (nextBlockSize == 0)
    {
        // Если пришло меньше 2-х байт, ждём пока будет 2 байта.
        // Первые 2 байта это размер блока
        if (socket->bytesAvailable() < (int)sizeof(quint64))
        {
            break;
        }
        // Блок получен целиком. Считываем размер блока (2 байта)
        in >> nextBlockSize;
    }
    // Ждём пока блок придёт полностью
    if (socket->bytesAvailable() < nextBlockSize)
    {
        break;
    }

    if (nextBlockSize < 10000)
    {
        // Определяем дату и строку, они в сообщении сервера
        QTime   time;
        QString str;
        // Считывание данных из потока в переменные
        in >> time >> str;

        ui->textEdit_allMessage->append(time.toString() + " - Сообщение от сервера: " + str);
    }
    else
    {

        QByteArray barr = socket->read(nextBlockSize);
        QBuffer buffer(&barr);
        buffer.open(QIODevice::ReadOnly);

        QImageReader reader(&buffer, "jpg");
        receivingImageJPG = reader.read();

        if (!receivingImageJPG.isNull())
        {
            ui->label_reciveImageJPG->setPixmap(QPixmap::fromImage(receivingImageJPG).scaled(ui->label_reciveImageJPG->size(),
                                                                                Qt::KeepAspectRatio,
                                                                                Qt::SmoothTransformation));

        }
        else
        {
            ui->label_reciveImageJPG->setText("Возникла ошибка при передачи картинки.");
        }
    }

    // Каждый раз обнуляем блок, для принятия следующего
    nextBlockSize = 0;
}
}

A: Словом, безотносительно к конкретно Qt... При передаче по сети - примерно как с безымянным файлом: есть просто поток данных. Как вы узнаете, что именно в нем - JPEG или "Война и мир"? :) Например, по начальным байтам ("заголовку") файла.
Так и здесь - используйте свой протокол. Самое простое - пересылайте перед отправлением информации информацию о том, что сейчас будет идти. Как в старой комедии - "Возьми трубку, я буду говорить с тобой по телефону!"
Можете даже предварять информацией не только о типе, но и, например, о размере передаваемых данных или еще чем-то - тут уж как ваша фантазия и ваши потребности скажут.
Получив заголовок, вы будете точно знать, что получаете дальше.

A: Если между передающей и принимающей стороной нет какого-либо соглашения о характере содержимого на текущую сессию, то можно отправлять все возможные варианты сразу. Это как коробка конфет. Она может быть полной, а может быть частично дегустирована. Вроде все формальности соблюдены: коробка, ленточка с бантиком. Но не оставляет чувство жёсткого... недоумения при непосредственном изучении содержимого.
Объявление класса подарка:
class Gift {
    friend QDataStream &operator<<(QDataStream &stream, const Gift &gift);
    friend QDataStream &operator>>(QDataStream &stream, Gift &gift);

    public:
        Gift() {}
        virtual ~Gift() {}

        QString text() const {return _txt}
        void setText(const QString &txt) {_txt = txt;}

        QImage image() const {return _img;}
        void setImage(const QImage &img) {_img = img;}

    private:
        QString _txt;
        QImage  _img;

};

Q_DECLARE_METATYPE(Gift)

Где-нибудь в реализации класса подарка:
qRegisterMetaType<Gift>("Gift");
qRegisterMetaTypeStreamOperators<Gift>("Gift");

QDataStream &operator<<(QDataStream &stream, const Gift &gift) {
    return stream << gift._txt << gift._img;
}

QDataStream &operator>>(QDataStream &stream, Gift &gift) {
    stream >> gift._txt >> gift._img;
    return stream;
}

Далее, остаётся лишь оформить, собственно, передачу (_socket - объект класса наследника QAbstractSocket):
QByteArray SocketManager::compressData(const QVariant &var) {
    QByteArray data;

    QDataStream stream(&data, QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);
    stream << var;

    return qCompress(data, 9);
}

QVariant SocketManager::uncompressData(const QByteArray &data) {
    QByteArray raw_data = qUncompress(data);
    if(raw_data.isEmpty()) return QVariant();

    QDataStream stream(raw_data);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);

    QVariant var;
    stream >> var;

    return var;
}

void SocketManager::sendMessage(const QVariant &var) {
    QByteArray data;

    QDataStream stream(&data, QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);
    stream << compressData(var);

    // Вставлять в поток размер блока данных необходимости нет
    // в том случае, если используется Qt 5.7 и выше.

    _socket->write(data);
}

void SocketManager::onReadyRead() {
    QDataStream stream(_socket);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);

    while(_socket->bytesAvailable()) {
        stream.startTransaction();

        QByteArray data;
        stream >> data;

        // Собственно проверка данных принятого размера
        // для Qt 5.7 и выше.
        if(stream.commitTransaction() == false) return;

        QVariant var = uncompressData(data);

        if(var.isValid() && var.canConvert<Gift>()) {
            // Время открывать шампанское.
            Gift gift = var.value<Gift>();
        }
    }
}

Объект класса подарка можно наполнить всеми типами данных, можно частично, а можно и вообще не заполнять, оставив пустым, так сказать, для большей радости юбиляра:
Gift gift;
gift.setText("Безвозмездно");
gift.setImage(QImage(":/gift.jpg"));

А отправлять можно так:
manager->sendMessage(QVariant::fromValue<Gift>(gift));


text:
Q: How to do injection in Angular Module imports I'm importing a configurable module from an external library like this:
@NgModule({
  imports: [ThirdPartyModule.forRoot(MY_CONFIG)]
})

Problem is that MY_CONFIG is not static and makes use of a service in order to define its value, so I would use a factory to build up the module configuration like this:
@Injectable
class ConfigFactory {
  constructor(private configService: ConfigService){}

  public config(){
    return {
      someconfigvalue: this.configService.buildSomeConfigValue()
    };
  }
}

In this case I should rewrite the import like
@NgModule({
  imports: [ThirdPartyModule.forRoot(configFactory.config())]
})

But I don't know how to inject the config factory.
I know that if I had this situation with a provider I could use a factory provider.
Is there something similar for the module imports? Can I use a factory for importing a module? Or is there another solution to this problem?
P.S. please note that I cannot change the code for the ThirdPartyModule.


text:
Q: How to add json object as a type for attributes in sails-mongo Document.js
module.exports = {

  attributes: {

    type: {
        type: 'string'
    },
    createdBy: {
        model: 'User',
        required: true
    },
    body: {
        type: 'string'
    },
    comments: {
        model: 'Comments'
    },
    metaInfo: {
        type: 'json'
    }

 }

};
I would like to know if there is any way that I can write a model like the one given above, so that, I can add a json object to metaInfo which contains a name-value pair.
Eg:
json:
{  name: 'Project',  value: 'MyFirstProject'}
Is this possible through waterline?
Thanks in advance.

A: I believe the comment answers your question. If you need any further help, you can refer the answers in this issue raised in Sails Github page: JSON Array of Strings


text:
Q: Can i replace the PFsence captive portal login form with a custom form i have tried to replace the PFsence captive portal with a custom form but couldnt find the captive portal folder in PFsense
I combined all the login form into a php file and was supposed to place it in a certain folder in the PFsence root folder


text:
Q: python data analysis, difficulty understanding cookbook code I'm learning to use python for data analysis, etc. and I am a little confused about what is going on in this code from the scipy cookbook.
When the cookbook describes the integration and then plotting process, via matplotlib, it has first:
t = linspace(0, 15, 1000)
X0 = array([10,5])
X = scipy.integrate.odeint(dX_dt, X0, t)
rabbits, foxes = X.T

What does this code do?
rabbits, foxes = X.T

Specifically, what does X.T do?

A: X.T is the transpose of X.  So, in that line, X must be an array with shape (N,2).  When you transpose it you get an array of shape (2,N) which can be unpacked.
Consider:
>>> import numpy as np
>>> a = np.arange(10).reshape((5,2))
>>> a
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> B,C = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> B,C = a.T
>>> B
array([0, 2, 4, 6, 8])
>>> C
array([1, 3, 5, 7, 9])

Also note that wherever possible, the transpose will return a new view (the data won't be copied), so this is a very efficient operation.

A: T stands for transpose. So X is aligned such that rabbits gets assigned to the first element and foxes to the second. These are arrays (equivalent to matrices in linear algebra) not lists, so that alignment does matter.


text:
Q: Comparing arrays in a function My function countCopies doesn't work even though it gets the right inputs. All it should do is taking an array of integers as an input and then searching through this array for duplicates of the second input x.
int main() {
    char intArray[100]; //The integer array can only hold 100 integers
    int i, x, j;
    printf("Please enter a couple of integers and when you're done enter end. ");

    i = 0;
    while (scanf("%d", &intArray[i++]) == 1)
        /*empty loop*/;

    scanf("%*s");

    printf("Enter x:");
    scanf("%d", &x);

    printf("Copies = %d\n", countCopies(intArray, i, x));
}

int countCopies(int a[], int n, int x) {
    int count = 0;
    int j = 0;
    for (j = 0; j < n - 1; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

A: The for loop is incorrect:  you should change the test to j < n.
The idiomatic for loop in C: for (j = 0; j < n; j++) ... iterates exactly n times, j taking values 0 to n-1 inclusively, which are correspond to exactly all valid positions in an array of n elements.
Note that the array has the wrong element type: it should be int, not char. You should also check for array bounds in the first loop and for conversion success of the last scanf.
Here is a corrected version:
#include <stdio.h>

int countCopies(int a[], int n, int x);

int main(void) {
    int intArray[100]; //The integer array can only hold 100 integers
    int i, x;

    printf("Please enter a series of integers, end the list with the word end.\n");

    for (i = 0; i < sizeof(intArray) / sizeof(*intArray); i++) {
        if (scanf("%d", &intArray[i]) != 1)
            break;
    }
    if (scanf("%d", &x) == 1) {
        printf("too many numbers\n");
        return 1;
    }
    scanf("%*s");  /* skip the end word.  Note that any word is OK */

    printf("Enter x:");
    if (scanf("%d", &x) == 1) {
        printf("Copies = %d\n", countCopies(intArray, i, x));
    }
    return 0;
}

int countCopies(int a[], int n, int x) {
    int j, count = 0;

    for (j = 0; j < n; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

A: To expand on chqrlie's answer,
The code for (i = 0; i < n; i++) {/* do stuff */} executes in the following order:

*

*The variable i is set to zero.

*The conditional i < n is tested. If true, the code in /* do stuff */ is executed, otherwise, the loop is exited.

*The increment i++ is applied.

*Go back to 2.

That means that on the loop iteration when i gets incremented to n, the for loop breaks before the code inside the loop gets executed, so if you're accessing an array with n elements, the last element that gets accessed has the index n - 1. Hence the C loop paradigm that chqrlie mentioned.


text:
Q: Model validation failing for valid form submission I have a table named EFT_BANK_INFO. Due to reasons I won't get into, I had to split up the form into 2 separate forms. This means that half the fields for this table are edited from one view, and half from another.
Everything was working great, until I added form validation to the tables model .cs file. While the codes syntax is correct, all submissions from both forms are labeled as being invalid, preventing me from updating, deleting, and adding rows to the table. It is marked as invalid due to the separation; i.e; I have Required fields in the model for the second portion of the fields, so when I submit data for one half of the fields, the other fields not part of the view/submission are marked as being invalid because no data was received for them.
A potential workaround would be to artificially satisfy the validation for the unwanted fields by inserting values for those fields in the C# controller during the create process. I could also do this for the edit process.
I was wondering if there's a better alternative, given I must have it structured this way. I'd like it to only validate the relevant fields in the model, and not validate all of them for the submission, which is causing the error. No code is really necessary since I have no bugs and know what is wrong, this is more of a theory/solution identification problem. Thanks.

A: Use ViewModels.

A view model represents only the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdowns).

See the accepted answer on the question linked above.


text:
Q: Let the gcc compile syscalls in "int 0x80" way? code here:
void main()
{
    _exit(0);
}

By disassembling the main section:
 80483d4:   55                      push   %ebp
 80483d5:   89 e5                   mov    %esp,%ebp
 80483d7:   83 e4 f0                and    $0xfffffff0,%esp
 80483da:   83 ec 10                sub    $0x10,%esp
 80483dd:   c7 04 24 00 00 00 00    movl   $0x0,(%esp)
 80483e4:   e8 17 ff ff ff          call   8048300 <_exit@plt>

As I know, the way to make syscalls is using "int 0x80", but I can just find "call 8048300 exit@plt" here, so how can I change the gcc to let it compile syscalls in "int 0x80" way(I need my program call syscall in this way)?

A: You should compile with gcc -Wall (and also perhaps the -g flag).
This will give you more warnings, and will pin-point some easy mistakes, like the lack of appropriate #include
The exit(3) function is a library function (making atexit possible). The corresponding syscall is _exit(2), but on recent Linux exit is calling exit_group(2). So your example misses an #include <stdlib.h>
Current Linux implementations often do not use int 0x80 but go thru the VDSO or at least use SYSENTER or SYSCALL machine instructions. YMMV.
You could, as Jeremy answered, use asm ; (you might define your own headers for all the syscalls you are using, and having these syscalls be static inline functions doing some asm) beware that for other syscalls, you want to catch their failure and the errno error code.
Why are you asking?.... The libc (and its startup routines crt0.o ...) is doing complex tricks to call main...
See also this answer

A: For 32-bit
asm( "int $0x80" :: "a" (1), "b" (0) );

for 64-bit
asm( "syscall" :: "a" (60), "D" (0) );

You might also need this if you have declared your exit function with attribute noreturn.
__builtin_unreachable();

A: The system calls are wrapped by glibc, which should use whatever the underlying kernel uses. Linux switched away from the int 0x80 mechanism for performance a while back...
Why do you want to do system calls in an outdated way?


text:
Q: fadeIn() starts over after resizing browser I was going to give 3 backgrounds to a browser-sized div rotating it with jQuery's fading effect. The main problem is whenever I resize the browser, the effect starts over, and I want it to continue wherever it is at the exact moment. I am using Chrome 37. I would appreciate any help or suggestions.
HTML

jQuery
$(window).load(function(){
$('div.wrapinside').hide();
var dg_H = $(window).height();
var dg_W = $(window).width();

$('.wrap').css({'height':dg_H,'width':dg_W});

function anim() {
    $(".wrap div.wrapinside").first().appendTo('.wrap').fadeOut(3000);
    $(".wrap div").first().fadeIn(3000);
    setTimeout(anim, 6000);
}
anim();})
$(window).resize(function(){window.location.href=window.location.href})

CSS
.wrap {
   position: fixed;
   z-index: -1;
   top: 0;
   left: 0;
   background: #000;
}

.wrap div.wrapinside {
   position: absolute;
   top: 0;
   display: none;
   width: 100%;
   height: 100%;
   z-index: -1;
   background-size: cover;
}

A: First of all you could add this to your div.wrapinside css:
display: none;

After that you won't need this anymore:
$('div.wrapinside').hide();

Maybe this link could help you, too.
Change background-image of a div with fade effect every 10 seconds with jquery
The problem is, that you are updating the value of some variables, but not the size of the div itself, because this line:
$('.wrap').css({'height':dg_H,'width':dg_W});

is only execute once.
Try this:
var dg_H;
var dg_W;
$(window).load(function(){
dg_H = $(window).height();
dg_W = $(window).width();

$('.wrap').css({'height':dg_H,'width':dg_W});

function anim() {
    $(".wrap div.wrapinside").first().appendTo('.wrap').fadeOut(3000);
    $(".wrap div").first().fadeIn(3000);
    setTimeout(anim, 6000);
}
anim();})
$(window).resize(function(){
dg_H = $(window).height();
dg_W = $(window).width();

$('.wrap').css({'height':dg_H,'width':dg_W});
})


text:
Q: Translate and scale animation I have a wpf application and image inside a canvas. The image is placed in 0,0.
I need to animate the image moving from 0,0 to 500,200 and in the same time growing (I like to make an effect like coming from far to near).
If I do this:
        TranslateTransform ttx = new TranslateTransform();
        TranslateTransform tty = new TranslateTransform();

        DoubleAnimationUsingKeyFrames dax = new DoubleAnimationUsingKeyFrames();
        dax.KeyFrames.Add(new LinearDoubleKeyFrame(500, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))));

        DoubleAnimationUsingKeyFrames day = new DoubleAnimationUsingKeyFrames();
        day.KeyFrames.Add(new LinearDoubleKeyFrame(200, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))));

        TransformGroup tg = new TransformGroup();
        tg.Children.Add(ttx);
        tg.Children.Add(tty);

        krug.RenderTransform = tg;

        ttx.BeginAnimation(TranslateTransform.XProperty, dax);
        tty.BeginAnimation(TranslateTransform.YProperty, day);

And this works fine. It animates the translation of the image "krug" from 0,0 to 500,200.
But when I add logic for zooming the image while translating like this:
        ScaleTransform zoom = new ScaleTransform();
        DoubleAnimationUsingKeyFrames zoomTimeline = new DoubleAnimationUsingKeyFrames();
        zoomTimeline.KeyFrames.Add(new LinearDoubleKeyFrame(2, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))));
        tg.Children.Add(zoom);
        zoom.BeginAnimation(ScaleTransform.ScaleXProperty, zoomTimeline);
        zoom.BeginAnimation(ScaleTransform.ScaleYProperty, zoomTimeline);

Then the image does not stop to 500, 200 but goes more far. If the zoom factor is bigger, the translation goes more future. How can I control the animation to stop at 500,200 ?

A: The problem you run into when combining scale and translate transforms is that it will scale the translate transform from the point of origin(ScaleTransform.CenterX, ScaleTransform.CenterY)
For example, if you want to slide it to the right by 50, and double it's scale, it will actually move a net distance of 100.
Try animating the ScaleTransform.CenterX and ScaleTransform.CenterY to match your translate transform. I believe that would let you scale on the fly like you want.

A: Put the animations in a single storyboard and set the duration of the storyboard to control the length of the animations.
Then start the storyboard.

A: I found a solution. I created separate user control that only does ScaleTransform. Then I apply  TranslateTransform on the user control.


text:
Q: CSS Position:Overflow issue I am trying to get the picture in the 2nd div to overflow the parent div. I have played around with different position attributes and overflow:visible, but none seem to solve my issue.
How can I solve this?
Thanks
EDIT: Okay scrap that first code - here is the actual code:
I want to get the slider to stretch across and overflow the sp_block
EDIT 2: I must not edit the first 4 divs by the way.

            <link type="text/css" rel="stylesheet" href="http://www.dedicatedrejects.com/icsa/test/slider/allinone_contentSlider.css"></link>
            <link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Cabin"></link>

                        <canvas class="mycanvas" width="36" height="36"></canvas>

A: As it is, the image will appear outside the parent div, for no overflow has been specified. If you want it to hide inside the parent div, just add to the div:
{
    overflow: hidden;
}

http://jsfiddle.net/Cn3n3/2/

A: The inline width and height attributes (within the  tag) shouldn't have the px unit in them. Only specify the number of pixels without a unit. You shouldn't need to specify overflow, since the defaults will suit your needs in this case.
See example: http://jsfiddle.net/orvn/ansBc/1/

#container { width: 300px; }
#container > img { display: block; }

Additionally, you don't need to wrap the image in a div here, you can apply display: block; to have it behave the way a div would.

A: Not sure what you're trying to achieve but the parent div needs the overflow tag.
HTML

image

CSS
.parent {
width:700px;
height:200px;
overflow:visible;
background-color:green;
}

.child {
    width:1000px;
    height:100px;
    background-color:red;
}

Here is a demo jsfiddel
I made the parent div background height longer so you can see the overflow. You can also replace the background color with an image. Replace the class (parent & Child) and write this inline but I advise against that.


text:
Q: Adding total numbers(Grand Total) in pivot chart I need help in adding the total numbers on pivot table as in the picture below. Any kind of help would be highly appreciated.

I have tried everything but was not able to make it reflected on the chart.
Regards

A: Only way that I can think of is not very elegant but it should do what you want. Create a formula in a cell that gets data you need from the pivot table, it should be ok to just write in "=" and click on the cell and Excel should write down the GETPIVOTDATA formula for you. After that you just create a text box and write "=(adress of the cell) in the formula bar while you have the text box selected.
Hope that helps


text:
Q: What's the .NET equivalent of link.exe's /RELEASE switch? When linking a native image, you specify /RELEASE so that link.exe stamps a checksum on the binary, so windbg doesn't complain about
*** WARNING: Unable to verify checksum for foo.exe

How do I do that for a .NET program? I've looked at the options in CSC.EXE, AL.EXE, but can't find anything like this.

A: You can use editbin.exe in a post-build event to achieve the same.  Check this answer for an example event, use /RELEASE instead.
It is only required for device drivers, so this doesn't matter for managed code.


text:
Q: InnerHTML does not outputs anchor elements but instead outputs current pg url. why? In the following code, links_container.innerHTML = links; outputs http://localhost/pagination/js-pagination.html# instead of Page 1.
HTML

JS
function createLinks() {
        var links_container = document.getElementsByClassName('pagination-links')[0];

for(i=1; i<=5; i++){
    var link = document.createElement('a');
    var txt = document.createTextNode('Page ' + i + " ");
    link.setAttribute("href", "#");
    link.appendChild(txt);
    links_container.innerHTML = link;
  }
}

Can anybuddy explain. why

A: innerHTML is a string property and thus takes a string as value. Your link is an element object and because of this it's implicitly converted to a string with its toString() method, which does indeed return the URL.
Here are two ways you can fix this:
Both of these solutions require you to clear the container before the for loop by running links_container.innerHTML = ''

*

*Append the element with links_container.appendChild(link)

*Use the outerHTML of the element object: links_container.innerHTML += link.outerHTML
The first option is the more appropriate one as it inserts the DOM element you created into the DOM directly. The second option converts your DOM element to a string and then forces the browser to create a new DOM element from that HTML. If there had been any event listeners added to the element they would've been lost.

A: Instead of setting innerHTML try calling appendChild. The link object is an element not an HTML string.
i.e. try changing:
links_container.innerHTML = links;

to
links_container.appendChild(link);

function createLinks() {
  var links_container = document.getElementsByClassName('pagination-links')[0];

  // clear out previous html
  links_container.innerHTML = "";

  for (i = 1; i <= 5; i++) {
    var link = document.createElement('a');
    var txt = document.createTextNode('Page ' + i + " ");
    link.setAttribute("href", "#");
    link.appendChild(txt);
    // append link to container
    links_container.appendChild(link);
  }
}

createLinks();

Solution using innerHTML:
links_container.innerHTML += link.outerHTML;

or
links_container.innerHTML += "Page " + i + " "

function createLinks() {
  var links_container = document.getElementsByClassName('pagination-links')[0];

  // clear out previous html
  links_container.innerHTML = "";

  for (i = 1; i <= 5; i++) {
    var link = document.createElement('a');
    var txt = document.createTextNode('Page ' + i + " ");
    link.setAttribute("href", "#");
    link.appendChild(txt);
    // add link
    links_container.innerHTML += link.outerHTML;

    // or you can use this instead of the above code
    //links_container.innerHTML += "Page " + i + " ";
  }
}

createLinks();

A: Replace this line
links_container.innerHTML = links;

with
links_container.innerHTML = link;

as you do not have any links variable there.