ExpectedException attribute fails to show the expected result C#

Question: I have created a Class library .
I have created unit test project to unit test a class.
I have gone through a particular class called
  " ExpectedExceptionAttribute Class "

I tried to implement it. But if i enable the attribute my code always shows failed. Even if data are correct.
Class :
public class SampleTestClass
{
    public double CheckValidAmount(object Name , double amount)
    {
        try
        {
            if (amount == 1.0 && Name.ToString() == "RamKumar")
                return 10.0 - amount;
            else
                return amount;
        }
        catch (NullReferenceException ex)
        {
            return amount;
        }
    }
}

Unit Test Pass :
 [TestClass]
 public class SampleTester
 {
    [TestMethod]
    public void CheckValidAmount()
    {
        SampleTestClass sp = new SampleTestClass();
        double dd = sp.CheckValidAmount("RamKumar", 1.0);

        Assert.AreEqual(dd, 9.0);
    }
}

Fail :
[TestClass]
public class SampleTester
{
    [TestMethod]
    [ExpectedException(typeof(NullReferenceException))]
    public void CheckValidAmount()
    {
        SampleTestClass sp = new SampleTestClass();
        double dd = sp.CheckValidAmount(null, 1.0); // here i have mentioned NULL
        Assert.AreEqual(dd, 9.0);
    }
}

Expected to be passed :
[TestClass]
public class SampleTester
{
    [TestMethod]
    [ExpectedException(typeof(NullReferenceException))]
    public void CheckValidAmount()
    {
        SampleTestClass sp = new SampleTestClass();
        double dd = sp.CheckValidAmount("RamKumar", 1.0);

        Assert.AreEqual(dd, 9.0);
    }
}

Last one should be passed .. But it always shows Failed...
Reference :
   ExpectedExceptionAttribute Class :
   https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx

My VS shows this message :
         ![enter image description here][1]

Kindly guide me to understand this..  Thanks
https://i.stack.imgur.com/G2R1b.png
Answer: You should use ExpectedExceptionAttribute when you want to verify that your method throw the correct exception. In your case you don't throw any exception(from your method). Your method behavior is:
Given amount is 1.0
When I check amount with invalid name(NULL name)
Then I should get 1.0 as amount
As you can see from my GWT your method behavior doesn't expect to throw any exception. Therefore your test failed.
    [TestMethod]
    [ExpectedException(typeof(NullReferenceException))]// remove this attribute to pass the test
    public void CheckValidAmount()
    {
        SampleTestClass sp = new SampleTestClass();
        double dd = sp.CheckValidAmount("RamKumar", 1.0);

        Assert.AreEqual(dd, 9.0);
    }

You should use ExpectedExceptionAttribute when your method behavior is similar to:
Given amount is 1.0
When I check amount with invalid name(NULL name)
Then an ArgumentNullException should be raise
In this case your method is:
    public double CheckValidAmount(object Name, double amount)
    {
            if (Name == null)
                throw new ArgumentNullException("Name");

            if (amount == 1.0 && Name.ToString() == "RamKumar")
                return 10.0 - amount;

            return amount;
    }

And your test method should be:
    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void CheckValidAmount_CallWithInvalidName_Throw()
    {
        SampleTestClass sp = new SampleTestClass();
        sp.CheckValidAmount("RamKumar", 1.0);

    }

Answer: Your unit under test doesn't throw an exception, because you catch it inside. So the unit test doesn't see it.
Decide whether to throw the exception and test it like this or catch it and do not expect an exception.
Comment: @user1182268: you are still catching the exception in the unit under test. The unit test cannot see it. Either do not catch it or do not expect it in the test. What you do is like throwing a ball, catch it after 1 meter, then expect that it arrives 10 meters away.
Comment: Stefan i have tried with same NullReferenceException still it shows an error kindly check i have updated my ques with an image ..
Answer: This test...
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CheckValidAmount()
{
    SampleTestClass sp = new SampleTestClass();
    double dd = sp.CheckValidAmount("RamKumar", 1.0);

    Assert.AreEqual(dd, 9.0);
}

will never pass for the following implementation...
public double CheckValidAmount(object Name , double amount)
{
    try
    {
        if (amount == 1.0 && Name.ToString() == "RamKumar")
            return 10.0 - amount;
        else
            return amount;
    }
    catch (ArgumentNullException ex)
    {
        return amount;
    }
}

because the test is expecting a ArgumentNullException, however, that implementation doesn't throw the argument for the given implementation. Remove the ExpectedException attribute and your test should pass


How to get mapping for key-property in NHibernate?

Question: I'm trying to load nhibernate mapping for POCO classes at runtime with following lines:
var persistentClass = NHibernateHelper.Configuration.GetClassMapping( type );
var property = persistentClass.GetProperty( propertyName );

It works fine except it fails on property GroupId on a class with following mapping:
<class name="GroupPartnerInterest" table="[GROUP_PARTNER_INTERESTS]">
  <composite-id >
    <key-property name="GroupId" column="PAR_ID" />

If type == typeof(GroupPartnerInterest) persistentClass.GetProperty( "GroupId" ) fails with MappingException:

property not found: GroupId on entity
  GroupPartnerInterest"

I can see in debugger that key-properties from composite-id do not appear in persistentClass.properties.
Is there a way to get mapping for this key-property?
Thank you in advance.
Answer: The ordinary properties can be iterated through persistentClass.PropertyClosureIterator (that is including properties from base classes).
The key properties are in ( ( Component )( persistentClass.Identifier ) ).PropertyIterator.
So with this piece of code I'm able to search both key properties and ordinary properties:
var propserties = persistentClass.PropertyClosureIterator;
if ( persistentClass.Identifier is Component )
{
    properties = ( ( Component )( persistentClass.Identifier ) ).PropertyIterator
                    .Union( properties );
}

Property property
    = (
        from it in properties
        where it.Name == propertyName
        select it
      ).FirstOrDefault();


Detecting semi-duplicate records in Bash/AWK

Question: Right now I have a script that rifles through tabulated data for cross-referencing record by record (using AWK).  But I've run into a problem. AWK is great for line-by-line comparisons to run through formatted data, but I also want to detect semi-duplicate records. Unfortunately, uniq will not work by itself as the record is not 100% carbon-copy.
This is an orderly list, sorted by second and third columns.  What I want to detect is the same values in Column 3, 6 and 7
Here's an example:
JJ   0072  0128  V7589  N     22.35   22.35   0.00   Auth
JJ   0073  0128  V7589  N     22.35   22.35   0.00   Auth

The second number is different while the other information is exactly the same, so uniq will not find it solo.
Is there something in AWK that lets me reference the previous line?  I already have this code block from AWK going line-by-line. (EDIT awk statement was an older version that was terrible)
awk '{printf "%s", $0; if($6 != $7 && $9 != "Void" && $5 == "N") {printf "****\n"} else {printf "\n"}}' /tmp/verbout.txt

Comment: What do you want to do with all duplicate lines? Do you just want to keep the first line where `$3 $6 $7` are the same? The last one? Just mark it with `duplicate`?
Answer:
Is there something in AWK that lets me reference the previous line?

No, but there's nothing stopping you from explicitly saving certain info from the last line and using that later:
{
    if (last3 != $3 || last6 != $6 || last7 != $7) {
        print
    } else
        handle duplicate here
    }
    last3=$3
    last6=$6
    last7=$7
}

The lastN variables all (effectively) default to an empty string at the start then we just compare each line with those and print that line if any are different.
Then we store the fields from that line to use for the next.

That is, of course, assuming duplicates should only be detected if they're consecutive. If you want to remove duplicates when order doesn't matter, you can sort on those fields first.
If order needs to be maintained, you can use an associative array to store the fact that the key has been seen before, something like:
{
    seenkey = $3" "$6" "$7
    if (seen[seenkey] == 0) {
        print
        seen[seenkey] = 1
    } else {
        handle duplicate here
    }
}

Comment: This solution ended up working because of the order in the list. Thanks a bunch! What I ended up with was something like this `awk '{printf $0; if ((($6 != $7) || (last3 == $3 && last6 == $6 && last7 == $7 )) && $9 != "Void" && $5 == "N") {printf "****\n"} else {printf "\n"}; last3=$3; last6=$6; last7=$7;}' /tmp/verbout.txt`
Answer: one way of doing this with awk is
$ awk '{print $0, (a[$3,$6,$7]++?"duplicate":"")' file

this will mark the duplicate records, note that you don't need to sort the file.
if you want to just print the uniq records, the idiomatic way is
$ awk '!a[$3,$6,$7]++' file

again, sorting is not required.


IIS7 folder permissions

Question: I build a basic WCF service that I now want to host in IIS7 under Windows Server 2008 R2.
I added the service as an application under the default web site but whenever i try to run the application I get the following error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Config Error - Cannot read configuration file due to insufficient permissions

The only way I can get this service working is if i choose to "connect as" the server Administrator when adding the service. the "application user (pass-through authentication)" option does not seem to work.
Could anyone help me out, I've just started using IIS7 and have no idea what to do... Thanks
Answer: Its a permissions issue, and its a two fold problem you need to solve (depending on what your goals are).

You need to determine if this site should be anonomous, or if you want a password.
1a.  If you want authentication, you need to determine if you want it to be integrated or basic.  If you go with basic, you'll want an SSL cert.  if you go with integrated, bear in mind by default NTLM is limited to a single hop for authentication.  So if you need the user logging into, to access a remote file share or a SQL server (authenticating as themselves not as the app pool), you'll need kerberos (which has its own level of complications)
You need to make sure your NTFS permissions are setup for the directory your pointing IIS at.
Answer: IIS should have given you good error message on where the issue is. If you are still finding it difficult to trace the error refer the blog Troubleshooting HTTP 500.19 Errors in IIS 7
Answer: well, you could start by checking what permissions your directory and files have and then adding what is needed. On a default 2008 r2 install Users group has read and list permission under inetpub, so that definitely works, although it's probably not that secure.
Comment: Same problem here looking at test IIS7 on Windows 2008 R2. You're right that the local Users group has read permissions and equally that it doesn't sound too secure
Answer: For the site you've set up, go to Authentication and choose the Edit action for Anonymous Authentication. The identity will be either a specific user or the application pool identity - whichever one is set up will tell you what user you need to grant filesystem access to the directory where you've hosted your WCF service.
Answer: you could try:
IIS->Sites->(DefaultWebSite or your Site)->Feature View->Double Click Error Pages->Edit Feature Settings -> select Detailed Errors -> press OK.
else there is a post abour debugging WCF Services here:
Detailed Errors not working for WCF Service in IIS

