Why are these values showing null?

Question: I have three tables. [C# windows form, ms sql server]
CustomerTable:
------Id
------Name
DressTypeTable
------DressTypeId
------Name
MeasurementDetailsTable
------Id
------DressTypeId
------Details
------CustomerId
I want to retrieve [ using customerId]
Customer Name
DressType Name
Measurement Details.
I'm using this query below:
 _aMeasurementDetails = new MeasurementDetails();
        _connection.Open();
        string query = string.Format("SELECT * FROM MeasurementDetailsTable where CustomerId='{0}'", id);
        _command = new SqlCommand(query, _connection);
        SqlDataReader aReader = _command.ExecuteReader();

        if (aReader.HasRows)
        {
            while (aReader.Read())
            {
                _aMeasurementDetails.MeasurementDetailsId = (int)aReader[0];
                _aMeasurementDetails.DressType.DressTypeId = (int)aReader[1];
                _aMeasurementDetails.Details = (string)aReader[2];
                _aMeasurementDetails.Customer.CustomerId = (int)aReader[3];
            }
        }
        _connection.Close();
        return _aMeasurementDetails;

When I want to retrieve value using CustomerId it shows "Object reference set to an instance of an object". It can not retrieve data from
 _aMeasurementDetails.DressType.DressTypeId = (int)aReader[1];

and
  _aMeasurementDetails.Customer.CustomerId = (int)aReader[3];

But when I'm executing the query in the ms sql server, it can retrieve the data! How to solve this problem?
Here is my MeasurementDetails Model Class
 public int MeasurementDetailsId { get; set; }
    public String Details { get; set; }
    public DressType DressType { get; set; }

    public Customer Customer { get; set; }

Here is my MeasurementDetails Manager Class
 private MeasurementDetailsGateway aMeasurementDetailsGateway;
    public bool SaveMeasurementDetails(Model.MeasurementDetails aMeasurementDetails)
    {
        aMeasurementDetailsGateway = new MeasurementDetailsGateway();
        return aMeasurementDetailsGateway.SaveMeasurementDetails(aMeasurementDetails);
    }

    public Model.MeasurementDetails GetMeasurementDetailsUsingCustomerInfo(int id)
    {
        aMeasurementDetailsGateway = new MeasurementDetailsGateway();
        return aMeasurementDetailsGateway.GetMeasurementDetailsUsingCustomerInfo(id);
    }

Here is my MeasurementDetails Gateway class
private SqlConnection _connection;
    private SqlCommand _command;
    private MeasurementDetails _aMeasurementDetails;

    public MeasurementDetailsGateway()
    {
        _connection = new SqlConnection();
        _connection.ConnectionString = ConfigurationManager.ConnectionStrings["TailorShopDB"].ConnectionString;
    }
    public bool SaveMeasurementDetails(Model.MeasurementDetails aMeasurementDetails)
    {
        _connection.Open();
        string query = string.Format("INSERT INTO MeasurementDetailsTable values ('{0}','{1}', '{2}')",
            aMeasurementDetails.DressType.DressTypeId, aMeasurementDetails.Details, aMeasurementDetails.Customer.CustomerId);

        _command = new SqlCommand(query, _connection);
        int affectedRows = _command.ExecuteNonQuery();
        _connection.Close();
        if (affectedRows > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public Model.MeasurementDetails GetMeasurementDetailsUsingCustomerInfo(int id)
    {

        _aMeasurementDetails = new MeasurementDetails();
        _connection.Open();
        string query = string.Format("SELECT * FROM MeasurementDetailsTable where CustomerId='{0}'", id);
        _command = new SqlCommand(query, _connection);
        SqlDataReader aReader = _command.ExecuteReader();

        if (aReader.HasRows)
        {
            while (aReader.Read())
            {
                _aMeasurementDetails.MeasurementDetailsId = (int)aReader[0];
                _aMeasurementDetails.DressType.DressTypeId = (int)aReader["DressTypeId"];
                _aMeasurementDetails.Details = (string)aReader[2];
                _aMeasurementDetails.Customer.CustomerId = (int)aReader["CustomerId"];
            }
        }
        _connection.Close();
        return _aMeasurementDetails;
    }

Comment: Are DressType and Customer and Details instantiated when you instantiate a new object of MeasurementDetails?
Comment: By the way: please use parameters in your query. Do not build the value into the string - that will lead to "sql injection" exploits.
Comment: Did you debug and see what is the exact query being generated, and then run that on server?
Comment: For starters... your reader, you should probably use the name of the field, not just the index. That may help you detect a field you are missing. You could be off
Comment: Put your breakpoint on   if (aReader.HasRows) and see if it even HAS ROWS. If it doesnt than you are either not connecting to the right SQL server or you are not querying exactly the same as MS_SQL
Comment: @shree.pat18 Yes, I debugged. I execute the query (in the ms sql server ) I got from debug, and it works perfect.
Comment: @logixologist Has Rows returns true
Comment: @AllanS.Hansen I'm not using _aDressType.DressTypeId / _aCustomer.CustomerId. So, if I instantiate those, those will be unreachable code, right? As I'm using _aMeasurementDetails.DressType.DressTypeId and _aMeasurementDetails.Customer.CustomerId. and yes, I've instantiated MeasurementDetails
Comment: Please show your MeasurementDetails class. 100% sure that @AllanS.Hansen is right.
Comment: @HansKesting You are right. I will use parameters in my query.
Comment: You are using a `while` loop to write to a single object. This seems like a mismatch to me. (OK, when you query by ID, you probably get at most a single record - so not a big problem in this case)
Comment: please add **relevant code**! The `Gateway` class is redundant information, because you've already posted the faulting code. Also, you still haven't posted the `MeasurementDetails` class. Sure, you posted the Properties, but if the constructor isn't doing `DressType = new DressType();` you'll won't be able to access anything *in* DressType property (which is what Allan S. Hansen asked about) because it will be `null`.
Comment: @HansKesting Oh! There will be several rows for the same customer.
Comment: @Default I've posted MeasurementDetails (Model) class. Isn't it MeasurementDetails class? I've posted again the full class to make sure that I've instantiated the MeasurementDetails class in the gateway class too.
Comment: Well as I said @AllanS.Hansen is right. Create DressType, Customer instances in MeasurementDetails constructor or before you trying to access those type properties.
Comment: @Reniuz in MeasurementDetails, I've included public DressType DressType {get; set;} and public Customer Customer {get; set;}. Why should I use them in the constructor? Sorry I don't understand this part. Can you show me how to?
Comment: @mmahbub please post full class, or at least the constructor. If no constructor exists, see if it helps by adding one and doing `DressType = new DressType(); Customer = new Customer();`.
Comment: @Default I have posted the full class! Where should I use DressType = new DressType();? Customer = new Customer();? Sorry, I don't understand.
Comment: You should learn what is property, and what is reference types. Its basic things.
Comment: I rolled back your question. If you need to ask additional questions ask a new question. Don't add new questions to already established questions. It renders the current discussions and answers obsolete.
Answer: The problem you are having is that the class you are instantiating sets its properties to their respective default values. If you examine _aMeasurementDetails in the debugger after this line:
_aMeasurementDetails = new MeasurementDetails();

You will see that DressType and Customer are null.
Since the default value for DressType and Customer is null you cannot access their respective properties. You have to instantiate these properties before accessing them, which can be done in some different ways.
Via constructor:
public class MeasurementDetails{
    ....
    public MeasurementDetails(){
        Customer = new Customer();
        DressType = new DressType();
        ....
    }
}

via the class that uses MeasurementDetails
_aMeasurementDetails = new MeasurementDetails();
_aMeasurementDetails.Customer = new Customer();
_aMeasurementDetails.DressType = new DressType();

or you can initialize it when you're fetching the values.
MeasurementDetails _aMeasurementDetails;

_aMeasurementDetails = new MeasurementDetails {
    MeasurementDetailsId = (int)aReader[0],
    DressType = { DressTypeId = (int)aReader[1] },
    Details = (string)aReader[2],
    Customer = { CustomerId = (int)aReader[3] }
}

Comment: It removes the errors now! Thanks. But How can I retrieve DressType Name and Customer Name? It does not retrieve them! Only dressTypeId can be retrieved! I've included the UI code above.
Comment: It's right there in your tables - `MeasurementDetailsTable` contains neither `DressTypeName` or `CustomerName`. You'd have to fetch them as well, from their respective tables.
Comment: But I'm using a foreign key here. How can I fetch them?! I'm saving DressType info into DressType table, Customer Info into Customer tables and made two foreign keys into MeasurementDetails Table.
Comment: I guess a join between the tables, and then modifying your `aReader[i]` indexes, something like. `select * from MeasurementDetailsTable join CustomerTable on MeasurementDetailsTable.CustomerId = Customer.Id join DressTypeTable on MeasurementDetailsTable.DressTypeId = DressType.Id`. If you require additional information about fetching related data I suggest asking a new question about that.

Why are these values showing null?


How to completely uninstall grafana?

Question: In Ubuntu 14.04, I installed grafana like below:
dpkg -i grafana_4.1.2-1486989747_amd64.deb

I am trying to uninstall it.
I tried:
sudo apt-get remove --auto-remove grafana
sudo apt-get purge --auto-remove grafana
sudo apt-get autoclean
sudo apt-get autoremove
locate grafana and manually remove files and folder

But still while reinstall it old templates is there.
While reinstall:
dpkg -i grafana_4.1.2-1486989747_amd64.deb
Selecting previously unselected package grafana.
(Reading database ... 68772 files and directories currently installed.)
 .................
 ......................

Comment: `sudo apt-get purge grafana` removes Grafana and all dependencies and temp files.
Answer: Uninstall just grafana:
sudo apt-get remove grafana

Uninstall grafana and its dependencies:
sudo apt-get remove --auto-remove grafana

For More details refer: http://installion.co.uk/ubuntu/xenial/universe/g/grafana/uninstall/index.html
Answer: I had this same issue. You need to use the commands you referenced, 'locate grafana' and remove every instance returned. You can use the python script I wrote as pasted below. I can't guarantee that its the best way to write but it gets the job done. This completely removes grafana.
import os
import time
import subprocess

print('------------------------------------')
print('...Removing Grafana...\n\n')
os.system("sudo apt-get remove --auto-remove grafana -y && sudo apt-get purge --auto-remove grafana -y")
time.sleep(1)
print('------------------------------------')
print('...Cleaning Up...\n\n')
os.system("sudo apt-get autoclean && sudo apt-get autoremove")
time.sleep(1)
print('------------------------------------')
print('...Checking Left-Overs...\n\n')
os.system("sudo updatedb")
time.sleep(1)

cmd = "sudo locate grafana"
openCmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fromCmd, stderr = openCmd.communicate()
cmds = fromCmd.split('\n')
print('------------------------------------')
print('...Removing Left-Overs...\n\n')

for cmd in cmds[:-1]:
    print('----------')
    print('Removing: '+str(cmd))
    os.system('sudo rm -r '+ str(cmd))

print('------------------------------------')
print('All Done!\n\n')

Answer: Error found in python program below:
Traceback (most recent call last):
  File line 21, in <module>
    cmds = fromCmd.split('\n')
TypeError: a bytes-like object is required, not 'str'

Solved with
cmds = fromCmd.decode().split('\n')

See
Cannot split, a bytes-like object is required, not 'str'

How to completely uninstall grafana?


React mapping array from Express API

Question: I am having trouble mapping the data from my Express API in React.
I have mapped data before from my Express API services without issues but I think the data is being displayed in a 2d array or something. I tried accessing it like a 2d array [0][0] but that didnt work. I can see the data in Google Chrome in my array.
I got the data in JSON format below from Postman.
Thank you very much for the help.
React Class:
class ScoreData extends React.Component{

constructor(props) {
    super(props);
    this.state = {
        selectedWeek: 1,
        selectedSeason: 2015,
        scoreData:[]
    };
}

componentDidMount(){
    fetch('/users/2015/1')
    .then(res => res.json())
    .then(dataArray => this.setState({scoreData: dataArray.data}));

}

Map function:
return (

NFL Score Data

    <button onClick={this.handleButtonClick}>Click me</button>

    {this.state.scoreData[0].map(currentScoreData=>

{currentScoreData.PK_GameID}

{currentScoreData.homeTeamPoints}

{currentScoreData.awayTeamPoints}

{currentScoreData.gameDate}

{currentScoreData.FK_AwayTeamID}

{currentScoreData.FK_HomeTeamID}

    )}

{
    "data": [
        [
            {
                "PK_GameID": 1591,
                "homeTeamPoints": 0,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 31,
                "FK_HomeTeamID": 3
            },
            {
                "PK_GameID": 1591,
                "homeTeamPoints": 0,
                "awayTeamPoints": 17,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 31,
                "FK_HomeTeamID": 3
            },
            {
                "PK_GameID": 1591,
                "homeTeamPoints": 8,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 31,
                "FK_HomeTeamID": 3
            },
            {
                "PK_GameID": 1591,
                "homeTeamPoints": 0,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 31,
                "FK_HomeTeamID": 3
            },
            {
                "PK_GameID": 1595,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 6,
                "FK_HomeTeamID": 4
            },
            {
                "PK_GameID": 1595,
                "homeTeamPoints": 9,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 6,
                "FK_HomeTeamID": 4
            },
            {
                "PK_GameID": 1595,
                "homeTeamPoints": 7,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 6,
                "FK_HomeTeamID": 4
            },
            {
                "PK_GameID": 1595,
                "homeTeamPoints": 10,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 6,
                "FK_HomeTeamID": 4
            },
            {
                "PK_GameID": 1589,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 27,
                "FK_HomeTeamID": 5
            },
            {
                "PK_GameID": 1589,
                "homeTeamPoints": 3,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 27,
                "FK_HomeTeamID": 5
            },
            {
                "PK_GameID": 1589,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 27,
                "FK_HomeTeamID": 5
            },
            {
                "PK_GameID": 1589,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 27,
                "FK_HomeTeamID": 5
            },
            {
                "PK_GameID": 1602,
                "homeTeamPoints": 3,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-14T05:00:00.000Z",
                "FK_AwayTeamID": 2,
                "FK_HomeTeamID": 8
            },
            {
                "PK_GameID": 1602,
                "homeTeamPoints": 14,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-14T05:00:00.000Z",
                "FK_AwayTeamID": 2,
                "FK_HomeTeamID": 8
            },
            {
                "PK_GameID": 1602,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-14T05:00:00.000Z",
                "FK_AwayTeamID": 2,
                "FK_HomeTeamID": 8
            },
            {
                "PK_GameID": 1602,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-14T05:00:00.000Z",
                "FK_AwayTeamID": 2,
                "FK_HomeTeamID": 8
            },
            {
                "PK_GameID": 1594,
                "homeTeamPoints": 3,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 25,
                "FK_HomeTeamID": 9
            },
            {
                "PK_GameID": 1594,
                "homeTeamPoints": 10,
                "awayTeamPoints": 6,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 25,
                "FK_HomeTeamID": 9
            },
            {
                "PK_GameID": 1594,
                "homeTeamPoints": 3,
                "awayTeamPoints": 21,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 25,
                "FK_HomeTeamID": 9
            },
            {
                "PK_GameID": 1594,
                "homeTeamPoints": 0,
                "awayTeamPoints": 21,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 25,
                "FK_HomeTeamID": 9
            },
            {
                "PK_GameID": 1590,
                "homeTeamPoints": 0,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 28,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1590,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 28,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1590,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 28,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1590,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 28,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1603,
                "homeTeamPoints": 3,
                "awayTeamPoints": 14,
                "gameDate": "2015-12-17T05:00:00.000Z",
                "FK_AwayTeamID": 23,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1603,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-17T05:00:00.000Z",
                "FK_AwayTeamID": 23,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1603,
                "homeTeamPoints": 3,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-17T05:00:00.000Z",
                "FK_AwayTeamID": 23,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1603,
                "homeTeamPoints": 17,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-17T05:00:00.000Z",
                "FK_AwayTeamID": 23,
                "FK_HomeTeamID": 10
            },
            {
                "PK_GameID": 1593,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 1,
                "FK_HomeTeamID": 14
            },
            {
                "PK_GameID": 1593,
                "homeTeamPoints": 3,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 1,
                "FK_HomeTeamID": 14
            },
            {
                "PK_GameID": 1593,
                "homeTeamPoints": 10,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 1,
                "FK_HomeTeamID": 14
            },
            {
                "PK_GameID": 1593,
                "homeTeamPoints": 0,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 1,
                "FK_HomeTeamID": 14
            },
            {
                "PK_GameID": 1604,
                "homeTeamPoints": 6,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-19T05:00:00.000Z",
                "FK_AwayTeamID": 3,
                "FK_HomeTeamID": 16
            },
            {
                "PK_GameID": 1604,
                "homeTeamPoints": 3,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-19T05:00:00.000Z",
                "FK_AwayTeamID": 3,
                "FK_HomeTeamID": 16
            },
            {
                "PK_GameID": 1604,
                "homeTeamPoints": 0,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-19T05:00:00.000Z",
                "FK_AwayTeamID": 3,
                "FK_HomeTeamID": 16
            },
            {
                "PK_GameID": 1604,
                "homeTeamPoints": 10,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-19T05:00:00.000Z",
                "FK_AwayTeamID": 3,
                "FK_HomeTeamID": 16
            },
            {
                "PK_GameID": 1601,
                "homeTeamPoints": 7,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 7,
                "FK_HomeTeamID": 17
            },
            {
                "PK_GameID": 1601,
                "homeTeamPoints": 10,
                "awayTeamPoints": 3,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 7,
                "FK_HomeTeamID": 17
            },
            {
                "PK_GameID": 1601,
                "homeTeamPoints": 3,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 7,
                "FK_HomeTeamID": 17
            },
            {
                "PK_GameID": 1601,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 7,
                "FK_HomeTeamID": 17
            },
            {
                "PK_GameID": 1599,
                "homeTeamPoints": 0,
                "awayTeamPoints": 6,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 21,
                "FK_HomeTeamID": 18
            },
            {
                "PK_GameID": 1599,
                "homeTeamPoints": 0,
                "awayTeamPoints": 6,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 21,
                "FK_HomeTeamID": 18
            },
            {
                "PK_GameID": 1599,
                "homeTeamPoints": 9,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 21,
                "FK_HomeTeamID": 18
            },
            {
                "PK_GameID": 1599,
                "homeTeamPoints": 6,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 21,
                "FK_HomeTeamID": 18
            },
            {
                "PK_GameID": 1592,
                "homeTeamPoints": 0,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 11,
                "FK_HomeTeamID": 19
            },
            {
                "PK_GameID": 1592,
                "homeTeamPoints": 0,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 11,
                "FK_HomeTeamID": 19
            },
            {
                "PK_GameID": 1592,
                "homeTeamPoints": 3,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 11,
                "FK_HomeTeamID": 19
            },
            {
                "PK_GameID": 1592,
                "homeTeamPoints": 0,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 11,
                "FK_HomeTeamID": 19
            },
            {
                "PK_GameID": 1596,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 12,
                "FK_HomeTeamID": 22
            },
            {
                "PK_GameID": 1596,
                "homeTeamPoints": 7,
                "awayTeamPoints": 6,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 12,
                "FK_HomeTeamID": 22
            },
            {
                "PK_GameID": 1596,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 12,
                "FK_HomeTeamID": 22
            },
            {
                "PK_GameID": 1596,
                "homeTeamPoints": 14,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 12,
                "FK_HomeTeamID": 22
            },
            {
                "PK_GameID": 1588,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 15,
                "FK_HomeTeamID": 23
            },
            {
                "PK_GameID": 1588,
                "homeTeamPoints": 10,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 15,
                "FK_HomeTeamID": 23
            },
            {
                "PK_GameID": 1588,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 15,
                "FK_HomeTeamID": 23
            },
            {
                "PK_GameID": 1588,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 15,
                "FK_HomeTeamID": 23
            },
            {
                "PK_GameID": 1600,
                "homeTeamPoints": 0,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 16,
                "FK_HomeTeamID": 26
            },
            {
                "PK_GameID": 1600,
                "homeTeamPoints": 0,
                "awayTeamPoints": 14,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 16,
                "FK_HomeTeamID": 26
            },
            {
                "PK_GameID": 1600,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 16,
                "FK_HomeTeamID": 26
            },
            {
                "PK_GameID": 1600,
                "homeTeamPoints": 0,
                "awayTeamPoints": 14,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 16,
                "FK_HomeTeamID": 26
            },
            {
                "PK_GameID": 1598,
                "homeTeamPoints": 7,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 13,
                "FK_HomeTeamID": 29
            },
            {
                "PK_GameID": 1598,
                "homeTeamPoints": 7,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 13,
                "FK_HomeTeamID": 29
            },
            {
                "PK_GameID": 1598,
                "homeTeamPoints": 7,
                "awayTeamPoints": 14,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 13,
                "FK_HomeTeamID": 29
            },
            {
                "PK_GameID": 1598,
                "homeTeamPoints": 3,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 13,
                "FK_HomeTeamID": 29
            },
            {
                "PK_GameID": 1597,
                "homeTeamPoints": 0,
                "awayTeamPoints": 21,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 24,
                "FK_HomeTeamID": 30
            },
            {
                "PK_GameID": 1597,
                "homeTeamPoints": 0,
                "awayTeamPoints": 7,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 24,
                "FK_HomeTeamID": 30
            },
            {
                "PK_GameID": 1597,
                "homeTeamPoints": 0,
                "awayTeamPoints": 10,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 24,
                "FK_HomeTeamID": 30
            },
            {
                "PK_GameID": 1597,
                "homeTeamPoints": 0,
                "awayTeamPoints": 0,
                "gameDate": "2015-12-13T05:00:00.000Z",
                "FK_AwayTeamID": 24,
                "FK_HomeTeamID": 30
            }
        ],
        {
            "fieldCount": 0,
            "affectedRows": 0,
            "insertId": 0,
            "serverStatus": 2,
            "warningCount": 0,
            "message": "",
            "protocol41": true,
            "changedRows": 0
        }
    ]
}

Comment: so, what's the problem you are facing? what is your expected output?
Answer: The code that you have is correct for the most part it looks like you only need to add the nested array to the default value:
constructor(props) {
    super(props);
    this.state = {
         selectedWeek: 1,
         selectedSeason: 2015,
         scoreData:[ [] ], // <--- this right here
    };
}

Or alternatively set scoreData to the nested array
Comment: Thank you very much. Worked right away. Another thing I have learned :)

mapped it with:
    {this.state.scoreData[0].map(currentScoreData=>

React mapping array from Express API


Import Bacpac file into Azure SQL DB

Question: I have a bacpac file of db1 in my local. I want the bacpac file to import in database db2.
When I was trying to import the file using import option in SSMS (right click database and import data) there is no option to connect to the existing/already created db. I have an already created db where I only want to import the contents from the bacpac file into the db2.
Answer: SQL Database doesn't support, import BACPAC file into Existing database not possible only New or Empty Database.
If you want to import the content file into Database 2, there are many ways you can get,

Export all your Database table view to Azure blob and import these files to your existing Azure SQL database with SSMS. Follow these steps

Export Data to Blob Storage

Select source table and view -> Choose one or more table views and copy -> Next -> Execution successful -> close.

Import data from blob storage to SQL Database

You can reference this document:
https://www.sqlshack.com/connect-azure-storage-account-sql-server-management-studio-ssms/

Import Bacpac file into Azure SQL DB


Choosing regression model

Question: How can I choose between these two regression models?
R outputs:
Regression 1
Call:
lm(formula = log.h ~ year)

Residuals:
     Min       1Q   Median       3Q      Max
-1.24004 -0.45221 -0.05301  0.44744  1.42060

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.588e+02  1.565e+01  -10.15 9.47e-13 ***
year         8.809e-02  7.859e-03   11.21 4.65e-14 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.6396 on 41 degrees of freedom
Multiple R-squared: 0.7539, Adjusted R-squared: 0.7479
F-statistic: 125.6 on 1 and 41 DF,  p-value: 4.654e-14

Regression 2:
Call:
lm(formula = log.h ~ year + I(year^2) + I(year^3))

Residuals:
    Min      1Q  Median      3Q     Max
-1.4044 -0.3966  0.1141  0.3447  1.2321

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.075e+06  4.663e+05  -2.304   0.0266 *
year         1.622e+03  7.027e+02   2.308   0.0264 *
I(year^2)   -8.162e-01  3.529e-01  -2.313   0.0261 *
I(year^3)    1.369e-04  5.909e-05   2.317   0.0259 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.58 on 39 degrees of freedom
Multiple R-squared: 0.8075, Adjusted R-squared: 0.7927
F-statistic: 54.54 on 3 and 39 DF,  p-value: 5.093e-14

Thoughts: The point is the first model is good, $R^{2}$ is good, p-values are great, but there are hints of heteroskedasticity of residuals vs predicted values.
The second one has a better adjusted $R^{2}$, a great $p$-value of regression, and the scatterplots have got better (not drastically, but better).
On the other hand, the $p$-values of the coefficients are a lot higher than before.
Considering all this, how can I choose between them?
Comment: I would not interpret the pattern of residuals in the first model as heteroscedasticity, but instead as a possible non-linear trend.  Applying a robust smoother (such as LOESS) to the residuals will help you see that. If the smoother is close to a straight horizontal line you can suspect heteroscedasticity (and test it by smoothing the roots of the absolute values of the residuals), but if it wiggles around appreciably, you have detected a *systematic variation in the average residual.*
Comment: Skimming your plots, @PeterFlom is right: there is clearly some structure in the residuals that isn't being captured by the 1st model fit. The 2nd is better, but isn't quite perfect. Using a spline seems ideal here.
Comment: whatever your variable `h` is,it doesn't make sense  adding square and cubic of time variable without any theoretical justification.
Comment: the lowess is't close to a horizontal line untile 1990, then bent of about 40 degrees!
Comment: You often need to tune the degree of smoothing with lowess (loess). (Some people apply cross-validation; some programs do that automatically, or so I guess.)
Answer: First, I wouldn't judge solely by $R^2$ and not at all by p values
Second, like @gung I would not use stepwise or its variants.
Third, your plots are nice, but the first plot I'd look at is a simple scatterplot of log.h and year, perhaps with a spline or other smooth added. Something like
plot(log.h~year)
lines(lowess(log.h~year))

to see what I could see.
Fourth, I would think about what the relationship could mean. Since I don't know what log.h is, I have no idea. But does accelerating change over time make sense? Or decelerating?
Fifth, I'd be careful of overfitting the sample, and especially of extrapolating beyond it with a polynomial model, which is often the aim when year is a predictor.
Sixth, I'd consider a spline fit.
Comment: Indeed, it makes quite sense that it's accelerating over time with a greater speed than linear one.. I guess I'm going for the cubic fit
Answer: I agree with the general tenor of other comments (including an aversion to stepwise). Like others I have reservations about polynomials here, and would tend to prefer splines, but you can do one simple thing to make your polynomial results less unfriendly.
The one plot most missing is a basic plot of the data, as @Peter Flom emphasized, but some reverse engineering makes it clearer what is happening.
Your first model is evidently close to
$-158.8 + 0.08809\ {\rm year}$,
and from your predicted values it can be guessed that year ranges from about 1975 to 2010.
Your second model is evidently close to
$-1075000 + 1622\ {\rm year} -0.8162\ {\rm year}^2 + 0.0001369\ {\rm year}^3$,
although digits not shown are essential to get predicted values close to those shown.
These polynomials are close numerically but not algebraically. A simple trick that would make it easier to work with polynomials is to choose an origin within the range of the data. There is no reason to privilege the origin of the Western calendar. Working with (say) (year $- 2000$) would give the intercept the simple interpretation of value in $2000$ and should make it easier to compare linear, quadratic and cubic fits.
Comment: I would really like to thank everyone, every answer has improved my understanding of regression.. I was mislead by the high p-value values, which, as i now discover, are not that significant (since translating -2000 years solves the problem of p-values, but of course the regression it's exactly the same)
Comment: I appreciate the acceptance, but want to underline that  other answers contain excellent strategic and tactical advice.
Comment: that is why I upvoted all of them :-)
Answer: Three things:

The adjusted $R^2$ value of your 2nd model is larger than your first. This means it explains more of the variation in the data than the first one. Unlike the standard $R^2$ value it is not impacted by the number of variables added to the model.
To more rigorously compare them you can run an ANOVA test like so:
anova(regression1.model, regression2.model)

Look for the p-value. The closer to zero the better, though common practice is it should be at least less than .05.
Make sure it makes sense. If you created regression 2 because you thought it might be a better fit and the above other points are met, you've found yourself an improved model.
Answer: This is a hard question to answer based on what you've shown.  And that's why it's hard for you.  If you had more information included it would be easier.
One might question whether the polynomial is contributing a meaningful amount of extra predictive power given the cost of the additional parameters and assess using AIC (AIC function in R).  It doesn't seem like they add much (they'll always add some) but you can check.
Then there's the question of whether the curved wavy line you've made is overfit.  Will it predict new values? You could look up cross validation techniques but for something like that.
Probably the more important thing to do is assess what you're expecting your predictor to do at a theoretical level.  Should it have a linear effect?  Are you expecting it to be wavy (you polynomial)?  Why is it wavy?  If you can't address these and other theoretical questions then neither of these statistical models is particularly good or bad.
To help you on the use of AIC you might want to look at a couple of papers.
Answer: $R^{2}$ will always increase as you add more variables to the model.  It seems what you are asking is what variables to include in the model.  This is called variable selection.  You can accomplish this in R by the step function.  This function bases the best model on a statistic called AIC.  Make sure you use the full model, the one with the most variables.
step(yourfullmodel)

the final output will give you your the best subset model under Call:
Comment: Welcome to the site, @willy. Note that stepwise variable selection routines are not considered valid anymore. If this doesn't make sense to you / you want to know why, it may help to read my answer here: [algorithms-for-automatic-model-selection](http://stats.stackexchange.com/questions/20836//20856#20856).
Comment: He does have the adjusted R^2 however which does not suffer from the same flaws as the standard R^2.

Choosing regression model


A question regarding finite field extensions

Question: If I understand correctly, the definition of the degree of a field extension $L/K$ is the dimension of $L$ over $K$ interpreted as a vector space. Now if the degree is $n < \infty$, the basis looks like $\{ 1, a_1, \dots , a_n\}$ where $a_i \in L - K$.
My question is:
Is it right to write $\{ 1, a, a^2, \dots , a^n\}$ for some $a \in L - K$ because of the primitive element theorem? If not, why exactly is the basis usually written $\{ 1, a, a^2, \dots , a^n\}$ instead of $\{ 1, a_1, \dots a_n\}$?
Answer: You are correct - there is a basis of the form $\{1,a,a^2,\ldots,a^{n-1}\}$ for some $a\in L-K$ precisely when the primitive element theorem does in fact hold, which is when $L/K$ is a finite, separable extension. Note that the exponents only go up to $n-1$, since the dimension, and hence the number of elements in a basis, is $n$.
Comment: @Matt: Those are not the most general conditions for the primitive element theorem. Any algebraic extension of fields that are of characteristic 0 is separable, which is why it is glossed over in most introductory treatments of the primitive element theorem. Given an algebraic extension $L/K$, we say that $a\in L$ is separable when its minimal polynomial over $K$ has no repeated roots. We then call the extension $L/K$ separable if every $a\in L$ is separable.
Comment: Also, regardless of characteristic: there will always be $n=[L:K]$ elements in a basis, and 1 is not necessarily in a basis (as Qiaochu points out). So if you wanted to refer to an arbitrary basis for $L/K$ when $\text{char}(K)=p$, all you would have is just $\{a_1,\ldots,a_n\}$.
Comment: Thank you. I don't know what separable means (yet) but I looked up the conditions for the primitive element theorem: $char(K) = 0$ and $a_i$ algebraic over $K$. I assume this is equivalent.

So when $char(K)=p$ you'd write $\{ 1, a_1, \dots , a_n\}$?
Answer: $1$ doesn't necessarily have to be in the basis; we are ignoring the multiplication and just thinking about the vector space structure, so it should just look like $\{ a_1, ... a_n \}$ for some linearly independent $a_i \in L$ (and it doesn't matter whether they're in $K$ or not).
When people say that there exists $a$ such that $\{ 1, a, a^2, ... a^{n-1} \}$ is a basis, they are appealing to the primitive element theorem.
Comment: @Matt: Yes - for example, $\{1+\sqrt{2},\sqrt{2}\}$ is a basis for $\mathbb{Q}(\sqrt{2})/\mathbb{Q}$.
Comment: Your answer is food for thought. Is there an example where none of the basis elements of $L/K$ are in $K$? I'm thinking about it.


Make useEffect hook run before rendering the component

Question: I've got a useEffect hook that I use in my App.js file. It puts data into redux store that I need to use in my App. But it renders before the useEffect runs, therefore the data is undefined. The useEffect then runs correctly.
I need useEffect to run before anything gets rendered. How could I do that? Or what other solution should I use? I have tried removing the useEffect completely and just running the action, but that results in it running endlessly.
This is my code:
function App() {
  const app = useSelector(state => state.app);
  const auth = useSelector(state => state.auth);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(authActions.checkUser());
  }, [dispatch]);

  console.log(auth.user); //undefined

  return (
    <ThemeProvider theme={!app.theme ? darkTheme : theme}>
      <CssBaseline />
      <React.Fragment>
        {/* TODO: Display drawer only when logged in */}
        {/* <Drawer></Drawer> */}
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/dashboard">
            <Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
          </Route>
          <Route exact path="/register" component={Register} />
        </Switch>
      </React.Fragment>
    </ThemeProvider>
  );
}

export const checkUser = () => async dispatch => {
  let token = localStorage.getItem("auth-token");
  if (token === null) {
    localStorage.setItem("auth-token", "");
    token = "";
  }
  const tokenRes = await Axios.post("http://localhost:5000/users/tokenIsValid", null, {
    headers: { "x-auth-token": token }
  });
  if (tokenRes.data) {
    const userRes = await Axios.get("http://localhost:5000/users/", {
      headers: { "x-auth-token": token }
    });
    dispatch({
      type: CHECK_USER,
      token,
      user: userRes.data
    });
  }
};

Answer:
I need useEffect to run before anything gets rendered. How could I do
that?

You cannot make useEffect run before the initial render.
Just like componentDidMount in class components runs after the initial render, useEffect runs after the initial render and then its execution depends on whether you pass the second argument, i.e. dependency array to useEffect hook.

what other solution should I use?

You can conditionally render the content by making sure that you render the asynchronously fetched data only after it is available.
return (
   { auth ? <render content> : null}
);

or
return (
   { auth && <render content> }
);

P.S: angle brackets < or > are not included in the syntax. They are just there as a placeholder for the content that you need to render.
For details, see: React - Conditional Rendering
Comment: Thanks, this works, but obviously, there's a slight delay before the render content displays. How could I prevent this delay?
Comment: While the data is loading, you could render some kind of loading spinner to indicate that data is being loaded.
Answer: Alternative
You can use useMemo, which doesn't wait for re-render. It will execute same way based on dependencies like useEffect too.
useMemo(()=>{
    doSomething() //Doesn't want until render is completed
}, [dep1, dep2])


Android imageview change tint to simulate button click

Question: I have an imageview on which I have set a bitmap fetched from an url.
On the imageview I have set an onClickListener which opens up a dialog.
I want to somehow change the tint (make it darker) when the imageview is pressed upon to provide a sort of button click like feel.
What do you suggest?
Answer: happydude's answer is the most elegant way to handle this but unfortunately (as pointed out in the comments) the source code for ImageView only accepts an integer (solid colour). Issue 18220 has been around for a couple years addressing this, I've posted a workaround there that I'll summarize here:
Extend ImageView and wrap drawableStateChanged() with code that sets the tint based on the new state:
TintableImageView.java
package com.example.widgets;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.support.v7.widget.AppCompatImageView;

import com.example.R;

public class TintableImageView extends AppCompatImageView {

    private ColorStateList tint;

    public TintableImageView(Context context) {
        super(context);
    }

    public TintableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public TintableImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, defStyle, 0);
        tint = a.getColorStateList(R.styleable.TintableImageView_tintColorStateList);
        a.recycle();
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (tint != null && tint.isStateful())
            updateTintColor();
    }

    private void updateTintColor() {
        int color = tint.getColorForState(getDrawableState(), 0);
        setColorFilter(color);
    }

}

Define a custom attribute:
attrs.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <declare-styleable name="TintableImageView">
        <attr name="tintColorStateList" format="reference|color" />
    </declare-styleable>

</resources>

Use the widget and custom attribute with your local namespace instead of Android's:
example_layout.xml
<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <com.example.widgets.TintableImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        android:clickable="true"
        app:tintColorStateList="@color/color_selector"/>

</LinearLayout>

You can then use a colour selector like happydude suggested:
color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/pressed_color"/>
    <item android:color="#00000000"/>
</selector>

Comment: This is why my answer defines a custom tint attribute in attrs.xml. You have to use the custom **app:tint** in your layout instead of **android:tint**. Essentially, you are creating a new attribute that wraps the native one and feeds it one color at a time.
Comment: I'm trying your solution, but still getting `java.lang.NumberFormatException: Invalid int: "@2130837701"` when a constructor inside `TintableImageView` calls its super... I needed to pass `new int[]{R.styleable.TintableImageView_tint}` because `obtainStyledAttributes` was asking for an array, and to declare `@drawable/tab_icon_selector` inside colors.xml in order to be able to reference it from android:tint
Comment: I pasted your code and check everything and it just doesn't work.
Comment: thanks for answering! I've changed to `app:tint` and the exception is gone... But the selector is still not being used, ie, my icons are black all the time... is my drawable declaration inside colors.xml the correct way to do it?
Comment: Please answer my question on SO, so I can accept it http://stackoverflow.com/questions/19500039/how-to-use-selector-to-tint-imageview-in-android
Comment: I've provided an answer there. Just as a note for others here, you can put your selector.xml in /res/color to reference it using @color
Comment: @StephenKidson thnk u very much for sharing such useful cod. thnks again
Comment: This doesn't work for me if I use a drawable state list or just a single color resource. How can I tint the ImageView in these cases?
Comment: I removed `mTint.isStateful()` from the `drawableStateChanged()` method and now it works for me for both of the situations i said above, including if they are both done on the same button.
Comment: For those reading that haven't turned to dust waiting for an official fix, it is now supposedly fixed in Android API 21 (Lollipop). Also the fix may someday be [**back-ported to previous APIs through AppCompat**](https://code.google.com/p/android/issues/detail?id=18220#c13) though I wouldn't hold my breath.
Comment: @DannySuen did you read my comments above? are you using a drawable state list or single color resource?
Comment: Thank you, buddy. It works perfectly! For those whose app crashes - do not forget to specify your correct package name in xml (instead of  com.example.widgets.TintableImageView)
Comment: Adding `android:clickable="true"` in the custom `ImageView` worked for me
Comment: By clicking image, tint color is not staying it only changing when image is pressesed
Answer: One way would be to use a combination of a ColorFilter and a ColorStateList that contains your tint color for when the button is pressed.  The xml for the ColorStateList in the res/color directory would look like this:
button_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:color="@color/pressed_color"/>
    <item android:color="#00000000"/>

</selector>

where @color/pressed_color is your tint color (which should be partially transparent).  Then in your ImageView subclass, you apply the color by overriding drawableStateChanged().
@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();

    ColorStateList list = getResources().getColorStateList(R.color.button_pressed);
    int color = list.getColorForState(getDrawableState(), Color.TRANSPARENT);
    setColorFilter(color);
    invalidate();
}

Any time the button's state changes, this code is called and will automatically set the tint as appropriate.
Comment: Ok. so this is the error when I get when i set android:tint="@drawable/button_pressed", I get this error during compile,06-19 20:22:54.222: E/AndroidRuntime(2338): Caused by:  java.lang.NumberFormatException: unable to parse 'res/drawable/button_pressed.xml' as integer
06-19 20:22:54.222: E/AndroidRuntime(2338):  at java.lang.Integer.parse(Integer.java:383)
06-19 20:22:54.222: E/AndroidRuntime(2338):  at java.lang.Integer.parseInt(Integer.java:372)
06-19 20:22:54.222: E/AndroidRuntime(2338):  at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:12s)
Comment: I tried your suggestion. It doesnt seem to do anything. Using the debugger I noticed that the drawableStateChanged() method is not triggered on onPress but seems to only trigger on onClick.
Comment: Hmm, I cannot see any errors in the code above. By definition, the method should be called when the pressed state changes. I have been using this construct in my own code and it works ok. As a test, in your ImageView XML add `android:tint="@color/pressed_color"`. This should add a permanent tint to your image, as it calls the same colorfilter setting method as the code above. This way you can at least rule out a problem with the color you chose.
Comment: Sorry, I am dumb. You can just add your color state list directly to your `ImageView` XML file directly. See edit above.
Comment: First off, please disregard the "edit."  I looked through the source code and sure enough `tint` will only accept a solid color.  Sorry to lead you down the wrong track.  Second, I tried the code from the original post above in a custom `ImageView` I created and it worked for me.  I tested it by setting the image using `setImageResource(int)`, though I don't see why the other image setting methods would not work.  Finally, make sure that in your XML definition you add `android:clickable="true"`.  Without this line it will not work.
Answer: I'd have to test it out, but you should be able to set an xml with that behaviour as the ImageView drawable, and then set your bitmap as the ImageView background.
Answer: For me a simple solution is working, using setAlpha(180) in onClick event make the image darker, giving the user a feedback that it was clicked or touched.
final ImageView myImage = (ImageView) findViewById(R.id.ivDocument);
myImage.setImage...(... your image ...); // load your ImageView
myImage.setClickable(true);
myImage.setFocusable(true);
myImage.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        myImage.setAlpha(180);
        doWhateverYouWantHere(v);
    }
});