IIS7 folder permissions


How to list kubernetes pods with age less than a specific period

Question: I am writing a script that runs each minute and looks for newly created pods. The script executes commands within these pods.
I need to add the missing part to my current solution which looks like this:
while true; do
  pods= $(kubectl get pods --field-selector status.phase=='Running' ---------- someting should be here ----------)
    for pod in ${pods[@]} ; do
    actions
    done
  sleep 60;
done

Comment: I'd recommend restructuring your images so that something like an `ENTRYPOINT` wrapper script does the required setup on its own.  Since pods can come and go outside your control the approach you describe here can be a little bit fragile.
Comment: Thanks for reply @DavidMaze. I don't have any access to the images so all I could do is to monitor what pods are alive and those who are newly created each 60s and make the difference between arrays. Still testing.
Answer: My current solution looks like this. Please feel free to review and enhance.
current_pods=$(kubectl get pods | grep "Running" | awk '{print $1}')
# attach existing pods
for pod in $current_pods; do
  do-something
done
# attach newly created pods each 60s
while true; do
  new_pods=$(kubectl get pods | grep "Running" | awk '{print $1}')
    for pod in $new_pods; do
      if [[ ! " ${current_pods[@]} " =~ $pod ]]; then
        do-something
      fi
    done
  current_pods=$new_pods
  sleep 60;
done

Comment: I also can't use --field-selector because it was not supported yet in the version I'm working on.
Answer: I'd suggest to make use of Kubernetes watch and/or events APIs.
Concrete implementation depends on what events you are actually interested in.
What do you mean by "newly created pods"?

This command will stream you the names of new pods entering the Running phase.
# --watch-only can be replaced by --watch
# --watch will show all current pods in Running state + stream changes
# --watch-only will just stream changes
kubectl get pods --field-selector status.phase=='Running' \
  --watch-only -ojsonpath='{.involvedObject.name}{"\n"}'

But this might be not what you want.
"Running" phase refers to a pod state, not to a state of related containers.
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase
As a result you can get the following output.
# from API server point of view all these pods are in Running phase,
# regardless of some containers failing
kubectl get pods --field-selector status.phase=Running --watch-only

NAME         READY   STATUS             RESTARTS   AGE
pod1         2/2     Running            30         31h
pod2         1/2     Running            30         31h
pod2         1/2     Error              30         31h
pod2         1/2     CrashLoopBackOff   30         30h

This command will stream you the names of newly scheduled pods (i. e. scheduling decision has been dispatched to a kubelet, but pod's containers may not be running yet).
This can be viewed as a moment of actual pod object creation, but doesn't say anything about whether the pod conainers have succesfully started.
kubectl get events --field-selector involvedObject.kind=Pod,reason=Scheduled \
  --watch-only -ojsonpath='{.involvedObject.name}{"\n"}'

This command will stream you the names of new pods which have started successfully.
Technically it means that certain conditions are met, like "all containers in the Pod are ready" and "the Pod is able to serve requests and should be added to the load balancing pools of all matching Services".
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-conditions
# as above: you can replace --watch-only by --watch
# --watch will show the pods that are already running successfully + stream newcomers
# --watch-only will just stream newcomers
kubectl get pods --field-selector status.phase=Running --watch-only -o json | \
  jq '. | select (.status.conditions[] | select (.type=="Ready" and .status=="True")) | .metadata.name'

Using these examples you could construct necessary conditions according to your needs and run a simple command like this.
# kubectl watch will timeout in a period of time
# timeout value is configured by API server param
# --min-request-timeout [default=1800s]
# also if API server restarts, the connection will be dropped
# so we still need 'while true' here
while true; do
  kubectl get events --field-selector involvedObject.kind=Pod,reason=Scheduled \
    --watch-only -ojsonpath='{.involvedObject.name}{"\n"}' | \
  while read pod; do
    echo "$pod"
  done
done

Frankly this approach doesn't guarantee you 100% consistency. You may miss some events with --watch-only (say, when the client restarts), as well as you may have duplicates with --watch.
For simple usecases keeping a short-lived vocabulary of proccessed pods is probably fine.
For more sophisticated tasks you could turn to advanced usage of watch APIs.
There is a good article to start with.
https://learnk8s.io/real-time-dashboard
Comment: Hi @Olesya, thank you very much for the thorough answer. What I'm seeking by "newly" is the pods that didn't existed in the last loop of the script. The pods are single container and I need to attach an agent to the container when it is running this is why I used "Running".


Using Piwik for a Single Page Application

Question: Building a single page / fat client application and I'm wondering what the best practice is for including and tracking using http://piwik.org/
I'd like to use Piwik in a way that is architecturally sound and replacable with a different library in the future.
It seems that there are two basic options for tracking with Piwik:

Fill up a global _paq array with commands, then load the script (it's unclear to me how to record future "page" views or change variables though)
Get and use var myTracker = Piwik.getTracker()

_paq approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
  window._paq = window._paq || [];
  _paq.push(['setDocumentTitle', pageName]);
  _paq.push(["trackPageView"]);
}
myApp.loadAnalytics()

// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else

.getTracker() approach:
myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
  myApp.tracker = myApp.tracker || Piwik.getTracker('https://mysite.com', 1);
  myApp.tracker.trackPageView(pageName);
}
myApp.loadAnalytics()

// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else

Are these approaches functionally identical? Is one preferred over another for a single page app?
Answer: The full solution using .getTracker looks like this:
https://gist.github.com/SimplGy/5349360
Still not sure if it would be better to use the _paq array instead.
Comment: This abstraction using .getTracker works, is pretty neat in terms of isolating the application from the Analytics library, and was put into live code. I'm going to call this the answer for now, but I'd like to know if the creators have any guidelines for when to use _paq VS .getTracker() some day :)
Answer: To have the tracking library used (eg. piwik) completely independent from your application, you would need to write a small class that will proxy the functions to the Piwik tracker. Later if you change from Piwik to XYZ you can simply update this proxy class rather than updating multiple files that do some tracking.
The Async code is a must for your app (for example a call to any 'track*' method will send the request)
Comment: What is "the async code"? To me both methods could be implemented asynchronously, so I'm confused.
Comment: I actually pored over this in some detail before asking my question. This documentation page mentions both of the methods under consideration.


mysql group by error

Question: below is a query I'm using
SELECT
  `names`, sum(cashin.amount) as amountin,
  sum(cashout.amount) as amountout,
  (sum(cashin.amount) - sum(cashout.amount)) as total
FROM (`client`)
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0
GROUP BY `client`.`id`

Problem is I get an error:

Invalid use of group function

Replacing the function in where clause with field alias 'total' I still get an error:

Unknown column total

How can this query be fixed?
Answer: Use HAVING instead of WHERE, and put the GROUP BY names clause instead of GROUP BY id before the HAVING clause like so:
SELECT
  `names`,
  sum(cashin.amount) as amountin,
  sum(cashout.amount) as amountout,
  (sum(cashin.amount) - sum(cashout.amount)) as total
FROM client
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
GROUP BY names
HAVING (sum(cashin.amount) - sum(cashout.amount)) < 0

Answer: Try this ::
SELECT
  `names`,
  sum(cashin.amount) as amountin,
  sum(cashout.amount) as amountout,
  (sum(cashin.amount) - sum(cashout.amount)) as total
FROM client
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
GROUP BY names
HAVING total < 0

Answer: As an alternative to using a HAVING clause, you can wrap your query in a SELECT statement and then place the filter in a WHERE clause:
select names,
  amountin,
  amountout,
  total
from
(
  SELECT
    `names`,
    sum(cashin.amount) as amountin,
    sum(cashout.amount) as amountout,
    (sum(cashin.amount) - sum(cashout.amount)) as total
  FROM client
  INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id`
  INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id`
  GROUP BY names
) src
where total < 0

Answer: you make an alias of this
   (sum(cashin.amount) - sum(cashout.amount)) as total

as total so why u dont use it here ?
  WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0

replace it by
     WHERE total < 0

and this
 FROM (`client`)

just use
  FROM `client`

and this
  (sum(cashin.amount) - sum(cashout.amount)) as total  // line 4

replace it by
   (amountin - amountout) as total

and it will work good for you.

mysql group by error


Why is Faile so much faster than The Simple Chess Program (TSCP)? (Chess engine optimization)

Question: I hope this isn't too much of an arbitrary question, but I have been looking through the source codes of Faile and TSCP and I have been playing them against each other. As far as I can see the engines have a lot in common, yet Faile searches ~1.3 million nodes per second while TSCP searches only 300k nodes per second.
The source code for faile can be found here: http://faile.sourceforge.net/download.php. TSCP source code can be found here: http://www.tckerrigan.com/Chess/TSCP.
After looking through them I see some similarities: both use an array board representation (although Faile uses a 144 size board), both use a alpha beta search with some sort of transposition table, both have very similar evaluate functions. The main difference I can find is that Faile uses a redundant representation of the board by also having arrays of the piece locations. This means that when the moves are generated (by very similar functions for both programs), Faile has to for loop through fewer bad pieces, while maintaining this array costs considerably fewer resources.
My question is: why is there a 4x difference in the speed of these two programs? Also, why does Faile consistently beat TSCP (I estimate about a ~200 ELO difference just by watching their moves)? For the latter, it seems to be because Faile is searching several plies deeper.
Answer: Short answer: TSCP is very simple (as you can guess from its name). Faile is more advanced, some time was spent by developers to optimize it. So it is just reasonable for Faile to be faster, which means also deeper search and higher ELO.
Long answer: As far as I remember, the most important part of the program, using alpha beta search (part which influences performance the most), is move generator. TSCP's move generator does not generate moves in any particular order. Faile's generator (as you noticed), uses piece list, which is sorted in order of decreasing piece value. This means it generates more important moves first. This allows alpha-beta pruning to cut more unneeded moves and makes search tree less branchy. And less branchy tree may be deeper and still have the same number of nodes, which allows deeper search.
Here is a very simplified example how the order of moves allows faster search. Suppose, last white's move was silly - they moved some piece to unprotected position. If we find some black's move that removes this piece, we can ignore all other, not yet estimated moves and return back to processing white's move list. Queen controls much more space than a pawn, so it has more chances to remove this piece, so if we look at queen's moves first, we can more likely skip more unneeded moves.
I didn't compare other parts of these programs. But most likely, Faile optimizes them better as well. Things like alpha-beta algorithm itself, variable depth of the search tree, static position analysis may be also optimized.
Comment: Thanks for the answer. I can share some research I did into it in the meantime. I think I found that perhaps the biggest reason, while what you said is a good reason, is that while it seems at first TSCP is using transposition tables, it actually isn't. It creates a Zobrist key but only uses it for draw by repetition. This means that it is potentially analyzing some positions many times. From what I've read, transposition tables can compose a 3-4x performance increase.
Answer: TSCP has not hash tables (-75 ELO).
TSCP has not Killers moves for ordering (-50 ELO).
TSCP has not null move (-100 ELO).
TSCP has a bad attack function design (-25 ELO).
In these 4 things you have about a difference of 250 points ELO. This will increase the number of nodes per second but you can not compare nodes per second on different engines as programmers can use a different interpretation of what is a node.