Regarding your XML layout, nothing special.
Answer: This code snippet worked for me:
porterDuffColorFilter = newPorterDuffColorFilter(getResources().getColor(R.color.cardview_dark_background),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT);


Creating multiple nodes in a linked list

Question: I'm trying to make a function that saves values entered into various elements of a given linked list (plus and lens), then display the result (id). I can enter, save, and display this only one time, but as soon as I exit the function or try to enter another set of values, it only shows the most recent one. The user is prompted to select whether to write something or to exit the program, within the main.c file. I think I'm only creating one node, but not sure how to fix it. Since, the number of entries is unknown, I can't just hard code the number of sets of data I want (or nodes). My code is below:
Within header function:
typedef struct nodetreat{
    int id;
    char user[51];
    char text[141];

    struct nodetreat *next;
}treat;

Within main.c:
int num = 0;
scanf("%d", &num);

if(num== 1) {
  treatmaker(treatList);
}

Within function (treatmaker):
treat *treatmaker(treat *treatList) {

  int i;
  int plus= 0;
  int lens = 0;
  struct nodetreat *new_node;

  new_node = malloc(sizeof(struct nodetreat));

  printf("Enter a name: ");
  fgets(new_node->user, 51, stdin);

  printf("Enter the text: ");
  fgets(new_node->text, 141, stdin);

  for(i = 0; i < strlen(new_node->user) - 1; i++) {
    plus += new_node->user[i];
  }

  lens= strlen(new_node->text) - 1;

  new_node->id = plus + lens;

  printf("id is %d.\n", new_node->id);
}

So my question is, what do I fix so that my linked list can hold multiple id's or nodes?
Comment: Show the declaration of the variable "treatList".
Comment: What does "plus and lens" mean?
Comment: the function: `fgets()` includes the trailing newline `\n` in the data,  You probably don't want to keep that newline.  Suggest: `new_node->user[ strcspn( new_node->user, "\n") ] = '\0';`    Then you probably will not need the `-1` on the calls to `strlen()`
Answer: You need to set new_node->next to nodetreat in the function treatmaker and then return new_node in the end.
treat *treatmaker(treat *treatList)
{
    // do something here...
    now_node->next = treatList;
    return new_node;
}

In your main.c file, you would then have to overwrite treatList with the returned new_node.
treatList = treatmaker(treatlist);

And by the way, I would suggest allocating memory for new_node like this:
new_node = malloc(sizeof *new_node);


Nuxt Auth Module - How to create Success Redirect

Question: I'm trying to a page in my nuxt app, where the user is on a dynamic route. On this route he has the possibility to log in and should then be redirected to exactly the same route. For the authentification I want to use the auth0 strategy.
I thought the following line would work:
this.$auth.loginWith('auth0')
  .then(() => {
    this.$router.push("/the-same-route-im-already-on");
  })

But apperently I'm only redirected to my home route "/loggedin". And changing the home redirect in my nuxt.config to false, redirects me to my callback-route "/login"
Right now my nuxt.config.js looks like this:
auth: {
    auth0: {
     ...
    },
    redirect: {
      login: '/',
      logout: '/',
      callback: '/login',
      home: '/loggedin',
    }
}