How to join all exported results' tables to ONE table with SQL Server

Question: I would like to add these tables into ONE table with many rows with Temporary Table

DECLARE @Week int,
    @Year int
SET @Week = 1
SET @Year = 2014
WHILE @Week <= 52 BEGIN
    SELECT  GetTotalPrice.[LocationID],
        SUM(GetTotalPrice.TotalPrice) AS TotalPrice,
        @Week AS WeekNumber
    FROM GetTotalPrice
    SET @Week = @Week + 1
END

Comment: Just craete table before `While`, change `Select` to `Insert` and output data after `While`. Thats it.
Comment: @Darka: Could you please give me a clear answer in the "Answer you question" below?
Comment: Your code get the same values for 52 times, changing only the week number, is that what you want?
Comment: @Serpiton: I just would like to merge all tables to one table. That's it.
Answer: I think I understood your problem right. You have multiple tables which you need to merge into one. If that is true you can do the following changes in your code
DECLARE @Locations TABLE
(
LocationID INT,
TotalPrice DECIMAL,
WeekNumber INT
)
DECLARE @Week int,
    @Year int
SET @Week = 1
SET @Year = 2014
WHILE @Week <= 52 BEGIN
    INSERT INTO @Locations
    SELECT  GetTotalPrice.[LocationID],
        SUM(GetTotalPrice.TotalPrice) AS TotalPrice,
        @Week AS WeekNumber
    FROM GetTotalPrice
    SET @Week = @Week + 1
END

SELECT * FROM @Locations

Comment: @PMay1903: Looping is rarely an optimal solution, though. You might get better suggestions if you showed how `@Week` and `@Year` were used in the query. (My guess is the real query has a WHERE clause that uses those variables for filtering.)
Comment: That's awesome. Your answer is totally correct to solve my problem. Thank you very much.
Comment: @AndriyM: I appreciate all your help but in that case that It should be like that...


Sendmail and .

Question: I have a Sendmail MTA running version 8.15.2 on Debian 9 that relays mail for a single domain. My issue is that when the server encounters a . at anytime after the headers and the DATA command, it terminates the mail connection, as it should according to RFC 5321. This could occur prior to the end of a boundary for a multipart message, effectively truncating any other content including attachments. (eg. if a . was encountered within an HTML multipart with attachments, all remaining HTML content including any other multipart objects such as attachments would be truncated).
My confusion is that other MTAs (eg. Exchange) for other organizations will receive the same message and process the content without any truncation. (I am assuming they are waiting for an EOF instead.)
I have attempted the define(confIGNORE_DOTS',true') in the m4 sendmail configuration with no luck, however, I understand this configuration is essentially ignored during server operations, and is intended for local transmission from the command line.
My only other option that I can think of would be to encode any . to hex (ie. 2E) prior to Sendmail's processing, however I have not been able to find any examples on the web.
I am assuming other MTAs such as Postfix or Exim would run into the same issue.
If necessary, I can post Sendmail's configuration file and server runtime parameters.
Any help is truly appreciated.
Comment: Where is this message coming from?
Comment: The message I am looking into specifically comes from another entity (ie. outside the corporate network) with a 2007 Exchange server relayed through Barracuda's AWS hosted spam filters. Exchange and Barracuda both relay the message, but Sendmail is the one truncating at the "."
Comment: It certainly sounds like whatever is delivering the message to you has screwed up, so you probably should start there.
Comment: To confirm my understanding of the RFC, the MTAs relaying mail to Sendmail SHOULD HAVE added a secondary dot to avoid the early . truncation, correct?
Comment: More like MUST, but yes.
Answer: sendmail (SMTP/MTA) server masks "single dot" lines in the message itself in RFC described way.
Most likely you do not provide some important "detail".
RFC-5321 section 4.5.2

4.5.2.  Transparency

Without some provision for data transparency, the character sequence
"." ends the mail text and cannot be sent by the user.
In general, users are not aware of such "forbidden" sequences.  To
allow all user composed text to be transmitted transparently, the
following procedures are used:

o  Before sending a line of mail text, the SMTP client checks the
first character of the line.  If it is a period, one additional
period is inserted at the beginning of the line.

o  When a line of mail text is received by the SMTP server, it checks
the line.  If the line is composed of a single period, it is
treated as the end of mail indicator.  If the first character is a
period and there are other characters on the line, the first
character is deleted.

Sendmail and .


Why are the performance of LASSOs implemented via glmnet in R going down after cross-validation?

Question: This question is a follow-up to this question I asked here last week. I got an important and useful answer to it, but what that led to was surprising. And once again, here is a link to the GitHub Repo for this project.
I am running N LASSO Regressions, one for each of N datasets I have in a file folder to serve as one of several Benchmark Variable Selection Algorithms whose performance can be compared with that of a novel Variable Selection Algorithm being proposed by the principal author of the paper we are collaborating on right now. I originally ran my N LASSOs via the enet function, but tried to replicate my findings via glmnet and lars, each selected different variables. The way I had previously set up my code to run them using the glmnet function was fundamentally misusing the s argument in the coef() function in the middle of the following code block:
set.seed(11)
glmnet_lasso.fits <- lapply(datasets, function(i)
               glmnet(x = as.matrix(select(i, starts_with("X"))),
                      y = i$Y, alpha = 1))

# This stores and prints out all of the regression
# equation specifications selected by LASSO when called
lasso.coeffs = glmnet_lasso.fits |>
  Map(f = \(model) coef(model, s = .1))

Variables.Selected <- lasso.coeffs |>
  Map(f = \(matr) matr |> as.matrix() |>
       as.data.frame() |> filter(s1 != 0) |> rownames())
Variables.Selected = lapply(seq_along(datasets), \(j)
                            j <- (Variables.Selected[[j]][-1]))

Variables.Not.Selected <- lasso.coeffs |>
  Map(f = \(matr) matr |> as.matrix() |>
        as.data.frame() |> filter(s1 == 0) |> rownames())

write.csv(data.frame(DS_name = DS_names_list,
             Variables.Selected.by.glmnet = sapply(Variables.Selected, toString),
Structural_Variables = sapply(Structural_Variables, toString),
             Variables.Not.Selected.by.glmnet = sapply(Variables.Not.Selected, toString),
Nonstructural_Variables = sapply(Nonstructural_Variables, toString)),
  file = "LASSO's Selections via glmnet for the DSs from '0.75-11-1-1 to 0.75-11-10-500'.csv",
  row.names = FALSE)

Because for glmnet, the s is the lambda penalty term in each LASSO itself, and this is not the case for enet or lars. That meant I was arbitrarily setting the L1 Norm for every LASSO, not using cross-validation. So, I realized my error, and wrote this adjusted code which works:
grid <- 10^seq(10, -2, length = 100)
set.seed(11)     # to ensure replicability
glmnet_lasso.fits <- lapply(X = datasets, function(i)
               glmnet(x = as.matrix(select(i, starts_with("X"))),
                      y = i$Y, alpha = 1, lambda = grid))

# Use cross-validation to select the penalty parameter
system.time(cv_glmnet_lasso.fits <- lapply(datasets, function(i)
  cv.glmnet(x = as.matrix(select(i, starts_with("X"))), y = i$Y, alpha = 1)))

# Store and print out the regression equation specifications selected by LASSO when called
lasso.coeffs = cv_glmnet_lasso.fits |>
  Map(f = \(model) coef(model, s = "lambda.min"))

Variables.Selected <- lasso.coeffs |>
  Map(f = \(matr) matr |> as.matrix() |>
        as.data.frame() |> filter(s1 != 0) |> rownames())

Variables.Selected = lapply(seq_along(datasets), \(j)
                            j <- (Variables.Selected[[j]][-1]))

But when I started re-running these glmnet LASSOs on all 260,000 of my datasets again, 5 or 10k at a time, I noticed their performances are noticeably poorer! For example, just running them both ways on the first 10 of my 260k datasets which are located in the folder called "ten" in the Repository, the original way I had it with an arbitrary lambda of 0.1 chosen for each of the 10 LASSOs, the resulting performance metrics were:
> performance_metrics
  True.Positive.Rate  True.Negative.Rate  False.Positive.Rate  Underspecified.Models.Selected
                   1                0.97                 0.03                               0
  Correctly.Specified.Models.Selected  Overspecified.Models.Selected
                                    4                             6
  All.Correct..Over..and.Underspecified.Models  Models.with.at.least.one.Omitted.Variable
                                            10                                          0
  Models.with.at.least.one.Extra.Variable
                                        6

But when I re-do it the proper way using cross-validation, these are my performance metrics:
> performance_metrics
  True.Positive.Rate  True.Negative.Rate  False.Positive.Rate  Underspecified.Models.Selected
                   1               0.819                0.181                               0
  Correctly.Specified.Models.Selected Overspecified.Models.Selected
                                    1                             9
  All.Correct..Over..and.Underspecified.Models  Models.with.at.least.one.Omitted.Variable
                                            10                                          0
  Models.with.at.least.one.Extra.Variable
                                        9