Answer: I think the default behavior of rewriteRedirect in nuxt Auth Module, should redirect you to the original guarded route.
rewriteRedirect
If this is not working maybe you could redirect the user to login route manually passing a query like this
this.$router.push({ path: '/login', redirect: 'actualRoute' });

And then check in your login page if redirect is setted and then after login you call $router passing the value of redirect.
I don't know if this will help you, so let me know.


How do I get the correct URL of an image field?

Question: I'm trying to print out the URL of an image field using the following code.
<img src="<?php echo $field_company_logo['und'][0]['uri']; ?>" alt="<?php echo $company[0]['#markup']; ?>" />

The code gives me a URI like public://company-logos/image.png when I would need sites/default/files/company-logos/image.png.
What code should I use to print the image path (i.e. sites/default/files/company-logos/image.png)?
Answer: You want to use the drupal_realpath() function to convert the URI into the actual filesystem path.
echo drupal_realpath($field_company_logo['und'][0]['uri']);

You could also use file_create_url() to get the actual URL to the image, as opposed to a local filepath.
And the correct way to render an image is to run it through theme_image():
echo theme('image', array(
  'path' => file_create_url($field_company_logo['und'][0]['uri']),
  'alt' => check_plain($company[0]['#markup']),
));

Also, accessing field data the way you're doing it isn't the preferred method. Have a look at field_get_items() and the detailed example in the Rendering Drupal Fields (the right way) blog entry.
Comment: +1 for using the theme function, although I don't think you would actually want drupal_realpath() anymore. The theme function will automatically transform the URI.
Comment: file_create_url worked for me, thanks! realpath gave me the absolute url though which wouldn't render.
Comment: You can pass the stream path directly (public://...) and it will automatically generate the right path.
Answer: If you literally just want to transform a URI into an actual URL, then you want the file_create_url() function, which is used like this:
$url = file_create_url($uri);

But you might find it easier to use a theme function, like Yuriy Babenko suggests:
$image_vars = array(
  'path' => $field_company_logo['und'][0]['uri'],
  'alt' => $company[0]['#markup'],
);
echo theme('image', $image_vars);

You can easily adapt this to use theme_image_style() instead, if you want a sized derivative of your image.
Answer: You can use the Image URL Formatter module. It allows to change the field format in order to get only the URL:

Bonus: it works with Views as well:


API Como passar resultado de uma função js para arquivo de rotas

Question: Sou iniciante e comecei a estudar sobre a criação de APIs com nodeJs, pegando algumas documentações consegui implementar algumas funcionalidades, tenho uma função de buscar que traz o resultado da pesquisa como result. ao imprimir no console dentro da propria função, consigo retornar o resultado da pesquisa em json, mas ao dar um return nessa função e chama-la no meu arquivo de rotas atribuindo-a a uma variável ela vem como undefined, alguém poderia me ajudar com esse problema?
ps: quero passar o resultado para o arquivo de rotas para fazer um response com o resultado
segue o codigo do meu arquivo de funcionalidades
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes')

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

///inserir dados
exports.Inserir = function(myobj){
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("mydb");
        dbo.collection("customers").insertOne(myobj, function(err, res) {
        if (err) throw err;
        db.close();
        });
    });
}

//buscar dados
exports.Buscar = function(query){
  var resultado = MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("customers").find(query).toArray(function(err, result) {
      if (err) throw err;
      return result
      db.close();
    });
  });
}

//deletar dados
exports.Deletar = function(myquery){
  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("customers").deleteMany(myquery, function(err, obj) {
      if (err) throw err;
      console.log("1 document deleted");
      db.close();
    });
  });
}

exports.Atualizar = function(){
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myquery = { address: "Mountain 21" };
  var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
  dbo.collection("customers").updateMany(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
    db.close();
  });
});
}

meu arquivo de rotas
const Connection = require('mysql/lib/Connection')
const routes = express.Router()
const connnection = require('./conection')

module.exports = routes

//Busca Dados
routes.get('/busca', (req, res) =>{
  resultado = connnection.Buscar( { address: "Mountain 22" })
  console.log(resultado)
  res.end();
})

//Inserir Dados
routes.post('/add', (req,res) => {
        dados = req.body
        connnection.Inserir(dados);
        res.write('Cadastrado com sucesso')
        res.end();
})

//Deleta Dados
routes.delete('/delete', (req, res) =>{
    dados = req.body
    connnection.Deletar(dados);
    res.end();
})

//Atualizar dados
routes.patch('/edit', (req, res) =>{
    connnection.Atualizar();
    res.end();
})

Comment: No teu helper de "Buscar" vc não está fazendo o retorno da variável, por isso lá no teu routes está vindo como undefined, basta você retornar o resultado `return MongoClient.connect(....`.
Answer: Fala Rafael, blza?
Você está importando o express mas praticamente vc não está fazendo uso dele. No teu segundo arquivo importe o express completo, não somente o routes.
Como sugestão, utilize uma constante para facilitar. Vc precisa tbm ser explicito em qual formato vc quer que o expressa faça o cast.
const app = express();
app.use(express.json());

Outra coisa que pode ser feita é vc dar logo o feedback no teu res, facilita
//Busca Dados
app.get('/busca', (req, res) =>{
  resultado = connnection.Buscar( { address: "Mountain 22" })
  console.log(resultado)
  res.status(200).json(resultado);
})


Create a fixed padding

Question: The current padding is in fluid. I want a same-sized(fixed) padding.
If i put width or box-size..the text will overflow.
How do i make a fixed padding without losing the css effect.

#buttons {
  list-style: none;
}

.first {
  background: #f7a63d;
}

@-webkit-keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

@keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

.a-1 {
  white-space: nowrap;
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  display: inline-block;
  text-align: center;
  padding: 10px 50px;
  font-size: 26px;
  line-height: 30px;
  border-radius: 10px;
  position: relative;
  cursor: pointer;
  border: 0px;
  margin: 15px 0px;
  transition: 0.5s;
  overflow: hidden;
  vertical-align: middle;
  text-decoration: none;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
  color: #8cffadf;
}

.a-1:before {
  content: "";
  position: absolute;
  width: 150%;
  height: 20px;
  background: rgba(255, 255, 255, 0.125);
  box-shadow: 0px 0px 50px rgba(255, 255, 255, 0.35);
  top: 10px;
  left: -10%;
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-animation: a1 2s ease infinite;
  animation: a1 2s ease infinite;
}

TEST

EXAMPLE

EXAMPLE 2

Comment: I edited the css here and removed the fiddle, next time put all the code here in a snippet. There is a button for that in the editor.
Answer: How about using a min-width? The buttons will take on that width, unless length of the text inside requires more space, in which case the button will become wider:

#buttons {
  list-style: none;
}

.first {
  background: #f7a63d;
}

@-webkit-keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

@keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

.a-1 {
  white-space: nowrap;
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  display: inline-block;
  text-align: center;
  padding: 10px 50px;
  font-size: 26px;
  line-height: 30px;
  border-radius: 10px;
  position: relative;
  cursor: pointer;
  border: 0px;
  margin: 15px 0px;
  transition: 0.5s;
  overflow: hidden;
  vertical-align: middle;
  text-decoration: none;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
  color: #8cffadf;
  min-width: 245px; /* I have added it here */
}

.a-1:before {
  content: "";
  position: absolute;
  width: 150%;
  height: 20px;
  background: rgba(255, 255, 255, 0.125);
  box-shadow: 0px 0px 50px rgba(255, 255, 255, 0.35);
  top: 10px;
  left: -10%;
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-animation: a1 2s ease infinite;
  animation: a1 2s ease infinite;
}

TEST

EXAMPLE

EXAMPLE 2

A REALLY REALLY LONG BUTTON

Or
Use the width style, as you were, but don't prevent the text inside from wrapping, by not changing the white-space style:

#buttons {
  list-style: none;
}

.first {
  background: #f7a63d;
}

@-webkit-keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

@keyframes a1 {
  0% {
    left: -170%;
  }
  100% {
    left: 100%;
  }
}

.a-1 {
  top: 50%;
  left: 50%;
  transform: translate(-50%);
  display: inline-block;
  text-align: center;
  padding: 10px 50px;
  font-size: 26px;
  line-height: 30px;
  border-radius: 10px;
  position: relative;
  cursor: pointer;
  border: 0px;
  margin: 15px 0px;
  transition: 0.5s;
  overflow: hidden;
  vertical-align: middle;
  text-decoration: none;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
  color: #8cffadf;
  width: 245px;
}

.a-1:before {
  content: "";
  position: absolute;
  width: 150%;
  height: 20px;
  background: rgba(255, 255, 255, 0.125);
  box-shadow: 0px 0px 50px rgba(255, 255, 255, 0.35);
  top: 10px;
  left: -10%;
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-animation: a1 2s ease infinite;
  animation: a1 2s ease infinite;
}

TEST

EXAMPLE

EXAMPLE 2

A REALLY REALLY LONG BUTTON

Create a fixed padding


How to display a warning message until user tick at least one checkboxes?

Question: I have some checkboxes on the website. If user doesn't tick any of the checkboxes I want to display a warning text on the page (not alert). Once one of the checkboxes ticked this warning will disappear. I wrote following code. This help me to display only on console. However, I want to get some help to display on page itself. Any help is appreciated! PS: I am pretty new in this. Sorry if my question is stupid.

Comment: Using some of the suggested answers you should have a listeners event and modify your results as needed, so having the warning div you can hide/unhide it when certain factors occur.
Answer: You add something like

 in your html.
And
document.querySelector('#warning').innerText = 'Please select at least one option';

in your javascript. Just play around with it.
Comment: Thank you so much for your help. Actually I did what you said and I can see the message on the webpage once no checkboxes is ticked. However, when I tick one of the checkboxes warning doesn't disappear. Even if I can see the selected checkboxes on local storage. It only disappear when I move to the next page and come back to the actual page. Do you have any idea what can be the problem?
Comment: You need to listen for events that suggest a reset has been made, to remove the message. You could run a timeout function that makes the message vanish and reset this timeout every call for warning.
Answer: Asuming you have something basically like this in your HTML
<input type="checkbox" name="group1" value="1">
<input type="checkbox" name="group1" value="2">
<input type="checkbox" name="group1" value="3">
<input type="checkbox" name="group1" value="4">
<input type="checkbox" name="group1" value="5">

Please select at least one option to process further!