Have a made another mistake in my code, but a different one this time somehow?
p.s. A quote from the README:

Each dataset name is of the general form n1-N2-N3-N4.csv; where
n1 is one of the following 4 levels of multicollinearity between the set all true regressors (structural variables/factors) for that dataset: 0, 0.25, 0.5, 0.7;
N2 is the number of structural variables in that dataset (this is known with certainty for each synthetic dataset by construction which is the reason to create them via Monte Carlo methods in order to use them to explore the properties of new algorithms or estimators and/or compare the performances of such things against standard Benchmarks as I am doing here for this project) which can be any one of 13 different possible values from 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15;
N3 is the Error Variance which is one of the 10 following monotonically increasing (integer) values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10; and lastly,
N4, which Dr. Davies decided to set to 500 for this project, is the number of different synthetic datasets with all three of the aforementioned character traits fixed to generate randomly. Just to make that last point a little clearer, 4 * 13 * 10 * 500 = 260,000 datasets.
Comment: I would worry about using your own single grid for the `lambda` values to evaluate over all data sets. The `glmnet()` function can do a pretty good job of finding a grid and adapting the grid to the data set at hand. Also, don't overestimate the ability of LASSO to find the "true" model; it often can't. If `lambda.min` is returning too many non-zero coefficients for this type of data, consider using `lambda.1se` from `cv.glmnet()` in parallel for comparison.
Comment: Don't forget that the superiority of `lambda.1se` is most likely to be seen when the true model has few non-zero coefficients, as seems to be the case here by construction, and when it's important to try to identify the "true" model (which you often can't do with messy real-world data, anyway). For predictive models you might be better off with `lambda.min` in LASSO even if that includes some "false positive" coefficients, or with elastic net or even ridge regression.
Comment: @EdM in retrospect, I think you are right. What I did was ran my code without any grid explicitly specified, then with the generic sized explicit grid you see here for the first subset of 5,000 datasets and got identical performance metrics and variables selected, so I just kept it in thinking it would make it slightly more readable for journal referees and whatnot.
I will go ahead and try lambda.lse and compare the results, thanks again!
Comment: @EdM I just uploaded 3 things to the Stage 2 Results folder in the Repo, two csvs and an xlx file, the latter is called glmnet's selections with vs without grid explicitly included for the DSs from '0.75-15-1-1 to 0.75-15-10-500 and its name is self explanatory. But I am sure you trust me enough to write a comparative IF function in Excel. I compared the variables selected for a different set of 5k datasets both with and without the grid argument included and they were identical for all 5k cases.
Comment: @EdM using lambda.1se instead makes an ENORMOUS difference, wow! And to the point in question, yes, its performance scores are slightly superior to the version I ran originally which was arbitrary on the 1st subset of 10k datasets, and the number of correctly specified models overall it selects is much higher as well.
Comment: @EdM yes of course, this is why I included a long paragraph from the README as a post script on this question explaining that there are only ever a minimum of 3 up to a maximum of 15 structural variables (true factors) in each dataset out of a total of 30 candidate variable columns. For me, the problem is determining how many does "only a few" structural variables mean? It isn't obvious to me how to figure that out.

Also, lambda.1se did WAY better than lambda.min. But it performed a bit worse than my original code with the lambda hard coded as 0.1. Strange.
Comment: @EdM I just put up another follow up about the fact that the performance is still worse than the original version which was arbitrary if you care to take a crack at it or let me know how I can improve the question: https://stats.stackexchange.com/questions/617875/interpreting-variable-selection-performance-on-n-datasets-using-n-glmnet-lassos
Answer: There is some statistical content underlying this question, having to do with what choice to make for the penalty factor when fitting a LASSO model. If you know that the "correct" model is sparse, lambda.min returned by cv.glmnet() might not be the best choice.
To illustrate the points in my comment, examine what happens with a single data set. First, let cv.glmnet() work on its own.
lDat <- read.csv("~/Downloads/0-3-1-1.csv",skip=2)
library(glmnet)
set.seed(11)
cv0311 <- cv.glmnet(x=as.matrix(lDat[2:31]),y=lDat$Y)
cv0311
#
# Call:  cv.glmnet(x = as.matrix(lDat[2:31]), y = lDat$Y)
#
# Measure: Mean-Squared Error
#
#     Lambda Index Measure      SE Nonzero
# min 0.03104    39  0.9792 0.06091      16
# 1se 0.13752    23  1.0316 0.05846       3

In this case, if you use minimum mean-square error as the criterion, you get lambda.min = 0.03104 and retain 16 of the 30 coefficients. There is no absolute necessity to make that choice, however. The same single invocation of the function also provides the highest penalty within one standard error of the minimum, for lambda.1se = 0.13752 and only 3 non-zero coefficients. If you know that the "correct" model is sparse (as these data seems to be constructed), then lambda.1se can be more appropriate.
I suspect that the arbitrary penalty values in your prior invocations of LASSO-related functions came closer to the lambda.1se values and thus retained fewer coefficients than what you have found with lambda.min.
The next point is more specifically about implementation. If you pre-specify the grid of lambda values to evaluate instead of letting the function choose, you might be getting into trouble.
grid <- 10^seq(10, -2, length = 100)
set.seed(11)
cv0311FixedGrid <- cv.glmnet(x=as.matrix(lDat[2:31]),y=lDat$Y,lambda=grid)
cv0311FixedGrid
#
# Call:  cv.glmnet(x = as.matrix(lDat[2:31]), y = lDat$Y, lambda = grid)
#
# Measure: Mean-Squared Error
#
#      Lambda Index Measure      SE Nonzero
# min 0.03054    96  0.9792 0.06095      17
# 1se 0.12328    91  1.0227 0.05798       3

You retain about the same number of coefficients at each of the final lambda choices as previously, but note that the Index in your grid at which you identify those choices is near the top of your 100 values, unlike what happens when you just let cv.glmnet() specify its own data-driven grids. I would worry that your best penalty choices will be "off the grid" with the same fixed grid on other data sets.
Comment: The problem with grids being too coarse or not covering a wide enough range is also very common in applications of kernel methods such as the SVM.  I use Nelder-Mead simplex instead, I wonder why gradient free optimisation methods other than grid search are not more widely used.


polynomial exercise

Question: I have the polynomial $$P(x)=(a^2-a)x^3+(a-1)x^2+(a^2-3a+2)x+a-1$$ and the function $f(a)=$ "degree of $P(x)$".

Find the domain of $f(a)$
Find the $\lim_{a\to 1}{f(a)}$ and $\lim_{a\to 0}{f(a)}$

But for $a=1$ the polynomial doesn't have a degree, so how can I find the mentioned above?
Comment: Do you have a convention for the degree of the zero polynomial?
Answer: To discuss about limit at $c$, we do not need the function value at that value to exists.
Just answer the following question:
what is $\lim_{a \to 1^-} f(a)$?
what is $\lim_{a \to 1^+} f(a)$?
If they are equal, that is the answer to $\lim_{a \to 1} f(a)$
Optional interesting reading:
The degree of zero polynomial is usually defined to be $-\infty$.

polynomial exercise


I'm looking for a way to force the migration to process entries with identical keys

Question: The full scenario is as follows:
We have two entities (Foo and Bar). Foo has a multi-value entity reference field to Bar entities.
The migration source outputs each Foo-Bar pair in a single CSV line (manual aggregation is not possible because there are thousands of entries).
My plan was to put several entries with identical keys and using the --update flag and a custom process plugin, update the entry's entity by adding the Bar entity to the existing Bar entities instead of replacing them.
When I tried to put two entries with identical keys in a single CSV file, the migration module processed the first entry and ignored the second.
My understanding of the migration module is that each entry is assigned a key and that that key is mapped to the entity that was created by the migration.
Is there a way force the migration module to process multiple entries with identical keys?
I've asked the question on drupal.org as well
Answer: You can do this with drush migrate-import --update. See the migrate_tools module.
Comment: the drush `migrate-import --update` processes each key only once.
Comment: o I see what you're saying, what you're asking cannot be done without some work on your end. It is usually expected that the source data has unique keys. If not, you'll need to generate unique keys yourself.


How to recall a method n amount of times?

Question: trying to recall a method here (so that it generates different results 100 times using a for loop)
Here is what I have in the main method:
for (int i = 0; i<99; i++) {
            double scaleFitness = ScalesSolution.ScalesFitness(randomNumberFile);
            System.out.print(scaleFitness + ", ");
        }

and this is the method I'm trying to call 100 times (in the ScalesSolution class):
public static double ScalesFitness(ArrayList<Double> weights)
    {
        int n = scasol.length();
        double lhs = 0.0, rhs = 0.0;
        if (n > weights.size()) return(-1);

        for(int i = 0; i < n; i++){
            if(scasol.charAt(i) == '0'){
                lhs += weights.get(i);
            }
            else if (scasol.charAt(i) == '1') {
                rhs += weights.get(i);
            }
        }
        return(Math.abs(lhs-rhs));
    }

This however prints the same value 100 time over.
Comment: But aren't you passing the same value in every time?  You should get the same response every time.
Comment: It sure looks like `ScalesFitness` _ought_ to return the same value when passed the same input.
Comment: BTW, for 100 print you need `i < 100` instead of `i < 99`.
Comment: Java convention is to start method names with lowercase letters.  Also, what exactly do you want to randomize?
Comment: If I rerun the program, different results are generated. (but obviously the same result is printed 100 times over)
Comment: A fitness solution to a set of weights that are in a text file. The ScalesFitness generates different fitness results when rerun every time.
Answer: Your method "ScaleFitness" and the output of this method is dependent on two variables:

weights

scasol

It seems these variables stay the same for the whole run of the program. So it is not surprising that your output is the same.
If you want a different output for each run of your loop. You need to reset at least one of these variables to a new value.
Btw. methods in Java always start with a lowercase. Classes start with an uppercase.
Comment: Of course.Because these values are set with new values, and I would guess that they are set in a randomized way.
If you could post the code, where these values are set, we can verify that assumption.
Comment: I understand what you're saying, but if I rerun the whole program, the  ScalesFitness method generates a different result to the previous one.
Answer: public static double scalesFitness(ArrayList<Double> weights)
{
    double randomElement = weights[((int) (Math.random() * weights.size()))];

This will enable you to retrieve a random element in the array, for manipulation later.


Salvar dados de uma textbox em uma classe e exibir em uma datagrid

Question: Estou fazendo um programa para cadastro simples, sem utilizar banco de dados, só com array. O programa já estava funcional quando eu notei que a parte mais importante estava errada pois eu não tinha entendido direito. Eu acabei não utilizando a classe Pessoa que criei, e sim acabei manipulando tudo com textbox e a datagrid que eu exibo os cadastros.
Não consegui entender direito como puxar os dados da classe Pessoa (que eu coloquei o código abaixo) para quando eu utilizar uma textBox para salvar os dados nessa classe, em um array. E com esses dados salvos, exibir cada cadastro em uma linha da datagrid.
List<Pessoa> list = new List<Pessoa>();

        public class Pessoa
    {

        //atributos privados da classe Pessoa
        private string nome;
        private string endereço;
        private string ano_nascimento;
        private string telefone;

        //propriedades públicas, read-only
        public Pessoa(string nome, string endereço, string ano_nascimento, string telefone)
        {
            this.nome = nome;
            this.endereço = endereço;
            this.ano_nascimento = ano_nascimento;
            this.telefone = telefone;
        }

        //método construtor get(pega a informação) e set(grava)
        public string getNome()
        {
            return nome;
        }

        public string getEndereço()
        {
            return endereço;
        }

        public string getAno_nascimento()
        {
            return ano_nascimento;
        }

        public string getTelefone()
        {
            return telefone;
        }

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

        public void setEndereço(string endereço)
        {
            this.endereço = endereço;
        }

        public void setAno_nascimento(string ano_nascimento)
        {
           this.ano_nascimento = ano_nascimento;
        }

        public void setTelefone(string telefone)
        {
            this.telefone = telefone;
        }

        public void AlterarEndereco(string novoEndereco)
        {
            endereço = novoEndereco;
        }

        public void AlterarTelefone(string novoTelefone)
        {
            telefone = novoTelefone;
        }

    }

Parte do código que eu tentei salvar o cadastro em um array depois de colocar os dados em cada textbox.
private void bt_salvar_Click(object sender, EventArgs e)
        {
             list.Add(new Pessoa(txt_nome.Text, txt_endereco.Text, /*dataNasc*/ txt_ano.Text, txt_tele.Text));

        }

E essa é a parte do código para salvar que eu vi que realmente estava errada e eu não estava lidando com os atributos da classe.
string[] dados = { txt_nome.Text, txt_endereco.Text, txt_ano.Text, txt_tele.Text, txt_registro.Text };

        this.dataGridView1.Rows.Add(dados);

Estou programando uma Windows Forms Application em C# no Visual Studio.

Na classe chamada "Pessoa", com os atributos "Nome", "Endereço", "AnoNascimento" e "Telefone", estou usando os atributos privados que são disponibilizados pelas propriedades públicas(read only).
Abaixo o código atual:
   public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    List<Pessoa> listcadastro = new List<Pessoa>();

    //apagar tudo que estava sendo escrito na opção de cadastro atual
    void reset()
    {
        txt_nome.Clear();
        txt_endereco.Clear();
        txt_ano.Clear();
        txt_registro.Clear();
        txt_tele.Clear();
        bt_pfisica.Checked = false;
        bt_pjuridica.Checked = false;
    }

    private void bt_cancel_Click(object sender, EventArgs e)
    {
        reset();
    }

    public class Pessoa
    {
        private string nome;
        private string endereço;
        private string ano_nascimento;
        private string telefone;

        /*
        //propriedades públicas, read-only
        public Pessoa(string nome, string endereço, string ano_nascimento, string telefone)
        {
            this.nome = nome;

            this.endereço = endereço;

            this.ano_nascimento = ano_nascimento;

            this.telefone = telefone;

        }*/

        public string Nome
        {
            get
            {
                return nome;
            }

            set
            {
                nome = value;
            }
        }

        public string Endereço
        {
            get
            {
                return endereço;
            }

            set
            {
                endereço = value;
            }
        }

        public string Ano_nascimento
        {
            get
            {
                return ano_nascimento;
            }

            set
            {
                ano_nascimento = value;
            }
        }

        public string Telefone
        {
            get
            {
                return telefone;
            }

            set
            {
                telefone = value;
            }
        }
    }

    private void bt_salvar_Click(object sender, EventArgs e)
    {

         listcadastro.Add(new Pessoa() {Ano_nascimento = txt_ano.Text, Nome = txt_nome.Text, Endereço = txt_endereco.Text, Telefone = txt_tele.Text });

         dataGridView1.DataSource = null;
         dataGridView1.DataSource = listcadastro;
    }

    private void novoMenuItem_Click(object sender, EventArgs e)
    {

        txt_nome.Enabled = true;
        txt_ano.Enabled = true;
        txt_endereco.Enabled = true;
        txt_tele.Enabled = true;

    }

    private void limpa_dados()
    {
        txt_nome.ResetText();// limpa o nome
        txt_tele.ResetText();// limpa o telefone
        txt_endereco.ResetText();// limpa o endereço
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        txt_nome.Enabled = false;
        txt_ano.Enabled = false;
        txt_endereco.Enabled = false;
        txt_tele.Enabled = false;
        txt_registro.Enabled = false;
    }

    private void bt_pfisica_CheckedChanged(object sender, EventArgs e)
    {
        if (bt_pfisica.Checked)
        {
            txt_registro.Enabled = true;
        }
    }

    private void bt_pjuridica_CheckedChanged(object sender, EventArgs e)
    {
        if (bt_pjuridica.Checked)
        {
            txt_registro.Enabled = true;
        }
    }

}

}
Comment: Você consegue ser mais específico? Quer dizer, dar mais detalhes sobre esta questão do grid que você pretende utilizar, por exemplo
Comment: Eu acabei editando a pergunta e adicionei mais códigos, se ainda não ficar bem claro posso dar mais informações sem problemas. Estou tentando ser objetivo mas acho que não estou conseguindo
Comment: Algum motivo em especial para você não utlizar os `get` e `set` do C#? https://msdn.microsoft.com/pt-BR/library/w86s7x04.aspx
Comment: Nenhum, até vi que também era outra forma de fazer o método construtor. É melhor fazer com ele?
Answer: Primeiramente eu alteraria a sua classe pessoa para utilizar os get e set do C#
public class Pessoa
{
    private string nome;
    private string endereço;
    private string ano_nascimento;
    private string telefone;