At this point you just need to do something like this:

The ":checked" is telling the selector to only return the ones that are selected. And the querySelectorAll returns an array of nodes, so you can easily check is lenght to verify is any was selected.
You can play along it if you want to validate one selected, two selected, more than one, etc.
If you paint the message into another element you need to add an else to remove the message.

As suggested you can put this into an listener, more or less like this:

function checkChecked()
{
    if(document.querySelectorAll('input[name=group1]:checked').length == 0)
     {
          document.getElementById('warningDiv').innerHTML = "Please select at least one option to process further!";
     }else{
          document.getElementById('warningDiv').innerHTML = "";
     }

}

checkChecked();

const allcheckboxes = document.querySelectorAll('input[name=group1]');
    for(let checkboxinput in allcheckboxes)
    {
        if(typeof allcheckboxes[checkboxinput] == "object" && allcheckboxes[checkboxinput] != null)
        {
          allcheckboxes[checkboxinput].addEventListener('change', function(e) {
            checkChecked()
          });
        }
    }
#warning {
  color: red;
}
<input type="checkbox" name="group1" value="1">
<input type="checkbox" name="group1" value="2">
<input type="checkbox" name="group1" value="3">
<input type="checkbox" name="group1" value="4">
<input type="checkbox" name="group1" value="5">

Please select at least one option to process further!

Comment: OP mentions in question that `alert()` is not an option.
Comment: Just noted, added the other version too
Comment: Thank you so much for your answer and time. It really helped!
Comment: Glad to hear! Happy Coding!
Answer:

// query and get elements
const checkboxs = document.querySelectorAll('input[type=checkbox]');
const messages = document.querySelectorAll('.warning');

// add event listener to each element
checkboxs.forEach(checkbox => {
  checkbox.addEventListener("click", () => {
    toggle(checkboxs, messages);
  });
});

// show controlled elements
const show = (elems) => {
  elems.forEach(elem =>
    elem.style.display = 'block'
  );
};

// hide controlled elements
const hide = (elems) => {
  elems.forEach(elem =>
    elem.style.display = 'none'
  );
};

// toggle controlled element visibility according to checkbox state
const toggle = (checkboxs, controlled) => {
  const emptys = [].filter.call(checkboxs, el => !el.checked);
  if (emptys.length == checkboxs.length) {
    show(controlled);
  } else {
    hide(controlled);
  }
};
.warning {
  color: red;
}
<input type='checkbox' value='1'>
<input type='checkbox' value='2'>
<input type='checkbox' value='3'>
<input type='checkbox' value='4'>

Please select at least one option to process further!

Comment: After going to the next page and coming back to this page, even if two of the boxes are checked there is still warning message. How can I fix it?
Comment: @A.A. You can execute `toggle(checkboxs, messages);` on page load


IndexError: list index out of range

Question: Alguém pode me ajudar? Estou recebendo o erro abaixo, entendi que o programa tenta acessar uma posição inexistente, porém não consigo corrigir...O código é um trabalho que tenho que completar e incrementar:

IndexError                                Traceback (most recent call
last)  in ()
12 cObject.computeMapping("corpus.txt")
13 # Chamada do algoritmo genetico
---> 14 listLog = geneticAlgorithm(cObject, message)
 in geneticAlgorithm(cypherObject,
mensagemCodificada, tamanhoPopulacao, numeroGeracoes, nMelhores)
26       # Fitness pode ser uma lista que armazena os valores de probabilidade
27       print("I antes do fitness:", i, "J antes do fitness:", j)
---> 28       fitness, mensagemTraduzida = cypherObject.computeLogProbability(mensagemCodificada, populacao[j])
29       print("I depois do fitness:", i, "I depois do fitness:", j, "\n")
30
IndexError: list index out of range

O trecho do código com o problema:
def geneticAlgorithm(cypherObject, mensagemCodificada, tamanhoPopulacao=10, numeroGeracoes=10, nMelhores=10):

  # Observacoes
  #   Guardar a melhor probabilidade (criar variavel)
  #   Criar uma variavel para armazenar a melhor traducao

  # Gerar uma populacao inicial
  populacao = []
  newPopulacao = []
  fitness = []
  listaLogProbabilidade = []
  melhorTraducao = []

  listaFitness = []
  for i in range(tamanhoPopulacao):
    listaCaracteres = list(cypherObject.getAlphabet())
    random.shuffle(listaCaracteres)
    resultado = "".join(listaCaracteres)
    populacao.append(resultado)
    print("\n", populacao) # teste para validar se a população está sendo gerada corretamente.

  for i in range(numeroGeracoes):
    # Calcular o fitness da populacao
    #print("Teste de for do i:", i)
    for j in range(tamanhoPopulacao):
      # Fitness pode ser uma lista que armazena os valores de probabilidade
      print("I antes do fitness:", i, "J antes do fitness:", j)
      fitness, mensagemTraduzida = cypherObject.computeLogProbability(mensagemCodificada, populacao[j])
      print("I depois do fitness:", i, "I depois do fitness:", j, "\n")

    # Selecionar os melhores valores de fitness (Posso ordenar os valores de fitness)
    # https://numpy.org/doc/stable/reference/generated/numpy.argsort.html
    # Ordenar valores e retornar os indices dos valores
    listaFitnessIndices =  np.argsort(listaFitness)[::-1]

    # Aplicar alteracoes na populacao
    #   Selecionar os N melhores
    #   Adicionar cromossomos mutados
    #   Cruzamento dos N melhores (Implementar depois)
    #   populacao[algum indice] = ['axcke'] (Mutacao do cromossomo)
    #       Sugestao: Trocar posicoes do vetor de lugar
    #         Ajudou a cair menos em maximos locais
    #   Gerar novos cromossomos de forma aleatoria (primeiro trecho do codigo)

    populacao = newPopulacao.copy()

  return listaLogProbabilidade, melhorTraducao

Answer: Você instanciou a lista aqui:
listaFitness = []
for i in range(tamanhoPopulacao):

Depois usou ela aqui:
listaFitnessIndices =  np.argsort(listaFitness)[::-1]

Mas neste meio caminho entre instanciar ela e usar você não a preencheu, acho que deve ter esquecido algum código, se no seu código for possível que em alguma situação a lista não seja preenchida não pode esquecer de verificar se a variável está preenchida com alguma coisa antes de usar ela.

IndexError: list index out of range


Matcher be_true ruby/rspec

Question: Estou começando a estudar sobre ruby/rspec seguindo um livro, mas não estou conseguindo progredir utilizando o matcher be_true.
Segue abaixo o erro:
BagOfWords#push is possible to put words on it (FAILED - 1)

Failures:

1) BagOfWords#push is possible to put words on it
  Failure/Error: expect(isTrue).to be_true
    expected true to respond to `true?`
  # ./spec/bag_of_words_spec.rb:12:in `block (3 levels) in <top (require d)>'

Finished in 0.015 seconds (files took 0.54403 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/bag_of_words_spec.rb:7 # BagOfWords#push is possible to put words on it

Comment: Qual versão do RSpec você está usando? Você pode tentar usar o `be_truthy` se for RSpec 3.
Comment: @cido18, pode incluir a resposta ao problema e aceitá-la? Isso evita perguntas que já estão respondidas nos comentários continuem sendo listadas como "Sem resposta".
Comment: Desculpa a demora em responder... Era isso mesmo, estou usando do RSpec 3, só  troquei e funcionou valeu.
Answer: De acordo com essa thread, os matchers be_true e be_false foram substituídos por be_truthy and be_falsey. Você ainda pode utilizar o be true e be false (note que são separados).
A diferença entre be true e be_truthy é que um teste utilizando o be_truthy irá passar caso o objeto não seja nil. O inverso acontece para o be false e be_falsey.
Da documentação oficial, temos:
expect(objeto).to be_truthy   # passa se o objeto não for nil ou false
expect(objeto).to be true     # passa somente se o objeto for true
expect(objeto).to be_falsy    # passa se o objeto for nil ou false
expect(objeto).to be false    # passa somente se o objeto for false

Exemplos
it { expect(true).to be true }        # passa
it { expect("string").to be true }    # falha
it { expect(nil).to be true }         # falha
it { expect(false).to be true }       # falha

it { expect(false).to be false }      # passa
it { expect("string").to be false}    # falha
it { expect(nil).to be false}         # falha
it { expect(true).to be false}        # falha

Answer: Resposta:
Qual versão do RSpec você está usando? Você pode tentar usar o be_truthy se for RSpec 3. – @Bruno dos Santos

Matcher be_true ruby/rspec


Erro no parametro nome do construtor ObjectParameter C#

Question: Quando passo uma variável string para o parâmetro do ObjetParameter da o seguinte erro.
<code>   string nomeParameter = sql.Substring(startPosition, stopPosition - startPosition);

   ObjectParameter parameter = new ObjectParameter(nomeParameter, parameters[contador]);
</code>

Additional information: The specified parameter name 'DESCRICAO ' is not valid. Parameter names must begin with a letter and can only contain letters, numbers, and underscores.

Se passar o parâmetro conforme abaixo, o erro não ocorre:
<code>   ObjectParameter parameter = new ObjectParameter("DESCRICAO", parameters[contador]);
</code>
Será que teria algum problema com Culture? mas o construtor do objeto não proporcionar colocar a Culture.
Answer: Não faço ideia do que você está fazendo, mas é bem claro, pela descrição do erro, que o problema é causado pelo espaço no final da string.
Remova mais um carácter do final da string que vai funcionar.
<code>string nomeParameter = sql.Substring(startPosition, stopPosition - startPosition + 1);
ObjectParameter parameter = new ObjectParameter(nomeParameter, parameters[contador]);
</code>
Comment: Realmente era isso amigo, coloquei o trim e deu certro, muito obrigado.
Comment: não me atentei a isso.. =(


R syntax of a second-order factor analysis. Does it work if one factor from the first order only consists of 2 items?

Question: I tried the following syntax:

MTX0 <- '

# First-order factors
StwR1t0_latent =~ S1pR1t0 + S2pR1t0 + S3pR1t0
RtwR1t0_latent =~ R1pR1t0 + R2pR1t0
TtwR1t0_latent =~ T1pR1t0 + T2pR1t0 + T3pR1t0 + T4pR1t0
GtwR1t0_latent =~ G1pR1t0 + G2pR1t0 + G3pR1t0

# Second-order factor
MuTex =~ StwR1t0_latent + RtwR1t0_latent + TtwR1t0_latent + GtwR1t0_latent

StwR1t0_latent ~~ RtwR1t0_latent
StwR1t0_latent ~~ TtwR1t0_latent
StwR1t0_latent ~~ GtwR1t0_latent
RtwR1t0_latent ~~ TtwR1t0_latent
RtwR1t0_latent ~~ GtwR1t0_latent
TtwR1t0_latent ~~ GtwR1t0_latent
'

#Modell berechnen für Effect Coding mit Meanstructure
fitMTX0<- cfa(MTX0, data=dataMaster012 , missing="fiml" , estimator="mlr" , meanstructure=T , auto.fix.first=F)
summaryCfa<-summary(fitMTX0, fit.measures=T, standardized=T, modindices=T)
summaryCfa

I get the following error message:
Error in modificationIndices(object, standardized = TRUE, cov.std = cov.std) :
  lavaan ERROR: could not compute modification indices; information matrix is singular
In addition: Warning messages:
1: In lav_fit_cfi_lavobject(lavobject = object, fit.measures = fit.measures,  :
  lavaan WARNING: computation of robust CFI failed.
2: In lav_fit_rmsea_lavobject(lavobject = object, fit.measures = fit.measures,  :
  lavaan WARNING: computation of robust RMSEA failed.
3: In sqrt(var.lhs.value * var.rhs.value) : NaNs produced
4: In lav_start_check_cov(lavpartable = lavpartable, start = START) :
  lavaan WARNING: starting values imply NaN for a correlation value;
                  variables involved are: StwR1t0_latent RtwR1t0_latent

Can anyone help with this problem? Is it possible that one of the first order factors only consists of 2 items?
Answer: I think the problem is that you are allowing your first-order factor residuals to correlate in addition to the first-order factors being indicators of a second-order factor. This leads to an underidentified model that also does not make sense conceptually (the second-order factor should account for all or at least most of the associations of the first-order factors). Deleting the last set of commands
StwR1t0_latent ~~ RtwR1t0_latent
StwR1t0_latent ~~ TtwR1t0_latent
StwR1t0_latent ~~ GtwR1t0_latent
RtwR1t0_latent ~~ TtwR1t0_latent
RtwR1t0_latent ~~ GtwR1t0_latent
TtwR1t0_latent ~~ GtwR1t0_latent
through which you specify the first-order factor residual correlations should help.
It is OK for a first-order factor to have only two indicators as long as that factor is substantially correlated with one of the other factors in the model (i.e., as long as that factor loads substantially on the g factor)
Comment: Thank you for your answer. Unfortunately, when I remove those commands, the model fit is not acceptable. My original model was without these last set of commands. After inspecting the modification indices, it seemed that the model could be improved by adding the last commands to the syntax. I understand that allowing the first-order factor residuals to correlate does not make sense conceptually and on top leads to an underidentified model . However, I'm wondering if there could be any other errors in the code or if you have any other recommendations to further enhance the model fit?


How to integrate audio recording in my PHP application or give me any idea regarding that type of application?

Question: I want to integrate voice recording in my PHP application?
Can anybody help me regarding this?
Thanks in advance.
Kanji
Comment: PHP or HTML will not have any control of the user's microphone, but Flash will.
Comment: Or a JavaApplet (if anyone still uses these nowadays)
Answer: You can't with only PHP (which handle SERVER, not client part ^^)
To record audio, you need an Flash || Java App (depends what you prefer...) Or maybe HTML5... I don't know if it works but may be a better way ^^
But remember that after it depends on the client computer and you mayb have difficulties or cases to handle ^^
But If you google it you will find some answers :
http://www.webmaster-talk.com/php-forum/173652-record-audio-using-php.html
Good Luck
Comment: Thanks for your answer but is any ready made tools of flash to control user's microphone?


Displaying fields from an entity reference of another entity's field

Question: I have three content types: compositions, recordings and artists. Compositions have entity references to artists for the field composer.  Recordings have entity references to compositions for the field composer and to artists for the field recording artist.
This is what I want to do:

I would like to display a page with a list of all the compositions and their composer (entity reference to Artist content type).  No problem here.
I would like another field with the field recording artist (an entity reference field in content type Recording) that is being referenced by an entity reference for the content type composition.  This is the problem.

I think the main problem is I'm trying to call a field from an entity reference's entity reference.  Is there a way to build that bridge?
Comment: did you check alternative solution? https://drupal.org/project/relation
Answer: You can use custom Displays to daisy-chain entity reference fields in this fashion (unless I misunderstand your requirements).
To do this...

Install the Entity View Mode module.
Then in configuration - system - entity view modes, create a new display for the entity in question and make sure it is attached to the recording type. Give your new display a self-explanatory name such as "embedded recording" to avoid confusion later.
Next, go to your recording entity's display mode settings, (eg 'manage display') and in the new "embedded recording" display make sure the Recording Artist entity reference field is visible.
Finally, go to your Composition entity's display mode settings (its 'manage display'), and for the Recording entity reference field, choose rendered entity as its format and pick "embedded recording" as its view mode (this option becomes available if you click on the little gear icon on the right hand side).

(Of course this would be far easier if you could add new display modes from the manage display setting! One day perhaps...)
Answer: I recently spent a lot of time on a very similar problem, so your question caught my eye. Note I'm new to Drupal, so take everything below with a good grain of salt.
If I understood correctly, you want the following architecture: Composition references Recording. Recording references Artist (let's call this Recording Artist).
And you want the following functionality. Firstly, you want to access the Recording Artist fields (e.g. name), given the Composition entity. Secondly, you want to add Recording Artist fields to the Composition entities' content object, so it could be printed out by templates along with other Composition fields. In other words, you want to make the Recording Artist fields accessible through the Composition entities' content object.
Consult this very nice answer by juhog. I believe it relates very well to what you're trying to do. It explains how to 'gain access to referenced entities' and how to append fields from referenced entities to referencing entities.
With this I was trying to nudge you in the right direction, because your question seemed confused (you have my sympathy, I've been there). I have limited experience so I will refrain from giving coding examples.
Answer: You just need to add a relationship of the third content type in the view and use a field of that content type in your field list, it will pick it up because when you add a relationship views will add a join statement in your sql query and you can use the columns of that joined table in your output.


Is there an MMC Snap-In available for Microsoft Baseline Security Analyzer?

Question: I tried looking up for it. Couldn't find one so far.
Answer: MBSA is a stand-alone tool, it's not part of the MMC.


Under what conditions do there exist non-constant meromorphic functions between general Riemann surfaces?

Question: The uniformization theorem answers this question for particular Riemann surfaces, but do we have a general theorem for this? Do we also get meromorphic functions that can separate points?
Answer: Given a complex Riemann surface $X$ and two points $x,y\in X$ there always exist a meromorphic function $f\in \mathcal M (X)$ which is holomorphic at both $x$ and $y$ and such that $f(x)\neq f(y)\in \mathbb C$.
a) If $X$ is non-compact you may even assume that $f\in \mathcal O(X)$ is holomorphic everywhere.
b) But if $X$ is compact then $\mathcal O(X)=\mathbb C$ and  $f$  will necessarily  have at least one pole .
These are highly non-trivial results going back to Riemann but of course his proofs do not meet contemporary standards of rigor: the first precise definition of "Riemann surface" goes back to Weyl's Die Idee der Riemannschen Fläche, published in 1913,  47 years after Riemann's death in 1866...
A high-brow explanation for these results is that a non compact Riemann surface is a Stein manifold (Behnke-Stein 1948) and that a compact Riemann surface is  a projective manifold, to which Serre's GAGA principle applies.
By far the best modern reference for Riemann surfaces is Otto Forster's book.


DHCP renewal can't go through because DHCP server is down

Question: To my experience, if a DHCP client tries to renew its lease, but the DHCP server is down, and after the lease time is over, there are two possible scenarios:

The client keeps the IP
The client goes back to INIT state

I've seen the two scenarios before with different vendors.
I can't find exactly which one is according to the standard.
Can someone help? Thanks!
Answer: Renewal usually happens before expiration - most often starting at 50% lease time.
If the lease eventually expires before a renewal can be DHCPACKed, the client must not continue to use the leased address. It must re-enter the INIT phase from before the lease.
See RFC 2131 section 4.4.5 for details.
Comment: Thank you for your answer.