    public string Nome
    {
        get
        {
            return nome;
        }

        private set
        {
            nome = value;
        }
    }

    public string Endereço
    {
        get
        {
            return endereço;
        }

        private set
        {
            endereço = value;
        }
    }

    public string Ano_nascimento
    {
        get
        {
            return ano_nascimento;
        }

        private set
        {
            ano_nascimento = value;
        }
    }

    public string Telefone
    {
        get
        {
            return telefone;
        }

        private set
        {
            telefone = value;
        }
    }

    public Pessoa(string nome, string endereço, string ano_nascimento, string telefone)
    {
        this.nome = nome;

        this.endereço = endereço;

        this.ano_nascimento = ano_nascimento;

        this.telefone = telefone;

    }
}

Depois disso, no seu botão salvar, basta adicionar os itens na lista de pessoa e referenciar no DataGridView através da propriedade DataSource
private void button1_Click(object sender, EventArgs e)
{
    list.Add(new Pessoa(txt_ano.Text, txt_nome.Text, txt_endereco.Text, txt_tele.Text));

    dataGridView1.DataSource = null;
    dataGridView1.DataSource = list;
}

Na forma declarativa de Field (campo) e Property (propriedade) como foi escrita a classe Pessoa. O método get retorna o campo associado a propriedade, o set atribui o value ao campo da propriedade.

A palavra-chave contextual value é usado em o acessador set nas
  declarações de propriedade comum. Ele é semelhante a um parâmetro de
  entrada em um método. A palavra value faz referência ao valor que o
  código do cliente está tentando atribuir à propriedade.

Fonte: https://msdn.microsoft.com/pt-Br/library/a1khb4f8.aspx
Código fonte completo: https://github.com/pablotdv/StackOverflow/tree/master/WindowsFormsApplication2
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54722/discussion-on-answer-by-pablo-tondolo-de-vargas-salvar-dados-de-uma-textbox-em-u)


slick carousel slickGoTo doesn't work

Question: I'm using the slick carousel class for a slider.
HTML:

 nextPage

your content

your content

your content

JS:
$(document).ready(function() {
  $('.map').slick({
    centerMode: true,
    adaptiveHeight: true
  });

  $('.next-slide').click(function() {
    $('.map').slickGoTo(1);
  });
});

The function slickGoTo doesn't work. What is wrong?
Comment: Problem solved: $('.map').slick('slickGoTo','1');
Comment: have you included jquery plugin files? please post whole html code here.
Comment: Yes, slik.min.js (version 1.4.0) and JQuery (Version 1.11.2). The slider itself works fine. Just the slickGoTo not..
Comment: .. just updated to slik.min.js version 1.4.1, nothing changed..
Comment: @user1272597 I love you
Answer: Please try:
$('.slider').slick('slickGoTo', number);

Comment: Please also include **why** this solution helps answer the question. That way, the original poster and others who read your answer can understand it. Thank you!
Comment: Well just because `$('.map').slickGoTo(1);` is wrong syntax with undefined function, while `$('.map').slick('slickGoTo', 1)` works :)
Answer: Try something like this mate.Its a small work around
$('.next-slide').click(function() {
  var slider = $('.map');
  slider[0].slick.slickGoTo(parseInt(2));
});

Fiddle here
Comment: Works for me. Thank you!

slick carousel slickGoTo doesn't work


Hiding the field label when creating a content type

Question: I have created a content type called "Design" in which there are 3 fields. When creating this content type I want to hide the label of fields. How would I do that?
Answer: Please go to admin/structure/types/manage/[your-content-type]/display

And you can hide labels accordingly.


Changing the size of all grace notes with Lilypond

Question: I am trying to change the size of all grace notes within a staff (or within the score, both would work) while engraving with Lilypond. The documentation on the grace engraver is not the most explanatory x__x
I know how to change the size of one grace note, but I'm engraving a score with like, tens and tens, so, not looking forward to do it by hand. Plus, if I suddenly decide to change the size to something else, it won't be very agreeable.
Comment: I'm not familiar with Lilypond, but is there a macro facility? In other words can you define a macro, X = a,b,c, etc., such that every time it comes across #X it replaces it with "a,b,c"? If so then you need to macroize from the start.
Comment: @BrianTowers Lilypond is LISP-based. The *entire language* is a macro facility.
Answer: You can define global defaults for grace notes with startGraceMusic and stopGraceMusic. The following code:
startGraceMusic = {
  <>(
  \override NoteHead.font-size = #3
}

stopGraceMusic = {
  \revert NoteHead.font-size
  <>)
}

\new Staff {
  \relative c'' {
    \grace { b16 } c4
    \grace { b16 } c4
    \grace { b16 } c4
    \grace { b16 } c4
  }
}

produces extremely large notes (but I've included it here to see the effect); you probably want #-3 or something.
Comment: Actually, I ran into a problem after I accepted that answer. I'm not actually using grace notes (`\grace`), but rather `\slashedGrace` (because they are barred and are not slurred). So I just wrote `startSlashedGraceMusic` and `stopSlashedGraceMusic` instead of `startGraceMusic` and `stopGraceMusic`. But now, my `\slashedGrace` notes are not longer barred, and they are slurred. Any idea how I revert to "normal" behavior (minus note head size) ?
Comment: Perhaps add `\override Flag.stroke-style = #"grace"` (and a corresponding `\revert`)? You can keep using `\grace` then.
Comment: Thanks, it work (for the slash). Do you know off the top of your head, the `override` for the slur (to remove it) ?
Comment: I see [here](http://lilypond.org/doc/v2.18/Documentation/notation/special-rhythmic-concerns#Selected-Snippets-43) a sample using `\slurDashed` and `\slurSolid`, but I have no idea if there's something like `\slurInvisible`.
Comment: `\slurInvisible` doesn't work, but the doc says that the global defaults are defined in `ly/grace-init.ly` so I gave it a try (to no avail). In that file, it seems that `<>\stopGraceSlur` and `<>\startGraceSlur` are used; defined as `startGraceSlur = #(make-music 'SlurEvent 'span-direction START 'spanner-id 'grace)` and `stopGraceSlur = #(make-music 'SlurEvent 'span-direction STOP 'spanner-id 'grace)`; but I couldn't make anything of it. It's okay, though. I'll stick with the default size of slashed grace notes (if nothing else). Thanks for your time !


Delete git branch by anything, not name

Question: I have a problem with deleting git branch. At first I was able to create it using 'git checkout -b ....'. But it seems to me, that I made a mistake while writing, hit something wrong, then backspace. It resulted in wrong name of this branch.
I was able to work on this branch, even push it to remote, but it makes weird behavior (cannot see branches in web interface).
git branch -r shows me
origin/master
origin/rrseria_test_utility

In web interface (bitbucket) I can see this branch in commits with following name
rrseriaÅl_test_utility

Pleasse note that capital A is not just A, but A with circle above. Seems like utf-8 character 'U+00C5'.
When I try to remove it, then
git branch -d rrseria_test_utility
error: branch 'rrseria_test_utility' not found.

git checkout rrseria_test_utility
error: pathspec 'rrseria_test_utility' did not match any file(s) known to git.

Can you help me how to delete this branch ?
Comment: Can't you just type `git branch -d rrseria` and use `TAB` for auto completion? Or Copy/Paste the Å character? Or you can just delete the branches' directory in your `.git/refs/heads/` directory .
Answer: You can use git branch --list rrseria* to list only the branches whose names start with rrseria. If there are more than one you can use a more specific pattern, using the * wildcard for the non-ASCII characters (rrseria*l_test_utility f.e.).
This command displays the name of the branch you want to delete.
If you are on Linux or macOS, you can use its output to create the Git command to delete that branch:
git branch -d $(git branch --list rrseria*)

Or you can use the mouse to copy the branch name in the terminal window from the output of git branch --list and paste it (back into the terminal window) to create the git branch -d command.
Or you can use your favorite file manager to navigate in the .git/ref/heads directory and remove the file whose name matches the branch name (this is what git branch -d does in the background).
After that you have to push the deletion to the remote repositories:
git push origin --prune refs/heads/*

If you have more than one remote then repeat the command above for each of them (put its name instead of origin).
Comment: You can use, as well, the techniques presented above (shell command line substitution, copy-paste, file operations) to rename the branch to the name you want, instead of deleting it. Just don't forget to run the `git push --prune` command after the rename or removal, to send the changes to the remotes too.
Comment: Hm... in my case `git branch --list partialname*` listing works and shows me the branch, but not deleting... also navigating to `.git/refs/head` doesn't show it...? Time to give up and remove the folder and check out the project from scratch? :P

Delete git branch by anything, not name


Why can't my user see the private groups they are members in?

Question: I just installed Drupal Commons 7.x-3.x. I configured two private groups, and added a normal user to them. That user can see content posted to those groups, but it cannot see the group itself, or post content to the group.
Why?
I've added the user as an administrator in the group.
I've cleared all the Drupal Caches on the performance page.
I've cleared my browsers cache.
I've logged the user in and out.
I've rebuilt node permissions.
I've run cron manually.
I've double checked the people/permissions to make sure the user had permission to create groups, just in case that mattered.
No matter what I do, if I try to go to commons/groups/privategroupname with my non-user1 user I get an "Access Denied" page.
If the user wasn't a member, it would not be able to see the content in the list on the /home page.
Public groups work fine.
When creating the private groups, I selected: "Joining requires an invitation. The group and content is hidden from non-members." in the Privacy Settings.
So, I'm at a loss. Help!
Comment: Have you "published" the groups in admin/content/groups/proposed?
Answer: I think this has to do with publishing the content.
If I published a group that was marked as invite only, it would then show up in the list of groups as invite only, and content would only be viewable by members. Seems like an imperfect solution though, as to me, an invite only group should be hidden. But if you do use this solution, be sure to mark the content type to default to published.
There's problems with Drupal and unpublished content sometimes. In this case, the usual solution (Views won't display unpublished nodes when explicitly told to) didn't seem  to fix it.


Hide user fields on profile2 registration form

Question: I am working on multi-user website with 3 roles in Drupal 7 website. I'm using profile2 module for custom fields for different users, also profile2 path for profile/user registration.
Problem came up with Location module because I need 3 different location cck (different fields from location cck are allowed) fields from every user/profile role. I got stuck with this more than 2 months. It would be nice that I can use Profile2 and Location cck but it's not possible because Views module does not extract different Location fields for my Profile2 CCK fields in different profiles (for example I need only phone or city field from location in some view).
The only way to achieve this (so far) is to make 3 location cck fields in user account fields and with field permission module grant privileges for specific roles.
But! I need to expose that location fields on profile2 registration paths with all other fields from specific profile and they need to be required.
Is there a way to hide location cck fields on the registration form based on user type (buyer, seller, etc)?
Answer: to hide and show fields on user registration form while using Profile2 path - try the following in hook_form_alter in template.php.
<code>if ($form_id == 'user_register_form') {

// get current path
$request_path = request_path();

// check if current path corresponds to your registration form for a particular role
if (strpos($request_path,'buyer') !== false) {

// removes the field that should be hidden
$form['field_1']['und'][0]['value']['#access'] = FALSE;

// or
unset($form['field_1']['und'][0]['value']);

// set the state of the field to required
 $form['field_2']['und'][0]['value']['#required'] = TRUE;

}
}
</code>
simple warning - you may find that Location  module fields that utilize ajax (same goes for Address Field module) have a bug that breaks the user reg. form produced by Profile2 Path if it is submitted with errors and exposes fields hidden with method described above. Look for insight in this issue (https://www.drupal.org/node/2558335).


Erro ao rodar testes com proxy models no Django

Question: Eu tenho uma tabela Seller.
https://github.com/rg3915/django-experience/blob/master/djexperience/crm/models.py#L109-L118
class Seller(Employee):
objects = SellerManager()

class Meta:
    proxy = True
    verbose_name = 'vendedor'
    verbose_name_plural = 'vendedores'

def __str__(self):
    return self.username

Ela é um proxy models.
Quando rodei o test_model_seller
https://github.com/rg3915/django-experience/blob/master/djexperience/crm/tests/test_model_seller.py
from datetime import datetime
from django.test import TestCase
from djexperience.crm.models import Seller, Occupation
from .data import EMPLOYEE_DICT

class SellerTest(TestCase):

    def setUp(self):
        self.occupation = Occupation.objects.create(occupation='Gerente')
        self.obj = Seller.objects.create(
            occupation=self.occupation,
            **EMPLOYEE_DICT)

    def test_create(self):
        self.assertTrue(Seller.objects.exists())

    def test_created(self):
        ''' Seller must have an auto created attr. '''
        self.assertIsInstance(self.obj.created, datetime)

This file has been truncated. show original
retornou o seguinte erro:
$ m test
Creating test database for alias 'default'...
...........F......
======================================================================
FAIL: test_create (djexperience.crm.tests.test_model_seller.SellerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/rg3915/gh/my/django-experience/djexperience/crm/tests/test_model_seller.py", line 16, in test_create
    self.assertTrue(Seller.objects.exists())
AssertionError: False is not true

----------------------------------------------------------------------
Ran 18 tests in 0.935s

FAILED (failures=1)
Destroying test database for alias 'default'...

Será que o teste não se aplica a proxy models?
Answer:
"Seu SellerManager retorna somente vendedores e no teste você está
  criando um gerente."

Trocando para vendedor resolve o problema.


Where should I place hook_block_view_alter?

Question: this may be a trivial question, but I have no clue to how to get this working. I have this theme 'nexus'. When try the hook
function nexus_preprocess_block(&$variables)

in the file nexus.theme, it works,
but function nexus_block_view_alter(&$data, $block)
doesn't.
Should I put it in a module? I tried creating a module using hello_world example, and put in the the module's controller but no avail.
Any hint would be much helpful.
Comment: Try with `function nexus_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) `
Comment: Yes that would need to go into a .module file. Did you enable your hello_world module and then flush all caches? and also change the function name to hello_world_block_view_alter if "hello_world" is your module name?
Comment: ah..this worked..somehow I ended up with a controller as given in the helloworld example and it didn't worked out...now I put it as .module file and prefixed the hook with module name, it worked. Thanks.
Answer: In drupal 8 the declaration of hook_block_view_alter changed from hook_block_view_alter(&$data, $block) (Drupal7) to  hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) (Drupal 8).
For more info check hook_block_view_alter Documentation page.
hook_block_view_alter be better in custom module not theme, see guide to building basic Drupal 8 module, and flush all caches.
Answer: While normally the alter hooks are invoked also when they are implemented from the theme used to render the page, there are cases where this doesn't happen. The method that invokes hook_entity_view(), hook_entity_view_alter(), hook_ENTITY_TYPE_view(), and hook_ENTITY_TYPE_view_alter(), EntityViewBuilder::buildMultiple(), invokes only module hooks.
  $this->moduleHandler()->invokeAll($view_hook, [
    &$build_list[$key],
    $entity,
    $display,
    $view_mode,
  ]);
  $this->moduleHandler()->invokeAll('entity_view', [
    &$build_list[$key],
    $entity,
    $display,
    $view_mode,
  ]);

  // ...

  // Allow modules to modify the render array.
  $this->moduleHandler()->alter([$view_hook, 'entity_view', ], $build_list[$key], $entity, $display);

In a theme, you can implement hook_preprocess_block(), but the other hooks require a module.


Iterating over list of strings in xslt, and using index

Question: I work in C#.
I use XSL Transformations (XSLT) Version 1.0.
https://www.w3.org/TR/xslt
I use xslt in order to create xml from the data in the class MyClass
MyClass matches the template and has a property
 List<string> Strings

I need to export it this way:
<Line1> first string value Here </Line1>
<Line2> Second string value here </Line2>
.
.
.

Could someone help me in realising how to do it?
All the best
Tal
Comment: @tal I wish "nubies" would read the help before posting.
Comment: Why do you want or need to use XSLT to iterate over a list of strings and create XML elements? That sounds more like a job for LINQ `list.Select((item, index) => new XElement("Line" + index, item))`.
Comment: Consider to show us what you currently have i.e. show us one class sample with a property or field together with the current XSLT doing the job, then we get an idea of what you are trying to do with that `List` property. The usual input to XSLT is XML and not a C# class so we need to understand where/how you combine C# classes and XSLT to create another XML.
Comment: I don't get it. Can you provide a more explicit XML source sample?
Comment: You say "I have a class to match the template with a property". In which programming language is that? Which XSLT processor do you use? The interaction between XSLT and other programming languages depends very much on the particular processor, its API and the programming platform.
Comment: I'm more familiar with XSLT in Java, but this doesn't seem like the thing XSLT does. You're looking for an XML serializer. XSLT is for transforming XML to different XML. Some quick Googling found me this: [How to serialize an object to XML in C#](https://support.microsoft.com/en-us/kb/815813).
Comment: I have tried to fix the question, I wish people here where more patient with nubies.
Comment: @DavidEhrmann i use it  to create xmls from classes, i just can't figure out this one.
Comment: @tal: This isn't a job for XSLT. You just want to serialize it.
Comment: Becuase that is the way all the template are written for all the xml's I need to produce from all the entities (different template for each entity). Templates should be editable by non programmeres.
Answer: Very simple :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {

        static void Main(string[] args)
        {
            List<string> Strings = new List<string>() {
                    "first string value Here",
                    "Second string value here"
            };

            List<XElement> output = Strings.Select((x, i) => new XElement("Line" + (i + 1).ToString(), x)).ToList();
        }

    }

}

Comment: Thank you for the answer. I need to use xslt template.
Answer: I have found a solution. Maybe there is a better one...
I have created a new ExportClass:
public class ExportString
{
   [XmlElement("StringObject")]
   public string StringObject{get; set;}
}

I have created a list as property is the MyExportClass that matches the XSLT:
public class MyExportClass
{
   [XmlElement("LOS"]
   public List<StringObject> LOS<get; set;}
}

I have used this syntax in the XSLT:
The code includes index in the element's name :
<xsl:for-each select="LOS" xml:space="default">

 //Get the index
  <xsl:variable name ="index" select="position()"/>

  <xsl:element name ="Line{$index}">
  <xsl:value-of select = "StringObject"/>
  </xsl:element>

   //Line break
  <xsl:text>
</xsl:text>
</xsl:for-each>

Result:
<Line1> my first string </Line1>
<Line2> my second string </Line2>
.
.
.


Incrementar variável enquanto segurar um button

Question: Estou precisando fazer uma ação dentro de um Button, quando a pessoa pressionar e segurar com o lado esquerdo do mouse no Button, incrementar uma variável até soltar. Soltou, para à ação.
Dentro do método desse Button, quero incrementar a seguinte variável:
int incrementar = 0;
incrementar++;

int valor = incrementar;

Comment: Eu não sei c#, mas pela lógica deve ter o método que é chamado quando vc clica e quando vc solta um botão, no que é chamado quando vc clica, vc chama outro método que faz um while(verdadeiro), e no de soltar vc muda o valor pra falso
Comment: Eu não sei qual método é esse, testei alguns aqui, mas.. sem sucesso.
Answer: Coloque um Timer no seu form, e defina o intervalo que a variavel será incrementada enquanto estiver com o mouse pressionado.
Feito isso, você utiliza o Evento MouseDown do Button, para habilitar o timer, e o evento MouseUp para desabilitar:
int incremento = 0;

private void button2_MouseDown(object sender, MouseEventArgs e)
{
    timer1.Enabled = true;
}

private void button2_MouseUp(object sender, MouseEventArgs e)
{
    timer1.Enabled = false;
    MessageBox.Show(incremento.ToString());
}

private void timer1_Tick(object sender, EventArgs e)
{
    incremento++;
}

Comment: Era disso que eu tava falando haha, +1
Answer:

<input type="text" id="u" value="0" />

<input type="button" id="b" value="Aperte!" />

Comment: Ah, pensei que era JS :(


Unable to connect server for database access from my local system

Question: <code>if (!($connection = ssh2_connect("serveraddress", port)))
 {

       echo "[FAILED]\n";
}
else

    echo "Connect";
</code>
this not connecting to server.
Comment: I'd like to say that this question.. is actually the best example that i've seen on how not to post a question on SO, please check the FAQ, or even read this: http://stackoverflow.com/questions/how-to-ask
Comment: will you suggest me the connection for accessing database from linux server.
Answer: you can't connect to a database through ssh protocol.
why not using PDO ? http://php.net/manual/fr/book.pdo.php


Is this statement trivial or requires some work?

Question:
My question regards the last two lines of that proof. Is such statement trivial or does it require some work?
My thought is that since the series with the $n-1$ in the power can be shifted so as to have $z^n$ the $n$ will have different initial value in the series and removing any finite number of values of power series does no change the radius of convergence.
Do we have to be rigorous and prove this?
Answer: The response to "it is obvious" is often "why is it obvious?" Always prove it rigorously to yourself first. If you have to think about how to prove it rigorously, it is not obvious. It can be hard to tell whether something will be obvious to somebody who hasn't thought about the particular issue as much as you have. If in doubt include the proof.
This particular one is not obvious to me, though I am a little rusty in this field.
Answer: If
$$
\limsup |a_n|^{1/n} = \limsup |n a_n|^{1/n}
\tag1$$
(possibly $\infty$), then
$$
\frac{1}{\limsup |a_n|^{1/n}} = \frac{1}{\limsup |n a_n|^{1/n}}
$$
with the conventions $1/0 = \infty$ and $1/\infty = 0$.
Hadamard's formula says that
$$
\frac{1}{\limsup |a_n|^{1/n}}
$$
is the radius of convergence of the power series $\sum a_n z^n$, and
$$
\frac{1}{\limsup |n a_n|^{1/n}}
$$
is the radius of convergence of the power series $\sum n a_n z^n$.
So it follows from $(1)$ that $\sum a_n z^n$ and $\sum n a_n z^n$
have the same radius of convergence.
Next, the series $\sum n a_n z^n$ converges if and only if
$\sum n a_n z^{n-1}$ converges.  So the radius of convergence
of $\sum n a_n z^n$ is the same as the radius of convergence of
$\sum n a_n z^{n-1}$.


Wordpress does not properly display CSS file

Question: I have a crazy problem happening and it is blowing my mind. I installed Wordpress on my Localhost and began developing. I modified the standard twenty twelve theme and add custom HTML and CSS to the whole site (4 or 5 pages.) The site shows up great on my local machine (Mac OSX - Safari 6.0.5, Firefox 23.0. Chrome 29.0).
I transferred my site to my live host (under GoDaddy) and I migrated the database by dumping it and then importing it. Now I can pull my site up under both my localhost and by going to the live host URL and the site looks exactly like it should. However, when I crosscheck the CSS via sites like (browsershots.org and browserstack) the site look terrible. Its almost like the main style.css file is not being linked properly. These browser check sites shows the site in ruins on all operating systems and all browsers. Still though when I bring the site up on my personal machine it looks just as it should. My client pulled the site up from their machine and it looked in ruins, just as the css checking sites depicted it.
I have cleared my browser cache thinking I may be reloading a cached version of the site (giving me false hope that it looks good) however it still appears just like it should while viewing the remote version through my local machine.
Side note:All elements of the page appear to be loading fine. The menu bar is there. The text and content is there. It's just not styled.
Does anyone have any idea what may be going on?
Comment: What's the url to the site?
Comment: http://www.fairchildwebsolutions.com/michael/
Answer: The site is trying to serve the files from your localhost.
From the WP Codex:

When your domain name or URLs change - i.e. from
  http://example.com/blog to http://example.com, or http://example.com
  to http://example.net - there are additional concerns. The files and
  database can be moved, however references to the old domain name or
  location will remain in the database, and that can cause issues with
  links or theme display. You need to change the site urls in your
  database before moving to a new host.

You will need to change those hardcoded urls, either by manually searching and replacing them in your database, or using this script.
More on WP Codex
Comment: Ah I see. I read those instructions, but when I viewed my migrated site I saw everything worked as should, so I didnt follow through with the search and replace. I see now that the reason it worked for me was that on my computer the site could still serve the localhost and work fine but on any other machines it could not.
Comment: @fstephen07 An easy mistake to make, and one that really confused me the first time I deployed a local site to my host :) Good luck!
Answer: You need to update all instances of the site URL in your database.  Partially this can be acccomplished by going into the admin panel and changing the site and home urls in Settings->General (or by a number of other methods like adding code to wp-config).
See here for details: Changing The Site URL (WP Codex)
That will probably fix your CSS problem (assuming you used get_stylesheet_directory_uri() or 'wp_enqueue_style` or any of the similar functions in your template call to it).
My preferred way of doing it is using this great serialized string find and replace script for WP.  This will go through your entire database (or whichever tables you select - the important ones are usually wp_options and wp_posts) and update all instances of the old url (e.g. localhost/whatever) and update it to the new web url.
It also has the advantage of not breaking serialized strings, which makes it better than doing a basic UPDATE SQL query through phpMyAdmin or similar.  Serialized strings are used by some things in WordPress like text widgets and many plugins.
Just upload the searchreplacedb2.php script to your web directory root (where wp-config.php lives) and go to it in your browser.
Comment: The Codex link (https://codex.wordpress.org/Changing_The_Site_URL) worked for me, thank you!
Answer: Looks like you haven't updated the settings in WP and everything is still pointing to localhost. Once you do that, everything should work out fine!
Answer: it's still linking to localhost. Here is your stylesheet URL:
http://localhost/Sites/michael/wp-content/themes/twentytwelve/style.css?ver=3.6

You need to search & replace your DB and replace the localhost address. Use this: http://interconnectit.com/products/search-and-replace-for-wordpress-databases/


Lost ssh access to Google Cloud VM

Question: I have a VM (Debian) running on Google Cloud Platform, but I can't connect via ssh or serial console (can't create an user via startup-script for some reason). Already tried a bunch of troubleshooting guides in order to fix it.
I was using the ssh connection previously with no problems at all. The website and databases running on that VM are still working.
I've tried
1 - Checked if firewall entry "default-allow-ssh" exists
2 - Tried connecting with a different user using cmd
gcloud compute ssh another-username@$PROB_INSTANCE

3 - Added metadata "startup-script" key with value:
#! /bin/bash
useradd -G sudo USER
echo 'USER:PASS' | chpasswd

Rebooted (also tried interrupt/start), tried connecting via serial console but it says the login is incorrect. The startup script is not working or not creating my user.
4 - Increased disk size.
5 - Increased memory (upgraded the VM instance type).
6 - Removed ssh keys from both VM details and Metadata tabs, followed by a reboot:
After removing I've tried to generate keys again using command:
gcloud beta compute ssh INSTANCE_NAME -- -vvv

but it returns:
No zone specified. Using zone [us-east1-b] for instance: [INSTANCE_NAME].
Updating project ssh metadata...⠏Updated [https://www.googleapis.com/compute/beta/projects/PROJECT_NAME].
Updating project ssh metadata...done.
Waiting for SSH key to propagate.
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).
USER@IP_ADDRESS: Permission denied (publickey).

More details
Running
gcloud beta compute ssh --zone ZONE INSTANCE_NAME --project PROJECT_NAME

returns:
USER@IP_ADDRESS: Permission denied (publickey).

Running (a second time, after waiting for propagation)
gcloud beta compute ssh INSTANCE_NAME -- -vvv

returns:
[...]
OpenSSH_7.9p1 Debian-10+deb10u2, OpenSSL 1.1.1g  21 Apr 2020
debug1: Reading configuration data /home/USER/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolve_canonicalize: hostname IP_ADDRESS is address
debug2: ssh_connect_direct
debug1: Connecting to IP_ADDRESS [IP_ADDRESS] port 22.
debug1: Connection established.
debug1: identity file /home/USER/.ssh/google_compute_engine type 0
debug1: identity file /home/USER/.ssh/google_compute_engine-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9p1 Debian-10+deb10u2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u7
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u7 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to IP_ADDRESS:22 as 'USER'
debug1: using hostkeyalias: compute.INSTANCE_ID
debug3: hostkeys_foreach: reading file "/home/USER/.ssh/google_compute_known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/USER/.ssh/google_compute_known_hosts:1
debug3: load_hostkeys: loaded 1 keys from compute.INSTANCE_ID
debug3: order_hostkeyalgs: prefer hostkeyalgs: firstname.lastname@example.com,email@example.com,email@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,email@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-grou
p14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,email@example.com
,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,email@example.com
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,firstname.lastname@example.com
debug2: MACs ctos: firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,firstname.lastname@example.com,zlib
debug2: compression stoc: none,email@example.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,firstname.lastname@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-grou
p14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,email@example.com
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,firstname.lastname@example.com
debug2: MACs ctos: firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,firstname.lastname@example.com
debug2: compression stoc: none,email@example.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: email@example.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: email@example.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:Or8[...]
debug1: using hostkeyalias: compute.INSTANCE_ID
debug3: hostkeys_foreach: reading file "/home/USER/.ssh/google_compute_known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/USER/.ssh/google_compute_known_hosts:1
debug3: load_hostkeys: loaded 1 keys from compute.INSTANCE_ID
debug1: Host 'compute.INSTANCE_ID' is known and matches the ECDSA host key.
debug1: Found key in /home/USER/.ssh/google_compute_known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Will attempt key: /home/USER/.ssh/google_compute_engine RSA SHA256:brI3[...] explicit
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/USER/.ssh/google_compute_engine RSA SHA256:brI3[...] explicit
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
USER@IP_ADDRESS: Permission denied (publickey).
ERROR: (gcloud.beta.compute.ssh) [/usr/bin/ssh] exited with return code [255].

Update
Followed Alex's suggestions and the serial port output returns:
Welcome to [1mDebian GNU/Linux 9 (stretch)[0m!

[    2.364319] systemd[1]: No hostname configured.
[    2.365157] systemd[1]: Set hostname to <localhost>.
[    3.142016] systemd[1]: google-shutdown-scripts.service: Cannot add dependency job, ignoring: Unit google-shutdown-scripts.service is masked.
[    3.144581] systemd[1]: google-clock-skew-daemon.service: Cannot add dependency job, ignoring: Unit google-clock-skew-daemon.service is masked.
[    3.147589] systemd[1]: google-instance-setup.service: Cannot add dependency job, ignoring: Unit google-instance-setup.service is masked.
[    3.149799] systemd[1]: google-accounts-daemon.service: Cannot add dependency job, ignoring: Unit google-accounts-daemon.service is masked.
[    3.152485] systemd[1]: google-startup-scripts.service: Cannot add dependency job, ignoring: Unit google-startup-scripts.service is masked.

I really hope there is a fix :/
I'd appreciate any help or tips,
Thanks!
Answer: This "Permission denied" error can occur for several reasons.

Did you enable "OS Login"? If OS Login is enabled on your project, your VM doesn't accept SSH keys that are stored in metadata. You have to disable "OS Login"

Or you used an SSH key stored in an OS Login profile to connect to a VM that doesn't have OS Login enabled. So enable "OS Login" and then add your SSH keys to metadata.

If you manually added SSH keys to your VM and then connected to your VM using the Google Cloud Console, Compute Engine created a new key pair for your connection. After the new key pair expired, Compute Engine deleted your ~/.ssh/authorized_keys file in the VM, which included your manually added SSH key. You have to re-add your SSH key to metadata.

If your sshd daemon isn't running or isn't configured properly you can't connect to your VM using SSH. You can connect to your VM via serial port, and then ensure that your sshd_config is set up correctly.
Answer: It is best to check the logs on Serial Console first by using the command

gcloud compute instances get-serial-port-output

Or you can check this link for other ways to do it. From here you should be able to get some answers on why it is failing. You will also be able to see why your startup script for serial connection fails.
You can try this block of code on the startup-script instead:
#! /bin/bash
useradd USERNAME
echo 'USERNAME:PASSWORD!' | chpasswd
usermod -aG wheel USERNAME

For a more detailed troubleshooting steps on SSH on GCE, you can check the GCP official documentation here.
Comment: Hey Alex, thanks for your response, but I think that the startup-script is not running at all for some reason... tried your version as well. Regarding the serial port output, that is what I've found:
"systemd[1]: google-instance-setup.service: Cannot add dependency job, ignoring: Unit google-instance-setup.service is masked.
systemd[1]: google-accounts-daemon.service: Cannot add dependency job, ignoring: Unit google-accounts-daemon.service is masked.
systemd[1]: google-startup-scripts.service: Cannot add dependency job, ignoring: Unit google-startup-scripts.service is masked."
Comment: Another approach would be mounting the disk to another VM instance and repairing the SSH configuration from there. This [article](https://serverfault.com/questions/706888/cant-ssh-after-configuring-sshd-config) might help,
Answer: SSH:
Use the link above provided by "Alex G" as a reference for troubleshooting ssh. Or find the same link here
Use the command below to check ssh service status
sudo systemctl status sshd

Startup script:
Use the link as a reference to use startup scripts
Use the command below to check installed google systemd services
sudo systemctl list-unit-files | grep google

If services are masked, unmask the services and then enable them.
sudo systemctl unmask "service-name"
sudo systemctl enable "service-name"

Startup script runs when booting up, not in the background after booting up and is not related to SSH. Hence, if the startup script is masked/disabled in the list above, you could try enabling it to automatically start on boot up.
Furthermore, if you have a startup script that needs to run immediately you can use the command below.
sudo systemctl start google-startup-scripts.service.

Use the command below to view output from the startup script.
sudo journalctl -u google-startup-scripts.service

List the google running processes to check for processes needed to SSH. Verify if  google-network-daemon.service and google-accounts-daemon.service are running.
sudo ps aux | grep google

If you are still facing issues, reinstall/update the guest environment. Use the link  as a reference

Lost ssh access to Google Cloud VM